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 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 [`AcceptContext::expected_no_args`](crate::context::AcceptContext::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/// Utility that deconstructs a MetaItem into usable parts.
259///
260/// MetaItems are syntactically extremely flexible, but specific attributes want to parse
261/// them in custom, more restricted ways. This can be done using this struct.
262///
263/// MetaItems consist of some path, and some args. The args could be empty. In other words:
264///
265/// - `name` -> args are empty
266/// - `name(...)` -> args are a [`list`](ArgParser::list), which is the bit between the parentheses
267/// - `name = value`-> arg is [`name_value`](ArgParser::name_value), where the argument is the
268///   `= value` part
269///
270/// The syntax of MetaItems can be found at <https://doc.rust-lang.org/reference/attributes.html>
271#[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)]
272pub struct MetaItemParser {
273    path: OwnedPathParser,
274    args: ArgParser,
275}
276
277impl Debug for MetaItemParser {
278    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
279        f.debug_struct("MetaItemParser")
280            .field("path", &self.path)
281            .field("args", &self.args)
282            .finish()
283    }
284}
285
286impl MetaItemParser {
287    /// For a single-segment meta item, returns its name; otherwise, returns `None`.
288    pub fn ident(&self) -> Option<Ident> {
289        if let [PathSegment { ident, .. }] = self.path.0.segments[..] { Some(ident) } else { None }
290    }
291
292    pub fn span(&self) -> Span {
293        if let Some(other) = self.args.span() {
294            self.path.borrow().span().with_hi(other.hi())
295        } else {
296            self.path.borrow().span()
297        }
298    }
299
300    /// Gets just the path, without the args. Some examples:
301    ///
302    /// - `#[rustfmt::skip]`: `rustfmt::skip` is a path
303    /// - `#[allow(clippy::complexity)]`: `clippy::complexity` is a path
304    /// - `#[inline]`: `inline` is a single segment path
305    pub fn path(&self) -> &OwnedPathParser {
306        &self.path
307    }
308
309    /// Gets just the args parser, without caring about the path.
310    pub fn args(&self) -> &ArgParser {
311        &self.args
312    }
313
314    /// Asserts that this MetaItem starts with a word, or single segment path.
315    ///
316    /// Some examples:
317    /// - `#[inline]`: `inline` is a word
318    /// - `#[rustfmt::skip]`: `rustfmt::skip` is a path,
319    ///   and not a word and should instead be parsed using [`path`](Self::path)
320    pub fn word_is(&self, sym: Symbol) -> Option<&ArgParser> {
321        self.path().word_is(sym).then(|| self.args())
322    }
323}
324
325#[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)]
326pub struct NameValueParser {
327    pub eq_span: Span,
328    value: MetaItemLit,
329    pub value_span: Span,
330}
331
332impl Debug for NameValueParser {
333    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
334        f.debug_struct("NameValueParser")
335            .field("eq_span", &self.eq_span)
336            .field("value", &self.value)
337            .field("value_span", &self.value_span)
338            .finish()
339    }
340}
341
342impl NameValueParser {
343    pub fn value_as_lit(&self) -> &MetaItemLit {
344        &self.value
345    }
346
347    pub fn value_as_str(&self) -> Option<Symbol> {
348        self.value_as_lit().kind.str()
349    }
350
351    /// If the value is a string literal, it will return its value associated with its span (an
352    /// `Ident` in short).
353    pub fn value_as_ident(&self) -> Option<Ident> {
354        let meta_item = self.value_as_lit();
355        meta_item.kind.str().map(|name| Ident { name, span: meta_item.span })
356    }
357
358    pub fn args_span(&self) -> Span {
359        self.eq_span.to(self.value_span)
360    }
361}
362
363fn expr_to_lit<'sess>(
364    psess: &'sess ParseSess,
365    expr: &Expr,
366    span: Span,
367    should_emit: ShouldEmit,
368) -> PResult<'sess, Option<MetaItemLit>> {
369    if let ExprKind::Lit(token_lit) = expr.kind {
370        let res = MetaItemLit::from_token_lit(token_lit, expr.span);
371        match res {
372            Ok(lit) => {
373                if token_lit.suffix.is_some() {
374                    Err(psess.dcx().create_err(SuffixedLiteralInAttribute { span: lit.span }))
375                } else {
376                    if lit.kind.is_unsuffixed() {
377                        Ok(Some(lit))
378                    } else {
379                        Err(psess.dcx().create_err(SuffixedLiteralInAttribute { span: lit.span }))
380                    }
381                }
382            }
383            Err(err) => {
384                let err = create_lit_error(psess, err, token_lit, expr.span);
385                if #[allow(non_exhaustive_omitted_patterns)] match should_emit {
    ShouldEmit::ErrorsAndLints { recovery: Recovery::Forbidden } => true,
    _ => false,
}matches!(
386                    should_emit,
387                    ShouldEmit::ErrorsAndLints { recovery: Recovery::Forbidden }
388                ) {
389                    Err(err)
390                } else {
391                    let lit = MetaItemLit {
392                        symbol: token_lit.symbol,
393                        suffix: token_lit.suffix,
394                        kind: LitKind::Err(err.emit()),
395                        span: expr.span,
396                    };
397                    Ok(Some(lit))
398                }
399            }
400        }
401    } else {
402        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(_)) {
403            return Ok(None);
404        }
405
406        // Example cases:
407        // - `#[foo = 1+1]`: results in `ast::ExprKind::BinOp`.
408        // - `#[foo = include_str!("nonexistent-file.rs")]`:
409        //   results in `ast::ExprKind::Err`.
410        let msg = "attribute value must be a literal";
411        let err = psess.dcx().struct_span_err(span, msg);
412        Err(err)
413    }
414}
415
416/// Whether expansions of `expr` metavariables from decrarative macros
417/// are permitted. Used when parsing meta items; currently, only `cfg` predicates
418/// enable this option
419#[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)]
420pub enum AllowExprMetavar {
421    No,
422    Yes,
423}
424
425struct MetaItemListParserContext<'a, 'sess> {
426    parser: &'a mut Parser<'sess>,
427    should_emit: ShouldEmit,
428    allow_expr_metavar: AllowExprMetavar,
429}
430
431impl<'a, 'sess> MetaItemListParserContext<'a, 'sess> {
432    fn parse_unsuffixed_meta_item_lit(&mut self) -> PResult<'sess, MetaItemLit> {
433        let Some(token_lit) = self.parser.eat_token_lit() else { return Err(self.expected_lit()) };
434        self.unsuffixed_meta_item_from_lit(token_lit)
435    }
436
437    fn unsuffixed_meta_item_from_lit(
438        &mut self,
439        token_lit: token::Lit,
440    ) -> PResult<'sess, MetaItemLit> {
441        let lit = match MetaItemLit::from_token_lit(token_lit, self.parser.prev_token.span) {
442            Ok(lit) => lit,
443            Err(err) => {
444                return Err(create_lit_error(
445                    &self.parser.psess,
446                    err,
447                    token_lit,
448                    self.parser.prev_token_uninterpolated_span(),
449                ));
450            }
451        };
452
453        if !lit.kind.is_unsuffixed() {
454            // Emit error and continue, we can still parse the attribute as if the suffix isn't there
455            let err = self.parser.dcx().create_err(SuffixedLiteralInAttribute { span: lit.span });
456            if #[allow(non_exhaustive_omitted_patterns)] match self.should_emit {
    ShouldEmit::ErrorsAndLints { recovery: Recovery::Forbidden } => true,
    _ => false,
}matches!(
457                self.should_emit,
458                ShouldEmit::ErrorsAndLints { recovery: Recovery::Forbidden }
459            ) {
460                return Err(err);
461            } else {
462                self.should_emit.emit_err(err)
463            };
464        }
465
466        Ok(lit)
467    }
468
469    fn parse_meta_item(&mut self) -> PResult<'sess, MetaItemParser> {
470        if let Some(metavar) = self.parser.token.is_metavar_seq() {
471            match (metavar, self.allow_expr_metavar) {
472                (kind @ MetaVarKind::Expr { .. }, AllowExprMetavar::Yes) => {
473                    return self
474                        .parser
475                        .eat_metavar_seq(kind, |this| {
476                            MetaItemListParserContext {
477                                parser: this,
478                                should_emit: self.should_emit,
479                                allow_expr_metavar: AllowExprMetavar::Yes,
480                            }
481                            .parse_meta_item()
482                        })
483                        .ok_or_else(|| {
484                            self.parser.unexpected_any::<core::convert::Infallible>().unwrap_err()
485                        });
486                }
487                (MetaVarKind::Meta { has_meta_form }, _) => {
488                    return if has_meta_form {
489                        let attr_item = self
490                            .parser
491                            .eat_metavar_seq(MetaVarKind::Meta { has_meta_form: true }, |this| {
492                                MetaItemListParserContext {
493                                    parser: this,
494                                    should_emit: self.should_emit,
495                                    allow_expr_metavar: self.allow_expr_metavar,
496                                }
497                                .parse_meta_item()
498                            })
499                            .unwrap();
500                        Ok(attr_item)
501                    } else {
502                        self.parser.unexpected_any()
503                    };
504                }
505                _ => {}
506            }
507        }
508
509        let path = self.parser.parse_path(PathStyle::Mod)?;
510
511        // Check style of arguments that this meta item has
512        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)) {
513            let start = self.parser.token.span;
514            let (sub_parsers, _) = self.parser.parse_paren_comma_seq(|parser| {
515                MetaItemListParserContext {
516                    parser,
517                    should_emit: self.should_emit,
518                    allow_expr_metavar: self.allow_expr_metavar,
519                }
520                .parse_meta_item_inner()
521            })?;
522            let end = self.parser.prev_token.span;
523            ArgParser::List(MetaItemListParser { sub_parsers, span: start.with_hi(end.hi()) })
524        } 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)) {
525            let eq_span = self.parser.prev_token.span;
526            let value = self.parse_unsuffixed_meta_item_lit()?;
527
528            ArgParser::NameValue(NameValueParser { eq_span, value, value_span: value.span })
529        } else {
530            ArgParser::NoArgs
531        };
532
533        Ok(MetaItemParser { path: PathParser(path), args })
534    }
535
536    fn parse_meta_item_inner(&mut self) -> PResult<'sess, MetaItemOrLitParser> {
537        if let Some(token_lit) = self.parser.eat_token_lit() {
538            // If a literal token is parsed, we commit to parsing a MetaItemLit for better errors
539            Ok(MetaItemOrLitParser::Lit(self.unsuffixed_meta_item_from_lit(token_lit)?))
540        } else {
541            let prev_pros = self.parser.approx_token_stream_pos();
542            match self.parse_meta_item() {
543                Ok(item) => Ok(MetaItemOrLitParser::MetaItemParser(item)),
544                Err(err) => {
545                    // If `parse_attr_item` made any progress, it likely has a more precise error we should prefer
546                    // If it didn't make progress we use the `expected_lit` from below
547                    if self.parser.approx_token_stream_pos() != prev_pros {
548                        Err(err)
549                    } else {
550                        err.cancel();
551                        Err(self.expected_lit())
552                    }
553                }
554            }
555        }
556    }
557
558    fn expected_lit(&mut self) -> Diag<'sess> {
559        let mut err = InvalidMetaItem {
560            span: self.parser.token.span,
561            descr: token_descr(&self.parser.token),
562            quote_ident_sugg: None,
563            remove_neg_sugg: None,
564            label: None,
565        };
566
567        if let token::OpenInvisible(_) = self.parser.token.kind {
568            // Do not attempt to suggest anything when encountered as part of a macro expansion.
569            return self.parser.dcx().create_err(err);
570        }
571
572        if let ShouldEmit::ErrorsAndLints { recovery: Recovery::Forbidden } = self.should_emit {
573            // Do not attempt to suggest anything in `Recovery::Forbidden` mode.
574            // Malformed diagnostic-attr arguments that start with an `if` expression can lead to
575            // an ICE (https://github.com/rust-lang/rust/issues/152744), because callers may cancel the `InvalidMetaItem` error.
576            return self.parser.dcx().create_err(err);
577        }
578
579        // Suggest quoting idents, e.g. in `#[cfg(key = value)]`. We don't use `Token::ident` and
580        // don't `uninterpolate` the token to avoid suggesting anything butchered or questionable
581        // when macro metavariables are involved.
582        let snapshot = self.parser.create_snapshot_for_diagnostic();
583        let stmt = self.parser.parse_stmt_without_recovery(false, ForceCollect::No, false);
584        match stmt {
585            Ok(Some(stmt)) => {
586                // The user tried to write something like
587                // `#[deprecated(note = concat!("a", "b"))]`.
588                err.descr = stmt.kind.descr().to_string();
589                err.label = Some(stmt.span);
590                err.span = stmt.span;
591                if let StmtKind::Expr(expr) = &stmt.kind
592                    && let ExprKind::Unary(UnOp::Neg, val) = &expr.kind
593                    && let ExprKind::Lit(_) = val.kind
594                {
595                    err.remove_neg_sugg = Some(InvalidMetaItemRemoveNegSugg {
596                        negative_sign: expr.span.until(val.span),
597                    });
598                } else if let StmtKind::Expr(expr) = &stmt.kind
599                    && let ExprKind::Path(None, Path { segments, .. }) = &expr.kind
600                    && segments.len() == 1
601                {
602                    while let token::Ident(..) | token::Literal(_) | token::Dot =
603                        self.parser.token.kind
604                    {
605                        // We've got a word, so we try to consume the rest of a potential sentence.
606                        // We include `.` to correctly handle things like `A sentence here.`.
607                        self.parser.bump();
608                    }
609                    err.quote_ident_sugg = Some(InvalidMetaItemQuoteIdentSugg {
610                        before: expr.span.shrink_to_lo(),
611                        after: self.parser.prev_token.span.shrink_to_hi(),
612                    });
613                }
614            }
615            Ok(None) => {}
616            Err(e) => {
617                e.cancel();
618                self.parser.restore_snapshot(snapshot);
619            }
620        }
621
622        self.parser.dcx().create_err(err)
623    }
624
625    fn parse(
626        tokens: TokenStream,
627        psess: &'sess ParseSess,
628        span: Span,
629        should_emit: ShouldEmit,
630        allow_expr_metavar: AllowExprMetavar,
631    ) -> PResult<'sess, MetaItemListParser> {
632        let mut parser = Parser::new(psess, tokens, None);
633        if let ShouldEmit::ErrorsAndLints { recovery } = should_emit {
634            parser = parser.recovery(recovery);
635        }
636
637        let mut this =
638            MetaItemListParserContext { parser: &mut parser, should_emit, allow_expr_metavar };
639
640        // Presumably, the majority of the time there will only be one attr.
641        let mut sub_parsers = ThinVec::with_capacity(1);
642        while this.parser.token != token::Eof {
643            sub_parsers.push(this.parse_meta_item_inner()?);
644
645            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)) {
646                break;
647            }
648        }
649
650        if parser.token != token::Eof {
651            parser.unexpected()?;
652        }
653
654        Ok(MetaItemListParser { sub_parsers, span })
655    }
656}
657
658#[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)]
659pub struct MetaItemListParser {
660    sub_parsers: ThinVec<MetaItemOrLitParser>,
661    pub span: Span,
662}
663
664impl MetaItemListParser {
665    pub(crate) fn new<'sess>(
666        tokens: &TokenStream,
667        span: Span,
668        psess: &'sess ParseSess,
669        should_emit: ShouldEmit,
670        allow_expr_metavar: AllowExprMetavar,
671    ) -> Result<Self, Diag<'sess>> {
672        MetaItemListParserContext::parse(
673            tokens.clone(),
674            psess,
675            span,
676            should_emit,
677            allow_expr_metavar,
678        )
679    }
680
681    /// Lets you pick and choose as what you want to parse each element in the list
682    pub fn mixed(&self) -> impl Iterator<Item = &MetaItemOrLitParser> {
683        self.sub_parsers.iter()
684    }
685
686    pub fn len(&self) -> usize {
687        self.sub_parsers.len()
688    }
689
690    pub fn is_empty(&self) -> bool {
691        self.len() == 0
692    }
693
694    /// Returns Some if the list contains only a single element.
695    ///
696    /// Inside the Some is the parser to parse this single element.
697    pub fn single(&self) -> Option<&MetaItemOrLitParser> {
698        let mut iter = self.mixed();
699        iter.next().filter(|_| iter.next().is_none())
700    }
701}