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::hir::map::Map;
8 use rustc::ty::query::Providers;
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::DUMMY_HIR_ID;
18 use rustc_hir::{self, HirId, Item, ItemKind, TraitItem};
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;
25 fn target_from_impl_item<'tcx>(tcx: TyCtxt<'tcx>, impl_item: &hir::ImplItem<'_>) -> Target {
26 match impl_item.kind {
27 hir::ImplItemKind::Const(..) => Target::AssocConst,
28 hir::ImplItemKind::Method(..) => {
29 let parent_hir_id = tcx.hir().get_parent_item(impl_item.hir_id);
30 let containing_item = tcx.hir().expect_item(parent_hir_id);
31 let containing_impl_is_for_trait = match &containing_item.kind {
32 hir::ItemKind::Impl { ref of_trait, .. } => of_trait.is_some(),
33 _ => bug!("parent of an ImplItem must be an Impl"),
35 if containing_impl_is_for_trait {
36 Target::Method(MethodKind::Trait { body: true })
38 Target::Method(MethodKind::Inherent)
41 hir::ImplItemKind::TyAlias(..) | hir::ImplItemKind::OpaqueTy(..) => Target::AssocTy,
45 struct CheckAttrVisitor<'tcx> {
49 impl CheckAttrVisitor<'tcx> {
50 /// Checks any attribute.
54 attrs: &'hir [Attribute],
57 item: Option<&Item<'_>>,
59 let mut is_valid = true;
61 is_valid &= if attr.check_name(sym::inline) {
62 self.check_inline(hir_id, attr, span, target)
63 } else if attr.check_name(sym::non_exhaustive) {
64 self.check_non_exhaustive(attr, span, target)
65 } else if attr.check_name(sym::marker) {
66 self.check_marker(attr, span, target)
67 } else if attr.check_name(sym::target_feature) {
68 self.check_target_feature(attr, span, target)
69 } else if attr.check_name(sym::track_caller) {
70 self.check_track_caller(&attr.span, attrs, span, target)
80 if target == Target::Fn {
81 self.tcx.codegen_fn_attrs(self.tcx.hir().local_def_id(hir_id));
84 self.check_repr(attrs, span, target, item, hir_id);
85 self.check_used(attrs, target);
88 /// Checks if an `#[inline]` is applied to a function or a closure. Returns `true` if valid.
89 fn check_inline(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) -> bool {
93 | Target::Method(MethodKind::Trait { body: true })
94 | Target::Method(MethodKind::Inherent) => true,
95 Target::Method(MethodKind::Trait { body: false }) | Target::ForeignFn => {
96 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
97 lint.build("`#[inline]` is ignored on function prototypes").emit()
101 // FIXME(#65833): We permit associated consts to have an `#[inline]` attribute with
102 // just a lint, because we previously erroneously allowed it and some crates used it
103 // accidentally, to to be compatible with crates depending on them, we can't throw an
105 Target::AssocConst => {
106 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
107 lint.build("`#[inline]` is ignored on constants")
109 "this was previously accepted by the compiler but is \
110 being phased out; it will become a hard error in \
114 "see issue #65833 <https://github.com/rust-lang/rust/issues/65833> \
115 for more information",
126 "attribute should be applied to function or closure",
128 .span_label(*span, "not a function or closure")
135 /// Checks if a `#[track_caller]` is applied to a non-naked function. Returns `true` if valid.
136 fn check_track_caller(
139 attrs: &'hir [Attribute],
144 Target::Fn if attr::contains_name(attrs, sym::naked) => {
149 "cannot use `#[track_caller]` with `#[naked]`",
154 Target::Fn | Target::Method(MethodKind::Inherent) => true,
155 Target::Method(_) => {
160 "`#[track_caller]` may not be used on trait methods",
170 "attribute should be applied to function"
172 .span_label(*span, "not a function")
179 /// Checks if the `#[non_exhaustive]` attribute on an `item` is valid. Returns `true` if valid.
180 fn check_non_exhaustive(&self, attr: &Attribute, span: &Span, target: Target) -> bool {
182 Target::Struct | Target::Enum => true,
188 "attribute can only be applied to a struct or enum"
190 .span_label(*span, "not a struct or enum")
197 /// Checks if the `#[marker]` attribute on an `item` is valid. Returns `true` if valid.
198 fn check_marker(&self, attr: &Attribute, span: &Span, target: Target) -> bool {
200 Target::Trait => true,
204 .struct_span_err(attr.span, "attribute can only be applied to a trait")
205 .span_label(*span, "not a trait")
212 /// Checks if the `#[target_feature]` attribute on `item` is valid. Returns `true` if valid.
213 fn check_target_feature(&self, attr: &Attribute, span: &Span, target: Target) -> bool {
216 | Target::Method(MethodKind::Trait { body: true })
217 | Target::Method(MethodKind::Inherent) => true,
221 .struct_span_err(attr.span, "attribute should be applied to a function")
222 .span_label(*span, "not a function")
229 /// Checks if the `#[repr]` attributes on `item` are valid.
232 attrs: &'hir [Attribute],
235 item: Option<&Item<'_>>,
238 // Extract the names of all repr hints, e.g., [foo, bar, align] for:
241 // #[repr(bar, align(8))]
243 let hints: Vec<_> = attrs
245 .filter(|attr| attr.check_name(sym::repr))
246 .filter_map(|attr| attr.meta_item_list())
250 let mut int_reprs = 0;
251 let mut is_c = false;
252 let mut is_simd = false;
253 let mut is_transparent = false;
256 let (article, allowed_targets) = match hint.name_or_empty() {
257 name @ sym::C | name @ sym::align => {
258 is_c |= name == sym::C;
260 Target::Struct | Target::Union | Target::Enum => continue,
261 _ => ("a", "struct, enum, or union"),
265 if target != Target::Struct && target != Target::Union {
266 ("a", "struct or union")
273 if target != Target::Struct { ("a", "struct") } else { continue }
275 sym::transparent => {
276 is_transparent = true;
278 Target::Struct | Target::Union | Target::Enum => continue,
279 _ => ("a", "struct, enum, or union"),
283 if !self.tcx.features().enabled(sym::no_niche) {
285 &self.tcx.sess.parse_sess,
288 "the attribute `repr(no_niche)` is currently unstable",
293 Target::Struct | Target::Enum => continue,
294 _ => ("a", "struct or enum"),
308 if target != Target::Enum { ("an", "enum") } else { continue }
312 self.emit_repr_error(
315 &format!("attribute should be applied to {}", allowed_targets),
316 &format!("not {} {}", article, allowed_targets),
320 // Just point at all repr hints if there are any incompatibilities.
321 // This is not ideal, but tracking precisely which ones are at fault is a huge hassle.
322 let hint_spans = hints.iter().map(|hint| hint.span());
324 // Error on repr(transparent, <anything else apart from no_niche>).
325 let non_no_niche = |hint: &&NestedMetaItem| hint.name_or_empty() != sym::no_niche;
326 let non_no_niche_count = hints.iter().filter(non_no_niche).count();
327 if is_transparent && non_no_niche_count > 1 {
328 let hint_spans: Vec<_> = hint_spans.clone().collect();
333 "transparent {} cannot have other repr hints",
338 // Warn on repr(u8, u16), repr(C, simd), and c-like-enum-repr(C, u8)
341 || (int_reprs == 1 && is_c && item.map_or(false, |item| is_c_like_enum(item)))
343 self.tcx.struct_span_lint_hir(
344 CONFLICTING_REPR_HINTS,
346 hint_spans.collect::<Vec<Span>>(),
348 lint.build("conflicting representation hints")
349 .code(rustc_errors::error_code!(E0566))
363 struct_span_err!(self.tcx.sess, hint_span, E0517, "{}", hint_message)
364 .span_label(label_span, label_message)
368 fn check_stmt_attributes(&self, stmt: &hir::Stmt<'_>) {
369 // When checking statements ignore expressions, they will be checked later
370 if let hir::StmtKind::Local(ref l) = stmt.kind {
371 for attr in l.attrs.iter() {
372 if attr.check_name(sym::inline) {
373 self.check_inline(DUMMY_HIR_ID, attr, &stmt.span, Target::Statement);
375 if attr.check_name(sym::repr) {
376 self.emit_repr_error(
379 "attribute should not be applied to a statement",
380 "not a struct, enum, or union",
387 fn check_expr_attributes(&self, expr: &hir::Expr<'_>) {
388 let target = match expr.kind {
389 hir::ExprKind::Closure(..) => Target::Closure,
390 _ => Target::Expression,
392 for attr in expr.attrs.iter() {
393 if attr.check_name(sym::inline) {
394 self.check_inline(DUMMY_HIR_ID, attr, &expr.span, target);
396 if attr.check_name(sym::repr) {
397 self.emit_repr_error(
400 "attribute should not be applied to an expression",
401 "not defining a struct, enum, or union",
407 fn check_used(&self, attrs: &'hir [Attribute], target: Target) {
409 if attr.check_name(sym::used) && target != Target::Static {
412 .span_err(attr.span, "attribute must be applied to a `static` variable");
418 impl Visitor<'tcx> for CheckAttrVisitor<'tcx> {
419 type Map = Map<'tcx>;
421 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, Self::Map> {
422 NestedVisitorMap::OnlyBodies(&self.tcx.hir())
425 fn visit_item(&mut self, item: &'tcx Item<'tcx>) {
426 let target = Target::from_item(item);
427 self.check_attributes(item.hir_id, item.attrs, &item.span, target, Some(item));
428 intravisit::walk_item(self, item)
431 fn visit_trait_item(&mut self, trait_item: &'tcx TraitItem<'tcx>) {
432 let target = Target::from_trait_item(trait_item);
433 self.check_attributes(trait_item.hir_id, &trait_item.attrs, &trait_item.span, target, None);
434 intravisit::walk_trait_item(self, trait_item)
437 fn visit_foreign_item(&mut self, f_item: &'tcx hir::ForeignItem<'tcx>) {
438 let target = Target::from_foreign_item(f_item);
439 self.check_attributes(f_item.hir_id, &f_item.attrs, &f_item.span, target, None);
440 intravisit::walk_foreign_item(self, f_item)
443 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
444 let target = target_from_impl_item(self.tcx, impl_item);
445 self.check_attributes(impl_item.hir_id, &impl_item.attrs, &impl_item.span, target, None);
446 intravisit::walk_impl_item(self, impl_item)
449 fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt<'tcx>) {
450 self.check_stmt_attributes(stmt);
451 intravisit::walk_stmt(self, stmt)
454 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
455 self.check_expr_attributes(expr);
456 intravisit::walk_expr(self, expr)
460 fn is_c_like_enum(item: &Item<'_>) -> bool {
461 if let ItemKind::Enum(ref def, _) = item.kind {
462 for variant in def.variants {
464 hir::VariantData::Unit(..) => { /* continue */ }
474 fn check_mod_attrs(tcx: TyCtxt<'_>, module_def_id: DefId) {
476 .visit_item_likes_in_module(module_def_id, &mut CheckAttrVisitor { tcx }.as_deep_visitor());
479 pub(crate) fn provide(providers: &mut Providers<'_>) {
480 *providers = Providers { check_mod_attrs, ..*providers };