]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_passes/src/check_attr.rs
Rollup merge of #85989 - jyn514:gitignore-cleanup, r=ehuss
[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::{AttrStyle, Attribute, Lit, LitKind, NestedMetaItem};
12 use rustc_errors::{pluralize, struct_span_err, Applicability};
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, FnSig, ForeignItem, HirId, Item, ItemKind, TraitItem, CRATE_HIR_ID};
17 use rustc_hir::{MethodKind, Target};
18 use rustc_session::lint::builtin::{
19     CONFLICTING_REPR_HINTS, INVALID_DOC_ATTRIBUTES, UNUSED_ATTRIBUTES,
20 };
21 use rustc_session::parse::feature_err;
22 use rustc_span::symbol::{sym, Symbol};
23 use rustc_span::{MultiSpan, 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(impl_) => impl_.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         span: &Span,
64         target: Target,
65         item: Option<ItemLike<'_>>,
66     ) {
67         let mut is_valid = true;
68         let mut specified_inline = None;
69         let attrs = self.tcx.hir().attrs(hir_id);
70         for attr in attrs {
71             is_valid &= match attr.name_or_empty() {
72                 sym::inline => self.check_inline(hir_id, attr, span, target),
73                 sym::non_exhaustive => self.check_non_exhaustive(hir_id, attr, span, target),
74                 sym::marker => self.check_marker(hir_id, attr, span, target),
75                 sym::target_feature => self.check_target_feature(hir_id, attr, span, target),
76                 sym::track_caller => {
77                     self.check_track_caller(hir_id, &attr.span, attrs, span, target)
78                 }
79                 sym::doc => self.check_doc_attrs(attr, hir_id, target, &mut specified_inline),
80                 sym::no_link => self.check_no_link(hir_id, &attr, span, target),
81                 sym::export_name => self.check_export_name(hir_id, &attr, span, target),
82                 sym::rustc_layout_scalar_valid_range_start
83                 | sym::rustc_layout_scalar_valid_range_end => {
84                     self.check_rustc_layout_scalar_valid_range(&attr, span, target)
85                 }
86                 sym::allow_internal_unstable => {
87                     self.check_allow_internal_unstable(hir_id, &attr, span, target, &attrs)
88                 }
89                 sym::rustc_allow_const_fn_unstable => {
90                     self.check_rustc_allow_const_fn_unstable(hir_id, &attr, span, target)
91                 }
92                 sym::naked => self.check_naked(hir_id, attr, span, target),
93                 sym::rustc_legacy_const_generics => {
94                     self.check_rustc_legacy_const_generics(&attr, span, target, item)
95                 }
96                 sym::rustc_clean
97                 | sym::rustc_dirty
98                 | sym::rustc_if_this_changed
99                 | sym::rustc_then_this_would_need => self.check_rustc_dirty_clean(&attr),
100                 _ => true,
101             };
102             // lint-only checks
103             match attr.name_or_empty() {
104                 sym::cold => self.check_cold(hir_id, attr, span, target),
105                 sym::link_name => self.check_link_name(hir_id, attr, span, target),
106                 sym::link_section => self.check_link_section(hir_id, attr, span, target),
107                 sym::no_mangle => self.check_no_mangle(hir_id, attr, span, target),
108                 _ => {}
109             }
110         }
111
112         if !is_valid {
113             return;
114         }
115
116         if matches!(target, Target::Closure | Target::Fn | Target::Method(_) | Target::ForeignFn) {
117             self.tcx.ensure().codegen_fn_attrs(self.tcx.hir().local_def_id(hir_id));
118         }
119
120         self.check_repr(attrs, span, target, item, hir_id);
121         self.check_used(attrs, target);
122     }
123
124     fn inline_attr_str_error_with_macro_def(&self, hir_id: HirId, attr: &Attribute, sym: &str) {
125         self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
126             lint.build(&format!(
127                 "`#[{}]` is ignored on struct fields, match arms and macro defs",
128                 sym,
129             ))
130             .warn(
131                 "this was previously accepted by the compiler but is \
132                  being phased out; it will become a hard error in \
133                  a future release!",
134             )
135             .note(
136                 "see issue #80564 <https://github.com/rust-lang/rust/issues/80564> \
137                  for more information",
138             )
139             .emit();
140         });
141     }
142
143     fn inline_attr_str_error_without_macro_def(&self, hir_id: HirId, attr: &Attribute, sym: &str) {
144         self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
145             lint.build(&format!("`#[{}]` is ignored on struct fields and match arms", sym))
146                 .warn(
147                     "this was previously accepted by the compiler but is \
148                  being phased out; it will become a hard error in \
149                  a future release!",
150                 )
151                 .note(
152                     "see issue #80564 <https://github.com/rust-lang/rust/issues/80564> \
153                  for more information",
154                 )
155                 .emit();
156         });
157     }
158
159     /// Checks if an `#[inline]` is applied to a function or a closure. Returns `true` if valid.
160     fn check_inline(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) -> bool {
161         match target {
162             Target::Fn
163             | Target::Closure
164             | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true,
165             Target::Method(MethodKind::Trait { body: false }) | Target::ForeignFn => {
166                 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
167                     lint.build("`#[inline]` is ignored on function prototypes").emit()
168                 });
169                 true
170             }
171             // FIXME(#65833): We permit associated consts to have an `#[inline]` attribute with
172             // just a lint, because we previously erroneously allowed it and some crates used it
173             // accidentally, to to be compatible with crates depending on them, we can't throw an
174             // error here.
175             Target::AssocConst => {
176                 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
177                     lint.build("`#[inline]` is ignored on constants")
178                         .warn(
179                             "this was previously accepted by the compiler but is \
180                              being phased out; it will become a hard error in \
181                              a future release!",
182                         )
183                         .note(
184                             "see issue #65833 <https://github.com/rust-lang/rust/issues/65833> \
185                              for more information",
186                         )
187                         .emit();
188                 });
189                 true
190             }
191             // FIXME(#80564): Same for fields, arms, and macro defs
192             Target::Field | Target::Arm | Target::MacroDef => {
193                 self.inline_attr_str_error_with_macro_def(hir_id, attr, "inline");
194                 true
195             }
196             _ => {
197                 struct_span_err!(
198                     self.tcx.sess,
199                     attr.span,
200                     E0518,
201                     "attribute should be applied to function or closure",
202                 )
203                 .span_label(*span, "not a function or closure")
204                 .emit();
205                 false
206             }
207         }
208     }
209
210     /// Checks if `#[naked]` is applied to a function definition.
211     fn check_naked(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) -> bool {
212         match target {
213             Target::Fn
214             | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true,
215             // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
216             // `#[allow_internal_unstable]` attribute with just a lint, because we previously
217             // erroneously allowed it and some crates used it accidentally, to to be compatible
218             // with crates depending on them, we can't throw an error here.
219             Target::Field | Target::Arm | Target::MacroDef => {
220                 self.inline_attr_str_error_with_macro_def(hir_id, attr, "naked");
221                 true
222             }
223             _ => {
224                 self.tcx
225                     .sess
226                     .struct_span_err(
227                         attr.span,
228                         "attribute should be applied to a function definition",
229                     )
230                     .span_label(*span, "not a function definition")
231                     .emit();
232                 false
233             }
234         }
235     }
236
237     /// Checks if a `#[track_caller]` is applied to a non-naked function. Returns `true` if valid.
238     fn check_track_caller(
239         &self,
240         hir_id: HirId,
241         attr_span: &Span,
242         attrs: &'hir [Attribute],
243         span: &Span,
244         target: Target,
245     ) -> bool {
246         match target {
247             _ if attrs.iter().any(|attr| attr.has_name(sym::naked)) => {
248                 struct_span_err!(
249                     self.tcx.sess,
250                     *attr_span,
251                     E0736,
252                     "cannot use `#[track_caller]` with `#[naked]`",
253                 )
254                 .emit();
255                 false
256             }
257             Target::Fn | Target::Method(..) | Target::ForeignFn | Target::Closure => true,
258             // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
259             // `#[track_caller]` attribute with just a lint, because we previously
260             // erroneously allowed it and some crates used it accidentally, to to be compatible
261             // with crates depending on them, we can't throw an error here.
262             Target::Field | Target::Arm | Target::MacroDef => {
263                 for attr in attrs {
264                     self.inline_attr_str_error_with_macro_def(hir_id, attr, "track_caller");
265                 }
266                 true
267             }
268             _ => {
269                 struct_span_err!(
270                     self.tcx.sess,
271                     *attr_span,
272                     E0739,
273                     "attribute should be applied to function"
274                 )
275                 .span_label(*span, "not a function")
276                 .emit();
277                 false
278             }
279         }
280     }
281
282     /// Checks if the `#[non_exhaustive]` attribute on an `item` is valid. Returns `true` if valid.
283     fn check_non_exhaustive(
284         &self,
285         hir_id: HirId,
286         attr: &Attribute,
287         span: &Span,
288         target: Target,
289     ) -> bool {
290         match target {
291             Target::Struct | Target::Enum | Target::Variant => true,
292             // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
293             // `#[non_exhaustive]` attribute with just a lint, because we previously
294             // erroneously allowed it and some crates used it accidentally, to to be compatible
295             // with crates depending on them, we can't throw an error here.
296             Target::Field | Target::Arm | Target::MacroDef => {
297                 self.inline_attr_str_error_with_macro_def(hir_id, attr, "non_exhaustive");
298                 true
299             }
300             _ => {
301                 struct_span_err!(
302                     self.tcx.sess,
303                     attr.span,
304                     E0701,
305                     "attribute can only be applied to a struct or enum"
306                 )
307                 .span_label(*span, "not a struct or enum")
308                 .emit();
309                 false
310             }
311         }
312     }
313
314     /// Checks if the `#[marker]` attribute on an `item` is valid. Returns `true` if valid.
315     fn check_marker(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) -> bool {
316         match target {
317             Target::Trait => true,
318             // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
319             // `#[marker]` attribute with just a lint, because we previously
320             // erroneously allowed it and some crates used it accidentally, to to be compatible
321             // with crates depending on them, we can't throw an error here.
322             Target::Field | Target::Arm | Target::MacroDef => {
323                 self.inline_attr_str_error_with_macro_def(hir_id, attr, "marker");
324                 true
325             }
326             _ => {
327                 self.tcx
328                     .sess
329                     .struct_span_err(attr.span, "attribute can only be applied to a trait")
330                     .span_label(*span, "not a trait")
331                     .emit();
332                 false
333             }
334         }
335     }
336
337     /// Checks if the `#[target_feature]` attribute on `item` is valid. Returns `true` if valid.
338     fn check_target_feature(
339         &self,
340         hir_id: HirId,
341         attr: &Attribute,
342         span: &Span,
343         target: Target,
344     ) -> bool {
345         match target {
346             Target::Fn
347             | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true,
348             // FIXME: #[target_feature] was previously erroneously allowed on statements and some
349             // crates used this, so only emit a warning.
350             Target::Statement => {
351                 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
352                     lint.build("attribute should be applied to a function")
353                         .warn(
354                             "this was previously accepted by the compiler but is \
355                              being phased out; it will become a hard error in \
356                              a future release!",
357                         )
358                         .span_label(*span, "not a function")
359                         .emit();
360                 });
361                 true
362             }
363             // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
364             // `#[target_feature]` attribute with just a lint, because we previously
365             // erroneously allowed it and some crates used it accidentally, to to be compatible
366             // with crates depending on them, we can't throw an error here.
367             Target::Field | Target::Arm | Target::MacroDef => {
368                 self.inline_attr_str_error_with_macro_def(hir_id, attr, "target_feature");
369                 true
370             }
371             _ => {
372                 self.tcx
373                     .sess
374                     .struct_span_err(attr.span, "attribute should be applied to a function")
375                     .span_label(*span, "not a function")
376                     .emit();
377                 false
378             }
379         }
380     }
381
382     fn doc_attr_str_error(&self, meta: &NestedMetaItem, attr_name: &str) {
383         self.tcx
384             .sess
385             .struct_span_err(
386                 meta.span(),
387                 &format!("doc {0} attribute expects a string: #[doc({0} = \"a\")]", attr_name),
388             )
389             .emit();
390     }
391
392     fn check_doc_alias_value(
393         &self,
394         meta: &NestedMetaItem,
395         doc_alias: &str,
396         hir_id: HirId,
397         target: Target,
398         is_list: bool,
399     ) -> bool {
400         let tcx = self.tcx;
401         let err_fn = move |span: Span, msg: &str| {
402             tcx.sess.span_err(
403                 span,
404                 &format!(
405                     "`#[doc(alias{})]` {}",
406                     if is_list { "(\"...\")" } else { " = \"...\"" },
407                     msg,
408                 ),
409             );
410             false
411         };
412         if doc_alias.is_empty() {
413             return err_fn(
414                 meta.name_value_literal_span().unwrap_or_else(|| meta.span()),
415                 "attribute cannot have empty value",
416             );
417         }
418         if let Some(c) =
419             doc_alias.chars().find(|&c| c == '"' || c == '\'' || (c.is_whitespace() && c != ' '))
420         {
421             self.tcx.sess.span_err(
422                 meta.name_value_literal_span().unwrap_or_else(|| meta.span()),
423                 &format!(
424                     "{:?} character isn't allowed in `#[doc(alias{})]`",
425                     c,
426                     if is_list { "(\"...\")" } else { " = \"...\"" },
427                 ),
428             );
429             return false;
430         }
431         if doc_alias.starts_with(' ') || doc_alias.ends_with(' ') {
432             return err_fn(
433                 meta.name_value_literal_span().unwrap_or_else(|| meta.span()),
434                 "cannot start or end with ' '",
435             );
436         }
437         if let Some(err) = match target {
438             Target::Impl => Some("implementation block"),
439             Target::ForeignMod => Some("extern block"),
440             Target::AssocTy => {
441                 let parent_hir_id = self.tcx.hir().get_parent_item(hir_id);
442                 let containing_item = self.tcx.hir().expect_item(parent_hir_id);
443                 if Target::from_item(containing_item) == Target::Impl {
444                     Some("type alias in implementation block")
445                 } else {
446                     None
447                 }
448             }
449             Target::AssocConst => {
450                 let parent_hir_id = self.tcx.hir().get_parent_item(hir_id);
451                 let containing_item = self.tcx.hir().expect_item(parent_hir_id);
452                 // We can't link to trait impl's consts.
453                 let err = "associated constant in trait implementation block";
454                 match containing_item.kind {
455                     ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) => Some(err),
456                     _ => None,
457                 }
458             }
459             _ => None,
460         } {
461             return err_fn(meta.span(), &format!("isn't allowed on {}", err));
462         }
463         let item_name = self.tcx.hir().name(hir_id);
464         if &*item_name.as_str() == doc_alias {
465             return err_fn(meta.span(), "is the same as the item's name");
466         }
467         true
468     }
469
470     fn check_doc_alias(&self, meta: &NestedMetaItem, hir_id: HirId, target: Target) -> bool {
471         if let Some(values) = meta.meta_item_list() {
472             let mut errors = 0;
473             for v in values {
474                 match v.literal() {
475                     Some(l) => match l.kind {
476                         LitKind::Str(s, _) => {
477                             if !self.check_doc_alias_value(v, &s.as_str(), hir_id, target, true) {
478                                 errors += 1;
479                             }
480                         }
481                         _ => {
482                             self.tcx
483                                 .sess
484                                 .struct_span_err(
485                                     v.span(),
486                                     "`#[doc(alias(\"a\"))]` expects string literals",
487                                 )
488                                 .emit();
489                             errors += 1;
490                         }
491                     },
492                     None => {
493                         self.tcx
494                             .sess
495                             .struct_span_err(
496                                 v.span(),
497                                 "`#[doc(alias(\"a\"))]` expects string literals",
498                             )
499                             .emit();
500                         errors += 1;
501                     }
502                 }
503             }
504             errors == 0
505         } else if let Some(doc_alias) = meta.value_str().map(|s| s.to_string()) {
506             self.check_doc_alias_value(meta, &doc_alias, hir_id, target, false)
507         } else {
508             self.tcx
509                 .sess
510                 .struct_span_err(
511                     meta.span(),
512                     "doc alias attribute expects a string `#[doc(alias = \"a\")]` or a list of \
513                      strings `#[doc(alias(\"a\", \"b\"))]`",
514                 )
515                 .emit();
516             false
517         }
518     }
519
520     fn check_doc_keyword(&self, meta: &NestedMetaItem, hir_id: HirId) -> bool {
521         let doc_keyword = meta.value_str().map(|s| s.to_string()).unwrap_or_else(String::new);
522         if doc_keyword.is_empty() {
523             self.doc_attr_str_error(meta, "keyword");
524             return false;
525         }
526         match self.tcx.hir().expect_item(hir_id).kind {
527             ItemKind::Mod(ref module) => {
528                 if !module.item_ids.is_empty() {
529                     self.tcx
530                         .sess
531                         .struct_span_err(
532                             meta.span(),
533                             "`#[doc(keyword = \"...\")]` can only be used on empty modules",
534                         )
535                         .emit();
536                     return false;
537                 }
538             }
539             _ => {
540                 self.tcx
541                     .sess
542                     .struct_span_err(
543                         meta.span(),
544                         "`#[doc(keyword = \"...\")]` can only be used on modules",
545                     )
546                     .emit();
547                 return false;
548             }
549         }
550         if !rustc_lexer::is_ident(&doc_keyword) {
551             self.tcx
552                 .sess
553                 .struct_span_err(
554                     meta.name_value_literal_span().unwrap_or_else(|| meta.span()),
555                     &format!("`{}` is not a valid identifier", doc_keyword),
556                 )
557                 .emit();
558             return false;
559         }
560         true
561     }
562
563     /// Checks `#[doc(inline)]`/`#[doc(no_inline)]` attributes. Returns `true` if valid.
564     ///
565     /// A doc inlining attribute is invalid if it is applied to a non-`use` item, or
566     /// if there are conflicting attributes for one item.
567     ///
568     /// `specified_inline` is used to keep track of whether we have
569     /// already seen an inlining attribute for this item.
570     /// If so, `specified_inline` holds the value and the span of
571     /// the first `inline`/`no_inline` attribute.
572     fn check_doc_inline(
573         &self,
574         attr: &Attribute,
575         meta: &NestedMetaItem,
576         hir_id: HirId,
577         target: Target,
578         specified_inline: &mut Option<(bool, Span)>,
579     ) -> bool {
580         if target == Target::Use || target == Target::ExternCrate {
581             let do_inline = meta.name_or_empty() == sym::inline;
582             if let Some((prev_inline, prev_span)) = *specified_inline {
583                 if do_inline != prev_inline {
584                     let mut spans = MultiSpan::from_spans(vec![prev_span, meta.span()]);
585                     spans.push_span_label(prev_span, String::from("this attribute..."));
586                     spans.push_span_label(
587                         meta.span(),
588                         String::from("...conflicts with this attribute"),
589                     );
590                     self.tcx
591                         .sess
592                         .struct_span_err(spans, "conflicting doc inlining attributes")
593                         .help("remove one of the conflicting attributes")
594                         .emit();
595                     return false;
596                 }
597                 true
598             } else {
599                 *specified_inline = Some((do_inline, meta.span()));
600                 true
601             }
602         } else {
603             self.tcx.struct_span_lint_hir(
604                 INVALID_DOC_ATTRIBUTES,
605                 hir_id,
606                 meta.span(),
607                 |lint| {
608                     let mut err = lint.build(
609                         "this attribute can only be applied to a `use` item",
610                     );
611                     err.span_label(meta.span(), "only applicable on `use` items");
612                     if attr.style == AttrStyle::Outer {
613                         err.span_label(
614                             self.tcx.hir().span(hir_id),
615                             "not a `use` item",
616                         );
617                     }
618                     err.note("read https://doc.rust-lang.org/nightly/rustdoc/the-doc-attribute.html#docno_inlinedocinline for more information")
619                         .emit();
620                 },
621             );
622             false
623         }
624     }
625
626     /// Checks that an attribute is *not* used at the crate level. Returns `true` if valid.
627     fn check_attr_not_crate_level(
628         &self,
629         meta: &NestedMetaItem,
630         hir_id: HirId,
631         attr_name: &str,
632     ) -> bool {
633         if CRATE_HIR_ID == hir_id {
634             self.tcx
635                 .sess
636                 .struct_span_err(
637                     meta.span(),
638                     &format!(
639                         "`#![doc({} = \"...\")]` isn't allowed as a crate-level attribute",
640                         attr_name,
641                     ),
642                 )
643                 .emit();
644             return false;
645         }
646         true
647     }
648
649     /// Checks that an attribute is used at the crate level. Returns `true` if valid.
650     fn check_attr_crate_level(
651         &self,
652         attr: &Attribute,
653         meta: &NestedMetaItem,
654         hir_id: HirId,
655     ) -> bool {
656         if hir_id != CRATE_HIR_ID {
657             self.tcx.struct_span_lint_hir(
658                 INVALID_DOC_ATTRIBUTES,
659                 hir_id,
660                 meta.span(),
661                 |lint| {
662                     let mut err = lint.build(
663                         "this attribute can only be applied at the crate level",
664                     );
665                     if attr.style == AttrStyle::Outer && self.tcx.hir().get_parent_item(hir_id) == CRATE_HIR_ID {
666                         if let Ok(mut src) =
667                             self.tcx.sess.source_map().span_to_snippet(attr.span)
668                         {
669                             src.insert(1, '!');
670                             err.span_suggestion_verbose(
671                                 attr.span,
672                                 "to apply to the crate, use an inner attribute",
673                                 src,
674                                 Applicability::MaybeIncorrect,
675                             );
676                         } else {
677                             err.span_help(
678                                 attr.span,
679                                 "to apply to the crate, use an inner attribute",
680                             );
681                         }
682                     }
683                     err.note("read https://doc.rust-lang.org/nightly/rustdoc/the-doc-attribute.html#at-the-crate-level for more information")
684                         .emit();
685                 },
686             );
687             return false;
688         }
689         true
690     }
691
692     /// Runs various checks on `#[doc]` attributes. Returns `true` if valid.
693     ///
694     /// `specified_inline` should be initialized to `None` and kept for the scope
695     /// of one item. Read the documentation of [`check_doc_inline`] for more information.
696     ///
697     /// [`check_doc_inline`]: Self::check_doc_inline
698     fn check_doc_attrs(
699         &self,
700         attr: &Attribute,
701         hir_id: HirId,
702         target: Target,
703         specified_inline: &mut Option<(bool, Span)>,
704     ) -> bool {
705         let mut is_valid = true;
706
707         if let Some(list) = attr.meta().and_then(|mi| mi.meta_item_list().map(|l| l.to_vec())) {
708             for meta in &list {
709                 if let Some(i_meta) = meta.meta_item() {
710                     match i_meta.name_or_empty() {
711                         sym::alias
712                             if !self.check_attr_not_crate_level(&meta, hir_id, "alias")
713                                 || !self.check_doc_alias(&meta, hir_id, target) =>
714                         {
715                             is_valid = false
716                         }
717
718                         sym::keyword
719                             if !self.check_attr_not_crate_level(&meta, hir_id, "keyword")
720                                 || !self.check_doc_keyword(&meta, hir_id) =>
721                         {
722                             is_valid = false
723                         }
724
725                         sym::html_favicon_url
726                         | sym::html_logo_url
727                         | sym::html_playground_url
728                         | sym::issue_tracker_base_url
729                         | sym::html_root_url
730                         | sym::html_no_source
731                         | sym::test
732                             if !self.check_attr_crate_level(&attr, &meta, hir_id) =>
733                         {
734                             is_valid = false;
735                         }
736
737                         sym::inline | sym::no_inline
738                             if !self.check_doc_inline(
739                                 &attr,
740                                 &meta,
741                                 hir_id,
742                                 target,
743                                 specified_inline,
744                             ) =>
745                         {
746                             is_valid = false;
747                         }
748
749                         // no_default_passes: deprecated
750                         // passes: deprecated
751                         // plugins: removed, but rustdoc warns about it itself
752                         sym::alias
753                         | sym::cfg
754                         | sym::hidden
755                         | sym::html_favicon_url
756                         | sym::html_logo_url
757                         | sym::html_no_source
758                         | sym::html_playground_url
759                         | sym::html_root_url
760                         | sym::inline
761                         | sym::issue_tracker_base_url
762                         | sym::keyword
763                         | sym::masked
764                         | sym::no_default_passes
765                         | sym::no_inline
766                         | sym::notable_trait
767                         | sym::passes
768                         | sym::plugins
769                         | sym::primitive
770                         | sym::test => {}
771
772                         _ => {
773                             self.tcx.struct_span_lint_hir(
774                                 INVALID_DOC_ATTRIBUTES,
775                                 hir_id,
776                                 i_meta.span,
777                                 |lint| {
778                                     let mut diag = lint.build(&format!(
779                                         "unknown `doc` attribute `{}`",
780                                         rustc_ast_pretty::pprust::path_to_string(&i_meta.path),
781                                     ));
782                                     if i_meta.has_name(sym::spotlight) {
783                                         diag.note(
784                                             "`doc(spotlight)` was renamed to `doc(notable_trait)`",
785                                         );
786                                         diag.span_suggestion_short(
787                                             i_meta.span,
788                                             "use `notable_trait` instead",
789                                             String::from("notable_trait"),
790                                             Applicability::MachineApplicable,
791                                         );
792                                         diag.note("`doc(spotlight)` is now a no-op");
793                                     }
794                                     if i_meta.has_name(sym::include) {
795                                         if let Some(value) = i_meta.value_str() {
796                                             // if there are multiple attributes, the suggestion would suggest deleting all of them, which is incorrect
797                                             let applicability = if list.len() == 1 {
798                                                 Applicability::MachineApplicable
799                                             } else {
800                                                 Applicability::MaybeIncorrect
801                                             };
802                                             let inner = if attr.style == AttrStyle::Inner {
803                                                 "!"
804                                             } else {
805                                                 ""
806                                             };
807                                             diag.span_suggestion(
808                                                 attr.meta().unwrap().span,
809                                                 "use `doc = include_str!` instead",
810                                                 format!(
811                                                     "#{}[doc = include_str!(\"{}\")]",
812                                                     inner, value
813                                                 ),
814                                                 applicability,
815                                             );
816                                         }
817                                     }
818                                     diag.emit();
819                                 },
820                             );
821                             is_valid = false;
822                         }
823                     }
824                 } else {
825                     self.tcx.struct_span_lint_hir(
826                         INVALID_DOC_ATTRIBUTES,
827                         hir_id,
828                         meta.span(),
829                         |lint| {
830                             lint.build(&format!("invalid `doc` attribute")).emit();
831                         },
832                     );
833                     is_valid = false;
834                 }
835             }
836         }
837
838         is_valid
839     }
840
841     /// Checks if `#[cold]` is applied to a non-function. Returns `true` if valid.
842     fn check_cold(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) {
843         match target {
844             Target::Fn | Target::Method(..) | Target::ForeignFn | Target::Closure => {}
845             // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
846             // `#[cold]` attribute with just a lint, because we previously
847             // erroneously allowed it and some crates used it accidentally, to to be compatible
848             // with crates depending on them, we can't throw an error here.
849             Target::Field | Target::Arm | Target::MacroDef => {
850                 self.inline_attr_str_error_with_macro_def(hir_id, attr, "cold");
851             }
852             _ => {
853                 // FIXME: #[cold] was previously allowed on non-functions and some crates used
854                 // this, so only emit a warning.
855                 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
856                     lint.build("attribute should be applied to a function")
857                         .warn(
858                             "this was previously accepted by the compiler but is \
859                              being phased out; it will become a hard error in \
860                              a future release!",
861                         )
862                         .span_label(*span, "not a function")
863                         .emit();
864                 });
865             }
866         }
867     }
868
869     /// Checks if `#[link_name]` is applied to an item other than a foreign function or static.
870     fn check_link_name(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) {
871         match target {
872             Target::ForeignFn | Target::ForeignStatic => {}
873             // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
874             // `#[link_name]` attribute with just a lint, because we previously
875             // erroneously allowed it and some crates used it accidentally, to to be compatible
876             // with crates depending on them, we can't throw an error here.
877             Target::Field | Target::Arm | Target::MacroDef => {
878                 self.inline_attr_str_error_with_macro_def(hir_id, attr, "link_name");
879             }
880             _ => {
881                 // FIXME: #[cold] was previously allowed on non-functions/statics and some crates
882                 // used this, so only emit a warning.
883                 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
884                     let mut diag =
885                         lint.build("attribute should be applied to a foreign function or static");
886                     diag.warn(
887                         "this was previously accepted by the compiler but is \
888                          being phased out; it will become a hard error in \
889                          a future release!",
890                     );
891
892                     // See issue #47725
893                     if let Target::ForeignMod = target {
894                         if let Some(value) = attr.value_str() {
895                             diag.span_help(
896                                 attr.span,
897                                 &format!(r#"try `#[link(name = "{}")]` instead"#, value),
898                             );
899                         } else {
900                             diag.span_help(attr.span, r#"try `#[link(name = "...")]` instead"#);
901                         }
902                     }
903
904                     diag.span_label(*span, "not a foreign function or static");
905                     diag.emit();
906                 });
907             }
908         }
909     }
910
911     /// Checks if `#[no_link]` is applied to an `extern crate`. Returns `true` if valid.
912     fn check_no_link(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) -> bool {
913         match target {
914             Target::ExternCrate => true,
915             // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
916             // `#[no_link]` attribute with just a lint, because we previously
917             // erroneously allowed it and some crates used it accidentally, to to be compatible
918             // with crates depending on them, we can't throw an error here.
919             Target::Field | Target::Arm | Target::MacroDef => {
920                 self.inline_attr_str_error_with_macro_def(hir_id, attr, "no_link");
921                 true
922             }
923             _ => {
924                 self.tcx
925                     .sess
926                     .struct_span_err(
927                         attr.span,
928                         "attribute should be applied to an `extern crate` item",
929                     )
930                     .span_label(*span, "not an `extern crate` item")
931                     .emit();
932                 false
933             }
934         }
935     }
936
937     /// Checks if `#[export_name]` is applied to a function or static. Returns `true` if valid.
938     fn check_export_name(
939         &self,
940         hir_id: HirId,
941         attr: &Attribute,
942         span: &Span,
943         target: Target,
944     ) -> bool {
945         match target {
946             Target::Static | Target::Fn | Target::Method(..) => true,
947             // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
948             // `#[export_name]` attribute with just a lint, because we previously
949             // erroneously allowed it and some crates used it accidentally, to to be compatible
950             // with crates depending on them, we can't throw an error here.
951             Target::Field | Target::Arm | Target::MacroDef => {
952                 self.inline_attr_str_error_with_macro_def(hir_id, attr, "export_name");
953                 true
954             }
955             _ => {
956                 self.tcx
957                     .sess
958                     .struct_span_err(
959                         attr.span,
960                         "attribute should be applied to a function or static",
961                     )
962                     .span_label(*span, "not a function or static")
963                     .emit();
964                 false
965             }
966         }
967     }
968
969     fn check_rustc_layout_scalar_valid_range(
970         &self,
971         attr: &Attribute,
972         span: &Span,
973         target: Target,
974     ) -> bool {
975         if target != Target::Struct {
976             self.tcx
977                 .sess
978                 .struct_span_err(attr.span, "attribute should be applied to a struct")
979                 .span_label(*span, "not a struct")
980                 .emit();
981             return false;
982         }
983
984         let list = match attr.meta_item_list() {
985             None => return false,
986             Some(it) => it,
987         };
988
989         if matches!(&list[..], &[NestedMetaItem::Literal(Lit { kind: LitKind::Int(..), .. })]) {
990             true
991         } else {
992             self.tcx
993                 .sess
994                 .struct_span_err(attr.span, "expected exactly one integer literal argument")
995                 .emit();
996             false
997         }
998     }
999
1000     /// Checks if `#[rustc_legacy_const_generics]` is applied to a function and has a valid argument.
1001     fn check_rustc_legacy_const_generics(
1002         &self,
1003         attr: &Attribute,
1004         span: &Span,
1005         target: Target,
1006         item: Option<ItemLike<'_>>,
1007     ) -> bool {
1008         let is_function = matches!(target, Target::Fn | Target::Method(..));
1009         if !is_function {
1010             self.tcx
1011                 .sess
1012                 .struct_span_err(attr.span, "attribute should be applied to a function")
1013                 .span_label(*span, "not a function")
1014                 .emit();
1015             return false;
1016         }
1017
1018         let list = match attr.meta_item_list() {
1019             // The attribute form is validated on AST.
1020             None => return false,
1021             Some(it) => it,
1022         };
1023
1024         let (decl, generics) = match item {
1025             Some(ItemLike::Item(Item {
1026                 kind: ItemKind::Fn(FnSig { decl, .. }, generics, _),
1027                 ..
1028             })) => (decl, generics),
1029             _ => bug!("should be a function item"),
1030         };
1031
1032         for param in generics.params {
1033             match param.kind {
1034                 hir::GenericParamKind::Const { .. } => {}
1035                 _ => {
1036                     self.tcx
1037                         .sess
1038                         .struct_span_err(
1039                             attr.span,
1040                             "#[rustc_legacy_const_generics] functions must \
1041                              only have const generics",
1042                         )
1043                         .span_label(param.span, "non-const generic parameter")
1044                         .emit();
1045                     return false;
1046                 }
1047             }
1048         }
1049
1050         if list.len() != generics.params.len() {
1051             self.tcx
1052                 .sess
1053                 .struct_span_err(
1054                     attr.span,
1055                     "#[rustc_legacy_const_generics] must have one index for each generic parameter",
1056                 )
1057                 .span_label(generics.span, "generic parameters")
1058                 .emit();
1059             return false;
1060         }
1061
1062         let arg_count = decl.inputs.len() as u128 + generics.params.len() as u128;
1063         let mut invalid_args = vec![];
1064         for meta in list {
1065             if let Some(LitKind::Int(val, _)) = meta.literal().map(|lit| &lit.kind) {
1066                 if *val >= arg_count {
1067                     let span = meta.span();
1068                     self.tcx
1069                         .sess
1070                         .struct_span_err(span, "index exceeds number of arguments")
1071                         .span_label(
1072                             span,
1073                             format!(
1074                                 "there {} only {} argument{}",
1075                                 if arg_count != 1 { "are" } else { "is" },
1076                                 arg_count,
1077                                 pluralize!(arg_count)
1078                             ),
1079                         )
1080                         .emit();
1081                     return false;
1082                 }
1083             } else {
1084                 invalid_args.push(meta.span());
1085             }
1086         }
1087
1088         if !invalid_args.is_empty() {
1089             self.tcx
1090                 .sess
1091                 .struct_span_err(invalid_args, "arguments should be non-negative integers")
1092                 .emit();
1093             false
1094         } else {
1095             true
1096         }
1097     }
1098
1099     /// Checks that the dep-graph debugging attributes are only present when the query-dep-graph
1100     /// option is passed to the compiler.
1101     fn check_rustc_dirty_clean(&self, attr: &Attribute) -> bool {
1102         if self.tcx.sess.opts.debugging_opts.query_dep_graph {
1103             true
1104         } else {
1105             self.tcx
1106                 .sess
1107                 .struct_span_err(attr.span, "attribute requires -Z query-dep-graph to be enabled")
1108                 .emit();
1109             false
1110         }
1111     }
1112
1113     /// Checks if `#[link_section]` is applied to a function or static.
1114     fn check_link_section(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) {
1115         match target {
1116             Target::Static | Target::Fn | Target::Method(..) => {}
1117             // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
1118             // `#[link_section]` attribute with just a lint, because we previously
1119             // erroneously allowed it and some crates used it accidentally, to to be compatible
1120             // with crates depending on them, we can't throw an error here.
1121             Target::Field | Target::Arm | Target::MacroDef => {
1122                 self.inline_attr_str_error_with_macro_def(hir_id, attr, "link_section");
1123             }
1124             _ => {
1125                 // FIXME: #[link_section] was previously allowed on non-functions/statics and some
1126                 // crates used this, so only emit a warning.
1127                 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
1128                     lint.build("attribute should be applied to a function or static")
1129                         .warn(
1130                             "this was previously accepted by the compiler but is \
1131                              being phased out; it will become a hard error in \
1132                              a future release!",
1133                         )
1134                         .span_label(*span, "not a function or static")
1135                         .emit();
1136                 });
1137             }
1138         }
1139     }
1140
1141     /// Checks if `#[no_mangle]` is applied to a function or static.
1142     fn check_no_mangle(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) {
1143         match target {
1144             Target::Static | Target::Fn | Target::Method(..) => {}
1145             // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
1146             // `#[no_mangle]` attribute with just a lint, because we previously
1147             // erroneously allowed it and some crates used it accidentally, to to be compatible
1148             // with crates depending on them, we can't throw an error here.
1149             Target::Field | Target::Arm | Target::MacroDef => {
1150                 self.inline_attr_str_error_with_macro_def(hir_id, attr, "no_mangle");
1151             }
1152             _ => {
1153                 // FIXME: #[no_mangle] was previously allowed on non-functions/statics and some
1154                 // crates used this, so only emit a warning.
1155                 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
1156                     lint.build("attribute should be applied to a function or static")
1157                         .warn(
1158                             "this was previously accepted by the compiler but is \
1159                              being phased out; it will become a hard error in \
1160                              a future release!",
1161                         )
1162                         .span_label(*span, "not a function or static")
1163                         .emit();
1164                 });
1165             }
1166         }
1167     }
1168
1169     /// Checks if the `#[repr]` attributes on `item` are valid.
1170     fn check_repr(
1171         &self,
1172         attrs: &'hir [Attribute],
1173         span: &Span,
1174         target: Target,
1175         item: Option<ItemLike<'_>>,
1176         hir_id: HirId,
1177     ) {
1178         // Extract the names of all repr hints, e.g., [foo, bar, align] for:
1179         // ```
1180         // #[repr(foo)]
1181         // #[repr(bar, align(8))]
1182         // ```
1183         let hints: Vec<_> = attrs
1184             .iter()
1185             .filter(|attr| attr.has_name(sym::repr))
1186             .filter_map(|attr| attr.meta_item_list())
1187             .flatten()
1188             .collect();
1189
1190         let mut int_reprs = 0;
1191         let mut is_c = false;
1192         let mut is_simd = false;
1193         let mut is_transparent = false;
1194
1195         for hint in &hints {
1196             if !hint.is_meta_item() {
1197                 struct_span_err!(
1198                     self.tcx.sess,
1199                     hint.span(),
1200                     E0565,
1201                     "meta item in `repr` must be an identifier"
1202                 )
1203                 .emit();
1204                 continue;
1205             }
1206
1207             let (article, allowed_targets) = match hint.name_or_empty() {
1208                 sym::C => {
1209                     is_c = true;
1210                     match target {
1211                         Target::Struct | Target::Union | Target::Enum => continue,
1212                         _ => ("a", "struct, enum, or union"),
1213                     }
1214                 }
1215                 sym::align => {
1216                     if let (Target::Fn, true) = (target, !self.tcx.features().fn_align) {
1217                         feature_err(
1218                             &self.tcx.sess.parse_sess,
1219                             sym::fn_align,
1220                             hint.span(),
1221                             "`repr(align)` attributes on functions are unstable",
1222                         )
1223                         .emit();
1224                     }
1225
1226                     match target {
1227                         Target::Struct | Target::Union | Target::Enum | Target::Fn => continue,
1228                         _ => ("a", "struct, enum, function, or union"),
1229                     }
1230                 }
1231                 sym::packed => {
1232                     if target != Target::Struct && target != Target::Union {
1233                         ("a", "struct or union")
1234                     } else {
1235                         continue;
1236                     }
1237                 }
1238                 sym::simd => {
1239                     is_simd = true;
1240                     if target != Target::Struct {
1241                         ("a", "struct")
1242                     } else {
1243                         continue;
1244                     }
1245                 }
1246                 sym::transparent => {
1247                     is_transparent = true;
1248                     match target {
1249                         Target::Struct | Target::Union | Target::Enum => continue,
1250                         _ => ("a", "struct, enum, or union"),
1251                     }
1252                 }
1253                 sym::no_niche => {
1254                     if !self.tcx.features().enabled(sym::no_niche) {
1255                         feature_err(
1256                             &self.tcx.sess.parse_sess,
1257                             sym::no_niche,
1258                             hint.span(),
1259                             "the attribute `repr(no_niche)` is currently unstable",
1260                         )
1261                         .emit();
1262                     }
1263                     match target {
1264                         Target::Struct | Target::Enum => continue,
1265                         _ => ("a", "struct or enum"),
1266                     }
1267                 }
1268                 sym::i8
1269                 | sym::u8
1270                 | sym::i16
1271                 | sym::u16
1272                 | sym::i32
1273                 | sym::u32
1274                 | sym::i64
1275                 | sym::u64
1276                 | sym::i128
1277                 | sym::u128
1278                 | sym::isize
1279                 | sym::usize => {
1280                     int_reprs += 1;
1281                     if target != Target::Enum {
1282                         ("an", "enum")
1283                     } else {
1284                         continue;
1285                     }
1286                 }
1287                 _ => {
1288                     struct_span_err!(
1289                         self.tcx.sess,
1290                         hint.span(),
1291                         E0552,
1292                         "unrecognized representation hint"
1293                     )
1294                     .emit();
1295
1296                     continue;
1297                 }
1298             };
1299
1300             struct_span_err!(
1301                 self.tcx.sess,
1302                 hint.span(),
1303                 E0517,
1304                 "{}",
1305                 &format!("attribute should be applied to {} {}", article, allowed_targets)
1306             )
1307             .span_label(*span, &format!("not {} {}", article, allowed_targets))
1308             .emit();
1309         }
1310
1311         // Just point at all repr hints if there are any incompatibilities.
1312         // This is not ideal, but tracking precisely which ones are at fault is a huge hassle.
1313         let hint_spans = hints.iter().map(|hint| hint.span());
1314
1315         // Error on repr(transparent, <anything else apart from no_niche>).
1316         let non_no_niche = |hint: &&NestedMetaItem| hint.name_or_empty() != sym::no_niche;
1317         let non_no_niche_count = hints.iter().filter(non_no_niche).count();
1318         if is_transparent && non_no_niche_count > 1 {
1319             let hint_spans: Vec<_> = hint_spans.clone().collect();
1320             struct_span_err!(
1321                 self.tcx.sess,
1322                 hint_spans,
1323                 E0692,
1324                 "transparent {} cannot have other repr hints",
1325                 target
1326             )
1327             .emit();
1328         }
1329         // Warn on repr(u8, u16), repr(C, simd), and c-like-enum-repr(C, u8)
1330         if (int_reprs > 1)
1331             || (is_simd && is_c)
1332             || (int_reprs == 1
1333                 && is_c
1334                 && item.map_or(false, |item| {
1335                     if let ItemLike::Item(item) = item {
1336                         return is_c_like_enum(item);
1337                     }
1338                     return false;
1339                 }))
1340         {
1341             self.tcx.struct_span_lint_hir(
1342                 CONFLICTING_REPR_HINTS,
1343                 hir_id,
1344                 hint_spans.collect::<Vec<Span>>(),
1345                 |lint| {
1346                     lint.build("conflicting representation hints")
1347                         .code(rustc_errors::error_code!(E0566))
1348                         .emit();
1349                 },
1350             );
1351         }
1352     }
1353
1354     fn check_used(&self, attrs: &'hir [Attribute], target: Target) {
1355         for attr in attrs {
1356             if attr.has_name(sym::used) && target != Target::Static {
1357                 self.tcx
1358                     .sess
1359                     .span_err(attr.span, "attribute must be applied to a `static` variable");
1360             }
1361         }
1362     }
1363
1364     /// Outputs an error for `#[allow_internal_unstable]` which can only be applied to macros.
1365     /// (Allows proc_macro functions)
1366     fn check_allow_internal_unstable(
1367         &self,
1368         hir_id: HirId,
1369         attr: &Attribute,
1370         span: &Span,
1371         target: Target,
1372         attrs: &[Attribute],
1373     ) -> bool {
1374         debug!("Checking target: {:?}", target);
1375         match target {
1376             Target::Fn => {
1377                 for attr in attrs {
1378                     if self.tcx.sess.is_proc_macro_attr(attr) {
1379                         debug!("Is proc macro attr");
1380                         return true;
1381                     }
1382                 }
1383                 debug!("Is not proc macro attr");
1384                 false
1385             }
1386             Target::MacroDef => true,
1387             // FIXME(#80564): We permit struct fields and match arms to have an
1388             // `#[allow_internal_unstable]` attribute with just a lint, because we previously
1389             // erroneously allowed it and some crates used it accidentally, to to be compatible
1390             // with crates depending on them, we can't throw an error here.
1391             Target::Field | Target::Arm => {
1392                 self.inline_attr_str_error_without_macro_def(
1393                     hir_id,
1394                     attr,
1395                     "allow_internal_unstable",
1396                 );
1397                 true
1398             }
1399             _ => {
1400                 self.tcx
1401                     .sess
1402                     .struct_span_err(attr.span, "attribute should be applied to a macro")
1403                     .span_label(*span, "not a macro")
1404                     .emit();
1405                 false
1406             }
1407         }
1408     }
1409
1410     /// Outputs an error for `#[allow_internal_unstable]` which can only be applied to macros.
1411     /// (Allows proc_macro functions)
1412     fn check_rustc_allow_const_fn_unstable(
1413         &self,
1414         hir_id: HirId,
1415         attr: &Attribute,
1416         span: &Span,
1417         target: Target,
1418     ) -> bool {
1419         match target {
1420             Target::Fn | Target::Method(_)
1421                 if self.tcx.is_const_fn_raw(self.tcx.hir().local_def_id(hir_id)) =>
1422             {
1423                 true
1424             }
1425             // FIXME(#80564): We permit struct fields and match arms to have an
1426             // `#[allow_internal_unstable]` attribute with just a lint, because we previously
1427             // erroneously allowed it and some crates used it accidentally, to to be compatible
1428             // with crates depending on them, we can't throw an error here.
1429             Target::Field | Target::Arm | Target::MacroDef => {
1430                 self.inline_attr_str_error_with_macro_def(hir_id, attr, "allow_internal_unstable");
1431                 true
1432             }
1433             _ => {
1434                 self.tcx
1435                     .sess
1436                     .struct_span_err(attr.span, "attribute should be applied to `const fn`")
1437                     .span_label(*span, "not a `const fn`")
1438                     .emit();
1439                 false
1440             }
1441         }
1442     }
1443 }
1444
1445 impl Visitor<'tcx> for CheckAttrVisitor<'tcx> {
1446     type Map = Map<'tcx>;
1447
1448     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1449         NestedVisitorMap::OnlyBodies(self.tcx.hir())
1450     }
1451
1452     fn visit_item(&mut self, item: &'tcx Item<'tcx>) {
1453         let target = Target::from_item(item);
1454         self.check_attributes(item.hir_id(), &item.span, target, Some(ItemLike::Item(item)));
1455         intravisit::walk_item(self, item)
1456     }
1457
1458     fn visit_generic_param(&mut self, generic_param: &'tcx hir::GenericParam<'tcx>) {
1459         let target = Target::from_generic_param(generic_param);
1460         self.check_attributes(generic_param.hir_id, &generic_param.span, target, None);
1461         intravisit::walk_generic_param(self, generic_param)
1462     }
1463
1464     fn visit_trait_item(&mut self, trait_item: &'tcx TraitItem<'tcx>) {
1465         let target = Target::from_trait_item(trait_item);
1466         self.check_attributes(trait_item.hir_id(), &trait_item.span, target, None);
1467         intravisit::walk_trait_item(self, trait_item)
1468     }
1469
1470     fn visit_field_def(&mut self, struct_field: &'tcx hir::FieldDef<'tcx>) {
1471         self.check_attributes(struct_field.hir_id, &struct_field.span, Target::Field, None);
1472         intravisit::walk_field_def(self, struct_field);
1473     }
1474
1475     fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) {
1476         self.check_attributes(arm.hir_id, &arm.span, Target::Arm, None);
1477         intravisit::walk_arm(self, arm);
1478     }
1479
1480     fn visit_foreign_item(&mut self, f_item: &'tcx ForeignItem<'tcx>) {
1481         let target = Target::from_foreign_item(f_item);
1482         self.check_attributes(
1483             f_item.hir_id(),
1484             &f_item.span,
1485             target,
1486             Some(ItemLike::ForeignItem(f_item)),
1487         );
1488         intravisit::walk_foreign_item(self, f_item)
1489     }
1490
1491     fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
1492         let target = target_from_impl_item(self.tcx, impl_item);
1493         self.check_attributes(impl_item.hir_id(), &impl_item.span, target, None);
1494         intravisit::walk_impl_item(self, impl_item)
1495     }
1496
1497     fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt<'tcx>) {
1498         // When checking statements ignore expressions, they will be checked later.
1499         if let hir::StmtKind::Local(ref l) = stmt.kind {
1500             self.check_attributes(l.hir_id, &stmt.span, Target::Statement, None);
1501         }
1502         intravisit::walk_stmt(self, stmt)
1503     }
1504
1505     fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
1506         let target = match expr.kind {
1507             hir::ExprKind::Closure(..) => Target::Closure,
1508             _ => Target::Expression,
1509         };
1510
1511         self.check_attributes(expr.hir_id, &expr.span, target, None);
1512         intravisit::walk_expr(self, expr)
1513     }
1514
1515     fn visit_variant(
1516         &mut self,
1517         variant: &'tcx hir::Variant<'tcx>,
1518         generics: &'tcx hir::Generics<'tcx>,
1519         item_id: HirId,
1520     ) {
1521         self.check_attributes(variant.id, &variant.span, Target::Variant, None);
1522         intravisit::walk_variant(self, variant, generics, item_id)
1523     }
1524
1525     fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef<'tcx>) {
1526         self.check_attributes(macro_def.hir_id(), &macro_def.span, Target::MacroDef, None);
1527         intravisit::walk_macro_def(self, macro_def);
1528     }
1529
1530     fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) {
1531         self.check_attributes(param.hir_id, &param.span, Target::Param, None);
1532
1533         intravisit::walk_param(self, param);
1534     }
1535 }
1536
1537 fn is_c_like_enum(item: &Item<'_>) -> bool {
1538     if let ItemKind::Enum(ref def, _) = item.kind {
1539         for variant in def.variants {
1540             match variant.data {
1541                 hir::VariantData::Unit(..) => { /* continue */ }
1542                 _ => return false,
1543             }
1544         }
1545         true
1546     } else {
1547         false
1548     }
1549 }
1550
1551 fn check_invalid_crate_level_attr(tcx: TyCtxt<'_>, attrs: &[Attribute]) {
1552     const ATTRS_TO_CHECK: &[Symbol] = &[
1553         sym::macro_export,
1554         sym::repr,
1555         sym::path,
1556         sym::automatically_derived,
1557         sym::start,
1558         sym::rustc_main,
1559     ];
1560
1561     for attr in attrs {
1562         for attr_to_check in ATTRS_TO_CHECK {
1563             if tcx.sess.check_name(attr, *attr_to_check) {
1564                 tcx.sess
1565                     .struct_span_err(
1566                         attr.span,
1567                         &format!(
1568                             "`{}` attribute cannot be used at crate level",
1569                             attr_to_check.to_ident_string()
1570                         ),
1571                     )
1572                     .emit();
1573             }
1574         }
1575     }
1576 }
1577
1578 fn check_invalid_macro_level_attr(tcx: TyCtxt<'_>, attrs: &[Attribute]) {
1579     for attr in attrs {
1580         if tcx.sess.check_name(attr, sym::inline) {
1581             struct_span_err!(
1582                 tcx.sess,
1583                 attr.span,
1584                 E0518,
1585                 "attribute should be applied to function or closure",
1586             )
1587             .span_label(attr.span, "not a function or closure")
1588             .emit();
1589         }
1590     }
1591 }
1592
1593 fn check_mod_attrs(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
1594     let check_attr_visitor = &mut CheckAttrVisitor { tcx };
1595     tcx.hir().visit_item_likes_in_module(module_def_id, &mut check_attr_visitor.as_deep_visitor());
1596     tcx.hir().visit_exported_macros_in_krate(check_attr_visitor);
1597     check_invalid_macro_level_attr(tcx, tcx.hir().krate().non_exported_macro_attrs);
1598     if module_def_id.is_top_level_module() {
1599         check_attr_visitor.check_attributes(CRATE_HIR_ID, &DUMMY_SP, Target::Mod, None);
1600         check_invalid_crate_level_attr(tcx, tcx.hir().krate_attrs());
1601     }
1602 }
1603
1604 pub(crate) fn provide(providers: &mut Providers) {
1605     *providers = Providers { check_mod_attrs, ..*providers };
1606 }