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