Skip to main content

rustc_attr_parsing/
parser.rs

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