]> git.proxmox.com Git - rustc.git/blob - compiler/rustc_passes/src/check_attr.rs
New upstream version 1.66.0+dfsg1
[rustc.git] / compiler / rustc_passes / src / check_attr.rs
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
7 use crate::errors::{
8 self, AttrApplication, DebugVisualizerUnreadable, InvalidAttrAtCrateLevel, ObjectLifetimeErr,
9 OnlyHasEffectOn, TransparentIncompatible, UnrecognizedReprHint,
10 };
11 use rustc_ast::{ast, AttrStyle, Attribute, Lit, LitKind, MetaItemKind, NestedMetaItem};
12 use rustc_data_structures::fx::FxHashMap;
13 use rustc_errors::{fluent, Applicability, MultiSpan};
14 use rustc_expand::base::resolve_path;
15 use rustc_feature::{AttributeDuplicates, AttributeType, BuiltinAttribute, BUILTIN_ATTRIBUTE_MAP};
16 use rustc_hir as hir;
17 use rustc_hir::def_id::LocalDefId;
18 use rustc_hir::intravisit::{self, Visitor};
19 use rustc_hir::{
20 self, FnSig, ForeignItem, HirId, Item, ItemKind, TraitItem, CRATE_HIR_ID, CRATE_OWNER_ID,
21 };
22 use rustc_hir::{MethodKind, Target};
23 use rustc_middle::hir::nested_filter;
24 use rustc_middle::middle::resolve_lifetime::ObjectLifetimeDefault;
25 use rustc_middle::ty::query::Providers;
26 use rustc_middle::ty::TyCtxt;
27 use rustc_session::lint::builtin::{
28 CONFLICTING_REPR_HINTS, INVALID_DOC_ATTRIBUTES, UNUSED_ATTRIBUTES,
29 };
30 use rustc_session::parse::feature_err;
31 use rustc_span::symbol::{kw, sym, Symbol};
32 use rustc_span::{Span, DUMMY_SP};
33 use rustc_target::spec::abi::Abi;
34 use std::collections::hash_map::Entry;
35
36 pub(crate) fn target_from_impl_item<'tcx>(
37 tcx: TyCtxt<'tcx>,
38 impl_item: &hir::ImplItem<'_>,
39 ) -> Target {
40 match impl_item.kind {
41 hir::ImplItemKind::Const(..) => Target::AssocConst,
42 hir::ImplItemKind::Fn(..) => {
43 let parent_def_id = tcx.hir().get_parent_item(impl_item.hir_id()).def_id;
44 let containing_item = tcx.hir().expect_item(parent_def_id);
45 let containing_impl_is_for_trait = match &containing_item.kind {
46 hir::ItemKind::Impl(impl_) => impl_.of_trait.is_some(),
47 _ => bug!("parent of an ImplItem must be an Impl"),
48 };
49 if containing_impl_is_for_trait {
50 Target::Method(MethodKind::Trait { body: true })
51 } else {
52 Target::Method(MethodKind::Inherent)
53 }
54 }
55 hir::ImplItemKind::Type(..) => Target::AssocTy,
56 }
57 }
58
59 #[derive(Clone, Copy)]
60 enum ItemLike<'tcx> {
61 Item(&'tcx Item<'tcx>),
62 ForeignItem,
63 }
64
65 struct CheckAttrVisitor<'tcx> {
66 tcx: TyCtxt<'tcx>,
67 }
68
69 impl CheckAttrVisitor<'_> {
70 /// Checks any attribute.
71 fn check_attributes(
72 &self,
73 hir_id: HirId,
74 span: Span,
75 target: Target,
76 item: Option<ItemLike<'_>>,
77 ) {
78 let mut doc_aliases = FxHashMap::default();
79 let mut is_valid = true;
80 let mut specified_inline = None;
81 let mut seen = FxHashMap::default();
82 let attrs = self.tcx.hir().attrs(hir_id);
83 for attr in attrs {
84 let attr_is_valid = match attr.name_or_empty() {
85 sym::inline => self.check_inline(hir_id, attr, span, target),
86 sym::no_coverage => self.check_no_coverage(hir_id, attr, span, target),
87 sym::non_exhaustive => self.check_non_exhaustive(hir_id, attr, span, target),
88 sym::marker => self.check_marker(hir_id, attr, span, target),
89 sym::rustc_must_implement_one_of => {
90 self.check_rustc_must_implement_one_of(attr, span, target)
91 }
92 sym::target_feature => self.check_target_feature(hir_id, attr, span, target),
93 sym::thread_local => self.check_thread_local(attr, span, target),
94 sym::track_caller => {
95 self.check_track_caller(hir_id, attr.span, attrs, span, target)
96 }
97 sym::doc => self.check_doc_attrs(
98 attr,
99 hir_id,
100 target,
101 &mut specified_inline,
102 &mut doc_aliases,
103 ),
104 sym::no_link => self.check_no_link(hir_id, &attr, span, target),
105 sym::export_name => self.check_export_name(hir_id, &attr, span, target),
106 sym::rustc_layout_scalar_valid_range_start
107 | sym::rustc_layout_scalar_valid_range_end => {
108 self.check_rustc_layout_scalar_valid_range(&attr, span, target)
109 }
110 sym::allow_internal_unstable => {
111 self.check_allow_internal_unstable(hir_id, &attr, span, target, &attrs)
112 }
113 sym::debugger_visualizer => self.check_debugger_visualizer(&attr, target),
114 sym::rustc_allow_const_fn_unstable => {
115 self.check_rustc_allow_const_fn_unstable(hir_id, &attr, span, target)
116 }
117 sym::rustc_std_internal_symbol => {
118 self.check_rustc_std_internal_symbol(&attr, span, target)
119 }
120 sym::naked => self.check_naked(hir_id, attr, span, target),
121 sym::rustc_legacy_const_generics => {
122 self.check_rustc_legacy_const_generics(&attr, span, target, item)
123 }
124 sym::rustc_lint_query_instability => {
125 self.check_rustc_lint_query_instability(&attr, span, target)
126 }
127 sym::rustc_lint_diagnostics => {
128 self.check_rustc_lint_diagnostics(&attr, span, target)
129 }
130 sym::rustc_lint_opt_ty => self.check_rustc_lint_opt_ty(&attr, span, target),
131 sym::rustc_lint_opt_deny_field_access => {
132 self.check_rustc_lint_opt_deny_field_access(&attr, span, target)
133 }
134 sym::rustc_clean
135 | sym::rustc_dirty
136 | sym::rustc_if_this_changed
137 | sym::rustc_then_this_would_need => self.check_rustc_dirty_clean(&attr),
138 sym::cmse_nonsecure_entry => self.check_cmse_nonsecure_entry(attr, span, target),
139 sym::collapse_debuginfo => self.check_collapse_debuginfo(attr, span, target),
140 sym::const_trait => self.check_const_trait(attr, span, target),
141 sym::must_not_suspend => self.check_must_not_suspend(&attr, span, target),
142 sym::must_use => self.check_must_use(hir_id, &attr, span, target),
143 sym::rustc_pass_by_value => self.check_pass_by_value(&attr, span, target),
144 sym::rustc_allow_incoherent_impl => {
145 self.check_allow_incoherent_impl(&attr, span, target)
146 }
147 sym::rustc_has_incoherent_inherent_impls => {
148 self.check_has_incoherent_inherent_impls(&attr, span, target)
149 }
150 sym::rustc_const_unstable
151 | sym::rustc_const_stable
152 | sym::unstable
153 | sym::stable
154 | sym::rustc_allowed_through_unstable_modules
155 | sym::rustc_promotable => self.check_stability_promotable(&attr, span, target),
156 sym::link_ordinal => self.check_link_ordinal(&attr, span, target),
157 _ => true,
158 };
159 is_valid &= attr_is_valid;
160
161 // lint-only checks
162 match attr.name_or_empty() {
163 sym::cold => self.check_cold(hir_id, attr, span, target),
164 sym::link => self.check_link(hir_id, attr, span, target),
165 sym::link_name => self.check_link_name(hir_id, attr, span, target),
166 sym::link_section => self.check_link_section(hir_id, attr, span, target),
167 sym::no_mangle => self.check_no_mangle(hir_id, attr, span, target),
168 sym::deprecated => self.check_deprecated(hir_id, attr, span, target),
169 sym::macro_use | sym::macro_escape => self.check_macro_use(hir_id, attr, target),
170 sym::path => self.check_generic_attr(hir_id, attr, target, Target::Mod),
171 sym::plugin_registrar => self.check_plugin_registrar(hir_id, attr, target),
172 sym::macro_export => self.check_macro_export(hir_id, attr, target),
173 sym::ignore | sym::should_panic | sym::proc_macro_derive => {
174 self.check_generic_attr(hir_id, attr, target, Target::Fn)
175 }
176 sym::automatically_derived => {
177 self.check_generic_attr(hir_id, attr, target, Target::Impl)
178 }
179 sym::no_implicit_prelude => {
180 self.check_generic_attr(hir_id, attr, target, Target::Mod)
181 }
182 sym::rustc_object_lifetime_default => self.check_object_lifetime_default(hir_id),
183 _ => {}
184 }
185
186 let builtin = attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name));
187
188 if hir_id != CRATE_HIR_ID {
189 if let Some(BuiltinAttribute { type_: AttributeType::CrateLevel, .. }) =
190 attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name))
191 {
192 match attr.style {
193 ast::AttrStyle::Outer => self.tcx.emit_spanned_lint(
194 UNUSED_ATTRIBUTES,
195 hir_id,
196 attr.span,
197 errors::OuterCrateLevelAttr,
198 ),
199 ast::AttrStyle::Inner => self.tcx.emit_spanned_lint(
200 UNUSED_ATTRIBUTES,
201 hir_id,
202 attr.span,
203 errors::InnerCrateLevelAttr,
204 ),
205 }
206 }
207 }
208
209 if let Some(BuiltinAttribute { duplicates, .. }) = builtin {
210 check_duplicates(self.tcx, attr, hir_id, *duplicates, &mut seen);
211 }
212
213 self.check_unused_attribute(hir_id, attr)
214 }
215
216 if !is_valid {
217 return;
218 }
219
220 // FIXME(@lcnr): this doesn't belong here.
221 if matches!(
222 target,
223 Target::Closure
224 | Target::Fn
225 | Target::Method(_)
226 | Target::ForeignFn
227 | Target::ForeignStatic
228 ) {
229 self.tcx.ensure().codegen_fn_attrs(self.tcx.hir().local_def_id(hir_id));
230 }
231
232 self.check_repr(attrs, span, target, item, hir_id);
233 self.check_used(attrs, target);
234 }
235
236 fn inline_attr_str_error_with_macro_def(&self, hir_id: HirId, attr: &Attribute, sym: &str) {
237 self.tcx.emit_spanned_lint(
238 UNUSED_ATTRIBUTES,
239 hir_id,
240 attr.span,
241 errors::IgnoredAttrWithMacro { sym },
242 );
243 }
244
245 fn inline_attr_str_error_without_macro_def(&self, hir_id: HirId, attr: &Attribute, sym: &str) {
246 self.tcx.emit_spanned_lint(
247 UNUSED_ATTRIBUTES,
248 hir_id,
249 attr.span,
250 errors::IgnoredAttr { sym },
251 );
252 }
253
254 /// Checks if an `#[inline]` is applied to a function or a closure. Returns `true` if valid.
255 fn check_inline(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) -> bool {
256 match target {
257 Target::Fn
258 | Target::Closure
259 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true,
260 Target::Method(MethodKind::Trait { body: false }) | Target::ForeignFn => {
261 self.tcx.emit_spanned_lint(
262 UNUSED_ATTRIBUTES,
263 hir_id,
264 attr.span,
265 errors::IgnoredInlineAttrFnProto,
266 );
267 true
268 }
269 // FIXME(#65833): We permit associated consts to have an `#[inline]` attribute with
270 // just a lint, because we previously erroneously allowed it and some crates used it
271 // accidentally, to be compatible with crates depending on them, we can't throw an
272 // error here.
273 Target::AssocConst => {
274 self.tcx.emit_spanned_lint(
275 UNUSED_ATTRIBUTES,
276 hir_id,
277 attr.span,
278 errors::IgnoredInlineAttrConstants,
279 );
280 true
281 }
282 // FIXME(#80564): Same for fields, arms, and macro defs
283 Target::Field | Target::Arm | Target::MacroDef => {
284 self.inline_attr_str_error_with_macro_def(hir_id, attr, "inline");
285 true
286 }
287 _ => {
288 self.tcx.sess.emit_err(errors::InlineNotFnOrClosure {
289 attr_span: attr.span,
290 defn_span: span,
291 });
292 false
293 }
294 }
295 }
296
297 /// Checks if a `#[no_coverage]` is applied directly to a function
298 fn check_no_coverage(
299 &self,
300 hir_id: HirId,
301 attr: &Attribute,
302 span: Span,
303 target: Target,
304 ) -> bool {
305 match target {
306 // no_coverage on function is fine
307 Target::Fn
308 | Target::Closure
309 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true,
310
311 // function prototypes can't be covered
312 Target::Method(MethodKind::Trait { body: false }) | Target::ForeignFn => {
313 self.tcx.emit_spanned_lint(
314 UNUSED_ATTRIBUTES,
315 hir_id,
316 attr.span,
317 errors::IgnoredNoCoverageFnProto,
318 );
319 true
320 }
321
322 Target::Mod | Target::ForeignMod | Target::Impl | Target::Trait => {
323 self.tcx.emit_spanned_lint(
324 UNUSED_ATTRIBUTES,
325 hir_id,
326 attr.span,
327 errors::IgnoredNoCoveragePropagate,
328 );
329 true
330 }
331
332 Target::Expression | Target::Statement | Target::Arm => {
333 self.tcx.emit_spanned_lint(
334 UNUSED_ATTRIBUTES,
335 hir_id,
336 attr.span,
337 errors::IgnoredNoCoverageFnDefn,
338 );
339 true
340 }
341
342 _ => {
343 self.tcx.sess.emit_err(errors::IgnoredNoCoverageNotCoverable {
344 attr_span: attr.span,
345 defn_span: span,
346 });
347 false
348 }
349 }
350 }
351
352 fn check_generic_attr(
353 &self,
354 hir_id: HirId,
355 attr: &Attribute,
356 target: Target,
357 allowed_target: Target,
358 ) {
359 if target != allowed_target {
360 self.tcx.emit_spanned_lint(
361 UNUSED_ATTRIBUTES,
362 hir_id,
363 attr.span,
364 OnlyHasEffectOn {
365 attr_name: attr.name_or_empty(),
366 target_name: allowed_target.name().replace(" ", "_"),
367 },
368 );
369 }
370 }
371
372 /// Checks if `#[naked]` is applied to a function definition.
373 fn check_naked(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) -> bool {
374 match target {
375 Target::Fn
376 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true,
377 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
378 // `#[allow_internal_unstable]` attribute with just a lint, because we previously
379 // erroneously allowed it and some crates used it accidentally, to be compatible
380 // with crates depending on them, we can't throw an error here.
381 Target::Field | Target::Arm | Target::MacroDef => {
382 self.inline_attr_str_error_with_macro_def(hir_id, attr, "naked");
383 true
384 }
385 _ => {
386 self.tcx.sess.emit_err(errors::AttrShouldBeAppliedToFn {
387 attr_span: attr.span,
388 defn_span: span,
389 });
390 false
391 }
392 }
393 }
394
395 /// Checks if `#[cmse_nonsecure_entry]` is applied to a function definition.
396 fn check_cmse_nonsecure_entry(&self, attr: &Attribute, span: Span, target: Target) -> bool {
397 match target {
398 Target::Fn
399 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true,
400 _ => {
401 self.tcx.sess.emit_err(errors::AttrShouldBeAppliedToFn {
402 attr_span: attr.span,
403 defn_span: span,
404 });
405 false
406 }
407 }
408 }
409
410 /// Debugging aid for `object_lifetime_default` query.
411 fn check_object_lifetime_default(&self, hir_id: HirId) {
412 let tcx = self.tcx;
413 if let Some(generics) = tcx.hir().get_generics(tcx.hir().local_def_id(hir_id)) {
414 for p in generics.params {
415 let hir::GenericParamKind::Type { .. } = p.kind else { continue };
416 let param_id = tcx.hir().local_def_id(p.hir_id);
417 let default = tcx.object_lifetime_default(param_id);
418 let repr = match default {
419 ObjectLifetimeDefault::Empty => "BaseDefault".to_owned(),
420 ObjectLifetimeDefault::Static => "'static".to_owned(),
421 ObjectLifetimeDefault::Param(def_id) => tcx.item_name(def_id).to_string(),
422 ObjectLifetimeDefault::Ambiguous => "Ambiguous".to_owned(),
423 };
424 tcx.sess.emit_err(ObjectLifetimeErr { span: p.span, repr });
425 }
426 }
427 }
428
429 /// Checks if `#[collapse_debuginfo]` is applied to a macro.
430 fn check_collapse_debuginfo(&self, attr: &Attribute, span: Span, target: Target) -> bool {
431 match target {
432 Target::MacroDef => true,
433 _ => {
434 self.tcx
435 .sess
436 .emit_err(errors::CollapseDebuginfo { attr_span: attr.span, defn_span: span });
437 false
438 }
439 }
440 }
441
442 /// Checks if a `#[track_caller]` is applied to a non-naked function. Returns `true` if valid.
443 fn check_track_caller(
444 &self,
445 hir_id: HirId,
446 attr_span: Span,
447 attrs: &[Attribute],
448 span: Span,
449 target: Target,
450 ) -> bool {
451 match target {
452 _ if attrs.iter().any(|attr| attr.has_name(sym::naked)) => {
453 self.tcx.sess.emit_err(errors::NakedTrackedCaller { attr_span });
454 false
455 }
456 Target::Fn | Target::Method(..) | Target::ForeignFn | Target::Closure => true,
457 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
458 // `#[track_caller]` attribute with just a lint, because we previously
459 // erroneously allowed it and some crates used it accidentally, to be compatible
460 // with crates depending on them, we can't throw an error here.
461 Target::Field | Target::Arm | Target::MacroDef => {
462 for attr in attrs {
463 self.inline_attr_str_error_with_macro_def(hir_id, attr, "track_caller");
464 }
465 true
466 }
467 _ => {
468 self.tcx
469 .sess
470 .emit_err(errors::TrackedCallerWrongLocation { attr_span, defn_span: span });
471 false
472 }
473 }
474 }
475
476 /// Checks if the `#[non_exhaustive]` attribute on an `item` is valid. Returns `true` if valid.
477 fn check_non_exhaustive(
478 &self,
479 hir_id: HirId,
480 attr: &Attribute,
481 span: Span,
482 target: Target,
483 ) -> bool {
484 match target {
485 Target::Struct | Target::Enum | Target::Variant => true,
486 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
487 // `#[non_exhaustive]` attribute with just a lint, because we previously
488 // erroneously allowed it and some crates used it accidentally, to be compatible
489 // with crates depending on them, we can't throw an error here.
490 Target::Field | Target::Arm | Target::MacroDef => {
491 self.inline_attr_str_error_with_macro_def(hir_id, attr, "non_exhaustive");
492 true
493 }
494 _ => {
495 self.tcx.sess.emit_err(errors::NonExhaustiveWrongLocation {
496 attr_span: attr.span,
497 defn_span: span,
498 });
499 false
500 }
501 }
502 }
503
504 /// Checks if the `#[marker]` attribute on an `item` is valid. Returns `true` if valid.
505 fn check_marker(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) -> bool {
506 match target {
507 Target::Trait => true,
508 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
509 // `#[marker]` attribute with just a lint, because we previously
510 // erroneously allowed it and some crates used it accidentally, to be compatible
511 // with crates depending on them, we can't throw an error here.
512 Target::Field | Target::Arm | Target::MacroDef => {
513 self.inline_attr_str_error_with_macro_def(hir_id, attr, "marker");
514 true
515 }
516 _ => {
517 self.tcx.sess.emit_err(errors::AttrShouldBeAppliedToTrait {
518 attr_span: attr.span,
519 defn_span: span,
520 });
521 false
522 }
523 }
524 }
525
526 /// Checks if the `#[rustc_must_implement_one_of]` attribute on a `target` is valid. Returns `true` if valid.
527 fn check_rustc_must_implement_one_of(
528 &self,
529 attr: &Attribute,
530 span: Span,
531 target: Target,
532 ) -> bool {
533 match target {
534 Target::Trait => true,
535 _ => {
536 self.tcx.sess.emit_err(errors::AttrShouldBeAppliedToTrait {
537 attr_span: attr.span,
538 defn_span: span,
539 });
540 false
541 }
542 }
543 }
544
545 /// Checks if the `#[target_feature]` attribute on `item` is valid. Returns `true` if valid.
546 fn check_target_feature(
547 &self,
548 hir_id: HirId,
549 attr: &Attribute,
550 span: Span,
551 target: Target,
552 ) -> bool {
553 match target {
554 Target::Fn
555 | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true,
556 // FIXME: #[target_feature] was previously erroneously allowed on statements and some
557 // crates used this, so only emit a warning.
558 Target::Statement => {
559 self.tcx.emit_spanned_lint(
560 UNUSED_ATTRIBUTES,
561 hir_id,
562 attr.span,
563 errors::TargetFeatureOnStatement,
564 );
565 true
566 }
567 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
568 // `#[target_feature]` attribute with just a lint, because we previously
569 // erroneously allowed it and some crates used it accidentally, to be compatible
570 // with crates depending on them, we can't throw an error here.
571 Target::Field | Target::Arm | Target::MacroDef => {
572 self.inline_attr_str_error_with_macro_def(hir_id, attr, "target_feature");
573 true
574 }
575 _ => {
576 self.tcx.sess.emit_err(errors::AttrShouldBeAppliedToFn {
577 attr_span: attr.span,
578 defn_span: span,
579 });
580 false
581 }
582 }
583 }
584
585 /// Checks if the `#[thread_local]` attribute on `item` is valid. Returns `true` if valid.
586 fn check_thread_local(&self, attr: &Attribute, span: Span, target: Target) -> bool {
587 match target {
588 Target::ForeignStatic | Target::Static => true,
589 _ => {
590 self.tcx.sess.emit_err(errors::AttrShouldBeAppliedToStatic {
591 attr_span: attr.span,
592 defn_span: span,
593 });
594 false
595 }
596 }
597 }
598
599 fn doc_attr_str_error(&self, meta: &NestedMetaItem, attr_name: &str) {
600 self.tcx.sess.emit_err(errors::DocExpectStr { attr_span: meta.span(), attr_name });
601 }
602
603 fn check_doc_alias_value(
604 &self,
605 meta: &NestedMetaItem,
606 doc_alias: Symbol,
607 hir_id: HirId,
608 target: Target,
609 is_list: bool,
610 aliases: &mut FxHashMap<String, Span>,
611 ) -> bool {
612 let tcx = self.tcx;
613 let span = meta.name_value_literal_span().unwrap_or_else(|| meta.span());
614 let attr_str =
615 &format!("`#[doc(alias{})]`", if is_list { "(\"...\")" } else { " = \"...\"" });
616 if doc_alias == kw::Empty {
617 tcx.sess.emit_err(errors::DocAliasEmpty { span, attr_str });
618 return false;
619 }
620
621 let doc_alias_str = doc_alias.as_str();
622 if let Some(c) = doc_alias_str
623 .chars()
624 .find(|&c| c == '"' || c == '\'' || (c.is_whitespace() && c != ' '))
625 {
626 tcx.sess.emit_err(errors::DocAliasBadChar { span, attr_str, char_: c });
627 return false;
628 }
629 if doc_alias_str.starts_with(' ') || doc_alias_str.ends_with(' ') {
630 tcx.sess.emit_err(errors::DocAliasStartEnd { span, attr_str });
631 return false;
632 }
633
634 let span = meta.span();
635 if let Some(location) = match target {
636 Target::AssocTy => {
637 let parent_def_id = self.tcx.hir().get_parent_item(hir_id).def_id;
638 let containing_item = self.tcx.hir().expect_item(parent_def_id);
639 if Target::from_item(containing_item) == Target::Impl {
640 Some("type alias in implementation block")
641 } else {
642 None
643 }
644 }
645 Target::AssocConst => {
646 let parent_def_id = self.tcx.hir().get_parent_item(hir_id).def_id;
647 let containing_item = self.tcx.hir().expect_item(parent_def_id);
648 // We can't link to trait impl's consts.
649 let err = "associated constant in trait implementation block";
650 match containing_item.kind {
651 ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) => Some(err),
652 _ => None,
653 }
654 }
655 // we check the validity of params elsewhere
656 Target::Param => return false,
657 Target::Expression
658 | Target::Statement
659 | Target::Arm
660 | Target::ForeignMod
661 | Target::Closure
662 | Target::Impl => Some(target.name()),
663 Target::ExternCrate
664 | Target::Use
665 | Target::Static
666 | Target::Const
667 | Target::Fn
668 | Target::Mod
669 | Target::GlobalAsm
670 | Target::TyAlias
671 | Target::OpaqueTy
672 | Target::ImplTraitPlaceholder
673 | Target::Enum
674 | Target::Variant
675 | Target::Struct
676 | Target::Field
677 | Target::Union
678 | Target::Trait
679 | Target::TraitAlias
680 | Target::Method(..)
681 | Target::ForeignFn
682 | Target::ForeignStatic
683 | Target::ForeignTy
684 | Target::GenericParam(..)
685 | Target::MacroDef
686 | Target::PatField
687 | Target::ExprField => None,
688 } {
689 tcx.sess.emit_err(errors::DocAliasBadLocation { span, attr_str, location });
690 return false;
691 }
692 let item_name = self.tcx.hir().name(hir_id);
693 if item_name == doc_alias {
694 tcx.sess.emit_err(errors::DocAliasNotAnAlias { span, attr_str });
695 return false;
696 }
697 if let Err(entry) = aliases.try_insert(doc_alias_str.to_owned(), span) {
698 self.tcx.emit_spanned_lint(
699 UNUSED_ATTRIBUTES,
700 hir_id,
701 span,
702 errors::DocAliasDuplicated { first_defn: *entry.entry.get() },
703 );
704 }
705 true
706 }
707
708 fn check_doc_alias(
709 &self,
710 meta: &NestedMetaItem,
711 hir_id: HirId,
712 target: Target,
713 aliases: &mut FxHashMap<String, Span>,
714 ) -> bool {
715 if let Some(values) = meta.meta_item_list() {
716 let mut errors = 0;
717 for v in values {
718 match v.literal() {
719 Some(l) => match l.kind {
720 LitKind::Str(s, _) => {
721 if !self.check_doc_alias_value(v, s, hir_id, target, true, aliases) {
722 errors += 1;
723 }
724 }
725 _ => {
726 self.tcx
727 .sess
728 .emit_err(errors::DocAliasNotStringLiteral { span: v.span() });
729 errors += 1;
730 }
731 },
732 None => {
733 self.tcx.sess.emit_err(errors::DocAliasNotStringLiteral { span: v.span() });
734 errors += 1;
735 }
736 }
737 }
738 errors == 0
739 } else if let Some(doc_alias) = meta.value_str() {
740 self.check_doc_alias_value(meta, doc_alias, hir_id, target, false, aliases)
741 } else {
742 self.tcx.sess.emit_err(errors::DocAliasMalformed { span: meta.span() });
743 false
744 }
745 }
746
747 fn check_doc_keyword(&self, meta: &NestedMetaItem, hir_id: HirId) -> bool {
748 let doc_keyword = meta.value_str().unwrap_or(kw::Empty);
749 if doc_keyword == kw::Empty {
750 self.doc_attr_str_error(meta, "keyword");
751 return false;
752 }
753 match self.tcx.hir().find(hir_id).and_then(|node| match node {
754 hir::Node::Item(item) => Some(&item.kind),
755 _ => None,
756 }) {
757 Some(ItemKind::Mod(ref module)) => {
758 if !module.item_ids.is_empty() {
759 self.tcx.sess.emit_err(errors::DocKeywordEmptyMod { span: meta.span() });
760 return false;
761 }
762 }
763 _ => {
764 self.tcx.sess.emit_err(errors::DocKeywordNotMod { span: meta.span() });
765 return false;
766 }
767 }
768 if !rustc_lexer::is_ident(doc_keyword.as_str()) {
769 self.tcx.sess.emit_err(errors::DocKeywordInvalidIdent {
770 span: meta.name_value_literal_span().unwrap_or_else(|| meta.span()),
771 doc_keyword,
772 });
773 return false;
774 }
775 true
776 }
777
778 fn check_doc_fake_variadic(&self, meta: &NestedMetaItem, hir_id: HirId) -> bool {
779 match self.tcx.hir().find(hir_id).and_then(|node| match node {
780 hir::Node::Item(item) => Some(&item.kind),
781 _ => None,
782 }) {
783 Some(ItemKind::Impl(ref i)) => {
784 let is_valid = matches!(&i.self_ty.kind, hir::TyKind::Tup([_]))
785 || if let hir::TyKind::BareFn(bare_fn_ty) = &i.self_ty.kind {
786 bare_fn_ty.decl.inputs.len() == 1
787 } else {
788 false
789 };
790 if !is_valid {
791 self.tcx.sess.emit_err(errors::DocFakeVariadicNotValid { span: meta.span() });
792 return false;
793 }
794 }
795 _ => {
796 self.tcx.sess.emit_err(errors::DocKeywordOnlyImpl { span: meta.span() });
797 return false;
798 }
799 }
800 true
801 }
802
803 /// Checks `#[doc(inline)]`/`#[doc(no_inline)]` attributes. Returns `true` if valid.
804 ///
805 /// A doc inlining attribute is invalid if it is applied to a non-`use` item, or
806 /// if there are conflicting attributes for one item.
807 ///
808 /// `specified_inline` is used to keep track of whether we have
809 /// already seen an inlining attribute for this item.
810 /// If so, `specified_inline` holds the value and the span of
811 /// the first `inline`/`no_inline` attribute.
812 fn check_doc_inline(
813 &self,
814 attr: &Attribute,
815 meta: &NestedMetaItem,
816 hir_id: HirId,
817 target: Target,
818 specified_inline: &mut Option<(bool, Span)>,
819 ) -> bool {
820 if target == Target::Use || target == Target::ExternCrate {
821 let do_inline = meta.name_or_empty() == sym::inline;
822 if let Some((prev_inline, prev_span)) = *specified_inline {
823 if do_inline != prev_inline {
824 let mut spans = MultiSpan::from_spans(vec![prev_span, meta.span()]);
825 spans.push_span_label(prev_span, fluent::passes_doc_inline_conflict_first);
826 spans.push_span_label(meta.span(), fluent::passes_doc_inline_conflict_second);
827 self.tcx.sess.emit_err(errors::DocKeywordConflict { spans });
828 return false;
829 }
830 true
831 } else {
832 *specified_inline = Some((do_inline, meta.span()));
833 true
834 }
835 } else {
836 self.tcx.emit_spanned_lint(
837 INVALID_DOC_ATTRIBUTES,
838 hir_id,
839 meta.span(),
840 errors::DocInlineOnlyUse {
841 attr_span: meta.span(),
842 item_span: (attr.style == AttrStyle::Outer)
843 .then(|| self.tcx.hir().span(hir_id)),
844 },
845 );
846 false
847 }
848 }
849
850 /// Checks that an attribute is *not* used at the crate level. Returns `true` if valid.
851 fn check_attr_not_crate_level(
852 &self,
853 meta: &NestedMetaItem,
854 hir_id: HirId,
855 attr_name: &str,
856 ) -> bool {
857 if CRATE_HIR_ID == hir_id {
858 self.tcx.sess.emit_err(errors::DocAttrNotCrateLevel { span: meta.span(), attr_name });
859 return false;
860 }
861 true
862 }
863
864 /// Checks that an attribute is used at the crate level. Returns `true` if valid.
865 fn check_attr_crate_level(
866 &self,
867 attr: &Attribute,
868 meta: &NestedMetaItem,
869 hir_id: HirId,
870 ) -> bool {
871 if hir_id != CRATE_HIR_ID {
872 self.tcx.struct_span_lint_hir(
873 INVALID_DOC_ATTRIBUTES,
874 hir_id,
875 meta.span(),
876 fluent::passes_attr_crate_level,
877 |err| {
878 if attr.style == AttrStyle::Outer
879 && self.tcx.hir().get_parent_item(hir_id) == CRATE_OWNER_ID
880 {
881 if let Ok(mut src) = self.tcx.sess.source_map().span_to_snippet(attr.span) {
882 src.insert(1, '!');
883 err.span_suggestion_verbose(
884 attr.span,
885 fluent::suggestion,
886 src,
887 Applicability::MaybeIncorrect,
888 );
889 } else {
890 err.span_help(attr.span, fluent::help);
891 }
892 }
893 err.note(fluent::note);
894 err
895 },
896 );
897 return false;
898 }
899 true
900 }
901
902 /// Checks that `doc(test(...))` attribute contains only valid attributes. Returns `true` if
903 /// valid.
904 fn check_test_attr(&self, meta: &NestedMetaItem, hir_id: HirId) -> bool {
905 let mut is_valid = true;
906 if let Some(metas) = meta.meta_item_list() {
907 for i_meta in metas {
908 match i_meta.name_or_empty() {
909 sym::attr | sym::no_crate_inject => {}
910 _ => {
911 self.tcx.emit_spanned_lint(
912 INVALID_DOC_ATTRIBUTES,
913 hir_id,
914 i_meta.span(),
915 errors::DocTestUnknown {
916 path: rustc_ast_pretty::pprust::path_to_string(
917 &i_meta.meta_item().unwrap().path,
918 ),
919 },
920 );
921 is_valid = false;
922 }
923 }
924 }
925 } else {
926 self.tcx.emit_spanned_lint(
927 INVALID_DOC_ATTRIBUTES,
928 hir_id,
929 meta.span(),
930 errors::DocTestTakesList,
931 );
932 is_valid = false;
933 }
934 is_valid
935 }
936
937 /// Check that the `#![doc(cfg_hide(...))]` attribute only contains a list of attributes.
938 /// Returns `true` if valid.
939 fn check_doc_cfg_hide(&self, meta: &NestedMetaItem, hir_id: HirId) -> bool {
940 if meta.meta_item_list().is_some() {
941 true
942 } else {
943 self.tcx.emit_spanned_lint(
944 INVALID_DOC_ATTRIBUTES,
945 hir_id,
946 meta.span(),
947 errors::DocCfgHideTakesList,
948 );
949 false
950 }
951 }
952
953 /// Runs various checks on `#[doc]` attributes. Returns `true` if valid.
954 ///
955 /// `specified_inline` should be initialized to `None` and kept for the scope
956 /// of one item. Read the documentation of [`check_doc_inline`] for more information.
957 ///
958 /// [`check_doc_inline`]: Self::check_doc_inline
959 fn check_doc_attrs(
960 &self,
961 attr: &Attribute,
962 hir_id: HirId,
963 target: Target,
964 specified_inline: &mut Option<(bool, Span)>,
965 aliases: &mut FxHashMap<String, Span>,
966 ) -> bool {
967 let mut is_valid = true;
968
969 if let Some(mi) = attr.meta() && let Some(list) = mi.meta_item_list() {
970 for meta in list {
971 if let Some(i_meta) = meta.meta_item() {
972 match i_meta.name_or_empty() {
973 sym::alias
974 if !self.check_attr_not_crate_level(meta, hir_id, "alias")
975 || !self.check_doc_alias(meta, hir_id, target, aliases) =>
976 {
977 is_valid = false
978 }
979
980 sym::keyword
981 if !self.check_attr_not_crate_level(meta, hir_id, "keyword")
982 || !self.check_doc_keyword(meta, hir_id) =>
983 {
984 is_valid = false
985 }
986
987 sym::fake_variadic
988 if !self.check_attr_not_crate_level(meta, hir_id, "fake_variadic")
989 || !self.check_doc_fake_variadic(meta, hir_id) =>
990 {
991 is_valid = false
992 }
993
994 sym::html_favicon_url
995 | sym::html_logo_url
996 | sym::html_playground_url
997 | sym::issue_tracker_base_url
998 | sym::html_root_url
999 | sym::html_no_source
1000 | sym::test
1001 if !self.check_attr_crate_level(attr, meta, hir_id) =>
1002 {
1003 is_valid = false;
1004 }
1005
1006 sym::cfg_hide
1007 if !self.check_attr_crate_level(attr, meta, hir_id)
1008 || !self.check_doc_cfg_hide(meta, hir_id) =>
1009 {
1010 is_valid = false;
1011 }
1012
1013 sym::inline | sym::no_inline
1014 if !self.check_doc_inline(
1015 attr,
1016 meta,
1017 hir_id,
1018 target,
1019 specified_inline,
1020 ) =>
1021 {
1022 is_valid = false;
1023 }
1024
1025 // no_default_passes: deprecated
1026 // passes: deprecated
1027 // plugins: removed, but rustdoc warns about it itself
1028 sym::alias
1029 | sym::cfg
1030 | sym::cfg_hide
1031 | sym::hidden
1032 | sym::html_favicon_url
1033 | sym::html_logo_url
1034 | sym::html_no_source
1035 | sym::html_playground_url
1036 | sym::html_root_url
1037 | sym::inline
1038 | sym::issue_tracker_base_url
1039 | sym::keyword
1040 | sym::masked
1041 | sym::no_default_passes
1042 | sym::no_inline
1043 | sym::notable_trait
1044 | sym::passes
1045 | sym::plugins
1046 | sym::fake_variadic => {}
1047
1048 sym::test => {
1049 if !self.check_test_attr(meta, hir_id) {
1050 is_valid = false;
1051 }
1052 }
1053
1054 sym::primitive => {
1055 if !self.tcx.features().rustdoc_internals {
1056 self.tcx.emit_spanned_lint(
1057 INVALID_DOC_ATTRIBUTES,
1058 hir_id,
1059 i_meta.span,
1060 errors::DocPrimitive,
1061 );
1062 }
1063 }
1064
1065 _ => {
1066 let path = rustc_ast_pretty::pprust::path_to_string(&i_meta.path);
1067 if i_meta.has_name(sym::spotlight) {
1068 self.tcx.emit_spanned_lint(
1069 INVALID_DOC_ATTRIBUTES,
1070 hir_id,
1071 i_meta.span,
1072 errors::DocTestUnknownSpotlight {
1073 path,
1074 span: i_meta.span
1075 }
1076 );
1077 } else if i_meta.has_name(sym::include) &&
1078 let Some(value) = i_meta.value_str() {
1079 let applicability = if list.len() == 1 {
1080 Applicability::MachineApplicable
1081 } else {
1082 Applicability::MaybeIncorrect
1083 };
1084 // If there are multiple attributes, the suggestion would suggest
1085 // deleting all of them, which is incorrect.
1086 self.tcx.emit_spanned_lint(
1087 INVALID_DOC_ATTRIBUTES,
1088 hir_id,
1089 i_meta.span,
1090 errors::DocTestUnknownInclude {
1091 path,
1092 value: value.to_string(),
1093 inner: (attr.style == AttrStyle::Inner)
1094 .then_some("!")
1095 .unwrap_or(""),
1096 sugg: (attr.meta().unwrap().span, applicability),
1097 }
1098 );
1099 } else {
1100 self.tcx.emit_spanned_lint(
1101 INVALID_DOC_ATTRIBUTES,
1102 hir_id,
1103 i_meta.span,
1104 errors::DocTestUnknownAny { path }
1105 );
1106 }
1107 is_valid = false;
1108 }
1109 }
1110 } else {
1111 self.tcx.emit_spanned_lint(
1112 INVALID_DOC_ATTRIBUTES,
1113 hir_id,
1114 meta.span(),
1115 errors::DocInvalid,
1116 );
1117 is_valid = false;
1118 }
1119 }
1120 }
1121
1122 is_valid
1123 }
1124
1125 /// Warns against some misuses of `#[pass_by_value]`
1126 fn check_pass_by_value(&self, attr: &Attribute, span: Span, target: Target) -> bool {
1127 match target {
1128 Target::Struct | Target::Enum | Target::TyAlias => true,
1129 _ => {
1130 self.tcx.sess.emit_err(errors::PassByValue { attr_span: attr.span, span });
1131 false
1132 }
1133 }
1134 }
1135
1136 fn check_allow_incoherent_impl(&self, attr: &Attribute, span: Span, target: Target) -> bool {
1137 match target {
1138 Target::Method(MethodKind::Inherent) => true,
1139 _ => {
1140 self.tcx.sess.emit_err(errors::AllowIncoherentImpl { attr_span: attr.span, span });
1141 false
1142 }
1143 }
1144 }
1145
1146 fn check_has_incoherent_inherent_impls(
1147 &self,
1148 attr: &Attribute,
1149 span: Span,
1150 target: Target,
1151 ) -> bool {
1152 match target {
1153 Target::Trait | Target::Struct | Target::Enum | Target::Union | Target::ForeignTy => {
1154 true
1155 }
1156 _ => {
1157 self.tcx
1158 .sess
1159 .emit_err(errors::HasIncoherentInherentImpl { attr_span: attr.span, span });
1160 false
1161 }
1162 }
1163 }
1164
1165 /// Warns against some misuses of `#[must_use]`
1166 fn check_must_use(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) -> bool {
1167 let node = self.tcx.hir().get(hir_id);
1168 if let Some(kind) = node.fn_kind() && let rustc_hir::IsAsync::Async = kind.asyncness() {
1169 self.tcx.emit_spanned_lint(
1170 UNUSED_ATTRIBUTES,
1171 hir_id,
1172 attr.span,
1173 errors::MustUseAsync { span }
1174 );
1175 }
1176
1177 if !matches!(
1178 target,
1179 Target::Fn
1180 | Target::Enum
1181 | Target::Struct
1182 | Target::Union
1183 | Target::Method(_)
1184 | Target::ForeignFn
1185 // `impl Trait` in return position can trip
1186 // `unused_must_use` if `Trait` is marked as
1187 // `#[must_use]`
1188 | Target::Trait
1189 ) {
1190 let article = match target {
1191 Target::ExternCrate
1192 | Target::OpaqueTy
1193 | Target::Enum
1194 | Target::Impl
1195 | Target::Expression
1196 | Target::Arm
1197 | Target::AssocConst
1198 | Target::AssocTy => "an",
1199 _ => "a",
1200 };
1201
1202 self.tcx.emit_spanned_lint(
1203 UNUSED_ATTRIBUTES,
1204 hir_id,
1205 attr.span,
1206 errors::MustUseNoEffect { article, target },
1207 );
1208 }
1209
1210 // For now, its always valid
1211 true
1212 }
1213
1214 /// Checks if `#[must_not_suspend]` is applied to a function. Returns `true` if valid.
1215 fn check_must_not_suspend(&self, attr: &Attribute, span: Span, target: Target) -> bool {
1216 match target {
1217 Target::Struct | Target::Enum | Target::Union | Target::Trait => true,
1218 _ => {
1219 self.tcx.sess.emit_err(errors::MustNotSuspend { attr_span: attr.span, span });
1220 false
1221 }
1222 }
1223 }
1224
1225 /// Checks if `#[cold]` is applied to a non-function. Returns `true` if valid.
1226 fn check_cold(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) {
1227 match target {
1228 Target::Fn | Target::Method(..) | Target::ForeignFn | Target::Closure => {}
1229 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
1230 // `#[cold]` attribute with just a lint, because we previously
1231 // erroneously allowed it and some crates used it accidentally, to be compatible
1232 // with crates depending on them, we can't throw an error here.
1233 Target::Field | Target::Arm | Target::MacroDef => {
1234 self.inline_attr_str_error_with_macro_def(hir_id, attr, "cold");
1235 }
1236 _ => {
1237 // FIXME: #[cold] was previously allowed on non-functions and some crates used
1238 // this, so only emit a warning.
1239 self.tcx.emit_spanned_lint(
1240 UNUSED_ATTRIBUTES,
1241 hir_id,
1242 attr.span,
1243 errors::Cold { span },
1244 );
1245 }
1246 }
1247 }
1248
1249 /// Checks if `#[link]` is applied to an item other than a foreign module.
1250 fn check_link(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) {
1251 if target == Target::ForeignMod
1252 && let hir::Node::Item(item) = self.tcx.hir().get(hir_id)
1253 && let Item { kind: ItemKind::ForeignMod { abi, .. }, .. } = item
1254 && !matches!(abi, Abi::Rust | Abi::RustIntrinsic | Abi::PlatformIntrinsic)
1255 {
1256 return;
1257 }
1258
1259 self.tcx.emit_spanned_lint(
1260 UNUSED_ATTRIBUTES,
1261 hir_id,
1262 attr.span,
1263 errors::Link { span: (target != Target::ForeignMod).then_some(span) },
1264 );
1265 }
1266
1267 /// Checks if `#[link_name]` is applied to an item other than a foreign function or static.
1268 fn check_link_name(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) {
1269 match target {
1270 Target::ForeignFn | Target::ForeignStatic => {}
1271 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
1272 // `#[link_name]` attribute with just a lint, because we previously
1273 // erroneously allowed it and some crates used it accidentally, to be compatible
1274 // with crates depending on them, we can't throw an error here.
1275 Target::Field | Target::Arm | Target::MacroDef => {
1276 self.inline_attr_str_error_with_macro_def(hir_id, attr, "link_name");
1277 }
1278 _ => {
1279 // FIXME: #[cold] was previously allowed on non-functions/statics and some crates
1280 // used this, so only emit a warning.
1281 let attr_span = matches!(target, Target::ForeignMod).then_some(attr.span);
1282 if let Some(s) = attr.value_str() {
1283 self.tcx.emit_spanned_lint(
1284 UNUSED_ATTRIBUTES,
1285 hir_id,
1286 attr.span,
1287 errors::LinkName { span, attr_span, value: s.as_str() },
1288 );
1289 } else {
1290 self.tcx.emit_spanned_lint(
1291 UNUSED_ATTRIBUTES,
1292 hir_id,
1293 attr.span,
1294 errors::LinkName { span, attr_span, value: "..." },
1295 );
1296 };
1297 }
1298 }
1299 }
1300
1301 /// Checks if `#[no_link]` is applied to an `extern crate`. Returns `true` if valid.
1302 fn check_no_link(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) -> bool {
1303 match target {
1304 Target::ExternCrate => true,
1305 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
1306 // `#[no_link]` attribute with just a lint, because we previously
1307 // erroneously allowed it and some crates used it accidentally, to be compatible
1308 // with crates depending on them, we can't throw an error here.
1309 Target::Field | Target::Arm | Target::MacroDef => {
1310 self.inline_attr_str_error_with_macro_def(hir_id, attr, "no_link");
1311 true
1312 }
1313 _ => {
1314 self.tcx.sess.emit_err(errors::NoLink { attr_span: attr.span, span });
1315 false
1316 }
1317 }
1318 }
1319
1320 fn is_impl_item(&self, hir_id: HirId) -> bool {
1321 matches!(self.tcx.hir().get(hir_id), hir::Node::ImplItem(..))
1322 }
1323
1324 /// Checks if `#[export_name]` is applied to a function or static. Returns `true` if valid.
1325 fn check_export_name(
1326 &self,
1327 hir_id: HirId,
1328 attr: &Attribute,
1329 span: Span,
1330 target: Target,
1331 ) -> bool {
1332 match target {
1333 Target::Static | Target::Fn => true,
1334 Target::Method(..) if self.is_impl_item(hir_id) => true,
1335 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
1336 // `#[export_name]` attribute with just a lint, because we previously
1337 // erroneously allowed it and some crates used it accidentally, to be compatible
1338 // with crates depending on them, we can't throw an error here.
1339 Target::Field | Target::Arm | Target::MacroDef => {
1340 self.inline_attr_str_error_with_macro_def(hir_id, attr, "export_name");
1341 true
1342 }
1343 _ => {
1344 self.tcx.sess.emit_err(errors::ExportName { attr_span: attr.span, span });
1345 false
1346 }
1347 }
1348 }
1349
1350 fn check_rustc_layout_scalar_valid_range(
1351 &self,
1352 attr: &Attribute,
1353 span: Span,
1354 target: Target,
1355 ) -> bool {
1356 if target != Target::Struct {
1357 self.tcx.sess.emit_err(errors::RustcLayoutScalarValidRangeNotStruct {
1358 attr_span: attr.span,
1359 span,
1360 });
1361 return false;
1362 }
1363
1364 let Some(list) = attr.meta_item_list() else {
1365 return false;
1366 };
1367
1368 if matches!(&list[..], &[NestedMetaItem::Literal(Lit { kind: LitKind::Int(..), .. })]) {
1369 true
1370 } else {
1371 self.tcx.sess.emit_err(errors::RustcLayoutScalarValidRangeArg { attr_span: attr.span });
1372 false
1373 }
1374 }
1375
1376 /// Checks if `#[rustc_legacy_const_generics]` is applied to a function and has a valid argument.
1377 fn check_rustc_legacy_const_generics(
1378 &self,
1379 attr: &Attribute,
1380 span: Span,
1381 target: Target,
1382 item: Option<ItemLike<'_>>,
1383 ) -> bool {
1384 let is_function = matches!(target, Target::Fn);
1385 if !is_function {
1386 self.tcx.sess.emit_err(errors::AttrShouldBeAppliedToFn {
1387 attr_span: attr.span,
1388 defn_span: span,
1389 });
1390 return false;
1391 }
1392
1393 let Some(list) = attr.meta_item_list() else {
1394 // The attribute form is validated on AST.
1395 return false;
1396 };
1397
1398 let Some(ItemLike::Item(Item {
1399 kind: ItemKind::Fn(FnSig { decl, .. }, generics, _),
1400 ..
1401 })) = item else {
1402 bug!("should be a function item");
1403 };
1404
1405 for param in generics.params {
1406 match param.kind {
1407 hir::GenericParamKind::Const { .. } => {}
1408 _ => {
1409 self.tcx.sess.emit_err(errors::RustcLegacyConstGenericsOnly {
1410 attr_span: attr.span,
1411 param_span: param.span,
1412 });
1413 return false;
1414 }
1415 }
1416 }
1417
1418 if list.len() != generics.params.len() {
1419 self.tcx.sess.emit_err(errors::RustcLegacyConstGenericsIndex {
1420 attr_span: attr.span,
1421 generics_span: generics.span,
1422 });
1423 return false;
1424 }
1425
1426 let arg_count = decl.inputs.len() as u128 + generics.params.len() as u128;
1427 let mut invalid_args = vec![];
1428 for meta in list {
1429 if let Some(LitKind::Int(val, _)) = meta.literal().map(|lit| &lit.kind) {
1430 if *val >= arg_count {
1431 let span = meta.span();
1432 self.tcx.sess.emit_err(errors::RustcLegacyConstGenericsIndexExceed {
1433 span,
1434 arg_count: arg_count as usize,
1435 });
1436 return false;
1437 }
1438 } else {
1439 invalid_args.push(meta.span());
1440 }
1441 }
1442
1443 if !invalid_args.is_empty() {
1444 self.tcx.sess.emit_err(errors::RustcLegacyConstGenericsIndexNegative { invalid_args });
1445 false
1446 } else {
1447 true
1448 }
1449 }
1450
1451 /// Helper function for checking that the provided attribute is only applied to a function or
1452 /// method.
1453 fn check_applied_to_fn_or_method(&self, attr: &Attribute, span: Span, target: Target) -> bool {
1454 let is_function = matches!(target, Target::Fn | Target::Method(..));
1455 if !is_function {
1456 self.tcx.sess.emit_err(errors::AttrShouldBeAppliedToFn {
1457 attr_span: attr.span,
1458 defn_span: span,
1459 });
1460 false
1461 } else {
1462 true
1463 }
1464 }
1465
1466 /// Checks that the `#[rustc_lint_query_instability]` attribute is only applied to a function
1467 /// or method.
1468 fn check_rustc_lint_query_instability(
1469 &self,
1470 attr: &Attribute,
1471 span: Span,
1472 target: Target,
1473 ) -> bool {
1474 self.check_applied_to_fn_or_method(attr, span, target)
1475 }
1476
1477 /// Checks that the `#[rustc_lint_diagnostics]` attribute is only applied to a function or
1478 /// method.
1479 fn check_rustc_lint_diagnostics(&self, attr: &Attribute, span: Span, target: Target) -> bool {
1480 self.check_applied_to_fn_or_method(attr, span, target)
1481 }
1482
1483 /// Checks that the `#[rustc_lint_opt_ty]` attribute is only applied to a struct.
1484 fn check_rustc_lint_opt_ty(&self, attr: &Attribute, span: Span, target: Target) -> bool {
1485 match target {
1486 Target::Struct => true,
1487 _ => {
1488 self.tcx.sess.emit_err(errors::RustcLintOptTy { attr_span: attr.span, span });
1489 false
1490 }
1491 }
1492 }
1493
1494 /// Checks that the `#[rustc_lint_opt_deny_field_access]` attribute is only applied to a field.
1495 fn check_rustc_lint_opt_deny_field_access(
1496 &self,
1497 attr: &Attribute,
1498 span: Span,
1499 target: Target,
1500 ) -> bool {
1501 match target {
1502 Target::Field => true,
1503 _ => {
1504 self.tcx
1505 .sess
1506 .emit_err(errors::RustcLintOptDenyFieldAccess { attr_span: attr.span, span });
1507 false
1508 }
1509 }
1510 }
1511
1512 /// Checks that the dep-graph debugging attributes are only present when the query-dep-graph
1513 /// option is passed to the compiler.
1514 fn check_rustc_dirty_clean(&self, attr: &Attribute) -> bool {
1515 if self.tcx.sess.opts.unstable_opts.query_dep_graph {
1516 true
1517 } else {
1518 self.tcx.sess.emit_err(errors::RustcDirtyClean { span: attr.span });
1519 false
1520 }
1521 }
1522
1523 /// Checks if `#[link_section]` is applied to a function or static.
1524 fn check_link_section(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) {
1525 match target {
1526 Target::Static | Target::Fn | Target::Method(..) => {}
1527 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
1528 // `#[link_section]` attribute with just a lint, because we previously
1529 // erroneously allowed it and some crates used it accidentally, to be compatible
1530 // with crates depending on them, we can't throw an error here.
1531 Target::Field | Target::Arm | Target::MacroDef => {
1532 self.inline_attr_str_error_with_macro_def(hir_id, attr, "link_section");
1533 }
1534 _ => {
1535 // FIXME: #[link_section] was previously allowed on non-functions/statics and some
1536 // crates used this, so only emit a warning.
1537 self.tcx.emit_spanned_lint(
1538 UNUSED_ATTRIBUTES,
1539 hir_id,
1540 attr.span,
1541 errors::LinkSection { span },
1542 );
1543 }
1544 }
1545 }
1546
1547 /// Checks if `#[no_mangle]` is applied to a function or static.
1548 fn check_no_mangle(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) {
1549 match target {
1550 Target::Static | Target::Fn => {}
1551 Target::Method(..) if self.is_impl_item(hir_id) => {}
1552 // FIXME(#80564): We permit struct fields, match arms and macro defs to have an
1553 // `#[no_mangle]` attribute with just a lint, because we previously
1554 // erroneously allowed it and some crates used it accidentally, to be compatible
1555 // with crates depending on them, we can't throw an error here.
1556 Target::Field | Target::Arm | Target::MacroDef => {
1557 self.inline_attr_str_error_with_macro_def(hir_id, attr, "no_mangle");
1558 }
1559 // FIXME: #[no_mangle] was previously allowed on non-functions/statics, this should be an error
1560 // The error should specify that the item that is wrong is specifically a *foreign* fn/static
1561 // otherwise the error seems odd
1562 Target::ForeignFn | Target::ForeignStatic => {
1563 let foreign_item_kind = match target {
1564 Target::ForeignFn => "function",
1565 Target::ForeignStatic => "static",
1566 _ => unreachable!(),
1567 };
1568 self.tcx.emit_spanned_lint(
1569 UNUSED_ATTRIBUTES,
1570 hir_id,
1571 attr.span,
1572 errors::NoMangleForeign { span, attr_span: attr.span, foreign_item_kind },
1573 );
1574 }
1575 _ => {
1576 // FIXME: #[no_mangle] was previously allowed on non-functions/statics and some
1577 // crates used this, so only emit a warning.
1578 self.tcx.emit_spanned_lint(
1579 UNUSED_ATTRIBUTES,
1580 hir_id,
1581 attr.span,
1582 errors::NoMangle { span },
1583 );
1584 }
1585 }
1586 }
1587
1588 /// Checks if the `#[repr]` attributes on `item` are valid.
1589 fn check_repr(
1590 &self,
1591 attrs: &[Attribute],
1592 span: Span,
1593 target: Target,
1594 item: Option<ItemLike<'_>>,
1595 hir_id: HirId,
1596 ) {
1597 // Extract the names of all repr hints, e.g., [foo, bar, align] for:
1598 // ```
1599 // #[repr(foo)]
1600 // #[repr(bar, align(8))]
1601 // ```
1602 let hints: Vec<_> = attrs
1603 .iter()
1604 .filter(|attr| attr.has_name(sym::repr))
1605 .filter_map(|attr| attr.meta_item_list())
1606 .flatten()
1607 .collect();
1608
1609 let mut int_reprs = 0;
1610 let mut is_c = false;
1611 let mut is_simd = false;
1612 let mut is_transparent = false;
1613
1614 for hint in &hints {
1615 if !hint.is_meta_item() {
1616 self.tcx.sess.emit_err(errors::ReprIdent { span: hint.span() });
1617 continue;
1618 }
1619
1620 match hint.name_or_empty() {
1621 sym::C => {
1622 is_c = true;
1623 match target {
1624 Target::Struct | Target::Union | Target::Enum => continue,
1625 _ => {
1626 self.tcx.sess.emit_err(AttrApplication::StructEnumUnion {
1627 hint_span: hint.span(),
1628 span,
1629 });
1630 }
1631 }
1632 }
1633 sym::align => {
1634 if let (Target::Fn, false) = (target, self.tcx.features().fn_align) {
1635 feature_err(
1636 &self.tcx.sess.parse_sess,
1637 sym::fn_align,
1638 hint.span(),
1639 "`repr(align)` attributes on functions are unstable",
1640 )
1641 .emit();
1642 }
1643
1644 match target {
1645 Target::Struct | Target::Union | Target::Enum | Target::Fn => continue,
1646 _ => {
1647 self.tcx.sess.emit_err(AttrApplication::StructEnumFunctionUnion {
1648 hint_span: hint.span(),
1649 span,
1650 });
1651 }
1652 }
1653 }
1654 sym::packed => {
1655 if target != Target::Struct && target != Target::Union {
1656 self.tcx.sess.emit_err(AttrApplication::StructUnion {
1657 hint_span: hint.span(),
1658 span,
1659 });
1660 } else {
1661 continue;
1662 }
1663 }
1664 sym::simd => {
1665 is_simd = true;
1666 if target != Target::Struct {
1667 self.tcx
1668 .sess
1669 .emit_err(AttrApplication::Struct { hint_span: hint.span(), span });
1670 } else {
1671 continue;
1672 }
1673 }
1674 sym::transparent => {
1675 is_transparent = true;
1676 match target {
1677 Target::Struct | Target::Union | Target::Enum => continue,
1678 _ => {
1679 self.tcx.sess.emit_err(AttrApplication::StructEnumUnion {
1680 hint_span: hint.span(),
1681 span,
1682 });
1683 }
1684 }
1685 }
1686 sym::i8
1687 | sym::u8
1688 | sym::i16
1689 | sym::u16
1690 | sym::i32
1691 | sym::u32
1692 | sym::i64
1693 | sym::u64
1694 | sym::i128
1695 | sym::u128
1696 | sym::isize
1697 | sym::usize => {
1698 int_reprs += 1;
1699 if target != Target::Enum {
1700 self.tcx
1701 .sess
1702 .emit_err(AttrApplication::Enum { hint_span: hint.span(), span });
1703 } else {
1704 continue;
1705 }
1706 }
1707 _ => {
1708 self.tcx.sess.emit_err(UnrecognizedReprHint { span: hint.span() });
1709 continue;
1710 }
1711 };
1712 }
1713
1714 // Just point at all repr hints if there are any incompatibilities.
1715 // This is not ideal, but tracking precisely which ones are at fault is a huge hassle.
1716 let hint_spans = hints.iter().map(|hint| hint.span());
1717
1718 // Error on repr(transparent, <anything else>).
1719 if is_transparent && hints.len() > 1 {
1720 let hint_spans: Vec<_> = hint_spans.clone().collect();
1721 self.tcx
1722 .sess
1723 .emit_err(TransparentIncompatible { hint_spans, target: target.to_string() });
1724 }
1725 // Warn on repr(u8, u16), repr(C, simd), and c-like-enum-repr(C, u8)
1726 if (int_reprs > 1)
1727 || (is_simd && is_c)
1728 || (int_reprs == 1
1729 && is_c
1730 && item.map_or(false, |item| {
1731 if let ItemLike::Item(item) = item {
1732 return is_c_like_enum(item);
1733 }
1734 return false;
1735 }))
1736 {
1737 self.tcx.emit_spanned_lint(
1738 CONFLICTING_REPR_HINTS,
1739 hir_id,
1740 hint_spans.collect::<Vec<Span>>(),
1741 errors::ReprConflicting,
1742 );
1743 }
1744 }
1745
1746 fn check_used(&self, attrs: &[Attribute], target: Target) {
1747 let mut used_linker_span = None;
1748 let mut used_compiler_span = None;
1749 for attr in attrs.iter().filter(|attr| attr.has_name(sym::used)) {
1750 if target != Target::Static {
1751 self.tcx.sess.emit_err(errors::UsedStatic { span: attr.span });
1752 }
1753 let inner = attr.meta_item_list();
1754 match inner.as_deref() {
1755 Some([item]) if item.has_name(sym::linker) => {
1756 if used_linker_span.is_none() {
1757 used_linker_span = Some(attr.span);
1758 }
1759 }
1760 Some([item]) if item.has_name(sym::compiler) => {
1761 if used_compiler_span.is_none() {
1762 used_compiler_span = Some(attr.span);
1763 }
1764 }
1765 Some(_) => {
1766 // This error case is handled in rustc_hir_analysis::collect.
1767 }
1768 None => {
1769 // Default case (compiler) when arg isn't defined.
1770 if used_compiler_span.is_none() {
1771 used_compiler_span = Some(attr.span);
1772 }
1773 }
1774 }
1775 }
1776 if let (Some(linker_span), Some(compiler_span)) = (used_linker_span, used_compiler_span) {
1777 self.tcx
1778 .sess
1779 .emit_err(errors::UsedCompilerLinker { spans: vec![linker_span, compiler_span] });
1780 }
1781 }
1782
1783 /// Outputs an error for `#[allow_internal_unstable]` which can only be applied to macros.
1784 /// (Allows proc_macro functions)
1785 fn check_allow_internal_unstable(
1786 &self,
1787 hir_id: HirId,
1788 attr: &Attribute,
1789 span: Span,
1790 target: Target,
1791 attrs: &[Attribute],
1792 ) -> bool {
1793 debug!("Checking target: {:?}", target);
1794 match target {
1795 Target::Fn => {
1796 for attr in attrs {
1797 if self.tcx.sess.is_proc_macro_attr(attr) {
1798 debug!("Is proc macro attr");
1799 return true;
1800 }
1801 }
1802 debug!("Is not proc macro attr");
1803 false
1804 }
1805 Target::MacroDef => true,
1806 // FIXME(#80564): We permit struct fields and match arms to have an
1807 // `#[allow_internal_unstable]` attribute with just a lint, because we previously
1808 // erroneously allowed it and some crates used it accidentally, to be compatible
1809 // with crates depending on them, we can't throw an error here.
1810 Target::Field | Target::Arm => {
1811 self.inline_attr_str_error_without_macro_def(
1812 hir_id,
1813 attr,
1814 "allow_internal_unstable",
1815 );
1816 true
1817 }
1818 _ => {
1819 self.tcx
1820 .sess
1821 .emit_err(errors::AllowInternalUnstable { attr_span: attr.span, span });
1822 false
1823 }
1824 }
1825 }
1826
1827 /// Checks if the items on the `#[debugger_visualizer]` attribute are valid.
1828 fn check_debugger_visualizer(&self, attr: &Attribute, target: Target) -> bool {
1829 match target {
1830 Target::Mod => {}
1831 _ => {
1832 self.tcx.sess.emit_err(errors::DebugVisualizerPlacement { span: attr.span });
1833 return false;
1834 }
1835 }
1836
1837 let Some(hints) = attr.meta_item_list() else {
1838 self.tcx.sess.emit_err(errors::DebugVisualizerInvalid { span: attr.span });
1839 return false;
1840 };
1841
1842 let hint = match hints.len() {
1843 1 => &hints[0],
1844 _ => {
1845 self.tcx.sess.emit_err(errors::DebugVisualizerInvalid { span: attr.span });
1846 return false;
1847 }
1848 };
1849
1850 let Some(meta_item) = hint.meta_item() else {
1851 self.tcx.sess.emit_err(errors::DebugVisualizerInvalid { span: attr.span });
1852 return false;
1853 };
1854
1855 let visualizer_path = match (meta_item.name_or_empty(), meta_item.value_str()) {
1856 (sym::natvis_file, Some(value)) => value,
1857 (sym::gdb_script_file, Some(value)) => value,
1858 (_, _) => {
1859 self.tcx.sess.emit_err(errors::DebugVisualizerInvalid { span: meta_item.span });
1860 return false;
1861 }
1862 };
1863
1864 let file =
1865 match resolve_path(&self.tcx.sess.parse_sess, visualizer_path.as_str(), attr.span) {
1866 Ok(file) => file,
1867 Err(mut err) => {
1868 err.emit();
1869 return false;
1870 }
1871 };
1872
1873 match std::fs::File::open(&file) {
1874 Ok(_) => true,
1875 Err(error) => {
1876 self.tcx.sess.emit_err(DebugVisualizerUnreadable {
1877 span: meta_item.span,
1878 file: &file,
1879 error,
1880 });
1881 false
1882 }
1883 }
1884 }
1885
1886 /// Outputs an error for `#[allow_internal_unstable]` which can only be applied to macros.
1887 /// (Allows proc_macro functions)
1888 fn check_rustc_allow_const_fn_unstable(
1889 &self,
1890 hir_id: HirId,
1891 attr: &Attribute,
1892 span: Span,
1893 target: Target,
1894 ) -> bool {
1895 match target {
1896 Target::Fn | Target::Method(_)
1897 if self.tcx.is_const_fn_raw(self.tcx.hir().local_def_id(hir_id).to_def_id()) =>
1898 {
1899 true
1900 }
1901 // FIXME(#80564): We permit struct fields and match arms to have an
1902 // `#[allow_internal_unstable]` attribute with just a lint, because we previously
1903 // erroneously allowed it and some crates used it accidentally, to be compatible
1904 // with crates depending on them, we can't throw an error here.
1905 Target::Field | Target::Arm | Target::MacroDef => {
1906 self.inline_attr_str_error_with_macro_def(hir_id, attr, "allow_internal_unstable");
1907 true
1908 }
1909 _ => {
1910 self.tcx
1911 .sess
1912 .emit_err(errors::RustcAllowConstFnUnstable { attr_span: attr.span, span });
1913 false
1914 }
1915 }
1916 }
1917
1918 fn check_rustc_std_internal_symbol(
1919 &self,
1920 attr: &Attribute,
1921 span: Span,
1922 target: Target,
1923 ) -> bool {
1924 match target {
1925 Target::Fn | Target::Static => true,
1926 _ => {
1927 self.tcx
1928 .sess
1929 .emit_err(errors::RustcStdInternalSymbol { attr_span: attr.span, span });
1930 false
1931 }
1932 }
1933 }
1934
1935 /// `#[const_trait]` only applies to traits.
1936 fn check_const_trait(&self, attr: &Attribute, _span: Span, target: Target) -> bool {
1937 match target {
1938 Target::Trait => true,
1939 _ => {
1940 self.tcx.sess.emit_err(errors::ConstTrait { attr_span: attr.span });
1941 false
1942 }
1943 }
1944 }
1945
1946 fn check_stability_promotable(&self, attr: &Attribute, _span: Span, target: Target) -> bool {
1947 match target {
1948 Target::Expression => {
1949 self.tcx.sess.emit_err(errors::StabilityPromotable { attr_span: attr.span });
1950 false
1951 }
1952 _ => true,
1953 }
1954 }
1955
1956 fn check_link_ordinal(&self, attr: &Attribute, _span: Span, target: Target) -> bool {
1957 match target {
1958 Target::ForeignFn | Target::ForeignStatic => true,
1959 _ => {
1960 self.tcx.sess.emit_err(errors::LinkOrdinal { attr_span: attr.span });
1961 false
1962 }
1963 }
1964 }
1965
1966 fn check_deprecated(&self, hir_id: HirId, attr: &Attribute, _span: Span, target: Target) {
1967 match target {
1968 Target::Closure | Target::Expression | Target::Statement | Target::Arm => {
1969 self.tcx.emit_spanned_lint(
1970 UNUSED_ATTRIBUTES,
1971 hir_id,
1972 attr.span,
1973 errors::Deprecated,
1974 );
1975 }
1976 _ => {}
1977 }
1978 }
1979
1980 fn check_macro_use(&self, hir_id: HirId, attr: &Attribute, target: Target) {
1981 let name = attr.name_or_empty();
1982 match target {
1983 Target::ExternCrate | Target::Mod => {}
1984 _ => {
1985 self.tcx.emit_spanned_lint(
1986 UNUSED_ATTRIBUTES,
1987 hir_id,
1988 attr.span,
1989 errors::MacroUse { name },
1990 );
1991 }
1992 }
1993 }
1994
1995 fn check_macro_export(&self, hir_id: HirId, attr: &Attribute, target: Target) {
1996 if target != Target::MacroDef {
1997 self.tcx.emit_spanned_lint(UNUSED_ATTRIBUTES, hir_id, attr.span, errors::MacroExport);
1998 }
1999 }
2000
2001 fn check_plugin_registrar(&self, hir_id: HirId, attr: &Attribute, target: Target) {
2002 if target != Target::Fn {
2003 self.tcx.emit_spanned_lint(
2004 UNUSED_ATTRIBUTES,
2005 hir_id,
2006 attr.span,
2007 errors::PluginRegistrar,
2008 );
2009 }
2010 }
2011
2012 fn check_unused_attribute(&self, hir_id: HirId, attr: &Attribute) {
2013 // Warn on useless empty attributes.
2014 let note = if matches!(
2015 attr.name_or_empty(),
2016 sym::macro_use
2017 | sym::allow
2018 | sym::expect
2019 | sym::warn
2020 | sym::deny
2021 | sym::forbid
2022 | sym::feature
2023 | sym::repr
2024 | sym::target_feature
2025 ) && attr.meta_item_list().map_or(false, |list| list.is_empty())
2026 {
2027 errors::UnusedNote::EmptyList { name: attr.name_or_empty() }
2028 } else if matches!(
2029 attr.name_or_empty(),
2030 sym::allow | sym::warn | sym::deny | sym::forbid | sym::expect
2031 ) && let Some(meta) = attr.meta_item_list()
2032 && meta.len() == 1
2033 && let Some(item) = meta[0].meta_item()
2034 && let MetaItemKind::NameValue(_) = &item.kind
2035 && item.path == sym::reason
2036 {
2037 errors::UnusedNote::NoLints { name: attr.name_or_empty() }
2038 } else if attr.name_or_empty() == sym::default_method_body_is_const {
2039 errors::UnusedNote::DefaultMethodBodyConst
2040 } else {
2041 return;
2042 };
2043
2044 self.tcx.emit_spanned_lint(
2045 UNUSED_ATTRIBUTES,
2046 hir_id,
2047 attr.span,
2048 errors::Unused { attr_span: attr.span, note },
2049 );
2050 }
2051 }
2052
2053 impl<'tcx> Visitor<'tcx> for CheckAttrVisitor<'tcx> {
2054 type NestedFilter = nested_filter::OnlyBodies;
2055
2056 fn nested_visit_map(&mut self) -> Self::Map {
2057 self.tcx.hir()
2058 }
2059
2060 fn visit_item(&mut self, item: &'tcx Item<'tcx>) {
2061 // Historically we've run more checks on non-exported than exported macros,
2062 // so this lets us continue to run them while maintaining backwards compatibility.
2063 // In the long run, the checks should be harmonized.
2064 if let ItemKind::Macro(ref macro_def, _) = item.kind {
2065 let def_id = item.owner_id.to_def_id();
2066 if macro_def.macro_rules && !self.tcx.has_attr(def_id, sym::macro_export) {
2067 check_non_exported_macro_for_invalid_attrs(self.tcx, item);
2068 }
2069 }
2070
2071 let target = Target::from_item(item);
2072 self.check_attributes(item.hir_id(), item.span, target, Some(ItemLike::Item(item)));
2073 intravisit::walk_item(self, item)
2074 }
2075
2076 fn visit_generic_param(&mut self, generic_param: &'tcx hir::GenericParam<'tcx>) {
2077 let target = Target::from_generic_param(generic_param);
2078 self.check_attributes(generic_param.hir_id, generic_param.span, target, None);
2079 intravisit::walk_generic_param(self, generic_param)
2080 }
2081
2082 fn visit_trait_item(&mut self, trait_item: &'tcx TraitItem<'tcx>) {
2083 let target = Target::from_trait_item(trait_item);
2084 self.check_attributes(trait_item.hir_id(), trait_item.span, target, None);
2085 intravisit::walk_trait_item(self, trait_item)
2086 }
2087
2088 fn visit_field_def(&mut self, struct_field: &'tcx hir::FieldDef<'tcx>) {
2089 self.check_attributes(struct_field.hir_id, struct_field.span, Target::Field, None);
2090 intravisit::walk_field_def(self, struct_field);
2091 }
2092
2093 fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) {
2094 self.check_attributes(arm.hir_id, arm.span, Target::Arm, None);
2095 intravisit::walk_arm(self, arm);
2096 }
2097
2098 fn visit_foreign_item(&mut self, f_item: &'tcx ForeignItem<'tcx>) {
2099 let target = Target::from_foreign_item(f_item);
2100 self.check_attributes(f_item.hir_id(), f_item.span, target, Some(ItemLike::ForeignItem));
2101 intravisit::walk_foreign_item(self, f_item)
2102 }
2103
2104 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
2105 let target = target_from_impl_item(self.tcx, impl_item);
2106 self.check_attributes(impl_item.hir_id(), impl_item.span, target, None);
2107 intravisit::walk_impl_item(self, impl_item)
2108 }
2109
2110 fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt<'tcx>) {
2111 // When checking statements ignore expressions, they will be checked later.
2112 if let hir::StmtKind::Local(ref l) = stmt.kind {
2113 self.check_attributes(l.hir_id, stmt.span, Target::Statement, None);
2114 }
2115 intravisit::walk_stmt(self, stmt)
2116 }
2117
2118 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
2119 let target = match expr.kind {
2120 hir::ExprKind::Closure { .. } => Target::Closure,
2121 _ => Target::Expression,
2122 };
2123
2124 self.check_attributes(expr.hir_id, expr.span, target, None);
2125 intravisit::walk_expr(self, expr)
2126 }
2127
2128 fn visit_expr_field(&mut self, field: &'tcx hir::ExprField<'tcx>) {
2129 self.check_attributes(field.hir_id, field.span, Target::ExprField, None);
2130 intravisit::walk_expr_field(self, field)
2131 }
2132
2133 fn visit_variant(&mut self, variant: &'tcx hir::Variant<'tcx>) {
2134 self.check_attributes(variant.id, variant.span, Target::Variant, None);
2135 intravisit::walk_variant(self, variant)
2136 }
2137
2138 fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) {
2139 self.check_attributes(param.hir_id, param.span, Target::Param, None);
2140
2141 intravisit::walk_param(self, param);
2142 }
2143
2144 fn visit_pat_field(&mut self, field: &'tcx hir::PatField<'tcx>) {
2145 self.check_attributes(field.hir_id, field.span, Target::PatField, None);
2146 intravisit::walk_pat_field(self, field);
2147 }
2148 }
2149
2150 fn is_c_like_enum(item: &Item<'_>) -> bool {
2151 if let ItemKind::Enum(ref def, _) = item.kind {
2152 for variant in def.variants {
2153 match variant.data {
2154 hir::VariantData::Unit(..) => { /* continue */ }
2155 _ => return false,
2156 }
2157 }
2158 true
2159 } else {
2160 false
2161 }
2162 }
2163
2164 // FIXME: Fix "Cannot determine resolution" error and remove built-in macros
2165 // from this check.
2166 fn check_invalid_crate_level_attr(tcx: TyCtxt<'_>, attrs: &[Attribute]) {
2167 // Check for builtin attributes at the crate level
2168 // which were unsuccessfully resolved due to cannot determine
2169 // resolution for the attribute macro error.
2170 const ATTRS_TO_CHECK: &[Symbol] = &[
2171 sym::macro_export,
2172 sym::repr,
2173 sym::path,
2174 sym::automatically_derived,
2175 sym::start,
2176 sym::rustc_main,
2177 sym::unix_sigpipe,
2178 sym::derive,
2179 sym::test,
2180 sym::test_case,
2181 sym::global_allocator,
2182 sym::bench,
2183 ];
2184
2185 for attr in attrs {
2186 // This function should only be called with crate attributes
2187 // which are inner attributes always but lets check to make sure
2188 if attr.style == AttrStyle::Inner {
2189 for attr_to_check in ATTRS_TO_CHECK {
2190 if attr.has_name(*attr_to_check) {
2191 tcx.sess.emit_err(InvalidAttrAtCrateLevel {
2192 span: attr.span,
2193 snippet: tcx.sess.source_map().span_to_snippet(attr.span).ok(),
2194 name: *attr_to_check,
2195 });
2196 }
2197 }
2198 }
2199 }
2200 }
2201
2202 fn check_non_exported_macro_for_invalid_attrs(tcx: TyCtxt<'_>, item: &Item<'_>) {
2203 let attrs = tcx.hir().attrs(item.hir_id());
2204
2205 for attr in attrs {
2206 if attr.has_name(sym::inline) {
2207 tcx.sess.emit_err(errors::NonExportedMacroInvalidAttrs { attr_span: attr.span });
2208 }
2209 }
2210 }
2211
2212 fn check_mod_attrs(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
2213 let check_attr_visitor = &mut CheckAttrVisitor { tcx };
2214 tcx.hir().visit_item_likes_in_module(module_def_id, check_attr_visitor);
2215 if module_def_id.is_top_level_module() {
2216 check_attr_visitor.check_attributes(CRATE_HIR_ID, DUMMY_SP, Target::Mod, None);
2217 check_invalid_crate_level_attr(tcx, tcx.hir().krate_attrs());
2218 }
2219 }
2220
2221 pub(crate) fn provide(providers: &mut Providers) {
2222 *providers = Providers { check_mod_attrs, ..*providers };
2223 }
2224
2225 fn check_duplicates(
2226 tcx: TyCtxt<'_>,
2227 attr: &Attribute,
2228 hir_id: HirId,
2229 duplicates: AttributeDuplicates,
2230 seen: &mut FxHashMap<Symbol, Span>,
2231 ) {
2232 use AttributeDuplicates::*;
2233 if matches!(duplicates, WarnFollowingWordOnly) && !attr.is_word() {
2234 return;
2235 }
2236 match duplicates {
2237 DuplicatesOk => {}
2238 WarnFollowing | FutureWarnFollowing | WarnFollowingWordOnly | FutureWarnPreceding => {
2239 match seen.entry(attr.name_or_empty()) {
2240 Entry::Occupied(mut entry) => {
2241 let (this, other) = if matches!(duplicates, FutureWarnPreceding) {
2242 let to_remove = entry.insert(attr.span);
2243 (to_remove, attr.span)
2244 } else {
2245 (attr.span, *entry.get())
2246 };
2247 tcx.emit_spanned_lint(
2248 UNUSED_ATTRIBUTES,
2249 hir_id,
2250 this,
2251 errors::UnusedDuplicate {
2252 this,
2253 other,
2254 warning: matches!(
2255 duplicates,
2256 FutureWarnFollowing | FutureWarnPreceding
2257 )
2258 .then_some(()),
2259 },
2260 );
2261 }
2262 Entry::Vacant(entry) => {
2263 entry.insert(attr.span);
2264 }
2265 }
2266 }
2267 ErrorFollowing | ErrorPreceding => match seen.entry(attr.name_or_empty()) {
2268 Entry::Occupied(mut entry) => {
2269 let (this, other) = if matches!(duplicates, ErrorPreceding) {
2270 let to_remove = entry.insert(attr.span);
2271 (to_remove, attr.span)
2272 } else {
2273 (attr.span, *entry.get())
2274 };
2275 tcx.sess.emit_err(errors::UnusedMultiple {
2276 this,
2277 other,
2278 name: attr.name_or_empty(),
2279 });
2280 }
2281 Entry::Vacant(entry) => {
2282 entry.insert(attr.span);
2283 }
2284 },
2285 }
2286 }