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::{self, HirId, HirVec, Attribute, Item, ItemKind, TraitItem, TraitItemKind};
8 use crate::hir::DUMMY_HIR_ID;
9 use crate::hir::def_id::DefId;
10 use crate::hir::intravisit::{self, Visitor, NestedVisitorMap};
11 use crate::lint::builtin::UNUSED_ATTRIBUTES;
12 use crate::ty::TyCtxt;
13 use crate::ty::query::Providers;
15 use std::fmt::{self, Display};
16 use syntax::{attr, symbol::sym};
19 #[derive(Copy, Clone, PartialEq)]
20 pub(crate) enum MethodKind {
25 #[derive(Copy, Clone, PartialEq)]
26 pub(crate) enum Target {
54 impl Display for Target {
55 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56 write!(f, "{}", match *self {
57 Target::ExternCrate => "extern crate",
59 Target::Static => "static item",
60 Target::Const => "constant item",
61 Target::Fn => "function",
62 Target::Closure => "closure",
63 Target::Mod => "module",
64 Target::ForeignMod => "foreign module",
65 Target::GlobalAsm => "global asm",
66 Target::TyAlias => "type alias",
67 Target::OpaqueTy => "opaque type",
68 Target::Enum => "enum",
69 Target::Struct => "struct",
70 Target::Union => "union",
71 Target::Trait => "trait",
72 Target::TraitAlias => "trait alias",
73 Target::Impl => "item",
74 Target::Expression => "expression",
75 Target::Statement => "statement",
76 Target::AssocConst => "associated const",
77 Target::Method(_) => "method",
78 Target::AssocTy => "associated type",
79 Target::ForeignFn => "foreign function",
80 Target::ForeignStatic => "foreign static item",
81 Target::ForeignTy => "foreign type",
87 pub(crate) fn from_item(item: &Item) -> Target {
89 ItemKind::ExternCrate(..) => Target::ExternCrate,
90 ItemKind::Use(..) => Target::Use,
91 ItemKind::Static(..) => Target::Static,
92 ItemKind::Const(..) => Target::Const,
93 ItemKind::Fn(..) => Target::Fn,
94 ItemKind::Mod(..) => Target::Mod,
95 ItemKind::ForeignMod(..) => Target::ForeignMod,
96 ItemKind::GlobalAsm(..) => Target::GlobalAsm,
97 ItemKind::TyAlias(..) => Target::TyAlias,
98 ItemKind::OpaqueTy(..) => Target::OpaqueTy,
99 ItemKind::Enum(..) => Target::Enum,
100 ItemKind::Struct(..) => Target::Struct,
101 ItemKind::Union(..) => Target::Union,
102 ItemKind::Trait(..) => Target::Trait,
103 ItemKind::TraitAlias(..) => Target::TraitAlias,
104 ItemKind::Impl(..) => Target::Impl,
108 fn from_trait_item(trait_item: &TraitItem) -> Target {
109 match trait_item.kind {
110 TraitItemKind::Const(..) => Target::AssocConst,
111 TraitItemKind::Method(_, hir::TraitMethod::Required(_)) => {
112 Target::Method(MethodKind::Trait { body: false })
114 TraitItemKind::Method(_, hir::TraitMethod::Provided(_)) => {
115 Target::Method(MethodKind::Trait { body: true })
117 TraitItemKind::Type(..) => Target::AssocTy,
121 fn from_foreign_item(foreign_item: &hir::ForeignItem) -> Target {
122 match foreign_item.kind {
123 hir::ForeignItemKind::Fn(..) => Target::ForeignFn,
124 hir::ForeignItemKind::Static(..) => Target::ForeignStatic,
125 hir::ForeignItemKind::Type => Target::ForeignTy,
129 fn from_impl_item<'tcx>(tcx: TyCtxt<'tcx>, impl_item: &hir::ImplItem) -> Target {
130 match impl_item.kind {
131 hir::ImplItemKind::Const(..) => Target::Const,
132 hir::ImplItemKind::Method(..) => {
133 let parent_hir_id = tcx.hir().get_parent_item(impl_item.hir_id);
134 let containing_item = tcx.hir().expect_item(parent_hir_id);
135 let containing_impl_is_for_trait = match &containing_item.kind {
136 hir::ItemKind::Impl(_, _, _, _, tr, _, _) => tr.is_some(),
137 _ => bug!("parent of an ImplItem must be an Impl"),
139 if containing_impl_is_for_trait {
140 Target::Method(MethodKind::Trait { body: true })
142 Target::Method(MethodKind::Inherent)
145 hir::ImplItemKind::TyAlias(..) => Target::TyAlias,
146 hir::ImplItemKind::OpaqueTy(..) => Target::OpaqueTy,
151 struct CheckAttrVisitor<'tcx> {
155 impl CheckAttrVisitor<'tcx> {
156 /// Checks any attribute.
160 attrs: &HirVec<Attribute>,
165 let mut is_valid = true;
167 is_valid &= if attr.check_name(sym::inline) {
168 self.check_inline(hir_id, attr, span, target)
169 } else if attr.check_name(sym::non_exhaustive) {
170 self.check_non_exhaustive(attr, span, target)
171 } else if attr.check_name(sym::marker) {
172 self.check_marker(attr, span, target)
173 } else if attr.check_name(sym::target_feature) {
174 self.check_target_feature(attr, span, target)
175 } else if attr.check_name(sym::track_caller) {
176 self.check_track_caller(&attr.span, attrs, span, target)
186 if target == Target::Fn {
187 self.tcx.codegen_fn_attrs(self.tcx.hir().local_def_id(hir_id));
190 self.check_repr(attrs, span, target, item);
191 self.check_used(attrs, target);
194 /// Checks if an `#[inline]` is applied to a function or a closure. Returns `true` if valid.
195 fn check_inline(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) -> bool {
197 Target::Fn | Target::Closure | Target::Method(MethodKind::Trait { body: true })
198 | Target::Method(MethodKind::Inherent) => true,
199 Target::Method(MethodKind::Trait { body: false }) | Target::ForeignFn => {
200 self.tcx.struct_span_lint_hir(
204 "`#[inline]` is ignored on function prototypes",
209 struct_span_err!(self.tcx.sess,
212 "attribute should be applied to function or closure")
213 .span_label(*span, "not a function or closure")
220 /// Checks if a `#[track_caller]` is applied to a non-naked function. Returns `true` if valid.
221 fn check_track_caller(
224 attrs: &HirVec<Attribute>,
229 Target::Fn if attr::contains_name(attrs, sym::naked) => {
234 "cannot use `#[track_caller]` with `#[naked]`",
238 Target::Fn | Target::Method(MethodKind::Inherent) => true,
239 Target::Method(_) => {
244 "`#[track_caller]` may not be used on trait methods",
253 "attribute should be applied to function"
255 .span_label(*span, "not a function")
262 /// Checks if the `#[non_exhaustive]` attribute on an `item` is valid. Returns `true` if valid.
263 fn check_non_exhaustive(
270 Target::Struct | Target::Enum => true,
272 struct_span_err!(self.tcx.sess,
275 "attribute can only be applied to a struct or enum")
276 .span_label(*span, "not a struct or enum")
283 /// Checks if the `#[marker]` attribute on an `item` is valid. Returns `true` if valid.
284 fn check_marker(&self, attr: &Attribute, span: &Span, target: Target) -> bool {
286 Target::Trait => true,
289 .struct_span_err(attr.span, "attribute can only be applied to a trait")
290 .span_label(*span, "not a trait")
297 /// Checks if the `#[target_feature]` attribute on `item` is valid. Returns `true` if valid.
298 fn check_target_feature(&self, attr: &Attribute, span: &Span, target: Target) -> bool {
300 Target::Fn | Target::Method(MethodKind::Trait { body: true })
301 | Target::Method(MethodKind::Inherent) => true,
304 .struct_span_err(attr.span, "attribute should be applied to a function")
305 .span_label(*span, "not a function")
312 /// Checks if the `#[repr]` attributes on `item` are valid.
315 attrs: &HirVec<Attribute>,
320 // Extract the names of all repr hints, e.g., [foo, bar, align] for:
323 // #[repr(bar, align(8))]
325 let hints: Vec<_> = attrs
327 .filter(|attr| attr.check_name(sym::repr))
328 .filter_map(|attr| attr.meta_item_list())
332 let mut int_reprs = 0;
333 let mut is_c = false;
334 let mut is_simd = false;
335 let mut is_transparent = false;
338 let (article, allowed_targets) = match hint.name_or_empty() {
339 name @ sym::C | name @ sym::align => {
340 is_c |= name == sym::C;
342 Target::Struct | Target::Union | Target::Enum => continue,
343 _ => ("a", "struct, enum, or union"),
347 if target != Target::Struct &&
348 target != Target::Union {
349 ("a", "struct or union")
356 if target != Target::Struct {
362 sym::transparent => {
363 is_transparent = true;
365 Target::Struct | Target::Union | Target::Enum => continue,
366 _ => ("a", "struct, enum, or union"),
369 sym::i8 | sym::u8 | sym::i16 | sym::u16 |
370 sym::i32 | sym::u32 | sym::i64 | sym::u64 |
371 sym::isize | sym::usize => {
373 if target != Target::Enum {
381 self.emit_repr_error(
384 &format!("attribute should be applied to {}", allowed_targets),
385 &format!("not {} {}", article, allowed_targets),
389 // Just point at all repr hints if there are any incompatibilities.
390 // This is not ideal, but tracking precisely which ones are at fault is a huge hassle.
391 let hint_spans = hints.iter().map(|hint| hint.span());
393 // Error on repr(transparent, <anything else>).
394 if is_transparent && hints.len() > 1 {
395 let hint_spans: Vec<_> = hint_spans.clone().collect();
396 span_err!(self.tcx.sess, hint_spans, E0692,
397 "transparent {} cannot have other repr hints", target);
399 // Warn on repr(u8, u16), repr(C, simd), and c-like-enum-repr(C, u8)
402 || (int_reprs == 1 && is_c && item.map_or(false, |item| is_c_like_enum(item))) {
403 let hint_spans: Vec<_> = hint_spans.collect();
404 span_warn!(self.tcx.sess, hint_spans, E0566,
405 "conflicting representation hints");
416 struct_span_err!(self.tcx.sess, hint_span, E0517, "{}", hint_message)
417 .span_label(label_span, label_message)
421 fn check_stmt_attributes(&self, stmt: &hir::Stmt) {
422 // When checking statements ignore expressions, they will be checked later
423 if let hir::StmtKind::Local(ref l) = stmt.kind {
424 for attr in l.attrs.iter() {
425 if attr.check_name(sym::inline) {
426 self.check_inline(DUMMY_HIR_ID, attr, &stmt.span, Target::Statement);
428 if attr.check_name(sym::repr) {
429 self.emit_repr_error(
432 "attribute should not be applied to a statement",
433 "not a struct, enum, or union",
440 fn check_expr_attributes(&self, expr: &hir::Expr) {
441 let target = match expr.kind {
442 hir::ExprKind::Closure(..) => Target::Closure,
443 _ => Target::Expression,
445 for attr in expr.attrs.iter() {
446 if attr.check_name(sym::inline) {
447 self.check_inline(DUMMY_HIR_ID, attr, &expr.span, target);
449 if attr.check_name(sym::repr) {
450 self.emit_repr_error(
453 "attribute should not be applied to an expression",
454 "not defining a struct, enum, or union",
460 fn check_used(&self, attrs: &HirVec<Attribute>, target: Target) {
462 if attr.check_name(sym::used) && target != Target::Static {
464 .span_err(attr.span, "attribute must be applied to a `static` variable");
470 impl Visitor<'tcx> for CheckAttrVisitor<'tcx> {
471 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
472 NestedVisitorMap::OnlyBodies(&self.tcx.hir())
475 fn visit_item(&mut self, item: &'tcx Item) {
476 let target = Target::from_item(item);
477 self.check_attributes(item.hir_id, &item.attrs, &item.span, target, Some(item));
478 intravisit::walk_item(self, item)
481 fn visit_trait_item(&mut self, trait_item: &'tcx TraitItem) {
482 let target = Target::from_trait_item(trait_item);
483 self.check_attributes(trait_item.hir_id, &trait_item.attrs, &trait_item.span, target, None);
484 intravisit::walk_trait_item(self, trait_item)
487 fn visit_foreign_item(&mut self, f_item: &'tcx hir::ForeignItem) {
488 let target = Target::from_foreign_item(f_item);
489 self.check_attributes(f_item.hir_id, &f_item.attrs, &f_item.span, target, None);
490 intravisit::walk_foreign_item(self, f_item)
493 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
494 let target = Target::from_impl_item(self.tcx, impl_item);
495 self.check_attributes(impl_item.hir_id, &impl_item.attrs, &impl_item.span, target, None);
496 intravisit::walk_impl_item(self, impl_item)
499 fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt) {
500 self.check_stmt_attributes(stmt);
501 intravisit::walk_stmt(self, stmt)
504 fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
505 self.check_expr_attributes(expr);
506 intravisit::walk_expr(self, expr)
510 fn is_c_like_enum(item: &Item) -> bool {
511 if let ItemKind::Enum(ref def, _) = item.kind {
512 for variant in &def.variants {
514 hir::VariantData::Unit(..) => { /* continue */ }
524 fn check_mod_attrs(tcx: TyCtxt<'_>, module_def_id: DefId) {
525 tcx.hir().visit_item_likes_in_module(
527 &mut CheckAttrVisitor { tcx }.as_deep_visitor()
531 pub(crate) fn provide(providers: &mut Providers<'_>) {
532 *providers = Providers {