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