Skip to main content

rustc_attr_parsing/
interface.rs

1//! API for other crates to parse attributes themselves.
2use std::convert::identity;
3#[cfg(debug_assertions)]
4use std::sync::atomic::{AtomicBool, Ordering};
5
6use rustc_ast::token::DocFragmentKind;
7use rustc_ast::{self as ast, AttrStyle, CRATE_NODE_ID, NodeId, Safety};
8use rustc_attr_ir::target::{AstTarget, Target};
9use rustc_attr_ir::{AttrArgs, AttrItem, AttrPath, Attribute, AttributeKind, HashIgnoredAttrId};
10use rustc_data_structures::sync::{DynSend, DynSync};
11use rustc_errors::{Diag, DiagCtxtHandle, Diagnostic, Level, MultiSpan};
12use rustc_feature::{BUILTIN_ATTRIBUTE_SET, Features};
13use rustc_lint_defs::Reflectiveness::NonReflective;
14use rustc_lint_defs::{LintId, RegisteredTools, ToolOptions};
15use rustc_session::Session;
16use rustc_span::{DUMMY_SP, ErrorGuaranteed, Ident, Span, Symbol, sym};
17
18use crate::attributes::AttributeSafety;
19use crate::attributes::doc_comment::target_check_doc_comment;
20use crate::context::{
21    ATTRIBUTE_PARSERS, AcceptContext, FinalizeCheckContext, FinalizeCheckFn, FinalizeContext,
22    FinalizeFn, FinalizeOutput, SharedContext,
23};
24use crate::diagnostics::ParsedDescription;
25use crate::generated::GeneratedAttrState;
26use crate::parser::{AllowExprMetavar, ArgParser, PathParser, RefPathParser};
27use crate::synthetic::SyntheticAttrState;
28use crate::validate_attr::parse_meta;
29use crate::{AttributeTemplate, ShouldEmit, diagnostics};
30
31pub struct EmitAttribute(
32    pub  Box<
33        dyn for<'a> FnOnce(DiagCtxtHandle<'a>, Level, &Session) -> Diag<'a>
34            + DynSend
35            + DynSync
36            + 'static,
37    >,
38);
39
40/// Context created once, for example as part of the ast lowering
41/// context, through which all attributes can be lowered.
42pub struct AttributeParser<'sess> {
43    pub(crate) attr_tools: Option<&'sess RegisteredTools>,
44    pub(crate) features: Option<&'sess Features>,
45    pub(crate) sess: &'sess Session,
46    pub(crate) should_emit: ShouldEmit,
47
48    /// *Only* parse attributes that passes this filter.
49    ///
50    /// Used in cases where we want the lowering infrastructure for parse just limited attributes.
51    pub(crate) parse_filter: Option<&'sess dyn Fn(&ast::Attribute) -> bool>,
52}
53
54impl<'sess> AttributeParser<'sess> {
55    /// This method allows you to parse attributes *before* you have access to features or tools.
56    /// One example where this is necessary, is to parse `feature` attributes themselves for
57    /// example.
58    ///
59    /// Try to use this as little as possible. Attributes *should* be lowered during
60    /// `rustc_ast_lowering`. Some attributes require access to features to parse, which would
61    /// crash if you tried to do so through [`parse_limited`](Self::parse_limited).
62    ///
63    /// To make sure use is limited, supply a filter. Only attributes that passes the filter are
64    /// picked out of the list of instructions and parsed. Those are returned.
65    ///
66    /// No diagnostics will be emitted when parsing limited. Lints are not emitted at all, while
67    /// errors will be emitted as a delayed bugs. in other words, we *expect* attributes parsed
68    /// with `parse_limited` to be reparsed later during ast lowering where we *do* emit the errors
69    ///
70    /// Due to this function not taking in `RegisteredTools`, *do not* use this for parsing any lint attributes
71    pub fn parse_limited(
72        sess: &'sess Session,
73        attrs: &[ast::Attribute],
74        parse_filter: &dyn Fn(&ast::Attribute) -> bool,
75    ) -> Option<Attribute> {
76        Self::parse_limited_should_emit(
77            sess,
78            attrs,
79            parse_filter,
80            // Because we're not emitting warnings/errors, the target should not matter
81            DUMMY_SP,
82            None,
83            ShouldEmit::Nothing,
84        )
85    }
86
87    /// This does the same as `parse_limited`, except that it takes a fixed symbol instead of a
88    /// filter.
89    pub fn parse_limited_sym(
90        sess: &'sess Session,
91        attrs: &[ast::Attribute],
92        sym: &'static [Symbol],
93    ) -> Option<Attribute> {
94        Self::parse_limited(sess, attrs, &|attr| attr.path_matches(sym))
95    }
96
97    /// This does the same as `parse_limited`, except it has a `should_emit` parameter which allows it to emit errors.
98    /// Usually you want `parse_limited`, which emits no errors.
99    ///
100    /// Due to this function not taking in `RegisteredTools`, *do not* use this for parsing any lint attributes
101    pub fn parse_limited_should_emit(
102        sess: &'sess Session,
103        attrs: &[ast::Attribute],
104        parse_filter: &dyn Fn(&ast::Attribute) -> bool,
105        target_span: Span,
106        features: Option<&'sess Features>,
107        should_emit: ShouldEmit,
108    ) -> Option<Attribute> {
109        let mut parsed = Self::parse_limited_all(
110            sess,
111            attrs,
112            Some(parse_filter),
113            AstTarget::None(Target::Crate),
114            target_span,
115            CRATE_NODE_ID,
116            features,
117            should_emit,
118            None,
119        );
120        if !(parsed.len() <= 1) {
    ::core::panicking::panic("assertion failed: parsed.len() <= 1")
};assert!(parsed.len() <= 1);
121        parsed.pop()
122    }
123
124    /// This does the same as `parse_limited_should_emit`, except that it takes a fixed symbol
125    /// instead of a filter.
126    pub fn parse_limited_sym_should_emit(
127        sess: &'sess Session,
128        attrs: &[ast::Attribute],
129        sym: &'static [Symbol],
130        target_span: Span,
131        features: Option<&'sess Features>,
132        should_emit: ShouldEmit,
133    ) -> Option<Attribute> {
134        Self::parse_limited_should_emit(
135            sess,
136            attrs,
137            &|attr| attr.path_matches(sym),
138            target_span,
139            features,
140            should_emit,
141        )
142    }
143
144    /// This method allows you to parse a list of attributes *before* `rustc_ast_lowering`.
145    /// This can be used for attributes that would be removed before `rustc_ast_lowering`, such as attributes on macro calls.
146    ///
147    /// Try to use this as little as possible. Attributes *should* be lowered during
148    /// `rustc_ast_lowering`. Some attributes require access to features to parse, which would
149    /// crash if you tried to do so through [`parse_limited_all`](Self::parse_limited_all).
150    /// Therefore, if `parse_filter` is None, then features *must* be provided.
151    pub fn parse_limited_all(
152        sess: &'sess Session,
153        attrs: &[ast::Attribute],
154        parse_filter: Option<&dyn Fn(&ast::Attribute) -> bool>,
155        ast_target: AstTarget<'_>,
156        target_span: Span,
157        target_node_id: NodeId,
158        features: Option<&'sess Features>,
159        should_emit: ShouldEmit,
160        attr_tools: Option<&'sess RegisteredTools>,
161    ) -> Vec<Attribute> {
162        let mut p = AttributeParser { features, attr_tools, parse_filter, sess, should_emit };
163        p.parse_attribute_list(
164            attrs,
165            target_span,
166            ast_target,
167            std::convert::identity,
168            |lint_id, span, kind| {
169                sess.psess.dyn_buffer_lint_sess(lint_id.lint, span, target_node_id, kind.0)
170            },
171        )
172    }
173
174    /// This method parses a single attribute, using `parse_fn`.
175    /// This is useful if you already know what exact attribute this is, and want to parse it.
176    pub fn parse_single<T>(
177        sess: &'sess Session,
178        attr: &ast::Attribute,
179        target_span: Span,
180        target_node_id: NodeId,
181        ast_target: AstTarget<'_>,
182        features: Option<&'sess Features>,
183        emit_errors: ShouldEmit,
184        parse_fn: fn(cx: &mut AcceptContext<'_, '_>, item: &ArgParser) -> Option<T>,
185        template: &AttributeTemplate,
186        allow_expr_metavar: AllowExprMetavar,
187        expected_safety: AttributeSafety,
188    ) -> Option<T> {
189        let attr_item = attr.get_normal_item();
190        let parts = attr_item.path.segments.iter().map(|seg| seg.ident.name).collect::<Vec<_>>();
191
192        let path = AttrPath::from_ast(&attr_item.path, identity);
193        let args = ArgParser::from_attr_args(
194            &attr_item.args,
195            &parts,
196            &sess.psess,
197            emit_errors,
198            allow_expr_metavar,
199        )?;
200        Self::parse_single_args(
201            sess,
202            attr.span,
203            attr_item.span,
204            attr.style,
205            path,
206            Some(attr_item.unsafety),
207            expected_safety,
208            ParsedDescription::Attribute,
209            target_span,
210            target_node_id,
211            ast_target,
212            features,
213            emit_errors,
214            &args,
215            parse_fn,
216            template,
217        )
218    }
219
220    /// This method is equivalent to `parse_single`, but parses arguments using `parse_fn` using manually created `args`.
221    /// This is useful when you want to parse other things than attributes using attribute parsers.
222    pub fn parse_single_args<T, I>(
223        sess: &'sess Session,
224        attr_span: Span,
225        inner_span: Span,
226        attr_style: AttrStyle,
227        attr_path: AttrPath,
228        attr_safety: Option<Safety>,
229        expected_safety: AttributeSafety,
230        parsed_description: ParsedDescription,
231        target_span: Span,
232        target_node_id: NodeId,
233        ast_target: AstTarget<'_>,
234        features: Option<&'sess Features>,
235        should_emit: ShouldEmit,
236        args: &I,
237        parse_fn: fn(cx: &mut AcceptContext<'_, '_>, item: &I) -> T,
238        template: &AttributeTemplate,
239    ) -> T {
240        let mut parser = Self { features, attr_tools: None, parse_filter: None, sess, should_emit };
241        let mut emit_lint = |lint_id: LintId, span: MultiSpan, kind: EmitAttribute| {
242            sess.psess.dyn_buffer_lint_sess(lint_id.lint, span, target_node_id, kind.0)
243        };
244        if let Some(safety) = attr_safety {
245            parser.check_attribute_safety(
246                &attr_path,
247                inner_span,
248                safety,
249                expected_safety,
250                &mut emit_lint,
251            );
252        }
253        let mut cx: AcceptContext<'_, 'sess> = AcceptContext {
254            shared: SharedContext {
255                cx: &mut parser,
256                target_span,
257                target: Target::from_ast_target(&ast_target),
258                emit_lint: &mut emit_lint,
259                #[cfg(debug_assertions)]
260                has_lint_been_emitted: AtomicBool::new(false),
261                ast_target,
262            },
263            attr_span,
264            inner_span,
265            attr_style,
266            parsed_description,
267            template,
268            attr_safety: attr_safety.unwrap_or(Safety::Default),
269            attr_path,
270            #[cfg(debug_assertions)]
271            has_target_been_checked: false,
272            attr_id: None,
273        };
274        parse_fn(&mut cx, args)
275    }
276}
277
278impl<'sess> AttributeParser<'sess> {
279    pub fn new(
280        sess: &'sess Session,
281        features: &'sess Features,
282        attr_tools: &'sess RegisteredTools,
283        should_emit: ShouldEmit,
284    ) -> Self {
285        Self {
286            features: Some(features),
287            attr_tools: Some(attr_tools),
288            parse_filter: None,
289            sess,
290            should_emit,
291        }
292    }
293
294    pub(crate) fn sess(&self) -> &'sess Session {
295        self.sess
296    }
297
298    #[track_caller]
299    pub(crate) fn features(&self) -> &'sess Features {
300        self.features.expect("features not available at this point in the compiler")
301    }
302
303    pub(crate) fn features_option(&self) -> Option<&'sess Features> {
304        self.features
305    }
306
307    pub(crate) fn dcx(&self) -> DiagCtxtHandle<'sess> {
308        self.sess().dcx()
309    }
310
311    #[track_caller]
312    pub(crate) fn emit_err(&self, diag: impl for<'x> Diagnostic<'x>) -> ErrorGuaranteed {
313        self.should_emit.emit_err(self.sess.dcx().create_err(diag))
314    }
315
316    /// Parse a list of attributes.
317    ///
318    /// `target_span` is the span of the thing this list of attributes is applied to.
319    pub fn parse_attribute_list(
320        &mut self,
321        attrs: &[ast::Attribute],
322        target_span: Span,
323        ast_target: AstTarget<'_>,
324        lower_span: impl Copy + Fn(Span) -> Span,
325        mut emit_lint: impl FnMut(LintId, MultiSpan, EmitAttribute),
326    ) -> Vec<Attribute> {
327        let mut attributes = Vec::new();
328        let mut attr_paths: Vec<RefPathParser<'_>> = Vec::new();
329        let mut synthetic_attr_state = SyntheticAttrState::default();
330        let mut generated_attr_state = GeneratedAttrState::default();
331        let mut has_target_checked_doc_comment = false;
332
333        let mut finalizers: Vec<FinalizeFn> = Vec::with_capacity(attrs.len());
334
335        for attr in attrs {
336            // If we're only looking for a single attribute, skip all the ones we don't care about.
337            if let Some(filter) = self.parse_filter {
338                if !filter(attr) {
339                    continue;
340                }
341            }
342
343            let attr_span = lower_span(attr.span);
344            match &attr.kind {
345                ast::AttrKind::DocComment(comment_kind, symbol) => {
346                    target_check_doc_comment(
347                        &self,
348                        attr,
349                        &ast_target,
350                        target_span,
351                        &mut emit_lint,
352                        &mut has_target_checked_doc_comment,
353                    );
354                    attributes.push(Attribute::Parsed(AttributeKind::DocComment {
355                        style: attr.style,
356                        kind: DocFragmentKind::Sugared(*comment_kind),
357                        span: attr_span,
358                        comment: *symbol,
359                    }));
360                }
361                ast::AttrKind::Synthetic(synthetic) => {
362                    synthetic_attr_state.accept_synthetic_attr(attr_span, lower_span, synthetic);
363                }
364                ast::AttrKind::Generated(generated) => {
365                    generated_attr_state.accept_generated_attr(attr_span, generated)
366                }
367                ast::AttrKind::Normal(n) => {
368                    attr_paths.push(PathParser(&n.item.path));
369                    let attr_path = AttrPath::from_ast(&n.item.path, lower_span);
370                    let parts =
371                        n.item.path.segments.iter().map(|seg| seg.ident.name).collect::<Vec<_>>();
372                    let inner_span = lower_span(n.item.span);
373
374                    let accepter = ATTRIBUTE_PARSERS.accepters.get(parts.as_slice());
375                    if let Some(accept) = accepter {
376                        self.check_attribute_safety(
377                            &attr_path,
378                            inner_span,
379                            n.item.unsafety,
380                            accept.safety,
381                            &mut emit_lint,
382                        );
383                        self.check_attribute_stability(&attr_path, attr_span, accept.stability);
384                        if let [part] = parts.as_slice() {
385                            if true {
    if !BUILTIN_ATTRIBUTE_SET.contains(part) {
        ::core::panicking::panic("assertion failed: BUILTIN_ATTRIBUTE_SET.contains(part)")
    };
};debug_assert!(BUILTIN_ATTRIBUTE_SET.contains(part));
386                        }
387
388                        let Some(args) = ArgParser::from_attr_args(
389                            &n.item.args,
390                            &parts,
391                            &self.sess.psess,
392                            self.should_emit,
393                            AllowExprMetavar::No,
394                        ) else {
395                            continue;
396                        };
397
398                        // Special-case handling for `#[doc = "..."]`: if we go through with
399                        // `DocParser`, the order of doc comments will be messed up because `///`
400                        // doc comments are added into `attributes` whereas attributes parsed with
401                        // `DocParser` are added into `parsed_attributes` which are then appended
402                        // to `attributes`. So if you have:
403                        //
404                        // /// bla
405                        // #[doc = "a"]
406                        // /// blob
407                        //
408                        // You would get:
409                        //
410                        // bla
411                        // blob
412                        // a
413                        if attr.has_name(sym::doc)
414                            && let ArgParser::NameValue(nv) = &args
415                            // If not a string key/value, it should emit an error, but to make
416                            // things simpler, it's handled in `DocParser` because it's simpler to
417                            // emit an error with `AcceptContext`.
418                            && let Some(comment) = nv.value_as_str()
419                        {
420                            target_check_doc_comment(
421                                &self,
422                                attr,
423                                &ast_target,
424                                target_span,
425                                &mut emit_lint,
426                                &mut false, // always linted
427                            );
428                            attributes.push(Attribute::Parsed(AttributeKind::DocComment {
429                                style: attr.style,
430                                kind: DocFragmentKind::Raw(nv.value_span),
431                                span: attr_span,
432                                comment,
433                            }));
434                            continue;
435                        }
436
437                        let mut cx: AcceptContext<'_, 'sess> = AcceptContext {
438                            shared: SharedContext {
439                                cx: self,
440                                target_span,
441                                target: Target::from_ast_target(&ast_target),
442                                emit_lint: &mut emit_lint,
443                                #[cfg(debug_assertions)]
444                                has_lint_been_emitted: AtomicBool::new(false),
445                                ast_target,
446                            },
447                            attr_span,
448                            inner_span,
449                            attr_style: attr.style,
450                            parsed_description: ParsedDescription::Attribute,
451                            template: &accept.template,
452                            attr_safety: n.item.unsafety,
453                            attr_path: attr_path.clone(),
454                            #[cfg(debug_assertions)]
455                            has_target_been_checked: false,
456                            attr_id: Some(HashIgnoredAttrId { attr_id: attr.id }),
457                        };
458
459                        (accept.accept_fn)(&mut cx, &args);
460                        finalizers.push(accept.finalizer);
461
462                        Self::check_target(&accept.allowed_targets, "", &mut cx);
463                        #[cfg(debug_assertions)]
464                        if !cx.shared.has_lint_been_emitted.load(Ordering::Relaxed) {
465                            cx.shared.cx.check_args_used(attr, &args)
466                        }
467                    } else if let [sym::diagnostic, _unknown, ..] = &*parts {
468                        self.unknown_diagnostic_attr(&n.item.path.segments[1], &mut emit_lint);
469                    } else if let [sym::lint, unknown, ..] = &*parts {
470                        // Avoid cascading errors. If the `lint` tool has not been registered,
471                        // we could be here in the `#[lint::attribute_macro] not found` case,
472                        // which recovers with a `NonMacroAttr` res.
473                        if let Some(tools) = self.attr_tools
474                            && tools.iter().any(|(i, _)| i.name == sym::lint)
475                        {
476                            self.emit_err(diagnostics::UnknownLintHelper {
477                                span: n.item.span,
478                                unknown: *unknown,
479                            });
480                        } else {
481                            self.dcx().span_delayed_bug(
482                                n.item.span,
483                                "encountered `lint` tool attribute but error not reported",
484                            );
485                        }
486                    } else {
487                        let attr = AttrItem {
488                            path: attr_path.clone(),
489                            args: self.lower_attr_args(&n.item.args, lower_span),
490                            style: attr.style,
491                            span: attr_span,
492                        };
493
494                        self.check_attribute_safety(
495                            &attr_path,
496                            inner_span,
497                            n.item.unsafety,
498                            AttributeSafety::Normal,
499                            &mut emit_lint,
500                        );
501
502                        if !#[allow(non_exhaustive_omitted_patterns)] match self.should_emit {
    ShouldEmit::Nothing => true,
    _ => false,
}matches!(self.should_emit, ShouldEmit::Nothing)
503                            && Target::from_ast_target(&ast_target) == Target::Crate
504                        {
505                            self.check_invalid_crate_level_attr_item(&attr, inner_span);
506                        }
507
508                        let attr = match attr_path.segments.len() {
509                            0 => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("no path for {0:?}", attr)));
}unreachable!("no path for {attr:?}"),
510                            1 => Attribute::DeriveHelper(Box::new(attr)),
511                            _ => {
512                                if let Some(tools) = self.attr_tools
513                                    && let Some(opts) =
514                                        tools.get(&Ident::with_dummy_span(attr_path.segments[0]))
515                                {
516                                    Attribute::Tool { item: Box::new(attr), opts: opts.clone() }
517                                } else {
518                                    Attribute::Tool {
519                                        item: Box::new(attr),
520                                        opts: ToolOptions { reflectiveness: NonReflective },
521                                    }
522                                }
523                            }
524                        };
525
526                        attributes.push(attr);
527                    };
528
529                    if accepter.is_none()
530                        && let rustc_ast::AttrArgs::Eq { .. } = n.item.args
531                    {
532                        // All key-value attributes are restricted to meta-item syntax.
533                        match parse_meta(&self.sess.psess, &attr) {
534                            Ok(_) => {}
535                            Err(err) => {
536                                err.emit();
537                            }
538                        }
539                    }
540                }
541            }
542        }
543
544        synthetic_attr_state.finalize_synthetic_attrs(&mut attributes);
545        generated_attr_state.finalize_generated_attrs(&mut attributes);
546
547        // First, run all finalizers to produce the parsed attributes. Cross-attribute
548        // checks that need to inspect the fully parsed attributes are deferred until all
549        // finalizers have run (see below), since the parsed attributes are not yet all
550        // available here.
551        let mut deferred_checks: Vec<(FinalizeCheckFn, Span)> = Vec::new();
552        for f in &finalizers {
553            let FinalizeOutput { attr, deferred_check } = f(&mut FinalizeContext {
554                shared: SharedContext {
555                    cx: self,
556                    target_span,
557                    target: Target::from_ast_target(&ast_target),
558                    ast_target,
559                    emit_lint: &mut emit_lint,
560                    #[cfg(debug_assertions)]
561                    has_lint_been_emitted: AtomicBool::new(false),
562                },
563                all_attrs: &attr_paths,
564            });
565            if let Some(attr) = attr {
566                attributes.push(Attribute::Parsed(attr));
567            }
568            if let Some(deferred_check) = deferred_check {
569                deferred_checks.push(deferred_check);
570            }
571        }
572
573        // Now that all attributes have been parsed, run the deferred checks. These can
574        // inspect the fully parsed attributes via `FinalizeCheckContext::parsed_attrs`.
575        if !#[allow(non_exhaustive_omitted_patterns)] match self.should_emit {
    ShouldEmit::Nothing => true,
    _ => false,
}matches!(self.should_emit, ShouldEmit::Nothing) {
576            for (check, attr_span) in deferred_checks {
577                check(
578                    &mut FinalizeCheckContext {
579                        shared: SharedContext {
580                            cx: self,
581                            target_span,
582                            target: Target::from_ast_target(&ast_target),
583                            ast_target,
584                            emit_lint: &mut emit_lint,
585                            #[cfg(debug_assertions)]
586                            has_lint_been_emitted: AtomicBool::new(false),
587                        },
588                        all_attrs: &attr_paths,
589                        parsed_attrs: &attributes,
590                    },
591                    attr_span,
592                );
593            }
594        }
595
596        if !#[allow(non_exhaustive_omitted_patterns)] match self.should_emit {
    ShouldEmit::Nothing => true,
    _ => false,
}matches!(self.should_emit, ShouldEmit::Nothing)
597            && Target::from_ast_target(&ast_target) == Target::WherePredicate
598        {
599            self.check_invalid_where_predicate_attrs(attributes.iter());
600        }
601
602        attributes
603    }
604
605    #[cfg(debug_assertions)]
606    /// Checks whether all `ArgParser`s were observed by an attribute parser at least once
607    /// This check exists because otherwise it is too easy to accidentally ignore the arguments of an attribute
608    fn check_args_used(&self, attr: &ast::Attribute, args: &ArgParser) {
609        if let ArgParser::List(items) = args {
610            for item in items.mixed() {
611                if let crate::parser::MetaItemOrLitParser::MetaItemParser(item) = item {
612                    if !item.are_args_checked() {
613                        self.dcx().span_delayed_bug(
614                            item.span(),
615                            "attribute args were not properly checked",
616                        );
617                        return;
618                    }
619                    self.check_args_used(attr, item.args());
620                }
621            }
622        }
623    }
624
625    /// Returns whether there is a parser for an attribute with this name
626    pub fn is_parsed_attribute(path: &[Symbol]) -> bool {
627        /// The list of attributes that are parsed attributes,
628        /// even though they don't have a parser in `Late::parsers()`
629        const SPECIAL_ATTRIBUTES: &[&[Symbol]] = &[
630            // Cfg attrs are removed after being converted into synthetic attrs and don't need to
631            // be in the parser list.
632            &[sym::cfg],
633            &[sym::cfg_attr],
634        ];
635
636        ATTRIBUTE_PARSERS.accepters.contains_key(path) || SPECIAL_ATTRIBUTES.contains(&path)
637    }
638
639    fn lower_attr_args(&self, args: &ast::AttrArgs, lower_span: impl Fn(Span) -> Span) -> AttrArgs {
640        match args {
641            ast::AttrArgs::Empty => AttrArgs::Empty,
642            ast::AttrArgs::Delimited(args) => AttrArgs::Delimited(args.clone()),
643            // This is an inert key-value attribute - it will never be visible to macros
644            // after it gets lowered to HIR. Therefore, we can extract literals to handle
645            // nonterminals in `#[doc]` (e.g. `#[doc = $e]`).
646            ast::AttrArgs::Eq { eq_span, expr } => {
647                // We perform error handling elsewhere, not here, so we only delay bugs.
648
649                if let Err(diag) =
650                    crate::validate_attr::check_attrs_on_rhs_expr(&self.sess.psess, expr)
651                {
652                    diag.delay_as_bug();
653                }
654
655                let lit = if let ast::ExprKind::Lit(token_lit) = expr.kind
656                    && let Ok(lit) =
657                        ast::MetaItemLit::from_token_lit(token_lit, lower_span(expr.span))
658                {
659                    lit
660                } else {
661                    let span = args.span().unwrap_or(DUMMY_SP);
662                    let guar =
663                        self.dcx().span_delayed_bug(span, "non-literal expr in key-value attr");
664                    ast::MetaItemLit {
665                        symbol: sym::dummy,
666                        suffix: None,
667                        kind: ast::LitKind::Err(guar),
668                        span: DUMMY_SP,
669                    }
670                };
671                AttrArgs::Eq { eq_span: lower_span(*eq_span), expr: lit }
672            }
673        }
674    }
675}