]> git.lizzy.rs Git - rust.git/blob - src/librustc/hir/check_attr.rs
Rename `Item.node` to `Item.kind`
[rust.git] / src / librustc / hir / check_attr.rs
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
5 //! item.
6
7 use crate::hir;
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;
12
13 use std::fmt::{self, Display};
14 use syntax::symbol::sym;
15 use syntax_pos::Span;
16
17 #[derive(Copy, Clone, PartialEq)]
18 pub(crate) enum Target {
19     ExternCrate,
20     Use,
21     Static,
22     Const,
23     Fn,
24     Closure,
25     Mod,
26     ForeignMod,
27     GlobalAsm,
28     TyAlias,
29     OpaqueTy,
30     Enum,
31     Struct,
32     Union,
33     Trait,
34     TraitAlias,
35     Impl,
36     Expression,
37     Statement,
38 }
39
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",
44             Target::Use => "use",
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",
62         })
63     }
64 }
65
66 impl Target {
67     pub(crate) fn from_item(item: &hir::Item) -> Target {
68         match item.kind {
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,
85         }
86     }
87 }
88
89 struct CheckAttrVisitor<'tcx> {
90     tcx: TyCtxt<'tcx>,
91 }
92
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")
101                 .emit();
102         }
103
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)
111             }
112         }
113
114         self.check_repr(item, target);
115         self.check_used(item, target);
116     }
117
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,
122                              attr.span,
123                              E0518,
124                              "attribute should be applied to function or closure")
125                 .span_label(*span, "not a function or closure")
126                 .emit();
127         }
128     }
129
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) {
132         match target {
133             Target::Struct | Target::Enum => { /* Valid */ },
134             _ => {
135                 struct_span_err!(self.tcx.sess,
136                                  attr.span,
137                                  E0701,
138                                  "attribute can only be applied to a struct or enum")
139                     .span_label(item.span, "not a struct or enum")
140                     .emit();
141                 return;
142             }
143         }
144     }
145
146     /// Checks if the `#[marker]` attribute on an `item` is valid.
147     fn check_marker(&self, attr: &hir::Attribute, item: &hir::Item, target: Target) {
148         match target {
149             Target::Trait => { /* Valid */ },
150             _ => {
151                 self.tcx.sess
152                     .struct_span_err(attr.span, "attribute can only be applied to a trait")
153                     .span_label(item.span, "not a trait")
154                     .emit();
155                 return;
156             }
157         }
158     }
159
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:
163         // ```
164         // #[repr(foo)]
165         // #[repr(bar, align(8))]
166         // ```
167         let hints: Vec<_> = item.attrs
168             .iter()
169             .filter(|attr| attr.check_name(sym::repr))
170             .filter_map(|attr| attr.meta_item_list())
171             .flatten()
172             .collect();
173
174         let mut int_reprs = 0;
175         let mut is_c = false;
176         let mut is_simd = false;
177         let mut is_transparent = false;
178
179         for hint in &hints {
180             let (article, allowed_targets) = match hint.name_or_empty() {
181                 name @ sym::C | name @ sym::align => {
182                     is_c |= name == sym::C;
183                     match target {
184                         Target::Struct | Target::Union | Target::Enum => continue,
185                         _ => ("a", "struct, enum, or union"),
186                     }
187                 }
188                 sym::packed => {
189                     if target != Target::Struct &&
190                             target != Target::Union {
191                                 ("a", "struct or union")
192                     } else {
193                         continue
194                     }
195                 }
196                 sym::simd => {
197                     is_simd = true;
198                     if target != Target::Struct {
199                         ("a", "struct")
200                     } else {
201                         continue
202                     }
203                 }
204                 sym::transparent => {
205                     is_transparent = true;
206                     match target {
207                         Target::Struct | Target::Union | Target::Enum => continue,
208                         _ => ("a", "struct, enum, or union"),
209                     }
210                 }
211                 sym::i8  | sym::u8  | sym::i16 | sym::u16 |
212                 sym::i32 | sym::u32 | sym::i64 | sym::u64 |
213                 sym::isize | sym::usize => {
214                     int_reprs += 1;
215                     if target != Target::Enum {
216                         ("an", "enum")
217                     } else {
218                         continue
219                     }
220                 }
221                 _ => continue,
222             };
223             self.emit_repr_error(
224                 hint.span(),
225                 item.span,
226                 &format!("attribute should be applied to {}", allowed_targets),
227                 &format!("not {} {}", article, allowed_targets),
228             )
229         }
230
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());
234
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);
240         }
241         // Warn on repr(u8, u16), repr(C, simd), and c-like-enum-repr(C, u8)
242         if (int_reprs > 1)
243            || (is_simd && is_c)
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");
248         }
249     }
250
251     fn emit_repr_error(
252         &self,
253         hint_span: Span,
254         label_span: Span,
255         hint_message: &str,
256         label_message: &str,
257     ) {
258         struct_span_err!(self.tcx.sess, hint_span, E0517, "{}", hint_message)
259             .span_label(label_span, label_message)
260             .emit();
261     }
262
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);
269                 }
270                 if attr.check_name(sym::repr) {
271                     self.emit_repr_error(
272                         attr.span,
273                         stmt.span,
274                         "attribute should not be applied to a statement",
275                         "not a struct, enum, or union",
276                     );
277                 }
278             }
279         }
280     }
281
282     fn check_expr_attributes(&self, expr: &hir::Expr) {
283         let target = match expr.kind {
284             hir::ExprKind::Closure(..) => Target::Closure,
285             _ => Target::Expression,
286         };
287         for attr in expr.attrs.iter() {
288             if attr.check_name(sym::inline) {
289                 self.check_inline(attr, &expr.span, target);
290             }
291             if attr.check_name(sym::repr) {
292                 self.emit_repr_error(
293                     attr.span,
294                     expr.span,
295                     "attribute should not be applied to an expression",
296                     "not defining a struct, enum, or union",
297                 );
298             }
299         }
300     }
301
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 {
305                 self.tcx.sess
306                     .span_err(attr.span, "attribute must be applied to a `static` variable");
307             }
308         }
309     }
310 }
311
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())
315     }
316
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)
321     }
322
323
324     fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt) {
325         self.check_stmt_attributes(stmt);
326         intravisit::walk_stmt(self, stmt)
327     }
328
329     fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
330         self.check_expr_attributes(expr);
331         intravisit::walk_expr(self, expr)
332     }
333 }
334
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 {
338             match variant.data {
339                 hir::VariantData::Unit(..) => { /* continue */ }
340                 _ => { return false; }
341             }
342         }
343         true
344     } else {
345         false
346     }
347 }
348
349 fn check_mod_attrs(tcx: TyCtxt<'_>, module_def_id: DefId) {
350     tcx.hir().visit_item_likes_in_module(
351         module_def_id,
352         &mut CheckAttrVisitor { tcx }.as_deep_visitor()
353     );
354 }
355
356 pub(crate) fn provide(providers: &mut Providers<'_>) {
357     *providers = Providers {
358         check_mod_attrs,
359         ..*providers
360     };
361 }