Skip to main content

rustc_attr_parsing/
parser.rs

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