1use std::cell::RefCell;
2use std::collections::BTreeMap;
3use std::ops::{Deref, DerefMut};
4use std::sync::LazyLock;
5
6use itertools::Itertools;
7use private::Sealed;
8use rustc_ast::{self as ast, LitKind, MetaItemLit, NodeId};
9use rustc_errors::{DiagCtxtHandle, Diagnostic};
10use rustc_feature::{AttributeTemplate, Features};
11use rustc_hir::attrs::AttributeKind;
12use rustc_hir::lints::{AttributeLint, AttributeLintKind};
13use rustc_hir::{
14 AttrArgs, AttrItem, AttrPath, Attribute, HashIgnoredAttrId, HirId, MethodKind, Target,
15};
16use rustc_session::Session;
17use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span, Symbol, sym};
18
19use crate::attributes::allow_unstable::{
20 AllowConstFnUnstableParser, AllowInternalUnstableParser, UnstableFeatureBoundParser,
21};
22use crate::attributes::body::CoroutineParser;
23use crate::attributes::codegen_attrs::{
24 ColdParser, CoverageParser, ExportNameParser, NakedParser, NoMangleParser, OptimizeParser,
25 TargetFeatureParser, TrackCallerParser, UsedParser,
26};
27use crate::attributes::confusables::ConfusablesParser;
28use crate::attributes::deprecation::DeprecationParser;
29use crate::attributes::dummy::DummyParser;
30use crate::attributes::inline::{InlineParser, RustcForceInlineParser};
31use crate::attributes::link_attrs::{
32 ExportStableParser, FfiConstParser, FfiPureParser, LinkNameParser, LinkOrdinalParser,
33 LinkSectionParser, LinkageParser, StdInternalSymbolParser,
34};
35use crate::attributes::lint_helpers::{
36 AsPtrParser, AutomaticallyDerivedParser, PassByValueParser, PubTransparentParser,
37};
38use crate::attributes::loop_match::{ConstContinueParser, LoopMatchParser};
39use crate::attributes::macro_attrs::{
40 AllowInternalUnsafeParser, MacroEscapeParser, MacroUseParser,
41};
42use crate::attributes::must_use::MustUseParser;
43use crate::attributes::no_implicit_prelude::NoImplicitPreludeParser;
44use crate::attributes::non_exhaustive::NonExhaustiveParser;
45use crate::attributes::path::PathParser as PathAttributeParser;
46use crate::attributes::proc_macro_attrs::{
47 ProcMacroAttributeParser, ProcMacroDeriveParser, ProcMacroParser, RustcBuiltinMacroParser,
48};
49use crate::attributes::prototype::CustomMirParser;
50use crate::attributes::repr::{AlignParser, ReprParser};
51use crate::attributes::rustc_internal::{
52 RustcLayoutScalarValidRangeEnd, RustcLayoutScalarValidRangeStart,
53 RustcObjectLifetimeDefaultParser,
54};
55use crate::attributes::semantics::MayDangleParser;
56use crate::attributes::stability::{
57 BodyStabilityParser, ConstStabilityIndirectParser, ConstStabilityParser, StabilityParser,
58};
59use crate::attributes::test_attrs::{IgnoreParser, ShouldPanicParser};
60use crate::attributes::traits::{
61 AllowIncoherentImplParser, CoherenceIsCoreParser, CoinductiveParser, ConstTraitParser,
62 DenyExplicitImplParser, DoNotImplementViaObjectParser, FundamentalParser, MarkerParser,
63 ParenSugarParser, PointeeParser, SkipDuringMethodDispatchParser, SpecializationTraitParser,
64 TypeConstParser, UnsafeSpecializationMarkerParser,
65};
66use crate::attributes::transparency::TransparencyParser;
67use crate::attributes::{AttributeParser as _, Combine, Single, WithoutArgs};
68use crate::context::MaybeWarn::{Allow, Error, Warn};
69use crate::parser::{ArgParser, MetaItemParser, PathParser};
70use crate::session_diagnostics::{
71 AttributeParseError, AttributeParseErrorReason, InvalidTarget, UnknownMetaItem,
72};
73
74type GroupType<S> = LazyLock<GroupTypeInner<S>>;
75
76struct GroupTypeInner<S: Stage> {
77 accepters: BTreeMap<&'static [Symbol], Vec<GroupTypeInnerAccept<S>>>,
78 finalizers: Vec<FinalizeFn<S>>,
79}
80
81struct GroupTypeInnerAccept<S: Stage> {
82 template: AttributeTemplate,
83 accept_fn: AcceptFn<S>,
84 allowed_targets: AllowedTargets,
85}
86
87type AcceptFn<S> =
88 Box<dyn for<'sess, 'a> Fn(&mut AcceptContext<'_, 'sess, S>, &ArgParser<'a>) + Send + Sync>;
89type FinalizeFn<S> =
90 Box<dyn Send + Sync + Fn(&mut FinalizeContext<'_, '_, S>) -> Option<AttributeKind>>;
91
92macro_rules! attribute_parsers {
93 (
94 pub(crate) static $name: ident = [$($names: ty),* $(,)?];
95 ) => {
96 mod early {
97 use super::*;
98 type Combine<T> = super::Combine<T, Early>;
99 type Single<T> = super::Single<T, Early>;
100 type WithoutArgs<T> = super::WithoutArgs<T, Early>;
101
102 attribute_parsers!(@[Early] pub(crate) static $name = [$($names),*];);
103 }
104 mod late {
105 use super::*;
106 type Combine<T> = super::Combine<T, Late>;
107 type Single<T> = super::Single<T, Late>;
108 type WithoutArgs<T> = super::WithoutArgs<T, Late>;
109
110 attribute_parsers!(@[Late] pub(crate) static $name = [$($names),*];);
111 }
112 };
113 (
114 @[$stage: ty] pub(crate) static $name: ident = [$($names: ty),* $(,)?];
115 ) => {
116 pub(crate) static $name: GroupType<$stage> = LazyLock::new(|| {
117 let mut accepts = BTreeMap::<_, Vec<GroupTypeInnerAccept<$stage>>>::new();
118 let mut finalizes = Vec::<FinalizeFn<$stage>>::new();
119 $(
120 {
121 thread_local! {
122 static STATE_OBJECT: RefCell<$names> = RefCell::new(<$names>::default());
123 };
124
125 for (path, template, accept_fn) in <$names>::ATTRIBUTES {
126 accepts.entry(*path).or_default().push(GroupTypeInnerAccept {
127 template: *template,
128 accept_fn: Box::new(|cx, args| {
129 STATE_OBJECT.with_borrow_mut(|s| {
130 accept_fn(s, cx, args)
131 })
132 }),
133 allowed_targets: <$names as crate::attributes::AttributeParser<$stage>>::ALLOWED_TARGETS,
134 });
135 }
136
137 finalizes.push(Box::new(|cx| {
138 let state = STATE_OBJECT.take();
139 state.finalize(cx)
140 }));
141 }
142 )*
143
144 GroupTypeInner { accepters:accepts, finalizers:finalizes }
145 });
146 };
147}
148attribute_parsers!(
149 pub(crate) static ATTRIBUTE_PARSERS = [
150 AlignParser,
152 BodyStabilityParser,
153 ConfusablesParser,
154 ConstStabilityParser,
155 MacroUseParser,
156 NakedParser,
157 StabilityParser,
158 UsedParser,
159 Combine<AllowConstFnUnstableParser>,
163 Combine<AllowInternalUnstableParser>,
164 Combine<ReprParser>,
165 Combine<TargetFeatureParser>,
166 Combine<UnstableFeatureBoundParser>,
167 Single<CoverageParser>,
171 Single<CustomMirParser>,
172 Single<DeprecationParser>,
173 Single<DummyParser>,
174 Single<ExportNameParser>,
175 Single<IgnoreParser>,
176 Single<InlineParser>,
177 Single<LinkNameParser>,
178 Single<LinkOrdinalParser>,
179 Single<LinkSectionParser>,
180 Single<LinkageParser>,
181 Single<MustUseParser>,
182 Single<OptimizeParser>,
183 Single<PathAttributeParser>,
184 Single<ProcMacroDeriveParser>,
185 Single<RustcBuiltinMacroParser>,
186 Single<RustcForceInlineParser>,
187 Single<RustcLayoutScalarValidRangeEnd>,
188 Single<RustcLayoutScalarValidRangeStart>,
189 Single<RustcObjectLifetimeDefaultParser>,
190 Single<ShouldPanicParser>,
191 Single<SkipDuringMethodDispatchParser>,
192 Single<TransparencyParser>,
193 Single<WithoutArgs<AllowIncoherentImplParser>>,
194 Single<WithoutArgs<AllowInternalUnsafeParser>>,
195 Single<WithoutArgs<AsPtrParser>>,
196 Single<WithoutArgs<AutomaticallyDerivedParser>>,
197 Single<WithoutArgs<CoherenceIsCoreParser>>,
198 Single<WithoutArgs<CoinductiveParser>>,
199 Single<WithoutArgs<ColdParser>>,
200 Single<WithoutArgs<ConstContinueParser>>,
201 Single<WithoutArgs<ConstStabilityIndirectParser>>,
202 Single<WithoutArgs<ConstTraitParser>>,
203 Single<WithoutArgs<CoroutineParser>>,
204 Single<WithoutArgs<DenyExplicitImplParser>>,
205 Single<WithoutArgs<DoNotImplementViaObjectParser>>,
206 Single<WithoutArgs<ExportStableParser>>,
207 Single<WithoutArgs<FfiConstParser>>,
208 Single<WithoutArgs<FfiPureParser>>,
209 Single<WithoutArgs<FundamentalParser>>,
210 Single<WithoutArgs<LoopMatchParser>>,
211 Single<WithoutArgs<MacroEscapeParser>>,
212 Single<WithoutArgs<MarkerParser>>,
213 Single<WithoutArgs<MayDangleParser>>,
214 Single<WithoutArgs<NoImplicitPreludeParser>>,
215 Single<WithoutArgs<NoMangleParser>>,
216 Single<WithoutArgs<NonExhaustiveParser>>,
217 Single<WithoutArgs<ParenSugarParser>>,
218 Single<WithoutArgs<PassByValueParser>>,
219 Single<WithoutArgs<PointeeParser>>,
220 Single<WithoutArgs<ProcMacroAttributeParser>>,
221 Single<WithoutArgs<ProcMacroParser>>,
222 Single<WithoutArgs<PubTransparentParser>>,
223 Single<WithoutArgs<SpecializationTraitParser>>,
224 Single<WithoutArgs<StdInternalSymbolParser>>,
225 Single<WithoutArgs<TrackCallerParser>>,
226 Single<WithoutArgs<TypeConstParser>>,
227 Single<WithoutArgs<UnsafeSpecializationMarkerParser>>,
228 ];
230);
231
232mod private {
233 pub trait Sealed {}
234 impl Sealed for super::Early {}
235 impl Sealed for super::Late {}
236}
237
238#[allow(private_interfaces)]
240pub trait Stage: Sized + 'static + Sealed {
241 type Id: Copy;
242
243 fn parsers() -> &'static GroupType<Self>;
244
245 fn emit_err<'sess>(
246 &self,
247 sess: &'sess Session,
248 diag: impl for<'x> Diagnostic<'x>,
249 ) -> ErrorGuaranteed;
250
251 fn should_emit(&self) -> ShouldEmit;
252}
253
254#[allow(private_interfaces)]
256impl Stage for Early {
257 type Id = NodeId;
258
259 fn parsers() -> &'static GroupType<Self> {
260 &early::ATTRIBUTE_PARSERS
261 }
262 fn emit_err<'sess>(
263 &self,
264 sess: &'sess Session,
265 diag: impl for<'x> Diagnostic<'x>,
266 ) -> ErrorGuaranteed {
267 if self.emit_errors.should_emit() {
268 sess.dcx().emit_err(diag)
269 } else {
270 sess.dcx().create_err(diag).delay_as_bug()
271 }
272 }
273
274 fn should_emit(&self) -> ShouldEmit {
275 self.emit_errors
276 }
277}
278
279#[allow(private_interfaces)]
281impl Stage for Late {
282 type Id = HirId;
283
284 fn parsers() -> &'static GroupType<Self> {
285 &late::ATTRIBUTE_PARSERS
286 }
287 fn emit_err<'sess>(
288 &self,
289 tcx: &'sess Session,
290 diag: impl for<'x> Diagnostic<'x>,
291 ) -> ErrorGuaranteed {
292 tcx.dcx().emit_err(diag)
293 }
294
295 fn should_emit(&self) -> ShouldEmit {
296 ShouldEmit::ErrorsAndLints
297 }
298}
299
300pub struct Early {
302 pub emit_errors: ShouldEmit,
306}
307pub struct Late;
309
310pub struct AcceptContext<'f, 'sess, S: Stage> {
314 pub(crate) shared: SharedContext<'f, 'sess, S>,
315 pub(crate) attr_span: Span,
317
318 pub(crate) template: &'f AttributeTemplate,
322
323 pub(crate) attr_path: AttrPath,
325}
326
327impl<'f, 'sess: 'f, S: Stage> SharedContext<'f, 'sess, S> {
328 pub(crate) fn emit_err(&self, diag: impl for<'x> Diagnostic<'x>) -> ErrorGuaranteed {
329 self.stage.emit_err(&self.sess, diag)
330 }
331
332 pub(crate) fn emit_lint(&mut self, lint: AttributeLintKind, span: Span) {
336 if !self.stage.should_emit().should_emit() {
337 return;
338 }
339 let id = self.target_id;
340 (self.emit_lint)(AttributeLint { id, span, kind: lint });
341 }
342
343 pub(crate) fn warn_unused_duplicate(&mut self, used_span: Span, unused_span: Span) {
344 self.emit_lint(
345 AttributeLintKind::UnusedDuplicate {
346 this: unused_span,
347 other: used_span,
348 warning: false,
349 },
350 unused_span,
351 )
352 }
353
354 pub(crate) fn warn_unused_duplicate_future_error(
355 &mut self,
356 used_span: Span,
357 unused_span: Span,
358 ) {
359 self.emit_lint(
360 AttributeLintKind::UnusedDuplicate {
361 this: unused_span,
362 other: used_span,
363 warning: true,
364 },
365 unused_span,
366 )
367 }
368}
369
370impl<'f, 'sess: 'f, S: Stage> AcceptContext<'f, 'sess, S> {
371 pub(crate) fn unknown_key(
372 &self,
373 span: Span,
374 found: String,
375 options: &'static [&'static str],
376 ) -> ErrorGuaranteed {
377 self.emit_err(UnknownMetaItem { span, item: found, expected: options })
378 }
379
380 pub(crate) fn expected_string_literal(
385 &self,
386 span: Span,
387 actual_literal: Option<&MetaItemLit>,
388 ) -> ErrorGuaranteed {
389 self.emit_err(AttributeParseError {
390 span,
391 attr_span: self.attr_span,
392 template: self.template.clone(),
393 attribute: self.attr_path.clone(),
394 reason: AttributeParseErrorReason::ExpectedStringLiteral {
395 byte_string: actual_literal.and_then(|i| {
396 i.kind.is_bytestr().then(|| self.sess().source_map().start_point(i.span))
397 }),
398 },
399 })
400 }
401
402 pub(crate) fn expected_integer_literal(&self, span: Span) -> ErrorGuaranteed {
403 self.emit_err(AttributeParseError {
404 span,
405 attr_span: self.attr_span,
406 template: self.template.clone(),
407 attribute: self.attr_path.clone(),
408 reason: AttributeParseErrorReason::ExpectedIntegerLiteral,
409 })
410 }
411
412 pub(crate) fn expected_list(&self, span: Span) -> ErrorGuaranteed {
413 self.emit_err(AttributeParseError {
414 span,
415 attr_span: self.attr_span,
416 template: self.template.clone(),
417 attribute: self.attr_path.clone(),
418 reason: AttributeParseErrorReason::ExpectedList,
419 })
420 }
421
422 pub(crate) fn expected_no_args(&self, args_span: Span) -> ErrorGuaranteed {
423 self.emit_err(AttributeParseError {
424 span: args_span,
425 attr_span: self.attr_span,
426 template: self.template.clone(),
427 attribute: self.attr_path.clone(),
428 reason: AttributeParseErrorReason::ExpectedNoArgs,
429 })
430 }
431
432 pub(crate) fn expected_identifier(&self, span: Span) -> ErrorGuaranteed {
434 self.emit_err(AttributeParseError {
435 span,
436 attr_span: self.attr_span,
437 template: self.template.clone(),
438 attribute: self.attr_path.clone(),
439 reason: AttributeParseErrorReason::ExpectedIdentifier,
440 })
441 }
442
443 pub(crate) fn expected_name_value(&self, span: Span, name: Option<Symbol>) -> ErrorGuaranteed {
446 self.emit_err(AttributeParseError {
447 span,
448 attr_span: self.attr_span,
449 template: self.template.clone(),
450 attribute: self.attr_path.clone(),
451 reason: AttributeParseErrorReason::ExpectedNameValue(name),
452 })
453 }
454
455 pub(crate) fn duplicate_key(&self, span: Span, key: Symbol) -> ErrorGuaranteed {
457 self.emit_err(AttributeParseError {
458 span,
459 attr_span: self.attr_span,
460 template: self.template.clone(),
461 attribute: self.attr_path.clone(),
462 reason: AttributeParseErrorReason::DuplicateKey(key),
463 })
464 }
465
466 pub(crate) fn unexpected_literal(&self, span: Span) -> ErrorGuaranteed {
469 self.emit_err(AttributeParseError {
470 span,
471 attr_span: self.attr_span,
472 template: self.template.clone(),
473 attribute: self.attr_path.clone(),
474 reason: AttributeParseErrorReason::UnexpectedLiteral,
475 })
476 }
477
478 pub(crate) fn expected_single_argument(&self, span: Span) -> ErrorGuaranteed {
479 self.emit_err(AttributeParseError {
480 span,
481 attr_span: self.attr_span,
482 template: self.template.clone(),
483 attribute: self.attr_path.clone(),
484 reason: AttributeParseErrorReason::ExpectedSingleArgument,
485 })
486 }
487
488 pub(crate) fn expected_at_least_one_argument(&self, span: Span) -> ErrorGuaranteed {
489 self.emit_err(AttributeParseError {
490 span,
491 attr_span: self.attr_span,
492 template: self.template.clone(),
493 attribute: self.attr_path.clone(),
494 reason: AttributeParseErrorReason::ExpectedAtLeastOneArgument,
495 })
496 }
497
498 pub(crate) fn expected_specific_argument(
499 &self,
500 span: Span,
501 possibilities: Vec<&'static str>,
502 ) -> ErrorGuaranteed {
503 self.emit_err(AttributeParseError {
504 span,
505 attr_span: self.attr_span,
506 template: self.template.clone(),
507 attribute: self.attr_path.clone(),
508 reason: AttributeParseErrorReason::ExpectedSpecificArgument {
509 possibilities,
510 strings: false,
511 list: false,
512 },
513 })
514 }
515
516 pub(crate) fn expected_specific_argument_and_list(
517 &self,
518 span: Span,
519 possibilities: Vec<&'static str>,
520 ) -> ErrorGuaranteed {
521 self.emit_err(AttributeParseError {
522 span,
523 attr_span: self.attr_span,
524 template: self.template.clone(),
525 attribute: self.attr_path.clone(),
526 reason: AttributeParseErrorReason::ExpectedSpecificArgument {
527 possibilities,
528 strings: false,
529 list: true,
530 },
531 })
532 }
533
534 pub(crate) fn expected_specific_argument_strings(
535 &self,
536 span: Span,
537 possibilities: Vec<&'static str>,
538 ) -> ErrorGuaranteed {
539 self.emit_err(AttributeParseError {
540 span,
541 attr_span: self.attr_span,
542 template: self.template.clone(),
543 attribute: self.attr_path.clone(),
544 reason: AttributeParseErrorReason::ExpectedSpecificArgument {
545 possibilities,
546 strings: true,
547 list: false,
548 },
549 })
550 }
551
552 pub(crate) fn warn_empty_attribute(&mut self, span: Span) {
553 self.emit_lint(AttributeLintKind::EmptyAttribute { first_span: span }, span);
554 }
555}
556
557impl<'f, 'sess, S: Stage> Deref for AcceptContext<'f, 'sess, S> {
558 type Target = SharedContext<'f, 'sess, S>;
559
560 fn deref(&self) -> &Self::Target {
561 &self.shared
562 }
563}
564
565impl<'f, 'sess, S: Stage> DerefMut for AcceptContext<'f, 'sess, S> {
566 fn deref_mut(&mut self) -> &mut Self::Target {
567 &mut self.shared
568 }
569}
570
571pub struct SharedContext<'p, 'sess, S: Stage> {
576 pub(crate) cx: &'p mut AttributeParser<'sess, S>,
579 pub(crate) target_span: Span,
581 pub(crate) target_id: S::Id,
583
584 emit_lint: &'p mut dyn FnMut(AttributeLint<S::Id>),
585}
586
587pub(crate) struct FinalizeContext<'p, 'sess, S: Stage> {
592 pub(crate) shared: SharedContext<'p, 'sess, S>,
593
594 pub(crate) all_attrs: &'p [PathParser<'p>],
601}
602
603impl<'p, 'sess: 'p, S: Stage> Deref for FinalizeContext<'p, 'sess, S> {
604 type Target = SharedContext<'p, 'sess, S>;
605
606 fn deref(&self) -> &Self::Target {
607 &self.shared
608 }
609}
610
611impl<'p, 'sess: 'p, S: Stage> DerefMut for FinalizeContext<'p, 'sess, S> {
612 fn deref_mut(&mut self) -> &mut Self::Target {
613 &mut self.shared
614 }
615}
616
617impl<'p, 'sess: 'p, S: Stage> Deref for SharedContext<'p, 'sess, S> {
618 type Target = AttributeParser<'sess, S>;
619
620 fn deref(&self) -> &Self::Target {
621 self.cx
622 }
623}
624
625impl<'p, 'sess: 'p, S: Stage> DerefMut for SharedContext<'p, 'sess, S> {
626 fn deref_mut(&mut self) -> &mut Self::Target {
627 self.cx
628 }
629}
630
631#[derive(PartialEq, Clone, Copy, Debug)]
632pub enum OmitDoc {
633 Lower,
634 Skip,
635}
636
637#[derive(Copy, Clone)]
638pub enum ShouldEmit {
639 ErrorsAndLints,
642 Nothing,
645}
646
647impl ShouldEmit {
648 pub fn should_emit(&self) -> bool {
649 match self {
650 ShouldEmit::ErrorsAndLints => true,
651 ShouldEmit::Nothing => false,
652 }
653 }
654}
655
656#[derive(Debug)]
657pub(crate) enum AllowedTargets {
658 AllowList(&'static [MaybeWarn]),
659 AllowListWarnRest(&'static [MaybeWarn]),
660}
661
662pub(crate) enum AllowedResult {
663 Allowed,
664 Warn,
665 Error,
666}
667
668impl AllowedTargets {
669 pub(crate) fn is_allowed(&self, target: Target) -> AllowedResult {
670 match self {
671 AllowedTargets::AllowList(list) => {
672 if list.contains(&Allow(target)) {
673 AllowedResult::Allowed
674 } else if list.contains(&Warn(target)) {
675 AllowedResult::Warn
676 } else {
677 AllowedResult::Error
678 }
679 }
680 AllowedTargets::AllowListWarnRest(list) => {
681 if list.contains(&Allow(target)) {
682 AllowedResult::Allowed
683 } else if list.contains(&Error(target)) {
684 AllowedResult::Error
685 } else {
686 AllowedResult::Warn
687 }
688 }
689 }
690 }
691
692 pub(crate) fn allowed_targets(&self) -> Vec<Target> {
693 match self {
694 AllowedTargets::AllowList(list) => list,
695 AllowedTargets::AllowListWarnRest(list) => list,
696 }
697 .iter()
698 .filter_map(|target| match target {
699 Allow(target) => Some(*target),
700 Warn(_) => None,
701 Error(_) => None,
702 })
703 .collect()
704 }
705}
706
707#[derive(Debug, Eq, PartialEq)]
708pub(crate) enum MaybeWarn {
709 Allow(Target),
710 Warn(Target),
711 Error(Target),
712}
713
714pub struct AttributeParser<'sess, S: Stage = Late> {
717 pub(crate) tools: Vec<Symbol>,
718 features: Option<&'sess Features>,
719 sess: &'sess Session,
720 stage: S,
721
722 parse_only: Option<Symbol>,
726}
727
728impl<'sess> AttributeParser<'sess, Early> {
729 pub fn parse_limited(
744 sess: &'sess Session,
745 attrs: &[ast::Attribute],
746 sym: Symbol,
747 target_span: Span,
748 target_node_id: NodeId,
749 features: Option<&'sess Features>,
750 ) -> Option<Attribute> {
751 let mut p = Self {
752 features,
753 tools: Vec::new(),
754 parse_only: Some(sym),
755 sess,
756 stage: Early { emit_errors: ShouldEmit::Nothing },
757 };
758 let mut parsed = p.parse_attribute_list(
759 attrs,
760 target_span,
761 target_node_id,
762 Target::Crate, OmitDoc::Skip,
764 std::convert::identity,
765 |_lint| {
766 panic!("can't emit lints here for now (nothing uses this atm)");
767 },
768 );
769 assert!(parsed.len() <= 1);
770
771 parsed.pop()
772 }
773
774 pub fn parse_single<T>(
775 sess: &'sess Session,
776 attr: &ast::Attribute,
777 target_span: Span,
778 target_node_id: NodeId,
779 features: Option<&'sess Features>,
780 emit_errors: ShouldEmit,
781 parse_fn: fn(cx: &mut AcceptContext<'_, '_, Early>, item: &ArgParser<'_>) -> T,
782 template: &AttributeTemplate,
783 ) -> T {
784 let mut parser = Self {
785 features,
786 tools: Vec::new(),
787 parse_only: None,
788 sess,
789 stage: Early { emit_errors },
790 };
791 let ast::AttrKind::Normal(normal_attr) = &attr.kind else {
792 panic!("parse_single called on a doc attr")
793 };
794 let meta_parser = MetaItemParser::from_attr(normal_attr, parser.dcx());
795 let path = meta_parser.path();
796 let args = meta_parser.args();
797 let mut cx: AcceptContext<'_, 'sess, Early> = AcceptContext {
798 shared: SharedContext {
799 cx: &mut parser,
800 target_span,
801 target_id: target_node_id,
802 emit_lint: &mut |_lint| {
803 panic!("can't emit lints here for now (nothing uses this atm)");
804 },
805 },
806 attr_span: attr.span,
807 template,
808 attr_path: path.get_attribute_path(),
809 };
810 parse_fn(&mut cx, args)
811 }
812}
813
814impl<'sess, S: Stage> AttributeParser<'sess, S> {
815 pub fn new(
816 sess: &'sess Session,
817 features: &'sess Features,
818 tools: Vec<Symbol>,
819 stage: S,
820 ) -> Self {
821 Self { features: Some(features), tools, parse_only: None, sess, stage }
822 }
823
824 pub(crate) fn sess(&self) -> &'sess Session {
825 &self.sess
826 }
827
828 pub(crate) fn features(&self) -> &'sess Features {
829 self.features.expect("features not available at this point in the compiler")
830 }
831
832 pub(crate) fn features_option(&self) -> Option<&'sess Features> {
833 self.features
834 }
835
836 pub(crate) fn dcx(&self) -> DiagCtxtHandle<'sess> {
837 self.sess().dcx()
838 }
839
840 pub fn parse_attribute_list(
845 &mut self,
846 attrs: &[ast::Attribute],
847 target_span: Span,
848 target_id: S::Id,
849 target: Target,
850 omit_doc: OmitDoc,
851
852 lower_span: impl Copy + Fn(Span) -> Span,
853 mut emit_lint: impl FnMut(AttributeLint<S::Id>),
854 ) -> Vec<Attribute> {
855 let mut attributes = Vec::new();
856 let mut attr_paths = Vec::new();
857
858 for attr in attrs {
859 if let Some(expected) = self.parse_only {
861 if !attr.has_name(expected) {
862 continue;
863 }
864 }
865
866 if omit_doc == OmitDoc::Skip && attr.has_name(sym::doc) {
872 continue;
873 }
874
875 match &attr.kind {
876 ast::AttrKind::DocComment(comment_kind, symbol) => {
877 if omit_doc == OmitDoc::Skip {
878 continue;
879 }
880
881 attributes.push(Attribute::Parsed(AttributeKind::DocComment {
882 style: attr.style,
883 kind: *comment_kind,
884 span: lower_span(attr.span),
885 comment: *symbol,
886 }))
887 }
888 ast::AttrKind::Normal(n) => {
900 attr_paths.push(PathParser::Ast(&n.item.path));
901
902 let parser = MetaItemParser::from_attr(n, self.dcx());
903 let path = parser.path();
904 let args = parser.args();
905 let parts = path.segments().map(|i| i.name).collect::<Vec<_>>();
906
907 if let Some(accepts) = S::parsers().accepters.get(parts.as_slice()) {
908 for accept in accepts {
909 let mut cx: AcceptContext<'_, 'sess, S> = AcceptContext {
910 shared: SharedContext {
911 cx: self,
912 target_span,
913 target_id,
914 emit_lint: &mut emit_lint,
915 },
916 attr_span: lower_span(attr.span),
917 template: &accept.template,
918 attr_path: path.get_attribute_path(),
919 };
920
921 (accept.accept_fn)(&mut cx, args);
922
923 if self.stage.should_emit().should_emit() {
924 match accept.allowed_targets.is_allowed(target) {
925 AllowedResult::Allowed => {}
926 AllowedResult::Warn => {
927 let allowed_targets =
928 accept.allowed_targets.allowed_targets();
929 let (applied, only) = allowed_targets_applied(
930 allowed_targets,
931 target,
932 self.features,
933 );
934 emit_lint(AttributeLint {
935 id: target_id,
936 span: attr.span,
937 kind: AttributeLintKind::InvalidTarget {
938 name: parts[0],
939 target,
940 only: if only { "only " } else { "" },
941 applied,
942 },
943 });
944 }
945 AllowedResult::Error => {
946 let allowed_targets =
947 accept.allowed_targets.allowed_targets();
948 let (applied, only) = allowed_targets_applied(
949 allowed_targets,
950 target,
951 self.features,
952 );
953 self.dcx().emit_err(InvalidTarget {
954 span: attr.span,
955 name: parts[0],
956 target: target.plural_name(),
957 only: if only { "only " } else { "" },
958 applied,
959 });
960 }
961 }
962 }
963 }
964 } else {
965 attributes.push(Attribute::Unparsed(Box::new(AttrItem {
981 path: AttrPath::from_ast(&n.item.path),
982 args: self.lower_attr_args(&n.item.args, lower_span),
983 id: HashIgnoredAttrId { attr_id: attr.id },
984 style: attr.style,
985 span: lower_span(attr.span),
986 })));
987 }
988 }
989 }
990 }
991
992 let mut parsed_attributes = Vec::new();
993 for f in &S::parsers().finalizers {
994 if let Some(attr) = f(&mut FinalizeContext {
995 shared: SharedContext {
996 cx: self,
997 target_span,
998 target_id,
999 emit_lint: &mut emit_lint,
1000 },
1001 all_attrs: &attr_paths,
1002 }) {
1003 parsed_attributes.push(Attribute::Parsed(attr));
1004 }
1005 }
1006
1007 attributes.extend(parsed_attributes);
1008
1009 attributes
1010 }
1011
1012 pub fn is_parsed_attribute(path: &[Symbol]) -> bool {
1014 Late::parsers().accepters.contains_key(path)
1015 }
1016
1017 fn lower_attr_args(&self, args: &ast::AttrArgs, lower_span: impl Fn(Span) -> Span) -> AttrArgs {
1018 match args {
1019 ast::AttrArgs::Empty => AttrArgs::Empty,
1020 ast::AttrArgs::Delimited(args) => AttrArgs::Delimited(args.clone()),
1021 ast::AttrArgs::Eq { eq_span, expr } => {
1025 let lit = if let ast::ExprKind::Lit(token_lit) = expr.kind
1028 && let Ok(lit) =
1029 ast::MetaItemLit::from_token_lit(token_lit, lower_span(expr.span))
1030 {
1031 lit
1032 } else {
1033 let guar = self.dcx().span_delayed_bug(
1034 args.span().unwrap_or(DUMMY_SP),
1035 "expr in place where literal is expected (builtin attr parsing)",
1036 );
1037 ast::MetaItemLit {
1038 symbol: sym::dummy,
1039 suffix: None,
1040 kind: ast::LitKind::Err(guar),
1041 span: DUMMY_SP,
1042 }
1043 };
1044 AttrArgs::Eq { eq_span: lower_span(*eq_span), expr: lit }
1045 }
1046 }
1047 }
1048}
1049
1050pub(crate) fn allowed_targets_applied(
1053 mut allowed_targets: Vec<Target>,
1054 target: Target,
1055 features: Option<&Features>,
1056) -> (String, bool) {
1057 if let Some(features) = features {
1059 if !features.fn_delegation() {
1060 allowed_targets.retain(|t| !matches!(t, Target::Delegation { .. }));
1061 }
1062 if !features.stmt_expr_attributes() {
1063 allowed_targets.retain(|t| !matches!(t, Target::Expression | Target::Statement));
1064 }
1065 if !features.extern_types() {
1066 allowed_targets.retain(|t| !matches!(t, Target::ForeignTy));
1067 }
1068 }
1069
1070 const FUNCTION_LIKE: &[Target] = &[
1074 Target::Fn,
1075 Target::Closure,
1076 Target::ForeignFn,
1077 Target::Method(MethodKind::Inherent),
1078 Target::Method(MethodKind::Trait { body: false }),
1079 Target::Method(MethodKind::Trait { body: true }),
1080 Target::Method(MethodKind::TraitImpl),
1081 ];
1082 const METHOD_LIKE: &[Target] = &[
1083 Target::Method(MethodKind::Inherent),
1084 Target::Method(MethodKind::Trait { body: false }),
1085 Target::Method(MethodKind::Trait { body: true }),
1086 Target::Method(MethodKind::TraitImpl),
1087 ];
1088 const IMPL_LIKE: &[Target] =
1089 &[Target::Impl { of_trait: false }, Target::Impl { of_trait: true }];
1090 const ADT_LIKE: &[Target] = &[Target::Struct, Target::Enum];
1091
1092 let mut added_fake_targets = Vec::new();
1093 filter_targets(
1094 &mut allowed_targets,
1095 FUNCTION_LIKE,
1096 "functions",
1097 target,
1098 &mut added_fake_targets,
1099 );
1100 filter_targets(&mut allowed_targets, METHOD_LIKE, "methods", target, &mut added_fake_targets);
1101 filter_targets(&mut allowed_targets, IMPL_LIKE, "impl blocks", target, &mut added_fake_targets);
1102 filter_targets(&mut allowed_targets, ADT_LIKE, "data types", target, &mut added_fake_targets);
1103
1104 (
1106 added_fake_targets
1107 .iter()
1108 .copied()
1109 .chain(allowed_targets.iter().map(|t| t.plural_name()))
1110 .join(", "),
1111 allowed_targets.len() + added_fake_targets.len() == 1,
1112 )
1113}
1114
1115fn filter_targets(
1116 allowed_targets: &mut Vec<Target>,
1117 target_group: &'static [Target],
1118 target_group_name: &'static str,
1119 target: Target,
1120 added_fake_targets: &mut Vec<&'static str>,
1121) {
1122 if target_group.contains(&target) {
1123 return;
1124 }
1125 if allowed_targets.iter().filter(|at| target_group.contains(at)).count() < 2 {
1126 return;
1127 }
1128 allowed_targets.retain(|t| !target_group.contains(t));
1129 added_fake_targets.push(target_group_name);
1130}
1131
1132pub(crate) const ALL_TARGETS: &'static [MaybeWarn] = &[
1137 Allow(Target::ExternCrate),
1138 Allow(Target::Use),
1139 Allow(Target::Static),
1140 Allow(Target::Const),
1141 Allow(Target::Fn),
1142 Allow(Target::Closure),
1143 Allow(Target::Mod),
1144 Allow(Target::ForeignMod),
1145 Allow(Target::GlobalAsm),
1146 Allow(Target::TyAlias),
1147 Allow(Target::Enum),
1148 Allow(Target::Variant),
1149 Allow(Target::Struct),
1150 Allow(Target::Field),
1151 Allow(Target::Union),
1152 Allow(Target::Trait),
1153 Allow(Target::TraitAlias),
1154 Allow(Target::Impl { of_trait: false }),
1155 Allow(Target::Impl { of_trait: true }),
1156 Allow(Target::Expression),
1157 Allow(Target::Statement),
1158 Allow(Target::Arm),
1159 Allow(Target::AssocConst),
1160 Allow(Target::Method(MethodKind::Inherent)),
1161 Allow(Target::Method(MethodKind::Trait { body: false })),
1162 Allow(Target::Method(MethodKind::Trait { body: true })),
1163 Allow(Target::Method(MethodKind::TraitImpl)),
1164 Allow(Target::AssocTy),
1165 Allow(Target::ForeignFn),
1166 Allow(Target::ForeignStatic),
1167 Allow(Target::ForeignTy),
1168 Allow(Target::MacroDef),
1169 Allow(Target::Param),
1170 Allow(Target::PatField),
1171 Allow(Target::ExprField),
1172 Allow(Target::WherePredicate),
1173 Allow(Target::MacroCall),
1174 Allow(Target::Crate),
1175 Allow(Target::Delegation { mac: false }),
1176 Allow(Target::Delegation { mac: true }),
1177];
1178
1179pub(crate) fn parse_single_integer<S: Stage>(
1186 cx: &mut AcceptContext<'_, '_, S>,
1187 args: &ArgParser<'_>,
1188) -> Option<u128> {
1189 let Some(list) = args.list() else {
1190 cx.expected_list(cx.attr_span);
1191 return None;
1192 };
1193 let Some(single) = list.single() else {
1194 cx.expected_single_argument(list.span);
1195 return None;
1196 };
1197 let Some(lit) = single.lit() else {
1198 cx.expected_integer_literal(single.span());
1199 return None;
1200 };
1201 let LitKind::Int(num, _ty) = lit.kind else {
1202 cx.expected_integer_literal(single.span());
1203 return None;
1204 };
1205 Some(num.0)
1206}