Skip to main content

rustc_parse/parser/
mod.rs

1pub mod attr;
2mod attr_wrapper;
3mod diagnostics;
4mod expr;
5mod function;
6mod generics;
7mod item;
8mod nonterminal;
9mod pat;
10mod path;
11mod stmt;
12pub mod token_type;
13mod ty;
14
15// Parsers for non-functionlike builtin macros are defined in rustc_parse so they can be used by
16// both rustc_builtin_macros and rustfmt.
17pub mod asm;
18pub mod cfg_select;
19
20use std::{debug_assert_matches, fmt, mem, slice};
21
22use attr_wrapper::{AttrWrapper, UsePreAttrPos};
23pub use diagnostics::AttemptLocalParseRecovery;
24// Public to use it for custom `if` expressions in rustfmt forks like https://github.com/tucant/rustfmt
25pub use expr::LetChainsPolicy;
26pub(crate) use function::{FnContext, FnParseMode, FrontMatterParsingMode, IsDotDotDot};
27pub use pat::{CommaRecoveryMode, RecoverColon, RecoverComma};
28pub use path::PathStyle;
29use rustc_ast::token::{
30    self, IdentKind, InvisibleOrigin, MetaVarKind, NtExprKind, NtPatKind, Token, TokenKind,
31};
32use rustc_ast::tokenstream::{
33    ParserRange, ParserReplacement, Spacing, TokenCursor, TokenStream, TokenTree, WithTokens,
34};
35use rustc_ast::util::case::Case;
36use rustc_ast::util::classify;
37use rustc_ast::{
38    self as ast, AnonConst, AttrArgs, AttrId, BinOpKind, ByRef, Const, CoroutineKind,
39    CoroutineMarker, DUMMY_NODE_ID, DelimArgs, Expr, ExprKind, Extern, HasTokens, ImplRestriction,
40    MutRestriction, Mutability, Recovered, RestrictionKind, Safety, StrLit, Visibility,
41    VisibilityKind,
42};
43use rustc_ast_pretty::pprust;
44use rustc_data_structures::fx::FxHashMap;
45use rustc_errors::{Applicability, Diag, FatalError, MultiSpan, PResult};
46use rustc_index::interval::IntervalSet;
47use rustc_session::parse::ParseSess;
48use rustc_span::{ErrorGuaranteed, Ident, Span, Symbol, kw, sym};
49use thin_vec::ThinVec;
50use token_type::TokenTypeSet;
51pub use token_type::{ExpKeywordPair, ExpTokenPair, TokenType};
52use tracing::debug;
53
54use crate::diagnostics::{
55    IncorrectImplRestriction, IncorrectMutRestriction, IncorrectVisibilityRestriction,
56    NonStringAbiLiteral, TokenDescription,
57};
58use crate::exp;
59
60#[cfg(test)]
61mod tests;
62
63// Ideally, these tests would be in `rustc_ast`. But they depend on having a
64// parser, so they are here.
65#[cfg(test)]
66mod tokenstream {
67    mod tests;
68}
69
70#[doc = r" Restrictions applied while parsing."]
#[doc = r""]
#[doc = r" The parser maintains a bitset of restrictions it will honor while"]
#[doc =
r" parsing. This is essentially used as a way of tracking state of what"]
#[doc = r" is being parsed and to change behavior based on that."]
struct Restrictions(<Restrictions as
    ::bitflags::__private::PublicFlags>::Internal);
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for Restrictions { }
#[automatically_derived]
impl ::core::clone::Clone for Restrictions {
    #[inline]
    fn clone(&self) -> Self {
        let _:
                ::core::clone::AssertParamIsClone<<Restrictions as
                ::bitflags::__private::PublicFlags>::Internal>;
        *self
    }
}
#[automatically_derived]
impl ::core::marker::Copy for Restrictions { }
#[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)
    }
}
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);
    #[doc = r" Used to detect a missing `else` in a let statement."]
    #[doc = r" e.g. let Some(foo) = bar{return;};"]
    #[allow(deprecated, non_upper_case_globals,)]
    pub const IN_LET: Self = Self::from_bits_retain(1 << 6);
}
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)
                    },
                    {

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