]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_passes/src/check_attr.rs
Auto merge of #77954 - JohnTitor:rollup-bpoy497, r=JohnTitor
[rust.git] / compiler / rustc_passes / src / 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, LitKind, NestedMetaItem};
12 use rustc_errors::{pluralize, 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::{
17     self, FnSig, ForeignItem, ForeignItemKind, HirId, Item, ItemKind, TraitItem, CRATE_HIR_ID,
18 };
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, Symbol};
23 use rustc_span::{Span, DUMMY_SP};
24
25 pub(crate) fn target_from_impl_item<'tcx>(
26     tcx: TyCtxt<'tcx>,
27     impl_item: &hir::ImplItem<'_>,
28 ) -> Target {
29     match impl_item.kind {
30         hir::ImplItemKind::Const(..) => Target::AssocConst,
31         hir::ImplItemKind::Fn(..) => {
32             let parent_hir_id = tcx.hir().get_parent_item(impl_item.hir_id);
33             let containing_item = tcx.hir().expect_item(parent_hir_id);
34             let containing_impl_is_for_trait = match &containing_item.kind {
35                 hir::ItemKind::Impl { ref of_trait, .. } => of_trait.is_some(),
36                 _ => bug!("parent of an ImplItem must be an Impl"),
37             };
38             if containing_impl_is_for_trait {
39                 Target::Method(MethodKind::Trait { body: true })
40             } else {
41                 Target::Method(MethodKind::Inherent)
42             }
43         }
44         hir::ImplItemKind::TyAlias(..) => Target::AssocTy,
45     }
46 }
47
48 #[derive(Clone, Copy)]
49 enum ItemLike<'tcx> {
50     Item(&'tcx Item<'tcx>),
51     ForeignItem(&'tcx ForeignItem<'tcx>),
52 }
53
54 struct CheckAttrVisitor<'tcx> {
55     tcx: TyCtxt<'tcx>,
56 }
57
58 impl CheckAttrVisitor<'tcx> {
59     /// Checks any attribute.
60     fn check_attributes(
61         &self,
62         hir_id: HirId,
63         attrs: &'hir [Attribute],
64         span: &Span,
65         target: Target,
66         item: Option<ItemLike<'_>>,
67     ) {
68         let mut is_valid = true;
69         for attr in attrs {
70             is_valid &= if self.tcx.sess.check_name(attr, sym::inline) {
71                 self.check_inline(hir_id, attr, span, target)
72             } else if self.tcx.sess.check_name(attr, sym::non_exhaustive) {
73                 self.check_non_exhaustive(attr, span, target)
74             } else if self.tcx.sess.check_name(attr, sym::marker) {
75                 self.check_marker(attr, span, target)
76             } else if self.tcx.sess.check_name(attr, sym::target_feature) {
77                 self.check_target_feature(hir_id, attr, span, target)
78             } else if self.tcx.sess.check_name(attr, sym::track_caller) {
79                 self.check_track_caller(&attr.span, attrs, span, target)
80             } else if self.tcx.sess.check_name(attr, sym::doc) {
81                 self.check_doc_alias(attr, hir_id, target)
82             } else if self.tcx.sess.check_name(attr, sym::no_link) {
83                 self.check_no_link(&attr, span, target)
84             } else if self.tcx.sess.check_name(attr, sym::export_name) {
85                 self.check_export_name(&attr, span, target)
86             } else if self.tcx.sess.check_name(attr, sym::rustc_args_required_const) {
87                 self.check_rustc_args_required_const(&attr, span, target, item)
88             } else {
89                 // lint-only checks
90                 if self.tcx.sess.check_name(attr, sym::cold) {
91                     self.check_cold(hir_id, attr, span, target);
92                 } else if self.tcx.sess.check_name(attr, sym::link_name) {
93                     self.check_link_name(hir_id, attr, span, target);
94                 } else if self.tcx.sess.check_name(attr, sym::link_section) {
95                     self.check_link_section(hir_id, attr, span, target);
96                 } else if self.tcx.sess.check_name(attr, sym::no_mangle) {
97                     self.check_no_mangle(hir_id, attr, span, target);
98                 }
99                 true
100             };
101         }
102
103         if !is_valid {
104             return;
105         }
106
107         if matches!(target, Target::Fn | Target::Method(_) | Target::ForeignFn) {
108             self.tcx.ensure().codegen_fn_attrs(self.tcx.hir().local_def_id(hir_id));
109         }
110
111         self.check_repr(attrs, span, target, item, hir_id);
112         self.check_used(attrs, target);
113     }
114
115     /// Checks if an `#[inline]` is applied to a function or a closure. Returns `true` if valid.
116     fn check_inline(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) -> bool {
117         match target {
118             Target::Fn
119             | Target::Closure
120             | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true,
121             Target::Method(MethodKind::Trait { body: false }) | Target::ForeignFn => {
122                 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
123                     lint.build("`#[inline]` is ignored on function prototypes").emit()
124                 });
125                 true
126             }
127             // FIXME(#65833): We permit associated consts to have an `#[inline]` attribute with
128             // just a lint, because we previously erroneously allowed it and some crates used it
129             // accidentally, to to be compatible with crates depending on them, we can't throw an
130             // error here.
131             Target::AssocConst => {
132                 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
133                     lint.build("`#[inline]` is ignored on constants")
134                         .warn(
135                             "this was previously accepted by the compiler but is \
136                              being phased out; it will become a hard error in \
137                              a future release!",
138                         )
139                         .note(
140                             "see issue #65833 <https://github.com/rust-lang/rust/issues/65833> \
141                              for more information",
142                         )
143                         .emit();
144                 });
145                 true
146             }
147             _ => {
148                 struct_span_err!(
149                     self.tcx.sess,
150                     attr.span,
151                     E0518,
152                     "attribute should be applied to function or closure",
153                 )
154                 .span_label(*span, "not a function or closure")
155                 .emit();
156                 false
157             }
158         }
159     }
160
161     /// Checks if a `#[track_caller]` is applied to a non-naked function. Returns `true` if valid.
162     fn check_track_caller(
163         &self,
164         attr_span: &Span,
165         attrs: &'hir [Attribute],
166         span: &Span,
167         target: Target,
168     ) -> bool {
169         match target {
170             _ if self.tcx.sess.contains_name(attrs, sym::naked) => {
171                 struct_span_err!(
172                     self.tcx.sess,
173                     *attr_span,
174                     E0736,
175                     "cannot use `#[track_caller]` with `#[naked]`",
176                 )
177                 .emit();
178                 false
179             }
180             Target::Fn | Target::Method(..) | Target::ForeignFn | Target::Closure => true,
181             _ => {
182                 struct_span_err!(
183                     self.tcx.sess,
184                     *attr_span,
185                     E0739,
186                     "attribute should be applied to function"
187                 )
188                 .span_label(*span, "not a function")
189                 .emit();
190                 false
191             }
192         }
193     }
194
195     /// Checks if the `#[non_exhaustive]` attribute on an `item` is valid. Returns `true` if valid.
196     fn check_non_exhaustive(&self, attr: &Attribute, span: &Span, target: Target) -> bool {
197         match target {
198             Target::Struct | Target::Enum => true,
199             _ => {
200                 struct_span_err!(
201                     self.tcx.sess,
202                     attr.span,
203                     E0701,
204                     "attribute can only be applied to a struct or enum"
205                 )
206                 .span_label(*span, "not a struct or enum")
207                 .emit();
208                 false
209             }
210         }
211     }
212
213     /// Checks if the `#[marker]` attribute on an `item` is valid. Returns `true` if valid.
214     fn check_marker(&self, attr: &Attribute, span: &Span, target: Target) -> bool {
215         match target {
216             Target::Trait => true,
217             _ => {
218                 self.tcx
219                     .sess
220                     .struct_span_err(attr.span, "attribute can only be applied to a trait")
221                     .span_label(*span, "not a trait")
222                     .emit();
223                 false
224             }
225         }
226     }
227
228     /// Checks if the `#[target_feature]` attribute on `item` is valid. Returns `true` if valid.
229     fn check_target_feature(
230         &self,
231         hir_id: HirId,
232         attr: &Attribute,
233         span: &Span,
234         target: Target,
235     ) -> bool {
236         match target {
237             Target::Fn
238             | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true,
239             // FIXME: #[target_feature] was previously erroneously allowed on statements and some
240             // crates used this, so only emit a warning.
241             Target::Statement => {
242                 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
243                     lint.build("attribute should be applied to a function")
244                         .warn(
245                             "this was previously accepted by the compiler but is \
246                              being phased out; it will become a hard error in \
247                              a future release!",
248                         )
249                         .span_label(*span, "not a function")
250                         .emit();
251                 });
252                 true
253             }
254             _ => {
255                 self.tcx
256                     .sess
257                     .struct_span_err(attr.span, "attribute should be applied to a function")
258                     .span_label(*span, "not a function")
259                     .emit();
260                 false
261             }
262         }
263     }
264
265     fn doc_alias_str_error(&self, meta: &NestedMetaItem) {
266         self.tcx
267             .sess
268             .struct_span_err(
269                 meta.span(),
270                 "doc alias attribute expects a string: #[doc(alias = \"0\")]",
271             )
272             .emit();
273     }
274
275     fn check_doc_alias(&self, attr: &Attribute, hir_id: HirId, target: Target) -> bool {
276         if let Some(mi) = attr.meta() {
277             if let Some(list) = mi.meta_item_list() {
278                 for meta in list {
279                     if meta.has_name(sym::alias) {
280                         if !meta.is_value_str() {
281                             self.doc_alias_str_error(meta);
282                             return false;
283                         }
284                         let doc_alias =
285                             meta.value_str().map(|s| s.to_string()).unwrap_or_else(String::new);
286                         if doc_alias.is_empty() {
287                             self.doc_alias_str_error(meta);
288                             return false;
289                         }
290                         if let Some(c) = doc_alias
291                             .chars()
292                             .find(|&c| c == '"' || c == '\'' || (c.is_whitespace() && c != ' '))
293                         {
294                             self.tcx
295                                 .sess
296                                 .struct_span_err(
297                                     meta.span(),
298                                     &format!(
299                                         "{:?} character isn't allowed in `#[doc(alias = \"...\")]`",
300                                         c,
301                                     ),
302                                 )
303                                 .emit();
304                             return false;
305                         }
306                         if doc_alias.starts_with(' ') || doc_alias.ends_with(' ') {
307                             self.tcx
308                                 .sess
309                                 .struct_span_err(
310                                     meta.span(),
311                                     "`#[doc(alias = \"...\")]` cannot start or end with ' '",
312                                 )
313                                 .emit();
314                             return false;
315                         }
316                         if let Some(err) = match target {
317                             Target::Impl => Some("implementation block"),
318                             Target::ForeignMod => Some("extern block"),
319                             Target::AssocTy => {
320                                 let parent_hir_id = self.tcx.hir().get_parent_item(hir_id);
321                                 let containing_item = self.tcx.hir().expect_item(parent_hir_id);
322                                 if Target::from_item(containing_item) == Target::Impl {
323                                     Some("type alias in implementation block")
324                                 } else {
325                                     None
326                                 }
327                             }
328                             Target::AssocConst => {
329                                 let parent_hir_id = self.tcx.hir().get_parent_item(hir_id);
330                                 let containing_item = self.tcx.hir().expect_item(parent_hir_id);
331                                 // We can't link to trait impl's consts.
332                                 let err = "associated constant in trait implementation block";
333                                 match containing_item.kind {
334                                     ItemKind::Impl { of_trait: Some(_), .. } => Some(err),
335                                     _ => None,
336                                 }
337                             }
338                             _ => None,
339                         } {
340                             self.tcx
341                                 .sess
342                                 .struct_span_err(
343                                     meta.span(),
344                                     &format!("`#[doc(alias = \"...\")]` isn't allowed on {}", err),
345                                 )
346                                 .emit();
347                             return false;
348                         }
349                         if CRATE_HIR_ID == hir_id {
350                             self.tcx
351                                 .sess
352                                 .struct_span_err(
353                                     meta.span(),
354                                     "`#![doc(alias = \"...\")]` isn't allowed as a crate \
355                                      level attribute",
356                                 )
357                                 .emit();
358                             return false;
359                         }
360                     }
361                 }
362             }
363         }
364         true
365     }
366
367     /// Checks if `#[cold]` is applied to a non-function. Returns `true` if valid.
368     fn check_cold(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) {
369         match target {
370             Target::Fn | Target::Method(..) | Target::ForeignFn | Target::Closure => {}
371             _ => {
372                 // FIXME: #[cold] was previously allowed on non-functions and some crates used
373                 // this, so only emit a warning.
374                 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
375                     lint.build("attribute should be applied to a function")
376                         .warn(
377                             "this was previously accepted by the compiler but is \
378                              being phased out; it will become a hard error in \
379                              a future release!",
380                         )
381                         .span_label(*span, "not a function")
382                         .emit();
383                 });
384             }
385         }
386     }
387
388     /// Checks if `#[link_name]` is applied to an item other than a foreign function or static.
389     fn check_link_name(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) {
390         match target {
391             Target::ForeignFn | Target::ForeignStatic => {}
392             _ => {
393                 // FIXME: #[cold] was previously allowed on non-functions/statics and some crates
394                 // used this, so only emit a warning.
395                 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
396                     let mut diag =
397                         lint.build("attribute should be applied to a foreign function or static");
398                     diag.warn(
399                         "this was previously accepted by the compiler but is \
400                          being phased out; it will become a hard error in \
401                          a future release!",
402                     );
403
404                     // See issue #47725
405                     if let Target::ForeignMod = target {
406                         if let Some(value) = attr.value_str() {
407                             diag.span_help(
408                                 attr.span,
409                                 &format!(r#"try `#[link(name = "{}")]` instead"#, value),
410                             );
411                         } else {
412                             diag.span_help(attr.span, r#"try `#[link(name = "...")]` instead"#);
413                         }
414                     }
415
416                     diag.span_label(*span, "not a foreign function or static");
417                     diag.emit();
418                 });
419             }
420         }
421     }
422
423     /// Checks if `#[no_link]` is applied to an `extern crate`. Returns `true` if valid.
424     fn check_no_link(&self, attr: &Attribute, span: &Span, target: Target) -> bool {
425         if target == Target::ExternCrate {
426             true
427         } else {
428             self.tcx
429                 .sess
430                 .struct_span_err(attr.span, "attribute should be applied to an `extern crate` item")
431                 .span_label(*span, "not an `extern crate` item")
432                 .emit();
433             false
434         }
435     }
436
437     /// Checks if `#[export_name]` is applied to a function or static. Returns `true` if valid.
438     fn check_export_name(&self, attr: &Attribute, span: &Span, target: Target) -> bool {
439         match target {
440             Target::Static | Target::Fn | Target::Method(..) => true,
441             _ => {
442                 self.tcx
443                     .sess
444                     .struct_span_err(
445                         attr.span,
446                         "attribute should be applied to a function or static",
447                     )
448                     .span_label(*span, "not a function or static")
449                     .emit();
450                 false
451             }
452         }
453     }
454
455     /// Checks if `#[rustc_args_required_const]` is applied to a function and has a valid argument.
456     fn check_rustc_args_required_const(
457         &self,
458         attr: &Attribute,
459         span: &Span,
460         target: Target,
461         item: Option<ItemLike<'_>>,
462     ) -> bool {
463         if let Target::Fn | Target::Method(..) | Target::ForeignFn = target {
464             let mut invalid_args = vec![];
465             for meta in attr.meta_item_list().expect("no meta item list") {
466                 if let Some(LitKind::Int(val, _)) = meta.literal().map(|lit| &lit.kind) {
467                     if let Some(ItemLike::Item(Item {
468                         kind: ItemKind::Fn(FnSig { decl, .. }, ..),
469                         ..
470                     }))
471                     | Some(ItemLike::ForeignItem(ForeignItem {
472                         kind: ForeignItemKind::Fn(decl, ..),
473                         ..
474                     })) = item
475                     {
476                         let arg_count = decl.inputs.len() as u128;
477                         if *val >= arg_count {
478                             let span = meta.span();
479                             self.tcx
480                                 .sess
481                                 .struct_span_err(span, "index exceeds number of arguments")
482                                 .span_label(
483                                     span,
484                                     format!(
485                                         "there {} only {} argument{}",
486                                         if arg_count != 1 { "are" } else { "is" },
487                                         arg_count,
488                                         pluralize!(arg_count)
489                                     ),
490                                 )
491                                 .emit();
492                             return false;
493                         }
494                     } else {
495                         bug!("should be a function item");
496                     }
497                 } else {
498                     invalid_args.push(meta.span());
499                 }
500             }
501             if !invalid_args.is_empty() {
502                 self.tcx
503                     .sess
504                     .struct_span_err(invalid_args, "arguments should be non-negative integers")
505                     .emit();
506                 false
507             } else {
508                 true
509             }
510         } else {
511             self.tcx
512                 .sess
513                 .struct_span_err(attr.span, "attribute should be applied to a function")
514                 .span_label(*span, "not a function")
515                 .emit();
516             false
517         }
518     }
519
520     /// Checks if `#[link_section]` is applied to a function or static.
521     fn check_link_section(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) {
522         match target {
523             Target::Static | Target::Fn | Target::Method(..) => {}
524             _ => {
525                 // FIXME: #[link_section] was previously allowed on non-functions/statics and some
526                 // crates used this, so only emit a warning.
527                 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
528                     lint.build("attribute should be applied to a function or static")
529                         .warn(
530                             "this was previously accepted by the compiler but is \
531                              being phased out; it will become a hard error in \
532                              a future release!",
533                         )
534                         .span_label(*span, "not a function or static")
535                         .emit();
536                 });
537             }
538         }
539     }
540
541     /// Checks if `#[no_mangle]` is applied to a function or static.
542     fn check_no_mangle(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) {
543         match target {
544             Target::Static | Target::Fn | Target::Method(..) => {}
545             _ => {
546                 // FIXME: #[no_mangle] was previously allowed on non-functions/statics and some
547                 // crates used this, so only emit a warning.
548                 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
549                     lint.build("attribute should be applied to a function or static")
550                         .warn(
551                             "this was previously accepted by the compiler but is \
552                              being phased out; it will become a hard error in \
553                              a future release!",
554                         )
555                         .span_label(*span, "not a function or static")
556                         .emit();
557                 });
558             }
559         }
560     }
561
562     /// Checks if the `#[repr]` attributes on `item` are valid.
563     fn check_repr(
564         &self,
565         attrs: &'hir [Attribute],
566         span: &Span,
567         target: Target,
568         item: Option<ItemLike<'_>>,
569         hir_id: HirId,
570     ) {
571         // Extract the names of all repr hints, e.g., [foo, bar, align] for:
572         // ```
573         // #[repr(foo)]
574         // #[repr(bar, align(8))]
575         // ```
576         let hints: Vec<_> = attrs
577             .iter()
578             .filter(|attr| self.tcx.sess.check_name(attr, sym::repr))
579             .filter_map(|attr| attr.meta_item_list())
580             .flatten()
581             .collect();
582
583         let mut int_reprs = 0;
584         let mut is_c = false;
585         let mut is_simd = false;
586         let mut is_transparent = false;
587
588         for hint in &hints {
589             let (article, allowed_targets) = match hint.name_or_empty() {
590                 name @ sym::C | name @ sym::align => {
591                     is_c |= name == sym::C;
592                     match target {
593                         Target::Struct | Target::Union | Target::Enum => continue,
594                         _ => ("a", "struct, enum, or union"),
595                     }
596                 }
597                 sym::packed => {
598                     if target != Target::Struct && target != Target::Union {
599                         ("a", "struct or union")
600                     } else {
601                         continue;
602                     }
603                 }
604                 sym::simd => {
605                     is_simd = true;
606                     if target != Target::Struct {
607                         ("a", "struct")
608                     } else {
609                         continue;
610                     }
611                 }
612                 sym::transparent => {
613                     is_transparent = true;
614                     match target {
615                         Target::Struct | Target::Union | Target::Enum => continue,
616                         _ => ("a", "struct, enum, or union"),
617                     }
618                 }
619                 sym::no_niche => {
620                     if !self.tcx.features().enabled(sym::no_niche) {
621                         feature_err(
622                             &self.tcx.sess.parse_sess,
623                             sym::no_niche,
624                             hint.span(),
625                             "the attribute `repr(no_niche)` is currently unstable",
626                         )
627                         .emit();
628                     }
629                     match target {
630                         Target::Struct | Target::Enum => continue,
631                         _ => ("a", "struct or enum"),
632                     }
633                 }
634                 sym::i8
635                 | sym::u8
636                 | sym::i16
637                 | sym::u16
638                 | sym::i32
639                 | sym::u32
640                 | sym::i64
641                 | sym::u64
642                 | sym::i128
643                 | sym::u128
644                 | sym::isize
645                 | sym::usize => {
646                     int_reprs += 1;
647                     if target != Target::Enum {
648                         ("an", "enum")
649                     } else {
650                         continue;
651                     }
652                 }
653                 _ => continue,
654             };
655             self.emit_repr_error(
656                 hint.span(),
657                 *span,
658                 &format!("attribute should be applied to {}", allowed_targets),
659                 &format!("not {} {}", article, allowed_targets),
660             )
661         }
662
663         // Just point at all repr hints if there are any incompatibilities.
664         // This is not ideal, but tracking precisely which ones are at fault is a huge hassle.
665         let hint_spans = hints.iter().map(|hint| hint.span());
666
667         // Error on repr(transparent, <anything else apart from no_niche>).
668         let non_no_niche = |hint: &&NestedMetaItem| hint.name_or_empty() != sym::no_niche;
669         let non_no_niche_count = hints.iter().filter(non_no_niche).count();
670         if is_transparent && non_no_niche_count > 1 {
671             let hint_spans: Vec<_> = hint_spans.clone().collect();
672             struct_span_err!(
673                 self.tcx.sess,
674                 hint_spans,
675                 E0692,
676                 "transparent {} cannot have other repr hints",
677                 target
678             )
679             .emit();
680         }
681         // Warn on repr(u8, u16), repr(C, simd), and c-like-enum-repr(C, u8)
682         if (int_reprs > 1)
683             || (is_simd && is_c)
684             || (int_reprs == 1
685                 && is_c
686                 && item.map_or(false, |item| {
687                     if let ItemLike::Item(item) = item {
688                         return is_c_like_enum(item);
689                     }
690                     return false;
691                 }))
692         {
693             self.tcx.struct_span_lint_hir(
694                 CONFLICTING_REPR_HINTS,
695                 hir_id,
696                 hint_spans.collect::<Vec<Span>>(),
697                 |lint| {
698                     lint.build("conflicting representation hints")
699                         .code(rustc_errors::error_code!(E0566))
700                         .emit();
701                 },
702             );
703         }
704     }
705
706     fn emit_repr_error(
707         &self,
708         hint_span: Span,
709         label_span: Span,
710         hint_message: &str,
711         label_message: &str,
712     ) {
713         struct_span_err!(self.tcx.sess, hint_span, E0517, "{}", hint_message)
714             .span_label(label_span, label_message)
715             .emit();
716     }
717
718     fn check_stmt_attributes(&self, stmt: &hir::Stmt<'_>) {
719         // When checking statements ignore expressions, they will be checked later
720         if let hir::StmtKind::Local(ref l) = stmt.kind {
721             self.check_attributes(l.hir_id, &l.attrs, &stmt.span, Target::Statement, None);
722             for attr in l.attrs.iter() {
723                 if self.tcx.sess.check_name(attr, sym::repr) {
724                     self.emit_repr_error(
725                         attr.span,
726                         stmt.span,
727                         "attribute should not be applied to a statement",
728                         "not a struct, enum, or union",
729                     );
730                 }
731             }
732         }
733     }
734
735     fn check_expr_attributes(&self, expr: &hir::Expr<'_>) {
736         let target = match expr.kind {
737             hir::ExprKind::Closure(..) => Target::Closure,
738             _ => Target::Expression,
739         };
740         self.check_attributes(expr.hir_id, &expr.attrs, &expr.span, target, None);
741         for attr in expr.attrs.iter() {
742             if self.tcx.sess.check_name(attr, sym::repr) {
743                 self.emit_repr_error(
744                     attr.span,
745                     expr.span,
746                     "attribute should not be applied to an expression",
747                     "not defining a struct, enum, or union",
748                 );
749             }
750         }
751         if target == Target::Closure {
752             self.tcx.ensure().codegen_fn_attrs(self.tcx.hir().local_def_id(expr.hir_id));
753         }
754     }
755
756     fn check_used(&self, attrs: &'hir [Attribute], target: Target) {
757         for attr in attrs {
758             if self.tcx.sess.check_name(attr, sym::used) && target != Target::Static {
759                 self.tcx
760                     .sess
761                     .span_err(attr.span, "attribute must be applied to a `static` variable");
762             }
763         }
764     }
765 }
766
767 impl Visitor<'tcx> for CheckAttrVisitor<'tcx> {
768     type Map = Map<'tcx>;
769
770     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
771         NestedVisitorMap::OnlyBodies(self.tcx.hir())
772     }
773
774     fn visit_item(&mut self, item: &'tcx Item<'tcx>) {
775         let target = Target::from_item(item);
776         self.check_attributes(
777             item.hir_id,
778             item.attrs,
779             &item.span,
780             target,
781             Some(ItemLike::Item(item)),
782         );
783         intravisit::walk_item(self, item)
784     }
785
786     fn visit_trait_item(&mut self, trait_item: &'tcx TraitItem<'tcx>) {
787         let target = Target::from_trait_item(trait_item);
788         self.check_attributes(trait_item.hir_id, &trait_item.attrs, &trait_item.span, target, None);
789         intravisit::walk_trait_item(self, trait_item)
790     }
791
792     fn visit_foreign_item(&mut self, f_item: &'tcx ForeignItem<'tcx>) {
793         let target = Target::from_foreign_item(f_item);
794         self.check_attributes(
795             f_item.hir_id,
796             &f_item.attrs,
797             &f_item.span,
798             target,
799             Some(ItemLike::ForeignItem(f_item)),
800         );
801         intravisit::walk_foreign_item(self, f_item)
802     }
803
804     fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
805         let target = target_from_impl_item(self.tcx, impl_item);
806         self.check_attributes(impl_item.hir_id, &impl_item.attrs, &impl_item.span, target, None);
807         intravisit::walk_impl_item(self, impl_item)
808     }
809
810     fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt<'tcx>) {
811         self.check_stmt_attributes(stmt);
812         intravisit::walk_stmt(self, stmt)
813     }
814
815     fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
816         self.check_expr_attributes(expr);
817         intravisit::walk_expr(self, expr)
818     }
819 }
820
821 fn is_c_like_enum(item: &Item<'_>) -> bool {
822     if let ItemKind::Enum(ref def, _) = item.kind {
823         for variant in def.variants {
824             match variant.data {
825                 hir::VariantData::Unit(..) => { /* continue */ }
826                 _ => return false,
827             }
828         }
829         true
830     } else {
831         false
832     }
833 }
834
835 fn check_invalid_crate_level_attr(tcx: TyCtxt<'_>, attrs: &[Attribute]) {
836     const ATTRS_TO_CHECK: &[Symbol] = &[
837         sym::macro_export,
838         sym::repr,
839         sym::path,
840         sym::automatically_derived,
841         sym::start,
842         sym::main,
843     ];
844
845     for attr in attrs {
846         for attr_to_check in ATTRS_TO_CHECK {
847             if tcx.sess.check_name(attr, *attr_to_check) {
848                 tcx.sess
849                     .struct_span_err(
850                         attr.span,
851                         &format!(
852                             "`{}` attribute cannot be used at crate level",
853                             attr_to_check.to_ident_string()
854                         ),
855                     )
856                     .emit();
857             }
858         }
859     }
860 }
861
862 fn check_mod_attrs(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
863     tcx.hir()
864         .visit_item_likes_in_module(module_def_id, &mut CheckAttrVisitor { tcx }.as_deep_visitor());
865     if module_def_id.is_top_level_module() {
866         CheckAttrVisitor { tcx }.check_attributes(
867             CRATE_HIR_ID,
868             tcx.hir().krate_attrs(),
869             &DUMMY_SP,
870             Target::Mod,
871             None,
872         );
873         check_invalid_crate_level_attr(tcx, tcx.hir().krate_attrs());
874     }
875 }
876
877 pub(crate) fn provide(providers: &mut Providers) {
878     *providers = Providers { check_mod_attrs, ..*providers };
879 }