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::ast::{Attribute, NestedMetaItem};
13 use rustc_errors::struct_span_err;
15 use rustc_hir::def_id::DefId;
16 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
17 use rustc_hir::{self, HirId, Item, ItemKind, TraitItem};
18 use rustc_hir::{MethodKind, Target};
19 use rustc_session::lint::builtin::{CONFLICTING_REPR_HINTS, UNUSED_ATTRIBUTES};
20 use rustc_session::parse::feature_err;
21 use rustc_span::symbol::sym;
24 fn target_from_impl_item<'tcx>(tcx: TyCtxt<'tcx>, impl_item: &hir::ImplItem<'_>) -> Target {
25 match impl_item.kind {
26 hir::ImplItemKind::Const(..) => Target::AssocConst,
27 hir::ImplItemKind::Fn(..) => {
28 let parent_hir_id = tcx.hir().get_parent_item(impl_item.hir_id);
29 let containing_item = tcx.hir().expect_item(parent_hir_id);
30 let containing_impl_is_for_trait = match &containing_item.kind {
31 hir::ItemKind::Impl { ref of_trait, .. } => of_trait.is_some(),
32 _ => bug!("parent of an ImplItem must be an Impl"),
34 if containing_impl_is_for_trait {
35 Target::Method(MethodKind::Trait { body: true })
37 Target::Method(MethodKind::Inherent)
40 hir::ImplItemKind::TyAlias(..) | hir::ImplItemKind::OpaqueTy(..) => Target::AssocTy,
44 struct CheckAttrVisitor<'tcx> {
48 impl CheckAttrVisitor<'tcx> {
49 /// Checks any attribute.
53 attrs: &'hir [Attribute],
56 item: Option<&Item<'_>>,
58 let mut is_valid = true;
60 is_valid &= if attr.check_name(sym::inline) {
61 self.check_inline(hir_id, attr, span, target)
62 } else if attr.check_name(sym::non_exhaustive) {
63 self.check_non_exhaustive(attr, span, target)
64 } else if attr.check_name(sym::marker) {
65 self.check_marker(attr, span, target)
66 } else if attr.check_name(sym::target_feature) {
67 self.check_target_feature(attr, span, target)
68 } else if attr.check_name(sym::track_caller) {
69 self.check_track_caller(&attr.span, attrs, span, target)
79 if target == Target::Fn {
80 self.tcx.codegen_fn_attrs(self.tcx.hir().local_def_id(hir_id));
83 self.check_repr(attrs, span, target, item, hir_id);
84 self.check_used(attrs, target);
87 /// Checks if an `#[inline]` is applied to a function or a closure. Returns `true` if valid.
88 fn check_inline(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) -> bool {
92 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true,
93 Target::Method(MethodKind::Trait { body: false }) | Target::ForeignFn => {
94 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
95 lint.build("`#[inline]` is ignored on function prototypes").emit()
99 // FIXME(#65833): We permit associated consts to have an `#[inline]` attribute with
100 // just a lint, because we previously erroneously allowed it and some crates used it
101 // accidentally, to to be compatible with crates depending on them, we can't throw an
103 Target::AssocConst => {
104 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
105 lint.build("`#[inline]` is ignored on constants")
107 "this was previously accepted by the compiler but is \
108 being phased out; it will become a hard error in \
112 "see issue #65833 <https://github.com/rust-lang/rust/issues/65833> \
113 for more information",
124 "attribute should be applied to function or closure",
126 .span_label(*span, "not a function or closure")
133 /// Checks if a `#[track_caller]` is applied to a non-naked function. Returns `true` if valid.
134 fn check_track_caller(
137 attrs: &'hir [Attribute],
142 _ if attr::contains_name(attrs, sym::naked) => {
147 "cannot use `#[track_caller]` with `#[naked]`",
152 Target::Fn | Target::Method(..) | Target::ForeignFn => true,
158 "attribute should be applied to function"
160 .span_label(*span, "not a function")
167 /// Checks if the `#[non_exhaustive]` attribute on an `item` is valid. Returns `true` if valid.
168 fn check_non_exhaustive(&self, attr: &Attribute, span: &Span, target: Target) -> bool {
170 Target::Struct | Target::Enum => true,
176 "attribute can only be applied to a struct or enum"
178 .span_label(*span, "not a struct or enum")
185 /// Checks if the `#[marker]` attribute on an `item` is valid. Returns `true` if valid.
186 fn check_marker(&self, attr: &Attribute, span: &Span, target: Target) -> bool {
188 Target::Trait => true,
192 .struct_span_err(attr.span, "attribute can only be applied to a trait")
193 .span_label(*span, "not a trait")
200 /// Checks if the `#[target_feature]` attribute on `item` is valid. Returns `true` if valid.
201 fn check_target_feature(&self, attr: &Attribute, span: &Span, target: Target) -> bool {
204 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true,
208 .struct_span_err(attr.span, "attribute should be applied to a function")
209 .span_label(*span, "not a function")
216 /// Checks if the `#[repr]` attributes on `item` are valid.
219 attrs: &'hir [Attribute],
222 item: Option<&Item<'_>>,
225 // Extract the names of all repr hints, e.g., [foo, bar, align] for:
228 // #[repr(bar, align(8))]
230 let hints: Vec<_> = attrs
232 .filter(|attr| attr.check_name(sym::repr))
233 .filter_map(|attr| attr.meta_item_list())
237 let mut int_reprs = 0;
238 let mut is_c = false;
239 let mut is_simd = false;
240 let mut is_transparent = false;
243 let (article, allowed_targets) = match hint.name_or_empty() {
244 name @ sym::C | name @ sym::align => {
245 is_c |= name == sym::C;
247 Target::Struct | Target::Union | Target::Enum => continue,
248 _ => ("a", "struct, enum, or union"),
252 if target != Target::Struct && target != Target::Union {
253 ("a", "struct or union")
260 if target != Target::Struct { ("a", "struct") } else { continue }
262 sym::transparent => {
263 is_transparent = true;
265 Target::Struct | Target::Union | Target::Enum => continue,
266 _ => ("a", "struct, enum, or union"),
270 if !self.tcx.features().enabled(sym::no_niche) {
272 &self.tcx.sess.parse_sess,
275 "the attribute `repr(no_niche)` is currently unstable",
280 Target::Struct | Target::Enum => continue,
281 _ => ("a", "struct or enum"),
295 if target != Target::Enum { ("an", "enum") } else { continue }
299 self.emit_repr_error(
302 &format!("attribute should be applied to {}", allowed_targets),
303 &format!("not {} {}", article, allowed_targets),
307 // Just point at all repr hints if there are any incompatibilities.
308 // This is not ideal, but tracking precisely which ones are at fault is a huge hassle.
309 let hint_spans = hints.iter().map(|hint| hint.span());
311 // Error on repr(transparent, <anything else apart from no_niche>).
312 let non_no_niche = |hint: &&NestedMetaItem| hint.name_or_empty() != sym::no_niche;
313 let non_no_niche_count = hints.iter().filter(non_no_niche).count();
314 if is_transparent && non_no_niche_count > 1 {
315 let hint_spans: Vec<_> = hint_spans.clone().collect();
320 "transparent {} cannot have other repr hints",
325 // Warn on repr(u8, u16), repr(C, simd), and c-like-enum-repr(C, u8)
328 || (int_reprs == 1 && is_c && item.map_or(false, |item| is_c_like_enum(item)))
330 self.tcx.struct_span_lint_hir(
331 CONFLICTING_REPR_HINTS,
333 hint_spans.collect::<Vec<Span>>(),
335 lint.build("conflicting representation hints")
336 .code(rustc_errors::error_code!(E0566))
350 struct_span_err!(self.tcx.sess, hint_span, E0517, "{}", hint_message)
351 .span_label(label_span, label_message)
355 fn check_stmt_attributes(&self, stmt: &hir::Stmt<'_>) {
356 // When checking statements ignore expressions, they will be checked later
357 if let hir::StmtKind::Local(ref l) = stmt.kind {
358 for attr in l.attrs.iter() {
359 if attr.check_name(sym::inline) {
360 self.check_inline(l.hir_id, attr, &stmt.span, Target::Statement);
362 if attr.check_name(sym::repr) {
363 self.emit_repr_error(
366 "attribute should not be applied to a statement",
367 "not a struct, enum, or union",
374 fn check_expr_attributes(&self, expr: &hir::Expr<'_>) {
375 let target = match expr.kind {
376 hir::ExprKind::Closure(..) => Target::Closure,
377 _ => Target::Expression,
379 for attr in expr.attrs.iter() {
380 if attr.check_name(sym::inline) {
381 self.check_inline(expr.hir_id, attr, &expr.span, target);
383 if attr.check_name(sym::repr) {
384 self.emit_repr_error(
387 "attribute should not be applied to an expression",
388 "not defining a struct, enum, or union",
394 fn check_used(&self, attrs: &'hir [Attribute], target: Target) {
396 if attr.check_name(sym::used) && target != Target::Static {
399 .span_err(attr.span, "attribute must be applied to a `static` variable");
405 impl Visitor<'tcx> for CheckAttrVisitor<'tcx> {
406 type Map = Map<'tcx>;
408 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
409 NestedVisitorMap::OnlyBodies(self.tcx.hir())
412 fn visit_item(&mut self, item: &'tcx Item<'tcx>) {
413 let target = Target::from_item(item);
414 self.check_attributes(item.hir_id, item.attrs, &item.span, target, Some(item));
415 intravisit::walk_item(self, item)
418 fn visit_trait_item(&mut self, trait_item: &'tcx TraitItem<'tcx>) {
419 let target = Target::from_trait_item(trait_item);
420 self.check_attributes(trait_item.hir_id, &trait_item.attrs, &trait_item.span, target, None);
421 intravisit::walk_trait_item(self, trait_item)
424 fn visit_foreign_item(&mut self, f_item: &'tcx hir::ForeignItem<'tcx>) {
425 let target = Target::from_foreign_item(f_item);
426 self.check_attributes(f_item.hir_id, &f_item.attrs, &f_item.span, target, None);
427 intravisit::walk_foreign_item(self, f_item)
430 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
431 let target = target_from_impl_item(self.tcx, impl_item);
432 self.check_attributes(impl_item.hir_id, &impl_item.attrs, &impl_item.span, target, None);
433 intravisit::walk_impl_item(self, impl_item)
436 fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt<'tcx>) {
437 self.check_stmt_attributes(stmt);
438 intravisit::walk_stmt(self, stmt)
441 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
442 self.check_expr_attributes(expr);
443 intravisit::walk_expr(self, expr)
447 fn is_c_like_enum(item: &Item<'_>) -> bool {
448 if let ItemKind::Enum(ref def, _) = item.kind {
449 for variant in def.variants {
451 hir::VariantData::Unit(..) => { /* continue */ }
461 fn check_mod_attrs(tcx: TyCtxt<'_>, module_def_id: DefId) {
463 .visit_item_likes_in_module(module_def_id, &mut CheckAttrVisitor { tcx }.as_deep_visitor());
466 pub(crate) fn provide(providers: &mut Providers<'_>) {
467 *providers = Providers { check_mod_attrs, ..*providers };