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, 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    ) -> Option<Self> {
113        Some(match value {
114            AttrArgs::Empty => Self::NoArgs,
115            AttrArgs::Delimited(args) => {
116                // Diagnostic attributes can't error if they encounter non meta item syntax.
117                // However, the current syntax for diagnostic attributes is meta item syntax.
118                // Therefore we can substitute with a dummy value on invalid syntax.
119                if #[allow(non_exhaustive_omitted_patterns)] match parts {
    [sym::rustc_dummy] | [sym::diagnostic, ..] => true,
    _ => false,
}matches!(parts, [sym::rustc_dummy] | [sym::diagnostic, ..]) {
120                    match MetaItemListParser::new(
121                        &args.tokens,
122                        args.dspan.entire(),
123                        psess,
124                        ShouldEmit::ErrorsAndLints { recover: false },
125                    ) {
126                        Ok(p) => return Some(ArgParser::List(p)),
127                        Err(e) => {
128                            // We can just dispose of the diagnostic and not bother with a lint,
129                            // because this will look like `#[diagnostic::attr()]` was used. This
130                            // is invalid for all diagnostic attrs, so a lint explaining the proper
131                            // form will be issued later.
132                            e.cancel();
133                            return Some(ArgParser::List(MetaItemListParser {
134                                sub_parsers: ThinVec::new(),
135                                span: args.dspan.entire(),
136                            }));
137                        }
138                    }
139                }
140
141                if args.delim != Delimiter::Parenthesis {
142                    should_emit.emit_err(psess.dcx().create_err(MetaBadDelim {
143                        span: args.dspan.entire(),
144                        sugg: MetaBadDelimSugg { open: args.dspan.open, close: args.dspan.close },
145                    }));
146                    return None;
147                }
148
149                Self::List(
150                    MetaItemListParser::new(&args.tokens, args.dspan.entire(), psess, should_emit)
151                        .map_err(|e| should_emit.emit_err(e))
152                        .ok()?,
153                )
154            }
155            AttrArgs::Eq { eq_span, expr } => Self::NameValue(NameValueParser {
156                eq_span: *eq_span,
157                value: expr_to_lit(psess, &expr, expr.span, should_emit)
158                    .map_err(|e| should_emit.emit_err(e))
159                    .ok()??,
160                value_span: expr.span,
161            }),
162        })
163    }
164
165    /// Asserts that this MetaItem is a list
166    ///
167    /// Some examples:
168    ///
169    /// - `#[allow(clippy::complexity)]`: `(clippy::complexity)` is a list
170    /// - `#[rustfmt::skip::macros(target_macro_name)]`: `(target_macro_name)` is a list
171    pub fn list(&self) -> Option<&MetaItemListParser> {
172        match self {
173            Self::List(l) => Some(l),
174            Self::NameValue(_) | Self::NoArgs => None,
175        }
176    }
177
178    /// Asserts that this MetaItem is a name-value pair.
179    ///
180    /// Some examples:
181    ///
182    /// - `#[clippy::cyclomatic_complexity = "100"]`: `clippy::cyclomatic_complexity = "100"` is a name value pair,
183    ///   where the name is a path (`clippy::cyclomatic_complexity`). You already checked the path
184    ///   to get an `ArgParser`, so this method will effectively only assert that the `= "100"` is
185    ///   there
186    /// - `#[doc = "hello"]`: `doc = "hello`  is also a name value pair
187    pub fn name_value(&self) -> Option<&NameValueParser> {
188        match self {
189            Self::NameValue(n) => Some(n),
190            Self::List(_) | Self::NoArgs => None,
191        }
192    }
193
194    /// Assert that there were no args.
195    /// If there were, get a span to the arguments
196    /// (to pass to [`AcceptContext::expected_no_args`](crate::context::AcceptContext::expected_no_args)).
197    pub fn no_args(&self) -> Result<(), Span> {
198        match self {
199            Self::NoArgs => Ok(()),
200            Self::List(args) => Err(args.span),
201            Self::NameValue(args) => Err(args.args_span()),
202        }
203    }
204}
205
206/// Inside lists, values could be either literals, or more deeply nested meta items.
207/// This enum represents that.
208///
209/// Choose which one you want using the provided methods.
210#[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)]
211pub enum MetaItemOrLitParser {
212    MetaItemParser(MetaItemParser),
213    Lit(MetaItemLit),
214}
215
216impl MetaItemOrLitParser {
217    pub fn parse_single<'sess>(
218        parser: &mut Parser<'sess>,
219        should_emit: ShouldEmit,
220    ) -> PResult<'sess, MetaItemOrLitParser> {
221        let mut this = MetaItemListParserContext { parser, should_emit };
222        this.parse_meta_item_inner()
223    }
224
225    pub fn span(&self) -> Span {
226        match self {
227            MetaItemOrLitParser::MetaItemParser(generic_meta_item_parser) => {
228                generic_meta_item_parser.span()
229            }
230            MetaItemOrLitParser::Lit(meta_item_lit) => meta_item_lit.span,
231        }
232    }
233
234    pub fn lit(&self) -> Option<&MetaItemLit> {
235        match self {
236            MetaItemOrLitParser::Lit(meta_item_lit) => Some(meta_item_lit),
237            MetaItemOrLitParser::MetaItemParser(_) => None,
238        }
239    }
240
241    pub fn meta_item(&self) -> Option<&MetaItemParser> {
242        match self {
243            MetaItemOrLitParser::MetaItemParser(parser) => Some(parser),
244            MetaItemOrLitParser::Lit(_) => None,
245        }
246    }
247}
248
249/// Utility that deconstructs a MetaItem into usable parts.
250///
251/// MetaItems are syntactically extremely flexible, but specific attributes want to parse
252/// them in custom, more restricted ways. This can be done using this struct.
253///
254/// MetaItems consist of some path, and some args. The args could be empty. In other words:
255///
256/// - `name` -> args are empty
257/// - `name(...)` -> args are a [`list`](ArgParser::list), which is the bit between the parentheses
258/// - `name = value`-> arg is [`name_value`](ArgParser::name_value), where the argument is the
259///   `= value` part
260///
261/// The syntax of MetaItems can be found at <https://doc.rust-lang.org/reference/attributes.html>
262#[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)]
263pub struct MetaItemParser {
264    path: OwnedPathParser,
265    args: ArgParser,
266}
267
268impl Debug for MetaItemParser {
269    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
270        f.debug_struct("MetaItemParser")
271            .field("path", &self.path)
272            .field("args", &self.args)
273            .finish()
274    }
275}
276
277impl MetaItemParser {
278    /// For a single-segment meta item, returns its name; otherwise, returns `None`.
279    pub fn ident(&self) -> Option<Ident> {
280        if let [PathSegment { ident, .. }] = self.path.0.segments[..] { Some(ident) } else { None }
281    }
282
283    pub fn span(&self) -> Span {
284        if let Some(other) = self.args.span() {
285            self.path.borrow().span().with_hi(other.hi())
286        } else {
287            self.path.borrow().span()
288        }
289    }
290
291    /// Gets just the path, without the args. Some examples:
292    ///
293    /// - `#[rustfmt::skip]`: `rustfmt::skip` is a path
294    /// - `#[allow(clippy::complexity)]`: `clippy::complexity` is a path
295    /// - `#[inline]`: `inline` is a single segment path
296    pub fn path(&self) -> &OwnedPathParser {
297        &self.path
298    }
299
300    /// Gets just the args parser, without caring about the path.
301    pub fn args(&self) -> &ArgParser {
302        &self.args
303    }
304
305    /// Asserts that this MetaItem starts with a word, or single segment path.
306    ///
307    /// Some examples:
308    /// - `#[inline]`: `inline` is a word
309    /// - `#[rustfmt::skip]`: `rustfmt::skip` is a path,
310    ///   and not a word and should instead be parsed using [`path`](Self::path)
311    pub fn word_is(&self, sym: Symbol) -> Option<&ArgParser> {
312        self.path().word_is(sym).then(|| self.args())
313    }
314}
315
316#[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)]
317pub struct NameValueParser {
318    pub eq_span: Span,
319    value: MetaItemLit,
320    pub value_span: Span,
321}
322
323impl Debug for NameValueParser {
324    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
325        f.debug_struct("NameValueParser")
326            .field("eq_span", &self.eq_span)
327            .field("value", &self.value)
328            .field("value_span", &self.value_span)
329            .finish()
330    }
331}
332
333impl NameValueParser {
334    pub fn value_as_lit(&self) -> &MetaItemLit {
335        &self.value
336    }
337
338    pub fn value_as_str(&self) -> Option<Symbol> {
339        self.value_as_lit().kind.str()
340    }
341
342    /// If the value is a string literal, it will return its value associated with its span (an
343    /// `Ident` in short).
344    pub fn value_as_ident(&self) -> Option<Ident> {
345        let meta_item = self.value_as_lit();
346        meta_item.kind.str().map(|name| Ident { name, span: meta_item.span })
347    }
348
349    pub fn args_span(&self) -> Span {
350        self.eq_span.to(self.value_span)
351    }
352}
353
354fn expr_to_lit<'sess>(
355    psess: &'sess ParseSess,
356    expr: &Expr,
357    span: Span,
358    should_emit: ShouldEmit,
359) -> PResult<'sess, Option<MetaItemLit>> {
360    if let ExprKind::Lit(token_lit) = expr.kind {
361        let res = MetaItemLit::from_token_lit(token_lit, expr.span);
362        match res {
363            Ok(lit) => {
364                if token_lit.suffix.is_some() {
365                    Err(psess.dcx().create_err(SuffixedLiteralInAttribute { span: lit.span }))
366                } else {
367                    if lit.kind.is_unsuffixed() {
368                        Ok(Some(lit))
369                    } else {
370                        Err(psess.dcx().create_err(SuffixedLiteralInAttribute { span: lit.span }))
371                    }
372                }
373            }
374            Err(err) => {
375                let err = create_lit_error(psess, err, token_lit, expr.span);
376                if #[allow(non_exhaustive_omitted_patterns)] match should_emit {
    ShouldEmit::ErrorsAndLints { recover: false } => true,
    _ => false,
}matches!(should_emit, ShouldEmit::ErrorsAndLints { recover: false }) {
377                    Err(err)
378                } else {
379                    let lit = MetaItemLit {
380                        symbol: token_lit.symbol,
381                        suffix: token_lit.suffix,
382                        kind: LitKind::Err(err.emit()),
383                        span: expr.span,
384                    };
385                    Ok(Some(lit))
386                }
387            }
388        }
389    } else {
390        if #[allow(non_exhaustive_omitted_patterns)] match should_emit {
    ShouldEmit::Nothing => true,
    _ => false,
}matches!(should_emit, ShouldEmit::Nothing) {
391            return Ok(None);
392        }
393
394        // Example cases:
395        // - `#[foo = 1+1]`: results in `ast::ExprKind::BinOp`.
396        // - `#[foo = include_str!("nonexistent-file.rs")]`:
397        //   results in `ast::ExprKind::Err`.
398        let msg = "attribute value must be a literal";
399        let err = psess.dcx().struct_span_err(span, msg);
400        Err(err)
401    }
402}
403
404struct MetaItemListParserContext<'a, 'sess> {
405    parser: &'a mut Parser<'sess>,
406    should_emit: ShouldEmit,
407}
408
409impl<'a, 'sess> MetaItemListParserContext<'a, 'sess> {
410    fn parse_unsuffixed_meta_item_lit(&mut self) -> PResult<'sess, MetaItemLit> {
411        let Some(token_lit) = self.parser.eat_token_lit() else { return Err(self.expected_lit()) };
412        self.unsuffixed_meta_item_from_lit(token_lit)
413    }
414
415    fn unsuffixed_meta_item_from_lit(
416        &mut self,
417        token_lit: token::Lit,
418    ) -> PResult<'sess, MetaItemLit> {
419        let lit = match MetaItemLit::from_token_lit(token_lit, self.parser.prev_token.span) {
420            Ok(lit) => lit,
421            Err(err) => {
422                return Err(create_lit_error(
423                    &self.parser.psess,
424                    err,
425                    token_lit,
426                    self.parser.prev_token_uninterpolated_span(),
427                ));
428            }
429        };
430
431        if !lit.kind.is_unsuffixed() {
432            // Emit error and continue, we can still parse the attribute as if the suffix isn't there
433            let err = self.parser.dcx().create_err(SuffixedLiteralInAttribute { span: lit.span });
434            if #[allow(non_exhaustive_omitted_patterns)] match self.should_emit {
    ShouldEmit::ErrorsAndLints { recover: false } => true,
    _ => false,
}matches!(self.should_emit, ShouldEmit::ErrorsAndLints { recover: false }) {
435                return Err(err);
436            } else {
437                self.should_emit.emit_err(err)
438            };
439        }
440
441        Ok(lit)
442    }
443
444    fn parse_attr_item(&mut self) -> PResult<'sess, MetaItemParser> {
445        if let Some(MetaVarKind::Meta { has_meta_form }) = self.parser.token.is_metavar_seq() {
446            return if has_meta_form {
447                let attr_item = self
448                    .parser
449                    .eat_metavar_seq(MetaVarKind::Meta { has_meta_form: true }, |this| {
450                        MetaItemListParserContext { parser: this, should_emit: self.should_emit }
451                            .parse_attr_item()
452                    })
453                    .unwrap();
454                Ok(attr_item)
455            } else {
456                self.parser.unexpected_any()
457            };
458        }
459
460        let path = self.parser.parse_path(PathStyle::Mod)?;
461
462        // Check style of arguments that this meta item has
463        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)) {
464            let start = self.parser.token.span;
465            let (sub_parsers, _) = self.parser.parse_paren_comma_seq(|parser| {
466                MetaItemListParserContext { parser, should_emit: self.should_emit }
467                    .parse_meta_item_inner()
468            })?;
469            let end = self.parser.prev_token.span;
470            ArgParser::List(MetaItemListParser { sub_parsers, span: start.with_hi(end.hi()) })
471        } 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)) {
472            let eq_span = self.parser.prev_token.span;
473            let value = self.parse_unsuffixed_meta_item_lit()?;
474
475            ArgParser::NameValue(NameValueParser { eq_span, value, value_span: value.span })
476        } else {
477            ArgParser::NoArgs
478        };
479
480        Ok(MetaItemParser { path: PathParser(path), args })
481    }
482
483    fn parse_meta_item_inner(&mut self) -> PResult<'sess, MetaItemOrLitParser> {
484        if let Some(token_lit) = self.parser.eat_token_lit() {
485            // If a literal token is parsed, we commit to parsing a MetaItemLit for better errors
486            Ok(MetaItemOrLitParser::Lit(self.unsuffixed_meta_item_from_lit(token_lit)?))
487        } else {
488            let prev_pros = self.parser.approx_token_stream_pos();
489            match self.parse_attr_item() {
490                Ok(item) => Ok(MetaItemOrLitParser::MetaItemParser(item)),
491                Err(err) => {
492                    // If `parse_attr_item` made any progress, it likely has a more precise error we should prefer
493                    // If it didn't make progress we use the `expected_lit` from below
494                    if self.parser.approx_token_stream_pos() != prev_pros {
495                        Err(err)
496                    } else {
497                        err.cancel();
498                        Err(self.expected_lit())
499                    }
500                }
501            }
502        }
503    }
504
505    fn expected_lit(&mut self) -> Diag<'sess> {
506        let mut err = InvalidMetaItem {
507            span: self.parser.token.span,
508            descr: token_descr(&self.parser.token),
509            quote_ident_sugg: None,
510            remove_neg_sugg: None,
511            label: None,
512        };
513
514        if let token::OpenInvisible(_) = self.parser.token.kind {
515            // Do not attempt to suggest anything when encountered as part of a macro expansion.
516            return self.parser.dcx().create_err(err);
517        }
518
519        // Suggest quoting idents, e.g. in `#[cfg(key = value)]`. We don't use `Token::ident` and
520        // don't `uninterpolate` the token to avoid suggesting anything butchered or questionable
521        // when macro metavariables are involved.
522        let snapshot = self.parser.create_snapshot_for_diagnostic();
523        let stmt = self.parser.parse_stmt_without_recovery(false, ForceCollect::No, false);
524        match stmt {
525            Ok(Some(stmt)) => {
526                // The user tried to write something like
527                // `#[deprecated(note = concat!("a", "b"))]`.
528                err.descr = stmt.kind.descr().to_string();
529                err.label = Some(stmt.span);
530                err.span = stmt.span;
531                if let StmtKind::Expr(expr) = &stmt.kind
532                    && let ExprKind::Unary(UnOp::Neg, val) = &expr.kind
533                    && let ExprKind::Lit(_) = val.kind
534                {
535                    err.remove_neg_sugg = Some(InvalidMetaItemRemoveNegSugg {
536                        negative_sign: expr.span.until(val.span),
537                    });
538                } else if let StmtKind::Expr(expr) = &stmt.kind
539                    && let ExprKind::Path(None, Path { segments, .. }) = &expr.kind
540                    && segments.len() == 1
541                {
542                    while let token::Ident(..) | token::Literal(_) | token::Dot =
543                        self.parser.token.kind
544                    {
545                        // We've got a word, so we try to consume the rest of a potential sentence.
546                        // We include `.` to correctly handle things like `A sentence here.`.
547                        self.parser.bump();
548                    }
549                    err.quote_ident_sugg = Some(InvalidMetaItemQuoteIdentSugg {
550                        before: expr.span.shrink_to_lo(),
551                        after: self.parser.prev_token.span.shrink_to_hi(),
552                    });
553                }
554            }
555            Ok(None) => {}
556            Err(e) => {
557                e.cancel();
558                self.parser.restore_snapshot(snapshot);
559            }
560        }
561
562        self.parser.dcx().create_err(err)
563    }
564
565    fn parse(
566        tokens: TokenStream,
567        psess: &'sess ParseSess,
568        span: Span,
569        should_emit: ShouldEmit,
570    ) -> PResult<'sess, MetaItemListParser> {
571        let mut parser = Parser::new(psess, tokens, None);
572        let mut this = MetaItemListParserContext { parser: &mut parser, should_emit };
573
574        // Presumably, the majority of the time there will only be one attr.
575        let mut sub_parsers = ThinVec::with_capacity(1);
576        while this.parser.token != token::Eof {
577            sub_parsers.push(this.parse_meta_item_inner()?);
578
579            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)) {
580                break;
581            }
582        }
583
584        if parser.token != token::Eof {
585            parser.unexpected()?;
586        }
587
588        Ok(MetaItemListParser { sub_parsers, span })
589    }
590}
591
592#[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)]
593pub struct MetaItemListParser {
594    sub_parsers: ThinVec<MetaItemOrLitParser>,
595    pub span: Span,
596}
597
598impl MetaItemListParser {
599    pub(crate) fn new<'sess>(
600        tokens: &TokenStream,
601        span: Span,
602        psess: &'sess ParseSess,
603        should_emit: ShouldEmit,
604    ) -> Result<Self, Diag<'sess>> {
605        MetaItemListParserContext::parse(tokens.clone(), psess, span, should_emit)
606    }
607
608    /// Lets you pick and choose as what you want to parse each element in the list
609    pub fn mixed(&self) -> impl Iterator<Item = &MetaItemOrLitParser> {
610        self.sub_parsers.iter()
611    }
612
613    pub fn len(&self) -> usize {
614        self.sub_parsers.len()
615    }
616
617    pub fn is_empty(&self) -> bool {
618        self.len() == 0
619    }
620
621    /// Returns Some if the list contains only a single element.
622    ///
623    /// Inside the Some is the parser to parse this single element.
624    pub fn single(&self) -> Option<&MetaItemOrLitParser> {
625        let mut iter = self.mixed();
626        iter.next().filter(|_| iter.next().is_none())
627    }
628}