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::def_id::DefId;
8 use crate::hir::intravisit::{self, NestedVisitorMap, Visitor};
9 use crate::hir::DUMMY_HIR_ID;
10 use crate::hir::{self, Attribute, HirId, Item, ItemKind, TraitItem, TraitItemKind};
11 use crate::lint::builtin::UNUSED_ATTRIBUTES;
12 use crate::ty::query::Providers;
13 use crate::ty::TyCtxt;
15 use std::fmt::{self, Display};
16 use syntax::{attr, symbol::sym};
19 use rustc_error_codes::*;
21 #[derive(Copy, Clone, PartialEq)]
22 pub(crate) enum MethodKind {
27 #[derive(Copy, Clone, PartialEq)]
28 pub(crate) enum Target {
56 impl Display for Target {
57 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62 Target::ExternCrate => "extern crate",
64 Target::Static => "static item",
65 Target::Const => "constant item",
66 Target::Fn => "function",
67 Target::Closure => "closure",
68 Target::Mod => "module",
69 Target::ForeignMod => "foreign module",
70 Target::GlobalAsm => "global asm",
71 Target::TyAlias => "type alias",
72 Target::OpaqueTy => "opaque type",
73 Target::Enum => "enum",
74 Target::Struct => "struct",
75 Target::Union => "union",
76 Target::Trait => "trait",
77 Target::TraitAlias => "trait alias",
78 Target::Impl => "item",
79 Target::Expression => "expression",
80 Target::Statement => "statement",
81 Target::AssocConst => "associated const",
82 Target::Method(_) => "method",
83 Target::AssocTy => "associated type",
84 Target::ForeignFn => "foreign function",
85 Target::ForeignStatic => "foreign static item",
86 Target::ForeignTy => "foreign type",
93 pub(crate) fn from_item(item: &Item<'_>) -> Target {
95 ItemKind::ExternCrate(..) => Target::ExternCrate,
96 ItemKind::Use(..) => Target::Use,
97 ItemKind::Static(..) => Target::Static,
98 ItemKind::Const(..) => Target::Const,
99 ItemKind::Fn(..) => Target::Fn,
100 ItemKind::Mod(..) => Target::Mod,
101 ItemKind::ForeignMod(..) => Target::ForeignMod,
102 ItemKind::GlobalAsm(..) => Target::GlobalAsm,
103 ItemKind::TyAlias(..) => Target::TyAlias,
104 ItemKind::OpaqueTy(..) => Target::OpaqueTy,
105 ItemKind::Enum(..) => Target::Enum,
106 ItemKind::Struct(..) => Target::Struct,
107 ItemKind::Union(..) => Target::Union,
108 ItemKind::Trait(..) => Target::Trait,
109 ItemKind::TraitAlias(..) => Target::TraitAlias,
110 ItemKind::Impl(..) => Target::Impl,
114 fn from_trait_item(trait_item: &TraitItem<'_>) -> Target {
115 match trait_item.kind {
116 TraitItemKind::Const(..) => Target::AssocConst,
117 TraitItemKind::Method(_, hir::TraitMethod::Required(_)) => {
118 Target::Method(MethodKind::Trait { body: false })
120 TraitItemKind::Method(_, hir::TraitMethod::Provided(_)) => {
121 Target::Method(MethodKind::Trait { body: true })
123 TraitItemKind::Type(..) => Target::AssocTy,
127 fn from_foreign_item(foreign_item: &hir::ForeignItem<'_>) -> Target {
128 match foreign_item.kind {
129 hir::ForeignItemKind::Fn(..) => Target::ForeignFn,
130 hir::ForeignItemKind::Static(..) => Target::ForeignStatic,
131 hir::ForeignItemKind::Type => Target::ForeignTy,
135 fn from_impl_item<'tcx>(tcx: TyCtxt<'tcx>, impl_item: &hir::ImplItem<'_>) -> Target {
136 match impl_item.kind {
137 hir::ImplItemKind::Const(..) => Target::AssocConst,
138 hir::ImplItemKind::Method(..) => {
139 let parent_hir_id = tcx.hir().get_parent_item(impl_item.hir_id);
140 let containing_item = tcx.hir().expect_item(parent_hir_id);
141 let containing_impl_is_for_trait = match &containing_item.kind {
142 hir::ItemKind::Impl(_, _, _, _, tr, _, _) => tr.is_some(),
143 _ => bug!("parent of an ImplItem must be an Impl"),
145 if containing_impl_is_for_trait {
146 Target::Method(MethodKind::Trait { body: true })
148 Target::Method(MethodKind::Inherent)
151 hir::ImplItemKind::TyAlias(..) | hir::ImplItemKind::OpaqueTy(..) => Target::AssocTy,
156 struct CheckAttrVisitor<'tcx> {
160 impl CheckAttrVisitor<'tcx> {
161 /// Checks any attribute.
165 attrs: &'hir [Attribute],
168 item: Option<&Item<'_>>,
170 let mut is_valid = true;
172 is_valid &= if attr.check_name(sym::inline) {
173 self.check_inline(hir_id, attr, span, target)
174 } else if attr.check_name(sym::non_exhaustive) {
175 self.check_non_exhaustive(attr, span, target)
176 } else if attr.check_name(sym::marker) {
177 self.check_marker(attr, span, target)
178 } else if attr.check_name(sym::target_feature) {
179 self.check_target_feature(attr, span, target)
180 } else if attr.check_name(sym::track_caller) {
181 self.check_track_caller(&attr.span, attrs, span, target)
191 if target == Target::Fn {
192 self.tcx.codegen_fn_attrs(self.tcx.hir().local_def_id(hir_id));
195 self.check_repr(attrs, span, target, item);
196 self.check_used(attrs, target);
199 /// Checks if an `#[inline]` is applied to a function or a closure. Returns `true` if valid.
200 fn check_inline(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) -> bool {
204 | Target::Method(MethodKind::Trait { body: true })
205 | Target::Method(MethodKind::Inherent) => true,
206 Target::Method(MethodKind::Trait { body: false }) | Target::ForeignFn => {
208 .struct_span_lint_hir(
212 "`#[inline]` is ignored on function prototypes",
217 // FIXME(#65833): We permit associated consts to have an `#[inline]` attribute with
218 // just a lint, because we previously erroneously allowed it and some crates used it
219 // accidentally, to to be compatible with crates depending on them, we can't throw an
221 Target::AssocConst => {
223 .struct_span_lint_hir(
227 "`#[inline]` is ignored on constants",
230 "this was previously accepted by the compiler but is \
231 being phased out; it will become a hard error in \
235 "for more information, see issue #65833 \
236 <https://github.com/rust-lang/rust/issues/65833>",
246 "attribute should be applied to function or closure",
248 .span_label(*span, "not a function or closure")
255 /// Checks if a `#[track_caller]` is applied to a non-naked function. Returns `true` if valid.
256 fn check_track_caller(
259 attrs: &'hir [Attribute],
264 Target::Fn if attr::contains_name(attrs, sym::naked) => {
269 "cannot use `#[track_caller]` with `#[naked]`",
274 Target::Fn | Target::Method(MethodKind::Inherent) => true,
275 Target::Method(_) => {
280 "`#[track_caller]` may not be used on trait methods",
290 "attribute should be applied to function"
292 .span_label(*span, "not a function")
299 /// Checks if the `#[non_exhaustive]` attribute on an `item` is valid. Returns `true` if valid.
300 fn check_non_exhaustive(&self, attr: &Attribute, span: &Span, target: Target) -> bool {
302 Target::Struct | Target::Enum => true,
308 "attribute can only be applied to a struct or enum"
310 .span_label(*span, "not a struct or enum")
317 /// Checks if the `#[marker]` attribute on an `item` is valid. Returns `true` if valid.
318 fn check_marker(&self, attr: &Attribute, span: &Span, target: Target) -> bool {
320 Target::Trait => true,
324 .struct_span_err(attr.span, "attribute can only be applied to a trait")
325 .span_label(*span, "not a trait")
332 /// Checks if the `#[target_feature]` attribute on `item` is valid. Returns `true` if valid.
333 fn check_target_feature(&self, attr: &Attribute, span: &Span, target: Target) -> bool {
336 | Target::Method(MethodKind::Trait { body: true })
337 | Target::Method(MethodKind::Inherent) => true,
341 .struct_span_err(attr.span, "attribute should be applied to a function")
342 .span_label(*span, "not a function")
349 /// Checks if the `#[repr]` attributes on `item` are valid.
352 attrs: &'hir [Attribute],
355 item: Option<&Item<'_>>,
357 // Extract the names of all repr hints, e.g., [foo, bar, align] for:
360 // #[repr(bar, align(8))]
362 let hints: Vec<_> = attrs
364 .filter(|attr| attr.check_name(sym::repr))
365 .filter_map(|attr| attr.meta_item_list())
369 let mut int_reprs = 0;
370 let mut is_c = false;
371 let mut is_simd = false;
372 let mut is_transparent = false;
375 let (article, allowed_targets) = match hint.name_or_empty() {
376 name @ sym::C | name @ sym::align => {
377 is_c |= name == sym::C;
379 Target::Struct | Target::Union | Target::Enum => continue,
380 _ => ("a", "struct, enum, or union"),
384 if target != Target::Struct && target != Target::Union {
385 ("a", "struct or union")
392 if target != Target::Struct { ("a", "struct") } else { continue }
394 sym::transparent => {
395 is_transparent = true;
397 Target::Struct | Target::Union | Target::Enum => continue,
398 _ => ("a", "struct, enum, or union"),
412 if target != Target::Enum { ("an", "enum") } else { continue }
416 self.emit_repr_error(
419 &format!("attribute should be applied to {}", allowed_targets),
420 &format!("not {} {}", article, allowed_targets),
424 // Just point at all repr hints if there are any incompatibilities.
425 // This is not ideal, but tracking precisely which ones are at fault is a huge hassle.
426 let hint_spans = hints.iter().map(|hint| hint.span());
428 // Error on repr(transparent, <anything else>).
429 if is_transparent && hints.len() > 1 {
430 let hint_spans: Vec<_> = hint_spans.clone().collect();
435 "transparent {} cannot have other repr hints",
439 // Warn on repr(u8, u16), repr(C, simd), and c-like-enum-repr(C, u8)
442 || (int_reprs == 1 && is_c && item.map_or(false, |item| is_c_like_enum(item)))
444 let hint_spans: Vec<_> = hint_spans.collect();
445 span_warn!(self.tcx.sess, hint_spans, E0566, "conflicting representation hints");
456 struct_span_err!(self.tcx.sess, hint_span, E0517, "{}", hint_message)
457 .span_label(label_span, label_message)
461 fn check_stmt_attributes(&self, stmt: &hir::Stmt) {
462 // When checking statements ignore expressions, they will be checked later
463 if let hir::StmtKind::Local(ref l) = stmt.kind {
464 for attr in l.attrs.iter() {
465 if attr.check_name(sym::inline) {
466 self.check_inline(DUMMY_HIR_ID, attr, &stmt.span, Target::Statement);
468 if attr.check_name(sym::repr) {
469 self.emit_repr_error(
472 "attribute should not be applied to a statement",
473 "not a struct, enum, or union",
480 fn check_expr_attributes(&self, expr: &hir::Expr) {
481 let target = match expr.kind {
482 hir::ExprKind::Closure(..) => Target::Closure,
483 _ => Target::Expression,
485 for attr in expr.attrs.iter() {
486 if attr.check_name(sym::inline) {
487 self.check_inline(DUMMY_HIR_ID, attr, &expr.span, target);
489 if attr.check_name(sym::repr) {
490 self.emit_repr_error(
493 "attribute should not be applied to an expression",
494 "not defining a struct, enum, or union",
500 fn check_used(&self, attrs: &'hir [Attribute], target: Target) {
502 if attr.check_name(sym::used) && target != Target::Static {
505 .span_err(attr.span, "attribute must be applied to a `static` variable");
511 impl Visitor<'tcx> for CheckAttrVisitor<'tcx> {
512 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
513 NestedVisitorMap::OnlyBodies(&self.tcx.hir())
516 fn visit_item(&mut self, item: &'tcx Item<'tcx>) {
517 let target = Target::from_item(item);
518 self.check_attributes(item.hir_id, item.attrs, &item.span, target, Some(item));
519 intravisit::walk_item(self, item)
522 fn visit_trait_item(&mut self, trait_item: &'tcx TraitItem<'tcx>) {
523 let target = Target::from_trait_item(trait_item);
524 self.check_attributes(trait_item.hir_id, &trait_item.attrs, &trait_item.span, target, None);
525 intravisit::walk_trait_item(self, trait_item)
528 fn visit_foreign_item(&mut self, f_item: &'tcx hir::ForeignItem<'tcx>) {
529 let target = Target::from_foreign_item(f_item);
530 self.check_attributes(f_item.hir_id, &f_item.attrs, &f_item.span, target, None);
531 intravisit::walk_foreign_item(self, f_item)
534 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
535 let target = Target::from_impl_item(self.tcx, impl_item);
536 self.check_attributes(impl_item.hir_id, &impl_item.attrs, &impl_item.span, target, None);
537 intravisit::walk_impl_item(self, impl_item)
540 fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt) {
541 self.check_stmt_attributes(stmt);
542 intravisit::walk_stmt(self, stmt)
545 fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
546 self.check_expr_attributes(expr);
547 intravisit::walk_expr(self, expr)
551 fn is_c_like_enum(item: &Item<'_>) -> bool {
552 if let ItemKind::Enum(ref def, _) = item.kind {
553 for variant in def.variants {
555 hir::VariantData::Unit(..) => { /* continue */ }
565 fn check_mod_attrs(tcx: TyCtxt<'_>, module_def_id: DefId) {
567 .visit_item_likes_in_module(module_def_id, &mut CheckAttrVisitor { tcx }.as_deep_visitor());
570 pub(crate) fn provide(providers: &mut Providers<'_>) {
571 *providers = Providers { check_mod_attrs, ..*providers };