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_alias(attr, hir_id, target)
82 } else if self.tcx.sess.check_name(attr, sym::no_link) {
83 self.check_no_link(&attr, span, target)
84 } else if self.tcx.sess.check_name(attr, sym::export_name) {
85 self.check_export_name(&attr, span, target)
86 } else if self.tcx.sess.check_name(attr, sym::rustc_args_required_const) {
87 self.check_rustc_args_required_const(&attr, span, target, item)
90 if self.tcx.sess.check_name(attr, sym::cold) {
91 self.check_cold(hir_id, attr, span, target);
92 } else if self.tcx.sess.check_name(attr, sym::link_name) {
93 self.check_link_name(hir_id, attr, span, target);
94 } else if self.tcx.sess.check_name(attr, sym::link_section) {
95 self.check_link_section(hir_id, attr, span, target);
96 } else if self.tcx.sess.check_name(attr, sym::no_mangle) {
97 self.check_no_mangle(hir_id, attr, span, target);
107 if matches!(target, Target::Fn | Target::Method(_) | Target::ForeignFn) {
108 self.tcx.ensure().codegen_fn_attrs(self.tcx.hir().local_def_id(hir_id));
111 self.check_repr(attrs, span, target, item, hir_id);
112 self.check_used(attrs, target);
115 /// Checks if an `#[inline]` is applied to a function or a closure. Returns `true` if valid.
116 fn check_inline(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) -> bool {
120 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true,
121 Target::Method(MethodKind::Trait { body: false }) | Target::ForeignFn => {
122 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
123 lint.build("`#[inline]` is ignored on function prototypes").emit()
127 // FIXME(#65833): We permit associated consts to have an `#[inline]` attribute with
128 // just a lint, because we previously erroneously allowed it and some crates used it
129 // accidentally, to to be compatible with crates depending on them, we can't throw an
131 Target::AssocConst => {
132 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
133 lint.build("`#[inline]` is ignored on constants")
135 "this was previously accepted by the compiler but is \
136 being phased out; it will become a hard error in \
140 "see issue #65833 <https://github.com/rust-lang/rust/issues/65833> \
141 for more information",
152 "attribute should be applied to function or closure",
154 .span_label(*span, "not a function or closure")
161 /// Checks if a `#[track_caller]` is applied to a non-naked function. Returns `true` if valid.
162 fn check_track_caller(
165 attrs: &'hir [Attribute],
170 _ if self.tcx.sess.contains_name(attrs, sym::naked) => {
175 "cannot use `#[track_caller]` with `#[naked]`",
180 Target::Fn | Target::Method(..) | Target::ForeignFn | Target::Closure => true,
186 "attribute should be applied to function"
188 .span_label(*span, "not a function")
195 /// Checks if the `#[non_exhaustive]` attribute on an `item` is valid. Returns `true` if valid.
196 fn check_non_exhaustive(&self, attr: &Attribute, span: &Span, target: Target) -> bool {
198 Target::Struct | Target::Enum => true,
204 "attribute can only be applied to a struct or enum"
206 .span_label(*span, "not a struct or enum")
213 /// Checks if the `#[marker]` attribute on an `item` is valid. Returns `true` if valid.
214 fn check_marker(&self, attr: &Attribute, span: &Span, target: Target) -> bool {
216 Target::Trait => true,
220 .struct_span_err(attr.span, "attribute can only be applied to a trait")
221 .span_label(*span, "not a trait")
228 /// Checks if the `#[target_feature]` attribute on `item` is valid. Returns `true` if valid.
229 fn check_target_feature(
238 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true,
239 // FIXME: #[target_feature] was previously erroneously allowed on statements and some
240 // crates used this, so only emit a warning.
241 Target::Statement => {
242 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
243 lint.build("attribute should be applied to a function")
245 "this was previously accepted by the compiler but is \
246 being phased out; it will become a hard error in \
249 .span_label(*span, "not a function")
257 .struct_span_err(attr.span, "attribute should be applied to a function")
258 .span_label(*span, "not a function")
265 fn doc_alias_str_error(&self, meta: &NestedMetaItem) {
270 "doc alias attribute expects a string: #[doc(alias = \"0\")]",
275 fn check_doc_alias(&self, attr: &Attribute, hir_id: HirId, target: Target) -> bool {
276 if let Some(mi) = attr.meta() {
277 if let Some(list) = mi.meta_item_list() {
279 if meta.has_name(sym::alias) {
280 if !meta.is_value_str() {
281 self.doc_alias_str_error(meta);
285 meta.value_str().map(|s| s.to_string()).unwrap_or_else(String::new);
286 if doc_alias.is_empty() {
287 self.doc_alias_str_error(meta);
290 if let Some(c) = doc_alias
292 .find(|&c| c == '"' || c == '\'' || (c.is_whitespace() && c != ' '))
299 "{:?} character isn't allowed in `#[doc(alias = \"...\")]`",
306 if doc_alias.starts_with(' ') || doc_alias.ends_with(' ') {
311 "`#[doc(alias = \"...\")]` cannot start or end with ' '",
316 if let Some(err) = match target {
317 Target::Impl => Some("implementation block"),
318 Target::ForeignMod => Some("extern block"),
320 let parent_hir_id = self.tcx.hir().get_parent_item(hir_id);
321 let containing_item = self.tcx.hir().expect_item(parent_hir_id);
322 if Target::from_item(containing_item) == Target::Impl {
323 Some("type alias in implementation block")
328 Target::AssocConst => {
329 let parent_hir_id = self.tcx.hir().get_parent_item(hir_id);
330 let containing_item = self.tcx.hir().expect_item(parent_hir_id);
331 // We can't link to trait impl's consts.
332 let err = "associated constant in trait implementation block";
333 match containing_item.kind {
334 ItemKind::Impl { of_trait: Some(_), .. } => Some(err),
344 &format!("`#[doc(alias = \"...\")]` isn't allowed on {}", err),
349 if CRATE_HIR_ID == hir_id {
354 "`#![doc(alias = \"...\")]` isn't allowed as a crate \
367 /// Checks if `#[cold]` is applied to a non-function. Returns `true` if valid.
368 fn check_cold(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) {
370 Target::Fn | Target::Method(..) | Target::ForeignFn | Target::Closure => {}
372 // FIXME: #[cold] was previously allowed on non-functions and some crates used
373 // this, so only emit a warning.
374 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
375 lint.build("attribute should be applied to a function")
377 "this was previously accepted by the compiler but is \
378 being phased out; it will become a hard error in \
381 .span_label(*span, "not a function")
388 /// Checks if `#[link_name]` is applied to an item other than a foreign function or static.
389 fn check_link_name(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) {
391 Target::ForeignFn | Target::ForeignStatic => {}
393 // FIXME: #[cold] was previously allowed on non-functions/statics and some crates
394 // used this, so only emit a warning.
395 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
397 lint.build("attribute should be applied to a foreign function or static");
399 "this was previously accepted by the compiler but is \
400 being phased out; it will become a hard error in \
405 if let Target::ForeignMod = target {
406 if let Some(value) = attr.value_str() {
409 &format!(r#"try `#[link(name = "{}")]` instead"#, value),
412 diag.span_help(attr.span, r#"try `#[link(name = "...")]` instead"#);
416 diag.span_label(*span, "not a foreign function or static");
423 /// Checks if `#[no_link]` is applied to an `extern crate`. Returns `true` if valid.
424 fn check_no_link(&self, attr: &Attribute, span: &Span, target: Target) -> bool {
425 if target == Target::ExternCrate {
430 .struct_span_err(attr.span, "attribute should be applied to an `extern crate` item")
431 .span_label(*span, "not an `extern crate` item")
437 /// Checks if `#[export_name]` is applied to a function or static. Returns `true` if valid.
438 fn check_export_name(&self, attr: &Attribute, span: &Span, target: Target) -> bool {
440 Target::Static | Target::Fn | Target::Method(..) => true,
446 "attribute should be applied to a function or static",
448 .span_label(*span, "not a function or static")
455 /// Checks if `#[rustc_args_required_const]` is applied to a function and has a valid argument.
456 fn check_rustc_args_required_const(
461 item: Option<ItemLike<'_>>,
463 if let Target::Fn | Target::Method(..) | Target::ForeignFn = target {
464 let mut invalid_args = vec![];
465 for meta in attr.meta_item_list().expect("no meta item list") {
466 if let Some(LitKind::Int(val, _)) = meta.literal().map(|lit| &lit.kind) {
467 if let Some(ItemLike::Item(Item {
468 kind: ItemKind::Fn(FnSig { decl, .. }, ..),
471 | Some(ItemLike::ForeignItem(ForeignItem {
472 kind: ForeignItemKind::Fn(decl, ..),
476 let arg_count = decl.inputs.len() as u128;
477 if *val >= arg_count {
478 let span = meta.span();
481 .struct_span_err(span, "index exceeds number of arguments")
485 "there {} only {} argument{}",
486 if arg_count != 1 { "are" } else { "is" },
488 pluralize!(arg_count)
495 bug!("should be a function item");
498 invalid_args.push(meta.span());
501 if !invalid_args.is_empty() {
504 .struct_span_err(invalid_args, "arguments should be non-negative integers")
513 .struct_span_err(attr.span, "attribute should be applied to a function")
514 .span_label(*span, "not a function")
520 /// Checks if `#[link_section]` is applied to a function or static.
521 fn check_link_section(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) {
523 Target::Static | Target::Fn | Target::Method(..) => {}
525 // FIXME: #[link_section] was previously allowed on non-functions/statics and some
526 // crates used this, so only emit a warning.
527 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
528 lint.build("attribute should be applied to a function or static")
530 "this was previously accepted by the compiler but is \
531 being phased out; it will become a hard error in \
534 .span_label(*span, "not a function or static")
541 /// Checks if `#[no_mangle]` is applied to a function or static.
542 fn check_no_mangle(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) {
544 Target::Static | Target::Fn | Target::Method(..) => {}
546 // FIXME: #[no_mangle] was previously allowed on non-functions/statics and some
547 // crates used this, so only emit a warning.
548 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
549 lint.build("attribute should be applied to a function or static")
551 "this was previously accepted by the compiler but is \
552 being phased out; it will become a hard error in \
555 .span_label(*span, "not a function or static")
562 /// Checks if the `#[repr]` attributes on `item` are valid.
565 attrs: &'hir [Attribute],
568 item: Option<ItemLike<'_>>,
571 // Extract the names of all repr hints, e.g., [foo, bar, align] for:
574 // #[repr(bar, align(8))]
576 let hints: Vec<_> = attrs
578 .filter(|attr| self.tcx.sess.check_name(attr, sym::repr))
579 .filter_map(|attr| attr.meta_item_list())
583 let mut int_reprs = 0;
584 let mut is_c = false;
585 let mut is_simd = false;
586 let mut is_transparent = false;
589 let (article, allowed_targets) = match hint.name_or_empty() {
590 name @ sym::C | name @ sym::align => {
591 is_c |= name == sym::C;
593 Target::Struct | Target::Union | Target::Enum => continue,
594 _ => ("a", "struct, enum, or union"),
598 if target != Target::Struct && target != Target::Union {
599 ("a", "struct or union")
606 if target != Target::Struct {
612 sym::transparent => {
613 is_transparent = true;
615 Target::Struct | Target::Union | Target::Enum => continue,
616 _ => ("a", "struct, enum, or union"),
620 if !self.tcx.features().enabled(sym::no_niche) {
622 &self.tcx.sess.parse_sess,
625 "the attribute `repr(no_niche)` is currently unstable",
630 Target::Struct | Target::Enum => continue,
631 _ => ("a", "struct or enum"),
647 if target != Target::Enum {
655 self.emit_repr_error(
658 &format!("attribute should be applied to {}", allowed_targets),
659 &format!("not {} {}", article, allowed_targets),
663 // Just point at all repr hints if there are any incompatibilities.
664 // This is not ideal, but tracking precisely which ones are at fault is a huge hassle.
665 let hint_spans = hints.iter().map(|hint| hint.span());
667 // Error on repr(transparent, <anything else apart from no_niche>).
668 let non_no_niche = |hint: &&NestedMetaItem| hint.name_or_empty() != sym::no_niche;
669 let non_no_niche_count = hints.iter().filter(non_no_niche).count();
670 if is_transparent && non_no_niche_count > 1 {
671 let hint_spans: Vec<_> = hint_spans.clone().collect();
676 "transparent {} cannot have other repr hints",
681 // Warn on repr(u8, u16), repr(C, simd), and c-like-enum-repr(C, u8)
686 && item.map_or(false, |item| {
687 if let ItemLike::Item(item) = item {
688 return is_c_like_enum(item);
693 self.tcx.struct_span_lint_hir(
694 CONFLICTING_REPR_HINTS,
696 hint_spans.collect::<Vec<Span>>(),
698 lint.build("conflicting representation hints")
699 .code(rustc_errors::error_code!(E0566))
713 struct_span_err!(self.tcx.sess, hint_span, E0517, "{}", hint_message)
714 .span_label(label_span, label_message)
718 fn check_stmt_attributes(&self, stmt: &hir::Stmt<'_>) {
719 // When checking statements ignore expressions, they will be checked later
720 if let hir::StmtKind::Local(ref l) = stmt.kind {
721 self.check_attributes(l.hir_id, &l.attrs, &stmt.span, Target::Statement, None);
722 for attr in l.attrs.iter() {
723 if self.tcx.sess.check_name(attr, sym::repr) {
724 self.emit_repr_error(
727 "attribute should not be applied to a statement",
728 "not a struct, enum, or union",
735 fn check_expr_attributes(&self, expr: &hir::Expr<'_>) {
736 let target = match expr.kind {
737 hir::ExprKind::Closure(..) => Target::Closure,
738 _ => Target::Expression,
740 self.check_attributes(expr.hir_id, &expr.attrs, &expr.span, target, None);
741 for attr in expr.attrs.iter() {
742 if self.tcx.sess.check_name(attr, sym::repr) {
743 self.emit_repr_error(
746 "attribute should not be applied to an expression",
747 "not defining a struct, enum, or union",
751 if target == Target::Closure {
752 self.tcx.ensure().codegen_fn_attrs(self.tcx.hir().local_def_id(expr.hir_id));
756 fn check_used(&self, attrs: &'hir [Attribute], target: Target) {
758 if self.tcx.sess.check_name(attr, sym::used) && target != Target::Static {
761 .span_err(attr.span, "attribute must be applied to a `static` variable");
767 impl Visitor<'tcx> for CheckAttrVisitor<'tcx> {
768 type Map = Map<'tcx>;
770 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
771 NestedVisitorMap::OnlyBodies(self.tcx.hir())
774 fn visit_item(&mut self, item: &'tcx Item<'tcx>) {
775 let target = Target::from_item(item);
776 self.check_attributes(
781 Some(ItemLike::Item(item)),
783 intravisit::walk_item(self, item)
786 fn visit_trait_item(&mut self, trait_item: &'tcx TraitItem<'tcx>) {
787 let target = Target::from_trait_item(trait_item);
788 self.check_attributes(trait_item.hir_id, &trait_item.attrs, &trait_item.span, target, None);
789 intravisit::walk_trait_item(self, trait_item)
792 fn visit_foreign_item(&mut self, f_item: &'tcx ForeignItem<'tcx>) {
793 let target = Target::from_foreign_item(f_item);
794 self.check_attributes(
799 Some(ItemLike::ForeignItem(f_item)),
801 intravisit::walk_foreign_item(self, f_item)
804 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
805 let target = target_from_impl_item(self.tcx, impl_item);
806 self.check_attributes(impl_item.hir_id, &impl_item.attrs, &impl_item.span, target, None);
807 intravisit::walk_impl_item(self, impl_item)
810 fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt<'tcx>) {
811 self.check_stmt_attributes(stmt);
812 intravisit::walk_stmt(self, stmt)
815 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
816 self.check_expr_attributes(expr);
817 intravisit::walk_expr(self, expr)
821 fn is_c_like_enum(item: &Item<'_>) -> bool {
822 if let ItemKind::Enum(ref def, _) = item.kind {
823 for variant in def.variants {
825 hir::VariantData::Unit(..) => { /* continue */ }
835 fn check_invalid_crate_level_attr(tcx: TyCtxt<'_>, attrs: &[Attribute]) {
836 const ATTRS_TO_CHECK: &[Symbol] = &[
840 sym::automatically_derived,
846 for attr_to_check in ATTRS_TO_CHECK {
847 if tcx.sess.check_name(attr, *attr_to_check) {
852 "`{}` attribute cannot be used at crate level",
853 attr_to_check.to_ident_string()
862 fn check_mod_attrs(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
864 .visit_item_likes_in_module(module_def_id, &mut CheckAttrVisitor { tcx }.as_deep_visitor());
865 if module_def_id.is_top_level_module() {
866 CheckAttrVisitor { tcx }.check_attributes(
868 tcx.hir().krate_attrs(),
873 check_invalid_crate_level_attr(tcx, tcx.hir().krate_attrs());
877 pub(crate) fn provide(providers: &mut Providers) {
878 *providers = Providers { check_mod_attrs, ..*providers };