]> git.proxmox.com Git - rustc.git/blame - src/librustc_passes/check_attr.rs
New upstream version 1.45.0+dfsg1
[rustc.git] / src / librustc_passes / check_attr.rs
CommitLineData
041b39d2
XL
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
ba9703b0
XL
7use rustc_middle::hir::map::Map;
8use rustc_middle::ty::query::Providers;
9use rustc_middle::ty::TyCtxt;
e1599b0c 10
74b04a01
XL
11use rustc_ast::ast::{Attribute, NestedMetaItem};
12use rustc_ast::attr;
dfeec247
XL
13use rustc_errors::struct_span_err;
14use rustc_hir as hir;
15use rustc_hir::def_id::DefId;
16use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
74b04a01
XL
17use rustc_hir::{self, HirId, Item, ItemKind, TraitItem};
18use rustc_hir::{MethodKind, Target};
dfeec247 19use rustc_session::lint::builtin::{CONFLICTING_REPR_HINTS, UNUSED_ATTRIBUTES};
74b04a01 20use rustc_session::parse::feature_err;
dfeec247
XL
21use rustc_span::symbol::sym;
22use rustc_span::Span;
b039eaaf 23
74b04a01
XL
24fn target_from_impl_item<'tcx>(tcx: TyCtxt<'tcx>, impl_item: &hir::ImplItem<'_>) -> Target {
25 match impl_item.kind {
26 hir::ImplItemKind::Const(..) => Target::AssocConst,
ba9703b0 27 hir::ImplItemKind::Fn(..) => {
74b04a01
XL
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"),
33 };
34 if containing_impl_is_for_trait {
e74abb32 35 Target::Method(MethodKind::Trait { body: true })
74b04a01
XL
36 } else {
37 Target::Method(MethodKind::Inherent)
e74abb32 38 }
b039eaaf 39 }
74b04a01 40 hir::ImplItemKind::TyAlias(..) | hir::ImplItemKind::OpaqueTy(..) => Target::AssocTy,
b039eaaf
SL
41 }
42}
43
dc9dc135
XL
44struct CheckAttrVisitor<'tcx> {
45 tcx: TyCtxt<'tcx>,
b039eaaf
SL
46}
47
dc9dc135 48impl CheckAttrVisitor<'tcx> {
9fa01778 49 /// Checks any attribute.
e74abb32
XL
50 fn check_attributes(
51 &self,
52 hir_id: HirId,
dfeec247 53 attrs: &'hir [Attribute],
e74abb32
XL
54 span: &Span,
55 target: Target,
dfeec247 56 item: Option<&Item<'_>>,
e74abb32
XL
57 ) {
58 let mut is_valid = true;
59 for attr in attrs {
60 is_valid &= if attr.check_name(sym::inline) {
61 self.check_inline(hir_id, attr, span, target)
48663c56 62 } else if attr.check_name(sym::non_exhaustive) {
e74abb32 63 self.check_non_exhaustive(attr, span, target)
48663c56 64 } else if attr.check_name(sym::marker) {
e74abb32
XL
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)
70 } else {
71 true
72 };
041b39d2 73 }
2c00a5a8 74
e74abb32
XL
75 if !is_valid {
76 return;
77 }
78
f9f354fc
XL
79 if matches!(target, Target::Fn | Target::Method(_) | Target::ForeignFn) {
80 self.tcx.ensure().codegen_fn_attrs(self.tcx.hir().local_def_id(hir_id));
e74abb32
XL
81 }
82
dfeec247 83 self.check_repr(attrs, span, target, item, hir_id);
e74abb32
XL
84 self.check_used(attrs, target);
85 }
86
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 {
89 match target {
dfeec247
XL
90 Target::Fn
91 | Target::Closure
ba9703b0 92 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true,
e74abb32 93 Target::Method(MethodKind::Trait { body: false }) | Target::ForeignFn => {
74b04a01
XL
94 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
95 lint.build("`#[inline]` is ignored on function prototypes").emit()
96 });
e74abb32
XL
97 true
98 }
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
102 // error here.
103 Target::AssocConst => {
74b04a01
XL
104 self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| {
105 lint.build("`#[inline]` is ignored on constants")
106 .warn(
107 "this was previously accepted by the compiler but is \
108 being phased out; it will become a hard error in \
109 a future release!",
110 )
111 .note(
112 "see issue #65833 <https://github.com/rust-lang/rust/issues/65833> \
113 for more information",
114 )
115 .emit();
116 });
e74abb32
XL
117 true
118 }
119 _ => {
120 struct_span_err!(
121 self.tcx.sess,
122 attr.span,
123 E0518,
124 "attribute should be applied to function or closure",
dfeec247
XL
125 )
126 .span_label(*span, "not a function or closure")
127 .emit();
e74abb32
XL
128 false
129 }
130 }
041b39d2
XL
131 }
132
e74abb32
XL
133 /// Checks if a `#[track_caller]` is applied to a non-naked function. Returns `true` if valid.
134 fn check_track_caller(
135 &self,
136 attr_span: &Span,
dfeec247 137 attrs: &'hir [Attribute],
e74abb32
XL
138 span: &Span,
139 target: Target,
140 ) -> bool {
141 match target {
ba9703b0 142 _ if attr::contains_name(attrs, sym::naked) => {
e74abb32
XL
143 struct_span_err!(
144 self.tcx.sess,
145 *attr_span,
146 E0736,
147 "cannot use `#[track_caller]` with `#[naked]`",
dfeec247
XL
148 )
149 .emit();
e74abb32
XL
150 false
151 }
ba9703b0 152 Target::Fn | Target::Method(..) | Target::ForeignFn => true,
e74abb32
XL
153 _ => {
154 struct_span_err!(
155 self.tcx.sess,
156 *attr_span,
157 E0739,
158 "attribute should be applied to function"
159 )
160 .span_label(*span, "not a function")
83c7162d 161 .emit();
e74abb32
XL
162 false
163 }
83c7162d
XL
164 }
165 }
166
e74abb32 167 /// Checks if the `#[non_exhaustive]` attribute on an `item` is valid. Returns `true` if valid.
dfeec247 168 fn check_non_exhaustive(&self, attr: &Attribute, span: &Span, target: Target) -> bool {
83c7162d 169 match target {
e74abb32 170 Target::Struct | Target::Enum => true,
83c7162d 171 _ => {
dfeec247
XL
172 struct_span_err!(
173 self.tcx.sess,
174 attr.span,
175 E0701,
176 "attribute can only be applied to a struct or enum"
177 )
178 .span_label(*span, "not a struct or enum")
179 .emit();
e74abb32 180 false
83c7162d
XL
181 }
182 }
b039eaaf
SL
183 }
184
e74abb32
XL
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 {
0bf4aa26 187 match target {
e74abb32 188 Target::Trait => true,
0bf4aa26 189 _ => {
dfeec247
XL
190 self.tcx
191 .sess
0bf4aa26 192 .struct_span_err(attr.span, "attribute can only be applied to a trait")
e74abb32 193 .span_label(*span, "not a trait")
0bf4aa26 194 .emit();
e74abb32 195 false
0bf4aa26
XL
196 }
197 }
0bf4aa26
XL
198 }
199
e74abb32
XL
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 {
202 match target {
dfeec247 203 Target::Fn
ba9703b0 204 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true,
e74abb32 205 _ => {
dfeec247
XL
206 self.tcx
207 .sess
e74abb32
XL
208 .struct_span_err(attr.span, "attribute should be applied to a function")
209 .span_label(*span, "not a function")
210 .emit();
211 false
dfeec247 212 }
e74abb32
XL
213 }
214 }
215
9fa01778 216 /// Checks if the `#[repr]` attributes on `item` are valid.
e74abb32
XL
217 fn check_repr(
218 &self,
dfeec247 219 attrs: &'hir [Attribute],
e74abb32
XL
220 span: &Span,
221 target: Target,
dfeec247
XL
222 item: Option<&Item<'_>>,
223 hir_id: HirId,
e74abb32 224 ) {
2c00a5a8
XL
225 // Extract the names of all repr hints, e.g., [foo, bar, align] for:
226 // ```
227 // #[repr(foo)]
228 // #[repr(bar, align(8))]
229 // ```
e74abb32 230 let hints: Vec<_> = attrs
2c00a5a8 231 .iter()
48663c56 232 .filter(|attr| attr.check_name(sym::repr))
2c00a5a8 233 .filter_map(|attr| attr.meta_item_list())
b7449926 234 .flatten()
2c00a5a8 235 .collect();
9e0c209e 236
ff7c6d11
XL
237 let mut int_reprs = 0;
238 let mut is_c = false;
239 let mut is_simd = false;
2c00a5a8
XL
240 let mut is_transparent = false;
241
242 for hint in &hints {
48663c56
XL
243 let (article, allowed_targets) = match hint.name_or_empty() {
244 name @ sym::C | name @ sym::align => {
245 is_c |= name == sym::C;
dc9dc135
XL
246 match target {
247 Target::Struct | Target::Union | Target::Enum => continue,
248 _ => ("a", "struct, enum, or union"),
9e0c209e
SL
249 }
250 }
48663c56 251 sym::packed => {
dfeec247
XL
252 if target != Target::Struct && target != Target::Union {
253 ("a", "struct or union")
92a42be0 254 } else {
dfeec247 255 continue;
b039eaaf
SL
256 }
257 }
48663c56 258 sym::simd => {
ff7c6d11 259 is_simd = true;
dfeec247 260 if target != Target::Struct { ("a", "struct") } else { continue }
b039eaaf 261 }
48663c56 262 sym::transparent => {
2c00a5a8 263 is_transparent = true;
dc9dc135
XL
264 match target {
265 Target::Struct | Target::Union | Target::Enum => continue,
266 _ => ("a", "struct, enum, or union"),
cc61c64b
XL
267 }
268 }
74b04a01
XL
269 sym::no_niche => {
270 if !self.tcx.features().enabled(sym::no_niche) {
271 feature_err(
272 &self.tcx.sess.parse_sess,
273 sym::no_niche,
274 hint.span(),
275 "the attribute `repr(no_niche)` is currently unstable",
276 )
277 .emit();
278 }
279 match target {
280 Target::Struct | Target::Enum => continue,
281 _ => ("a", "struct or enum"),
282 }
283 }
dfeec247
XL
284 sym::i8
285 | sym::u8
286 | sym::i16
287 | sym::u16
288 | sym::i32
289 | sym::u32
290 | sym::i64
291 | sym::u64
292 | sym::isize
293 | sym::usize => {
ff7c6d11 294 int_reprs += 1;
dfeec247 295 if target != Target::Enum { ("an", "enum") } else { continue }
b039eaaf 296 }
92a42be0
SL
297 _ => continue,
298 };
0531ce1d 299 self.emit_repr_error(
532ac7d7 300 hint.span(),
e74abb32 301 *span,
0531ce1d
XL
302 &format!("attribute should be applied to {}", allowed_targets),
303 &format!("not {} {}", article, allowed_targets),
304 )
9e0c209e 305 }
ff7c6d11 306
2c00a5a8
XL
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.
532ac7d7 309 let hint_spans = hints.iter().map(|hint| hint.span());
2c00a5a8 310
74b04a01
XL
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 {
2c00a5a8 315 let hint_spans: Vec<_> = hint_spans.clone().collect();
dfeec247
XL
316 struct_span_err!(
317 self.tcx.sess,
318 hint_spans,
319 E0692,
320 "transparent {} cannot have other repr hints",
321 target
322 )
323 .emit();
2c00a5a8 324 }
ff7c6d11
XL
325 // Warn on repr(u8, u16), repr(C, simd), and c-like-enum-repr(C, u8)
326 if (int_reprs > 1)
dfeec247
XL
327 || (is_simd && is_c)
328 || (int_reprs == 1 && is_c && item.map_or(false, |item| is_c_like_enum(item)))
329 {
74b04a01
XL
330 self.tcx.struct_span_lint_hir(
331 CONFLICTING_REPR_HINTS,
332 hir_id,
333 hint_spans.collect::<Vec<Span>>(),
334 |lint| {
335 lint.build("conflicting representation hints")
336 .code(rustc_errors::error_code!(E0566))
337 .emit();
338 },
339 );
b039eaaf
SL
340 }
341 }
0531ce1d
XL
342
343 fn emit_repr_error(
344 &self,
345 hint_span: Span,
346 label_span: Span,
347 hint_message: &str,
348 label_message: &str,
349 ) {
350 struct_span_err!(self.tcx.sess, hint_span, E0517, "{}", hint_message)
351 .span_label(label_span, label_message)
352 .emit();
353 }
354
dfeec247 355 fn check_stmt_attributes(&self, stmt: &hir::Stmt<'_>) {
0531ce1d 356 // When checking statements ignore expressions, they will be checked later
e74abb32 357 if let hir::StmtKind::Local(ref l) = stmt.kind {
9fa01778 358 for attr in l.attrs.iter() {
48663c56 359 if attr.check_name(sym::inline) {
ba9703b0 360 self.check_inline(l.hir_id, attr, &stmt.span, Target::Statement);
0531ce1d 361 }
48663c56 362 if attr.check_name(sym::repr) {
0531ce1d
XL
363 self.emit_repr_error(
364 attr.span,
365 stmt.span,
8faf50e0 366 "attribute should not be applied to a statement",
dc9dc135 367 "not a struct, enum, or union",
0531ce1d
XL
368 );
369 }
370 }
371 }
372 }
373
dfeec247 374 fn check_expr_attributes(&self, expr: &hir::Expr<'_>) {
e74abb32 375 let target = match expr.kind {
8faf50e0 376 hir::ExprKind::Closure(..) => Target::Closure,
83c7162d
XL
377 _ => Target::Expression,
378 };
0531ce1d 379 for attr in expr.attrs.iter() {
48663c56 380 if attr.check_name(sym::inline) {
ba9703b0 381 self.check_inline(expr.hir_id, attr, &expr.span, target);
0531ce1d 382 }
48663c56 383 if attr.check_name(sym::repr) {
0531ce1d
XL
384 self.emit_repr_error(
385 attr.span,
386 expr.span,
8faf50e0 387 "attribute should not be applied to an expression",
dc9dc135 388 "not defining a struct, enum, or union",
0531ce1d
XL
389 );
390 }
391 }
f9f354fc
XL
392 if target == Target::Closure {
393 self.tcx.ensure().codegen_fn_attrs(self.tcx.hir().local_def_id(expr.hir_id));
394 }
0531ce1d 395 }
83c7162d 396
dfeec247 397 fn check_used(&self, attrs: &'hir [Attribute], target: Target) {
e74abb32 398 for attr in attrs {
48663c56 399 if attr.check_name(sym::used) && target != Target::Static {
dfeec247
XL
400 self.tcx
401 .sess
83c7162d
XL
402 .span_err(attr.span, "attribute must be applied to a `static` variable");
403 }
404 }
405 }
b039eaaf
SL
406}
407
dc9dc135 408impl Visitor<'tcx> for CheckAttrVisitor<'tcx> {
dfeec247
XL
409 type Map = Map<'tcx>;
410
ba9703b0
XL
411 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
412 NestedVisitorMap::OnlyBodies(self.tcx.hir())
2c00a5a8
XL
413 }
414
dfeec247 415 fn visit_item(&mut self, item: &'tcx Item<'tcx>) {
b039eaaf 416 let target = Target::from_item(item);
dfeec247 417 self.check_attributes(item.hir_id, item.attrs, &item.span, target, Some(item));
0531ce1d
XL
418 intravisit::walk_item(self, item)
419 }
420
dfeec247 421 fn visit_trait_item(&mut self, trait_item: &'tcx TraitItem<'tcx>) {
e74abb32
XL
422 let target = Target::from_trait_item(trait_item);
423 self.check_attributes(trait_item.hir_id, &trait_item.attrs, &trait_item.span, target, None);
424 intravisit::walk_trait_item(self, trait_item)
425 }
426
dfeec247 427 fn visit_foreign_item(&mut self, f_item: &'tcx hir::ForeignItem<'tcx>) {
e74abb32
XL
428 let target = Target::from_foreign_item(f_item);
429 self.check_attributes(f_item.hir_id, &f_item.attrs, &f_item.span, target, None);
430 intravisit::walk_foreign_item(self, f_item)
431 }
432
dfeec247 433 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
74b04a01 434 let target = target_from_impl_item(self.tcx, impl_item);
e74abb32
XL
435 self.check_attributes(impl_item.hir_id, &impl_item.attrs, &impl_item.span, target, None);
436 intravisit::walk_impl_item(self, impl_item)
437 }
0531ce1d 438
dfeec247 439 fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt<'tcx>) {
0531ce1d
XL
440 self.check_stmt_attributes(stmt);
441 intravisit::walk_stmt(self, stmt)
442 }
443
dfeec247 444 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
0531ce1d
XL
445 self.check_expr_attributes(expr);
446 intravisit::walk_expr(self, expr)
b039eaaf
SL
447 }
448}
449
dfeec247 450fn is_c_like_enum(item: &Item<'_>) -> bool {
e74abb32 451 if let ItemKind::Enum(ref def, _) = item.kind {
dfeec247 452 for variant in def.variants {
e1599b0c 453 match variant.data {
9fa01778 454 hir::VariantData::Unit(..) => { /* continue */ }
e74abb32 455 _ => return false,
ff7c6d11
XL
456 }
457 }
458 true
459 } else {
460 false
461 }
462}
0731742a 463
416331ca 464fn check_mod_attrs(tcx: TyCtxt<'_>, module_def_id: DefId) {
dfeec247
XL
465 tcx.hir()
466 .visit_item_likes_in_module(module_def_id, &mut CheckAttrVisitor { tcx }.as_deep_visitor());
0731742a
XL
467}
468
469pub(crate) fn provide(providers: &mut Providers<'_>) {
dfeec247 470 *providers = Providers { check_mod_attrs, ..*providers };
0731742a 471}