rustc_attr_parsing/
context.rs

1use std::cell::RefCell;
2use std::collections::BTreeMap;
3use std::ops::{Deref, DerefMut};
4use std::sync::LazyLock;
5
6use private::Sealed;
7use rustc_ast::{AttrStyle, CRATE_NODE_ID, MetaItemLit, NodeId};
8use rustc_errors::{Diag, Diagnostic, Level};
9use rustc_feature::AttributeTemplate;
10use rustc_hir::attrs::AttributeKind;
11use rustc_hir::lints::{AttributeLint, AttributeLintKind};
12use rustc_hir::{AttrPath, CRATE_HIR_ID, HirId};
13use rustc_session::Session;
14use rustc_span::{ErrorGuaranteed, Span, Symbol};
15
16use crate::AttributeParser;
17use crate::attributes::allow_unstable::{
18    AllowConstFnUnstableParser, AllowInternalUnstableParser, UnstableFeatureBoundParser,
19};
20use crate::attributes::body::CoroutineParser;
21use crate::attributes::codegen_attrs::{
22    ColdParser, CoverageParser, ExportNameParser, ForceTargetFeatureParser, NakedParser,
23    NoMangleParser, ObjcClassParser, ObjcSelectorParser, OptimizeParser, SanitizeParser,
24    TargetFeatureParser, TrackCallerParser, UsedParser,
25};
26use crate::attributes::confusables::ConfusablesParser;
27use crate::attributes::crate_level::{
28    CrateNameParser, MoveSizeLimitParser, NoCoreParser, NoStdParser, PatternComplexityLimitParser,
29    RecursionLimitParser, RustcCoherenceIsCoreParser, TypeLengthLimitParser,
30};
31use crate::attributes::debugger::DebuggerViualizerParser;
32use crate::attributes::deprecation::DeprecationParser;
33use crate::attributes::dummy::DummyParser;
34use crate::attributes::inline::{InlineParser, RustcForceInlineParser};
35use crate::attributes::link_attrs::{
36    ExportStableParser, FfiConstParser, FfiPureParser, LinkNameParser, LinkOrdinalParser,
37    LinkParser, LinkSectionParser, LinkageParser, StdInternalSymbolParser,
38};
39use crate::attributes::lint_helpers::{
40    AsPtrParser, AutomaticallyDerivedParser, PassByValueParser, PubTransparentParser,
41};
42use crate::attributes::loop_match::{ConstContinueParser, LoopMatchParser};
43use crate::attributes::macro_attrs::{
44    AllowInternalUnsafeParser, MacroEscapeParser, MacroExportParser, MacroUseParser,
45};
46use crate::attributes::must_use::MustUseParser;
47use crate::attributes::no_implicit_prelude::NoImplicitPreludeParser;
48use crate::attributes::non_exhaustive::NonExhaustiveParser;
49use crate::attributes::path::PathParser as PathAttributeParser;
50use crate::attributes::proc_macro_attrs::{
51    ProcMacroAttributeParser, ProcMacroDeriveParser, ProcMacroParser, RustcBuiltinMacroParser,
52};
53use crate::attributes::prototype::CustomMirParser;
54use crate::attributes::repr::{AlignParser, AlignStaticParser, ReprParser};
55use crate::attributes::rustc_internal::{
56    RustcLayoutScalarValidRangeEnd, RustcLayoutScalarValidRangeStart,
57    RustcObjectLifetimeDefaultParser, RustcSimdMonomorphizeLaneLimitParser,
58};
59use crate::attributes::semantics::MayDangleParser;
60use crate::attributes::stability::{
61    BodyStabilityParser, ConstStabilityIndirectParser, ConstStabilityParser, StabilityParser,
62};
63use crate::attributes::test_attrs::{IgnoreParser, ShouldPanicParser};
64use crate::attributes::traits::{
65    AllowIncoherentImplParser, CoinductiveParser, ConstTraitParser, DenyExplicitImplParser,
66    DoNotImplementViaObjectParser, FundamentalParser, MarkerParser, ParenSugarParser,
67    PointeeParser, SkipDuringMethodDispatchParser, SpecializationTraitParser, TypeConstParser,
68    UnsafeSpecializationMarkerParser,
69};
70use crate::attributes::transparency::TransparencyParser;
71use crate::attributes::{AttributeParser as _, Combine, Single, WithoutArgs};
72use crate::parser::{ArgParser, PathParser};
73use crate::session_diagnostics::{AttributeParseError, AttributeParseErrorReason, UnknownMetaItem};
74use crate::target_checking::AllowedTargets;
75
76type GroupType<S> = LazyLock<GroupTypeInner<S>>;
77
78pub(super) struct GroupTypeInner<S: Stage> {
79    pub(super) accepters: BTreeMap<&'static [Symbol], Vec<GroupTypeInnerAccept<S>>>,
80    pub(super) finalizers: Vec<FinalizeFn<S>>,
81}
82
83pub(super) struct GroupTypeInnerAccept<S: Stage> {
84    pub(super) template: AttributeTemplate,
85    pub(super) accept_fn: AcceptFn<S>,
86    pub(super) allowed_targets: AllowedTargets,
87}
88
89type AcceptFn<S> =
90    Box<dyn for<'sess, 'a> Fn(&mut AcceptContext<'_, 'sess, S>, &ArgParser<'a>) + Send + Sync>;
91type FinalizeFn<S> =
92    Box<dyn Send + Sync + Fn(&mut FinalizeContext<'_, '_, S>) -> Option<AttributeKind>>;
93
94macro_rules! attribute_parsers {
95    (
96        pub(crate) static $name: ident = [$($names: ty),* $(,)?];
97    ) => {
98        mod early {
99            use super::*;
100            type Combine<T> = super::Combine<T, Early>;
101            type Single<T> = super::Single<T, Early>;
102            type WithoutArgs<T> = super::WithoutArgs<T, Early>;
103
104            attribute_parsers!(@[Early] pub(crate) static $name = [$($names),*];);
105        }
106        mod late {
107            use super::*;
108            type Combine<T> = super::Combine<T, Late>;
109            type Single<T> = super::Single<T, Late>;
110            type WithoutArgs<T> = super::WithoutArgs<T, Late>;
111
112            attribute_parsers!(@[Late] pub(crate) static $name = [$($names),*];);
113        }
114    };
115    (
116        @[$stage: ty] pub(crate) static $name: ident = [$($names: ty),* $(,)?];
117    ) => {
118        pub(crate) static $name: GroupType<$stage> = LazyLock::new(|| {
119            let mut accepts = BTreeMap::<_, Vec<GroupTypeInnerAccept<$stage>>>::new();
120            let mut finalizes = Vec::<FinalizeFn<$stage>>::new();
121            $(
122                {
123                    thread_local! {
124                        static STATE_OBJECT: RefCell<$names> = RefCell::new(<$names>::default());
125                    };
126
127                    for (path, template, accept_fn) in <$names>::ATTRIBUTES {
128                        accepts.entry(*path).or_default().push(GroupTypeInnerAccept {
129                            template: *template,
130                            accept_fn: Box::new(|cx, args| {
131                                STATE_OBJECT.with_borrow_mut(|s| {
132                                    accept_fn(s, cx, args)
133                                })
134                            }),
135                            allowed_targets: <$names as crate::attributes::AttributeParser<$stage>>::ALLOWED_TARGETS,
136                        });
137                    }
138
139                    finalizes.push(Box::new(|cx| {
140                        let state = STATE_OBJECT.take();
141                        state.finalize(cx)
142                    }));
143                }
144            )*
145
146            GroupTypeInner { accepters:accepts, finalizers:finalizes }
147        });
148    };
149}
150attribute_parsers!(
151    pub(crate) static ATTRIBUTE_PARSERS = [
152        // tidy-alphabetical-start
153        AlignParser,
154        AlignStaticParser,
155        BodyStabilityParser,
156        ConfusablesParser,
157        ConstStabilityParser,
158        MacroUseParser,
159        NakedParser,
160        StabilityParser,
161        UsedParser,
162        // tidy-alphabetical-end
163
164        // tidy-alphabetical-start
165        Combine<AllowConstFnUnstableParser>,
166        Combine<AllowInternalUnstableParser>,
167        Combine<DebuggerViualizerParser>,
168        Combine<ForceTargetFeatureParser>,
169        Combine<LinkParser>,
170        Combine<ReprParser>,
171        Combine<TargetFeatureParser>,
172        Combine<UnstableFeatureBoundParser>,
173        // tidy-alphabetical-end
174
175        // tidy-alphabetical-start
176        Single<CoverageParser>,
177        Single<CrateNameParser>,
178        Single<CustomMirParser>,
179        Single<DeprecationParser>,
180        Single<DummyParser>,
181        Single<ExportNameParser>,
182        Single<IgnoreParser>,
183        Single<InlineParser>,
184        Single<LinkNameParser>,
185        Single<LinkOrdinalParser>,
186        Single<LinkSectionParser>,
187        Single<LinkageParser>,
188        Single<MacroExportParser>,
189        Single<MoveSizeLimitParser>,
190        Single<MustUseParser>,
191        Single<ObjcClassParser>,
192        Single<ObjcSelectorParser>,
193        Single<OptimizeParser>,
194        Single<PathAttributeParser>,
195        Single<PatternComplexityLimitParser>,
196        Single<ProcMacroDeriveParser>,
197        Single<RecursionLimitParser>,
198        Single<RustcBuiltinMacroParser>,
199        Single<RustcForceInlineParser>,
200        Single<RustcLayoutScalarValidRangeEnd>,
201        Single<RustcLayoutScalarValidRangeStart>,
202        Single<RustcObjectLifetimeDefaultParser>,
203        Single<RustcSimdMonomorphizeLaneLimitParser>,
204        Single<SanitizeParser>,
205        Single<ShouldPanicParser>,
206        Single<SkipDuringMethodDispatchParser>,
207        Single<TransparencyParser>,
208        Single<TypeLengthLimitParser>,
209        Single<WithoutArgs<AllowIncoherentImplParser>>,
210        Single<WithoutArgs<AllowInternalUnsafeParser>>,
211        Single<WithoutArgs<AsPtrParser>>,
212        Single<WithoutArgs<AutomaticallyDerivedParser>>,
213        Single<WithoutArgs<CoinductiveParser>>,
214        Single<WithoutArgs<ColdParser>>,
215        Single<WithoutArgs<ConstContinueParser>>,
216        Single<WithoutArgs<ConstStabilityIndirectParser>>,
217        Single<WithoutArgs<ConstTraitParser>>,
218        Single<WithoutArgs<CoroutineParser>>,
219        Single<WithoutArgs<DenyExplicitImplParser>>,
220        Single<WithoutArgs<DoNotImplementViaObjectParser>>,
221        Single<WithoutArgs<ExportStableParser>>,
222        Single<WithoutArgs<FfiConstParser>>,
223        Single<WithoutArgs<FfiPureParser>>,
224        Single<WithoutArgs<FundamentalParser>>,
225        Single<WithoutArgs<LoopMatchParser>>,
226        Single<WithoutArgs<MacroEscapeParser>>,
227        Single<WithoutArgs<MarkerParser>>,
228        Single<WithoutArgs<MayDangleParser>>,
229        Single<WithoutArgs<NoCoreParser>>,
230        Single<WithoutArgs<NoImplicitPreludeParser>>,
231        Single<WithoutArgs<NoMangleParser>>,
232        Single<WithoutArgs<NoStdParser>>,
233        Single<WithoutArgs<NonExhaustiveParser>>,
234        Single<WithoutArgs<ParenSugarParser>>,
235        Single<WithoutArgs<PassByValueParser>>,
236        Single<WithoutArgs<PointeeParser>>,
237        Single<WithoutArgs<ProcMacroAttributeParser>>,
238        Single<WithoutArgs<ProcMacroParser>>,
239        Single<WithoutArgs<PubTransparentParser>>,
240        Single<WithoutArgs<RustcCoherenceIsCoreParser>>,
241        Single<WithoutArgs<SpecializationTraitParser>>,
242        Single<WithoutArgs<StdInternalSymbolParser>>,
243        Single<WithoutArgs<TrackCallerParser>>,
244        Single<WithoutArgs<TypeConstParser>>,
245        Single<WithoutArgs<UnsafeSpecializationMarkerParser>>,
246        // tidy-alphabetical-end
247    ];
248);
249
250mod private {
251    pub trait Sealed {}
252    impl Sealed for super::Early {}
253    impl Sealed for super::Late {}
254}
255
256// allow because it's a sealed trait
257#[allow(private_interfaces)]
258pub trait Stage: Sized + 'static + Sealed {
259    type Id: Copy;
260
261    fn parsers() -> &'static GroupType<Self>;
262
263    fn emit_err<'sess>(
264        &self,
265        sess: &'sess Session,
266        diag: impl for<'x> Diagnostic<'x>,
267    ) -> ErrorGuaranteed;
268
269    fn should_emit(&self) -> ShouldEmit;
270
271    fn id_is_crate_root(id: Self::Id) -> bool;
272}
273
274// allow because it's a sealed trait
275#[allow(private_interfaces)]
276impl Stage for Early {
277    type Id = NodeId;
278
279    fn parsers() -> &'static GroupType<Self> {
280        &early::ATTRIBUTE_PARSERS
281    }
282    fn emit_err<'sess>(
283        &self,
284        sess: &'sess Session,
285        diag: impl for<'x> Diagnostic<'x>,
286    ) -> ErrorGuaranteed {
287        self.should_emit().emit_err(sess.dcx().create_err(diag))
288    }
289
290    fn should_emit(&self) -> ShouldEmit {
291        self.emit_errors
292    }
293
294    fn id_is_crate_root(id: Self::Id) -> bool {
295        id == CRATE_NODE_ID
296    }
297}
298
299// allow because it's a sealed trait
300#[allow(private_interfaces)]
301impl Stage for Late {
302    type Id = HirId;
303
304    fn parsers() -> &'static GroupType<Self> {
305        &late::ATTRIBUTE_PARSERS
306    }
307    fn emit_err<'sess>(
308        &self,
309        tcx: &'sess Session,
310        diag: impl for<'x> Diagnostic<'x>,
311    ) -> ErrorGuaranteed {
312        tcx.dcx().emit_err(diag)
313    }
314
315    fn should_emit(&self) -> ShouldEmit {
316        ShouldEmit::ErrorsAndLints
317    }
318
319    fn id_is_crate_root(id: Self::Id) -> bool {
320        id == CRATE_HIR_ID
321    }
322}
323
324/// used when parsing attributes for miscellaneous things *before* ast lowering
325pub struct Early {
326    /// Whether to emit errors or delay them as a bug
327    /// For most attributes, the attribute will be parsed again in the `Late` stage and in this case the errors should be delayed
328    /// But for some, such as `cfg`, the attribute will be removed before the `Late` stage so errors must be emitted
329    pub emit_errors: ShouldEmit,
330}
331/// used when parsing attributes during ast lowering
332pub struct Late;
333
334/// Context given to every attribute parser when accepting
335///
336/// Gives [`AttributeParser`]s enough information to create errors, for example.
337pub struct AcceptContext<'f, 'sess, S: Stage> {
338    pub(crate) shared: SharedContext<'f, 'sess, S>,
339    /// The span of the attribute currently being parsed
340    pub(crate) attr_span: Span,
341
342    /// Whether it is an inner or outer attribute
343    pub(crate) attr_style: AttrStyle,
344
345    /// The expected structure of the attribute.
346    ///
347    /// Used in reporting errors to give a hint to users what the attribute *should* look like.
348    pub(crate) template: &'f AttributeTemplate,
349
350    /// The name of the attribute we're currently accepting.
351    pub(crate) attr_path: AttrPath,
352}
353
354impl<'f, 'sess: 'f, S: Stage> SharedContext<'f, 'sess, S> {
355    pub(crate) fn emit_err(&self, diag: impl for<'x> Diagnostic<'x>) -> ErrorGuaranteed {
356        self.stage.emit_err(&self.sess, diag)
357    }
358
359    /// Emit a lint. This method is somewhat special, since lints emitted during attribute parsing
360    /// must be delayed until after HIR is built. This method will take care of the details of
361    /// that.
362    pub(crate) fn emit_lint(&mut self, lint: AttributeLintKind, span: Span) {
363        if !matches!(
364            self.stage.should_emit(),
365            ShouldEmit::ErrorsAndLints | ShouldEmit::EarlyFatal { also_emit_lints: true }
366        ) {
367            return;
368        }
369        let id = self.target_id;
370        (self.emit_lint)(AttributeLint { id, span, kind: lint });
371    }
372
373    pub(crate) fn warn_unused_duplicate(&mut self, used_span: Span, unused_span: Span) {
374        self.emit_lint(
375            AttributeLintKind::UnusedDuplicate {
376                this: unused_span,
377                other: used_span,
378                warning: false,
379            },
380            unused_span,
381        )
382    }
383
384    pub(crate) fn warn_unused_duplicate_future_error(
385        &mut self,
386        used_span: Span,
387        unused_span: Span,
388    ) {
389        self.emit_lint(
390            AttributeLintKind::UnusedDuplicate {
391                this: unused_span,
392                other: used_span,
393                warning: true,
394            },
395            unused_span,
396        )
397    }
398}
399
400impl<'f, 'sess: 'f, S: Stage> AcceptContext<'f, 'sess, S> {
401    pub(crate) fn unknown_key(
402        &self,
403        span: Span,
404        found: String,
405        options: &'static [&'static str],
406    ) -> ErrorGuaranteed {
407        self.emit_err(UnknownMetaItem { span, item: found, expected: options })
408    }
409
410    /// error that a string literal was expected.
411    /// You can optionally give the literal you did find (which you found not to be a string literal)
412    /// which can make better errors. For example, if the literal was a byte string it will suggest
413    /// removing the `b` prefix.
414    pub(crate) fn expected_string_literal(
415        &self,
416        span: Span,
417        actual_literal: Option<&MetaItemLit>,
418    ) -> ErrorGuaranteed {
419        self.emit_err(AttributeParseError {
420            span,
421            attr_span: self.attr_span,
422            template: self.template.clone(),
423            attribute: self.attr_path.clone(),
424            reason: AttributeParseErrorReason::ExpectedStringLiteral {
425                byte_string: actual_literal.and_then(|i| {
426                    i.kind.is_bytestr().then(|| self.sess().source_map().start_point(i.span))
427                }),
428            },
429            attr_style: self.attr_style,
430        })
431    }
432
433    pub(crate) fn expected_integer_literal(&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::ExpectedIntegerLiteral,
440            attr_style: self.attr_style,
441        })
442    }
443
444    pub(crate) fn expected_list(&self, span: Span) -> ErrorGuaranteed {
445        self.emit_err(AttributeParseError {
446            span,
447            attr_span: self.attr_span,
448            template: self.template.clone(),
449            attribute: self.attr_path.clone(),
450            reason: AttributeParseErrorReason::ExpectedList,
451            attr_style: self.attr_style,
452        })
453    }
454
455    pub(crate) fn expected_no_args(&self, args_span: Span) -> ErrorGuaranteed {
456        self.emit_err(AttributeParseError {
457            span: args_span,
458            attr_span: self.attr_span,
459            template: self.template.clone(),
460            attribute: self.attr_path.clone(),
461            reason: AttributeParseErrorReason::ExpectedNoArgs,
462            attr_style: self.attr_style,
463        })
464    }
465
466    /// emit an error that a `name` was expected here
467    pub(crate) fn expected_identifier(&self, span: Span) -> ErrorGuaranteed {
468        self.emit_err(AttributeParseError {
469            span,
470            attr_span: self.attr_span,
471            template: self.template.clone(),
472            attribute: self.attr_path.clone(),
473            reason: AttributeParseErrorReason::ExpectedIdentifier,
474            attr_style: self.attr_style,
475        })
476    }
477
478    /// emit an error that a `name = value` pair was expected at this span. The symbol can be given for
479    /// a nicer error message talking about the specific name that was found lacking a value.
480    pub(crate) fn expected_name_value(&self, span: Span, name: Option<Symbol>) -> ErrorGuaranteed {
481        self.emit_err(AttributeParseError {
482            span,
483            attr_span: self.attr_span,
484            template: self.template.clone(),
485            attribute: self.attr_path.clone(),
486            reason: AttributeParseErrorReason::ExpectedNameValue(name),
487            attr_style: self.attr_style,
488        })
489    }
490
491    /// emit an error that a `name = value` pair was found where that name was already seen.
492    pub(crate) fn duplicate_key(&self, span: Span, key: Symbol) -> ErrorGuaranteed {
493        self.emit_err(AttributeParseError {
494            span,
495            attr_span: self.attr_span,
496            template: self.template.clone(),
497            attribute: self.attr_path.clone(),
498            reason: AttributeParseErrorReason::DuplicateKey(key),
499            attr_style: self.attr_style,
500        })
501    }
502
503    /// an error that should be emitted when a [`MetaItemOrLitParser`](crate::parser::MetaItemOrLitParser)
504    /// was expected *not* to be a literal, but instead a meta item.
505    pub(crate) fn unexpected_literal(&self, span: Span) -> ErrorGuaranteed {
506        self.emit_err(AttributeParseError {
507            span,
508            attr_span: self.attr_span,
509            template: self.template.clone(),
510            attribute: self.attr_path.clone(),
511            reason: AttributeParseErrorReason::UnexpectedLiteral,
512            attr_style: self.attr_style,
513        })
514    }
515
516    pub(crate) fn expected_single_argument(&self, span: Span) -> ErrorGuaranteed {
517        self.emit_err(AttributeParseError {
518            span,
519            attr_span: self.attr_span,
520            template: self.template.clone(),
521            attribute: self.attr_path.clone(),
522            reason: AttributeParseErrorReason::ExpectedSingleArgument,
523            attr_style: self.attr_style,
524        })
525    }
526
527    pub(crate) fn expected_at_least_one_argument(&self, span: Span) -> ErrorGuaranteed {
528        self.emit_err(AttributeParseError {
529            span,
530            attr_span: self.attr_span,
531            template: self.template.clone(),
532            attribute: self.attr_path.clone(),
533            reason: AttributeParseErrorReason::ExpectedAtLeastOneArgument,
534            attr_style: self.attr_style,
535        })
536    }
537
538    /// produces an error along the lines of `expected one of [foo, meow]`
539    pub(crate) fn expected_specific_argument(
540        &self,
541        span: Span,
542        possibilities: &[Symbol],
543    ) -> ErrorGuaranteed {
544        self.emit_err(AttributeParseError {
545            span,
546            attr_span: self.attr_span,
547            template: self.template.clone(),
548            attribute: self.attr_path.clone(),
549            reason: AttributeParseErrorReason::ExpectedSpecificArgument {
550                possibilities,
551                strings: false,
552                list: false,
553            },
554            attr_style: self.attr_style,
555        })
556    }
557
558    /// produces an error along the lines of `expected one of [foo, meow] as an argument`.
559    /// i.e. slightly different wording to [`expected_specific_argument`](Self::expected_specific_argument).
560    pub(crate) fn expected_specific_argument_and_list(
561        &self,
562        span: Span,
563        possibilities: &[Symbol],
564    ) -> ErrorGuaranteed {
565        self.emit_err(AttributeParseError {
566            span,
567            attr_span: self.attr_span,
568            template: self.template.clone(),
569            attribute: self.attr_path.clone(),
570            reason: AttributeParseErrorReason::ExpectedSpecificArgument {
571                possibilities,
572                strings: false,
573                list: true,
574            },
575            attr_style: self.attr_style,
576        })
577    }
578
579    /// produces an error along the lines of `expected one of ["foo", "meow"]`
580    pub(crate) fn expected_specific_argument_strings(
581        &self,
582        span: Span,
583        possibilities: &[Symbol],
584    ) -> ErrorGuaranteed {
585        self.emit_err(AttributeParseError {
586            span,
587            attr_span: self.attr_span,
588            template: self.template.clone(),
589            attribute: self.attr_path.clone(),
590            reason: AttributeParseErrorReason::ExpectedSpecificArgument {
591                possibilities,
592                strings: true,
593                list: false,
594            },
595            attr_style: self.attr_style,
596        })
597    }
598
599    pub(crate) fn warn_empty_attribute(&mut self, span: Span) {
600        let attr_path = self.attr_path.clone();
601        let valid_without_list = self.template.word;
602        self.emit_lint(
603            AttributeLintKind::EmptyAttribute { first_span: span, attr_path, valid_without_list },
604            span,
605        );
606    }
607}
608
609impl<'f, 'sess, S: Stage> Deref for AcceptContext<'f, 'sess, S> {
610    type Target = SharedContext<'f, 'sess, S>;
611
612    fn deref(&self) -> &Self::Target {
613        &self.shared
614    }
615}
616
617impl<'f, 'sess, S: Stage> DerefMut for AcceptContext<'f, 'sess, S> {
618    fn deref_mut(&mut self) -> &mut Self::Target {
619        &mut self.shared
620    }
621}
622
623/// Context given to every attribute parser during finalization.
624///
625/// Gives [`AttributeParser`](crate::attributes::AttributeParser)s enough information to create
626/// errors, for example.
627pub struct SharedContext<'p, 'sess, S: Stage> {
628    /// The parse context, gives access to the session and the
629    /// diagnostics context.
630    pub(crate) cx: &'p mut AttributeParser<'sess, S>,
631    /// The span of the syntactical component this attribute was applied to
632    pub(crate) target_span: Span,
633    /// The id ([`NodeId`] if `S` is `Early`, [`HirId`] if `S` is `Late`) of the syntactical component this attribute was applied to
634    pub(crate) target_id: S::Id,
635
636    pub(crate) emit_lint: &'p mut dyn FnMut(AttributeLint<S::Id>),
637}
638
639/// Context given to every attribute parser during finalization.
640///
641/// Gives [`AttributeParser`](crate::attributes::AttributeParser)s enough information to create
642/// errors, for example.
643pub(crate) struct FinalizeContext<'p, 'sess, S: Stage> {
644    pub(crate) shared: SharedContext<'p, 'sess, S>,
645
646    /// A list of all attribute on this syntax node.
647    ///
648    /// Useful for compatibility checks with other attributes in [`finalize`](crate::attributes::AttributeParser::finalize)
649    ///
650    /// Usually, you should use normal attribute parsing logic instead,
651    /// especially when making a *denylist* of other attributes.
652    pub(crate) all_attrs: &'p [PathParser<'p>],
653}
654
655impl<'p, 'sess: 'p, S: Stage> Deref for FinalizeContext<'p, 'sess, S> {
656    type Target = SharedContext<'p, 'sess, S>;
657
658    fn deref(&self) -> &Self::Target {
659        &self.shared
660    }
661}
662
663impl<'p, 'sess: 'p, S: Stage> DerefMut for FinalizeContext<'p, 'sess, S> {
664    fn deref_mut(&mut self) -> &mut Self::Target {
665        &mut self.shared
666    }
667}
668
669impl<'p, 'sess: 'p, S: Stage> Deref for SharedContext<'p, 'sess, S> {
670    type Target = AttributeParser<'sess, S>;
671
672    fn deref(&self) -> &Self::Target {
673        self.cx
674    }
675}
676
677impl<'p, 'sess: 'p, S: Stage> DerefMut for SharedContext<'p, 'sess, S> {
678    fn deref_mut(&mut self) -> &mut Self::Target {
679        self.cx
680    }
681}
682
683#[derive(PartialEq, Clone, Copy, Debug)]
684pub enum OmitDoc {
685    Lower,
686    Skip,
687}
688
689#[derive(Copy, Clone, Debug)]
690pub enum ShouldEmit {
691    /// The operations will emit errors, and lints, and errors are fatal.
692    ///
693    /// Only relevant when early parsing, in late parsing equivalent to `ErrorsAndLints`.
694    /// Late parsing is never fatal, and instead tries to emit as many diagnostics as possible.
695    EarlyFatal { also_emit_lints: bool },
696    /// The operation will emit errors and lints.
697    /// This is usually what you need.
698    ErrorsAndLints,
699    /// The operation will emit *not* errors and lints.
700    /// Use this if you are *sure* that this operation will be called at a different time with `ShouldEmit::ErrorsAndLints`.
701    Nothing,
702}
703
704impl ShouldEmit {
705    pub(crate) fn emit_err(&self, diag: Diag<'_>) -> ErrorGuaranteed {
706        match self {
707            ShouldEmit::EarlyFatal { .. } if diag.level() == Level::DelayedBug => diag.emit(),
708            ShouldEmit::EarlyFatal { .. } => diag.upgrade_to_fatal().emit(),
709            ShouldEmit::ErrorsAndLints => diag.emit(),
710            ShouldEmit::Nothing => diag.delay_as_bug(),
711        }
712    }
713}