]> git.lizzy.rs Git - rust.git/blob - src/librustc/hir/check_attr.rs
Auto merge of #65153 - da-x:issue-58017, 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 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::{attr, 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         let mut is_valid = true;
97         for attr in &item.attrs {
98             is_valid &= if attr.check_name(sym::inline) {
99                 self.check_inline(attr, &item.span, target)
100             } else if attr.check_name(sym::non_exhaustive) {
101                 self.check_non_exhaustive(attr, item, target)
102             } else if attr.check_name(sym::marker) {
103                 self.check_marker(attr, item, target)
104             } else if attr.check_name(sym::target_feature) {
105                 self.check_target_feature(attr, item, target)
106             } else if attr.check_name(sym::track_caller) {
107                 self.check_track_caller(attr, &item, target)
108             } else {
109                 true
110             };
111         }
112
113         if !is_valid {
114             return;
115         }
116
117         if target == Target::Fn {
118             self.tcx.codegen_fn_attrs(self.tcx.hir().local_def_id(item.hir_id));
119         }
120
121         self.check_repr(item, target);
122         self.check_used(item, target);
123     }
124
125     /// Checks if an `#[inline]` is applied to a function or a closure. Returns `true` if valid.
126     fn check_inline(&self, attr: &hir::Attribute, span: &Span, target: Target) -> bool {
127         if target != Target::Fn && target != Target::Closure {
128             struct_span_err!(self.tcx.sess,
129                              attr.span,
130                              E0518,
131                              "attribute should be applied to function or closure")
132                 .span_label(*span, "not a function or closure")
133                 .emit();
134             false
135         } else {
136             true
137         }
138     }
139
140     /// Checks if a `#[track_caller]` is applied to a non-naked function. Returns `true` if valid.
141     fn check_track_caller(&self, attr: &hir::Attribute, item: &hir::Item, target: Target) -> bool {
142         if target != Target::Fn {
143             struct_span_err!(
144                 self.tcx.sess,
145                 attr.span,
146                 E0739,
147                 "attribute should be applied to function"
148             )
149             .span_label(item.span, "not a function")
150             .emit();
151             false
152         } else if attr::contains_name(&item.attrs, sym::naked) {
153             struct_span_err!(
154                 self.tcx.sess,
155                 attr.span,
156                 E0736,
157                 "cannot use `#[track_caller]` with `#[naked]`",
158             )
159             .emit();
160             false
161         } else {
162             true
163         }
164     }
165
166     /// Checks if the `#[non_exhaustive]` attribute on an `item` is valid. Returns `true` if valid.
167     fn check_non_exhaustive(
168         &self,
169         attr: &hir::Attribute,
170         item: &hir::Item,
171         target: Target,
172     ) -> bool {
173         match target {
174             Target::Struct | Target::Enum => true,
175             _ => {
176                 struct_span_err!(self.tcx.sess,
177                                  attr.span,
178                                  E0701,
179                                  "attribute can only be applied to a struct or enum")
180                     .span_label(item.span, "not a struct or enum")
181                     .emit();
182                 false
183             }
184         }
185     }
186
187     /// Checks if the `#[marker]` attribute on an `item` is valid. Returns `true` if valid.
188     fn check_marker(&self, attr: &hir::Attribute, item: &hir::Item, target: Target) -> bool {
189         match target {
190             Target::Trait => true,
191             _ => {
192                 self.tcx.sess
193                     .struct_span_err(attr.span, "attribute can only be applied to a trait")
194                     .span_label(item.span, "not a trait")
195                     .emit();
196                 false
197             }
198         }
199     }
200
201     /// Checks if the `#[target_feature]` attribute on `item` is valid. Returns `true` if valid.
202     fn check_target_feature(
203         &self,
204         attr: &hir::Attribute,
205         item: &hir::Item,
206         target: Target,
207     ) -> bool {
208         match target {
209             Target::Fn => true,
210             _ => {
211                 self.tcx.sess
212                     .struct_span_err(attr.span, "attribute should be applied to a function")
213                     .span_label(item.span, "not a function")
214                     .emit();
215                 false
216             },
217         }
218     }
219
220     /// Checks if the `#[repr]` attributes on `item` are valid.
221     fn check_repr(&self, item: &hir::Item, target: Target) {
222         // Extract the names of all repr hints, e.g., [foo, bar, align] for:
223         // ```
224         // #[repr(foo)]
225         // #[repr(bar, align(8))]
226         // ```
227         let hints: Vec<_> = item.attrs
228             .iter()
229             .filter(|attr| attr.check_name(sym::repr))
230             .filter_map(|attr| attr.meta_item_list())
231             .flatten()
232             .collect();
233
234         let mut int_reprs = 0;
235         let mut is_c = false;
236         let mut is_simd = false;
237         let mut is_transparent = false;
238
239         for hint in &hints {
240             let (article, allowed_targets) = match hint.name_or_empty() {
241                 name @ sym::C | name @ sym::align => {
242                     is_c |= name == sym::C;
243                     match target {
244                         Target::Struct | Target::Union | Target::Enum => continue,
245                         _ => ("a", "struct, enum, or union"),
246                     }
247                 }
248                 sym::packed => {
249                     if target != Target::Struct &&
250                             target != Target::Union {
251                                 ("a", "struct or union")
252                     } else {
253                         continue
254                     }
255                 }
256                 sym::simd => {
257                     is_simd = true;
258                     if target != Target::Struct {
259                         ("a", "struct")
260                     } else {
261                         continue
262                     }
263                 }
264                 sym::transparent => {
265                     is_transparent = true;
266                     match target {
267                         Target::Struct | Target::Union | Target::Enum => continue,
268                         _ => ("a", "struct, enum, or union"),
269                     }
270                 }
271                 sym::i8  | sym::u8  | sym::i16 | sym::u16 |
272                 sym::i32 | sym::u32 | sym::i64 | sym::u64 |
273                 sym::isize | sym::usize => {
274                     int_reprs += 1;
275                     if target != Target::Enum {
276                         ("an", "enum")
277                     } else {
278                         continue
279                     }
280                 }
281                 _ => continue,
282             };
283             self.emit_repr_error(
284                 hint.span(),
285                 item.span,
286                 &format!("attribute should be applied to {}", allowed_targets),
287                 &format!("not {} {}", article, allowed_targets),
288             )
289         }
290
291         // Just point at all repr hints if there are any incompatibilities.
292         // This is not ideal, but tracking precisely which ones are at fault is a huge hassle.
293         let hint_spans = hints.iter().map(|hint| hint.span());
294
295         // Error on repr(transparent, <anything else>).
296         if is_transparent && hints.len() > 1 {
297             let hint_spans: Vec<_> = hint_spans.clone().collect();
298             span_err!(self.tcx.sess, hint_spans, E0692,
299                       "transparent {} cannot have other repr hints", target);
300         }
301         // Warn on repr(u8, u16), repr(C, simd), and c-like-enum-repr(C, u8)
302         if (int_reprs > 1)
303            || (is_simd && is_c)
304            || (int_reprs == 1 && is_c && is_c_like_enum(item)) {
305             let hint_spans: Vec<_> = hint_spans.collect();
306             span_warn!(self.tcx.sess, hint_spans, E0566,
307                        "conflicting representation hints");
308         }
309     }
310
311     fn emit_repr_error(
312         &self,
313         hint_span: Span,
314         label_span: Span,
315         hint_message: &str,
316         label_message: &str,
317     ) {
318         struct_span_err!(self.tcx.sess, hint_span, E0517, "{}", hint_message)
319             .span_label(label_span, label_message)
320             .emit();
321     }
322
323     fn check_stmt_attributes(&self, stmt: &hir::Stmt) {
324         // When checking statements ignore expressions, they will be checked later
325         if let hir::StmtKind::Local(ref l) = stmt.kind {
326             for attr in l.attrs.iter() {
327                 if attr.check_name(sym::inline) {
328                     self.check_inline(attr, &stmt.span, Target::Statement);
329                 }
330                 if attr.check_name(sym::repr) {
331                     self.emit_repr_error(
332                         attr.span,
333                         stmt.span,
334                         "attribute should not be applied to a statement",
335                         "not a struct, enum, or union",
336                     );
337                 }
338             }
339         }
340     }
341
342     fn check_expr_attributes(&self, expr: &hir::Expr) {
343         let target = match expr.kind {
344             hir::ExprKind::Closure(..) => Target::Closure,
345             _ => Target::Expression,
346         };
347         for attr in expr.attrs.iter() {
348             if attr.check_name(sym::inline) {
349                 self.check_inline(attr, &expr.span, target);
350             }
351             if attr.check_name(sym::repr) {
352                 self.emit_repr_error(
353                     attr.span,
354                     expr.span,
355                     "attribute should not be applied to an expression",
356                     "not defining a struct, enum, or union",
357                 );
358             }
359         }
360     }
361
362     fn check_used(&self, item: &hir::Item, target: Target) {
363         for attr in &item.attrs {
364             if attr.check_name(sym::used) && target != Target::Static {
365                 self.tcx.sess
366                     .span_err(attr.span, "attribute must be applied to a `static` variable");
367             }
368         }
369     }
370 }
371
372 impl Visitor<'tcx> for CheckAttrVisitor<'tcx> {
373     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
374         NestedVisitorMap::OnlyBodies(&self.tcx.hir())
375     }
376
377     fn visit_item(&mut self, item: &'tcx hir::Item) {
378         let target = Target::from_item(item);
379         self.check_attributes(item, target);
380         intravisit::walk_item(self, item)
381     }
382
383
384     fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt) {
385         self.check_stmt_attributes(stmt);
386         intravisit::walk_stmt(self, stmt)
387     }
388
389     fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
390         self.check_expr_attributes(expr);
391         intravisit::walk_expr(self, expr)
392     }
393 }
394
395 fn is_c_like_enum(item: &hir::Item) -> bool {
396     if let hir::ItemKind::Enum(ref def, _) = item.kind {
397         for variant in &def.variants {
398             match variant.data {
399                 hir::VariantData::Unit(..) => { /* continue */ }
400                 _ => { return false; }
401             }
402         }
403         true
404     } else {
405         false
406     }
407 }
408
409 fn check_mod_attrs(tcx: TyCtxt<'_>, module_def_id: DefId) {
410     tcx.hir().visit_item_likes_in_module(
411         module_def_id,
412         &mut CheckAttrVisitor { tcx }.as_deep_visitor()
413     );
414 }
415
416 pub(crate) fn provide(providers: &mut Providers<'_>) {
417     *providers = Providers {
418         check_mod_attrs,
419         ..*providers
420     };
421 }