]> git.lizzy.rs Git - rust.git/blob - src/librustc/hir/check_attr.rs
Permit #[track_caller] on inherent methods
[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::{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;
14
15 use std::fmt::{self, Display};
16 use syntax::{attr, symbol::sym};
17 use syntax_pos::Span;
18
19 #[derive(Copy, Clone, PartialEq)]
20 pub(crate) enum MethodKind {
21     Trait { body: bool },
22     Inherent,
23 }
24
25 #[derive(Copy, Clone, PartialEq)]
26 pub(crate) enum Target {
27     ExternCrate,
28     Use,
29     Static,
30     Const,
31     Fn,
32     Closure,
33     Mod,
34     ForeignMod,
35     GlobalAsm,
36     TyAlias,
37     OpaqueTy,
38     Enum,
39     Struct,
40     Union,
41     Trait,
42     TraitAlias,
43     Impl,
44     Expression,
45     Statement,
46     AssocConst,
47     Method(MethodKind),
48     AssocTy,
49     ForeignFn,
50     ForeignStatic,
51     ForeignTy,
52 }
53
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",
58             Target::Use => "use",
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",
82         })
83     }
84 }
85
86 impl Target {
87     pub(crate) fn from_item(item: &Item) -> Target {
88         match item.kind {
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,
105         }
106     }
107
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 })
113             }
114             TraitItemKind::Method(_, hir::TraitMethod::Provided(_)) => {
115                 Target::Method(MethodKind::Trait { body: true })
116             }
117             TraitItemKind::Type(..) => Target::AssocTy,
118         }
119     }
120
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,
126         }
127     }
128
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"),
138                 };
139                 if containing_impl_is_for_trait {
140                     Target::Method(MethodKind::Trait { body: true })
141                 } else {
142                     Target::Method(MethodKind::Inherent)
143                 }
144             }
145             hir::ImplItemKind::TyAlias(..) => Target::TyAlias,
146             hir::ImplItemKind::OpaqueTy(..) => Target::OpaqueTy,
147         }
148     }
149 }
150
151 struct CheckAttrVisitor<'tcx> {
152     tcx: TyCtxt<'tcx>,
153 }
154
155 impl CheckAttrVisitor<'tcx> {
156     /// Checks any attribute.
157     fn check_attributes(
158         &self,
159         hir_id: HirId,
160         attrs: &HirVec<Attribute>,
161         span: &Span,
162         target: Target,
163         item: Option<&Item>,
164     ) {
165         let mut is_valid = true;
166         for attr in attrs {
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)
177             } else {
178                 true
179             };
180         }
181
182         if !is_valid {
183             return;
184         }
185
186         if target == Target::Fn {
187             self.tcx.codegen_fn_attrs(self.tcx.hir().local_def_id(hir_id));
188         }
189
190         self.check_repr(attrs, span, target, item);
191         self.check_used(attrs, target);
192     }
193
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 {
196         match target {
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(
201                     UNUSED_ATTRIBUTES,
202                     hir_id,
203                     attr.span,
204                     "`#[inline]` is ignored on function prototypes",
205                 ).emit();
206                 true
207             }
208             _ => {
209                 struct_span_err!(self.tcx.sess,
210                                  attr.span,
211                                  E0518,
212                                  "attribute should be applied to function or closure")
213                     .span_label(*span, "not a function or closure")
214                     .emit();
215                 false
216             }
217         }
218     }
219
220     /// Checks if a `#[track_caller]` is applied to a non-naked function. Returns `true` if valid.
221     fn check_track_caller(
222         &self,
223         attr_span: &Span,
224         attrs: &HirVec<Attribute>,
225         span: &Span,
226         target: Target,
227     ) -> bool {
228         match target {
229             Target::Fn if attr::contains_name(attrs, sym::naked) => {
230                 struct_span_err!(
231                     self.tcx.sess,
232                     *attr_span,
233                     E0736,
234                     "cannot use `#[track_caller]` with `#[naked]`",
235                 ).emit();
236                 false
237             }
238             Target::Fn | Target::Method(MethodKind::Inherent) => true,
239             Target::Method(_) => {
240                 struct_span_err!(
241                     self.tcx.sess,
242                     *attr_span,
243                     E0738,
244                     "`#[track_caller]` may not be used on trait methods",
245                 ).emit();
246                 false
247             }
248             _ => {
249                 struct_span_err!(
250                     self.tcx.sess,
251                     *attr_span,
252                     E0739,
253                     "attribute should be applied to function"
254                 )
255                 .span_label(*span, "not a function")
256                 .emit();
257                 false
258             }
259         }
260     }
261
262     /// Checks if the `#[non_exhaustive]` attribute on an `item` is valid. Returns `true` if valid.
263     fn check_non_exhaustive(
264         &self,
265         attr: &Attribute,
266         span: &Span,
267         target: Target,
268     ) -> bool {
269         match target {
270             Target::Struct | Target::Enum => true,
271             _ => {
272                 struct_span_err!(self.tcx.sess,
273                                  attr.span,
274                                  E0701,
275                                  "attribute can only be applied to a struct or enum")
276                     .span_label(*span, "not a struct or enum")
277                     .emit();
278                 false
279             }
280         }
281     }
282
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 {
285         match target {
286             Target::Trait => true,
287             _ => {
288                 self.tcx.sess
289                     .struct_span_err(attr.span, "attribute can only be applied to a trait")
290                     .span_label(*span, "not a trait")
291                     .emit();
292                 false
293             }
294         }
295     }
296
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 {
299         match target {
300             Target::Fn | Target::Method(MethodKind::Trait { body: true })
301             | Target::Method(MethodKind::Inherent) => true,
302             _ => {
303                 self.tcx.sess
304                     .struct_span_err(attr.span, "attribute should be applied to a function")
305                     .span_label(*span, "not a function")
306                     .emit();
307                 false
308             },
309         }
310     }
311
312     /// Checks if the `#[repr]` attributes on `item` are valid.
313     fn check_repr(
314         &self,
315         attrs: &HirVec<Attribute>,
316         span: &Span,
317         target: Target,
318         item: Option<&Item>,
319     ) {
320         // Extract the names of all repr hints, e.g., [foo, bar, align] for:
321         // ```
322         // #[repr(foo)]
323         // #[repr(bar, align(8))]
324         // ```
325         let hints: Vec<_> = attrs
326             .iter()
327             .filter(|attr| attr.check_name(sym::repr))
328             .filter_map(|attr| attr.meta_item_list())
329             .flatten()
330             .collect();
331
332         let mut int_reprs = 0;
333         let mut is_c = false;
334         let mut is_simd = false;
335         let mut is_transparent = false;
336
337         for hint in &hints {
338             let (article, allowed_targets) = match hint.name_or_empty() {
339                 name @ sym::C | name @ sym::align => {
340                     is_c |= name == sym::C;
341                     match target {
342                         Target::Struct | Target::Union | Target::Enum => continue,
343                         _ => ("a", "struct, enum, or union"),
344                     }
345                 }
346                 sym::packed => {
347                     if target != Target::Struct &&
348                             target != Target::Union {
349                                 ("a", "struct or union")
350                     } else {
351                         continue
352                     }
353                 }
354                 sym::simd => {
355                     is_simd = true;
356                     if target != Target::Struct {
357                         ("a", "struct")
358                     } else {
359                         continue
360                     }
361                 }
362                 sym::transparent => {
363                     is_transparent = true;
364                     match target {
365                         Target::Struct | Target::Union | Target::Enum => continue,
366                         _ => ("a", "struct, enum, or union"),
367                     }
368                 }
369                 sym::i8  | sym::u8  | sym::i16 | sym::u16 |
370                 sym::i32 | sym::u32 | sym::i64 | sym::u64 |
371                 sym::isize | sym::usize => {
372                     int_reprs += 1;
373                     if target != Target::Enum {
374                         ("an", "enum")
375                     } else {
376                         continue
377                     }
378                 }
379                 _ => continue,
380             };
381             self.emit_repr_error(
382                 hint.span(),
383                 *span,
384                 &format!("attribute should be applied to {}", allowed_targets),
385                 &format!("not {} {}", article, allowed_targets),
386             )
387         }
388
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());
392
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);
398         }
399         // Warn on repr(u8, u16), repr(C, simd), and c-like-enum-repr(C, u8)
400         if (int_reprs > 1)
401            || (is_simd && is_c)
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");
406         }
407     }
408
409     fn emit_repr_error(
410         &self,
411         hint_span: Span,
412         label_span: Span,
413         hint_message: &str,
414         label_message: &str,
415     ) {
416         struct_span_err!(self.tcx.sess, hint_span, E0517, "{}", hint_message)
417             .span_label(label_span, label_message)
418             .emit();
419     }
420
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);
427                 }
428                 if attr.check_name(sym::repr) {
429                     self.emit_repr_error(
430                         attr.span,
431                         stmt.span,
432                         "attribute should not be applied to a statement",
433                         "not a struct, enum, or union",
434                     );
435                 }
436             }
437         }
438     }
439
440     fn check_expr_attributes(&self, expr: &hir::Expr) {
441         let target = match expr.kind {
442             hir::ExprKind::Closure(..) => Target::Closure,
443             _ => Target::Expression,
444         };
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);
448             }
449             if attr.check_name(sym::repr) {
450                 self.emit_repr_error(
451                     attr.span,
452                     expr.span,
453                     "attribute should not be applied to an expression",
454                     "not defining a struct, enum, or union",
455                 );
456             }
457         }
458     }
459
460     fn check_used(&self, attrs: &HirVec<Attribute>, target: Target) {
461         for attr in attrs {
462             if attr.check_name(sym::used) && target != Target::Static {
463                 self.tcx.sess
464                     .span_err(attr.span, "attribute must be applied to a `static` variable");
465             }
466         }
467     }
468 }
469
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())
473     }
474
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)
479     }
480
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)
485     }
486
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)
491     }
492
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)
497     }
498
499     fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt) {
500         self.check_stmt_attributes(stmt);
501         intravisit::walk_stmt(self, stmt)
502     }
503
504     fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
505         self.check_expr_attributes(expr);
506         intravisit::walk_expr(self, expr)
507     }
508 }
509
510 fn is_c_like_enum(item: &Item) -> bool {
511     if let ItemKind::Enum(ref def, _) = item.kind {
512         for variant in &def.variants {
513             match variant.data {
514                 hir::VariantData::Unit(..) => { /* continue */ }
515                 _ => return false,
516             }
517         }
518         true
519     } else {
520         false
521     }
522 }
523
524 fn check_mod_attrs(tcx: TyCtxt<'_>, module_def_id: DefId) {
525     tcx.hir().visit_item_likes_in_module(
526         module_def_id,
527         &mut CheckAttrVisitor { tcx }.as_deep_visitor()
528     );
529 }
530
531 pub(crate) fn provide(providers: &mut Providers<'_>) {
532     *providers = Providers {
533         check_mod_attrs,
534         ..*providers
535     };
536 }