]> git.lizzy.rs Git - rust.git/blob - src/librustc/hir/check_attr.rs
Auto merge of #68530 - estebank:abolish-ice, 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::map::Map;
8 use crate::ty::query::Providers;
9 use crate::ty::TyCtxt;
10
11 use rustc_errors::struct_span_err;
12 use rustc_hir as hir;
13 use rustc_hir::def_id::DefId;
14 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
15 use rustc_hir::DUMMY_HIR_ID;
16 use rustc_hir::{self, HirId, Item, ItemKind, TraitItem, TraitItemKind};
17 use rustc_session::lint::builtin::UNUSED_ATTRIBUTES;
18 use rustc_span::symbol::sym;
19 use rustc_span::Span;
20 use syntax::ast::Attribute;
21 use syntax::attr;
22
23 use std::fmt::{self, Display};
24
25 #[derive(Copy, Clone, PartialEq)]
26 pub(crate) enum MethodKind {
27     Trait { body: bool },
28     Inherent,
29 }
30
31 #[derive(Copy, Clone, PartialEq)]
32 pub(crate) enum Target {
33     ExternCrate,
34     Use,
35     Static,
36     Const,
37     Fn,
38     Closure,
39     Mod,
40     ForeignMod,
41     GlobalAsm,
42     TyAlias,
43     OpaqueTy,
44     Enum,
45     Struct,
46     Union,
47     Trait,
48     TraitAlias,
49     Impl,
50     Expression,
51     Statement,
52     AssocConst,
53     Method(MethodKind),
54     AssocTy,
55     ForeignFn,
56     ForeignStatic,
57     ForeignTy,
58 }
59
60 impl Display for Target {
61     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62         write!(
63             f,
64             "{}",
65             match *self {
66                 Target::ExternCrate => "extern crate",
67                 Target::Use => "use",
68                 Target::Static => "static item",
69                 Target::Const => "constant item",
70                 Target::Fn => "function",
71                 Target::Closure => "closure",
72                 Target::Mod => "module",
73                 Target::ForeignMod => "foreign module",
74                 Target::GlobalAsm => "global asm",
75                 Target::TyAlias => "type alias",
76                 Target::OpaqueTy => "opaque type",
77                 Target::Enum => "enum",
78                 Target::Struct => "struct",
79                 Target::Union => "union",
80                 Target::Trait => "trait",
81                 Target::TraitAlias => "trait alias",
82                 Target::Impl => "item",
83                 Target::Expression => "expression",
84                 Target::Statement => "statement",
85                 Target::AssocConst => "associated const",
86                 Target::Method(_) => "method",
87                 Target::AssocTy => "associated type",
88                 Target::ForeignFn => "foreign function",
89                 Target::ForeignStatic => "foreign static item",
90                 Target::ForeignTy => "foreign type",
91             }
92         )
93     }
94 }
95
96 impl Target {
97     pub(crate) fn from_item(item: &Item<'_>) -> Target {
98         match item.kind {
99             ItemKind::ExternCrate(..) => Target::ExternCrate,
100             ItemKind::Use(..) => Target::Use,
101             ItemKind::Static(..) => Target::Static,
102             ItemKind::Const(..) => Target::Const,
103             ItemKind::Fn(..) => Target::Fn,
104             ItemKind::Mod(..) => Target::Mod,
105             ItemKind::ForeignMod(..) => Target::ForeignMod,
106             ItemKind::GlobalAsm(..) => Target::GlobalAsm,
107             ItemKind::TyAlias(..) => Target::TyAlias,
108             ItemKind::OpaqueTy(..) => Target::OpaqueTy,
109             ItemKind::Enum(..) => Target::Enum,
110             ItemKind::Struct(..) => Target::Struct,
111             ItemKind::Union(..) => Target::Union,
112             ItemKind::Trait(..) => Target::Trait,
113             ItemKind::TraitAlias(..) => Target::TraitAlias,
114             ItemKind::Impl { .. } => Target::Impl,
115         }
116     }
117
118     fn from_trait_item(trait_item: &TraitItem<'_>) -> Target {
119         match trait_item.kind {
120             TraitItemKind::Const(..) => Target::AssocConst,
121             TraitItemKind::Method(_, hir::TraitMethod::Required(_)) => {
122                 Target::Method(MethodKind::Trait { body: false })
123             }
124             TraitItemKind::Method(_, hir::TraitMethod::Provided(_)) => {
125                 Target::Method(MethodKind::Trait { body: true })
126             }
127             TraitItemKind::Type(..) => Target::AssocTy,
128         }
129     }
130
131     fn from_foreign_item(foreign_item: &hir::ForeignItem<'_>) -> Target {
132         match foreign_item.kind {
133             hir::ForeignItemKind::Fn(..) => Target::ForeignFn,
134             hir::ForeignItemKind::Static(..) => Target::ForeignStatic,
135             hir::ForeignItemKind::Type => Target::ForeignTy,
136         }
137     }
138
139     fn from_impl_item<'tcx>(tcx: TyCtxt<'tcx>, impl_item: &hir::ImplItem<'_>) -> Target {
140         match impl_item.kind {
141             hir::ImplItemKind::Const(..) => Target::AssocConst,
142             hir::ImplItemKind::Method(..) => {
143                 let parent_hir_id = tcx.hir().get_parent_item(impl_item.hir_id);
144                 let containing_item = tcx.hir().expect_item(parent_hir_id);
145                 let containing_impl_is_for_trait = match &containing_item.kind {
146                     hir::ItemKind::Impl { ref of_trait, .. } => of_trait.is_some(),
147                     _ => bug!("parent of an ImplItem must be an Impl"),
148                 };
149                 if containing_impl_is_for_trait {
150                     Target::Method(MethodKind::Trait { body: true })
151                 } else {
152                     Target::Method(MethodKind::Inherent)
153                 }
154             }
155             hir::ImplItemKind::TyAlias(..) | hir::ImplItemKind::OpaqueTy(..) => Target::AssocTy,
156         }
157     }
158 }
159
160 struct CheckAttrVisitor<'tcx> {
161     tcx: TyCtxt<'tcx>,
162 }
163
164 impl CheckAttrVisitor<'tcx> {
165     /// Checks any attribute.
166     fn check_attributes(
167         &self,
168         hir_id: HirId,
169         attrs: &'hir [Attribute],
170         span: &Span,
171         target: Target,
172         item: Option<&Item<'_>>,
173     ) {
174         let mut is_valid = true;
175         for attr in attrs {
176             is_valid &= if attr.check_name(sym::inline) {
177                 self.check_inline(hir_id, attr, span, target)
178             } else if attr.check_name(sym::non_exhaustive) {
179                 self.check_non_exhaustive(attr, span, target)
180             } else if attr.check_name(sym::marker) {
181                 self.check_marker(attr, span, target)
182             } else if attr.check_name(sym::target_feature) {
183                 self.check_target_feature(attr, span, target)
184             } else if attr.check_name(sym::track_caller) {
185                 self.check_track_caller(&attr.span, attrs, span, target)
186             } else {
187                 true
188             };
189         }
190
191         if !is_valid {
192             return;
193         }
194
195         if target == Target::Fn {
196             self.tcx.codegen_fn_attrs(self.tcx.hir().local_def_id(hir_id));
197         }
198
199         self.check_repr(attrs, span, target, item);
200         self.check_used(attrs, target);
201     }
202
203     /// Checks if an `#[inline]` is applied to a function or a closure. Returns `true` if valid.
204     fn check_inline(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) -> bool {
205         match target {
206             Target::Fn
207             | Target::Closure
208             | Target::Method(MethodKind::Trait { body: true })
209             | Target::Method(MethodKind::Inherent) => true,
210             Target::Method(MethodKind::Trait { body: false }) | Target::ForeignFn => {
211                 self.tcx
212                     .struct_span_lint_hir(
213                         UNUSED_ATTRIBUTES,
214                         hir_id,
215                         attr.span,
216                         "`#[inline]` is ignored on function prototypes",
217                     )
218                     .emit();
219                 true
220             }
221             // FIXME(#65833): We permit associated consts to have an `#[inline]` attribute with
222             // just a lint, because we previously erroneously allowed it and some crates used it
223             // accidentally, to to be compatible with crates depending on them, we can't throw an
224             // error here.
225             Target::AssocConst => {
226                 self.tcx
227                     .struct_span_lint_hir(
228                         UNUSED_ATTRIBUTES,
229                         hir_id,
230                         attr.span,
231                         "`#[inline]` is ignored on constants",
232                     )
233                     .warn(
234                         "this was previously accepted by the compiler but is \
235                        being phased out; it will become a hard error in \
236                        a future release!",
237                     )
238                     .note(
239                         "for more information, see issue #65833 \
240                        <https://github.com/rust-lang/rust/issues/65833>",
241                     )
242                     .emit();
243                 true
244             }
245             _ => {
246                 struct_span_err!(
247                     self.tcx.sess,
248                     attr.span,
249                     E0518,
250                     "attribute should be applied to function or closure",
251                 )
252                 .span_label(*span, "not a function or closure")
253                 .emit();
254                 false
255             }
256         }
257     }
258
259     /// Checks if a `#[track_caller]` is applied to a non-naked function. Returns `true` if valid.
260     fn check_track_caller(
261         &self,
262         attr_span: &Span,
263         attrs: &'hir [Attribute],
264         span: &Span,
265         target: Target,
266     ) -> bool {
267         match target {
268             Target::Fn if attr::contains_name(attrs, sym::naked) => {
269                 struct_span_err!(
270                     self.tcx.sess,
271                     *attr_span,
272                     E0736,
273                     "cannot use `#[track_caller]` with `#[naked]`",
274                 )
275                 .emit();
276                 false
277             }
278             Target::Fn | Target::Method(MethodKind::Inherent) => true,
279             Target::Method(_) => {
280                 struct_span_err!(
281                     self.tcx.sess,
282                     *attr_span,
283                     E0738,
284                     "`#[track_caller]` may not be used on trait methods",
285                 )
286                 .emit();
287                 false
288             }
289             _ => {
290                 struct_span_err!(
291                     self.tcx.sess,
292                     *attr_span,
293                     E0739,
294                     "attribute should be applied to function"
295                 )
296                 .span_label(*span, "not a function")
297                 .emit();
298                 false
299             }
300         }
301     }
302
303     /// Checks if the `#[non_exhaustive]` attribute on an `item` is valid. Returns `true` if valid.
304     fn check_non_exhaustive(&self, attr: &Attribute, span: &Span, target: Target) -> bool {
305         match target {
306             Target::Struct | Target::Enum => true,
307             _ => {
308                 struct_span_err!(
309                     self.tcx.sess,
310                     attr.span,
311                     E0701,
312                     "attribute can only be applied to a struct or enum"
313                 )
314                 .span_label(*span, "not a struct or enum")
315                 .emit();
316                 false
317             }
318         }
319     }
320
321     /// Checks if the `#[marker]` attribute on an `item` is valid. Returns `true` if valid.
322     fn check_marker(&self, attr: &Attribute, span: &Span, target: Target) -> bool {
323         match target {
324             Target::Trait => true,
325             _ => {
326                 self.tcx
327                     .sess
328                     .struct_span_err(attr.span, "attribute can only be applied to a trait")
329                     .span_label(*span, "not a trait")
330                     .emit();
331                 false
332             }
333         }
334     }
335
336     /// Checks if the `#[target_feature]` attribute on `item` is valid. Returns `true` if valid.
337     fn check_target_feature(&self, attr: &Attribute, span: &Span, target: Target) -> bool {
338         match target {
339             Target::Fn
340             | Target::Method(MethodKind::Trait { body: true })
341             | Target::Method(MethodKind::Inherent) => true,
342             _ => {
343                 self.tcx
344                     .sess
345                     .struct_span_err(attr.span, "attribute should be applied to a function")
346                     .span_label(*span, "not a function")
347                     .emit();
348                 false
349             }
350         }
351     }
352
353     /// Checks if the `#[repr]` attributes on `item` are valid.
354     fn check_repr(
355         &self,
356         attrs: &'hir [Attribute],
357         span: &Span,
358         target: Target,
359         item: Option<&Item<'_>>,
360     ) {
361         // Extract the names of all repr hints, e.g., [foo, bar, align] for:
362         // ```
363         // #[repr(foo)]
364         // #[repr(bar, align(8))]
365         // ```
366         let hints: Vec<_> = attrs
367             .iter()
368             .filter(|attr| attr.check_name(sym::repr))
369             .filter_map(|attr| attr.meta_item_list())
370             .flatten()
371             .collect();
372
373         let mut int_reprs = 0;
374         let mut is_c = false;
375         let mut is_simd = false;
376         let mut is_transparent = false;
377
378         for hint in &hints {
379             let (article, allowed_targets) = match hint.name_or_empty() {
380                 name @ sym::C | name @ sym::align => {
381                     is_c |= name == sym::C;
382                     match target {
383                         Target::Struct | Target::Union | Target::Enum => continue,
384                         _ => ("a", "struct, enum, or union"),
385                     }
386                 }
387                 sym::packed => {
388                     if target != Target::Struct && target != Target::Union {
389                         ("a", "struct or union")
390                     } else {
391                         continue;
392                     }
393                 }
394                 sym::simd => {
395                     is_simd = true;
396                     if target != Target::Struct { ("a", "struct") } else { continue }
397                 }
398                 sym::transparent => {
399                     is_transparent = true;
400                     match target {
401                         Target::Struct | Target::Union | Target::Enum => continue,
402                         _ => ("a", "struct, enum, or union"),
403                     }
404                 }
405                 sym::i8
406                 | sym::u8
407                 | sym::i16
408                 | sym::u16
409                 | sym::i32
410                 | sym::u32
411                 | sym::i64
412                 | sym::u64
413                 | sym::isize
414                 | sym::usize => {
415                     int_reprs += 1;
416                     if target != Target::Enum { ("an", "enum") } else { continue }
417                 }
418                 _ => continue,
419             };
420             self.emit_repr_error(
421                 hint.span(),
422                 *span,
423                 &format!("attribute should be applied to {}", allowed_targets),
424                 &format!("not {} {}", article, allowed_targets),
425             )
426         }
427
428         // Just point at all repr hints if there are any incompatibilities.
429         // This is not ideal, but tracking precisely which ones are at fault is a huge hassle.
430         let hint_spans = hints.iter().map(|hint| hint.span());
431
432         // Error on repr(transparent, <anything else>).
433         if is_transparent && hints.len() > 1 {
434             let hint_spans: Vec<_> = hint_spans.clone().collect();
435             struct_span_err!(
436                 self.tcx.sess,
437                 hint_spans,
438                 E0692,
439                 "transparent {} cannot have other repr hints",
440                 target
441             )
442             .emit();
443         }
444         // Warn on repr(u8, u16), repr(C, simd), and c-like-enum-repr(C, u8)
445         if (int_reprs > 1)
446             || (is_simd && is_c)
447             || (int_reprs == 1 && is_c && item.map_or(false, |item| is_c_like_enum(item)))
448         {
449             struct_span_err!(
450                 self.tcx.sess,
451                 hint_spans.collect::<Vec<Span>>(),
452                 E0566,
453                 "conflicting representation hints",
454             )
455             .emit();
456         }
457     }
458
459     fn emit_repr_error(
460         &self,
461         hint_span: Span,
462         label_span: Span,
463         hint_message: &str,
464         label_message: &str,
465     ) {
466         struct_span_err!(self.tcx.sess, hint_span, E0517, "{}", hint_message)
467             .span_label(label_span, label_message)
468             .emit();
469     }
470
471     fn check_stmt_attributes(&self, stmt: &hir::Stmt<'_>) {
472         // When checking statements ignore expressions, they will be checked later
473         if let hir::StmtKind::Local(ref l) = stmt.kind {
474             for attr in l.attrs.iter() {
475                 if attr.check_name(sym::inline) {
476                     self.check_inline(DUMMY_HIR_ID, attr, &stmt.span, Target::Statement);
477                 }
478                 if attr.check_name(sym::repr) {
479                     self.emit_repr_error(
480                         attr.span,
481                         stmt.span,
482                         "attribute should not be applied to a statement",
483                         "not a struct, enum, or union",
484                     );
485                 }
486             }
487         }
488     }
489
490     fn check_expr_attributes(&self, expr: &hir::Expr<'_>) {
491         let target = match expr.kind {
492             hir::ExprKind::Closure(..) => Target::Closure,
493             _ => Target::Expression,
494         };
495         for attr in expr.attrs.iter() {
496             if attr.check_name(sym::inline) {
497                 self.check_inline(DUMMY_HIR_ID, attr, &expr.span, target);
498             }
499             if attr.check_name(sym::repr) {
500                 self.emit_repr_error(
501                     attr.span,
502                     expr.span,
503                     "attribute should not be applied to an expression",
504                     "not defining a struct, enum, or union",
505                 );
506             }
507         }
508     }
509
510     fn check_used(&self, attrs: &'hir [Attribute], target: Target) {
511         for attr in attrs {
512             if attr.check_name(sym::used) && target != Target::Static {
513                 self.tcx
514                     .sess
515                     .span_err(attr.span, "attribute must be applied to a `static` variable");
516             }
517         }
518     }
519 }
520
521 impl Visitor<'tcx> for CheckAttrVisitor<'tcx> {
522     type Map = Map<'tcx>;
523
524     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, Self::Map> {
525         NestedVisitorMap::OnlyBodies(&self.tcx.hir())
526     }
527
528     fn visit_item(&mut self, item: &'tcx Item<'tcx>) {
529         let target = Target::from_item(item);
530         self.check_attributes(item.hir_id, item.attrs, &item.span, target, Some(item));
531         intravisit::walk_item(self, item)
532     }
533
534     fn visit_trait_item(&mut self, trait_item: &'tcx TraitItem<'tcx>) {
535         let target = Target::from_trait_item(trait_item);
536         self.check_attributes(trait_item.hir_id, &trait_item.attrs, &trait_item.span, target, None);
537         intravisit::walk_trait_item(self, trait_item)
538     }
539
540     fn visit_foreign_item(&mut self, f_item: &'tcx hir::ForeignItem<'tcx>) {
541         let target = Target::from_foreign_item(f_item);
542         self.check_attributes(f_item.hir_id, &f_item.attrs, &f_item.span, target, None);
543         intravisit::walk_foreign_item(self, f_item)
544     }
545
546     fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
547         let target = Target::from_impl_item(self.tcx, impl_item);
548         self.check_attributes(impl_item.hir_id, &impl_item.attrs, &impl_item.span, target, None);
549         intravisit::walk_impl_item(self, impl_item)
550     }
551
552     fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt<'tcx>) {
553         self.check_stmt_attributes(stmt);
554         intravisit::walk_stmt(self, stmt)
555     }
556
557     fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
558         self.check_expr_attributes(expr);
559         intravisit::walk_expr(self, expr)
560     }
561 }
562
563 fn is_c_like_enum(item: &Item<'_>) -> bool {
564     if let ItemKind::Enum(ref def, _) = item.kind {
565         for variant in def.variants {
566             match variant.data {
567                 hir::VariantData::Unit(..) => { /* continue */ }
568                 _ => return false,
569             }
570         }
571         true
572     } else {
573         false
574     }
575 }
576
577 fn check_mod_attrs(tcx: TyCtxt<'_>, module_def_id: DefId) {
578     tcx.hir()
579         .visit_item_likes_in_module(module_def_id, &mut CheckAttrVisitor { tcx }.as_deep_visitor());
580 }
581
582 pub(crate) fn provide(providers: &mut Providers<'_>) {
583     *providers = Providers { check_mod_attrs, ..*providers };
584 }