Skip to main content

rustc_parse/parser/
mod.rs

1pub mod attr;
2mod attr_wrapper;
3mod diagnostics;
4mod expr;
5mod generics;
6mod item;
7mod nonterminal;
8mod pat;
9mod path;
10mod stmt;
11pub mod token_type;
12mod ty;
13
14// Parsers for non-functionlike builtin macros are defined in rustc_parse so they can be used by
15// both rustc_builtin_macros and rustfmt.
16pub mod asm;
17pub mod cfg_select;
18
19use std::{fmt, mem, slice};
20
21use attr_wrapper::{AttrWrapper, UsePreAttrPos};
22pub use diagnostics::AttemptLocalParseRecovery;
23// Public to use it for custom `if` expressions in rustfmt forks like https://github.com/tucant/rustfmt
24pub use expr::LetChainsPolicy;
25pub(crate) use item::{FnContext, FnParseMode};
26pub use pat::{CommaRecoveryMode, RecoverColon, RecoverComma};
27pub use path::PathStyle;
28use rustc_ast::token::{
29    self, IdentIsRaw, InvisibleOrigin, MetaVarKind, NtExprKind, NtPatKind, Token, TokenKind,
30};
31use rustc_ast::tokenstream::{
32    ParserRange, ParserReplacement, Spacing, TokenCursor, TokenStream, TokenTree, TokenTreeCursor,
33};
34use rustc_ast::util::case::Case;
35use rustc_ast::{
36    self as ast, AnonConst, AttrArgs, AttrId, ByRef, Const, CoroutineKind, DUMMY_NODE_ID,
37    DelimArgs, Expr, ExprKind, Extern, HasAttrs, HasTokens, MgcaDisambiguation, Mutability,
38    Recovered, Safety, StrLit, Visibility, VisibilityKind,
39};
40use rustc_ast_pretty::pprust;
41use rustc_data_structures::debug_assert_matches;
42use rustc_data_structures::fx::FxHashMap;
43use rustc_errors::{Applicability, Diag, FatalError, MultiSpan, PResult};
44use rustc_index::interval::IntervalSet;
45use rustc_session::parse::ParseSess;
46use rustc_span::{Ident, Span, Symbol, kw, sym};
47use thin_vec::ThinVec;
48use token_type::TokenTypeSet;
49pub use token_type::{ExpKeywordPair, ExpTokenPair, TokenType};
50use tracing::debug;
51
52use crate::errors::{self, IncorrectVisibilityRestriction, NonStringAbiLiteral, TokenDescription};
53use crate::exp;
54
55#[cfg(test)]
56mod tests;
57
58// Ideally, these tests would be in `rustc_ast`. But they depend on having a
59// parser, so they are here.
60#[cfg(test)]
61mod tokenstream {
62    mod tests;
63}
64
65bitflags::bitflags! {
66    /// Restrictions applied while parsing.
67    ///
68    /// The parser maintains a bitset of restrictions it will honor while
69    /// parsing. This is essentially used as a way of tracking state of what
70    /// is being parsed and to change behavior based on that.
71    #[derive(#[automatically_derived]
impl ::core::clone::Clone for Restrictions {
    #[inline]
    fn clone(&self) -> Restrictions {
        let _:
                ::core::clone::AssertParamIsClone<<Restrictions as
                ::bitflags::__private::PublicFlags>::Internal>;
        *self
    }
}
impl Restrictions {
    #[doc = r" Restricts expressions for use in statement position."]
    #[doc = r""]
    #[doc =
    r" When expressions are used in various places, like statements or"]
    #[doc =
    r" match arms, this is used to stop parsing once certain tokens are"]
    #[doc = r" reached."]
    #[doc = r""]
    #[doc =
    r" For example, `if true {} & 1` with `STMT_EXPR` in effect is parsed"]
    #[doc =
    r" as two separate expression statements (`if` and a reference to 1)."]
    #[doc =
    r" Otherwise it is parsed as a bitwise AND where `if` is on the left"]
    #[doc = r" and 1 is on the right."]
    #[allow(deprecated, non_upper_case_globals,)]
    pub const STMT_EXPR: Self = Self::from_bits_retain(1 << 0);
    #[doc = r" Do not allow struct literals."]
    #[doc = r""]
    #[doc =
    r" There are several places in the grammar where we don't want to"]
    #[doc = r" allow struct literals because they can require lookahead, or"]
    #[doc = r" otherwise could be ambiguous or cause confusion. For example,"]
    #[doc =
    r" `if Foo {} {}` isn't clear if it is `Foo{}` struct literal, or"]
    #[doc = r" just `Foo` is the condition, followed by a consequent block,"]
    #[doc = r" followed by an empty block."]
    #[doc = r""]
    #[doc =
    r" See [RFC 92](https://rust-lang.github.io/rfcs/0092-struct-grammar.html)."]
    #[allow(deprecated, non_upper_case_globals,)]
    pub const NO_STRUCT_LITERAL: Self = Self::from_bits_retain(1 << 1);
    #[doc =
    r" Used to provide better error messages for const generic arguments."]
    #[doc = r""]
    #[doc =
    r" An un-braced const generic argument is limited to a very small"]
    #[doc =
    r" subset of expressions. This is used to detect the situation where"]
    #[doc =
    r" an expression outside of that subset is used, and to suggest to"]
    #[doc = r" wrap the expression in braces."]
    #[allow(deprecated, non_upper_case_globals,)]
    pub const CONST_EXPR: Self = Self::from_bits_retain(1 << 2);
    #[doc = r" Allows `let` expressions."]
    #[doc = r""]
    #[doc =
    r" `let pattern = scrutinee` is parsed as an expression, but it is"]
    #[doc = r" only allowed in let chains (`if` and `while` conditions)."]
    #[doc =
    r" Otherwise it is not an expression (note that `let` in statement"]
    #[doc =
    r" positions is treated as a `StmtKind::Let` statement, which has a"]
    #[doc = r" slightly different grammar)."]
    #[allow(deprecated, non_upper_case_globals,)]
    pub const ALLOW_LET: Self = Self::from_bits_retain(1 << 3);
    #[doc = r" Used to detect a missing `=>` in a match guard."]
    #[doc = r""]
    #[doc =
    r" This is used for error handling in a match guard to give a better"]
    #[doc =
    r" error message if the `=>` is missing. It is set when parsing the"]
    #[doc = r" guard expression."]
    #[allow(deprecated, non_upper_case_globals,)]
    pub const IN_IF_GUARD: Self = Self::from_bits_retain(1 << 4);
    #[doc = r" Used to detect the incorrect use of expressions in patterns."]
    #[doc = r""]
    #[doc =
    r" This is used for error handling while parsing a pattern. During"]
    #[doc =
    r" error recovery, this will be set to try to parse the pattern as an"]
    #[doc =
    r" expression, but halts parsing the expression when reaching certain"]
    #[doc = r" tokens like `=`."]
    #[allow(deprecated, non_upper_case_globals,)]
    pub const IS_PAT: Self = Self::from_bits_retain(1 << 5);
}
impl ::bitflags::Flags for Restrictions {
    const FLAGS: &'static [::bitflags::Flag<Restrictions>] =
        &[{

                        #[allow(deprecated, non_upper_case_globals,)]
                        ::bitflags::Flag::new("STMT_EXPR", Restrictions::STMT_EXPR)
                    },
                    {

                        #[allow(deprecated, non_upper_case_globals,)]
                        ::bitflags::Flag::new("NO_STRUCT_LITERAL",
                            Restrictions::NO_STRUCT_LITERAL)
                    },
                    {

                        #[allow(deprecated, non_upper_case_globals,)]
                        ::bitflags::Flag::new("CONST_EXPR",
                            Restrictions::CONST_EXPR)
                    },
                    {

                        #[allow(deprecated, non_upper_case_globals,)]
                        ::bitflags::Flag::new("ALLOW_LET", Restrictions::ALLOW_LET)
                    },
                    {

                        #[allow(deprecated, non_upper_case_globals,)]
                        ::bitflags::Flag::new("IN_IF_GUARD",
                            Restrictions::IN_IF_GUARD)
                    },
                    {

                        #[allow(deprecated, non_upper_case_globals,)]
                        ::bitflags::Flag::new("IS_PAT", Restrictions::IS_PAT)
                    }];
    type Bits = u8;
    fn bits(&self) -> u8 { Restrictions::bits(self) }
    fn from_bits_retain(bits: u8) -> Restrictions {
        Restrictions::from_bits_retain(bits)
    }
}
#[allow(dead_code, deprecated, unused_doc_comments, unused_attributes,
unused_mut, unused_imports, non_upper_case_globals, clippy ::
assign_op_pattern, clippy :: indexing_slicing, clippy :: same_name_method,
clippy :: iter_without_into_iter,)]
const _: () =
    {
        #[repr(transparent)]
        struct InternalBitFlags(u8);
        #[automatically_derived]
        #[doc(hidden)]
        unsafe impl ::core::clone::TrivialClone for InternalBitFlags { }
        #[automatically_derived]
        impl ::core::clone::Clone for InternalBitFlags {
            #[inline]
            fn clone(&self) -> InternalBitFlags {
                let _: ::core::clone::AssertParamIsClone<u8>;
                *self
            }
        }
        #[automatically_derived]
        impl ::core::marker::Copy for InternalBitFlags { }
        #[automatically_derived]
        impl ::core::marker::StructuralPartialEq for InternalBitFlags { }
        #[automatically_derived]
        impl ::core::cmp::PartialEq for InternalBitFlags {
            #[inline]
            fn eq(&self, other: &InternalBitFlags) -> bool {
                self.0 == other.0
            }
        }
        #[automatically_derived]
        impl ::core::cmp::Eq for InternalBitFlags {
            #[inline]
            #[doc(hidden)]
            #[coverage(off)]
            fn assert_receiver_is_total_eq(&self) {
                let _: ::core::cmp::AssertParamIsEq<u8>;
            }
        }
        #[automatically_derived]
        impl ::core::cmp::PartialOrd for InternalBitFlags {
            #[inline]
            fn partial_cmp(&self, other: &InternalBitFlags)
                -> ::core::option::Option<::core::cmp::Ordering> {
                ::core::cmp::PartialOrd::partial_cmp(&self.0, &other.0)
            }
        }
        #[automatically_derived]
        impl ::core::cmp::Ord for InternalBitFlags {
            #[inline]
            fn cmp(&self, other: &InternalBitFlags) -> ::core::cmp::Ordering {
                ::core::cmp::Ord::cmp(&self.0, &other.0)
            }
        }
        #[automatically_derived]
        impl ::core::hash::Hash for InternalBitFlags {
            #[inline]
            fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
                ::core::hash::Hash::hash(&self.0, state)
            }
        }
        impl ::bitflags::__private::PublicFlags for Restrictions {
            type Primitive = u8;
            type Internal = InternalBitFlags;
        }
        impl ::bitflags::__private::core::default::Default for
            InternalBitFlags {
            #[inline]
            fn default() -> Self { InternalBitFlags::empty() }
        }
        impl ::bitflags::__private::core::fmt::Debug for InternalBitFlags {
            fn fmt(&self,
                f: &mut ::bitflags::__private::core::fmt::Formatter<'_>)
                -> ::bitflags::__private::core::fmt::Result {
                if self.is_empty() {
                    f.write_fmt(format_args!("{0:#x}",
                            <u8 as ::bitflags::Bits>::EMPTY))
                } else {
                    ::bitflags::__private::core::fmt::Display::fmt(self, f)
                }
            }
        }
        impl ::bitflags::__private::core::fmt::Display for InternalBitFlags {
            fn fmt(&self,
                f: &mut ::bitflags::__private::core::fmt::Formatter<'_>)
                -> ::bitflags::__private::core::fmt::Result {
                ::bitflags::parser::to_writer(&Restrictions(*self), f)
            }
        }
        impl ::bitflags::__private::core::str::FromStr for InternalBitFlags {
            type Err = ::bitflags::parser::ParseError;
            fn from_str(s: &str)
                ->
                    ::bitflags::__private::core::result::Result<Self,
                    Self::Err> {
                ::bitflags::parser::from_str::<Restrictions>(s).map(|flags|
                        flags.0)
            }
        }
        impl ::bitflags::__private::core::convert::AsRef<u8> for
            InternalBitFlags {
            fn as_ref(&self) -> &u8 { &self.0 }
        }
        impl ::bitflags::__private::core::convert::From<u8> for
            InternalBitFlags {
            fn from(bits: u8) -> Self { Self::from_bits_retain(bits) }
        }
        #[allow(dead_code, deprecated, unused_attributes)]
        impl InternalBitFlags {
            /// Get a flags value with all bits unset.
            #[inline]
            pub const fn empty() -> Self {
                Self(<u8 as ::bitflags::Bits>::EMPTY)
            }
            /// Get a flags value with all known bits set.
            #[inline]
            pub const fn all() -> Self {
                let mut truncated = <u8 as ::bitflags::Bits>::EMPTY;
                let mut i = 0;
                {
                    {
                        let flag =
                            <Restrictions as
                                            ::bitflags::Flags>::FLAGS[i].value().bits();
                        truncated = truncated | flag;
                        i += 1;
                    }
                };
                {
                    {
                        let flag =
                            <Restrictions as
                                            ::bitflags::Flags>::FLAGS[i].value().bits();
                        truncated = truncated | flag;
                        i += 1;
                    }
                };
                {
                    {
                        let flag =
                            <Restrictions as
                                            ::bitflags::Flags>::FLAGS[i].value().bits();
                        truncated = truncated | flag;
                        i += 1;
                    }
                };
                {
                    {
                        let flag =
                            <Restrictions as
                                            ::bitflags::Flags>::FLAGS[i].value().bits();
                        truncated = truncated | flag;
                        i += 1;
                    }
                };
                {
                    {
                        let flag =
                            <Restrictions as
                                            ::bitflags::Flags>::FLAGS[i].value().bits();
                        truncated = truncated | flag;
                        i += 1;
                    }
                };
                {
                    {
                        let flag =
                            <Restrictions as
                                            ::bitflags::Flags>::FLAGS[i].value().bits();
                        truncated = truncated | flag;
                        i += 1;
                    }
                };
                let _ = i;
                Self(truncated)
            }
            /// Get the underlying bits value.
            ///
            /// The returned value is exactly the bits set in this flags value.
            #[inline]
            pub const fn bits(&self) -> u8 { self.0 }
            /// Convert from a bits value.
            ///
            /// This method will return `None` if any unknown bits are set.
            #[inline]
            pub const fn from_bits(bits: u8)
                -> ::bitflags::__private::core::option::Option<Self> {
                let truncated = Self::from_bits_truncate(bits).0;
                if truncated == bits {
                    ::bitflags::__private::core::option::Option::Some(Self(bits))
                } else { ::bitflags::__private::core::option::Option::None }
            }
            /// Convert from a bits value, unsetting any unknown bits.
            #[inline]
            pub const fn from_bits_truncate(bits: u8) -> Self {
                Self(bits & Self::all().0)
            }
            /// Convert from a bits value exactly.
            #[inline]
            pub const fn from_bits_retain(bits: u8) -> Self { Self(bits) }
            /// Get a flags value with the bits of a flag with the given name set.
            ///
            /// This method will return `None` if `name` is empty or doesn't
            /// correspond to any named flag.
            #[inline]
            pub fn from_name(name: &str)
                -> ::bitflags::__private::core::option::Option<Self> {
                {
                    if name == "STMT_EXPR" {
                        return ::bitflags::__private::core::option::Option::Some(Self(Restrictions::STMT_EXPR.bits()));
                    }
                };
                ;
                {
                    if name == "NO_STRUCT_LITERAL" {
                        return ::bitflags::__private::core::option::Option::Some(Self(Restrictions::NO_STRUCT_LITERAL.bits()));
                    }
                };
                ;
                {
                    if name == "CONST_EXPR" {
                        return ::bitflags::__private::core::option::Option::Some(Self(Restrictions::CONST_EXPR.bits()));
                    }
                };
                ;
                {
                    if name == "ALLOW_LET" {
                        return ::bitflags::__private::core::option::Option::Some(Self(Restrictions::ALLOW_LET.bits()));
                    }
                };
                ;
                {
                    if name == "IN_IF_GUARD" {
                        return ::bitflags::__private::core::option::Option::Some(Self(Restrictions::IN_IF_GUARD.bits()));
                    }
                };
                ;
                {
                    if name == "IS_PAT" {
                        return ::bitflags::__private::core::option::Option::Some(Self(Restrictions::IS_PAT.bits()));
                    }
                };
                ;
                let _ = name;
                ::bitflags::__private::core::option::Option::None
            }
            /// Whether all bits in this flags value are unset.
            #[inline]
            pub const fn is_empty(&self) -> bool {
                self.0 == <u8 as ::bitflags::Bits>::EMPTY
            }
            /// Whether all known bits in this flags value are set.
            #[inline]
            pub const fn is_all(&self) -> bool {
                Self::all().0 | self.0 == self.0
            }
            /// Whether any set bits in a source flags value are also set in a target flags value.
            #[inline]
            pub const fn intersects(&self, other: Self) -> bool {
                self.0 & other.0 != <u8 as ::bitflags::Bits>::EMPTY
            }
            /// Whether all set bits in a source flags value are also set in a target flags value.
            #[inline]
            pub const fn contains(&self, other: Self) -> bool {
                self.0 & other.0 == other.0
            }
            /// The bitwise or (`|`) of the bits in two flags values.
            #[inline]
            pub fn insert(&mut self, other: Self) {
                *self = Self(self.0).union(other);
            }
            /// The intersection of a source flags value with the complement of a target flags
            /// value (`&!`).
            ///
            /// This method is not equivalent to `self & !other` when `other` has unknown bits set.
            /// `remove` won't truncate `other`, but the `!` operator will.
            #[inline]
            pub fn remove(&mut self, other: Self) {
                *self = Self(self.0).difference(other);
            }
            /// The bitwise exclusive-or (`^`) of the bits in two flags values.
            #[inline]
            pub fn toggle(&mut self, other: Self) {
                *self = Self(self.0).symmetric_difference(other);
            }
            /// Call `insert` when `value` is `true` or `remove` when `value` is `false`.
            #[inline]
            pub fn set(&mut self, other: Self, value: bool) {
                if value { self.insert(other); } else { self.remove(other); }
            }
            /// The bitwise and (`&`) of the bits in two flags values.
            #[inline]
            #[must_use]
            pub const fn intersection(self, other: Self) -> Self {
                Self(self.0 & other.0)
            }
            /// The bitwise or (`|`) of the bits in two flags values.
            #[inline]
            #[must_use]
            pub const fn union(self, other: Self) -> Self {
                Self(self.0 | other.0)
            }
            /// The intersection of a source flags value with the complement of a target flags
            /// value (`&!`).
            ///
            /// This method is not equivalent to `self & !other` when `other` has unknown bits set.
            /// `difference` won't truncate `other`, but the `!` operator will.
            #[inline]
            #[must_use]
            pub const fn difference(self, other: Self) -> Self {
                Self(self.0 & !other.0)
            }
            /// The bitwise exclusive-or (`^`) of the bits in two flags values.
            #[inline]
            #[must_use]
            pub const fn symmetric_difference(self, other: Self) -> Self {
                Self(self.0 ^ other.0)
            }
            /// The bitwise negation (`!`) of the bits in a flags value, truncating the result.
            #[inline]
            #[must_use]
            pub const fn complement(self) -> Self {
                Self::from_bits_truncate(!self.0)
            }
        }
        impl ::bitflags::__private::core::fmt::Binary for InternalBitFlags {
            fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
                -> ::bitflags::__private::core::fmt::Result {
                let inner = self.0;
                ::bitflags::__private::core::fmt::Binary::fmt(&inner, f)
            }
        }
        impl ::bitflags::__private::core::fmt::Octal for InternalBitFlags {
            fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
                -> ::bitflags::__private::core::fmt::Result {
                let inner = self.0;
                ::bitflags::__private::core::fmt::Octal::fmt(&inner, f)
            }
        }
        impl ::bitflags::__private::core::fmt::LowerHex for InternalBitFlags {
            fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
                -> ::bitflags::__private::core::fmt::Result {
                let inner = self.0;
                ::bitflags::__private::core::fmt::LowerHex::fmt(&inner, f)
            }
        }
        impl ::bitflags::__private::core::fmt::UpperHex for InternalBitFlags {
            fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
                -> ::bitflags::__private::core::fmt::Result {
                let inner = self.0;
                ::bitflags::__private::core::fmt::UpperHex::fmt(&inner, f)
            }
        }
        impl ::bitflags::__private::core::ops::BitOr for InternalBitFlags {
            type Output = Self;
            /// The bitwise or (`|`) of the bits in two flags values.
            #[inline]
            fn bitor(self, other: InternalBitFlags) -> Self {
                self.union(other)
            }
        }
        impl ::bitflags::__private::core::ops::BitOrAssign for
            InternalBitFlags {
            /// The bitwise or (`|`) of the bits in two flags values.
            #[inline]
            fn bitor_assign(&mut self, other: Self) { self.insert(other); }
        }
        impl ::bitflags::__private::core::ops::BitXor for InternalBitFlags {
            type Output = Self;
            /// The bitwise exclusive-or (`^`) of the bits in two flags values.
            #[inline]
            fn bitxor(self, other: Self) -> Self {
                self.symmetric_difference(other)
            }
        }
        impl ::bitflags::__private::core::ops::BitXorAssign for
            InternalBitFlags {
            /// The bitwise exclusive-or (`^`) of the bits in two flags values.
            #[inline]
            fn bitxor_assign(&mut self, other: Self) { self.toggle(other); }
        }
        impl ::bitflags::__private::core::ops::BitAnd for InternalBitFlags {
            type Output = Self;
            /// The bitwise and (`&`) of the bits in two flags values.
            #[inline]
            fn bitand(self, other: Self) -> Self { self.intersection(other) }
        }
        impl ::bitflags::__private::core::ops::BitAndAssign for
            InternalBitFlags {
            /// The bitwise and (`&`) of the bits in two flags values.
            #[inline]
            fn bitand_assign(&mut self, other: Self) {
                *self =
                    Self::from_bits_retain(self.bits()).intersection(other);
            }
        }
        impl ::bitflags::__private::core::ops::Sub for InternalBitFlags {
            type Output = Self;
            /// The intersection of a source flags value with the complement of a target flags value (`&!`).
            ///
            /// This method is not equivalent to `self & !other` when `other` has unknown bits set.
            /// `difference` won't truncate `other`, but the `!` operator will.
            #[inline]
            fn sub(self, other: Self) -> Self { self.difference(other) }
        }
        impl ::bitflags::__private::core::ops::SubAssign for InternalBitFlags
            {
            /// The intersection of a source flags value with the complement of a target flags value (`&!`).
            ///
            /// This method is not equivalent to `self & !other` when `other` has unknown bits set.
            /// `difference` won't truncate `other`, but the `!` operator will.
            #[inline]
            fn sub_assign(&mut self, other: Self) { self.remove(other); }
        }
        impl ::bitflags::__private::core::ops::Not for InternalBitFlags {
            type Output = Self;
            /// The bitwise negation (`!`) of the bits in a flags value, truncating the result.
            #[inline]
            fn not(self) -> Self { self.complement() }
        }
        impl ::bitflags::__private::core::iter::Extend<InternalBitFlags> for
            InternalBitFlags {
            /// The bitwise or (`|`) of the bits in each flags value.
            fn extend<T: ::bitflags::__private::core::iter::IntoIterator<Item
                = Self>>(&mut self, iterator: T) {
                for item in iterator { self.insert(item) }
            }
        }
        impl ::bitflags::__private::core::iter::FromIterator<InternalBitFlags>
            for InternalBitFlags {
            /// The bitwise or (`|`) of the bits in each flags value.
            fn from_iter<T: ::bitflags::__private::core::iter::IntoIterator<Item
                = Self>>(iterator: T) -> Self {
                use ::bitflags::__private::core::iter::Extend;
                let mut result = Self::empty();
                result.extend(iterator);
                result
            }
        }
        impl InternalBitFlags {
            /// Yield a set of contained flags values.
            ///
            /// Each yielded flags value will correspond to a defined named flag. Any unknown bits
            /// will be yielded together as a final flags value.
            #[inline]
            pub const fn iter(&self) -> ::bitflags::iter::Iter<Restrictions> {
                ::bitflags::iter::Iter::__private_const_new(<Restrictions as
                        ::bitflags::Flags>::FLAGS,
                    Restrictions::from_bits_retain(self.bits()),
                    Restrictions::from_bits_retain(self.bits()))
            }
            /// Yield a set of contained named flags values.
            ///
            /// This method is like [`iter`](#method.iter), except only yields bits in contained named flags.
            /// Any unknown bits, or bits not corresponding to a contained flag will not be yielded.
            #[inline]
            pub const fn iter_names(&self)
                -> ::bitflags::iter::IterNames<Restrictions> {
                ::bitflags::iter::IterNames::__private_const_new(<Restrictions
                        as ::bitflags::Flags>::FLAGS,
                    Restrictions::from_bits_retain(self.bits()),
                    Restrictions::from_bits_retain(self.bits()))
            }
        }
        impl ::bitflags::__private::core::iter::IntoIterator for
            InternalBitFlags {
            type Item = Restrictions;
            type IntoIter = ::bitflags::iter::Iter<Restrictions>;
            fn into_iter(self) -> Self::IntoIter { self.iter() }
        }
        impl InternalBitFlags {
            /// Returns a mutable reference to the raw value of the flags currently stored.
            #[inline]
            pub fn bits_mut(&mut self) -> &mut u8 { &mut self.0 }
        }
        #[allow(dead_code, deprecated, unused_attributes)]
        impl Restrictions {
            /// Get a flags value with all bits unset.
            #[inline]
            pub const fn empty() -> Self { Self(InternalBitFlags::empty()) }
            /// Get a flags value with all known bits set.
            #[inline]
            pub const fn all() -> Self { Self(InternalBitFlags::all()) }
            /// Get the underlying bits value.
            ///
            /// The returned value is exactly the bits set in this flags value.
            #[inline]
            pub const fn bits(&self) -> u8 { self.0.bits() }
            /// Convert from a bits value.
            ///
            /// This method will return `None` if any unknown bits are set.
            #[inline]
            pub const fn from_bits(bits: u8)
                -> ::bitflags::__private::core::option::Option<Self> {
                match InternalBitFlags::from_bits(bits) {
                    ::bitflags::__private::core::option::Option::Some(bits) =>
                        ::bitflags::__private::core::option::Option::Some(Self(bits)),
                    ::bitflags::__private::core::option::Option::None =>
                        ::bitflags::__private::core::option::Option::None,
                }
            }
            /// Convert from a bits value, unsetting any unknown bits.
            #[inline]
            pub const fn from_bits_truncate(bits: u8) -> Self {
                Self(InternalBitFlags::from_bits_truncate(bits))
            }
            /// Convert from a bits value exactly.
            #[inline]
            pub const fn from_bits_retain(bits: u8) -> Self {
                Self(InternalBitFlags::from_bits_retain(bits))
            }
            /// Get a flags value with the bits of a flag with the given name set.
            ///
            /// This method will return `None` if `name` is empty or doesn't
            /// correspond to any named flag.
            #[inline]
            pub fn from_name(name: &str)
                -> ::bitflags::__private::core::option::Option<Self> {
                match InternalBitFlags::from_name(name) {
                    ::bitflags::__private::core::option::Option::Some(bits) =>
                        ::bitflags::__private::core::option::Option::Some(Self(bits)),
                    ::bitflags::__private::core::option::Option::None =>
                        ::bitflags::__private::core::option::Option::None,
                }
            }
            /// Whether all bits in this flags value are unset.
            #[inline]
            pub const fn is_empty(&self) -> bool { self.0.is_empty() }
            /// Whether all known bits in this flags value are set.
            #[inline]
            pub const fn is_all(&self) -> bool { self.0.is_all() }
            /// Whether any set bits in a source flags value are also set in a target flags value.
            #[inline]
            pub const fn intersects(&self, other: Self) -> bool {
                self.0.intersects(other.0)
            }
            /// Whether all set bits in a source flags value are also set in a target flags value.
            #[inline]
            pub const fn contains(&self, other: Self) -> bool {
                self.0.contains(other.0)
            }
            /// The bitwise or (`|`) of the bits in two flags values.
            #[inline]
            pub fn insert(&mut self, other: Self) { self.0.insert(other.0) }
            /// The intersection of a source flags value with the complement of a target flags
            /// value (`&!`).
            ///
            /// This method is not equivalent to `self & !other` when `other` has unknown bits set.
            /// `remove` won't truncate `other`, but the `!` operator will.
            #[inline]
            pub fn remove(&mut self, other: Self) { self.0.remove(other.0) }
            /// The bitwise exclusive-or (`^`) of the bits in two flags values.
            #[inline]
            pub fn toggle(&mut self, other: Self) { self.0.toggle(other.0) }
            /// Call `insert` when `value` is `true` or `remove` when `value` is `false`.
            #[inline]
            pub fn set(&mut self, other: Self, value: bool) {
                self.0.set(other.0, value)
            }
            /// The bitwise and (`&`) of the bits in two flags values.
            #[inline]
            #[must_use]
            pub const fn intersection(self, other: Self) -> Self {
                Self(self.0.intersection(other.0))
            }
            /// The bitwise or (`|`) of the bits in two flags values.
            #[inline]
            #[must_use]
            pub const fn union(self, other: Self) -> Self {
                Self(self.0.union(other.0))
            }
            /// The intersection of a source flags value with the complement of a target flags
            /// value (`&!`).
            ///
            /// This method is not equivalent to `self & !other` when `other` has unknown bits set.
            /// `difference` won't truncate `other`, but the `!` operator will.
            #[inline]
            #[must_use]
            pub const fn difference(self, other: Self) -> Self {
                Self(self.0.difference(other.0))
            }
            /// The bitwise exclusive-or (`^`) of the bits in two flags values.
            #[inline]
            #[must_use]
            pub const fn symmetric_difference(self, other: Self) -> Self {
                Self(self.0.symmetric_difference(other.0))
            }
            /// The bitwise negation (`!`) of the bits in a flags value, truncating the result.
            #[inline]
            #[must_use]
            pub const fn complement(self) -> Self {
                Self(self.0.complement())
            }
        }
        impl ::bitflags::__private::core::fmt::Binary for Restrictions {
            fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
                -> ::bitflags::__private::core::fmt::Result {
                let inner = self.0;
                ::bitflags::__private::core::fmt::Binary::fmt(&inner, f)
            }
        }
        impl ::bitflags::__private::core::fmt::Octal for Restrictions {
            fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
                -> ::bitflags::__private::core::fmt::Result {
                let inner = self.0;
                ::bitflags::__private::core::fmt::Octal::fmt(&inner, f)
            }
        }
        impl ::bitflags::__private::core::fmt::LowerHex for Restrictions {
            fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
                -> ::bitflags::__private::core::fmt::Result {
                let inner = self.0;
                ::bitflags::__private::core::fmt::LowerHex::fmt(&inner, f)
            }
        }
        impl ::bitflags::__private::core::fmt::UpperHex for Restrictions {
            fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
                -> ::bitflags::__private::core::fmt::Result {
                let inner = self.0;
                ::bitflags::__private::core::fmt::UpperHex::fmt(&inner, f)
            }
        }
        impl ::bitflags::__private::core::ops::BitOr for Restrictions {
            type Output = Self;
            /// The bitwise or (`|`) of the bits in two flags values.
            #[inline]
            fn bitor(self, other: Restrictions) -> Self { self.union(other) }
        }
        impl ::bitflags::__private::core::ops::BitOrAssign for Restrictions {
            /// The bitwise or (`|`) of the bits in two flags values.
            #[inline]
            fn bitor_assign(&mut self, other: Self) { self.insert(other); }
        }
        impl ::bitflags::__private::core::ops::BitXor for Restrictions {
            type Output = Self;
            /// The bitwise exclusive-or (`^`) of the bits in two flags values.
            #[inline]
            fn bitxor(self, other: Self) -> Self {
                self.symmetric_difference(other)
            }
        }
        impl ::bitflags::__private::core::ops::BitXorAssign for Restrictions {
            /// The bitwise exclusive-or (`^`) of the bits in two flags values.
            #[inline]
            fn bitxor_assign(&mut self, other: Self) { self.toggle(other); }
        }
        impl ::bitflags::__private::core::ops::BitAnd for Restrictions {
            type Output = Self;
            /// The bitwise and (`&`) of the bits in two flags values.
            #[inline]
            fn bitand(self, other: Self) -> Self { self.intersection(other) }
        }
        impl ::bitflags::__private::core::ops::BitAndAssign for Restrictions {
            /// The bitwise and (`&`) of the bits in two flags values.
            #[inline]
            fn bitand_assign(&mut self, other: Self) {
                *self =
                    Self::from_bits_retain(self.bits()).intersection(other);
            }
        }
        impl ::bitflags::__private::core::ops::Sub for Restrictions {
            type Output = Self;
            /// The intersection of a source flags value with the complement of a target flags value (`&!`).
            ///
            /// This method is not equivalent to `self & !other` when `other` has unknown bits set.
            /// `difference` won't truncate `other`, but the `!` operator will.
            #[inline]
            fn sub(self, other: Self) -> Self { self.difference(other) }
        }
        impl ::bitflags::__private::core::ops::SubAssign for Restrictions {
            /// The intersection of a source flags value with the complement of a target flags value (`&!`).
            ///
            /// This method is not equivalent to `self & !other` when `other` has unknown bits set.
            /// `difference` won't truncate `other`, but the `!` operator will.
            #[inline]
            fn sub_assign(&mut self, other: Self) { self.remove(other); }
        }
        impl ::bitflags::__private::core::ops::Not for Restrictions {
            type Output = Self;
            /// The bitwise negation (`!`) of the bits in a flags value, truncating the result.
            #[inline]
            fn not(self) -> Self { self.complement() }
        }
        impl ::bitflags::__private::core::iter::Extend<Restrictions> for
            Restrictions {
            /// The bitwise or (`|`) of the bits in each flags value.
            fn extend<T: ::bitflags::__private::core::iter::IntoIterator<Item
                = Self>>(&mut self, iterator: T) {
                for item in iterator { self.insert(item) }
            }
        }
        impl ::bitflags::__private::core::iter::FromIterator<Restrictions> for
            Restrictions {
            /// The bitwise or (`|`) of the bits in each flags value.
            fn from_iter<T: ::bitflags::__private::core::iter::IntoIterator<Item
                = Self>>(iterator: T) -> Self {
                use ::bitflags::__private::core::iter::Extend;
                let mut result = Self::empty();
                result.extend(iterator);
                result
            }
        }
        impl Restrictions {
            /// Yield a set of contained flags values.
            ///
            /// Each yielded flags value will correspond to a defined named flag. Any unknown bits
            /// will be yielded together as a final flags value.
            #[inline]
            pub const fn iter(&self) -> ::bitflags::iter::Iter<Restrictions> {
                ::bitflags::iter::Iter::__private_const_new(<Restrictions as
                        ::bitflags::Flags>::FLAGS,
                    Restrictions::from_bits_retain(self.bits()),
                    Restrictions::from_bits_retain(self.bits()))
            }
            /// Yield a set of contained named flags values.
            ///
            /// This method is like [`iter`](#method.iter), except only yields bits in contained named flags.
            /// Any unknown bits, or bits not corresponding to a contained flag will not be yielded.
            #[inline]
            pub const fn iter_names(&self)
                -> ::bitflags::iter::IterNames<Restrictions> {
                ::bitflags::iter::IterNames::__private_const_new(<Restrictions
                        as ::bitflags::Flags>::FLAGS,
                    Restrictions::from_bits_retain(self.bits()),
                    Restrictions::from_bits_retain(self.bits()))
            }
        }
        impl ::bitflags::__private::core::iter::IntoIterator for Restrictions
            {
            type Item = Restrictions;
            type IntoIter = ::bitflags::iter::Iter<Restrictions>;
            fn into_iter(self) -> Self::IntoIter { self.iter() }
        }
    };Clone, #[automatically_derived]
impl ::core::marker::Copy for Restrictions { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for Restrictions {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Restrictions",
            &&self.0)
    }
}Debug)]
72    struct Restrictions: u8 {
73        /// Restricts expressions for use in statement position.
74        ///
75        /// When expressions are used in various places, like statements or
76        /// match arms, this is used to stop parsing once certain tokens are
77        /// reached.
78        ///
79        /// For example, `if true {} & 1` with `STMT_EXPR` in effect is parsed
80        /// as two separate expression statements (`if` and a reference to 1).
81        /// Otherwise it is parsed as a bitwise AND where `if` is on the left
82        /// and 1 is on the right.
83        const STMT_EXPR         = 1 << 0;
84        /// Do not allow struct literals.
85        ///
86        /// There are several places in the grammar where we don't want to
87        /// allow struct literals because they can require lookahead, or
88        /// otherwise could be ambiguous or cause confusion. For example,
89        /// `if Foo {} {}` isn't clear if it is `Foo{}` struct literal, or
90        /// just `Foo` is the condition, followed by a consequent block,
91        /// followed by an empty block.
92        ///
93        /// See [RFC 92](https://rust-lang.github.io/rfcs/0092-struct-grammar.html).
94        const NO_STRUCT_LITERAL = 1 << 1;
95        /// Used to provide better error messages for const generic arguments.
96        ///
97        /// An un-braced const generic argument is limited to a very small
98        /// subset of expressions. This is used to detect the situation where
99        /// an expression outside of that subset is used, and to suggest to
100        /// wrap the expression in braces.
101        const CONST_EXPR        = 1 << 2;
102        /// Allows `let` expressions.
103        ///
104        /// `let pattern = scrutinee` is parsed as an expression, but it is
105        /// only allowed in let chains (`if` and `while` conditions).
106        /// Otherwise it is not an expression (note that `let` in statement
107        /// positions is treated as a `StmtKind::Let` statement, which has a
108        /// slightly different grammar).
109        const ALLOW_LET         = 1 << 3;
110        /// Used to detect a missing `=>` in a match guard.
111        ///
112        /// This is used for error handling in a match guard to give a better
113        /// error message if the `=>` is missing. It is set when parsing the
114        /// guard expression.
115        const IN_IF_GUARD       = 1 << 4;
116        /// Used to detect the incorrect use of expressions in patterns.
117        ///
118        /// This is used for error handling while parsing a pattern. During
119        /// error recovery, this will be set to try to parse the pattern as an
120        /// expression, but halts parsing the expression when reaching certain
121        /// tokens like `=`.
122        const IS_PAT            = 1 << 5;
123    }
124}
125
126#[derive(#[automatically_derived]
impl ::core::clone::Clone for SemiColonMode {
    #[inline]
    fn clone(&self) -> SemiColonMode { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for SemiColonMode { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for SemiColonMode {
    #[inline]
    fn eq(&self, other: &SemiColonMode) -> 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::fmt::Debug for SemiColonMode {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                SemiColonMode::Break => "Break",
                SemiColonMode::Ignore => "Ignore",
                SemiColonMode::Comma => "Comma",
            })
    }
}Debug)]
127enum SemiColonMode {
128    Break,
129    Ignore,
130    Comma,
131}
132
133#[derive(#[automatically_derived]
impl ::core::clone::Clone for BlockMode {
    #[inline]
    fn clone(&self) -> BlockMode { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for BlockMode { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for BlockMode {
    #[inline]
    fn eq(&self, other: &BlockMode) -> 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::fmt::Debug for BlockMode {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                BlockMode::Break => "Break",
                BlockMode::Ignore => "Ignore",
            })
    }
}Debug)]
134enum BlockMode {
135    Break,
136    Ignore,
137}
138
139/// Whether or not we should force collection of tokens for an AST node,
140/// regardless of whether or not it has attributes
141#[derive(#[automatically_derived]
impl ::core::clone::Clone for ForceCollect {
    #[inline]
    fn clone(&self) -> ForceCollect { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for ForceCollect { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for ForceCollect {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                ForceCollect::Yes => "Yes",
                ForceCollect::No => "No",
            })
    }
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for ForceCollect {
    #[inline]
    fn eq(&self, other: &ForceCollect) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq)]
142pub enum ForceCollect {
143    Yes,
144    No,
145}
146
147/// Whether to accept `const { ... }` as a shorthand for `const _: () = const { ... }`.
148#[derive(#[automatically_derived]
impl ::core::clone::Clone for AllowConstBlockItems {
    #[inline]
    fn clone(&self) -> AllowConstBlockItems { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for AllowConstBlockItems { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for AllowConstBlockItems {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                AllowConstBlockItems::Yes => "Yes",
                AllowConstBlockItems::No => "No",
                AllowConstBlockItems::DoesNotMatter => "DoesNotMatter",
            })
    }
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for AllowConstBlockItems {
    #[inline]
    fn eq(&self, other: &AllowConstBlockItems) -> 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 AllowConstBlockItems {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_receiver_is_total_eq(&self) {}
}Eq)]
149pub enum AllowConstBlockItems {
150    Yes,
151    No,
152    DoesNotMatter,
153}
154
155/// If the next tokens are ill-formed `$ty::` recover them as `<$ty>::`.
156#[macro_export]
157macro_rules! maybe_recover_from_interpolated_ty_qpath {
158    ($self: expr, $allow_qpath_recovery: expr) => {
159        if $allow_qpath_recovery
160            && $self.may_recover()
161            && let Some(mv_kind) = $self.token.is_metavar_seq()
162            && let token::MetaVarKind::Ty { .. } = mv_kind
163            && $self.check_noexpect_past_close_delim(&token::PathSep)
164        {
165            // Reparse the type, then move to recovery.
166            let ty = $self
167                .eat_metavar_seq(mv_kind, |this| this.parse_ty_no_question_mark_recover())
168                .expect("metavar seq ty");
169
170            return $self.maybe_recover_from_bad_qpath_stage_2($self.prev_token.span, ty);
171        }
172    };
173}
174
175#[derive(#[automatically_derived]
impl ::core::clone::Clone for Recovery {
    #[inline]
    fn clone(&self) -> Recovery { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for Recovery { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for Recovery {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                Recovery::Allowed => "Allowed",
                Recovery::Forbidden => "Forbidden",
            })
    }
}Debug)]
176pub enum Recovery {
177    Allowed,
178    Forbidden,
179}
180
181#[derive(#[automatically_derived]
impl<'a> ::core::clone::Clone for Parser<'a> {
    #[inline]
    fn clone(&self) -> Parser<'a> {
        Parser {
            psess: ::core::clone::Clone::clone(&self.psess),
            token: ::core::clone::Clone::clone(&self.token),
            token_spacing: ::core::clone::Clone::clone(&self.token_spacing),
            prev_token: ::core::clone::Clone::clone(&self.prev_token),
            capture_cfg: ::core::clone::Clone::clone(&self.capture_cfg),
            restrictions: ::core::clone::Clone::clone(&self.restrictions),
            expected_token_types: ::core::clone::Clone::clone(&self.expected_token_types),
            token_cursor: ::core::clone::Clone::clone(&self.token_cursor),
            num_bump_calls: ::core::clone::Clone::clone(&self.num_bump_calls),
            break_last_token: ::core::clone::Clone::clone(&self.break_last_token),
            unmatched_angle_bracket_count: ::core::clone::Clone::clone(&self.unmatched_angle_bracket_count),
            angle_bracket_nesting: ::core::clone::Clone::clone(&self.angle_bracket_nesting),
            parsing_generics: ::core::clone::Clone::clone(&self.parsing_generics),
            last_unexpected_token_span: ::core::clone::Clone::clone(&self.last_unexpected_token_span),
            subparser_name: ::core::clone::Clone::clone(&self.subparser_name),
            capture_state: ::core::clone::Clone::clone(&self.capture_state),
            current_closure: ::core::clone::Clone::clone(&self.current_closure),
            recovery: ::core::clone::Clone::clone(&self.recovery),
        }
    }
}Clone)]
182pub struct Parser<'a> {
183    pub psess: &'a ParseSess,
184    /// The current token.
185    pub token: Token = Token::dummy(),
186    /// The spacing for the current token.
187    token_spacing: Spacing = Spacing::Alone,
188    /// The previous token.
189    pub prev_token: Token = Token::dummy(),
190    pub capture_cfg: bool = false,
191    restrictions: Restrictions = Restrictions::empty(),
192    expected_token_types: TokenTypeSet = TokenTypeSet::new(),
193    token_cursor: TokenCursor,
194    // The number of calls to `bump`, i.e. the position in the token stream.
195    num_bump_calls: u32 = 0,
196    // During parsing we may sometimes need to "unglue" a glued token into two
197    // or three component tokens (e.g. `>>` into `>` and `>`, or `>>=` into `>`
198    // and `>` and `=`), so the parser can consume them one at a time. This
199    // process bypasses the normal capturing mechanism (e.g. `num_bump_calls`
200    // will not be incremented), since the "unglued" tokens due not exist in
201    // the original `TokenStream`.
202    //
203    // If we end up consuming all the component tokens, this is not an issue,
204    // because we'll end up capturing the single "glued" token.
205    //
206    // However, sometimes we may want to capture not all of the original
207    // token. For example, capturing the `Vec<u8>` in `Option<Vec<u8>>`
208    // requires us to unglue the trailing `>>` token. The `break_last_token`
209    // field is used to track these tokens. They get appended to the captured
210    // stream when we evaluate a `LazyAttrTokenStream`.
211    //
212    // This value is always 0, 1, or 2. It can only reach 2 when splitting
213    // `>>=` or `<<=`.
214    break_last_token: u32 = 0,
215    /// This field is used to keep track of how many left angle brackets we have seen. This is
216    /// required in order to detect extra leading left angle brackets (`<` characters) and error
217    /// appropriately.
218    ///
219    /// See the comments in the `parse_path_segment` function for more details.
220    unmatched_angle_bracket_count: u16 = 0,
221    angle_bracket_nesting: u16 = 0,
222    /// Keep track of when we're within `<...>` for proper error recovery.
223    parsing_generics: bool = false,
224
225    last_unexpected_token_span: Option<Span> = None,
226    /// If present, this `Parser` is not parsing Rust code but rather a macro call.
227    subparser_name: Option<&'static str>,
228    capture_state: CaptureState,
229    /// This allows us to recover when the user forget to add braces around
230    /// multiple statements in the closure body.
231    current_closure: Option<ClosureSpans> = None,
232    /// Whether the parser is allowed to do recovery.
233    /// This is disabled when parsing macro arguments, see #103534
234    recovery: Recovery = Recovery::Allowed,
235}
236
237// This type is used a lot, e.g. it's cloned when matching many declarative macro rules with
238// nonterminals. Make sure it doesn't unintentionally get bigger. We only check a few arches
239// though, because `TokenTypeSet(u128)` alignment varies on others, changing the total size.
240#[cfg(all(target_pointer_width = "64", any(target_arch = "aarch64", target_arch = "x86_64")))]
241const _: [(); 288] = [(); ::std::mem::size_of::<Parser<'_>>()];rustc_data_structures::static_assert_size!(Parser<'_>, 288);
242
243/// Stores span information about a closure.
244#[derive(#[automatically_derived]
impl ::core::clone::Clone for ClosureSpans {
    #[inline]
    fn clone(&self) -> ClosureSpans {
        ClosureSpans {
            whole_closure: ::core::clone::Clone::clone(&self.whole_closure),
            closing_pipe: ::core::clone::Clone::clone(&self.closing_pipe),
            body: ::core::clone::Clone::clone(&self.body),
        }
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for ClosureSpans {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f, "ClosureSpans",
            "whole_closure", &self.whole_closure, "closing_pipe",
            &self.closing_pipe, "body", &&self.body)
    }
}Debug)]
245struct ClosureSpans {
246    whole_closure: Span,
247    closing_pipe: Span,
248    body: Span,
249}
250
251/// Controls how we capture tokens. Capturing can be expensive,
252/// so we try to avoid performing capturing in cases where
253/// we will never need an `AttrTokenStream`.
254#[derive(#[automatically_derived]
impl ::core::marker::Copy for Capturing { }Copy, #[automatically_derived]
impl ::core::clone::Clone for Capturing {
    #[inline]
    fn clone(&self) -> Capturing { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for Capturing {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self { Capturing::No => "No", Capturing::Yes => "Yes", })
    }
}Debug)]
255enum Capturing {
256    /// We aren't performing any capturing - this is the default mode.
257    No,
258    /// We are capturing tokens
259    Yes,
260}
261
262// This state is used by `Parser::collect_tokens`.
263#[derive(#[automatically_derived]
impl ::core::clone::Clone for CaptureState {
    #[inline]
    fn clone(&self) -> CaptureState {
        CaptureState {
            capturing: ::core::clone::Clone::clone(&self.capturing),
            parser_replacements: ::core::clone::Clone::clone(&self.parser_replacements),
            inner_attr_parser_ranges: ::core::clone::Clone::clone(&self.inner_attr_parser_ranges),
            seen_attrs: ::core::clone::Clone::clone(&self.seen_attrs),
        }
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for CaptureState {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field4_finish(f, "CaptureState",
            "capturing", &self.capturing, "parser_replacements",
            &self.parser_replacements, "inner_attr_parser_ranges",
            &self.inner_attr_parser_ranges, "seen_attrs", &&self.seen_attrs)
    }
}Debug)]
264struct CaptureState {
265    capturing: Capturing,
266    parser_replacements: Vec<ParserReplacement>,
267    inner_attr_parser_ranges: FxHashMap<AttrId, ParserRange>,
268    // `IntervalSet` is good for perf because attrs are mostly added to this
269    // set in contiguous ranges.
270    seen_attrs: IntervalSet<AttrId>,
271}
272
273/// A sequence separator.
274#[derive(#[automatically_derived]
impl ::core::fmt::Debug for SeqSep {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "SeqSep", "sep",
            &self.sep, "trailing_sep_allowed", &&self.trailing_sep_allowed)
    }
}Debug)]
275struct SeqSep {
276    /// The separator token.
277    sep: Option<ExpTokenPair>,
278    /// `true` if a trailing separator is allowed.
279    trailing_sep_allowed: bool,
280}
281
282impl SeqSep {
283    fn trailing_allowed(sep: ExpTokenPair) -> SeqSep {
284        SeqSep { sep: Some(sep), trailing_sep_allowed: true }
285    }
286
287    fn none() -> SeqSep {
288        SeqSep { sep: None, trailing_sep_allowed: false }
289    }
290}
291
292#[derive(#[automatically_derived]
impl ::core::fmt::Debug for FollowedByType {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                FollowedByType::Yes => "Yes",
                FollowedByType::No => "No",
            })
    }
}Debug)]
293pub enum FollowedByType {
294    Yes,
295    No,
296}
297
298#[derive(#[automatically_derived]
impl ::core::marker::Copy for Trailing { }Copy, #[automatically_derived]
impl ::core::clone::Clone for Trailing {
    #[inline]
    fn clone(&self) -> Trailing { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for Trailing {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self { Trailing::No => "No", Trailing::Yes => "Yes", })
    }
}Debug)]
299pub enum Trailing {
300    No,
301    Yes,
302}
303
304impl From<bool> for Trailing {
305    fn from(b: bool) -> Trailing {
306        if b { Trailing::Yes } else { Trailing::No }
307    }
308}
309
310pub fn token_descr(token: &Token) -> String {
311    let s = pprust::token_to_string(token).to_string();
312
313    match (TokenDescription::from_token(token), &token.kind) {
314        (Some(TokenDescription::ReservedIdentifier), _) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("reserved identifier `{0}`", s))
    })format!("reserved identifier `{s}`"),
315        (Some(TokenDescription::Keyword), _) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("keyword `{0}`", s))
    })format!("keyword `{s}`"),
316        (Some(TokenDescription::ReservedKeyword), _) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("reserved keyword `{0}`", s))
    })format!("reserved keyword `{s}`"),
317        (Some(TokenDescription::DocComment), _) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("doc comment `{0}`", s))
    })format!("doc comment `{s}`"),
318        // Deliberately doesn't print `s`, which is empty.
319        (Some(TokenDescription::MetaVar(kind)), _) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` metavariable", kind))
    })format!("`{kind}` metavariable"),
320        (None, TokenKind::NtIdent(..)) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("identifier `{0}`", s))
    })format!("identifier `{s}`"),
321        (None, TokenKind::NtLifetime(..)) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("lifetime `{0}`", s))
    })format!("lifetime `{s}`"),
322        (None, _) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", s))
    })format!("`{s}`"),
323    }
324}
325
326impl<'a> Parser<'a> {
327    pub fn new(
328        psess: &'a ParseSess,
329        stream: TokenStream,
330        subparser_name: Option<&'static str>,
331    ) -> Self {
332        let mut parser = Parser {
333            psess,
334            token_cursor: TokenCursor { curr: TokenTreeCursor::new(stream), stack: Vec::new() },
335            subparser_name,
336            capture_state: CaptureState {
337                capturing: Capturing::No,
338                parser_replacements: Vec::new(),
339                inner_attr_parser_ranges: Default::default(),
340                seen_attrs: IntervalSet::new(u32::MAX as usize),
341            },
342            ..
343        };
344
345        // Make parser point to the first token.
346        parser.bump();
347
348        // Change this from 1 back to 0 after the bump. This eases debugging of
349        // `Parser::collect_tokens` because 0-indexed token positions are nicer
350        // than 1-indexed token positions.
351        parser.num_bump_calls = 0;
352
353        parser
354    }
355
356    #[inline]
357    pub fn recovery(mut self, recovery: Recovery) -> Self {
358        self.recovery = recovery;
359        self
360    }
361
362    #[inline]
363    fn with_recovery<T>(&mut self, recovery: Recovery, f: impl FnOnce(&mut Self) -> T) -> T {
364        let old = mem::replace(&mut self.recovery, recovery);
365        let res = f(self);
366        self.recovery = old;
367        res
368    }
369
370    /// Whether the parser is allowed to recover from broken code.
371    ///
372    /// If this returns false, recovering broken code into valid code (especially if this recovery does lookahead)
373    /// is not allowed. All recovery done by the parser must be gated behind this check.
374    ///
375    /// Technically, this only needs to restrict eager recovery by doing lookahead at more tokens.
376    /// But making the distinction is very subtle, and simply forbidding all recovery is a lot simpler to uphold.
377    #[inline]
378    fn may_recover(&self) -> bool {
379        #[allow(non_exhaustive_omitted_patterns)] match self.recovery {
    Recovery::Allowed => true,
    _ => false,
}matches!(self.recovery, Recovery::Allowed)
380    }
381
382    /// Version of [`unexpected`](Parser::unexpected) that "returns" any type in the `Ok`
383    /// (both those functions never return "Ok", and so can lie like that in the type).
384    pub fn unexpected_any<T>(&mut self) -> PResult<'a, T> {
385        match self.expect_one_of(&[], &[]) {
386            Err(e) => Err(e),
387            // We can get `Ok(true)` from `recover_closing_delimiter`
388            // which is called in `expected_one_of_not_found`.
389            Ok(_) => FatalError.raise(),
390        }
391    }
392
393    pub fn unexpected(&mut self) -> PResult<'a, ()> {
394        self.unexpected_any()
395    }
396
397    /// Expects and consumes the token `t`. Signals an error if the next token is not `t`.
398    pub fn expect(&mut self, exp: ExpTokenPair) -> PResult<'a, Recovered> {
399        if self.expected_token_types.is_empty() {
400            if self.token == exp.tok {
401                self.bump();
402                Ok(Recovered::No)
403            } else {
404                self.unexpected_try_recover(&exp.tok)
405            }
406        } else {
407            self.expect_one_of(slice::from_ref(&exp), &[])
408        }
409    }
410
411    /// Expect next token to be edible or inedible token. If edible,
412    /// then consume it; if inedible, then return without consuming
413    /// anything. Signal a fatal error if next token is unexpected.
414    fn expect_one_of(
415        &mut self,
416        edible: &[ExpTokenPair],
417        inedible: &[ExpTokenPair],
418    ) -> PResult<'a, Recovered> {
419        if edible.iter().any(|exp| exp.tok == self.token.kind) {
420            self.bump();
421            Ok(Recovered::No)
422        } else if inedible.iter().any(|exp| exp.tok == self.token.kind) {
423            // leave it in the input
424            Ok(Recovered::No)
425        } else if self.token != token::Eof
426            && self.last_unexpected_token_span == Some(self.token.span)
427        {
428            FatalError.raise();
429        } else {
430            self.expected_one_of_not_found(edible, inedible)
431                .map(|error_guaranteed| Recovered::Yes(error_guaranteed))
432        }
433    }
434
435    // Public for rustfmt usage.
436    pub fn parse_ident(&mut self) -> PResult<'a, Ident> {
437        self.parse_ident_common(self.may_recover())
438    }
439
440    pub(crate) fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, Ident> {
441        let (ident, is_raw) = self.ident_or_err(recover)?;
442
443        if is_raw == IdentIsRaw::No && ident.is_reserved() {
444            let err = self.expected_ident_found_err();
445            if recover {
446                err.emit();
447            } else {
448                return Err(err);
449            }
450        }
451        self.bump();
452        Ok(ident)
453    }
454
455    fn ident_or_err(&mut self, recover: bool) -> PResult<'a, (Ident, IdentIsRaw)> {
456        match self.token.ident() {
457            Some(ident) => Ok(ident),
458            None => self.expected_ident_found(recover),
459        }
460    }
461
462    /// Checks if the next token is `tok`, and returns `true` if so.
463    ///
464    /// This method will automatically add `tok` to `expected_token_types` if `tok` is not
465    /// encountered.
466    #[inline]
467    pub fn check(&mut self, exp: ExpTokenPair) -> bool {
468        let is_present = self.token == exp.tok;
469        if !is_present {
470            self.expected_token_types.insert(exp.token_type);
471        }
472        is_present
473    }
474
475    #[inline]
476    #[must_use]
477    fn check_noexpect(&self, tok: &TokenKind) -> bool {
478        self.token == *tok
479    }
480
481    // Check the first token after the delimiter that closes the current
482    // delimited sequence. (Panics if used in the outermost token stream, which
483    // has no delimiters.) It uses a clone of the relevant tree cursor to skip
484    // past the entire `TokenTree::Delimited` in a single step, avoiding the
485    // need for unbounded token lookahead.
486    //
487    // Primarily used when `self.token` matches `OpenInvisible(_))`, to look
488    // ahead through the current metavar expansion.
489    fn check_noexpect_past_close_delim(&self, tok: &TokenKind) -> bool {
490        let mut tree_cursor = self.token_cursor.stack.last().unwrap().clone();
491        tree_cursor.bump();
492        #[allow(non_exhaustive_omitted_patterns)] match tree_cursor.curr() {
    Some(TokenTree::Token(token::Token { kind, .. }, _)) if kind == tok =>
        true,
    _ => false,
}matches!(
493            tree_cursor.curr(),
494            Some(TokenTree::Token(token::Token { kind, .. }, _)) if kind == tok
495        )
496    }
497
498    /// Consumes a token 'tok' if it exists. Returns whether the given token was present.
499    ///
500    /// the main purpose of this function is to reduce the cluttering of the suggestions list
501    /// which using the normal eat method could introduce in some cases.
502    #[inline]
503    #[must_use]
504    fn eat_noexpect(&mut self, tok: &TokenKind) -> bool {
505        let is_present = self.check_noexpect(tok);
506        if is_present {
507            self.bump()
508        }
509        is_present
510    }
511
512    /// Consumes a token 'tok' if it exists. Returns whether the given token was present.
513    #[inline]
514    #[must_use]
515    pub fn eat(&mut self, exp: ExpTokenPair) -> bool {
516        let is_present = self.check(exp);
517        if is_present {
518            self.bump()
519        }
520        is_present
521    }
522
523    /// If the next token is the given keyword, returns `true` without eating it.
524    /// An expectation is also added for diagnostics purposes.
525    #[inline]
526    #[must_use]
527    fn check_keyword(&mut self, exp: ExpKeywordPair) -> bool {
528        let is_keyword = self.token.is_keyword(exp.kw);
529        if !is_keyword {
530            self.expected_token_types.insert(exp.token_type);
531        }
532        is_keyword
533    }
534
535    #[inline]
536    #[must_use]
537    fn check_keyword_case(&mut self, exp: ExpKeywordPair, case: Case) -> bool {
538        if self.check_keyword(exp) {
539            true
540        } else if case == Case::Insensitive
541            && let Some((ident, IdentIsRaw::No)) = self.token.ident()
542            // Do an ASCII case-insensitive match, because all keywords are ASCII.
543            && ident.as_str().eq_ignore_ascii_case(exp.kw.as_str())
544        {
545            true
546        } else {
547            false
548        }
549    }
550
551    /// If the next token is the given keyword, eats it and returns `true`.
552    /// Otherwise, returns `false`. An expectation is also added for diagnostics purposes.
553    // Public for rustc_builtin_macros and rustfmt usage.
554    #[inline]
555    #[must_use]
556    pub fn eat_keyword(&mut self, exp: ExpKeywordPair) -> bool {
557        let is_keyword = self.check_keyword(exp);
558        if is_keyword {
559            self.bump();
560        }
561        is_keyword
562    }
563
564    /// Eats a keyword, optionally ignoring the case.
565    /// If the case differs (and is ignored) an error is issued.
566    /// This is useful for recovery.
567    #[inline]
568    #[must_use]
569    fn eat_keyword_case(&mut self, exp: ExpKeywordPair, case: Case) -> bool {
570        if self.eat_keyword(exp) {
571            true
572        } else if case == Case::Insensitive
573            && let Some((ident, IdentIsRaw::No)) = self.token.ident()
574            // Do an ASCII case-insensitive match, because all keywords are ASCII.
575            && ident.as_str().eq_ignore_ascii_case(exp.kw.as_str())
576        {
577            let kw = exp.kw.as_str();
578            let is_upper = kw.chars().all(char::is_uppercase);
579            let is_lower = kw.chars().all(char::is_lowercase);
580
581            let case = match (is_upper, is_lower) {
582                (true, true) => {
583                    {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("keyword that is both fully upper- and fully lowercase")));
}unreachable!("keyword that is both fully upper- and fully lowercase")
584                }
585                (true, false) => errors::Case::Upper,
586                (false, true) => errors::Case::Lower,
587                (false, false) => errors::Case::Mixed,
588            };
589
590            self.dcx().emit_err(errors::KwBadCase { span: ident.span, kw, case });
591            self.bump();
592            true
593        } else {
594            false
595        }
596    }
597
598    /// If the next token is the given keyword, eats it and returns `true`.
599    /// Otherwise, returns `false`. No expectation is added.
600    // Public for rustc_builtin_macros usage.
601    #[inline]
602    #[must_use]
603    pub fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool {
604        let is_keyword = self.token.is_keyword(kw);
605        if is_keyword {
606            self.bump();
607        }
608        is_keyword
609    }
610
611    /// If the given word is not a keyword, signals an error.
612    /// If the next token is not the given word, signals an error.
613    /// Otherwise, eats it.
614    pub fn expect_keyword(&mut self, exp: ExpKeywordPair) -> PResult<'a, ()> {
615        if !self.eat_keyword(exp) { self.unexpected() } else { Ok(()) }
616    }
617
618    /// Consume a sequence produced by a metavar expansion, if present.
619    pub fn eat_metavar_seq<T>(
620        &mut self,
621        mv_kind: MetaVarKind,
622        f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
623    ) -> Option<T> {
624        self.eat_metavar_seq_with_matcher(|mvk| mvk == mv_kind, f)
625    }
626
627    /// A slightly more general form of `eat_metavar_seq`, for use with the
628    /// `MetaVarKind` variants that have parameters, where an exact match isn't
629    /// desired.
630    fn eat_metavar_seq_with_matcher<T>(
631        &mut self,
632        match_mv_kind: impl Fn(MetaVarKind) -> bool,
633        mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
634    ) -> Option<T> {
635        if let token::OpenInvisible(InvisibleOrigin::MetaVar(mv_kind)) = self.token.kind
636            && match_mv_kind(mv_kind)
637        {
638            self.bump();
639
640            // Recovery is disabled when parsing macro arguments, so it must
641            // also be disabled when reparsing pasted macro arguments,
642            // otherwise we get inconsistent results (e.g. #137874).
643            let res = self.with_recovery(Recovery::Forbidden, |this| f(this));
644
645            let res = match res {
646                Ok(res) => res,
647                Err(err) => {
648                    // This can occur in unusual error cases, e.g. #139445.
649                    err.delay_as_bug();
650                    return None;
651                }
652            };
653
654            if let token::CloseInvisible(InvisibleOrigin::MetaVar(mv_kind)) = self.token.kind
655                && match_mv_kind(mv_kind)
656            {
657                self.bump();
658                Some(res)
659            } else {
660                // This can occur when invalid syntax is passed to a decl macro. E.g. see #139248,
661                // where the reparse attempt of an invalid expr consumed the trailing invisible
662                // delimiter.
663                self.dcx()
664                    .span_delayed_bug(self.token.span, "no close delim with reparsing {mv_kind:?}");
665                None
666            }
667        } else {
668            None
669        }
670    }
671
672    /// Is the given keyword `kw` followed by a non-reserved identifier?
673    fn is_kw_followed_by_ident(&self, kw: Symbol) -> bool {
674        self.token.is_keyword(kw) && self.look_ahead(1, |t| t.is_non_reserved_ident())
675    }
676
677    #[inline]
678    fn check_or_expected(&mut self, ok: bool, token_type: TokenType) -> bool {
679        if !ok {
680            self.expected_token_types.insert(token_type);
681        }
682        ok
683    }
684
685    fn check_ident(&mut self) -> bool {
686        self.check_or_expected(self.token.is_ident(), TokenType::Ident)
687    }
688
689    fn check_path(&mut self) -> bool {
690        self.check_or_expected(self.token.is_path_start(), TokenType::Path)
691    }
692
693    fn check_type(&mut self) -> bool {
694        self.check_or_expected(self.token.can_begin_type(), TokenType::Type)
695    }
696
697    fn check_const_arg(&mut self) -> bool {
698        let is_mcg_arg = self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const);
699        let is_mgca_arg = self.is_keyword_ahead(0, &[kw::Const])
700            && self.look_ahead(1, |t| *t == token::OpenBrace);
701        is_mcg_arg || is_mgca_arg
702    }
703
704    fn check_const_closure(&self) -> bool {
705        self.is_keyword_ahead(0, &[kw::Const])
706            && self.look_ahead(1, |t| match &t.kind {
707                // async closures do not work with const closures, so we do not parse that here.
708                token::Ident(kw::Move | kw::Use | kw::Static, IdentIsRaw::No)
709                | token::OrOr
710                | token::Or => true,
711                _ => false,
712            })
713    }
714
715    fn check_inline_const(&self, dist: usize) -> bool {
716        self.is_keyword_ahead(dist, &[kw::Const])
717            && self.look_ahead(dist + 1, |t| match &t.kind {
718                token::OpenBrace => true,
719                token::OpenInvisible(InvisibleOrigin::MetaVar(MetaVarKind::Block)) => true,
720                _ => false,
721            })
722    }
723
724    /// Checks to see if the next token is either `+` or `+=`.
725    /// Otherwise returns `false`.
726    #[inline]
727    fn check_plus(&mut self) -> bool {
728        self.check_or_expected(self.token.is_like_plus(), TokenType::Plus)
729    }
730
731    /// Eats the expected token if it's present possibly breaking
732    /// compound tokens like multi-character operators in process.
733    /// Returns `true` if the token was eaten.
734    fn break_and_eat(&mut self, exp: ExpTokenPair) -> bool {
735        if self.token == exp.tok {
736            self.bump();
737            return true;
738        }
739        match self.token.kind.break_two_token_op(1) {
740            Some((first, second)) if first == exp.tok => {
741                let first_span = self.psess.source_map().start_point(self.token.span);
742                let second_span = self.token.span.with_lo(first_span.hi());
743                self.token = Token::new(first, first_span);
744                // Keep track of this token - if we end token capturing now,
745                // we'll want to append this token to the captured stream.
746                //
747                // If we consume any additional tokens, then this token
748                // is not needed (we'll capture the entire 'glued' token),
749                // and `bump` will set this field to 0.
750                self.break_last_token += 1;
751                // Use the spacing of the glued token as the spacing of the
752                // unglued second token.
753                self.bump_with((Token::new(second, second_span), self.token_spacing));
754                true
755            }
756            _ => {
757                self.expected_token_types.insert(exp.token_type);
758                false
759            }
760        }
761    }
762
763    /// Eats `+` possibly breaking tokens like `+=` in process.
764    fn eat_plus(&mut self) -> bool {
765        self.break_and_eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Plus,
    token_type: crate::parser::token_type::TokenType::Plus,
}exp!(Plus))
766    }
767
768    /// Eats `&` possibly breaking tokens like `&&` in process.
769    /// Signals an error if `&` is not eaten.
770    fn expect_and(&mut self) -> PResult<'a, ()> {
771        if self.break_and_eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::And,
    token_type: crate::parser::token_type::TokenType::And,
}exp!(And)) { Ok(()) } else { self.unexpected() }
772    }
773
774    /// Eats `|` possibly breaking tokens like `||` in process.
775    /// Signals an error if `|` was not eaten.
776    fn expect_or(&mut self) -> PResult<'a, ()> {
777        if self.break_and_eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Or,
    token_type: crate::parser::token_type::TokenType::Or,
}exp!(Or)) { Ok(()) } else { self.unexpected() }
778    }
779
780    /// Eats `<` possibly breaking tokens like `<<` in process.
781    fn eat_lt(&mut self) -> bool {
782        let ate = self.break_and_eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Lt,
    token_type: crate::parser::token_type::TokenType::Lt,
}exp!(Lt));
783        if ate {
784            // See doc comment for `unmatched_angle_bracket_count`.
785            self.unmatched_angle_bracket_count += 1;
786            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_parse/src/parser/mod.rs:786",
                        "rustc_parse::parser", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_parse/src/parser/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(786u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_parse::parser"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("eat_lt: (increment) count={0:?}",
                                                    self.unmatched_angle_bracket_count) as &dyn Value))])
            });
    } else { ; }
};debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count);
787        }
788        ate
789    }
790
791    /// Eats `<` possibly breaking tokens like `<<` in process.
792    /// Signals an error if `<` was not eaten.
793    fn expect_lt(&mut self) -> PResult<'a, ()> {
794        if self.eat_lt() { Ok(()) } else { self.unexpected() }
795    }
796
797    /// Eats `>` possibly breaking tokens like `>>` in process.
798    /// Signals an error if `>` was not eaten.
799    fn expect_gt(&mut self) -> PResult<'a, ()> {
800        if self.break_and_eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Gt,
    token_type: crate::parser::token_type::TokenType::Gt,
}exp!(Gt)) {
801            // See doc comment for `unmatched_angle_bracket_count`.
802            if self.unmatched_angle_bracket_count > 0 {
803                self.unmatched_angle_bracket_count -= 1;
804                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_parse/src/parser/mod.rs:804",
                        "rustc_parse::parser", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_parse/src/parser/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(804u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_parse::parser"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("expect_gt: (decrement) count={0:?}",
                                                    self.unmatched_angle_bracket_count) as &dyn Value))])
            });
    } else { ; }
};debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count);
805            }
806            Ok(())
807        } else {
808            self.unexpected()
809        }
810    }
811
812    /// Checks if the next token is contained within `closes`, and returns `true` if so.
813    fn expect_any_with_type(
814        &mut self,
815        closes_expected: &[ExpTokenPair],
816        closes_not_expected: &[&TokenKind],
817    ) -> bool {
818        closes_expected.iter().any(|&close| self.check(close))
819            || closes_not_expected.iter().any(|k| self.check_noexpect(k))
820    }
821
822    /// Parses a sequence until the specified delimiters. The function
823    /// `f` must consume tokens until reaching the next separator or
824    /// closing bracket.
825    fn parse_seq_to_before_tokens<T>(
826        &mut self,
827        closes_expected: &[ExpTokenPair],
828        closes_not_expected: &[&TokenKind],
829        sep: SeqSep,
830        mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
831    ) -> PResult<'a, (ThinVec<T>, Trailing, Recovered)> {
832        let mut first = true;
833        let mut recovered = Recovered::No;
834        let mut trailing = Trailing::No;
835        let mut v = ThinVec::new();
836
837        while !self.expect_any_with_type(closes_expected, closes_not_expected) {
838            if self.token.kind.is_close_delim_or_eof() {
839                break;
840            }
841            if let Some(exp) = sep.sep {
842                if first {
843                    // no separator for the first element
844                    first = false;
845                } else {
846                    // check for separator
847                    match self.expect(exp) {
848                        Ok(Recovered::No) => {
849                            self.current_closure.take();
850                        }
851                        Ok(Recovered::Yes(guar)) => {
852                            self.current_closure.take();
853                            recovered = Recovered::Yes(guar);
854                            break;
855                        }
856                        Err(mut expect_err) => {
857                            let sp = self.prev_token.span.shrink_to_hi();
858                            let token_str = pprust::token_kind_to_string(&exp.tok);
859
860                            match self.current_closure.take() {
861                                Some(closure_spans) if self.token == TokenKind::Semi => {
862                                    // Finding a semicolon instead of a comma
863                                    // after a closure body indicates that the
864                                    // closure body may be a block but the user
865                                    // forgot to put braces around its
866                                    // statements.
867
868                                    self.recover_missing_braces_around_closure_body(
869                                        closure_spans,
870                                        expect_err,
871                                    )?;
872
873                                    continue;
874                                }
875
876                                _ => {
877                                    // Attempt to keep parsing if it was a similar separator.
878                                    if exp.tok.similar_tokens().contains(&self.token.kind) {
879                                        self.bump();
880                                    }
881                                }
882                            }
883
884                            // If this was a missing `@` in a binding pattern
885                            // bail with a suggestion
886                            // https://github.com/rust-lang/rust/issues/72373
887                            if self.prev_token.is_ident() && self.token == token::DotDot {
888                                let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("if you meant to bind the contents of the rest of the array pattern into `{0}`, use `@`",
                pprust::token_to_string(&self.prev_token)))
    })format!(
889                                    "if you meant to bind the contents of the rest of the array \
890                                     pattern into `{}`, use `@`",
891                                    pprust::token_to_string(&self.prev_token)
892                                );
893                                expect_err
894                                    .with_span_suggestion_verbose(
895                                        self.prev_token.span.shrink_to_hi().until(self.token.span),
896                                        msg,
897                                        " @ ",
898                                        Applicability::MaybeIncorrect,
899                                    )
900                                    .emit();
901                                break;
902                            }
903
904                            // Attempt to keep parsing if it was an omitted separator.
905                            self.last_unexpected_token_span = None;
906                            match f(self) {
907                                Ok(t) => {
908                                    // Parsed successfully, therefore most probably the code only
909                                    // misses a separator.
910                                    expect_err
911                                        .with_span_suggestion_short(
912                                            sp,
913                                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("missing `{0}`", token_str))
    })format!("missing `{token_str}`"),
914                                            token_str,
915                                            Applicability::MaybeIncorrect,
916                                        )
917                                        .emit();
918
919                                    v.push(t);
920                                    continue;
921                                }
922                                Err(e) => {
923                                    // Parsing failed, therefore it must be something more serious
924                                    // than just a missing separator.
925                                    for xx in &e.children {
926                                        // Propagate the help message from sub error `e` to main
927                                        // error `expect_err`.
928                                        expect_err.children.push(xx.clone());
929                                    }
930                                    e.cancel();
931                                    if self.token == token::Colon {
932                                        // We will try to recover in
933                                        // `maybe_recover_struct_lit_bad_delims`.
934                                        return Err(expect_err);
935                                    } else if let [exp] = closes_expected
936                                        && exp.token_type == TokenType::CloseParen
937                                    {
938                                        return Err(expect_err);
939                                    } else {
940                                        expect_err.emit();
941                                        break;
942                                    }
943                                }
944                            }
945                        }
946                    }
947                }
948            }
949            if sep.trailing_sep_allowed
950                && self.expect_any_with_type(closes_expected, closes_not_expected)
951            {
952                trailing = Trailing::Yes;
953                break;
954            }
955
956            let t = f(self)?;
957            v.push(t);
958        }
959
960        Ok((v, trailing, recovered))
961    }
962
963    fn recover_missing_braces_around_closure_body(
964        &mut self,
965        closure_spans: ClosureSpans,
966        mut expect_err: Diag<'_>,
967    ) -> PResult<'a, ()> {
968        let initial_semicolon = self.token.span;
969
970        while self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Semi,
    token_type: crate::parser::token_type::TokenType::Semi,
}exp!(Semi)) {
971            let _ = self
972                .parse_stmt_without_recovery(false, ForceCollect::No, false)
973                .unwrap_or_else(|e| {
974                    e.cancel();
975                    None
976                });
977        }
978
979        expect_err
980            .primary_message("closure bodies that contain statements must be surrounded by braces");
981
982        let preceding_pipe_span = closure_spans.closing_pipe;
983        let following_token_span = self.token.span;
984
985        let mut first_note = MultiSpan::from(<[_]>::into_vec(::alloc::boxed::box_new([initial_semicolon]))vec![initial_semicolon]);
986        first_note.push_span_label(
987            initial_semicolon,
988            "this `;` turns the preceding closure into a statement",
989        );
990        first_note.push_span_label(
991            closure_spans.body,
992            "this expression is a statement because of the trailing semicolon",
993        );
994        expect_err.span_note(first_note, "statement found outside of a block");
995
996        let mut second_note = MultiSpan::from(<[_]>::into_vec(::alloc::boxed::box_new([closure_spans.whole_closure]))vec![closure_spans.whole_closure]);
997        second_note.push_span_label(closure_spans.whole_closure, "this is the parsed closure...");
998        second_note.push_span_label(
999            following_token_span,
1000            "...but likely you meant the closure to end here",
1001        );
1002        expect_err.span_note(second_note, "the closure body may be incorrectly delimited");
1003
1004        expect_err.span(<[_]>::into_vec(::alloc::boxed::box_new([preceding_pipe_span,
                following_token_span]))vec![preceding_pipe_span, following_token_span]);
1005
1006        let opening_suggestion_str = " {".to_string();
1007        let closing_suggestion_str = "}".to_string();
1008
1009        expect_err.multipart_suggestion(
1010            "try adding braces",
1011            <[_]>::into_vec(::alloc::boxed::box_new([(preceding_pipe_span.shrink_to_hi(),
                    opening_suggestion_str),
                (following_token_span.shrink_to_lo(),
                    closing_suggestion_str)]))vec![
1012                (preceding_pipe_span.shrink_to_hi(), opening_suggestion_str),
1013                (following_token_span.shrink_to_lo(), closing_suggestion_str),
1014            ],
1015            Applicability::MaybeIncorrect,
1016        );
1017
1018        expect_err.emit();
1019
1020        Ok(())
1021    }
1022
1023    /// Parses a sequence, not including the delimiters. The function
1024    /// `f` must consume tokens until reaching the next separator or
1025    /// closing bracket.
1026    fn parse_seq_to_before_end<T>(
1027        &mut self,
1028        close: ExpTokenPair,
1029        sep: SeqSep,
1030        f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1031    ) -> PResult<'a, (ThinVec<T>, Trailing, Recovered)> {
1032        self.parse_seq_to_before_tokens(&[close], &[], sep, f)
1033    }
1034
1035    /// Parses a sequence, including only the closing delimiter. The function
1036    /// `f` must consume tokens until reaching the next separator or
1037    /// closing bracket.
1038    fn parse_seq_to_end<T>(
1039        &mut self,
1040        close: ExpTokenPair,
1041        sep: SeqSep,
1042        f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1043    ) -> PResult<'a, (ThinVec<T>, Trailing)> {
1044        let (val, trailing, recovered) = self.parse_seq_to_before_end(close, sep, f)?;
1045        if #[allow(non_exhaustive_omitted_patterns)] match recovered {
    Recovered::No => true,
    _ => false,
}matches!(recovered, Recovered::No) && !self.eat(close) {
1046            self.dcx().span_delayed_bug(
1047                self.token.span,
1048                "recovered but `parse_seq_to_before_end` did not give us the close token",
1049            );
1050        }
1051        Ok((val, trailing))
1052    }
1053
1054    /// Parses a sequence, including both delimiters. The function
1055    /// `f` must consume tokens until reaching the next separator or
1056    /// closing bracket.
1057    fn parse_unspanned_seq<T>(
1058        &mut self,
1059        open: ExpTokenPair,
1060        close: ExpTokenPair,
1061        sep: SeqSep,
1062        f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1063    ) -> PResult<'a, (ThinVec<T>, Trailing)> {
1064        self.expect(open)?;
1065        self.parse_seq_to_end(close, sep, f)
1066    }
1067
1068    /// Parses a comma-separated sequence, including both delimiters.
1069    /// The function `f` must consume tokens until reaching the next separator or
1070    /// closing bracket.
1071    fn parse_delim_comma_seq<T>(
1072        &mut self,
1073        open: ExpTokenPair,
1074        close: ExpTokenPair,
1075        f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1076    ) -> PResult<'a, (ThinVec<T>, Trailing)> {
1077        self.parse_unspanned_seq(open, close, SeqSep::trailing_allowed(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma)), f)
1078    }
1079
1080    /// Parses a comma-separated sequence delimited by parentheses (e.g. `(x, y)`).
1081    /// The function `f` must consume tokens until reaching the next separator or
1082    /// closing bracket.
1083    pub fn parse_paren_comma_seq<T>(
1084        &mut self,
1085        f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1086    ) -> PResult<'a, (ThinVec<T>, Trailing)> {
1087        self.parse_delim_comma_seq(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenParen,
    token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen), crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseParen,
    token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen), f)
1088    }
1089
1090    /// Advance the parser by one token using provided token as the next one.
1091    fn bump_with(&mut self, next: (Token, Spacing)) {
1092        self.inlined_bump_with(next)
1093    }
1094
1095    /// This always-inlined version should only be used on hot code paths.
1096    #[inline(always)]
1097    fn inlined_bump_with(&mut self, (next_token, next_spacing): (Token, Spacing)) {
1098        // Update the current and previous tokens.
1099        self.prev_token = mem::replace(&mut self.token, next_token);
1100        self.token_spacing = next_spacing;
1101
1102        // Diagnostics.
1103        self.expected_token_types.clear();
1104    }
1105
1106    /// Advance the parser by one token.
1107    pub fn bump(&mut self) {
1108        // Note: destructuring here would give nicer code, but it was found in #96210 to be slower
1109        // than `.0`/`.1` access.
1110        let mut next = self.token_cursor.inlined_next();
1111        self.num_bump_calls += 1;
1112        // We got a token from the underlying cursor and no longer need to
1113        // worry about an unglued token. See `break_and_eat` for more details.
1114        self.break_last_token = 0;
1115        if next.0.span.is_dummy() {
1116            // Tweak the location for better diagnostics, but keep syntactic context intact.
1117            let fallback_span = self.token.span;
1118            next.0.span = fallback_span.with_ctxt(next.0.span.ctxt());
1119        }
1120        if true {
    if !!#[allow(non_exhaustive_omitted_patterns)] match next.0.kind {
                    token::OpenInvisible(origin) | token::CloseInvisible(origin)
                        if origin.skip() => true,
                    _ => false,
                } {
        ::core::panicking::panic("assertion failed: !matches!(next.0.kind, token::OpenInvisible(origin) |\n        token::CloseInvisible(origin) if origin.skip())")
    };
};debug_assert!(!matches!(
1121            next.0.kind,
1122            token::OpenInvisible(origin) | token::CloseInvisible(origin) if origin.skip()
1123        ));
1124        self.inlined_bump_with(next)
1125    }
1126
1127    /// Look-ahead `dist` tokens of `self.token` and get access to that token there.
1128    /// When `dist == 0` then the current token is looked at. `Eof` will be
1129    /// returned if the look-ahead is any distance past the end of the tokens.
1130    pub fn look_ahead<R>(&self, dist: usize, looker: impl FnOnce(&Token) -> R) -> R {
1131        if dist == 0 {
1132            return looker(&self.token);
1133        }
1134
1135        // Typically around 98% of the `dist > 0` cases have `dist == 1`, so we
1136        // have a fast special case for that.
1137        if dist == 1 {
1138            // The index is zero because the tree cursor's index always points
1139            // to the next token to be gotten.
1140            match self.token_cursor.curr.curr() {
1141                Some(tree) => {
1142                    // Indexing stayed within the current token tree.
1143                    match tree {
1144                        TokenTree::Token(token, _) => return looker(token),
1145                        &TokenTree::Delimited(dspan, _, delim, _) => {
1146                            if !delim.skip() {
1147                                return looker(&Token::new(delim.as_open_token_kind(), dspan.open));
1148                            }
1149                        }
1150                    }
1151                }
1152                None => {
1153                    // The tree cursor lookahead went (one) past the end of the
1154                    // current token tree. Try to return a close delimiter.
1155                    if let Some(last) = self.token_cursor.stack.last()
1156                        && let Some(&TokenTree::Delimited(span, _, delim, _)) = last.curr()
1157                        && !delim.skip()
1158                    {
1159                        // We are not in the outermost token stream, so we have
1160                        // delimiters. Also, those delimiters are not skipped.
1161                        return looker(&Token::new(delim.as_close_token_kind(), span.close));
1162                    }
1163                }
1164            }
1165        }
1166
1167        // Just clone the token cursor and use `next`, skipping delimiters as
1168        // necessary. Slow but simple.
1169        let mut cursor = self.token_cursor.clone();
1170        let mut i = 0;
1171        let mut token = Token::dummy();
1172        while i < dist {
1173            token = cursor.next().0;
1174            if let token::OpenInvisible(origin) | token::CloseInvisible(origin) = token.kind
1175                && origin.skip()
1176            {
1177                continue;
1178            }
1179            i += 1;
1180        }
1181        looker(&token)
1182    }
1183
1184    /// Like `lookahead`, but skips over token trees rather than tokens. Useful
1185    /// when looking past possible metavariable pasting sites.
1186    pub fn tree_look_ahead<R>(
1187        &self,
1188        dist: usize,
1189        looker: impl FnOnce(&TokenTree) -> R,
1190    ) -> Option<R> {
1191        match (&dist, &0) {
    (left_val, right_val) => {
        if *left_val == *right_val {
            let kind = ::core::panicking::AssertKind::Ne;
            ::core::panicking::assert_failed(kind, &*left_val, &*right_val,
                ::core::option::Option::None);
        }
    }
};assert_ne!(dist, 0);
1192        self.token_cursor.curr.look_ahead(dist - 1).map(looker)
1193    }
1194
1195    /// Returns whether any of the given keywords are `dist` tokens ahead of the current one.
1196    pub(crate) fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool {
1197        self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw)))
1198    }
1199
1200    /// Parses asyncness: `async` or nothing.
1201    fn parse_coroutine_kind(&mut self, case: Case) -> Option<CoroutineKind> {
1202        let span = self.token_uninterpolated_span();
1203        if self.eat_keyword_case(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Async,
    token_type: crate::parser::token_type::TokenType::KwAsync,
}exp!(Async), case) {
1204            // FIXME(gen_blocks): Do we want to unconditionally parse `gen` and then
1205            // error if edition <= 2024, like we do with async and edition <= 2018?
1206            if self.token_uninterpolated_span().at_least_rust_2024()
1207                && self.eat_keyword_case(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Gen,
    token_type: crate::parser::token_type::TokenType::KwGen,
}exp!(Gen), case)
1208            {
1209                let gen_span = self.prev_token_uninterpolated_span();
1210                Some(CoroutineKind::AsyncGen {
1211                    span: span.to(gen_span),
1212                    closure_id: DUMMY_NODE_ID,
1213                    return_impl_trait_id: DUMMY_NODE_ID,
1214                })
1215            } else {
1216                Some(CoroutineKind::Async {
1217                    span,
1218                    closure_id: DUMMY_NODE_ID,
1219                    return_impl_trait_id: DUMMY_NODE_ID,
1220                })
1221            }
1222        } else if self.token_uninterpolated_span().at_least_rust_2024()
1223            && self.eat_keyword_case(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Gen,
    token_type: crate::parser::token_type::TokenType::KwGen,
}exp!(Gen), case)
1224        {
1225            Some(CoroutineKind::Gen {
1226                span,
1227                closure_id: DUMMY_NODE_ID,
1228                return_impl_trait_id: DUMMY_NODE_ID,
1229            })
1230        } else {
1231            None
1232        }
1233    }
1234
1235    /// Parses fn unsafety: `unsafe`, `safe` or nothing.
1236    fn parse_safety(&mut self, case: Case) -> Safety {
1237        if self.eat_keyword_case(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Unsafe,
    token_type: crate::parser::token_type::TokenType::KwUnsafe,
}exp!(Unsafe), case) {
1238            Safety::Unsafe(self.prev_token_uninterpolated_span())
1239        } else if self.eat_keyword_case(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Safe,
    token_type: crate::parser::token_type::TokenType::KwSafe,
}exp!(Safe), case) {
1240            Safety::Safe(self.prev_token_uninterpolated_span())
1241        } else {
1242            Safety::Default
1243        }
1244    }
1245
1246    /// Parses constness: `const` or nothing.
1247    fn parse_constness(&mut self, case: Case) -> Const {
1248        self.parse_constness_(case, false)
1249    }
1250
1251    /// Parses constness for closures (case sensitive, feature-gated)
1252    fn parse_closure_constness(&mut self) -> Const {
1253        let constness = self.parse_constness_(Case::Sensitive, true);
1254        if let Const::Yes(span) = constness {
1255            self.psess.gated_spans.gate(sym::const_closures, span);
1256        }
1257        constness
1258    }
1259
1260    fn parse_constness_(&mut self, case: Case, is_closure: bool) -> Const {
1261        // Avoid const blocks and const closures to be parsed as const items
1262        if (self.check_const_closure() == is_closure)
1263            && !self.look_ahead(1, |t| *t == token::OpenBrace || t.is_metavar_block())
1264            && self.eat_keyword_case(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Const,
    token_type: crate::parser::token_type::TokenType::KwConst,
}exp!(Const), case)
1265        {
1266            Const::Yes(self.prev_token_uninterpolated_span())
1267        } else {
1268            Const::No
1269        }
1270    }
1271
1272    /// Parses inline const expressions.
1273    fn parse_const_block(&mut self, span: Span) -> PResult<'a, Box<Expr>> {
1274        self.expect_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Const,
    token_type: crate::parser::token_type::TokenType::KwConst,
}exp!(Const))?;
1275        let (attrs, blk) = self.parse_inner_attrs_and_block(None)?;
1276        let anon_const = AnonConst {
1277            id: DUMMY_NODE_ID,
1278            value: self.mk_expr(blk.span, ExprKind::Block(blk, None)),
1279            mgca_disambiguation: MgcaDisambiguation::AnonConst,
1280        };
1281        let blk_span = anon_const.value.span;
1282        let kind = ExprKind::ConstBlock(anon_const);
1283        Ok(self.mk_expr_with_attrs(span.to(blk_span), kind, attrs))
1284    }
1285
1286    /// Parses mutability (`mut` or nothing).
1287    fn parse_mutability(&mut self) -> Mutability {
1288        if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Mut,
    token_type: crate::parser::token_type::TokenType::KwMut,
}exp!(Mut)) { Mutability::Mut } else { Mutability::Not }
1289    }
1290
1291    /// Parses reference binding mode (`ref`, `ref mut`, `ref pin const`, `ref pin mut`, or nothing).
1292    fn parse_byref(&mut self) -> ByRef {
1293        if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Ref,
    token_type: crate::parser::token_type::TokenType::KwRef,
}exp!(Ref)) {
1294            let (pinnedness, mutability) = self.parse_pin_and_mut();
1295            ByRef::Yes(pinnedness, mutability)
1296        } else {
1297            ByRef::No
1298        }
1299    }
1300
1301    /// Possibly parses mutability (`const` or `mut`).
1302    fn parse_const_or_mut(&mut self) -> Option<Mutability> {
1303        if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Mut,
    token_type: crate::parser::token_type::TokenType::KwMut,
}exp!(Mut)) {
1304            Some(Mutability::Mut)
1305        } else if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Const,
    token_type: crate::parser::token_type::TokenType::KwConst,
}exp!(Const)) {
1306            Some(Mutability::Not)
1307        } else {
1308            None
1309        }
1310    }
1311
1312    fn parse_field_name(&mut self) -> PResult<'a, Ident> {
1313        if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = self.token.kind
1314        {
1315            if let Some(suffix) = suffix {
1316                self.dcx().emit_err(errors::InvalidLiteralSuffixOnTupleIndex {
1317                    span: self.token.span,
1318                    suffix,
1319                });
1320            }
1321            self.bump();
1322            Ok(Ident::new(symbol, self.prev_token.span))
1323        } else {
1324            self.parse_ident_common(true)
1325        }
1326    }
1327
1328    fn parse_delim_args(&mut self) -> PResult<'a, Box<DelimArgs>> {
1329        if let Some(args) = self.parse_delim_args_inner() {
1330            Ok(Box::new(args))
1331        } else {
1332            self.unexpected_any()
1333        }
1334    }
1335
1336    fn parse_attr_args(&mut self) -> PResult<'a, AttrArgs> {
1337        Ok(if let Some(args) = self.parse_delim_args_inner() {
1338            AttrArgs::Delimited(args)
1339        } else if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Eq,
    token_type: crate::parser::token_type::TokenType::Eq,
}exp!(Eq)) {
1340            let eq_span = self.prev_token.span;
1341            let expr = self.parse_expr_force_collect()?;
1342            AttrArgs::Eq { eq_span, expr }
1343        } else {
1344            AttrArgs::Empty
1345        })
1346    }
1347
1348    fn parse_delim_args_inner(&mut self) -> Option<DelimArgs> {
1349        let delimited = self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenParen,
    token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen))
1350            || self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenBracket,
    token_type: crate::parser::token_type::TokenType::OpenBracket,
}exp!(OpenBracket))
1351            || self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenBrace,
    token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace));
1352
1353        delimited.then(|| {
1354            let TokenTree::Delimited(dspan, _, delim, tokens) = self.parse_token_tree() else {
1355                ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
1356            };
1357            DelimArgs { dspan, delim, tokens }
1358        })
1359    }
1360
1361    /// Parses a single token tree from the input.
1362    pub fn parse_token_tree(&mut self) -> TokenTree {
1363        if self.token.kind.open_delim().is_some() {
1364            // Clone the `TokenTree::Delimited` that we are currently
1365            // within. That's what we are going to return.
1366            let tree = self.token_cursor.stack.last().unwrap().curr().unwrap().clone();
1367            if true {
    match tree {
        TokenTree::Delimited(..) => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "TokenTree::Delimited(..)", ::core::option::Option::None);
        }
    };
};debug_assert_matches!(tree, TokenTree::Delimited(..));
1368
1369            // Advance the token cursor through the entire delimited
1370            // sequence. After getting the `OpenDelim` we are *within* the
1371            // delimited sequence, i.e. at depth `d`. After getting the
1372            // matching `CloseDelim` we are *after* the delimited sequence,
1373            // i.e. at depth `d - 1`.
1374            let target_depth = self.token_cursor.stack.len() - 1;
1375
1376            if let Capturing::No = self.capture_state.capturing {
1377                // We are not capturing tokens, so skip to the end of the
1378                // delimited sequence. This is a perf win when dealing with
1379                // declarative macros that pass large `tt` fragments through
1380                // multiple rules, as seen in the uom-0.37.0 crate.
1381                self.token_cursor.curr.bump_to_end();
1382                self.bump();
1383                if true {
    match (&self.token_cursor.stack.len(), &target_depth) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    };
};debug_assert_eq!(self.token_cursor.stack.len(), target_depth);
1384            } else {
1385                loop {
1386                    // Advance one token at a time, so `TokenCursor::next()`
1387                    // can capture these tokens if necessary.
1388                    self.bump();
1389                    if self.token_cursor.stack.len() == target_depth {
1390                        break;
1391                    }
1392                }
1393            }
1394            if true {
    if !self.token.kind.close_delim().is_some() {
        ::core::panicking::panic("assertion failed: self.token.kind.close_delim().is_some()")
    };
};debug_assert!(self.token.kind.close_delim().is_some());
1395
1396            // Consume close delimiter
1397            self.bump();
1398            tree
1399        } else {
1400            if !!self.token.kind.is_close_delim_or_eof() {
    ::core::panicking::panic("assertion failed: !self.token.kind.is_close_delim_or_eof()")
};assert!(!self.token.kind.is_close_delim_or_eof());
1401            let prev_spacing = self.token_spacing;
1402            self.bump();
1403            TokenTree::Token(self.prev_token, prev_spacing)
1404        }
1405    }
1406
1407    pub fn parse_tokens(&mut self) -> TokenStream {
1408        let mut result = Vec::new();
1409        loop {
1410            if self.token.kind.is_close_delim_or_eof() {
1411                break;
1412            } else {
1413                result.push(self.parse_token_tree());
1414            }
1415        }
1416        TokenStream::new(result)
1417    }
1418
1419    /// Evaluates the closure with restrictions in place.
1420    ///
1421    /// Afters the closure is evaluated, restrictions are reset.
1422    fn with_res<T>(&mut self, res: Restrictions, f: impl FnOnce(&mut Self) -> T) -> T {
1423        let old = self.restrictions;
1424        self.restrictions = res;
1425        let res = f(self);
1426        self.restrictions = old;
1427        res
1428    }
1429
1430    /// Parses `pub` and `pub(in path)` plus shortcuts `pub(crate)` for `pub(in crate)`, `pub(self)`
1431    /// for `pub(in self)` and `pub(super)` for `pub(in super)`.
1432    /// If the following element can't be a tuple (i.e., it's a function definition), then
1433    /// it's not a tuple struct field), and the contents within the parentheses aren't valid,
1434    /// so emit a proper diagnostic.
1435    // Public for rustfmt usage.
1436    pub fn parse_visibility(&mut self, fbt: FollowedByType) -> PResult<'a, Visibility> {
1437        if let Some(vis) = self
1438            .eat_metavar_seq(MetaVarKind::Vis, |this| this.parse_visibility(FollowedByType::Yes))
1439        {
1440            return Ok(vis);
1441        }
1442
1443        if !self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Pub,
    token_type: crate::parser::token_type::TokenType::KwPub,
}exp!(Pub)) {
1444            // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
1445            // keyword to grab a span from for inherited visibility; an empty span at the
1446            // beginning of the current token would seem to be the "Schelling span".
1447            return Ok(Visibility {
1448                span: self.token.span.shrink_to_lo(),
1449                kind: VisibilityKind::Inherited,
1450                tokens: None,
1451            });
1452        }
1453        let lo = self.prev_token.span;
1454
1455        if self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenParen,
    token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen)) {
1456            // We don't `self.bump()` the `(` yet because this might be a struct definition where
1457            // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
1458            // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
1459            // by the following tokens.
1460            if self.is_keyword_ahead(1, &[kw::In]) {
1461                // Parse `pub(in path)`.
1462                self.bump(); // `(`
1463                self.bump(); // `in`
1464                let path = self.parse_path(PathStyle::Mod)?; // `path`
1465                self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseParen,
    token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen))?; // `)`
1466                let vis = VisibilityKind::Restricted {
1467                    path: Box::new(path),
1468                    id: ast::DUMMY_NODE_ID,
1469                    shorthand: false,
1470                };
1471                return Ok(Visibility {
1472                    span: lo.to(self.prev_token.span),
1473                    kind: vis,
1474                    tokens: None,
1475                });
1476            } else if self.look_ahead(2, |t| t == &token::CloseParen)
1477                && self.is_keyword_ahead(1, &[kw::Crate, kw::Super, kw::SelfLower])
1478            {
1479                // Parse `pub(crate)`, `pub(self)`, or `pub(super)`.
1480                self.bump(); // `(`
1481                let path = self.parse_path(PathStyle::Mod)?; // `crate`/`super`/`self`
1482                self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseParen,
    token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen))?; // `)`
1483                let vis = VisibilityKind::Restricted {
1484                    path: Box::new(path),
1485                    id: ast::DUMMY_NODE_ID,
1486                    shorthand: true,
1487                };
1488                return Ok(Visibility {
1489                    span: lo.to(self.prev_token.span),
1490                    kind: vis,
1491                    tokens: None,
1492                });
1493            } else if let FollowedByType::No = fbt {
1494                // Provide this diagnostic if a type cannot follow;
1495                // in particular, if this is not a tuple struct.
1496                self.recover_incorrect_vis_restriction()?;
1497                // Emit diagnostic, but continue with public visibility.
1498            }
1499        }
1500
1501        Ok(Visibility { span: lo, kind: VisibilityKind::Public, tokens: None })
1502    }
1503
1504    /// Recovery for e.g. `pub(something) fn ...` or `struct X { pub(something) y: Z }`
1505    fn recover_incorrect_vis_restriction(&mut self) -> PResult<'a, ()> {
1506        self.bump(); // `(`
1507        let path = self.parse_path(PathStyle::Mod)?;
1508        self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseParen,
    token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen))?; // `)`
1509
1510        let path_str = pprust::path_to_string(&path);
1511        self.dcx()
1512            .emit_err(IncorrectVisibilityRestriction { span: path.span, inner_str: path_str });
1513
1514        Ok(())
1515    }
1516
1517    /// Parses `extern string_literal?`.
1518    fn parse_extern(&mut self, case: Case) -> Extern {
1519        if self.eat_keyword_case(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Extern,
    token_type: crate::parser::token_type::TokenType::KwExtern,
}exp!(Extern), case) {
1520            let mut extern_span = self.prev_token.span;
1521            let abi = self.parse_abi();
1522            if let Some(abi) = abi {
1523                extern_span = extern_span.to(abi.span);
1524            }
1525            Extern::from_abi(abi, extern_span)
1526        } else {
1527            Extern::None
1528        }
1529    }
1530
1531    /// Parses a string literal as an ABI spec.
1532    fn parse_abi(&mut self) -> Option<StrLit> {
1533        match self.parse_str_lit() {
1534            Ok(str_lit) => Some(str_lit),
1535            Err(Some(lit)) => match lit.kind {
1536                ast::LitKind::Err(_) => None,
1537                _ => {
1538                    self.dcx().emit_err(NonStringAbiLiteral { span: lit.span });
1539                    None
1540                }
1541            },
1542            Err(None) => None,
1543        }
1544    }
1545
1546    fn collect_tokens_no_attrs<R: HasAttrs + HasTokens>(
1547        &mut self,
1548        f: impl FnOnce(&mut Self) -> PResult<'a, R>,
1549    ) -> PResult<'a, R> {
1550        // The only reason to call `collect_tokens_no_attrs` is if you want tokens, so use
1551        // `ForceCollect::Yes`
1552        self.collect_tokens(None, AttrWrapper::empty(), ForceCollect::Yes, |this, _attrs| {
1553            Ok((f(this)?, Trailing::No, UsePreAttrPos::No))
1554        })
1555    }
1556
1557    /// Checks for `::` or, potentially, `:::` and then look ahead after it.
1558    fn check_path_sep_and_look_ahead(&mut self, looker: impl Fn(&Token) -> bool) -> bool {
1559        if self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::PathSep,
    token_type: crate::parser::token_type::TokenType::PathSep,
}exp!(PathSep)) {
1560            if self.may_recover() && self.look_ahead(1, |t| t.kind == token::Colon) {
1561                if true {
    if !!self.look_ahead(1, &looker) {
        {
            ::core::panicking::panic_fmt(format_args!("Looker must not match on colon"));
        }
    };
};debug_assert!(!self.look_ahead(1, &looker), "Looker must not match on colon");
1562                self.look_ahead(2, looker)
1563            } else {
1564                self.look_ahead(1, looker)
1565            }
1566        } else {
1567            false
1568        }
1569    }
1570
1571    /// `::{` or `::*`
1572    fn is_import_coupler(&mut self) -> bool {
1573        self.check_path_sep_and_look_ahead(|t| #[allow(non_exhaustive_omitted_patterns)] match t.kind {
    token::OpenBrace | token::Star => true,
    _ => false,
}matches!(t.kind, token::OpenBrace | token::Star))
1574    }
1575
1576    // Debug view of the parser's token stream, up to `{lookahead}` tokens.
1577    // Only used when debugging.
1578    #[allow(unused)]
1579    pub(crate) fn debug_lookahead(&self, lookahead: usize) -> impl fmt::Debug {
1580        fmt::from_fn(move |f| {
1581            let mut dbg_fmt = f.debug_struct("Parser"); // or at least, one view of
1582
1583            // we don't need N spans, but we want at least one, so print all of prev_token
1584            dbg_fmt.field("prev_token", &self.prev_token);
1585            let mut tokens = ::alloc::vec::Vec::new()vec![];
1586            for i in 0..lookahead {
1587                let tok = self.look_ahead(i, |tok| tok.kind);
1588                let is_eof = tok == TokenKind::Eof;
1589                tokens.push(tok);
1590                if is_eof {
1591                    // Don't look ahead past EOF.
1592                    break;
1593                }
1594            }
1595            dbg_fmt.field_with("tokens", |field| field.debug_list().entries(tokens).finish());
1596            dbg_fmt.field("approx_token_stream_pos", &self.num_bump_calls);
1597
1598            // some fields are interesting for certain values, as they relate to macro parsing
1599            if let Some(subparser) = self.subparser_name {
1600                dbg_fmt.field("subparser_name", &subparser);
1601            }
1602            if let Recovery::Forbidden = self.recovery {
1603                dbg_fmt.field("recovery", &self.recovery);
1604            }
1605
1606            // imply there's "more to know" than this view
1607            dbg_fmt.finish_non_exhaustive()
1608        })
1609    }
1610
1611    pub fn clear_expected_token_types(&mut self) {
1612        self.expected_token_types.clear();
1613    }
1614
1615    pub fn approx_token_stream_pos(&self) -> u32 {
1616        self.num_bump_calls
1617    }
1618
1619    /// For interpolated `self.token`, returns a span of the fragment to which
1620    /// the interpolated token refers. For all other tokens this is just a
1621    /// regular span. It is particularly important to use this for identifiers
1622    /// and lifetimes for which spans affect name resolution and edition
1623    /// checks. Note that keywords are also identifiers, so they should use
1624    /// this if they keep spans or perform edition checks.
1625    pub fn token_uninterpolated_span(&self) -> Span {
1626        match &self.token.kind {
1627            token::NtIdent(ident, _) | token::NtLifetime(ident, _) => ident.span,
1628            token::OpenInvisible(InvisibleOrigin::MetaVar(_)) => self.look_ahead(1, |t| t.span),
1629            _ => self.token.span,
1630        }
1631    }
1632
1633    /// Like `token_uninterpolated_span`, but works on `self.prev_token`.
1634    pub fn prev_token_uninterpolated_span(&self) -> Span {
1635        match &self.prev_token.kind {
1636            token::NtIdent(ident, _) | token::NtLifetime(ident, _) => ident.span,
1637            token::OpenInvisible(InvisibleOrigin::MetaVar(_)) => self.look_ahead(0, |t| t.span),
1638            _ => self.prev_token.span,
1639        }
1640    }
1641}
1642
1643// Metavar captures of various kinds.
1644#[derive(#[automatically_derived]
impl ::core::clone::Clone for ParseNtResult {
    #[inline]
    fn clone(&self) -> ParseNtResult {
        match self {
            ParseNtResult::Tt(__self_0) =>
                ParseNtResult::Tt(::core::clone::Clone::clone(__self_0)),
            ParseNtResult::Ident(__self_0, __self_1) =>
                ParseNtResult::Ident(::core::clone::Clone::clone(__self_0),
                    ::core::clone::Clone::clone(__self_1)),
            ParseNtResult::Lifetime(__self_0, __self_1) =>
                ParseNtResult::Lifetime(::core::clone::Clone::clone(__self_0),
                    ::core::clone::Clone::clone(__self_1)),
            ParseNtResult::Item(__self_0) =>
                ParseNtResult::Item(::core::clone::Clone::clone(__self_0)),
            ParseNtResult::Block(__self_0) =>
                ParseNtResult::Block(::core::clone::Clone::clone(__self_0)),
            ParseNtResult::Stmt(__self_0) =>
                ParseNtResult::Stmt(::core::clone::Clone::clone(__self_0)),
            ParseNtResult::Pat(__self_0, __self_1) =>
                ParseNtResult::Pat(::core::clone::Clone::clone(__self_0),
                    ::core::clone::Clone::clone(__self_1)),
            ParseNtResult::Expr(__self_0, __self_1) =>
                ParseNtResult::Expr(::core::clone::Clone::clone(__self_0),
                    ::core::clone::Clone::clone(__self_1)),
            ParseNtResult::Literal(__self_0) =>
                ParseNtResult::Literal(::core::clone::Clone::clone(__self_0)),
            ParseNtResult::Ty(__self_0) =>
                ParseNtResult::Ty(::core::clone::Clone::clone(__self_0)),
            ParseNtResult::Meta(__self_0) =>
                ParseNtResult::Meta(::core::clone::Clone::clone(__self_0)),
            ParseNtResult::Path(__self_0) =>
                ParseNtResult::Path(::core::clone::Clone::clone(__self_0)),
            ParseNtResult::Vis(__self_0) =>
                ParseNtResult::Vis(::core::clone::Clone::clone(__self_0)),
        }
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for ParseNtResult {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            ParseNtResult::Tt(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Tt",
                    &__self_0),
            ParseNtResult::Ident(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f, "Ident",
                    __self_0, &__self_1),
            ParseNtResult::Lifetime(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "Lifetime", __self_0, &__self_1),
            ParseNtResult::Item(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Item",
                    &__self_0),
            ParseNtResult::Block(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Block",
                    &__self_0),
            ParseNtResult::Stmt(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Stmt",
                    &__self_0),
            ParseNtResult::Pat(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f, "Pat",
                    __self_0, &__self_1),
            ParseNtResult::Expr(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f, "Expr",
                    __self_0, &__self_1),
            ParseNtResult::Literal(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Literal", &__self_0),
            ParseNtResult::Ty(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Ty",
                    &__self_0),
            ParseNtResult::Meta(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Meta",
                    &__self_0),
            ParseNtResult::Path(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Path",
                    &__self_0),
            ParseNtResult::Vis(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Vis",
                    &__self_0),
        }
    }
}Debug)]
1645pub enum ParseNtResult {
1646    Tt(TokenTree),
1647    Ident(Ident, IdentIsRaw),
1648    Lifetime(Ident, IdentIsRaw),
1649    Item(Box<ast::Item>),
1650    Block(Box<ast::Block>),
1651    Stmt(Box<ast::Stmt>),
1652    Pat(Box<ast::Pat>, NtPatKind),
1653    Expr(Box<ast::Expr>, NtExprKind),
1654    Literal(Box<ast::Expr>),
1655    Ty(Box<ast::Ty>),
1656    Meta(Box<ast::AttrItem>),
1657    Path(Box<ast::Path>),
1658    Vis(Box<ast::Visibility>),
1659}