Skip to main content

rustc_attr_parsing/
parser.rs

1//! Parsing of attribute arguments.
2//!
3//! Depending on the attribute parser, an [`ArgParser`] can be used to parse the arguments given to
4//! an attribute. See its documentation for more information.
5//!
6//! This is in essence an (improved) duplicate of `rustc_ast/attr/mod.rs`.
7//! That module is intended to be deleted in its entirety.
8//!
9//! FIXME(jdonszelmann): delete `rustc_ast/attr/mod.rs`
10
11use std::borrow::Borrow;
12use std::fmt::{Debug, Display};
13#[cfg(debug_assertions)]
14use std::sync::atomic::{AtomicBool, Ordering};
15
16use rustc_ast::token::{self, Delimiter, MetaVarKind};
17use rustc_ast::tokenstream::TokenStream;
18use rustc_ast::{
19    AttrArgs, Expr, ExprKind, LitKind, MetaItemLit, Path, PathSegment, StmtKind, UnOp,
20};
21use rustc_ast_pretty::pprust;
22use rustc_errors::{Applicability, Diag, PResult};
23use rustc_hir::{self as hir, AttrPath};
24use rustc_parse::exp;
25use rustc_parse::parser::{ForceCollect, Parser, PathStyle, Recovery, token_descr};
26use rustc_session::diagnostics::create_lit_error;
27use rustc_session::parse::ParseSess;
28use rustc_span::{Ident, Span, Symbol, sym};
29use thin_vec::ThinVec;
30
31use crate::ShouldEmit;
32use crate::session_diagnostics::{
33    AdditionalCommaSuggestion, ExpectedComma, InvalidMetaItem, InvalidMetaItemQuoteIdentSugg,
34    InvalidMetaItemRemoveNegSugg, MetaBadDelim, MetaBadDelimSugg, SuffixedLiteralInAttribute,
35};
36
37#[derive(#[automatically_derived]
impl<P: ::core::clone::Clone + Borrow<Path>> ::core::clone::Clone for
    PathParser<P> {
    #[inline]
    fn clone(&self) -> PathParser<P> {
        PathParser(::core::clone::Clone::clone(&self.0))
    }
}Clone, #[automatically_derived]
impl<P: ::core::fmt::Debug + Borrow<Path>> ::core::fmt::Debug for
    PathParser<P> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_tuple_field1_finish(f, "PathParser",
            &&self.0)
    }
}Debug)]
38pub struct PathParser<P: Borrow<Path>>(pub P);
39
40pub type OwnedPathParser = PathParser<Path>;
41pub type RefPathParser<'p> = PathParser<&'p Path>;
42
43impl<P: Borrow<Path>> PathParser<P> {
44    pub fn get_attribute_path(&self) -> hir::AttrPath {
45        AttrPath {
46            segments: self.segments().map(|s| s.name).collect::<Vec<_>>().into_boxed_slice(),
47            span: self.span(),
48        }
49    }
50
51    pub fn segments(&self) -> impl Iterator<Item = &Ident> {
52        self.0.borrow().segments.iter().map(|seg| &seg.ident)
53    }
54
55    pub fn span(&self) -> Span {
56        self.0.borrow().span
57    }
58
59    pub fn len(&self) -> usize {
60        self.0.borrow().segments.len()
61    }
62
63    pub fn segments_is(&self, segments: &[Symbol]) -> bool {
64        self.segments().map(|segment| &segment.name).eq(segments)
65    }
66
67    pub fn word(&self) -> Option<Ident> {
68        (self.len() == 1).then(|| **self.segments().next().as_ref().unwrap())
69    }
70
71    pub fn word_sym(&self) -> Option<Symbol> {
72        self.word().map(|ident| ident.name)
73    }
74
75    /// Asserts that this `MetaItem` is some specific word.
76    ///
77    /// See [`word`](Self::word) for examples of what a word is.
78    pub fn word_is(&self, sym: Symbol) -> bool {
79        self.word().is_some_and(|i| i.name == sym)
80    }
81
82    /// Checks whether the first segments match the givens.
83    ///
84    /// Unlike [`segments_is`](Self::segments_is),
85    /// `self` may contain more segments than the number matched  against.
86    pub fn starts_with(&self, segments: &[Symbol]) -> bool {
87        segments.len() < self.len() && self.segments().zip(segments).all(|(a, b)| a.name == *b)
88    }
89}
90
91impl<P: Borrow<Path>> Display for PathParser<P> {
92    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
93        f.write_fmt(format_args!("{0}", pprust::path_to_string(self.0.borrow())))write!(f, "{}", pprust::path_to_string(self.0.borrow()))
94    }
95}
96
97/// Used for parsing attribute arguments.
98///
99/// See also [`AttributeDiagnosticContext`], which is the preferred interface for issuing argument
100/// parsing related diagnostics.
101///
102/// [`AttributeDiagnosticContext`]: crate::context::AttributeDiagnosticContext
103#[derive(#[automatically_derived]
impl ::core::fmt::Debug for ArgParser {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            ArgParser::NoArgs =>
                ::core::fmt::Formatter::write_str(f, "NoArgs"),
            ArgParser::List(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "List",
                    &__self_0),
            ArgParser::NameValue(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "NameValue", &__self_0),
        }
    }
}Debug)]
104#[must_use]
105pub enum ArgParser {
106    NoArgs,
107    List(MetaItemListParser),
108    NameValue(NameValueParser),
109}
110
111impl ArgParser {
112    pub fn span(&self) -> Option<Span> {
113        match self {
114            Self::NoArgs => None,
115            Self::List(l) => Some(l.span),
116            Self::NameValue(n) => Some(n.value_span.with_lo(n.eq_span.lo())),
117        }
118    }
119
120    pub fn from_attr_args<'sess>(
121        value: &AttrArgs,
122        parts: &[Symbol],
123        psess: &'sess ParseSess,
124        should_emit: ShouldEmit,
125        allow_expr_metavar: AllowExprMetavar,
126    ) -> Option<Self> {
127        Some(match value {
128            AttrArgs::Empty => Self::NoArgs,
129            AttrArgs::Delimited(args) => {
130                // Diagnostic attributes can't error if they encounter non meta item syntax.
131                // However, the current syntax for diagnostic attributes is meta item syntax.
132                // Therefore we can substitute with a dummy value on invalid syntax.
133                if #[allow(non_exhaustive_omitted_patterns)] match parts {
    [sym::rustc_dummy] | [sym::diagnostic, ..] => true,
    _ => false,
}matches!(parts, [sym::rustc_dummy] | [sym::diagnostic, ..]) {
134                    match MetaItemListParser::new(
135                        &args.tokens,
136                        args.dspan.entire(),
137                        psess,
138                        ShouldEmit::ErrorsAndLints { recovery: Recovery::Forbidden },
139                        allow_expr_metavar,
140                    ) {
141                        Ok(p) => return Some(ArgParser::List(p)),
142                        Err(e) => {
143                            // We can just dispose of the diagnostic and not bother with a lint,
144                            // because this will look like `#[diagnostic::attr()]` was used. This
145                            // is invalid for all diagnostic attrs, so a lint explaining the proper
146                            // form will be issued later.
147                            e.cancel();
148                            return Some(ArgParser::List(MetaItemListParser {
149                                sub_parsers: ThinVec::new(),
150                                span: args.dspan.entire(),
151                            }));
152                        }
153                    }
154                }
155
156                if args.delim != Delimiter::Parenthesis {
157                    should_emit.emit_err(psess.dcx().create_err(MetaBadDelim {
158                        span: args.dspan.entire(),
159                        sugg: MetaBadDelimSugg { open: args.dspan.open, close: args.dspan.close },
160                    }));
161                    return None;
162                }
163
164                Self::List(
165                    MetaItemListParser::new(
166                        &args.tokens,
167                        args.dspan.entire(),
168                        psess,
169                        should_emit,
170                        allow_expr_metavar,
171                    )
172                    .map_err(|e| should_emit.emit_err(e))
173                    .ok()?,
174                )
175            }
176            AttrArgs::Eq { eq_span, expr } => Self::NameValue(NameValueParser {
177                eq_span: *eq_span,
178                value: expr_to_lit(psess, expr, expr.span, should_emit)
179                    .map_err(|e| should_emit.emit_err(e))
180                    .ok()??,
181                value_span: expr.span,
182            }),
183        })
184    }
185
186    /// Asserts that this `MetaItem` is a list
187    ///
188    /// Some examples:
189    ///
190    /// - `#[allow(clippy::complexity)]`: `(clippy::complexity)` is a list
191    /// - `#[rustfmt::skip::macros(target_macro_name)]`: `(target_macro_name)` is a list
192    pub fn as_list(&self) -> Option<&MetaItemListParser> {
193        match self {
194            Self::List(l) => Some(l),
195            Self::NameValue(_) | Self::NoArgs => None,
196        }
197    }
198
199    /// Asserts that this `MetaItem` is a name-value pair.
200    ///
201    /// Some examples:
202    ///
203    /// - `#[clippy::cyclomatic_complexity = "100"]`: `clippy::cyclomatic_complexity = "100"` is a name value pair,
204    ///   where the name is a path (`clippy::cyclomatic_complexity`). You already checked the path
205    ///   to get an `ArgParser`, so this method will effectively only assert that the `= "100"` is
206    ///   there
207    /// - `#[doc = "hello"]`: `doc = "hello`  is also a name value pair
208    pub fn as_name_value(&self) -> Option<&NameValueParser> {
209        match self {
210            Self::NameValue(n) => Some(n),
211            Self::List(_) | Self::NoArgs => None,
212        }
213    }
214
215    /// Assert that there were no args.
216    /// If there were, get a span to the arguments
217    /// (to pass to [`AttributeDiagnosticContext::expected_no_args`](crate::context::AttributeDiagnosticContext::expected_no_args)).
218    pub fn as_no_args(&self) -> Result<(), Span> {
219        match self {
220            Self::NoArgs => Ok(()),
221            Self::List(args) => Err(args.span),
222            Self::NameValue(args) => Err(args.args_span()),
223        }
224    }
225
226    /// Explicitly ignore the arguments, disarming the arguments-used check
227    pub fn ignore_args(&self) {
228        #[cfg(debug_assertions)]
229        if let ArgParser::List(list) = self {
230            for item in list.mixed() {
231                item.ignore_args();
232            }
233        }
234    }
235}
236
237/// Inside lists, values could be either literals, or more deeply nested meta items.
238/// This enum represents that.
239///
240/// Choose which one you want using the provided methods.
241#[derive(#[automatically_derived]
impl ::core::fmt::Debug for MetaItemOrLitParser {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            MetaItemOrLitParser::MetaItemParser(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "MetaItemParser", &__self_0),
            MetaItemOrLitParser::Lit(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Lit",
                    &__self_0),
        }
    }
}Debug)]
242pub enum MetaItemOrLitParser {
243    MetaItemParser(MetaItemParser),
244    Lit(MetaItemLit),
245}
246
247impl MetaItemOrLitParser {
248    pub fn parse_single<'sess>(
249        parser: &mut Parser<'sess>,
250        should_emit: ShouldEmit,
251        allow_expr_metavar: AllowExprMetavar,
252    ) -> PResult<'sess, MetaItemOrLitParser> {
253        let mut this = MetaItemListParserContext { parser, should_emit, allow_expr_metavar };
254        this.parse_meta_item_inner()
255    }
256
257    pub fn span(&self) -> Span {
258        match self {
259            MetaItemOrLitParser::MetaItemParser(generic_meta_item_parser) => {
260                generic_meta_item_parser.span()
261            }
262            MetaItemOrLitParser::Lit(meta_item_lit) => meta_item_lit.span,
263        }
264    }
265
266    pub fn as_lit(&self) -> Option<&MetaItemLit> {
267        match self {
268            MetaItemOrLitParser::Lit(meta_item_lit) => Some(meta_item_lit),
269            MetaItemOrLitParser::MetaItemParser(_) => None,
270        }
271    }
272
273    pub fn meta_item(&self) -> Option<&MetaItemParser> {
274        match self {
275            MetaItemOrLitParser::MetaItemParser(parser) => Some(parser),
276            MetaItemOrLitParser::Lit(_) => None,
277        }
278    }
279
280    /// Returns some if this `MetaItemOrLitParser` is a `MetaItem` with no arguments
281    pub fn meta_item_no_args(&self) -> Option<&MetaItemParser> {
282        let meta_item = self.meta_item()?;
283        match meta_item.args().as_no_args() {
284            Ok(()) => Some(meta_item),
285            Err(_) => None,
286        }
287    }
288
289    /// Explicitly ignore the arguments, disarming the arguments-used check
290    pub fn ignore_args(&self) {
291        #[cfg(debug_assertions)]
292        match self {
293            MetaItemOrLitParser::MetaItemParser(meta_item) => {
294                meta_item.ignore_args();
295            }
296            MetaItemOrLitParser::Lit(_) => {}
297        }
298    }
299}
300
301/// Utility that deconstructs a `MetaItem` into usable parts.
302///
303/// `MetaItems` are syntactically extremely flexible, but specific attributes want to parse
304/// them in custom, more restricted ways. For common argument shapes, prefer the higher-level
305/// [`AcceptContext::expect_list`](crate::context::AcceptContext::expect_list) and
306/// [`AcceptContext::expect_single`](crate::context::AcceptContext::expect_single) helpers.
307/// Use this struct when parsing a custom restricted syntax.
308///
309/// `MetaItems` consist of some path, and some args. The args could be empty. In other words:
310///
311/// - `name` -> args are empty
312/// - `name(...)` -> args are a [`list`](ArgParser::as_list), which is the bit between the
313///   parentheses
314/// - `name = value`-> arg is [`name_value`](ArgParser::as_name_value), where the argument is the
315///   `= value` part
316///
317/// The syntax of `MetaItems` can be found at <https://doc.rust-lang.org/reference/attributes.html>
318pub struct MetaItemParser {
319    path: OwnedPathParser,
320    args: ArgParser,
321
322    /// Whether the `args` of this meta item have been looked at.
323    /// This is tracked because if the arguments of a `MetaItemParser` are ignored, this is probably a mistake
324    #[cfg(debug_assertions)]
325    args_checked: AtomicBool,
326}
327
328impl Debug for MetaItemParser {
329    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
330        f.debug_struct("MetaItemParser")
331            .field("path", &self.path)
332            .field("args", &self.args)
333            .finish()
334    }
335}
336
337impl MetaItemParser {
338    /// For a single-segment meta item, returns its name; otherwise, returns `None`.
339    pub fn ident(&self) -> Option<Ident> {
340        if let [PathSegment { ident, .. }] = self.path.0.segments[..] { Some(ident) } else { None }
341    }
342
343    pub fn span(&self) -> Span {
344        if let Some(other) = self.args.span() {
345            self.path.borrow().span().with_hi(other.hi())
346        } else {
347            self.path.borrow().span()
348        }
349    }
350
351    /// Gets just the path, without the args. Some examples:
352    ///
353    /// - `#[rustfmt::skip]`: `rustfmt::skip` is a path
354    /// - `#[allow(clippy::complexity)]`: `clippy::complexity` is a path
355    /// - `#[inline]`: `inline` is a single segment path
356    pub fn path(&self) -> &OwnedPathParser {
357        &self.path
358    }
359
360    /// Gets just the args parser, without caring about the path.
361    pub fn args(&self) -> &ArgParser {
362        #[cfg(debug_assertions)]
363        self.args_checked.store(true, Ordering::Relaxed);
364        &self.args
365    }
366
367    /// Asserts that this `MetaItem` starts with a word, or single segment path.
368    ///
369    /// Some examples:
370    /// - `#[inline]`: `inline` is a word
371    /// - `#[rustfmt::skip]`: `rustfmt::skip` is a path,
372    ///   and not a word and should instead be parsed using [`path`](Self::path)
373    pub fn word_is(&self, sym: Symbol) -> Option<&ArgParser> {
374        self.path().word_is(sym).then(|| self.args())
375    }
376
377    /// Explicitly ignore the arguments, disarming the arguments-used check
378    pub fn ignore_args(&self) {
379        self.args().ignore_args();
380    }
381
382    #[cfg(debug_assertions)]
383    pub fn are_args_checked(&self) -> bool {
384        self.args_checked.load(Ordering::Relaxed)
385    }
386}
387
388#[derive(#[automatically_derived]
impl ::core::clone::Clone for NameValueParser {
    #[inline]
    fn clone(&self) -> NameValueParser {
        NameValueParser {
            eq_span: ::core::clone::Clone::clone(&self.eq_span),
            value: ::core::clone::Clone::clone(&self.value),
            value_span: ::core::clone::Clone::clone(&self.value_span),
        }
    }
}Clone)]
389pub struct NameValueParser {
390    pub eq_span: Span,
391    value: MetaItemLit,
392    pub value_span: Span,
393}
394
395impl Debug for NameValueParser {
396    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
397        f.debug_struct("NameValueParser")
398            .field("eq_span", &self.eq_span)
399            .field("value", &self.value)
400            .field("value_span", &self.value_span)
401            .finish()
402    }
403}
404
405impl NameValueParser {
406    pub fn value_as_lit(&self) -> &MetaItemLit {
407        &self.value
408    }
409
410    pub fn value_as_str(&self) -> Option<Symbol> {
411        self.value_as_lit().kind.str()
412    }
413
414    /// If the value is a string literal, it will return its value associated with its span (an
415    /// `Ident` in short).
416    pub fn value_as_ident(&self) -> Option<Ident> {
417        let meta_item = self.value_as_lit();
418        meta_item.kind.str().map(|name| Ident { name, span: meta_item.span })
419    }
420
421    pub fn args_span(&self) -> Span {
422        self.eq_span.to(self.value_span)
423    }
424}
425
426fn expr_to_lit<'sess>(
427    psess: &'sess ParseSess,
428    expr: &Expr,
429    span: Span,
430    should_emit: ShouldEmit,
431) -> PResult<'sess, Option<MetaItemLit>> {
432    if let ExprKind::Lit(token_lit) = expr.kind {
433        let res = MetaItemLit::from_token_lit(token_lit, expr.span);
434        match res {
435            Ok(lit) => {
436                if token_lit.suffix.is_some() {
437                    Err(psess.dcx().create_err(SuffixedLiteralInAttribute { span: lit.span }))
438                } else if lit.kind.is_unsuffixed() {
439                    Ok(Some(lit))
440                } else {
441                    Err(psess.dcx().create_err(SuffixedLiteralInAttribute { span: lit.span }))
442                }
443            }
444            Err(err) => {
445                let err = create_lit_error(psess, err, token_lit, expr.span);
446                if #[allow(non_exhaustive_omitted_patterns)] match should_emit {
    ShouldEmit::ErrorsAndLints { recovery: Recovery::Forbidden } => true,
    _ => false,
}matches!(
447                    should_emit,
448                    ShouldEmit::ErrorsAndLints { recovery: Recovery::Forbidden }
449                ) {
450                    Err(err)
451                } else {
452                    let lit = MetaItemLit {
453                        symbol: token_lit.symbol,
454                        suffix: token_lit.suffix,
455                        kind: LitKind::Err(err.emit()),
456                        span: expr.span,
457                    };
458                    Ok(Some(lit))
459                }
460            }
461        }
462    } else {
463        if #[allow(non_exhaustive_omitted_patterns)] match should_emit {
    ShouldEmit::Nothing => true,
    _ => false,
}matches!(should_emit, ShouldEmit::Nothing) || #[allow(non_exhaustive_omitted_patterns)] match expr.kind {
    ExprKind::Err(_) => true,
    _ => false,
}matches!(expr.kind, ExprKind::Err(_)) {
464            return Ok(None);
465        }
466
467        // Example cases:
468        // - `#[foo = 1+1]`: results in `ast::ExprKind::BinOp`.
469        // - `#[foo = include_str!("nonexistent-file.rs")]`:
470        //   results in `ast::ExprKind::Err`.
471        let msg = "attribute value must be a literal";
472        let mut err = psess.dcx().struct_span_err(span, msg);
473
474        // Suggest adding quotation marks to turn an identifier into a string literal
475        if let ExprKind::Path(None, ref path) = expr.kind
476            && let [_] = path.segments.as_slice()
477        {
478            err.multipart_suggestion(
479                "you might have meant to write a string literal",
480                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(expr.span.shrink_to_lo(), "\"".to_string()),
                (expr.span.shrink_to_hi(), "\"".to_string())]))vec![
481                    (expr.span.shrink_to_lo(), "\"".to_string()),
482                    (expr.span.shrink_to_hi(), "\"".to_string()),
483                ],
484                Applicability::MaybeIncorrect,
485            );
486        }
487
488        Err(err)
489    }
490}
491
492/// Whether expansions of `expr` metavariables from declarative  macros
493/// are permitted. Used when parsing meta items; currently, only `cfg` predicates
494/// enable this option
495#[derive(#[automatically_derived]
impl ::core::clone::Clone for AllowExprMetavar {
    #[inline]
    fn clone(&self) -> AllowExprMetavar { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for AllowExprMetavar { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for AllowExprMetavar {
    #[inline]
    fn eq(&self, other: &AllowExprMetavar) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for AllowExprMetavar {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq)]
496pub enum AllowExprMetavar {
497    No,
498    Yes,
499}
500
501struct MetaItemListParserContext<'a, 'sess> {
502    parser: &'a mut Parser<'sess>,
503    should_emit: ShouldEmit,
504    allow_expr_metavar: AllowExprMetavar,
505}
506
507impl<'a, 'sess> MetaItemListParserContext<'a, 'sess> {
508    fn parse_unsuffixed_meta_item_lit(&mut self) -> PResult<'sess, MetaItemLit> {
509        let Some(token_lit) = self.parser.eat_token_lit() else { return Err(self.expected_lit()) };
510        self.unsuffixed_meta_item_from_lit(token_lit)
511    }
512
513    fn unsuffixed_meta_item_from_lit(
514        &mut self,
515        token_lit: token::Lit,
516    ) -> PResult<'sess, MetaItemLit> {
517        let lit = match MetaItemLit::from_token_lit(token_lit, self.parser.prev_token.span) {
518            Ok(lit) => lit,
519            Err(err) => {
520                return Err(create_lit_error(
521                    self.parser.psess,
522                    err,
523                    token_lit,
524                    self.parser.prev_token_uninterpolated_span(),
525                ));
526            }
527        };
528
529        if !lit.kind.is_unsuffixed() {
530            // Emit error and continue, we can still parse the attribute as if the suffix isn't there
531            let err = self.parser.dcx().create_err(SuffixedLiteralInAttribute { span: lit.span });
532            if #[allow(non_exhaustive_omitted_patterns)] match self.should_emit {
    ShouldEmit::ErrorsAndLints { recovery: Recovery::Forbidden } => true,
    _ => false,
}matches!(
533                self.should_emit,
534                ShouldEmit::ErrorsAndLints { recovery: Recovery::Forbidden }
535            ) {
536                return Err(err);
537            }
538            self.should_emit.emit_err(err);
539        }
540
541        Ok(lit)
542    }
543
544    fn parse_meta_item(&mut self) -> PResult<'sess, MetaItemParser> {
545        if let Some(metavar) = self.parser.token.is_metavar_seq() {
546            match (metavar, self.allow_expr_metavar) {
547                (kind @ MetaVarKind::Expr { .. }, AllowExprMetavar::Yes) => {
548                    return self
549                        .parser
550                        .eat_metavar_seq(kind, |this| {
551                            MetaItemListParserContext {
552                                parser: this,
553                                should_emit: self.should_emit,
554                                allow_expr_metavar: AllowExprMetavar::Yes,
555                            }
556                            .parse_meta_item()
557                        })
558                        .ok_or_else(|| {
559                            self.parser.unexpected_any::<core::convert::Infallible>().unwrap_err()
560                        });
561                }
562                (MetaVarKind::Meta { has_meta_form }, _) => {
563                    return if has_meta_form {
564                        let attr_item = self
565                            .parser
566                            .eat_metavar_seq(MetaVarKind::Meta { has_meta_form: true }, |this| {
567                                MetaItemListParserContext {
568                                    parser: this,
569                                    should_emit: self.should_emit,
570                                    allow_expr_metavar: self.allow_expr_metavar,
571                                }
572                                .parse_meta_item()
573                            })
574                            .unwrap();
575                        Ok(attr_item)
576                    } else {
577                        self.parser.unexpected_any()
578                    };
579                }
580                _ => {}
581            }
582        }
583
584        let path = self.parser.parse_path(PathStyle::Mod)?;
585
586        // Check style of arguments that this meta item has
587        let args = if self.parser.check(::rustc_parse::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenParen,
    token_type: ::rustc_parse::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen)) {
588            let start = self.parser.token.span;
589            let (sub_parsers, _) = self.parser.parse_paren_comma_seq(|parser| {
590                MetaItemListParserContext {
591                    parser,
592                    should_emit: self.should_emit,
593                    allow_expr_metavar: self.allow_expr_metavar,
594                }
595                .parse_meta_item_inner()
596            })?;
597            let end = self.parser.prev_token.span;
598            ArgParser::List(MetaItemListParser { sub_parsers, span: start.with_hi(end.hi()) })
599        } else if self.parser.eat(::rustc_parse::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Eq,
    token_type: ::rustc_parse::parser::token_type::TokenType::Eq,
}exp!(Eq)) {
600            let eq_span = self.parser.prev_token.span;
601            let value = self.parse_unsuffixed_meta_item_lit()?;
602
603            ArgParser::NameValue(NameValueParser { eq_span, value, value_span: value.span })
604        } else {
605            ArgParser::NoArgs
606        };
607
608        Ok(MetaItemParser {
609            path: PathParser(path),
610            args,
611            #[cfg(debug_assertions)]
612            args_checked: AtomicBool::new(false),
613        })
614    }
615
616    fn parse_meta_item_inner(&mut self) -> PResult<'sess, MetaItemOrLitParser> {
617        if let Some(token_lit) = self.parser.eat_token_lit() {
618            // If a literal token is parsed, we commit to parsing a MetaItemLit for better errors
619            Ok(MetaItemOrLitParser::Lit(self.unsuffixed_meta_item_from_lit(token_lit)?))
620        } else {
621            let prev_pros = self.parser.approx_token_stream_pos();
622            match self.parse_meta_item() {
623                Ok(item) => Ok(MetaItemOrLitParser::MetaItemParser(item)),
624                Err(err) => {
625                    // If `parse_attr_item` made any progress, it likely has a more precise error we should prefer
626                    // If it didn't make progress we use the `expected_lit` from below
627                    if self.parser.approx_token_stream_pos() == prev_pros {
628                        err.cancel();
629                        Err(self.expected_lit())
630                    } else {
631                        Err(err)
632                    }
633                }
634            }
635        }
636    }
637
638    fn expected_lit(&mut self) -> Diag<'sess> {
639        let mut err = InvalidMetaItem {
640            span: self.parser.token.span,
641            descr: token_descr(&self.parser.token),
642            quote_ident_sugg: None,
643            remove_neg_sugg: None,
644            label: None,
645        };
646
647        if let token::OpenInvisible(_) = self.parser.token.kind {
648            // Do not attempt to suggest anything when encountered as part of a macro expansion.
649            return self.parser.dcx().create_err(err);
650        }
651
652        if let ShouldEmit::ErrorsAndLints { recovery: Recovery::Forbidden } = self.should_emit {
653            // Do not attempt to suggest anything in `Recovery::Forbidden` mode.
654            // Malformed diagnostic-attr arguments that start with an `if` expression can lead to
655            // an ICE (https://github.com/rust-lang/rust/issues/152744), because callers may cancel the `InvalidMetaItem` error.
656            return self.parser.dcx().create_err(err);
657        }
658
659        // Suggest quoting idents, e.g. in `#[cfg(key = value)]`. We don't use `Token::ident` and
660        // don't `uninterpolate` the token to avoid suggesting anything butchered or questionable
661        // when macro metavariables are involved.
662        let snapshot = self.parser.create_snapshot_for_diagnostic();
663        match self.parser.parse_stmt_without_recovery(false, ForceCollect::No, false) {
664            Ok(stmt) => {
665                // The user tried to write something like
666                // `#[deprecated(note = concat!("a", "b"))]`.
667                err.descr = stmt.kind.descr().to_string();
668                err.label = Some(stmt.span);
669                err.span = stmt.span;
670                if let StmtKind::Expr(expr) = &stmt.kind
671                    && let ExprKind::Unary(UnOp::Neg, val) = &expr.kind
672                    && let ExprKind::Lit(_) = val.kind
673                {
674                    err.remove_neg_sugg = Some(InvalidMetaItemRemoveNegSugg {
675                        negative_sign: expr.span.until(val.span),
676                    });
677                } else if let StmtKind::Expr(expr) = &stmt.kind
678                    && let ExprKind::Path(None, Path { segments, .. }) = &expr.kind
679                    && segments.len() == 1
680                {
681                    while let token::Ident(..) | token::Literal(_) | token::Dot =
682                        self.parser.token.kind
683                    {
684                        // We've got a word, so we try to consume the rest of a potential sentence.
685                        // We include `.` to correctly handle things like `A sentence here.`.
686                        self.parser.bump();
687                    }
688                    err.quote_ident_sugg = Some(InvalidMetaItemQuoteIdentSugg {
689                        before: expr.span.shrink_to_lo(),
690                        after: self.parser.prev_token.span.shrink_to_hi(),
691                    });
692                }
693            }
694            Err(e) => {
695                e.cancel();
696                self.parser.restore_snapshot(snapshot);
697            }
698        }
699
700        self.parser.dcx().create_err(err)
701    }
702
703    fn should_continue_parsing_meta_items(&mut self) -> Result<bool, Diag<'sess>> {
704        if self.parser.eat(::rustc_parse::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: ::rustc_parse::parser::token_type::TokenType::Comma,
}exp!(Comma)) {
705            return Ok(true);
706        } else if self.parser.token == token::Eof {
707            return Ok(false);
708        }
709
710        let mut snapshot = self.parser.create_snapshot_for_diagnostic();
711        if #[allow(non_exhaustive_omitted_patterns)] match self.should_emit {
    ShouldEmit::ErrorsAndLints { recovery: Recovery::Allowed } => true,
    _ => false,
}matches!(self.should_emit, ShouldEmit::ErrorsAndLints { recovery: Recovery::Allowed }) {
712            let mut missing_commas = ThinVec::new();
713            let mut found_comma = false;
714            while self.parser.token != token::Eof {
715                let span = self.parser.prev_token.span.shrink_to_hi();
716                self.should_emit = ShouldEmit::Nothing;
717                match self.parse_meta_item_inner() {
718                    Ok(_) => {
719                        if !found_comma {
720                            missing_commas.push(span);
721                        }
722                    }
723                    Err(e) => {
724                        e.cancel();
725                        break;
726                    }
727                }
728                found_comma = self.parser.eat(::rustc_parse::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: ::rustc_parse::parser::token_type::TokenType::Comma,
}exp!(Comma));
729            }
730
731            let mut missing_commas = missing_commas.into_iter();
732            if let Some(span) = missing_commas.next() {
733                let additional =
734                    missing_commas.map(|span| AdditionalCommaSuggestion { span }).collect();
735                return Err(self.parser.dcx().create_err(ExpectedComma { span, additional }));
736            }
737        }
738        snapshot.unexpected_any()
739    }
740
741    fn parse(
742        tokens: TokenStream,
743        psess: &'sess ParseSess,
744        span: Span,
745        should_emit: ShouldEmit,
746        allow_expr_metavar: AllowExprMetavar,
747    ) -> PResult<'sess, MetaItemListParser> {
748        let mut parser = Parser::new(psess, tokens, None);
749        if let ShouldEmit::ErrorsAndLints { recovery } = should_emit {
750            parser = parser.recovery(recovery);
751        }
752
753        let mut this =
754            MetaItemListParserContext { parser: &mut parser, should_emit, allow_expr_metavar };
755
756        // Presumably, the majority of the time there will only be one attr.
757        let mut sub_parsers = ThinVec::with_capacity(1);
758        while this.parser.token != token::Eof {
759            sub_parsers.push(this.parse_meta_item_inner()?);
760
761            if !this.should_continue_parsing_meta_items()? {
762                break;
763            }
764        }
765
766        Ok(MetaItemListParser { sub_parsers, span })
767    }
768}
769
770#[derive(#[automatically_derived]
impl ::core::fmt::Debug for MetaItemListParser {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "MetaItemListParser", "sub_parsers", &self.sub_parsers, "span",
            &&self.span)
    }
}Debug)]
771pub struct MetaItemListParser {
772    sub_parsers: ThinVec<MetaItemOrLitParser>,
773    pub span: Span,
774}
775
776impl MetaItemListParser {
777    pub(crate) fn new<'sess>(
778        tokens: &TokenStream,
779        span: Span,
780        psess: &'sess ParseSess,
781        should_emit: ShouldEmit,
782        allow_expr_metavar: AllowExprMetavar,
783    ) -> Result<Self, Diag<'sess>> {
784        MetaItemListParserContext::parse(
785            tokens.clone(),
786            psess,
787            span,
788            should_emit,
789            allow_expr_metavar,
790        )
791    }
792
793    /// Lets you pick and choose as what you want to parse each element in the list
794    pub fn mixed(&self) -> impl Iterator<Item = &MetaItemOrLitParser> {
795        self.sub_parsers.iter()
796    }
797
798    pub fn len(&self) -> usize {
799        self.sub_parsers.len()
800    }
801
802    pub fn is_empty(&self) -> bool {
803        self.len() == 0
804    }
805
806    /// Returns Some if the list contains only a single element.
807    ///
808    /// Inside the Some is the parser to parse this single element.
809    pub fn as_single(&self) -> Option<&MetaItemOrLitParser> {
810        let mut iter = self.mixed();
811        iter.next().filter(|_| iter.next().is_none())
812    }
813}