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