]> git.lizzy.rs Git - rust.git/blob - src/librustc/hir/check_attr.rs
Auto merge of #60763 - matklad:tt-parser, r=petrochenkov
[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
8 use crate::ty::TyCtxt;
9 use crate::ty::query::Providers;
10
11 use crate::hir;
12 use crate::hir::def_id::DefId;
13 use crate::hir::intravisit::{self, Visitor, NestedVisitorMap};
14 use std::fmt::{self, Display};
15 use syntax::symbol::sym;
16 use syntax_pos::Span;
17
18 #[derive(Copy, Clone, PartialEq)]
19 pub(crate) enum Target {
20     ExternCrate,
21     Use,
22     Static,
23     Const,
24     Fn,
25     Closure,
26     Mod,
27     ForeignMod,
28     GlobalAsm,
29     Ty,
30     Existential,
31     Enum,
32     Struct,
33     Union,
34     Trait,
35     TraitAlias,
36     Impl,
37     Expression,
38     Statement,
39 }
40
41 impl Display for Target {
42     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
43         write!(f, "{}", match *self {
44             Target::ExternCrate => "extern crate",
45             Target::Use => "use",
46             Target::Static => "static item",
47             Target::Const => "constant item",
48             Target::Fn => "function",
49             Target::Closure => "closure",
50             Target::Mod => "module",
51             Target::ForeignMod => "foreign module",
52             Target::GlobalAsm => "global asm",
53             Target::Ty => "type alias",
54             Target::Existential => "existential type",
55             Target::Enum => "enum",
56             Target::Struct => "struct",
57             Target::Union => "union",
58             Target::Trait => "trait",
59             Target::TraitAlias => "trait alias",
60             Target::Impl => "item",
61             Target::Expression => "expression",
62             Target::Statement => "statement",
63         })
64     }
65 }
66
67 impl Target {
68     pub(crate) fn from_item(item: &hir::Item) -> Target {
69         match item.node {
70             hir::ItemKind::ExternCrate(..) => Target::ExternCrate,
71             hir::ItemKind::Use(..) => Target::Use,
72             hir::ItemKind::Static(..) => Target::Static,
73             hir::ItemKind::Const(..) => Target::Const,
74             hir::ItemKind::Fn(..) => Target::Fn,
75             hir::ItemKind::Mod(..) => Target::Mod,
76             hir::ItemKind::ForeignMod(..) => Target::ForeignMod,
77             hir::ItemKind::GlobalAsm(..) => Target::GlobalAsm,
78             hir::ItemKind::Ty(..) => Target::Ty,
79             hir::ItemKind::Existential(..) => Target::Existential,
80             hir::ItemKind::Enum(..) => Target::Enum,
81             hir::ItemKind::Struct(..) => Target::Struct,
82             hir::ItemKind::Union(..) => Target::Union,
83             hir::ItemKind::Trait(..) => Target::Trait,
84             hir::ItemKind::TraitAlias(..) => Target::TraitAlias,
85             hir::ItemKind::Impl(..) => Target::Impl,
86         }
87     }
88 }
89
90 struct CheckAttrVisitor<'a, 'tcx: 'a> {
91     tcx: TyCtxt<'a, 'tcx, 'tcx>,
92 }
93
94 impl<'a, 'tcx> CheckAttrVisitor<'a, 'tcx> {
95     /// Checks any attribute.
96     fn check_attributes(&self, item: &hir::Item, target: Target) {
97         if target == Target::Fn || target == Target::Const {
98             self.tcx.codegen_fn_attrs(self.tcx.hir().local_def_id_from_hir_id(item.hir_id));
99         } else if let Some(a) = item.attrs.iter().find(|a| a.check_name(sym::target_feature)) {
100             self.tcx.sess.struct_span_err(a.span, "attribute should be applied to a function")
101                 .span_label(item.span, "not a function")
102                 .emit();
103         }
104
105         for attr in &item.attrs {
106             if attr.check_name(sym::inline) {
107                 self.check_inline(attr, &item.span, target)
108             } else if attr.check_name(sym::non_exhaustive) {
109                 self.check_non_exhaustive(attr, item, target)
110             } else if attr.check_name(sym::marker) {
111                 self.check_marker(attr, item, target)
112             }
113         }
114
115         self.check_repr(item, target);
116         self.check_used(item, target);
117     }
118
119     /// Checks if an `#[inline]` is applied to a function or a closure.
120     fn check_inline(&self, attr: &hir::Attribute, span: &Span, target: Target) {
121         if target != Target::Fn && target != Target::Closure {
122             struct_span_err!(self.tcx.sess,
123                              attr.span,
124                              E0518,
125                              "attribute should be applied to function or closure")
126                 .span_label(*span, "not a function or closure")
127                 .emit();
128         }
129     }
130
131     /// Checks if the `#[non_exhaustive]` attribute on an `item` is valid.
132     fn check_non_exhaustive(&self, attr: &hir::Attribute, item: &hir::Item, target: Target) {
133         match target {
134             Target::Struct | Target::Enum => { /* Valid */ },
135             _ => {
136                 struct_span_err!(self.tcx.sess,
137                                  attr.span,
138                                  E0701,
139                                  "attribute can only be applied to a struct or enum")
140                     .span_label(item.span, "not a struct or enum")
141                     .emit();
142                 return;
143             }
144         }
145     }
146
147     /// Checks if the `#[marker]` attribute on an `item` is valid.
148     fn check_marker(&self, attr: &hir::Attribute, item: &hir::Item, target: Target) {
149         match target {
150             Target::Trait => { /* Valid */ },
151             _ => {
152                 self.tcx.sess
153                     .struct_span_err(attr.span, "attribute can only be applied to a trait")
154                     .span_label(item.span, "not a trait")
155                     .emit();
156                 return;
157             }
158         }
159     }
160
161     /// Checks if the `#[repr]` attributes on `item` are valid.
162     fn check_repr(&self, item: &hir::Item, target: Target) {
163         // Extract the names of all repr hints, e.g., [foo, bar, align] for:
164         // ```
165         // #[repr(foo)]
166         // #[repr(bar, align(8))]
167         // ```
168         let hints: Vec<_> = item.attrs
169             .iter()
170             .filter(|attr| attr.check_name(sym::repr))
171             .filter_map(|attr| attr.meta_item_list())
172             .flatten()
173             .collect();
174
175         let mut int_reprs = 0;
176         let mut is_c = false;
177         let mut is_simd = false;
178         let mut is_transparent = false;
179
180         for hint in &hints {
181             let (article, allowed_targets) = match hint.name_or_empty() {
182                 name @ sym::C | name @ sym::align => {
183                     is_c |= name == sym::C;
184                     if target != Target::Struct &&
185                             target != Target::Union &&
186                             target != Target::Enum {
187                                 ("a", "struct, enum or union")
188                     } else {
189                         continue
190                     }
191                 }
192                 sym::packed => {
193                     if target != Target::Struct &&
194                             target != Target::Union {
195                                 ("a", "struct or union")
196                     } else {
197                         continue
198                     }
199                 }
200                 sym::simd => {
201                     is_simd = true;
202                     if target != Target::Struct {
203                         ("a", "struct")
204                     } else {
205                         continue
206                     }
207                 }
208                 sym::transparent => {
209                     is_transparent = true;
210                     if target != Target::Struct {
211                         ("a", "struct")
212                     } else {
213                         continue
214                     }
215                 }
216                 sym::i8  | sym::u8  | sym::i16 | sym::u16 |
217                 sym::i32 | sym::u32 | sym::i64 | sym::u64 |
218                 sym::isize | sym::usize => {
219                     int_reprs += 1;
220                     if target != Target::Enum {
221                         ("an", "enum")
222                     } else {
223                         continue
224                     }
225                 }
226                 _ => continue,
227             };
228             self.emit_repr_error(
229                 hint.span(),
230                 item.span,
231                 &format!("attribute should be applied to {}", allowed_targets),
232                 &format!("not {} {}", article, allowed_targets),
233             )
234         }
235
236         // Just point at all repr hints if there are any incompatibilities.
237         // This is not ideal, but tracking precisely which ones are at fault is a huge hassle.
238         let hint_spans = hints.iter().map(|hint| hint.span());
239
240         // Error on repr(transparent, <anything else>).
241         if is_transparent && hints.len() > 1 {
242             let hint_spans: Vec<_> = hint_spans.clone().collect();
243             span_err!(self.tcx.sess, hint_spans, E0692,
244                       "transparent struct cannot have other repr hints");
245         }
246         // Warn on repr(u8, u16), repr(C, simd), and c-like-enum-repr(C, u8)
247         if (int_reprs > 1)
248            || (is_simd && is_c)
249            || (int_reprs == 1 && is_c && is_c_like_enum(item)) {
250             let hint_spans: Vec<_> = hint_spans.collect();
251             span_warn!(self.tcx.sess, hint_spans, E0566,
252                        "conflicting representation hints");
253         }
254     }
255
256     fn emit_repr_error(
257         &self,
258         hint_span: Span,
259         label_span: Span,
260         hint_message: &str,
261         label_message: &str,
262     ) {
263         struct_span_err!(self.tcx.sess, hint_span, E0517, "{}", hint_message)
264             .span_label(label_span, label_message)
265             .emit();
266     }
267
268     fn check_stmt_attributes(&self, stmt: &hir::Stmt) {
269         // When checking statements ignore expressions, they will be checked later
270         if let hir::StmtKind::Local(ref l) = stmt.node {
271             for attr in l.attrs.iter() {
272                 if attr.check_name(sym::inline) {
273                     self.check_inline(attr, &stmt.span, Target::Statement);
274                 }
275                 if attr.check_name(sym::repr) {
276                     self.emit_repr_error(
277                         attr.span,
278                         stmt.span,
279                         "attribute should not be applied to a statement",
280                         "not a struct, enum or union",
281                     );
282                 }
283             }
284         }
285     }
286
287     fn check_expr_attributes(&self, expr: &hir::Expr) {
288         let target = match expr.node {
289             hir::ExprKind::Closure(..) => Target::Closure,
290             _ => Target::Expression,
291         };
292         for attr in expr.attrs.iter() {
293             if attr.check_name(sym::inline) {
294                 self.check_inline(attr, &expr.span, target);
295             }
296             if attr.check_name(sym::repr) {
297                 self.emit_repr_error(
298                     attr.span,
299                     expr.span,
300                     "attribute should not be applied to an expression",
301                     "not defining a struct, enum or union",
302                 );
303             }
304         }
305     }
306
307     fn check_used(&self, item: &hir::Item, target: Target) {
308         for attr in &item.attrs {
309             if attr.check_name(sym::used) && target != Target::Static {
310                 self.tcx.sess
311                     .span_err(attr.span, "attribute must be applied to a `static` variable");
312             }
313         }
314     }
315 }
316
317 impl<'a, 'tcx> Visitor<'tcx> for CheckAttrVisitor<'a, 'tcx> {
318     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
319         NestedVisitorMap::OnlyBodies(&self.tcx.hir())
320     }
321
322     fn visit_item(&mut self, item: &'tcx hir::Item) {
323         let target = Target::from_item(item);
324         self.check_attributes(item, target);
325         intravisit::walk_item(self, item)
326     }
327
328
329     fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt) {
330         self.check_stmt_attributes(stmt);
331         intravisit::walk_stmt(self, stmt)
332     }
333
334     fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
335         self.check_expr_attributes(expr);
336         intravisit::walk_expr(self, expr)
337     }
338 }
339
340 fn is_c_like_enum(item: &hir::Item) -> bool {
341     if let hir::ItemKind::Enum(ref def, _) = item.node {
342         for variant in &def.variants {
343             match variant.node.data {
344                 hir::VariantData::Unit(..) => { /* continue */ }
345                 _ => { return false; }
346             }
347         }
348         true
349     } else {
350         false
351     }
352 }
353
354 fn check_mod_attrs<'tcx>(tcx: TyCtxt<'_, 'tcx, 'tcx>, module_def_id: DefId) {
355     tcx.hir().visit_item_likes_in_module(
356         module_def_id,
357         &mut CheckAttrVisitor { tcx }.as_deep_visitor()
358     );
359 }
360
361 pub(crate) fn provide(providers: &mut Providers<'_>) {
362     *providers = Providers {
363         check_mod_attrs,
364         ..*providers
365     };
366 }