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