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
7 use rustc_middle::hir::map::Map;
8 use rustc_middle::ty::query::Providers;
9 use rustc_middle::ty::TyCtxt;
11 use rustc_ast::{Attribute, LitKind, NestedMetaItem};
12 use rustc_errors::{pluralize, struct_span_err};
14 use rustc_hir::def_id::LocalDefId;
15 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
17 self, FnSig, ForeignItem, ForeignItemKind, HirId, Item, ItemKind, TraitItem, CRATE_HIR_ID,
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};
25 pub(crate) fn target_from_impl_item<'tcx>(
27 impl_item: &hir::ImplItem<'_>,
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"),
38 if containing_impl_is_for_trait {
39 Target::Method(MethodKind::Trait { body: true })
41 Target::Method(MethodKind::Inherent)
44 hir::ImplItemKind::TyAlias(..) => Target::AssocTy,
48 #[derive(Clone, Copy)]
50 Item(&'tcx Item<'tcx>),
51 ForeignItem(&'tcx ForeignItem<'tcx>),
54 struct CheckAttrVisitor<'tcx> {
58 impl CheckAttrVisitor<'tcx> {
59 /// Checks any attribute.
63 attrs: &'hir [Attribute],
66 item: Option<ItemLike<'_>>,
68 let mut is_valid = true;
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_attrs(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 if self.tcx.sess.check_name(attr, sym::allow_internal_unstable) {
89 self.check_allow_internal_unstable(&attr, span, target, &attrs)
90 } else if self.tcx.sess.check_name(attr, sym::rustc_allow_const_fn_unstable) {
91 self.check_rustc_allow_const_fn_unstable(hir_id, &attr, span, target)
92 } else if self.tcx.sess.check_name(attr, sym::naked) {
93 self.check_naked(attr, span, target)
96 if self.tcx.sess.check_name(attr, sym::cold) {
97 self.check_cold(hir_id, attr, span, target);
98 } else if self.tcx.sess.check_name(attr, sym::link_name) {
99 self.check_link_name(hir_id, attr, span, target);
100 } else if self.tcx.sess.check_name(attr, sym::link_section) {
101 self.check_link_section(hir_id, attr, span, target);
102 } else if self.tcx.sess.check_name(attr, sym::no_mangle) {
103 self.check_no_mangle(hir_id, attr, span, target);
113 if matches!(target, Target::Closure | Target::Fn | Target::Method(_) | Target::ForeignFn) {
114 self.tcx.ensure().codegen_fn_attrs(self.tcx.hir().local_def_id(hir_id));
117 self.check_repr(attrs, span, target, item, hir_id);
118 self.check_used(attrs, target);
121 /// Checks if an `#[inline]` is applied to a function or a closure. Returns `true` if valid.
122 fn check_inline(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) -> bool {
126 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true,
127 Target::Method(MethodKind::Trait { body: false }) | Target::ForeignFn => {
128 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
129 lint.build("`#[inline]` is ignored on function prototypes").emit()
133 // FIXME(#65833): We permit associated consts to have an `#[inline]` attribute with
134 // just a lint, because we previously erroneously allowed it and some crates used it
135 // accidentally, to to be compatible with crates depending on them, we can't throw an
137 Target::AssocConst => {
138 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
139 lint.build("`#[inline]` is ignored on constants")
141 "this was previously accepted by the compiler but is \
142 being phased out; it will become a hard error in \
146 "see issue #65833 <https://github.com/rust-lang/rust/issues/65833> \
147 for more information",
158 "attribute should be applied to function or closure",
160 .span_label(*span, "not a function or closure")
167 /// Checks if `#[naked]` is applied to a function definition.
168 fn check_naked(&self, attr: &Attribute, span: &Span, target: Target) -> bool {
171 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true,
177 "attribute should be applied to a function definition",
179 .span_label(*span, "not a function definition")
186 /// Checks if a `#[track_caller]` is applied to a non-naked function. Returns `true` if valid.
187 fn check_track_caller(
190 attrs: &'hir [Attribute],
195 _ if attrs.iter().any(|attr| attr.has_name(sym::naked)) => {
200 "cannot use `#[track_caller]` with `#[naked]`",
205 Target::Fn | Target::Method(..) | Target::ForeignFn | Target::Closure => true,
211 "attribute should be applied to function"
213 .span_label(*span, "not a function")
220 /// Checks if the `#[non_exhaustive]` attribute on an `item` is valid. Returns `true` if valid.
221 fn check_non_exhaustive(&self, attr: &Attribute, span: &Span, target: Target) -> bool {
223 Target::Struct | Target::Enum | Target::Variant => true,
229 "attribute can only be applied to a struct or enum"
231 .span_label(*span, "not a struct or enum")
238 /// Checks if the `#[marker]` attribute on an `item` is valid. Returns `true` if valid.
239 fn check_marker(&self, attr: &Attribute, span: &Span, target: Target) -> bool {
241 Target::Trait => true,
245 .struct_span_err(attr.span, "attribute can only be applied to a trait")
246 .span_label(*span, "not a trait")
253 /// Checks if the `#[target_feature]` attribute on `item` is valid. Returns `true` if valid.
254 fn check_target_feature(
263 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true,
264 // FIXME: #[target_feature] was previously erroneously allowed on statements and some
265 // crates used this, so only emit a warning.
266 Target::Statement => {
267 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
268 lint.build("attribute should be applied to a function")
270 "this was previously accepted by the compiler but is \
271 being phased out; it will become a hard error in \
274 .span_label(*span, "not a function")
282 .struct_span_err(attr.span, "attribute should be applied to a function")
283 .span_label(*span, "not a function")
290 fn doc_attr_str_error(&self, meta: &NestedMetaItem, attr_name: &str) {
295 &format!("doc {0} attribute expects a string: #[doc({0} = \"a\")]", attr_name),
300 fn check_doc_alias(&self, meta: &NestedMetaItem, hir_id: HirId, target: Target) -> bool {
301 let doc_alias = meta.value_str().map(|s| s.to_string()).unwrap_or_else(String::new);
302 if doc_alias.is_empty() {
303 self.doc_attr_str_error(meta, "alias");
307 doc_alias.chars().find(|&c| c == '"' || c == '\'' || (c.is_whitespace() && c != ' '))
312 meta.name_value_literal_span().unwrap_or_else(|| meta.span()),
313 &format!("{:?} character isn't allowed in `#[doc(alias = \"...\")]`", c,),
318 if doc_alias.starts_with(' ') || doc_alias.ends_with(' ') {
322 meta.name_value_literal_span().unwrap_or_else(|| meta.span()),
323 "`#[doc(alias = \"...\")]` cannot start or end with ' '",
328 if let Some(err) = match target {
329 Target::Impl => Some("implementation block"),
330 Target::ForeignMod => Some("extern block"),
332 let parent_hir_id = self.tcx.hir().get_parent_item(hir_id);
333 let containing_item = self.tcx.hir().expect_item(parent_hir_id);
334 if Target::from_item(containing_item) == Target::Impl {
335 Some("type alias in implementation block")
340 Target::AssocConst => {
341 let parent_hir_id = self.tcx.hir().get_parent_item(hir_id);
342 let containing_item = self.tcx.hir().expect_item(parent_hir_id);
343 // We can't link to trait impl's consts.
344 let err = "associated constant in trait implementation block";
345 match containing_item.kind {
346 ItemKind::Impl { of_trait: Some(_), .. } => Some(err),
356 &format!("`#[doc(alias = \"...\")]` isn't allowed on {}", err),
364 fn check_doc_keyword(&self, meta: &NestedMetaItem, hir_id: HirId) -> bool {
365 let doc_keyword = meta.value_str().map(|s| s.to_string()).unwrap_or_else(String::new);
366 if doc_keyword.is_empty() {
367 self.doc_attr_str_error(meta, "keyword");
370 match self.tcx.hir().expect_item(hir_id).kind {
371 ItemKind::Mod(ref module) => {
372 if !module.item_ids.is_empty() {
377 "`#[doc(keyword = \"...\")]` can only be used on empty modules",
388 "`#[doc(keyword = \"...\")]` can only be used on modules",
394 if !rustc_lexer::is_ident(&doc_keyword) {
398 meta.name_value_literal_span().unwrap_or_else(|| meta.span()),
399 &format!("`{}` is not a valid identifier", doc_keyword),
407 fn check_attr_crate_level(
409 meta: &NestedMetaItem,
413 if CRATE_HIR_ID == hir_id {
419 "`#![doc({} = \"...\")]` isn't allowed as a crate level attribute",
429 fn check_doc_attrs(&self, attr: &Attribute, hir_id: HirId, target: Target) -> bool {
430 if let Some(mi) = attr.meta() {
431 if let Some(list) = mi.meta_item_list() {
433 if meta.has_name(sym::alias) {
434 if !self.check_attr_crate_level(meta, hir_id, "alias")
435 || !self.check_doc_alias(meta, hir_id, target)
439 } else if meta.has_name(sym::keyword) {
440 if !self.check_attr_crate_level(meta, hir_id, "keyword")
441 || !self.check_doc_keyword(meta, hir_id)
452 /// Checks if `#[cold]` is applied to a non-function. Returns `true` if valid.
453 fn check_cold(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) {
455 Target::Fn | Target::Method(..) | Target::ForeignFn | Target::Closure => {}
457 // FIXME: #[cold] was previously allowed on non-functions and some crates used
458 // this, so only emit a warning.
459 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
460 lint.build("attribute should be applied to a function")
462 "this was previously accepted by the compiler but is \
463 being phased out; it will become a hard error in \
466 .span_label(*span, "not a function")
473 /// Checks if `#[link_name]` is applied to an item other than a foreign function or static.
474 fn check_link_name(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) {
476 Target::ForeignFn | Target::ForeignStatic => {}
478 // FIXME: #[cold] was previously allowed on non-functions/statics and some crates
479 // used this, so only emit a warning.
480 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
482 lint.build("attribute should be applied to a foreign function or static");
484 "this was previously accepted by the compiler but is \
485 being phased out; it will become a hard error in \
490 if let Target::ForeignMod = target {
491 if let Some(value) = attr.value_str() {
494 &format!(r#"try `#[link(name = "{}")]` instead"#, value),
497 diag.span_help(attr.span, r#"try `#[link(name = "...")]` instead"#);
501 diag.span_label(*span, "not a foreign function or static");
508 /// Checks if `#[no_link]` is applied to an `extern crate`. Returns `true` if valid.
509 fn check_no_link(&self, attr: &Attribute, span: &Span, target: Target) -> bool {
510 if target == Target::ExternCrate {
515 .struct_span_err(attr.span, "attribute should be applied to an `extern crate` item")
516 .span_label(*span, "not an `extern crate` item")
522 /// Checks if `#[export_name]` is applied to a function or static. Returns `true` if valid.
523 fn check_export_name(&self, attr: &Attribute, span: &Span, target: Target) -> bool {
525 Target::Static | Target::Fn | Target::Method(..) => true,
531 "attribute should be applied to a function or static",
533 .span_label(*span, "not a function or static")
540 /// Checks if `#[rustc_args_required_const]` is applied to a function and has a valid argument.
541 fn check_rustc_args_required_const(
546 item: Option<ItemLike<'_>>,
548 let is_function = matches!(target, Target::Fn | Target::Method(..) | Target::ForeignFn);
552 .struct_span_err(attr.span, "attribute should be applied to a function")
553 .span_label(*span, "not a function")
558 let list = match attr.meta_item_list() {
559 // The attribute form is validated on AST.
560 None => return false,
564 let mut invalid_args = vec![];
566 if let Some(LitKind::Int(val, _)) = meta.literal().map(|lit| &lit.kind) {
567 if let Some(ItemLike::Item(Item {
568 kind: ItemKind::Fn(FnSig { decl, .. }, ..),
571 | Some(ItemLike::ForeignItem(ForeignItem {
572 kind: ForeignItemKind::Fn(decl, ..),
576 let arg_count = decl.inputs.len() as u128;
577 if *val >= arg_count {
578 let span = meta.span();
581 .struct_span_err(span, "index exceeds number of arguments")
585 "there {} only {} argument{}",
586 if arg_count != 1 { "are" } else { "is" },
588 pluralize!(arg_count)
595 bug!("should be a function item");
598 invalid_args.push(meta.span());
602 if !invalid_args.is_empty() {
605 .struct_span_err(invalid_args, "arguments should be non-negative integers")
613 /// Checks if `#[link_section]` is applied to a function or static.
614 fn check_link_section(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) {
616 Target::Static | Target::Fn | Target::Method(..) => {}
618 // FIXME: #[link_section] was previously allowed on non-functions/statics and some
619 // crates used this, so only emit a warning.
620 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
621 lint.build("attribute should be applied to a function or static")
623 "this was previously accepted by the compiler but is \
624 being phased out; it will become a hard error in \
627 .span_label(*span, "not a function or static")
634 /// Checks if `#[no_mangle]` is applied to a function or static.
635 fn check_no_mangle(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) {
637 Target::Static | Target::Fn | Target::Method(..) => {}
639 // FIXME: #[no_mangle] was previously allowed on non-functions/statics and some
640 // crates used this, so only emit a warning.
641 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
642 lint.build("attribute should be applied to a function or static")
644 "this was previously accepted by the compiler but is \
645 being phased out; it will become a hard error in \
648 .span_label(*span, "not a function or static")
655 /// Checks if the `#[repr]` attributes on `item` are valid.
658 attrs: &'hir [Attribute],
661 item: Option<ItemLike<'_>>,
664 // Extract the names of all repr hints, e.g., [foo, bar, align] for:
667 // #[repr(bar, align(8))]
669 let hints: Vec<_> = attrs
671 .filter(|attr| self.tcx.sess.check_name(attr, sym::repr))
672 .filter_map(|attr| attr.meta_item_list())
676 let mut int_reprs = 0;
677 let mut is_c = false;
678 let mut is_simd = false;
679 let mut is_transparent = false;
682 let (article, allowed_targets) = match hint.name_or_empty() {
683 _ if !matches!(target, Target::Struct | Target::Enum | Target::Union) => {
684 ("a", "struct, enum, or union")
686 name @ sym::C | name @ sym::align => {
687 is_c |= name == sym::C;
689 Target::Struct | Target::Union | Target::Enum => continue,
690 _ => ("a", "struct, enum, or union"),
694 if target != Target::Struct && target != Target::Union {
695 ("a", "struct or union")
702 if target != Target::Struct {
708 sym::transparent => {
709 is_transparent = true;
711 Target::Struct | Target::Union | Target::Enum => continue,
712 _ => ("a", "struct, enum, or union"),
716 if !self.tcx.features().enabled(sym::no_niche) {
718 &self.tcx.sess.parse_sess,
721 "the attribute `repr(no_niche)` is currently unstable",
726 Target::Struct | Target::Enum => continue,
727 _ => ("a", "struct or enum"),
743 if target != Target::Enum {
757 &format!("attribute should be applied to {} {}", article, allowed_targets)
759 .span_label(*span, &format!("not {} {}", article, allowed_targets))
763 // Just point at all repr hints if there are any incompatibilities.
764 // This is not ideal, but tracking precisely which ones are at fault is a huge hassle.
765 let hint_spans = hints.iter().map(|hint| hint.span());
767 // Error on repr(transparent, <anything else apart from no_niche>).
768 let non_no_niche = |hint: &&NestedMetaItem| hint.name_or_empty() != sym::no_niche;
769 let non_no_niche_count = hints.iter().filter(non_no_niche).count();
770 if is_transparent && non_no_niche_count > 1 {
771 let hint_spans: Vec<_> = hint_spans.clone().collect();
776 "transparent {} cannot have other repr hints",
781 // Warn on repr(u8, u16), repr(C, simd), and c-like-enum-repr(C, u8)
786 && item.map_or(false, |item| {
787 if let ItemLike::Item(item) = item {
788 return is_c_like_enum(item);
793 self.tcx.struct_span_lint_hir(
794 CONFLICTING_REPR_HINTS,
796 hint_spans.collect::<Vec<Span>>(),
798 lint.build("conflicting representation hints")
799 .code(rustc_errors::error_code!(E0566))
806 fn check_used(&self, attrs: &'hir [Attribute], target: Target) {
808 if self.tcx.sess.check_name(attr, sym::used) && target != Target::Static {
811 .span_err(attr.span, "attribute must be applied to a `static` variable");
816 /// Outputs an error for `#[allow_internal_unstable]` which can only be applied to macros.
817 /// (Allows proc_macro functions)
818 fn check_allow_internal_unstable(
825 debug!("Checking target: {:?}", target);
826 if target == Target::Fn {
828 if self.tcx.sess.is_proc_macro_attr(attr) {
829 debug!("Is proc macro attr");
833 debug!("Is not proc macro attr");
837 .struct_span_err(attr.span, "attribute should be applied to a macro")
838 .span_label(*span, "not a macro")
843 /// Outputs an error for `#[allow_internal_unstable]` which can only be applied to macros.
844 /// (Allows proc_macro functions)
845 fn check_rustc_allow_const_fn_unstable(
852 if let Target::Fn | Target::Method(_) = target {
853 if self.tcx.is_const_fn_raw(self.tcx.hir().local_def_id(hir_id)) {
859 .struct_span_err(attr.span, "attribute should be applied to `const fn`")
860 .span_label(*span, "not a `const fn`")
866 impl Visitor<'tcx> for CheckAttrVisitor<'tcx> {
867 type Map = Map<'tcx>;
869 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
870 NestedVisitorMap::OnlyBodies(self.tcx.hir())
873 fn visit_item(&mut self, item: &'tcx Item<'tcx>) {
874 let target = Target::from_item(item);
875 self.check_attributes(
880 Some(ItemLike::Item(item)),
882 intravisit::walk_item(self, item)
885 fn visit_trait_item(&mut self, trait_item: &'tcx TraitItem<'tcx>) {
886 let target = Target::from_trait_item(trait_item);
887 self.check_attributes(trait_item.hir_id, &trait_item.attrs, &trait_item.span, target, None);
888 intravisit::walk_trait_item(self, trait_item)
891 fn visit_foreign_item(&mut self, f_item: &'tcx ForeignItem<'tcx>) {
892 let target = Target::from_foreign_item(f_item);
893 self.check_attributes(
898 Some(ItemLike::ForeignItem(f_item)),
900 intravisit::walk_foreign_item(self, f_item)
903 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
904 let target = target_from_impl_item(self.tcx, impl_item);
905 self.check_attributes(impl_item.hir_id, &impl_item.attrs, &impl_item.span, target, None);
906 intravisit::walk_impl_item(self, impl_item)
909 fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt<'tcx>) {
910 // When checking statements ignore expressions, they will be checked later.
911 if let hir::StmtKind::Local(ref l) = stmt.kind {
912 self.check_attributes(l.hir_id, &l.attrs, &stmt.span, Target::Statement, None);
914 intravisit::walk_stmt(self, stmt)
917 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
918 let target = match expr.kind {
919 hir::ExprKind::Closure(..) => Target::Closure,
920 _ => Target::Expression,
923 self.check_attributes(expr.hir_id, &expr.attrs, &expr.span, target, None);
924 intravisit::walk_expr(self, expr)
929 variant: &'tcx hir::Variant<'tcx>,
930 generics: &'tcx hir::Generics<'tcx>,
933 self.check_attributes(variant.id, variant.attrs, &variant.span, Target::Variant, None);
934 intravisit::walk_variant(self, variant, generics, item_id)
938 fn is_c_like_enum(item: &Item<'_>) -> bool {
939 if let ItemKind::Enum(ref def, _) = item.kind {
940 for variant in def.variants {
942 hir::VariantData::Unit(..) => { /* continue */ }
952 fn check_invalid_crate_level_attr(tcx: TyCtxt<'_>, attrs: &[Attribute]) {
953 const ATTRS_TO_CHECK: &[Symbol] = &[
957 sym::automatically_derived,
963 for attr_to_check in ATTRS_TO_CHECK {
964 if tcx.sess.check_name(attr, *attr_to_check) {
969 "`{}` attribute cannot be used at crate level",
970 attr_to_check.to_ident_string()
979 fn check_mod_attrs(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
981 .visit_item_likes_in_module(module_def_id, &mut CheckAttrVisitor { tcx }.as_deep_visitor());
982 if module_def_id.is_top_level_module() {
983 CheckAttrVisitor { tcx }.check_attributes(
985 tcx.hir().krate_attrs(),
990 check_invalid_crate_level_attr(tcx, tcx.hir().krate_attrs());
994 pub(crate) fn provide(providers: &mut Providers) {
995 *providers = Providers { check_mod_attrs, ..*providers };