1 //! This module implements some validity checks for attributes.
2 //! In particular it verifies that `#[inline]` and `#[repr]` attributes are
3 //! attached to items that actually support them and if there are
4 //! conflicts between multiple such attributes attached to the same
7 use crate::hir::map::Map;
8 use crate::ty::query::Providers;
11 use rustc_errors::struct_span_err;
13 use rustc_hir::def_id::DefId;
14 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
15 use rustc_hir::DUMMY_HIR_ID;
16 use rustc_hir::{self, HirId, Item, ItemKind, TraitItem, TraitItemKind};
17 use rustc_session::lint::builtin::UNUSED_ATTRIBUTES;
18 use rustc_span::symbol::sym;
20 use syntax::ast::Attribute;
23 use std::fmt::{self, Display};
25 #[derive(Copy, Clone, PartialEq)]
26 pub(crate) enum MethodKind {
31 #[derive(Copy, Clone, PartialEq)]
32 pub(crate) enum Target {
60 impl Display for Target {
61 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66 Target::ExternCrate => "extern crate",
68 Target::Static => "static item",
69 Target::Const => "constant item",
70 Target::Fn => "function",
71 Target::Closure => "closure",
72 Target::Mod => "module",
73 Target::ForeignMod => "foreign module",
74 Target::GlobalAsm => "global asm",
75 Target::TyAlias => "type alias",
76 Target::OpaqueTy => "opaque type",
77 Target::Enum => "enum",
78 Target::Struct => "struct",
79 Target::Union => "union",
80 Target::Trait => "trait",
81 Target::TraitAlias => "trait alias",
82 Target::Impl => "item",
83 Target::Expression => "expression",
84 Target::Statement => "statement",
85 Target::AssocConst => "associated const",
86 Target::Method(_) => "method",
87 Target::AssocTy => "associated type",
88 Target::ForeignFn => "foreign function",
89 Target::ForeignStatic => "foreign static item",
90 Target::ForeignTy => "foreign type",
97 pub(crate) fn from_item(item: &Item<'_>) -> Target {
99 ItemKind::ExternCrate(..) => Target::ExternCrate,
100 ItemKind::Use(..) => Target::Use,
101 ItemKind::Static(..) => Target::Static,
102 ItemKind::Const(..) => Target::Const,
103 ItemKind::Fn(..) => Target::Fn,
104 ItemKind::Mod(..) => Target::Mod,
105 ItemKind::ForeignMod(..) => Target::ForeignMod,
106 ItemKind::GlobalAsm(..) => Target::GlobalAsm,
107 ItemKind::TyAlias(..) => Target::TyAlias,
108 ItemKind::OpaqueTy(..) => Target::OpaqueTy,
109 ItemKind::Enum(..) => Target::Enum,
110 ItemKind::Struct(..) => Target::Struct,
111 ItemKind::Union(..) => Target::Union,
112 ItemKind::Trait(..) => Target::Trait,
113 ItemKind::TraitAlias(..) => Target::TraitAlias,
114 ItemKind::Impl { .. } => Target::Impl,
118 fn from_trait_item(trait_item: &TraitItem<'_>) -> Target {
119 match trait_item.kind {
120 TraitItemKind::Const(..) => Target::AssocConst,
121 TraitItemKind::Method(_, hir::TraitMethod::Required(_)) => {
122 Target::Method(MethodKind::Trait { body: false })
124 TraitItemKind::Method(_, hir::TraitMethod::Provided(_)) => {
125 Target::Method(MethodKind::Trait { body: true })
127 TraitItemKind::Type(..) => Target::AssocTy,
131 fn from_foreign_item(foreign_item: &hir::ForeignItem<'_>) -> Target {
132 match foreign_item.kind {
133 hir::ForeignItemKind::Fn(..) => Target::ForeignFn,
134 hir::ForeignItemKind::Static(..) => Target::ForeignStatic,
135 hir::ForeignItemKind::Type => Target::ForeignTy,
139 fn from_impl_item<'tcx>(tcx: TyCtxt<'tcx>, impl_item: &hir::ImplItem<'_>) -> Target {
140 match impl_item.kind {
141 hir::ImplItemKind::Const(..) => Target::AssocConst,
142 hir::ImplItemKind::Method(..) => {
143 let parent_hir_id = tcx.hir().get_parent_item(impl_item.hir_id);
144 let containing_item = tcx.hir().expect_item(parent_hir_id);
145 let containing_impl_is_for_trait = match &containing_item.kind {
146 hir::ItemKind::Impl { ref of_trait, .. } => of_trait.is_some(),
147 _ => bug!("parent of an ImplItem must be an Impl"),
149 if containing_impl_is_for_trait {
150 Target::Method(MethodKind::Trait { body: true })
152 Target::Method(MethodKind::Inherent)
155 hir::ImplItemKind::TyAlias(..) | hir::ImplItemKind::OpaqueTy(..) => Target::AssocTy,
160 struct CheckAttrVisitor<'tcx> {
164 impl CheckAttrVisitor<'tcx> {
165 /// Checks any attribute.
169 attrs: &'hir [Attribute],
172 item: Option<&Item<'_>>,
174 let mut is_valid = true;
176 is_valid &= if attr.check_name(sym::inline) {
177 self.check_inline(hir_id, attr, span, target)
178 } else if attr.check_name(sym::non_exhaustive) {
179 self.check_non_exhaustive(attr, span, target)
180 } else if attr.check_name(sym::marker) {
181 self.check_marker(attr, span, target)
182 } else if attr.check_name(sym::target_feature) {
183 self.check_target_feature(attr, span, target)
184 } else if attr.check_name(sym::track_caller) {
185 self.check_track_caller(&attr.span, attrs, span, target)
195 if target == Target::Fn {
196 self.tcx.codegen_fn_attrs(self.tcx.hir().local_def_id(hir_id));
199 self.check_repr(attrs, span, target, item);
200 self.check_used(attrs, target);
203 /// Checks if an `#[inline]` is applied to a function or a closure. Returns `true` if valid.
204 fn check_inline(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) -> bool {
208 | Target::Method(MethodKind::Trait { body: true })
209 | Target::Method(MethodKind::Inherent) => true,
210 Target::Method(MethodKind::Trait { body: false }) | Target::ForeignFn => {
212 .struct_span_lint_hir(
216 "`#[inline]` is ignored on function prototypes",
221 // FIXME(#65833): We permit associated consts to have an `#[inline]` attribute with
222 // just a lint, because we previously erroneously allowed it and some crates used it
223 // accidentally, to to be compatible with crates depending on them, we can't throw an
225 Target::AssocConst => {
227 .struct_span_lint_hir(
231 "`#[inline]` is ignored on constants",
234 "this was previously accepted by the compiler but is \
235 being phased out; it will become a hard error in \
239 "for more information, see issue #65833 \
240 <https://github.com/rust-lang/rust/issues/65833>",
250 "attribute should be applied to function or closure",
252 .span_label(*span, "not a function or closure")
259 /// Checks if a `#[track_caller]` is applied to a non-naked function. Returns `true` if valid.
260 fn check_track_caller(
263 attrs: &'hir [Attribute],
268 Target::Fn if attr::contains_name(attrs, sym::naked) => {
273 "cannot use `#[track_caller]` with `#[naked]`",
278 Target::Fn | Target::Method(MethodKind::Inherent) => true,
279 Target::Method(_) => {
284 "`#[track_caller]` may not be used on trait methods",
294 "attribute should be applied to function"
296 .span_label(*span, "not a function")
303 /// Checks if the `#[non_exhaustive]` attribute on an `item` is valid. Returns `true` if valid.
304 fn check_non_exhaustive(&self, attr: &Attribute, span: &Span, target: Target) -> bool {
306 Target::Struct | Target::Enum => true,
312 "attribute can only be applied to a struct or enum"
314 .span_label(*span, "not a struct or enum")
321 /// Checks if the `#[marker]` attribute on an `item` is valid. Returns `true` if valid.
322 fn check_marker(&self, attr: &Attribute, span: &Span, target: Target) -> bool {
324 Target::Trait => true,
328 .struct_span_err(attr.span, "attribute can only be applied to a trait")
329 .span_label(*span, "not a trait")
336 /// Checks if the `#[target_feature]` attribute on `item` is valid. Returns `true` if valid.
337 fn check_target_feature(&self, attr: &Attribute, span: &Span, target: Target) -> bool {
340 | Target::Method(MethodKind::Trait { body: true })
341 | Target::Method(MethodKind::Inherent) => true,
345 .struct_span_err(attr.span, "attribute should be applied to a function")
346 .span_label(*span, "not a function")
353 /// Checks if the `#[repr]` attributes on `item` are valid.
356 attrs: &'hir [Attribute],
359 item: Option<&Item<'_>>,
361 // Extract the names of all repr hints, e.g., [foo, bar, align] for:
364 // #[repr(bar, align(8))]
366 let hints: Vec<_> = attrs
368 .filter(|attr| attr.check_name(sym::repr))
369 .filter_map(|attr| attr.meta_item_list())
373 let mut int_reprs = 0;
374 let mut is_c = false;
375 let mut is_simd = false;
376 let mut is_transparent = false;
379 let (article, allowed_targets) = match hint.name_or_empty() {
380 name @ sym::C | name @ sym::align => {
381 is_c |= name == sym::C;
383 Target::Struct | Target::Union | Target::Enum => continue,
384 _ => ("a", "struct, enum, or union"),
388 if target != Target::Struct && target != Target::Union {
389 ("a", "struct or union")
396 if target != Target::Struct { ("a", "struct") } else { continue }
398 sym::transparent => {
399 is_transparent = true;
401 Target::Struct | Target::Union | Target::Enum => continue,
402 _ => ("a", "struct, enum, or union"),
416 if target != Target::Enum { ("an", "enum") } else { continue }
420 self.emit_repr_error(
423 &format!("attribute should be applied to {}", allowed_targets),
424 &format!("not {} {}", article, allowed_targets),
428 // Just point at all repr hints if there are any incompatibilities.
429 // This is not ideal, but tracking precisely which ones are at fault is a huge hassle.
430 let hint_spans = hints.iter().map(|hint| hint.span());
432 // Error on repr(transparent, <anything else>).
433 if is_transparent && hints.len() > 1 {
434 let hint_spans: Vec<_> = hint_spans.clone().collect();
439 "transparent {} cannot have other repr hints",
444 // Warn on repr(u8, u16), repr(C, simd), and c-like-enum-repr(C, u8)
447 || (int_reprs == 1 && is_c && item.map_or(false, |item| is_c_like_enum(item)))
451 hint_spans.collect::<Vec<Span>>(),
453 "conflicting representation hints",
466 struct_span_err!(self.tcx.sess, hint_span, E0517, "{}", hint_message)
467 .span_label(label_span, label_message)
471 fn check_stmt_attributes(&self, stmt: &hir::Stmt<'_>) {
472 // When checking statements ignore expressions, they will be checked later
473 if let hir::StmtKind::Local(ref l) = stmt.kind {
474 for attr in l.attrs.iter() {
475 if attr.check_name(sym::inline) {
476 self.check_inline(DUMMY_HIR_ID, attr, &stmt.span, Target::Statement);
478 if attr.check_name(sym::repr) {
479 self.emit_repr_error(
482 "attribute should not be applied to a statement",
483 "not a struct, enum, or union",
490 fn check_expr_attributes(&self, expr: &hir::Expr<'_>) {
491 let target = match expr.kind {
492 hir::ExprKind::Closure(..) => Target::Closure,
493 _ => Target::Expression,
495 for attr in expr.attrs.iter() {
496 if attr.check_name(sym::inline) {
497 self.check_inline(DUMMY_HIR_ID, attr, &expr.span, target);
499 if attr.check_name(sym::repr) {
500 self.emit_repr_error(
503 "attribute should not be applied to an expression",
504 "not defining a struct, enum, or union",
510 fn check_used(&self, attrs: &'hir [Attribute], target: Target) {
512 if attr.check_name(sym::used) && target != Target::Static {
515 .span_err(attr.span, "attribute must be applied to a `static` variable");
521 impl Visitor<'tcx> for CheckAttrVisitor<'tcx> {
522 type Map = Map<'tcx>;
524 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, Self::Map> {
525 NestedVisitorMap::OnlyBodies(&self.tcx.hir())
528 fn visit_item(&mut self, item: &'tcx Item<'tcx>) {
529 let target = Target::from_item(item);
530 self.check_attributes(item.hir_id, item.attrs, &item.span, target, Some(item));
531 intravisit::walk_item(self, item)
534 fn visit_trait_item(&mut self, trait_item: &'tcx TraitItem<'tcx>) {
535 let target = Target::from_trait_item(trait_item);
536 self.check_attributes(trait_item.hir_id, &trait_item.attrs, &trait_item.span, target, None);
537 intravisit::walk_trait_item(self, trait_item)
540 fn visit_foreign_item(&mut self, f_item: &'tcx hir::ForeignItem<'tcx>) {
541 let target = Target::from_foreign_item(f_item);
542 self.check_attributes(f_item.hir_id, &f_item.attrs, &f_item.span, target, None);
543 intravisit::walk_foreign_item(self, f_item)
546 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
547 let target = Target::from_impl_item(self.tcx, impl_item);
548 self.check_attributes(impl_item.hir_id, &impl_item.attrs, &impl_item.span, target, None);
549 intravisit::walk_impl_item(self, impl_item)
552 fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt<'tcx>) {
553 self.check_stmt_attributes(stmt);
554 intravisit::walk_stmt(self, stmt)
557 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
558 self.check_expr_attributes(expr);
559 intravisit::walk_expr(self, expr)
563 fn is_c_like_enum(item: &Item<'_>) -> bool {
564 if let ItemKind::Enum(ref def, _) = item.kind {
565 for variant in def.variants {
567 hir::VariantData::Unit(..) => { /* continue */ }
577 fn check_mod_attrs(tcx: TyCtxt<'_>, module_def_id: DefId) {
579 .visit_item_likes_in_module(module_def_id, &mut CheckAttrVisitor { tcx }.as_deep_visitor());
582 pub(crate) fn provide(providers: &mut Providers<'_>) {
583 *providers = Providers { check_mod_attrs, ..*providers };