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