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
8 use crate::hir::def_id::DefId;
9 use crate::hir::intravisit::{self, Visitor, NestedVisitorMap};
10 use crate::ty::TyCtxt;
11 use crate::ty::query::Providers;
13 use std::fmt::{self, Display};
14 use syntax::symbol::sym;
17 #[derive(Copy, Clone, PartialEq)]
18 pub(crate) enum Target {
40 impl Display for Target {
41 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
42 write!(f, "{}", match *self {
43 Target::ExternCrate => "extern crate",
45 Target::Static => "static item",
46 Target::Const => "constant item",
47 Target::Fn => "function",
48 Target::Closure => "closure",
49 Target::Mod => "module",
50 Target::ForeignMod => "foreign module",
51 Target::GlobalAsm => "global asm",
52 Target::TyAlias => "type alias",
53 Target::OpaqueTy => "opaque type",
54 Target::Enum => "enum",
55 Target::Struct => "struct",
56 Target::Union => "union",
57 Target::Trait => "trait",
58 Target::TraitAlias => "trait alias",
59 Target::Impl => "item",
60 Target::Expression => "expression",
61 Target::Statement => "statement",
67 pub(crate) fn from_item(item: &hir::Item) -> Target {
69 hir::ItemKind::ExternCrate(..) => Target::ExternCrate,
70 hir::ItemKind::Use(..) => Target::Use,
71 hir::ItemKind::Static(..) => Target::Static,
72 hir::ItemKind::Const(..) => Target::Const,
73 hir::ItemKind::Fn(..) => Target::Fn,
74 hir::ItemKind::Mod(..) => Target::Mod,
75 hir::ItemKind::ForeignMod(..) => Target::ForeignMod,
76 hir::ItemKind::GlobalAsm(..) => Target::GlobalAsm,
77 hir::ItemKind::TyAlias(..) => Target::TyAlias,
78 hir::ItemKind::OpaqueTy(..) => Target::OpaqueTy,
79 hir::ItemKind::Enum(..) => Target::Enum,
80 hir::ItemKind::Struct(..) => Target::Struct,
81 hir::ItemKind::Union(..) => Target::Union,
82 hir::ItemKind::Trait(..) => Target::Trait,
83 hir::ItemKind::TraitAlias(..) => Target::TraitAlias,
84 hir::ItemKind::Impl(..) => Target::Impl,
89 struct CheckAttrVisitor<'tcx> {
93 impl CheckAttrVisitor<'tcx> {
94 /// Checks any attribute.
95 fn check_attributes(&self, item: &hir::Item, target: Target) {
96 if target == Target::Fn || target == Target::Const {
97 self.tcx.codegen_fn_attrs(self.tcx.hir().local_def_id(item.hir_id));
98 } else if let Some(a) = item.attrs.iter().find(|a| a.check_name(sym::target_feature)) {
99 self.tcx.sess.struct_span_err(a.span, "attribute should be applied to a function")
100 .span_label(item.span, "not a function")
104 for attr in &item.attrs {
105 if attr.check_name(sym::inline) {
106 self.check_inline(attr, &item.span, target)
107 } else if attr.check_name(sym::non_exhaustive) {
108 self.check_non_exhaustive(attr, item, target)
109 } else if attr.check_name(sym::marker) {
110 self.check_marker(attr, item, target)
114 self.check_repr(item, target);
115 self.check_used(item, target);
118 /// Checks if an `#[inline]` is applied to a function or a closure.
119 fn check_inline(&self, attr: &hir::Attribute, span: &Span, target: Target) {
120 if target != Target::Fn && target != Target::Closure {
121 struct_span_err!(self.tcx.sess,
124 "attribute should be applied to function or closure")
125 .span_label(*span, "not a function or closure")
130 /// Checks if the `#[non_exhaustive]` attribute on an `item` is valid.
131 fn check_non_exhaustive(&self, attr: &hir::Attribute, item: &hir::Item, target: Target) {
133 Target::Struct | Target::Enum => { /* Valid */ },
135 struct_span_err!(self.tcx.sess,
138 "attribute can only be applied to a struct or enum")
139 .span_label(item.span, "not a struct or enum")
146 /// Checks if the `#[marker]` attribute on an `item` is valid.
147 fn check_marker(&self, attr: &hir::Attribute, item: &hir::Item, target: Target) {
149 Target::Trait => { /* Valid */ },
152 .struct_span_err(attr.span, "attribute can only be applied to a trait")
153 .span_label(item.span, "not a trait")
160 /// Checks if the `#[repr]` attributes on `item` are valid.
161 fn check_repr(&self, item: &hir::Item, target: Target) {
162 // Extract the names of all repr hints, e.g., [foo, bar, align] for:
165 // #[repr(bar, align(8))]
167 let hints: Vec<_> = item.attrs
169 .filter(|attr| attr.check_name(sym::repr))
170 .filter_map(|attr| attr.meta_item_list())
174 let mut int_reprs = 0;
175 let mut is_c = false;
176 let mut is_simd = false;
177 let mut is_transparent = false;
180 let (article, allowed_targets) = match hint.name_or_empty() {
181 name @ sym::C | name @ sym::align => {
182 is_c |= name == sym::C;
184 Target::Struct | Target::Union | Target::Enum => continue,
185 _ => ("a", "struct, enum, or union"),
189 if target != Target::Struct &&
190 target != Target::Union {
191 ("a", "struct or union")
198 if target != Target::Struct {
204 sym::transparent => {
205 is_transparent = true;
207 Target::Struct | Target::Union | Target::Enum => continue,
208 _ => ("a", "struct, enum, or union"),
211 sym::i8 | sym::u8 | sym::i16 | sym::u16 |
212 sym::i32 | sym::u32 | sym::i64 | sym::u64 |
213 sym::isize | sym::usize => {
215 if target != Target::Enum {
223 self.emit_repr_error(
226 &format!("attribute should be applied to {}", allowed_targets),
227 &format!("not {} {}", article, allowed_targets),
231 // Just point at all repr hints if there are any incompatibilities.
232 // This is not ideal, but tracking precisely which ones are at fault is a huge hassle.
233 let hint_spans = hints.iter().map(|hint| hint.span());
235 // Error on repr(transparent, <anything else>).
236 if is_transparent && hints.len() > 1 {
237 let hint_spans: Vec<_> = hint_spans.clone().collect();
238 span_err!(self.tcx.sess, hint_spans, E0692,
239 "transparent {} cannot have other repr hints", target);
241 // Warn on repr(u8, u16), repr(C, simd), and c-like-enum-repr(C, u8)
244 || (int_reprs == 1 && is_c && is_c_like_enum(item)) {
245 let hint_spans: Vec<_> = hint_spans.collect();
246 span_warn!(self.tcx.sess, hint_spans, E0566,
247 "conflicting representation hints");
258 struct_span_err!(self.tcx.sess, hint_span, E0517, "{}", hint_message)
259 .span_label(label_span, label_message)
263 fn check_stmt_attributes(&self, stmt: &hir::Stmt) {
264 // When checking statements ignore expressions, they will be checked later
265 if let hir::StmtKind::Local(ref l) = stmt.kind {
266 for attr in l.attrs.iter() {
267 if attr.check_name(sym::inline) {
268 self.check_inline(attr, &stmt.span, Target::Statement);
270 if attr.check_name(sym::repr) {
271 self.emit_repr_error(
274 "attribute should not be applied to a statement",
275 "not a struct, enum, or union",
282 fn check_expr_attributes(&self, expr: &hir::Expr) {
283 let target = match expr.kind {
284 hir::ExprKind::Closure(..) => Target::Closure,
285 _ => Target::Expression,
287 for attr in expr.attrs.iter() {
288 if attr.check_name(sym::inline) {
289 self.check_inline(attr, &expr.span, target);
291 if attr.check_name(sym::repr) {
292 self.emit_repr_error(
295 "attribute should not be applied to an expression",
296 "not defining a struct, enum, or union",
302 fn check_used(&self, item: &hir::Item, target: Target) {
303 for attr in &item.attrs {
304 if attr.check_name(sym::used) && target != Target::Static {
306 .span_err(attr.span, "attribute must be applied to a `static` variable");
312 impl Visitor<'tcx> for CheckAttrVisitor<'tcx> {
313 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
314 NestedVisitorMap::OnlyBodies(&self.tcx.hir())
317 fn visit_item(&mut self, item: &'tcx hir::Item) {
318 let target = Target::from_item(item);
319 self.check_attributes(item, target);
320 intravisit::walk_item(self, item)
324 fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt) {
325 self.check_stmt_attributes(stmt);
326 intravisit::walk_stmt(self, stmt)
329 fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
330 self.check_expr_attributes(expr);
331 intravisit::walk_expr(self, expr)
335 fn is_c_like_enum(item: &hir::Item) -> bool {
336 if let hir::ItemKind::Enum(ref def, _) = item.kind {
337 for variant in &def.variants {
339 hir::VariantData::Unit(..) => { /* continue */ }
340 _ => { return false; }
349 fn check_mod_attrs(tcx: TyCtxt<'_>, module_def_id: DefId) {
350 tcx.hir().visit_item_likes_in_module(
352 &mut CheckAttrVisitor { tcx }.as_deep_visitor()
356 pub(crate) fn provide(providers: &mut Providers<'_>) {
357 *providers = Providers {