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    RustcLayoutScalarValidRangeEndParser, RustcLayoutScalarValidRangeStartParser, RustcMainParser,
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<RustcLayoutScalarValidRangeEndParser>,
201        Single<RustcLayoutScalarValidRangeStartParser>,
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<RustcMainParser>>,
242        Single<WithoutArgs<SpecializationTraitParser>>,
243        Single<WithoutArgs<StdInternalSymbolParser>>,
244        Single<WithoutArgs<TrackCallerParser>>,
245        Single<WithoutArgs<TypeConstParser>>,
246        Single<WithoutArgs<UnsafeSpecializationMarkerParser>>,
247        // tidy-alphabetical-end
248    ];
249);
250
251mod private {
252    pub trait Sealed {}
253    impl Sealed for super::Early {}
254    impl Sealed for super::Late {}
255}
256
257// allow because it's a sealed trait
258#[allow(private_interfaces)]
259pub trait Stage: Sized + 'static + Sealed {
260    type Id: Copy;
261
262    fn parsers() -> &'static GroupType<Self>;
263
264    fn emit_err<'sess>(
265        &self,
266        sess: &'sess Session,
267        diag: impl for<'x> Diagnostic<'x>,
268    ) -> ErrorGuaranteed;
269
270    fn should_emit(&self) -> ShouldEmit;
271
272    fn id_is_crate_root(id: Self::Id) -> bool;
273}
274
275// allow because it's a sealed trait
276#[allow(private_interfaces)]
277impl Stage for Early {
278    type Id = NodeId;
279
280    fn parsers() -> &'static GroupType<Self> {
281        &early::ATTRIBUTE_PARSERS
282    }
283    fn emit_err<'sess>(
284        &self,
285        sess: &'sess Session,
286        diag: impl for<'x> Diagnostic<'x>,
287    ) -> ErrorGuaranteed {
288        self.should_emit().emit_err(sess.dcx().create_err(diag))
289    }
290
291    fn should_emit(&self) -> ShouldEmit {
292        self.emit_errors
293    }
294
295    fn id_is_crate_root(id: Self::Id) -> bool {
296        id == CRATE_NODE_ID
297    }
298}
299
300// allow because it's a sealed trait
301#[allow(private_interfaces)]
302impl Stage for Late {
303    type Id = HirId;
304
305    fn parsers() -> &'static GroupType<Self> {
306        &late::ATTRIBUTE_PARSERS
307    }
308    fn emit_err<'sess>(
309        &self,
310        tcx: &'sess Session,
311        diag: impl for<'x> Diagnostic<'x>,
312    ) -> ErrorGuaranteed {
313        tcx.dcx().emit_err(diag)
314    }
315
316    fn should_emit(&self) -> ShouldEmit {
317        ShouldEmit::ErrorsAndLints
318    }
319
320    fn id_is_crate_root(id: Self::Id) -> bool {
321        id == CRATE_HIR_ID
322    }
323}
324
325/// used when parsing attributes for miscellaneous things *before* ast lowering
326pub struct Early {
327    /// Whether to emit errors or delay them as a bug
328    /// For most attributes, the attribute will be parsed again in the `Late` stage and in this case the errors should be delayed
329    /// But for some, such as `cfg`, the attribute will be removed before the `Late` stage so errors must be emitted
330    pub emit_errors: ShouldEmit,
331}
332/// used when parsing attributes during ast lowering
333pub struct Late;
334
335/// Context given to every attribute parser when accepting
336///
337/// Gives [`AttributeParser`]s enough information to create errors, for example.
338pub struct AcceptContext<'f, 'sess, S: Stage> {
339    pub(crate) shared: SharedContext<'f, 'sess, S>,
340    /// The span of the attribute currently being parsed
341    pub(crate) attr_span: Span,
342
343    /// Whether it is an inner or outer attribute
344    pub(crate) attr_style: AttrStyle,
345
346    /// The expected structure of the attribute.
347    ///
348    /// Used in reporting errors to give a hint to users what the attribute *should* look like.
349    pub(crate) template: &'f AttributeTemplate,
350
351    /// The name of the attribute we're currently accepting.
352    pub(crate) attr_path: AttrPath,
353}
354
355impl<'f, 'sess: 'f, S: Stage> SharedContext<'f, 'sess, S> {
356    pub(crate) fn emit_err(&self, diag: impl for<'x> Diagnostic<'x>) -> ErrorGuaranteed {
357        self.stage.emit_err(&self.sess, diag)
358    }
359
360    /// Emit a lint. This method is somewhat special, since lints emitted during attribute parsing
361    /// must be delayed until after HIR is built. This method will take care of the details of
362    /// that.
363    pub(crate) fn emit_lint(&mut self, lint: AttributeLintKind, span: Span) {
364        if !matches!(
365            self.stage.should_emit(),
366            ShouldEmit::ErrorsAndLints | ShouldEmit::EarlyFatal { also_emit_lints: true }
367        ) {
368            return;
369        }
370        let id = self.target_id;
371        (self.emit_lint)(AttributeLint { id, span, kind: lint });
372    }
373
374    pub(crate) fn warn_unused_duplicate(&mut self, used_span: Span, unused_span: Span) {
375        self.emit_lint(
376            AttributeLintKind::UnusedDuplicate {
377                this: unused_span,
378                other: used_span,
379                warning: false,
380            },
381            unused_span,
382        )
383    }
384
385    pub(crate) fn warn_unused_duplicate_future_error(
386        &mut self,
387        used_span: Span,
388        unused_span: Span,
389    ) {
390        self.emit_lint(
391            AttributeLintKind::UnusedDuplicate {
392                this: unused_span,
393                other: used_span,
394                warning: true,
395            },
396            unused_span,
397        )
398    }
399}
400
401impl<'f, 'sess: 'f, S: Stage> AcceptContext<'f, 'sess, S> {
402    pub(crate) fn unknown_key(
403        &self,
404        span: Span,
405        found: String,
406        options: &'static [&'static str],
407    ) -> ErrorGuaranteed {
408        self.emit_err(UnknownMetaItem { span, item: found, expected: options })
409    }
410
411    /// error that a string literal was expected.
412    /// You can optionally give the literal you did find (which you found not to be a string literal)
413    /// which can make better errors. For example, if the literal was a byte string it will suggest
414    /// removing the `b` prefix.
415    pub(crate) fn expected_string_literal(
416        &self,
417        span: Span,
418        actual_literal: Option<&MetaItemLit>,
419    ) -> ErrorGuaranteed {
420        self.emit_err(AttributeParseError {
421            span,
422            attr_span: self.attr_span,
423            template: self.template.clone(),
424            attribute: self.attr_path.clone(),
425            reason: AttributeParseErrorReason::ExpectedStringLiteral {
426                byte_string: actual_literal.and_then(|i| {
427                    i.kind.is_bytestr().then(|| self.sess().source_map().start_point(i.span))
428                }),
429            },
430            attr_style: self.attr_style,
431        })
432    }
433
434    pub(crate) fn expected_integer_literal(&self, span: Span) -> ErrorGuaranteed {
435        self.emit_err(AttributeParseError {
436            span,
437            attr_span: self.attr_span,
438            template: self.template.clone(),
439            attribute: self.attr_path.clone(),
440            reason: AttributeParseErrorReason::ExpectedIntegerLiteral,
441            attr_style: self.attr_style,
442        })
443    }
444
445    pub(crate) fn expected_list(&self, span: Span) -> 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::ExpectedList,
452            attr_style: self.attr_style,
453        })
454    }
455
456    pub(crate) fn expected_no_args(&self, args_span: Span) -> ErrorGuaranteed {
457        self.emit_err(AttributeParseError {
458            span: args_span,
459            attr_span: self.attr_span,
460            template: self.template.clone(),
461            attribute: self.attr_path.clone(),
462            reason: AttributeParseErrorReason::ExpectedNoArgs,
463            attr_style: self.attr_style,
464        })
465    }
466
467    /// emit an error that a `name` was expected here
468    pub(crate) fn expected_identifier(&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::ExpectedIdentifier,
475            attr_style: self.attr_style,
476        })
477    }
478
479    /// emit an error that a `name = value` pair was expected at this span. The symbol can be given for
480    /// a nicer error message talking about the specific name that was found lacking a value.
481    pub(crate) fn expected_name_value(&self, span: Span, name: Option<Symbol>) -> ErrorGuaranteed {
482        self.emit_err(AttributeParseError {
483            span,
484            attr_span: self.attr_span,
485            template: self.template.clone(),
486            attribute: self.attr_path.clone(),
487            reason: AttributeParseErrorReason::ExpectedNameValue(name),
488            attr_style: self.attr_style,
489        })
490    }
491
492    /// emit an error that a `name = value` pair was found where that name was already seen.
493    pub(crate) fn duplicate_key(&self, span: Span, key: Symbol) -> ErrorGuaranteed {
494        self.emit_err(AttributeParseError {
495            span,
496            attr_span: self.attr_span,
497            template: self.template.clone(),
498            attribute: self.attr_path.clone(),
499            reason: AttributeParseErrorReason::DuplicateKey(key),
500            attr_style: self.attr_style,
501        })
502    }
503
504    /// an error that should be emitted when a [`MetaItemOrLitParser`](crate::parser::MetaItemOrLitParser)
505    /// was expected *not* to be a literal, but instead a meta item.
506    pub(crate) fn unexpected_literal(&self, span: Span) -> ErrorGuaranteed {
507        self.emit_err(AttributeParseError {
508            span,
509            attr_span: self.attr_span,
510            template: self.template.clone(),
511            attribute: self.attr_path.clone(),
512            reason: AttributeParseErrorReason::UnexpectedLiteral,
513            attr_style: self.attr_style,
514        })
515    }
516
517    pub(crate) fn expected_single_argument(&self, span: Span) -> ErrorGuaranteed {
518        self.emit_err(AttributeParseError {
519            span,
520            attr_span: self.attr_span,
521            template: self.template.clone(),
522            attribute: self.attr_path.clone(),
523            reason: AttributeParseErrorReason::ExpectedSingleArgument,
524            attr_style: self.attr_style,
525        })
526    }
527
528    pub(crate) fn expected_at_least_one_argument(&self, span: Span) -> ErrorGuaranteed {
529        self.emit_err(AttributeParseError {
530            span,
531            attr_span: self.attr_span,
532            template: self.template.clone(),
533            attribute: self.attr_path.clone(),
534            reason: AttributeParseErrorReason::ExpectedAtLeastOneArgument,
535            attr_style: self.attr_style,
536        })
537    }
538
539    /// produces an error along the lines of `expected one of [foo, meow]`
540    pub(crate) fn expected_specific_argument(
541        &self,
542        span: Span,
543        possibilities: &[Symbol],
544    ) -> ErrorGuaranteed {
545        self.emit_err(AttributeParseError {
546            span,
547            attr_span: self.attr_span,
548            template: self.template.clone(),
549            attribute: self.attr_path.clone(),
550            reason: AttributeParseErrorReason::ExpectedSpecificArgument {
551                possibilities,
552                strings: false,
553                list: false,
554            },
555            attr_style: self.attr_style,
556        })
557    }
558
559    /// produces an error along the lines of `expected one of [foo, meow] as an argument`.
560    /// i.e. slightly different wording to [`expected_specific_argument`](Self::expected_specific_argument).
561    pub(crate) fn expected_specific_argument_and_list(
562        &self,
563        span: Span,
564        possibilities: &[Symbol],
565    ) -> ErrorGuaranteed {
566        self.emit_err(AttributeParseError {
567            span,
568            attr_span: self.attr_span,
569            template: self.template.clone(),
570            attribute: self.attr_path.clone(),
571            reason: AttributeParseErrorReason::ExpectedSpecificArgument {
572                possibilities,
573                strings: false,
574                list: true,
575            },
576            attr_style: self.attr_style,
577        })
578    }
579
580    /// produces an error along the lines of `expected one of ["foo", "meow"]`
581    pub(crate) fn expected_specific_argument_strings(
582        &self,
583        span: Span,
584        possibilities: &[Symbol],
585    ) -> ErrorGuaranteed {
586        self.emit_err(AttributeParseError {
587            span,
588            attr_span: self.attr_span,
589            template: self.template.clone(),
590            attribute: self.attr_path.clone(),
591            reason: AttributeParseErrorReason::ExpectedSpecificArgument {
592                possibilities,
593                strings: true,
594                list: false,
595            },
596            attr_style: self.attr_style,
597        })
598    }
599
600    pub(crate) fn warn_empty_attribute(&mut self, span: Span) {
601        let attr_path = self.attr_path.clone();
602        let valid_without_list = self.template.word;
603        self.emit_lint(
604            AttributeLintKind::EmptyAttribute { first_span: span, attr_path, valid_without_list },
605            span,
606        );
607    }
608}
609
610impl<'f, 'sess, S: Stage> Deref for AcceptContext<'f, 'sess, S> {
611    type Target = SharedContext<'f, 'sess, S>;
612
613    fn deref(&self) -> &Self::Target {
614        &self.shared
615    }
616}
617
618impl<'f, 'sess, S: Stage> DerefMut for AcceptContext<'f, 'sess, S> {
619    fn deref_mut(&mut self) -> &mut Self::Target {
620        &mut self.shared
621    }
622}
623
624/// Context given to every attribute parser during finalization.
625///
626/// Gives [`AttributeParser`](crate::attributes::AttributeParser)s enough information to create
627/// errors, for example.
628pub struct SharedContext<'p, 'sess, S: Stage> {
629    /// The parse context, gives access to the session and the
630    /// diagnostics context.
631    pub(crate) cx: &'p mut AttributeParser<'sess, S>,
632    /// The span of the syntactical component this attribute was applied to
633    pub(crate) target_span: Span,
634    /// The id ([`NodeId`] if `S` is `Early`, [`HirId`] if `S` is `Late`) of the syntactical component this attribute was applied to
635    pub(crate) target_id: S::Id,
636
637    pub(crate) emit_lint: &'p mut dyn FnMut(AttributeLint<S::Id>),
638}
639
640/// Context given to every attribute parser during finalization.
641///
642/// Gives [`AttributeParser`](crate::attributes::AttributeParser)s enough information to create
643/// errors, for example.
644pub(crate) struct FinalizeContext<'p, 'sess, S: Stage> {
645    pub(crate) shared: SharedContext<'p, 'sess, S>,
646
647    /// A list of all attribute on this syntax node.
648    ///
649    /// Useful for compatibility checks with other attributes in [`finalize`](crate::attributes::AttributeParser::finalize)
650    ///
651    /// Usually, you should use normal attribute parsing logic instead,
652    /// especially when making a *denylist* of other attributes.
653    pub(crate) all_attrs: &'p [PathParser<'p>],
654}
655
656impl<'p, 'sess: 'p, S: Stage> Deref for FinalizeContext<'p, 'sess, S> {
657    type Target = SharedContext<'p, 'sess, S>;
658
659    fn deref(&self) -> &Self::Target {
660        &self.shared
661    }
662}
663
664impl<'p, 'sess: 'p, S: Stage> DerefMut for FinalizeContext<'p, 'sess, S> {
665    fn deref_mut(&mut self) -> &mut Self::Target {
666        &mut self.shared
667    }
668}
669
670impl<'p, 'sess: 'p, S: Stage> Deref for SharedContext<'p, 'sess, S> {
671    type Target = AttributeParser<'sess, S>;
672
673    fn deref(&self) -> &Self::Target {
674        self.cx
675    }
676}
677
678impl<'p, 'sess: 'p, S: Stage> DerefMut for SharedContext<'p, 'sess, S> {
679    fn deref_mut(&mut self) -> &mut Self::Target {
680        self.cx
681    }
682}
683
684#[derive(PartialEq, Clone, Copy, Debug)]
685pub enum OmitDoc {
686    Lower,
687    Skip,
688}
689
690#[derive(Copy, Clone, Debug)]
691pub enum ShouldEmit {
692    /// The operations will emit errors, and lints, and errors are fatal.
693    ///
694    /// Only relevant when early parsing, in late parsing equivalent to `ErrorsAndLints`.
695    /// Late parsing is never fatal, and instead tries to emit as many diagnostics as possible.
696    EarlyFatal { also_emit_lints: bool },
697    /// The operation will emit errors and lints.
698    /// This is usually what you need.
699    ErrorsAndLints,
700    /// The operation will emit *not* errors and lints.
701    /// Use this if you are *sure* that this operation will be called at a different time with `ShouldEmit::ErrorsAndLints`.
702    Nothing,
703}
704
705impl ShouldEmit {
706    pub(crate) fn emit_err(&self, diag: Diag<'_>) -> ErrorGuaranteed {
707        match self {
708            ShouldEmit::EarlyFatal { .. } if diag.level() == Level::DelayedBug => diag.emit(),
709            ShouldEmit::EarlyFatal { .. } => diag.upgrade_to_fatal().emit(),
710            ShouldEmit::ErrorsAndLints => diag.emit(),
711            ShouldEmit::Nothing => diag.delay_as_bug(),
712        }
713    }
714}