rustc_attr_parsing/
context.rs

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        // tidy-alphabetical-start
151        AlignParser,
152        BodyStabilityParser,
153        ConfusablesParser,
154        ConstStabilityParser,
155        MacroUseParser,
156        NakedParser,
157        StabilityParser,
158        UsedParser,
159        // tidy-alphabetical-end
160
161        // tidy-alphabetical-start
162        Combine<AllowConstFnUnstableParser>,
163        Combine<AllowInternalUnstableParser>,
164        Combine<ReprParser>,
165        Combine<TargetFeatureParser>,
166        Combine<UnstableFeatureBoundParser>,
167        // tidy-alphabetical-end
168
169        // tidy-alphabetical-start
170        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        // tidy-alphabetical-end
229    ];
230);
231
232mod private {
233    pub trait Sealed {}
234    impl Sealed for super::Early {}
235    impl Sealed for super::Late {}
236}
237
238// allow because it's a sealed trait
239#[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 because it's a sealed trait
255#[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 because it's a sealed trait
280#[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
300/// used when parsing attributes for miscellaneous things *before* ast lowering
301pub struct Early {
302    /// Whether to emit errors or delay them as a bug
303    /// For most attributes, the attribute will be parsed again in the `Late` stage and in this case the errors should be delayed
304    /// But for some, such as `cfg`, the attribute will be removed before the `Late` stage so errors must be emitted
305    pub emit_errors: ShouldEmit,
306}
307/// used when parsing attributes during ast lowering
308pub struct Late;
309
310/// Context given to every attribute parser when accepting
311///
312/// Gives [`AttributeParser`]s enough information to create errors, for example.
313pub struct AcceptContext<'f, 'sess, S: Stage> {
314    pub(crate) shared: SharedContext<'f, 'sess, S>,
315    /// The span of the attribute currently being parsed
316    pub(crate) attr_span: Span,
317
318    /// The expected structure of the attribute.
319    ///
320    /// Used in reporting errors to give a hint to users what the attribute *should* look like.
321    pub(crate) template: &'f AttributeTemplate,
322
323    /// The name of the attribute we're currently accepting.
324    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    /// Emit a lint. This method is somewhat special, since lints emitted during attribute parsing
333    /// must be delayed until after HIR is built. This method will take care of the details of
334    /// that.
335    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    /// error that a string literal was expected.
381    /// You can optionally give the literal you did find (which you found not to be a string literal)
382    /// which can make better errors. For example, if the literal was a byte string it will suggest
383    /// removing the `b` prefix.
384    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    /// emit an error that a `name` was expected here
433    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    /// emit an error that a `name = value` pair was expected at this span. The symbol can be given for
444    /// a nicer error message talking about the specific name that was found lacking a value.
445    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    /// emit an error that a `name = value` pair was found where that name was already seen.
456    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    /// an error that should be emitted when a [`MetaItemOrLitParser`](crate::parser::MetaItemOrLitParser)
467    /// was expected *not* to be a literal, but instead a meta item.
468    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
571/// Context given to every attribute parser during finalization.
572///
573/// Gives [`AttributeParser`](crate::attributes::AttributeParser)s enough information to create
574/// errors, for example.
575pub struct SharedContext<'p, 'sess, S: Stage> {
576    /// The parse context, gives access to the session and the
577    /// diagnostics context.
578    pub(crate) cx: &'p mut AttributeParser<'sess, S>,
579    /// The span of the syntactical component this attribute was applied to
580    pub(crate) target_span: Span,
581    /// The id ([`NodeId`] if `S` is `Early`, [`HirId`] if `S` is `Late`) of the syntactical component this attribute was applied to
582    pub(crate) target_id: S::Id,
583
584    emit_lint: &'p mut dyn FnMut(AttributeLint<S::Id>),
585}
586
587/// Context given to every attribute parser during finalization.
588///
589/// Gives [`AttributeParser`](crate::attributes::AttributeParser)s enough information to create
590/// errors, for example.
591pub(crate) struct FinalizeContext<'p, 'sess, S: Stage> {
592    pub(crate) shared: SharedContext<'p, 'sess, S>,
593
594    /// A list of all attribute on this syntax node.
595    ///
596    /// Useful for compatibility checks with other attributes in [`finalize`](crate::attributes::AttributeParser::finalize)
597    ///
598    /// Usually, you should use normal attribute parsing logic instead,
599    /// especially when making a *denylist* of other attributes.
600    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    /// The operation will emit errors and lints.
640    /// This is usually what you need.
641    ErrorsAndLints,
642    /// The operation will emit *not* errors and lints.
643    /// Use this if you are *sure* that this operation will be called at a different time with `ShouldEmit::Emit`.
644    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
714/// Context created once, for example as part of the ast lowering
715/// context, through which all attributes can be lowered.
716pub 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    /// *Only* parse attributes with this symbol.
723    ///
724    /// Used in cases where we want the lowering infrastructure for parse just a single attribute.
725    parse_only: Option<Symbol>,
726}
727
728impl<'sess> AttributeParser<'sess, Early> {
729    /// This method allows you to parse attributes *before* you have access to features or tools.
730    /// One example where this is necessary, is to parse `feature` attributes themselves for
731    /// example.
732    ///
733    /// Try to use this as little as possible. Attributes *should* be lowered during
734    /// `rustc_ast_lowering`. Some attributes require access to features to parse, which would
735    /// crash if you tried to do so through [`parse_limited`](Self::parse_limited).
736    ///
737    /// To make sure use is limited, supply a `Symbol` you'd like to parse. Only attributes with
738    /// that symbol are picked out of the list of instructions and parsed. Those are returned.
739    ///
740    /// No diagnostics will be emitted when parsing limited. Lints are not emitted at all, while
741    /// errors will be emitted as a delayed bugs. in other words, we *expect* attributes parsed
742    /// with `parse_limited` to be reparsed later during ast lowering where we *do* emit the errors
743    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, // Does not matter, we're not going to emit errors anyways
763            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    /// Parse a list of attributes.
841    ///
842    /// `target_span` is the span of the thing this list of attributes is applied to,
843    /// and when `omit_doc` is set, doc attributes are filtered out.
844    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 we're only looking for a single attribute, skip all the ones we don't care about.
860            if let Some(expected) = self.parse_only {
861                if !attr.has_name(expected) {
862                    continue;
863                }
864            }
865
866            // Sometimes, for example for `#![doc = include_str!("readme.md")]`,
867            // doc still contains a non-literal. You might say, when we're lowering attributes
868            // that's expanded right? But no, sometimes, when parsing attributes on macros,
869            // we already use the lowering logic and these are still there. So, when `omit_doc`
870            // is set we *also* want to ignore these.
871            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                // // FIXME: make doc attributes go through a proper attribute parser
889                // ast::AttrKind::Normal(n) if n.has_name(sym::doc) => {
890                //     let p = GenericMetaItemParser::from_attr(&n, self.dcx());
891                //
892                //     attributes.push(Attribute::Parsed(AttributeKind::DocComment {
893                //         style: attr.style,
894                //         kind: CommentKind::Line,
895                //         span: attr.span,
896                //         comment: p.args().name_value(),
897                //     }))
898                // }
899                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                        // If we're here, we must be compiling a tool attribute... Or someone
966                        // forgot to parse their fancy new attribute. Let's warn them in any case.
967                        // If you are that person, and you really think your attribute should
968                        // remain unparsed, carefully read the documentation in this module and if
969                        // you still think so you can add an exception to this assertion.
970
971                        // FIXME(jdonszelmann): convert other attributes, and check with this that
972                        // we caught em all
973                        // const FIXME_TEMPORARY_ATTR_ALLOWLIST: &[Symbol] = &[sym::cfg];
974                        // assert!(
975                        //     self.tools.contains(&parts[0]) || true,
976                        //     // || FIXME_TEMPORARY_ATTR_ALLOWLIST.contains(&parts[0]),
977                        //     "attribute {path} wasn't parsed and isn't a know tool attribute",
978                        // );
979
980                        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    /// Returns whether there is a parser for an attribute with this name
1013    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            // This is an inert key-value attribute - it will never be visible to macros
1022            // after it gets lowered to HIR. Therefore, we can extract literals to handle
1023            // nonterminals in `#[doc]` (e.g. `#[doc = $e]`).
1024            ast::AttrArgs::Eq { eq_span, expr } => {
1025                // In valid code the value always ends up as a single literal. Otherwise, a dummy
1026                // literal suffices because the error is handled elsewhere.
1027                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
1050/// Takes a list of `allowed_targets` for an attribute, and the `target` the attribute was applied to.
1051/// Does some heuristic-based filtering to remove uninteresting targets, and formats the targets into a string
1052pub(crate) fn allowed_targets_applied(
1053    mut allowed_targets: Vec<Target>,
1054    target: Target,
1055    features: Option<&Features>,
1056) -> (String, bool) {
1057    // Remove unstable targets from `allowed_targets` if their features are not enabled
1058    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    // We define groups of "similar" targets.
1071    // If at least two of the targets are allowed, and the `target` is not in the group,
1072    // we collapse the entire group to a single entry to simplify the target list
1073    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    // If there is now only 1 target left, show that as the only possible target
1105    (
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
1132/// This is the list of all targets to which a attribute can be applied
1133/// This is used for:
1134/// - `rustc_dummy`, which can be applied to all targets
1135/// - Attributes that are not parted to the new target system yet can use this list as a placeholder
1136pub(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
1179/// Parse a single integer.
1180///
1181/// Used by attributes that take a single integer as argument, such as
1182/// `#[link_ordinal]` and `#[rustc_layout_scalar_valid_range_start]`.
1183/// `cx` is the context given to the attribute.
1184/// `args` is the parser for the attribute arguments.
1185pub(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}