1pub mod attr;
2mod attr_wrapper;
3mod diagnostics;
4mod expr;
5mod generics;
6mod item;
7mod nonterminal;
8mod pat;
9mod path;
10mod stmt;
11pub mod token_type;
12mod ty;
1314// Parsers for non-functionlike builtin macros are defined in rustc_parse so they can be used by
15// both rustc_builtin_macros and rustfmt.
16pub mod asm;
17pub mod cfg_select;
1819use std::{fmt, mem, slice};
2021use attr_wrapper::{AttrWrapper, UsePreAttrPos};
22pub use diagnostics::AttemptLocalParseRecovery;
23// Public to use it for custom `if` expressions in rustfmt forks like https://github.com/tucant/rustfmt
24pub use expr::LetChainsPolicy;
25pub(crate) use item::{FnContext, FnParseMode};
26pub use pat::{CommaRecoveryMode, RecoverColon, RecoverComma};
27pub use path::PathStyle;
28use rustc_ast::token::{
29self, IdentIsRaw, InvisibleOrigin, MetaVarKind, NtExprKind, NtPatKind, Token, TokenKind,
30};
31use rustc_ast::tokenstream::{
32ParserRange, ParserReplacement, Spacing, TokenCursor, TokenStream, TokenTree, TokenTreeCursor,
33};
34use rustc_ast::util::case::Case;
35use rustc_ast::util::classify;
36use rustc_ast::{
37selfas ast, AnonConst, AttrArgs, AttrId, BinOpKind, ByRef, Const, CoroutineKind,
38DUMMY_NODE_ID, DelimArgs, Expr, ExprKind, Extern, HasAttrs, HasTokens, MgcaDisambiguation,
39Mutability, Recovered, Safety, StrLit, Visibility, VisibilityKind,
40};
41use rustc_ast_pretty::pprust;
42use rustc_data_structures::debug_assert_matches;
43use rustc_data_structures::fx::FxHashMap;
44use rustc_errors::{Applicability, Diag, FatalError, MultiSpan, PResult};
45use rustc_index::interval::IntervalSet;
46use rustc_session::parse::ParseSess;
47use rustc_span::{ErrorGuaranteed, Ident, Span, Symbol, kw, sym};
48use thin_vec::ThinVec;
49use token_type::TokenTypeSet;
50pub use token_type::{ExpKeywordPair, ExpTokenPair, TokenType};
51use tracing::debug;
5253use crate::errors::{self, IncorrectVisibilityRestriction, NonStringAbiLiteral, TokenDescription};
54use crate::exp;
5556#[cfg(test)]
57mod tests;
5859// Ideally, these tests would be in `rustc_ast`. But they depend on having a
60// parser, so they are here.
61#[cfg(test)]
62mod tokenstream {
63mod tests;
64}
6566bitflags::bitflags! {
67/// Restrictions applied while parsing.
68 ///
69 /// The parser maintains a bitset of restrictions it will honor while
70 /// parsing. This is essentially used as a way of tracking state of what
71 /// is being parsed and to change behavior based on that.
72#[derive(#[automatically_derived]
impl ::core::clone::Clone for Restrictions {
#[inline]
fn clone(&self) -> Restrictions {
let _:
::core::clone::AssertParamIsClone<<Restrictions as
::bitflags::__private::PublicFlags>::Internal>;
*self
}
}
impl Restrictions {
#[doc = r" Restricts expressions for use in statement position."]
#[doc = r""]
#[doc =
r" When expressions are used in various places, like statements or"]
#[doc =
r" match arms, this is used to stop parsing once certain tokens are"]
#[doc = r" reached."]
#[doc = r""]
#[doc =
r" For example, `if true {} & 1` with `STMT_EXPR` in effect is parsed"]
#[doc =
r" as two separate expression statements (`if` and a reference to 1)."]
#[doc =
r" Otherwise it is parsed as a bitwise AND where `if` is on the left"]
#[doc = r" and 1 is on the right."]
#[allow(deprecated, non_upper_case_globals,)]
pub const STMT_EXPR: Self = Self::from_bits_retain(1 << 0);
#[doc = r" Do not allow struct literals."]
#[doc = r""]
#[doc =
r" There are several places in the grammar where we don't want to"]
#[doc = r" allow struct literals because they can require lookahead, or"]
#[doc = r" otherwise could be ambiguous or cause confusion. For example,"]
#[doc =
r" `if Foo {} {}` isn't clear if it is `Foo{}` struct literal, or"]
#[doc = r" just `Foo` is the condition, followed by a consequent block,"]
#[doc = r" followed by an empty block."]
#[doc = r""]
#[doc =
r" See [RFC 92](https://rust-lang.github.io/rfcs/0092-struct-grammar.html)."]
#[allow(deprecated, non_upper_case_globals,)]
pub const NO_STRUCT_LITERAL: Self = Self::from_bits_retain(1 << 1);
#[doc =
r" Used to provide better error messages for const generic arguments."]
#[doc = r""]
#[doc =
r" An un-braced const generic argument is limited to a very small"]
#[doc =
r" subset of expressions. This is used to detect the situation where"]
#[doc =
r" an expression outside of that subset is used, and to suggest to"]
#[doc = r" wrap the expression in braces."]
#[allow(deprecated, non_upper_case_globals,)]
pub const CONST_EXPR: Self = Self::from_bits_retain(1 << 2);
#[doc = r" Allows `let` expressions."]
#[doc = r""]
#[doc =
r" `let pattern = scrutinee` is parsed as an expression, but it is"]
#[doc = r" only allowed in let chains (`if` and `while` conditions)."]
#[doc =
r" Otherwise it is not an expression (note that `let` in statement"]
#[doc =
r" positions is treated as a `StmtKind::Let` statement, which has a"]
#[doc = r" slightly different grammar)."]
#[allow(deprecated, non_upper_case_globals,)]
pub const ALLOW_LET: Self = Self::from_bits_retain(1 << 3);
#[doc = r" Used to detect a missing `=>` in a match guard."]
#[doc = r""]
#[doc =
r" This is used for error handling in a match guard to give a better"]
#[doc =
r" error message if the `=>` is missing. It is set when parsing the"]
#[doc = r" guard expression."]
#[allow(deprecated, non_upper_case_globals,)]
pub const IN_IF_GUARD: Self = Self::from_bits_retain(1 << 4);
#[doc = r" Used to detect the incorrect use of expressions in patterns."]
#[doc = r""]
#[doc =
r" This is used for error handling while parsing a pattern. During"]
#[doc =
r" error recovery, this will be set to try to parse the pattern as an"]
#[doc =
r" expression, but halts parsing the expression when reaching certain"]
#[doc = r" tokens like `=`."]
#[allow(deprecated, non_upper_case_globals,)]
pub const IS_PAT: Self = Self::from_bits_retain(1 << 5);
}
impl ::bitflags::Flags for Restrictions {
const FLAGS: &'static [::bitflags::Flag<Restrictions>] =
&[{
#[allow(deprecated, non_upper_case_globals,)]
::bitflags::Flag::new("STMT_EXPR", Restrictions::STMT_EXPR)
},
{
#[allow(deprecated, non_upper_case_globals,)]
::bitflags::Flag::new("NO_STRUCT_LITERAL",
Restrictions::NO_STRUCT_LITERAL)
},
{
#[allow(deprecated, non_upper_case_globals,)]
::bitflags::Flag::new("CONST_EXPR",
Restrictions::CONST_EXPR)
},
{
#[allow(deprecated, non_upper_case_globals,)]
::bitflags::Flag::new("ALLOW_LET", Restrictions::ALLOW_LET)
},
{
#[allow(deprecated, non_upper_case_globals,)]
::bitflags::Flag::new("IN_IF_GUARD",
Restrictions::IN_IF_GUARD)
},
{
#[allow(deprecated, non_upper_case_globals,)]
::bitflags::Flag::new("IS_PAT", Restrictions::IS_PAT)
}];
type Bits = u8;
fn bits(&self) -> u8 { Restrictions::bits(self) }
fn from_bits_retain(bits: u8) -> Restrictions {
Restrictions::from_bits_retain(bits)
}
}
#[allow(dead_code, deprecated, unused_doc_comments, unused_attributes,
unused_mut, unused_imports, non_upper_case_globals, clippy ::
assign_op_pattern, clippy :: indexing_slicing, clippy :: same_name_method,
clippy :: iter_without_into_iter,)]
const _: () =
{
#[repr(transparent)]
struct InternalBitFlags(u8);
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for InternalBitFlags { }
#[automatically_derived]
impl ::core::clone::Clone for InternalBitFlags {
#[inline]
fn clone(&self) -> InternalBitFlags {
let _: ::core::clone::AssertParamIsClone<u8>;
*self
}
}
#[automatically_derived]
impl ::core::marker::Copy for InternalBitFlags { }
#[automatically_derived]
impl ::core::marker::StructuralPartialEq for InternalBitFlags { }
#[automatically_derived]
impl ::core::cmp::PartialEq for InternalBitFlags {
#[inline]
fn eq(&self, other: &InternalBitFlags) -> bool {
self.0 == other.0
}
}
#[automatically_derived]
impl ::core::cmp::Eq for InternalBitFlags {
#[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: &InternalBitFlags)
-> ::core::option::Option<::core::cmp::Ordering> {
::core::cmp::PartialOrd::partial_cmp(&self.0, &other.0)
}
}
#[automatically_derived]
impl ::core::cmp::Ord for InternalBitFlags {
#[inline]
fn cmp(&self, other: &InternalBitFlags) -> ::core::cmp::Ordering {
::core::cmp::Ord::cmp(&self.0, &other.0)
}
}
#[automatically_derived]
impl ::core::hash::Hash for InternalBitFlags {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.0, state)
}
}
impl ::bitflags::__private::PublicFlags for Restrictions {
type Primitive = u8;
type Internal = InternalBitFlags;
}
impl ::bitflags::__private::core::default::Default for
InternalBitFlags {
#[inline]
fn default() -> Self { InternalBitFlags::empty() }
}
impl ::bitflags::__private::core::fmt::Debug for InternalBitFlags {
fn fmt(&self,
f: &mut ::bitflags::__private::core::fmt::Formatter<'_>)
-> ::bitflags::__private::core::fmt::Result {
if self.is_empty() {
f.write_fmt(format_args!("{0:#x}",
<u8 as ::bitflags::Bits>::EMPTY))
} else {
::bitflags::__private::core::fmt::Display::fmt(self, f)
}
}
}
impl ::bitflags::__private::core::fmt::Display for InternalBitFlags {
fn fmt(&self,
f: &mut ::bitflags::__private::core::fmt::Formatter<'_>)
-> ::bitflags::__private::core::fmt::Result {
::bitflags::parser::to_writer(&Restrictions(*self), f)
}
}
impl ::bitflags::__private::core::str::FromStr for InternalBitFlags {
type Err = ::bitflags::parser::ParseError;
fn from_str(s: &str)
->
::bitflags::__private::core::result::Result<Self,
Self::Err> {
::bitflags::parser::from_str::<Restrictions>(s).map(|flags|
flags.0)
}
}
impl ::bitflags::__private::core::convert::AsRef<u8> for
InternalBitFlags {
fn as_ref(&self) -> &u8 { &self.0 }
}
impl ::bitflags::__private::core::convert::From<u8> for
InternalBitFlags {
fn from(bits: u8) -> Self { Self::from_bits_retain(bits) }
}
#[allow(dead_code, deprecated, unused_attributes)]
impl InternalBitFlags {
/// Get a flags value with all bits unset.
#[inline]
pub const fn empty() -> Self {
Self(<u8 as ::bitflags::Bits>::EMPTY)
}
/// Get a flags value with all known bits set.
#[inline]
pub const fn all() -> Self {
let mut truncated = <u8 as ::bitflags::Bits>::EMPTY;
let mut i = 0;
{
{
let flag =
<Restrictions as
::bitflags::Flags>::FLAGS[i].value().bits();
truncated = truncated | flag;
i += 1;
}
};
{
{
let flag =
<Restrictions as
::bitflags::Flags>::FLAGS[i].value().bits();
truncated = truncated | flag;
i += 1;
}
};
{
{
let flag =
<Restrictions as
::bitflags::Flags>::FLAGS[i].value().bits();
truncated = truncated | flag;
i += 1;
}
};
{
{
let flag =
<Restrictions as
::bitflags::Flags>::FLAGS[i].value().bits();
truncated = truncated | flag;
i += 1;
}
};
{
{
let flag =
<Restrictions as
::bitflags::Flags>::FLAGS[i].value().bits();
truncated = truncated | flag;
i += 1;
}
};
{
{
let flag =
<Restrictions as
::bitflags::Flags>::FLAGS[i].value().bits();
truncated = truncated | flag;
i += 1;
}
};
let _ = i;
Self(truncated)
}
/// Get the underlying bits value.
///
/// The returned value is exactly the bits set in this flags value.
#[inline]
pub const fn bits(&self) -> u8 { self.0 }
/// Convert from a bits value.
///
/// This method will return `None` if any unknown bits are set.
#[inline]
pub const fn from_bits(bits: u8)
-> ::bitflags::__private::core::option::Option<Self> {
let truncated = Self::from_bits_truncate(bits).0;
if truncated == bits {
::bitflags::__private::core::option::Option::Some(Self(bits))
} else { ::bitflags::__private::core::option::Option::None }
}
/// Convert from a bits value, unsetting any unknown bits.
#[inline]
pub const fn from_bits_truncate(bits: u8) -> Self {
Self(bits & Self::all().0)
}
/// Convert from a bits value exactly.
#[inline]
pub const fn from_bits_retain(bits: u8) -> Self { Self(bits) }
/// Get a flags value with the bits of a flag with the given name set.
///
/// This method will return `None` if `name` is empty or doesn't
/// correspond to any named flag.
#[inline]
pub fn from_name(name: &str)
-> ::bitflags::__private::core::option::Option<Self> {
{
if name == "STMT_EXPR" {
return ::bitflags::__private::core::option::Option::Some(Self(Restrictions::STMT_EXPR.bits()));
}
};
;
{
if name == "NO_STRUCT_LITERAL" {
return ::bitflags::__private::core::option::Option::Some(Self(Restrictions::NO_STRUCT_LITERAL.bits()));
}
};
;
{
if name == "CONST_EXPR" {
return ::bitflags::__private::core::option::Option::Some(Self(Restrictions::CONST_EXPR.bits()));
}
};
;
{
if name == "ALLOW_LET" {
return ::bitflags::__private::core::option::Option::Some(Self(Restrictions::ALLOW_LET.bits()));
}
};
;
{
if name == "IN_IF_GUARD" {
return ::bitflags::__private::core::option::Option::Some(Self(Restrictions::IN_IF_GUARD.bits()));
}
};
;
{
if name == "IS_PAT" {
return ::bitflags::__private::core::option::Option::Some(Self(Restrictions::IS_PAT.bits()));
}
};
;
let _ = name;
::bitflags::__private::core::option::Option::None
}
/// Whether all bits in this flags value are unset.
#[inline]
pub const fn is_empty(&self) -> bool {
self.0 == <u8 as ::bitflags::Bits>::EMPTY
}
/// Whether all known bits in this flags value are set.
#[inline]
pub const fn is_all(&self) -> bool {
Self::all().0 | self.0 == self.0
}
/// Whether any set bits in a source flags value are also set in a target flags value.
#[inline]
pub const fn intersects(&self, other: Self) -> bool {
self.0 & other.0 != <u8 as ::bitflags::Bits>::EMPTY
}
/// Whether all set bits in a source flags value are also set in a target flags value.
#[inline]
pub const fn contains(&self, other: Self) -> bool {
self.0 & other.0 == other.0
}
/// The bitwise or (`|`) of the bits in two flags values.
#[inline]
pub fn insert(&mut self, other: Self) {
*self = Self(self.0).union(other);
}
/// The intersection of a source flags value with the complement of a target flags
/// value (`&!`).
///
/// This method is not equivalent to `self & !other` when `other` has unknown bits set.
/// `remove` won't truncate `other`, but the `!` operator will.
#[inline]
pub fn remove(&mut self, other: Self) {
*self = Self(self.0).difference(other);
}
/// The bitwise exclusive-or (`^`) of the bits in two flags values.
#[inline]
pub fn toggle(&mut self, other: Self) {
*self = Self(self.0).symmetric_difference(other);
}
/// Call `insert` when `value` is `true` or `remove` when `value` is `false`.
#[inline]
pub fn set(&mut self, other: Self, value: bool) {
if value { self.insert(other); } else { self.remove(other); }
}
/// The bitwise and (`&`) of the bits in two flags values.
#[inline]
#[must_use]
pub const fn intersection(self, other: Self) -> Self {
Self(self.0 & other.0)
}
/// The bitwise or (`|`) of the bits in two flags values.
#[inline]
#[must_use]
pub const fn union(self, other: Self) -> Self {
Self(self.0 | other.0)
}
/// The intersection of a source flags value with the complement of a target flags
/// value (`&!`).
///
/// This method is not equivalent to `self & !other` when `other` has unknown bits set.
/// `difference` won't truncate `other`, but the `!` operator will.
#[inline]
#[must_use]
pub const fn difference(self, other: Self) -> Self {
Self(self.0 & !other.0)
}
/// The bitwise exclusive-or (`^`) of the bits in two flags values.
#[inline]
#[must_use]
pub const fn symmetric_difference(self, other: Self) -> Self {
Self(self.0 ^ other.0)
}
/// The bitwise negation (`!`) of the bits in a flags value, truncating the result.
#[inline]
#[must_use]
pub const fn complement(self) -> Self {
Self::from_bits_truncate(!self.0)
}
}
impl ::bitflags::__private::core::fmt::Binary for InternalBitFlags {
fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
-> ::bitflags::__private::core::fmt::Result {
let inner = self.0;
::bitflags::__private::core::fmt::Binary::fmt(&inner, f)
}
}
impl ::bitflags::__private::core::fmt::Octal for InternalBitFlags {
fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
-> ::bitflags::__private::core::fmt::Result {
let inner = self.0;
::bitflags::__private::core::fmt::Octal::fmt(&inner, f)
}
}
impl ::bitflags::__private::core::fmt::LowerHex for InternalBitFlags {
fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
-> ::bitflags::__private::core::fmt::Result {
let inner = self.0;
::bitflags::__private::core::fmt::LowerHex::fmt(&inner, f)
}
}
impl ::bitflags::__private::core::fmt::UpperHex for InternalBitFlags {
fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
-> ::bitflags::__private::core::fmt::Result {
let inner = self.0;
::bitflags::__private::core::fmt::UpperHex::fmt(&inner, f)
}
}
impl ::bitflags::__private::core::ops::BitOr for InternalBitFlags {
type Output = Self;
/// The bitwise or (`|`) of the bits in two flags values.
#[inline]
fn bitor(self, other: InternalBitFlags) -> Self {
self.union(other)
}
}
impl ::bitflags::__private::core::ops::BitOrAssign for
InternalBitFlags {
/// The bitwise or (`|`) of the bits in two flags values.
#[inline]
fn bitor_assign(&mut self, other: Self) { self.insert(other); }
}
impl ::bitflags::__private::core::ops::BitXor for InternalBitFlags {
type Output = Self;
/// The bitwise exclusive-or (`^`) of the bits in two flags values.
#[inline]
fn bitxor(self, other: Self) -> Self {
self.symmetric_difference(other)
}
}
impl ::bitflags::__private::core::ops::BitXorAssign for
InternalBitFlags {
/// The bitwise exclusive-or (`^`) of the bits in two flags values.
#[inline]
fn bitxor_assign(&mut self, other: Self) { self.toggle(other); }
}
impl ::bitflags::__private::core::ops::BitAnd for InternalBitFlags {
type Output = Self;
/// The bitwise and (`&`) of the bits in two flags values.
#[inline]
fn bitand(self, other: Self) -> Self { self.intersection(other) }
}
impl ::bitflags::__private::core::ops::BitAndAssign for
InternalBitFlags {
/// The bitwise and (`&`) of the bits in two flags values.
#[inline]
fn bitand_assign(&mut self, other: Self) {
*self =
Self::from_bits_retain(self.bits()).intersection(other);
}
}
impl ::bitflags::__private::core::ops::Sub for InternalBitFlags {
type Output = Self;
/// The intersection of a source flags value with the complement of a target flags value (`&!`).
///
/// This method is not equivalent to `self & !other` when `other` has unknown bits set.
/// `difference` won't truncate `other`, but the `!` operator will.
#[inline]
fn sub(self, other: Self) -> Self { self.difference(other) }
}
impl ::bitflags::__private::core::ops::SubAssign for InternalBitFlags
{
/// The intersection of a source flags value with the complement of a target flags value (`&!`).
///
/// This method is not equivalent to `self & !other` when `other` has unknown bits set.
/// `difference` won't truncate `other`, but the `!` operator will.
#[inline]
fn sub_assign(&mut self, other: Self) { self.remove(other); }
}
impl ::bitflags::__private::core::ops::Not for InternalBitFlags {
type Output = Self;
/// The bitwise negation (`!`) of the bits in a flags value, truncating the result.
#[inline]
fn not(self) -> Self { self.complement() }
}
impl ::bitflags::__private::core::iter::Extend<InternalBitFlags> for
InternalBitFlags {
/// The bitwise or (`|`) of the bits in each flags value.
fn extend<T: ::bitflags::__private::core::iter::IntoIterator<Item
= Self>>(&mut self, iterator: T) {
for item in iterator { self.insert(item) }
}
}
impl ::bitflags::__private::core::iter::FromIterator<InternalBitFlags>
for InternalBitFlags {
/// The bitwise or (`|`) of the bits in each flags value.
fn from_iter<T: ::bitflags::__private::core::iter::IntoIterator<Item
= Self>>(iterator: T) -> Self {
use ::bitflags::__private::core::iter::Extend;
let mut result = Self::empty();
result.extend(iterator);
result
}
}
impl InternalBitFlags {
/// Yield a set of contained flags values.
///
/// Each yielded flags value will correspond to a defined named flag. Any unknown bits
/// will be yielded together as a final flags value.
#[inline]
pub const fn iter(&self) -> ::bitflags::iter::Iter<Restrictions> {
::bitflags::iter::Iter::__private_const_new(<Restrictions as
::bitflags::Flags>::FLAGS,
Restrictions::from_bits_retain(self.bits()),
Restrictions::from_bits_retain(self.bits()))
}
/// Yield a set of contained named flags values.
///
/// This method is like [`iter`](#method.iter), except only yields bits in contained named flags.
/// Any unknown bits, or bits not corresponding to a contained flag will not be yielded.
#[inline]
pub const fn iter_names(&self)
-> ::bitflags::iter::IterNames<Restrictions> {
::bitflags::iter::IterNames::__private_const_new(<Restrictions
as ::bitflags::Flags>::FLAGS,
Restrictions::from_bits_retain(self.bits()),
Restrictions::from_bits_retain(self.bits()))
}
}
impl ::bitflags::__private::core::iter::IntoIterator for
InternalBitFlags {
type Item = Restrictions;
type IntoIter = ::bitflags::iter::Iter<Restrictions>;
fn into_iter(self) -> Self::IntoIter { self.iter() }
}
impl InternalBitFlags {
/// Returns a mutable reference to the raw value of the flags currently stored.
#[inline]
pub fn bits_mut(&mut self) -> &mut u8 { &mut self.0 }
}
#[allow(dead_code, deprecated, unused_attributes)]
impl Restrictions {
/// Get a flags value with all bits unset.
#[inline]
pub const fn empty() -> Self { Self(InternalBitFlags::empty()) }
/// Get a flags value with all known bits set.
#[inline]
pub const fn all() -> Self { Self(InternalBitFlags::all()) }
/// Get the underlying bits value.
///
/// The returned value is exactly the bits set in this flags value.
#[inline]
pub const fn bits(&self) -> u8 { self.0.bits() }
/// Convert from a bits value.
///
/// This method will return `None` if any unknown bits are set.
#[inline]
pub const fn from_bits(bits: u8)
-> ::bitflags::__private::core::option::Option<Self> {
match InternalBitFlags::from_bits(bits) {
::bitflags::__private::core::option::Option::Some(bits) =>
::bitflags::__private::core::option::Option::Some(Self(bits)),
::bitflags::__private::core::option::Option::None =>
::bitflags::__private::core::option::Option::None,
}
}
/// Convert from a bits value, unsetting any unknown bits.
#[inline]
pub const fn from_bits_truncate(bits: u8) -> Self {
Self(InternalBitFlags::from_bits_truncate(bits))
}
/// Convert from a bits value exactly.
#[inline]
pub const fn from_bits_retain(bits: u8) -> Self {
Self(InternalBitFlags::from_bits_retain(bits))
}
/// Get a flags value with the bits of a flag with the given name set.
///
/// This method will return `None` if `name` is empty or doesn't
/// correspond to any named flag.
#[inline]
pub fn from_name(name: &str)
-> ::bitflags::__private::core::option::Option<Self> {
match InternalBitFlags::from_name(name) {
::bitflags::__private::core::option::Option::Some(bits) =>
::bitflags::__private::core::option::Option::Some(Self(bits)),
::bitflags::__private::core::option::Option::None =>
::bitflags::__private::core::option::Option::None,
}
}
/// Whether all bits in this flags value are unset.
#[inline]
pub const fn is_empty(&self) -> bool { self.0.is_empty() }
/// Whether all known bits in this flags value are set.
#[inline]
pub const fn is_all(&self) -> bool { self.0.is_all() }
/// Whether any set bits in a source flags value are also set in a target flags value.
#[inline]
pub const fn intersects(&self, other: Self) -> bool {
self.0.intersects(other.0)
}
/// Whether all set bits in a source flags value are also set in a target flags value.
#[inline]
pub const fn contains(&self, other: Self) -> bool {
self.0.contains(other.0)
}
/// The bitwise or (`|`) of the bits in two flags values.
#[inline]
pub fn insert(&mut self, other: Self) { self.0.insert(other.0) }
/// The intersection of a source flags value with the complement of a target flags
/// value (`&!`).
///
/// This method is not equivalent to `self & !other` when `other` has unknown bits set.
/// `remove` won't truncate `other`, but the `!` operator will.
#[inline]
pub fn remove(&mut self, other: Self) { self.0.remove(other.0) }
/// The bitwise exclusive-or (`^`) of the bits in two flags values.
#[inline]
pub fn toggle(&mut self, other: Self) { self.0.toggle(other.0) }
/// Call `insert` when `value` is `true` or `remove` when `value` is `false`.
#[inline]
pub fn set(&mut self, other: Self, value: bool) {
self.0.set(other.0, value)
}
/// The bitwise and (`&`) of the bits in two flags values.
#[inline]
#[must_use]
pub const fn intersection(self, other: Self) -> Self {
Self(self.0.intersection(other.0))
}
/// The bitwise or (`|`) of the bits in two flags values.
#[inline]
#[must_use]
pub const fn union(self, other: Self) -> Self {
Self(self.0.union(other.0))
}
/// The intersection of a source flags value with the complement of a target flags
/// value (`&!`).
///
/// This method is not equivalent to `self & !other` when `other` has unknown bits set.
/// `difference` won't truncate `other`, but the `!` operator will.
#[inline]
#[must_use]
pub const fn difference(self, other: Self) -> Self {
Self(self.0.difference(other.0))
}
/// The bitwise exclusive-or (`^`) of the bits in two flags values.
#[inline]
#[must_use]
pub const fn symmetric_difference(self, other: Self) -> Self {
Self(self.0.symmetric_difference(other.0))
}
/// The bitwise negation (`!`) of the bits in a flags value, truncating the result.
#[inline]
#[must_use]
pub const fn complement(self) -> Self {
Self(self.0.complement())
}
}
impl ::bitflags::__private::core::fmt::Binary for Restrictions {
fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
-> ::bitflags::__private::core::fmt::Result {
let inner = self.0;
::bitflags::__private::core::fmt::Binary::fmt(&inner, f)
}
}
impl ::bitflags::__private::core::fmt::Octal for Restrictions {
fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
-> ::bitflags::__private::core::fmt::Result {
let inner = self.0;
::bitflags::__private::core::fmt::Octal::fmt(&inner, f)
}
}
impl ::bitflags::__private::core::fmt::LowerHex for Restrictions {
fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
-> ::bitflags::__private::core::fmt::Result {
let inner = self.0;
::bitflags::__private::core::fmt::LowerHex::fmt(&inner, f)
}
}
impl ::bitflags::__private::core::fmt::UpperHex for Restrictions {
fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
-> ::bitflags::__private::core::fmt::Result {
let inner = self.0;
::bitflags::__private::core::fmt::UpperHex::fmt(&inner, f)
}
}
impl ::bitflags::__private::core::ops::BitOr for Restrictions {
type Output = Self;
/// The bitwise or (`|`) of the bits in two flags values.
#[inline]
fn bitor(self, other: Restrictions) -> Self { self.union(other) }
}
impl ::bitflags::__private::core::ops::BitOrAssign for Restrictions {
/// The bitwise or (`|`) of the bits in two flags values.
#[inline]
fn bitor_assign(&mut self, other: Self) { self.insert(other); }
}
impl ::bitflags::__private::core::ops::BitXor for Restrictions {
type Output = Self;
/// The bitwise exclusive-or (`^`) of the bits in two flags values.
#[inline]
fn bitxor(self, other: Self) -> Self {
self.symmetric_difference(other)
}
}
impl ::bitflags::__private::core::ops::BitXorAssign for Restrictions {
/// The bitwise exclusive-or (`^`) of the bits in two flags values.
#[inline]
fn bitxor_assign(&mut self, other: Self) { self.toggle(other); }
}
impl ::bitflags::__private::core::ops::BitAnd for Restrictions {
type Output = Self;
/// The bitwise and (`&`) of the bits in two flags values.
#[inline]
fn bitand(self, other: Self) -> Self { self.intersection(other) }
}
impl ::bitflags::__private::core::ops::BitAndAssign for Restrictions {
/// The bitwise and (`&`) of the bits in two flags values.
#[inline]
fn bitand_assign(&mut self, other: Self) {
*self =
Self::from_bits_retain(self.bits()).intersection(other);
}
}
impl ::bitflags::__private::core::ops::Sub for Restrictions {
type Output = Self;
/// The intersection of a source flags value with the complement of a target flags value (`&!`).
///
/// This method is not equivalent to `self & !other` when `other` has unknown bits set.
/// `difference` won't truncate `other`, but the `!` operator will.
#[inline]
fn sub(self, other: Self) -> Self { self.difference(other) }
}
impl ::bitflags::__private::core::ops::SubAssign for Restrictions {
/// The intersection of a source flags value with the complement of a target flags value (`&!`).
///
/// This method is not equivalent to `self & !other` when `other` has unknown bits set.
/// `difference` won't truncate `other`, but the `!` operator will.
#[inline]
fn sub_assign(&mut self, other: Self) { self.remove(other); }
}
impl ::bitflags::__private::core::ops::Not for Restrictions {
type Output = Self;
/// The bitwise negation (`!`) of the bits in a flags value, truncating the result.
#[inline]
fn not(self) -> Self { self.complement() }
}
impl ::bitflags::__private::core::iter::Extend<Restrictions> for
Restrictions {
/// The bitwise or (`|`) of the bits in each flags value.
fn extend<T: ::bitflags::__private::core::iter::IntoIterator<Item
= Self>>(&mut self, iterator: T) {
for item in iterator { self.insert(item) }
}
}
impl ::bitflags::__private::core::iter::FromIterator<Restrictions> for
Restrictions {
/// The bitwise or (`|`) of the bits in each flags value.
fn from_iter<T: ::bitflags::__private::core::iter::IntoIterator<Item
= Self>>(iterator: T) -> Self {
use ::bitflags::__private::core::iter::Extend;
let mut result = Self::empty();
result.extend(iterator);
result
}
}
impl Restrictions {
/// Yield a set of contained flags values.
///
/// Each yielded flags value will correspond to a defined named flag. Any unknown bits
/// will be yielded together as a final flags value.
#[inline]
pub const fn iter(&self) -> ::bitflags::iter::Iter<Restrictions> {
::bitflags::iter::Iter::__private_const_new(<Restrictions as
::bitflags::Flags>::FLAGS,
Restrictions::from_bits_retain(self.bits()),
Restrictions::from_bits_retain(self.bits()))
}
/// Yield a set of contained named flags values.
///
/// This method is like [`iter`](#method.iter), except only yields bits in contained named flags.
/// Any unknown bits, or bits not corresponding to a contained flag will not be yielded.
#[inline]
pub const fn iter_names(&self)
-> ::bitflags::iter::IterNames<Restrictions> {
::bitflags::iter::IterNames::__private_const_new(<Restrictions
as ::bitflags::Flags>::FLAGS,
Restrictions::from_bits_retain(self.bits()),
Restrictions::from_bits_retain(self.bits()))
}
}
impl ::bitflags::__private::core::iter::IntoIterator for Restrictions
{
type Item = Restrictions;
type IntoIter = ::bitflags::iter::Iter<Restrictions>;
fn into_iter(self) -> Self::IntoIter { self.iter() }
}
};Clone, #[automatically_derived]
impl ::core::marker::Copy for Restrictions { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for Restrictions {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Restrictions",
&&self.0)
}
}Debug)]
73struct Restrictions: u8 {
74/// Restricts expressions for use in statement position.
75 ///
76 /// When expressions are used in various places, like statements or
77 /// match arms, this is used to stop parsing once certain tokens are
78 /// reached.
79 ///
80 /// For example, `if true {} & 1` with `STMT_EXPR` in effect is parsed
81 /// as two separate expression statements (`if` and a reference to 1).
82 /// Otherwise it is parsed as a bitwise AND where `if` is on the left
83 /// and 1 is on the right.
84const STMT_EXPR = 1 << 0;
85/// Do not allow struct literals.
86 ///
87 /// There are several places in the grammar where we don't want to
88 /// allow struct literals because they can require lookahead, or
89 /// otherwise could be ambiguous or cause confusion. For example,
90 /// `if Foo {} {}` isn't clear if it is `Foo{}` struct literal, or
91 /// just `Foo` is the condition, followed by a consequent block,
92 /// followed by an empty block.
93 ///
94 /// See [RFC 92](https://rust-lang.github.io/rfcs/0092-struct-grammar.html).
95const NO_STRUCT_LITERAL = 1 << 1;
96/// Used to provide better error messages for const generic arguments.
97 ///
98 /// An un-braced const generic argument is limited to a very small
99 /// subset of expressions. This is used to detect the situation where
100 /// an expression outside of that subset is used, and to suggest to
101 /// wrap the expression in braces.
102const CONST_EXPR = 1 << 2;
103/// Allows `let` expressions.
104 ///
105 /// `let pattern = scrutinee` is parsed as an expression, but it is
106 /// only allowed in let chains (`if` and `while` conditions).
107 /// Otherwise it is not an expression (note that `let` in statement
108 /// positions is treated as a `StmtKind::Let` statement, which has a
109 /// slightly different grammar).
110const ALLOW_LET = 1 << 3;
111/// Used to detect a missing `=>` in a match guard.
112 ///
113 /// This is used for error handling in a match guard to give a better
114 /// error message if the `=>` is missing. It is set when parsing the
115 /// guard expression.
116const IN_IF_GUARD = 1 << 4;
117/// Used to detect the incorrect use of expressions in patterns.
118 ///
119 /// This is used for error handling while parsing a pattern. During
120 /// error recovery, this will be set to try to parse the pattern as an
121 /// expression, but halts parsing the expression when reaching certain
122 /// tokens like `=`.
123const IS_PAT = 1 << 5;
124 }
125}
126127#[derive(#[automatically_derived]
impl ::core::clone::Clone for SemiColonMode {
#[inline]
fn clone(&self) -> SemiColonMode { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for SemiColonMode { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for SemiColonMode {
#[inline]
fn eq(&self, other: &SemiColonMode) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::fmt::Debug for SemiColonMode {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
SemiColonMode::Break => "Break",
SemiColonMode::Ignore => "Ignore",
SemiColonMode::Comma => "Comma",
})
}
}Debug)]
128enum SemiColonMode {
129 Break,
130 Ignore,
131 Comma,
132}
133134#[derive(#[automatically_derived]
impl ::core::clone::Clone for BlockMode {
#[inline]
fn clone(&self) -> BlockMode { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for BlockMode { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for BlockMode {
#[inline]
fn eq(&self, other: &BlockMode) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::fmt::Debug for BlockMode {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
BlockMode::Break => "Break",
BlockMode::Ignore => "Ignore",
})
}
}Debug)]
135enum BlockMode {
136 Break,
137 Ignore,
138}
139140/// Whether or not we should force collection of tokens for an AST node,
141/// regardless of whether or not it has attributes
142#[derive(#[automatically_derived]
impl ::core::clone::Clone for ForceCollect {
#[inline]
fn clone(&self) -> ForceCollect { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for ForceCollect { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for ForceCollect {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
ForceCollect::Yes => "Yes",
ForceCollect::No => "No",
})
}
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for ForceCollect {
#[inline]
fn eq(&self, other: &ForceCollect) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq)]
143pub enum ForceCollect {
144 Yes,
145 No,
146}
147148/// Whether to accept `const { ... }` as a shorthand for `const _: () = const { ... }`.
149#[derive(#[automatically_derived]
impl ::core::clone::Clone for AllowConstBlockItems {
#[inline]
fn clone(&self) -> AllowConstBlockItems { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for AllowConstBlockItems { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for AllowConstBlockItems {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
AllowConstBlockItems::Yes => "Yes",
AllowConstBlockItems::No => "No",
AllowConstBlockItems::DoesNotMatter => "DoesNotMatter",
})
}
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for AllowConstBlockItems {
#[inline]
fn eq(&self, other: &AllowConstBlockItems) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for AllowConstBlockItems {
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {}
}Eq)]
150pub enum AllowConstBlockItems {
151 Yes,
152 No,
153 DoesNotMatter,
154}
155156/// If the next tokens are ill-formed `$ty::` recover them as `<$ty>::`.
157#[macro_export]
158macro_rules!maybe_recover_from_interpolated_ty_qpath {
159 ($self: expr, $allow_qpath_recovery: expr) => {
160if $allow_qpath_recovery
161&& $self.may_recover()
162 && let Some(mv_kind) = $self.token.is_metavar_seq()
163 && let token::MetaVarKind::Ty { .. } = mv_kind
164 && $self.check_noexpect_past_close_delim(&token::PathSep)
165 {
166// Reparse the type, then move to recovery.
167let ty = $self
168.eat_metavar_seq(mv_kind, |this| this.parse_ty_no_question_mark_recover())
169 .expect("metavar seq ty");
170171return $self.maybe_recover_from_bad_qpath_stage_2($self.prev_token.span, ty);
172 }
173 };
174}
175176#[derive(#[automatically_derived]
impl ::core::clone::Clone for Recovery {
#[inline]
fn clone(&self) -> Recovery { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for Recovery { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for Recovery {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
Recovery::Allowed => "Allowed",
Recovery::Forbidden => "Forbidden",
})
}
}Debug)]
177pub enum Recovery {
178 Allowed,
179 Forbidden,
180}
181182#[derive(#[automatically_derived]
impl<'a> ::core::clone::Clone for Parser<'a> {
#[inline]
fn clone(&self) -> Parser<'a> {
Parser {
psess: ::core::clone::Clone::clone(&self.psess),
token: ::core::clone::Clone::clone(&self.token),
token_spacing: ::core::clone::Clone::clone(&self.token_spacing),
prev_token: ::core::clone::Clone::clone(&self.prev_token),
capture_cfg: ::core::clone::Clone::clone(&self.capture_cfg),
restrictions: ::core::clone::Clone::clone(&self.restrictions),
expected_token_types: ::core::clone::Clone::clone(&self.expected_token_types),
token_cursor: ::core::clone::Clone::clone(&self.token_cursor),
num_bump_calls: ::core::clone::Clone::clone(&self.num_bump_calls),
break_last_token: ::core::clone::Clone::clone(&self.break_last_token),
unmatched_angle_bracket_count: ::core::clone::Clone::clone(&self.unmatched_angle_bracket_count),
angle_bracket_nesting: ::core::clone::Clone::clone(&self.angle_bracket_nesting),
parsing_generics: ::core::clone::Clone::clone(&self.parsing_generics),
last_unexpected_token_span: ::core::clone::Clone::clone(&self.last_unexpected_token_span),
subparser_name: ::core::clone::Clone::clone(&self.subparser_name),
capture_state: ::core::clone::Clone::clone(&self.capture_state),
current_closure: ::core::clone::Clone::clone(&self.current_closure),
recovery: ::core::clone::Clone::clone(&self.recovery),
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)]
183pub struct Parser<'a> {
184pub psess: &'a ParseSess,
185/// The current token.
186pub token: Token = Token::dummy(),
187/// The spacing for the current token.
188token_spacing: Spacing = Spacing::Alone,
189/// The previous token.
190pub prev_token: Token = Token::dummy(),
191pub capture_cfg: bool = false,
192 restrictions: Restrictions = Restrictions::empty(),
193 expected_token_types: TokenTypeSet = TokenTypeSet::new(),
194 token_cursor: TokenCursor,
195// The number of calls to `bump`, i.e. the position in the token stream.
196num_bump_calls: u32 = 0,
197// During parsing we may sometimes need to "unglue" a glued token into two
198 // or three component tokens (e.g. `>>` into `>` and `>`, or `>>=` into `>`
199 // and `>` and `=`), so the parser can consume them one at a time. This
200 // process bypasses the normal capturing mechanism (e.g. `num_bump_calls`
201 // will not be incremented), since the "unglued" tokens due not exist in
202 // the original `TokenStream`.
203 //
204 // If we end up consuming all the component tokens, this is not an issue,
205 // because we'll end up capturing the single "glued" token.
206 //
207 // However, sometimes we may want to capture not all of the original
208 // token. For example, capturing the `Vec<u8>` in `Option<Vec<u8>>`
209 // requires us to unglue the trailing `>>` token. The `break_last_token`
210 // field is used to track these tokens. They get appended to the captured
211 // stream when we evaluate a `LazyAttrTokenStream`.
212 //
213 // This value is always 0, 1, or 2. It can only reach 2 when splitting
214 // `>>=` or `<<=`.
215break_last_token: u32 = 0,
216/// This field is used to keep track of how many left angle brackets we have seen. This is
217 /// required in order to detect extra leading left angle brackets (`<` characters) and error
218 /// appropriately.
219 ///
220 /// See the comments in the `parse_path_segment` function for more details.
221unmatched_angle_bracket_count: u16 = 0,
222 angle_bracket_nesting: u16 = 0,
223/// Keep track of when we're within `<...>` for proper error recovery.
224parsing_generics: bool = false,
225226 last_unexpected_token_span: Option<Span> = None,
227/// If present, this `Parser` is not parsing Rust code but rather a macro call.
228subparser_name: Option<&'static str>,
229 capture_state: CaptureState,
230/// This allows us to recover when the user forget to add braces around
231 /// multiple statements in the closure body.
232current_closure: Option<ClosureSpans> = None,
233/// Whether the parser is allowed to do recovery.
234 /// This is disabled when parsing macro arguments, see #103534
235recovery: Recovery = Recovery::Allowed,
236/// Whether we're parsing a function body.
237in_fn_body: bool = false,
238/// Whether we have detected a missing semicolon in function body.
239pub fn_body_missing_semi_guar: Option<ErrorGuaranteed> = None,
240}
241242// This type is used a lot, e.g. it's cloned when matching many declarative macro rules with
243// nonterminals. Make sure it doesn't unintentionally get bigger. We only check a few arches
244// though, because `TokenTypeSet(u128)` alignment varies on others, changing the total size.
245#[cfg(all(target_pointer_width = "64", any(target_arch = "aarch64", target_arch = "x86_64")))]
246const _: [(); 288] = [(); ::std::mem::size_of::<Parser<'_>>()];rustc_data_structures::static_assert_size!(Parser<'_>, 288);
247248/// Stores span information about a closure.
249#[derive(#[automatically_derived]
impl ::core::clone::Clone for ClosureSpans {
#[inline]
fn clone(&self) -> ClosureSpans {
ClosureSpans {
whole_closure: ::core::clone::Clone::clone(&self.whole_closure),
closing_pipe: ::core::clone::Clone::clone(&self.closing_pipe),
body: ::core::clone::Clone::clone(&self.body),
}
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for ClosureSpans {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f, "ClosureSpans",
"whole_closure", &self.whole_closure, "closing_pipe",
&self.closing_pipe, "body", &&self.body)
}
}Debug)]
250struct ClosureSpans {
251 whole_closure: Span,
252 closing_pipe: Span,
253 body: Span,
254}
255256/// Controls how we capture tokens. Capturing can be expensive,
257/// so we try to avoid performing capturing in cases where
258/// we will never need an `AttrTokenStream`.
259#[derive(#[automatically_derived]
impl ::core::marker::Copy for Capturing { }Copy, #[automatically_derived]
impl ::core::clone::Clone for Capturing {
#[inline]
fn clone(&self) -> Capturing { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for Capturing {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self { Capturing::No => "No", Capturing::Yes => "Yes", })
}
}Debug)]
260enum Capturing {
261/// We aren't performing any capturing - this is the default mode.
262No,
263/// We are capturing tokens
264Yes,
265}
266267// This state is used by `Parser::collect_tokens`.
268#[derive(#[automatically_derived]
impl ::core::clone::Clone for CaptureState {
#[inline]
fn clone(&self) -> CaptureState {
CaptureState {
capturing: ::core::clone::Clone::clone(&self.capturing),
parser_replacements: ::core::clone::Clone::clone(&self.parser_replacements),
inner_attr_parser_ranges: ::core::clone::Clone::clone(&self.inner_attr_parser_ranges),
seen_attrs: ::core::clone::Clone::clone(&self.seen_attrs),
}
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for CaptureState {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field4_finish(f, "CaptureState",
"capturing", &self.capturing, "parser_replacements",
&self.parser_replacements, "inner_attr_parser_ranges",
&self.inner_attr_parser_ranges, "seen_attrs", &&self.seen_attrs)
}
}Debug)]
269struct CaptureState {
270 capturing: Capturing,
271 parser_replacements: Vec<ParserReplacement>,
272 inner_attr_parser_ranges: FxHashMap<AttrId, ParserRange>,
273// `IntervalSet` is good for perf because attrs are mostly added to this
274 // set in contiguous ranges.
275seen_attrs: IntervalSet<AttrId>,
276}
277278/// A sequence separator.
279#[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)]
280struct SeqSep {
281/// The separator token.
282sep: Option<ExpTokenPair>,
283/// `true` if a trailing separator is allowed.
284trailing_sep_allowed: bool,
285}
286287impl SeqSep {
288fn trailing_allowed(sep: ExpTokenPair) -> SeqSep {
289SeqSep { sep: Some(sep), trailing_sep_allowed: true }
290 }
291292fn none() -> SeqSep {
293SeqSep { sep: None, trailing_sep_allowed: false }
294 }
295}
296297#[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)]
298pub enum FollowedByType {
299 Yes,
300 No,
301}
302303#[derive(#[automatically_derived]
impl ::core::marker::Copy for Trailing { }Copy, #[automatically_derived]
impl ::core::clone::Clone for Trailing {
#[inline]
fn clone(&self) -> Trailing { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for Trailing {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self { Trailing::No => "No", Trailing::Yes => "Yes", })
}
}Debug)]
304pub enum Trailing {
305 No,
306 Yes,
307}
308309impl From<bool> for Trailing {
310fn from(b: bool) -> Trailing {
311if b { Trailing::Yes } else { Trailing::No }
312 }
313}
314315pub fn token_descr(token: &Token) -> String {
316let s = pprust::token_to_string(token).to_string();
317318match (TokenDescription::from_token(token), &token.kind) {
319 (Some(TokenDescription::ReservedIdentifier), _) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("reserved identifier `{0}`", s))
})format!("reserved identifier `{s}`"),
320 (Some(TokenDescription::Keyword), _) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("keyword `{0}`", s))
})format!("keyword `{s}`"),
321 (Some(TokenDescription::ReservedKeyword), _) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("reserved keyword `{0}`", s))
})format!("reserved keyword `{s}`"),
322 (Some(TokenDescription::DocComment), _) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("doc comment `{0}`", s))
})format!("doc comment `{s}`"),
323// Deliberately doesn't print `s`, which is empty.
324 (Some(TokenDescription::MetaVar(kind)), _) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` metavariable", kind))
})format!("`{kind}` metavariable"),
325 (None, TokenKind::NtIdent(..)) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("identifier `{0}`", s))
})format!("identifier `{s}`"),
326 (None, TokenKind::NtLifetime(..)) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("lifetime `{0}`", s))
})format!("lifetime `{s}`"),
327 (None, _) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", s))
})format!("`{s}`"),
328 }
329}
330331impl<'a> Parser<'a> {
332pub fn new(
333 psess: &'a ParseSess,
334 stream: TokenStream,
335 subparser_name: Option<&'static str>,
336 ) -> Self {
337let mut parser = Parser {
338psess,
339 token_cursor: TokenCursor { curr: TokenTreeCursor::new(stream), stack: Vec::new() },
340subparser_name,
341 capture_state: CaptureState {
342 capturing: Capturing::No,
343 parser_replacements: Vec::new(),
344 inner_attr_parser_ranges: Default::default(),
345 seen_attrs: IntervalSet::new(u32::MAXas usize),
346 },
347 ..
348 };
349350// Make parser point to the first token.
351parser.bump();
352353// Change this from 1 back to 0 after the bump. This eases debugging of
354 // `Parser::collect_tokens` because 0-indexed token positions are nicer
355 // than 1-indexed token positions.
356parser.num_bump_calls = 0;
357358parser359 }
360361#[inline]
362pub fn recovery(mut self, recovery: Recovery) -> Self {
363self.recovery = recovery;
364self365 }
366367#[inline]
368fn with_recovery<T>(&mut self, recovery: Recovery, f: impl FnOnce(&mut Self) -> T) -> T {
369let old = mem::replace(&mut self.recovery, recovery);
370let res = f(self);
371self.recovery = old;
372res373 }
374375/// Whether the parser is allowed to recover from broken code.
376 ///
377 /// If this returns false, recovering broken code into valid code (especially if this recovery does lookahead)
378 /// is not allowed. All recovery done by the parser must be gated behind this check.
379 ///
380 /// Technically, this only needs to restrict eager recovery by doing lookahead at more tokens.
381 /// But making the distinction is very subtle, and simply forbidding all recovery is a lot simpler to uphold.
382#[inline]
383fn may_recover(&self) -> bool {
384#[allow(non_exhaustive_omitted_patterns)] match self.recovery {
Recovery::Allowed => true,
_ => false,
}matches!(self.recovery, Recovery::Allowed)385 }
386387/// Version of [`unexpected`](Parser::unexpected) that "returns" any type in the `Ok`
388 /// (both those functions never return "Ok", and so can lie like that in the type).
389pub fn unexpected_any<T>(&mut self) -> PResult<'a, T> {
390match self.expect_one_of(&[], &[]) {
391Err(e) => Err(e),
392// We can get `Ok(true)` from `recover_closing_delimiter`
393 // which is called in `expected_one_of_not_found`.
394Ok(_) => FatalError.raise(),
395 }
396 }
397398pub fn unexpected(&mut self) -> PResult<'a, ()> {
399self.unexpected_any()
400 }
401402/// Expects and consumes the token `t`. Signals an error if the next token is not `t`.
403pub fn expect(&mut self, exp: ExpTokenPair) -> PResult<'a, Recovered> {
404if self.expected_token_types.is_empty() {
405if self.token == exp.tok {
406self.bump();
407Ok(Recovered::No)
408 } else {
409self.unexpected_try_recover(&exp.tok)
410 }
411 } else {
412self.expect_one_of(slice::from_ref(&exp), &[])
413 }
414 }
415416/// Expect next token to be edible or inedible token. If edible,
417 /// then consume it; if inedible, then return without consuming
418 /// anything. Signal a fatal error if next token is unexpected.
419fn expect_one_of(
420&mut self,
421 edible: &[ExpTokenPair],
422 inedible: &[ExpTokenPair],
423 ) -> PResult<'a, Recovered> {
424if edible.iter().any(|exp| exp.tok == self.token.kind) {
425self.bump();
426Ok(Recovered::No)
427 } else if inedible.iter().any(|exp| exp.tok == self.token.kind) {
428// leave it in the input
429Ok(Recovered::No)
430 } else if self.token != token::Eof431 && self.last_unexpected_token_span == Some(self.token.span)
432 {
433FatalError.raise();
434 } else {
435self.expected_one_of_not_found(edible, inedible)
436 .map(|error_guaranteed| Recovered::Yes(error_guaranteed))
437 }
438 }
439440// Public for rustfmt usage.
441pub fn parse_ident(&mut self) -> PResult<'a, Ident> {
442self.parse_ident_common(self.may_recover())
443 }
444445pub(crate) fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, Ident> {
446let (ident, is_raw) = self.ident_or_err(recover)?;
447448if is_raw == IdentIsRaw::No && ident.is_reserved() {
449let err = self.expected_ident_found_err();
450if recover {
451err.emit();
452 } else {
453return Err(err);
454 }
455 }
456self.bump();
457Ok(ident)
458 }
459460fn ident_or_err(&mut self, recover: bool) -> PResult<'a, (Ident, IdentIsRaw)> {
461match self.token.ident() {
462Some(ident) => Ok(ident),
463None => self.expected_ident_found(recover),
464 }
465 }
466467/// Checks if the next token is `tok`, and returns `true` if so.
468 ///
469 /// This method will automatically add `tok` to `expected_token_types` if `tok` is not
470 /// encountered.
471#[inline]
472pub fn check(&mut self, exp: ExpTokenPair) -> bool {
473let is_present = self.token == exp.tok;
474if !is_present {
475self.expected_token_types.insert(exp.token_type);
476 }
477is_present478 }
479480#[inline]
481 #[must_use]
482fn check_noexpect(&self, tok: &TokenKind) -> bool {
483self.token == *tok484 }
485486// Check the first token after the delimiter that closes the current
487 // delimited sequence. (Panics if used in the outermost token stream, which
488 // has no delimiters.) It uses a clone of the relevant tree cursor to skip
489 // past the entire `TokenTree::Delimited` in a single step, avoiding the
490 // need for unbounded token lookahead.
491 //
492 // Primarily used when `self.token` matches `OpenInvisible(_))`, to look
493 // ahead through the current metavar expansion.
494fn check_noexpect_past_close_delim(&self, tok: &TokenKind) -> bool {
495let mut tree_cursor = self.token_cursor.stack.last().unwrap().clone();
496tree_cursor.bump();
497#[allow(non_exhaustive_omitted_patterns)] match tree_cursor.curr() {
Some(TokenTree::Token(token::Token { kind, .. }, _)) if kind == tok =>
true,
_ => false,
}matches!(
498 tree_cursor.curr(),
499Some(TokenTree::Token(token::Token { kind, .. }, _)) if kind == tok
500 )501 }
502503/// Consumes a token 'tok' if it exists. Returns whether the given token was present.
504 ///
505 /// the main purpose of this function is to reduce the cluttering of the suggestions list
506 /// which using the normal eat method could introduce in some cases.
507#[inline]
508 #[must_use]
509fn eat_noexpect(&mut self, tok: &TokenKind) -> bool {
510let is_present = self.check_noexpect(tok);
511if is_present {
512self.bump()
513 }
514is_present515 }
516517/// Consumes a token 'tok' if it exists. Returns whether the given token was present.
518#[inline]
519 #[must_use]
520pub fn eat(&mut self, exp: ExpTokenPair) -> bool {
521let is_present = self.check(exp);
522if is_present {
523self.bump()
524 }
525is_present526 }
527528/// If the next token is the given keyword, returns `true` without eating it.
529 /// An expectation is also added for diagnostics purposes.
530#[inline]
531 #[must_use]
532fn check_keyword(&mut self, exp: ExpKeywordPair) -> bool {
533let is_keyword = self.token.is_keyword(exp.kw);
534if !is_keyword {
535self.expected_token_types.insert(exp.token_type);
536 }
537is_keyword538 }
539540#[inline]
541 #[must_use]
542fn check_keyword_case(&mut self, exp: ExpKeywordPair, case: Case) -> bool {
543if self.check_keyword(exp) {
544true
545} else if case == Case::Insensitive546 && let Some((ident, IdentIsRaw::No)) = self.token.ident()
547// Do an ASCII case-insensitive match, because all keywords are ASCII.
548&& ident.as_str().eq_ignore_ascii_case(exp.kw.as_str())
549 {
550true
551} else {
552false
553}
554 }
555556/// If the next token is the given keyword, eats it and returns `true`.
557 /// Otherwise, returns `false`. An expectation is also added for diagnostics purposes.
558// Public for rustc_builtin_macros and rustfmt usage.
559#[inline]
560 #[must_use]
561pub fn eat_keyword(&mut self, exp: ExpKeywordPair) -> bool {
562let is_keyword = self.check_keyword(exp);
563if is_keyword {
564self.bump();
565 }
566is_keyword567 }
568569/// Eats a keyword, optionally ignoring the case.
570 /// If the case differs (and is ignored) an error is issued.
571 /// This is useful for recovery.
572#[inline]
573 #[must_use]
574fn eat_keyword_case(&mut self, exp: ExpKeywordPair, case: Case) -> bool {
575if self.eat_keyword(exp) {
576true
577} else if case == Case::Insensitive578 && let Some((ident, IdentIsRaw::No)) = self.token.ident()
579// Do an ASCII case-insensitive match, because all keywords are ASCII.
580&& ident.as_str().eq_ignore_ascii_case(exp.kw.as_str())
581 {
582let kw = exp.kw.as_str();
583let is_upper = kw.chars().all(char::is_uppercase);
584let is_lower = kw.chars().all(char::is_lowercase);
585586let case = match (is_upper, is_lower) {
587 (true, true) => {
588{
::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")589 }
590 (true, false) => errors::Case::Upper,
591 (false, true) => errors::Case::Lower,
592 (false, false) => errors::Case::Mixed,
593 };
594595self.dcx().emit_err(errors::KwBadCase { span: ident.span, kw, case });
596self.bump();
597true
598} else {
599false
600}
601 }
602603/// If the next token is the given keyword, eats it and returns `true`.
604 /// Otherwise, returns `false`. No expectation is added.
605// Public for rustc_builtin_macros usage.
606#[inline]
607 #[must_use]
608pub fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool {
609let is_keyword = self.token.is_keyword(kw);
610if is_keyword {
611self.bump();
612 }
613is_keyword614 }
615616/// If the given word is not a keyword, signals an error.
617 /// If the next token is not the given word, signals an error.
618 /// Otherwise, eats it.
619pub fn expect_keyword(&mut self, exp: ExpKeywordPair) -> PResult<'a, ()> {
620if !self.eat_keyword(exp) { self.unexpected() } else { Ok(()) }
621 }
622623/// Consume a sequence produced by a metavar expansion, if present.
624pub fn eat_metavar_seq<T>(
625&mut self,
626 mv_kind: MetaVarKind,
627 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
628 ) -> Option<T> {
629self.eat_metavar_seq_with_matcher(|mvk| mvk == mv_kind, f)
630 }
631632/// A slightly more general form of `eat_metavar_seq`, for use with the
633 /// `MetaVarKind` variants that have parameters, where an exact match isn't
634 /// desired.
635fn eat_metavar_seq_with_matcher<T>(
636&mut self,
637 match_mv_kind: impl Fn(MetaVarKind) -> bool,
638mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
639 ) -> Option<T> {
640if let token::OpenInvisible(InvisibleOrigin::MetaVar(mv_kind)) = self.token.kind
641 && match_mv_kind(mv_kind)
642 {
643self.bump();
644645// Recovery is disabled when parsing macro arguments, so it must
646 // also be disabled when reparsing pasted macro arguments,
647 // otherwise we get inconsistent results (e.g. #137874).
648let res = self.with_recovery(Recovery::Forbidden, |this| f(this));
649650let res = match res {
651Ok(res) => res,
652Err(err) => {
653// This can occur in unusual error cases, e.g. #139445.
654err.delay_as_bug();
655return None;
656 }
657 };
658659if let token::CloseInvisible(InvisibleOrigin::MetaVar(mv_kind)) = self.token.kind
660 && match_mv_kind(mv_kind)
661 {
662self.bump();
663Some(res)
664 } else {
665// This can occur when invalid syntax is passed to a decl macro. E.g. see #139248,
666 // where the reparse attempt of an invalid expr consumed the trailing invisible
667 // delimiter.
668self.dcx()
669 .span_delayed_bug(self.token.span, "no close delim with reparsing {mv_kind:?}");
670None671 }
672 } else {
673None674 }
675 }
676677/// Is the given keyword `kw` followed by a non-reserved identifier?
678fn is_kw_followed_by_ident(&self, kw: Symbol) -> bool {
679self.token.is_keyword(kw) && self.look_ahead(1, |t| t.is_non_reserved_ident())
680 }
681682#[inline]
683fn check_or_expected(&mut self, ok: bool, token_type: TokenType) -> bool {
684if !ok {
685self.expected_token_types.insert(token_type);
686 }
687ok688 }
689690fn check_ident(&mut self) -> bool {
691self.check_or_expected(self.token.is_ident(), TokenType::Ident)
692 }
693694fn check_path(&mut self) -> bool {
695self.check_or_expected(self.token.is_path_start(), TokenType::Path)
696 }
697698fn check_type(&mut self) -> bool {
699self.check_or_expected(self.token.can_begin_type(), TokenType::Type)
700 }
701702fn check_const_arg(&mut self) -> bool {
703let is_mcg_arg = self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const);
704let is_mgca_arg = self.is_keyword_ahead(0, &[kw::Const])
705 && self.look_ahead(1, |t| *t == token::OpenBrace);
706is_mcg_arg || is_mgca_arg707 }
708709fn check_const_closure(&self) -> bool {
710self.is_keyword_ahead(0, &[kw::Const])
711 && self.look_ahead(1, |t| match &t.kind {
712// async closures do not work with const closures, so we do not parse that here.
713token::Ident(kw::Move | kw::Use | kw::Static, IdentIsRaw::No)
714 | token::OrOr715 | token::Or => true,
716_ => false,
717 })
718 }
719720fn check_inline_const(&self, dist: usize) -> bool {
721self.is_keyword_ahead(dist, &[kw::Const])
722 && self.look_ahead(dist + 1, |t| match &t.kind {
723 token::OpenBrace => true,
724 token::OpenInvisible(InvisibleOrigin::MetaVar(MetaVarKind::Block)) => true,
725_ => false,
726 })
727 }
728729/// Checks to see if the next token is either `+` or `+=`.
730 /// Otherwise returns `false`.
731#[inline]
732fn check_plus(&mut self) -> bool {
733self.check_or_expected(self.token.is_like_plus(), TokenType::Plus)
734 }
735736/// Eats the expected token if it's present possibly breaking
737 /// compound tokens like multi-character operators in process.
738 /// Returns `true` if the token was eaten.
739fn break_and_eat(&mut self, exp: ExpTokenPair) -> bool {
740if self.token == exp.tok {
741self.bump();
742return true;
743 }
744match self.token.kind.break_two_token_op(1) {
745Some((first, second)) if first == exp.tok => {
746let first_span = self.psess.source_map().start_point(self.token.span);
747let second_span = self.token.span.with_lo(first_span.hi());
748self.token = Token::new(first, first_span);
749// Keep track of this token - if we end token capturing now,
750 // we'll want to append this token to the captured stream.
751 //
752 // If we consume any additional tokens, then this token
753 // is not needed (we'll capture the entire 'glued' token),
754 // and `bump` will set this field to 0.
755self.break_last_token += 1;
756// Use the spacing of the glued token as the spacing of the
757 // unglued second token.
758self.bump_with((Token::new(second, second_span), self.token_spacing));
759true
760}
761_ => {
762self.expected_token_types.insert(exp.token_type);
763false
764}
765 }
766 }
767768/// Eats `+` possibly breaking tokens like `+=` in process.
769fn eat_plus(&mut self) -> bool {
770self.break_and_eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Plus,
token_type: crate::parser::token_type::TokenType::Plus,
}exp!(Plus))
771 }
772773/// Eats `&` possibly breaking tokens like `&&` in process.
774 /// Signals an error if `&` is not eaten.
775fn expect_and(&mut self) -> PResult<'a, ()> {
776if 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() }
777 }
778779/// Eats `|` possibly breaking tokens like `||` in process.
780 /// Signals an error if `|` was not eaten.
781fn expect_or(&mut self) -> PResult<'a, ()> {
782if 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() }
783 }
784785/// Eats `<` possibly breaking tokens like `<<` in process.
786fn eat_lt(&mut self) -> bool {
787let 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));
788if ate {
789// See doc comment for `unmatched_angle_bracket_count`.
790self.unmatched_angle_bracket_count += 1;
791{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_parse/src/parser/mod.rs:791",
"rustc_parse::parser", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_parse/src/parser/mod.rs"),
::tracing_core::__macro_support::Option::Some(791u32),
::tracing_core::__macro_support::Option::Some("rustc_parse::parser"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("eat_lt: (increment) count={0:?}",
self.unmatched_angle_bracket_count) as &dyn Value))])
});
} else { ; }
};debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count);
792 }
793ate794 }
795796/// Eats `<` possibly breaking tokens like `<<` in process.
797 /// Signals an error if `<` was not eaten.
798fn expect_lt(&mut self) -> PResult<'a, ()> {
799if self.eat_lt() { Ok(()) } else { self.unexpected() }
800 }
801802/// Eats `>` possibly breaking tokens like `>>` in process.
803 /// Signals an error if `>` was not eaten.
804fn expect_gt(&mut self) -> PResult<'a, ()> {
805if self.break_and_eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Gt,
token_type: crate::parser::token_type::TokenType::Gt,
}exp!(Gt)) {
806// See doc comment for `unmatched_angle_bracket_count`.
807if self.unmatched_angle_bracket_count > 0 {
808self.unmatched_angle_bracket_count -= 1;
809{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_parse/src/parser/mod.rs:809",
"rustc_parse::parser", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_parse/src/parser/mod.rs"),
::tracing_core::__macro_support::Option::Some(809u32),
::tracing_core::__macro_support::Option::Some("rustc_parse::parser"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("expect_gt: (decrement) count={0:?}",
self.unmatched_angle_bracket_count) as &dyn Value))])
});
} else { ; }
};debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count);
810 }
811Ok(())
812 } else {
813self.unexpected()
814 }
815 }
816817/// Checks if the next token is contained within `closes`, and returns `true` if so.
818fn expect_any_with_type(
819&mut self,
820 closes_expected: &[ExpTokenPair],
821 closes_not_expected: &[&TokenKind],
822 ) -> bool {
823closes_expected.iter().any(|&close| self.check(close))
824 || closes_not_expected.iter().any(|k| self.check_noexpect(k))
825 }
826827/// Parses a sequence until the specified delimiters. The function
828 /// `f` must consume tokens until reaching the next separator or
829 /// closing bracket.
830fn parse_seq_to_before_tokens<T>(
831&mut self,
832 closes_expected: &[ExpTokenPair],
833 closes_not_expected: &[&TokenKind],
834 sep: SeqSep,
835mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
836 ) -> PResult<'a, (ThinVec<T>, Trailing, Recovered)> {
837let mut first = true;
838let mut recovered = Recovered::No;
839let mut trailing = Trailing::No;
840let mut v = ThinVec::new();
841842while !self.expect_any_with_type(closes_expected, closes_not_expected) {
843if self.token.kind.is_close_delim_or_eof() {
844break;
845 }
846if let Some(exp) = sep.sep {
847if first {
848// no separator for the first element
849first = false;
850 } else {
851// check for separator
852match self.expect(exp) {
853Ok(Recovered::No) => {
854self.current_closure.take();
855 }
856Ok(Recovered::Yes(guar)) => {
857self.current_closure.take();
858 recovered = Recovered::Yes(guar);
859break;
860 }
861Err(mut expect_err) => {
862let sp = self.prev_token.span.shrink_to_hi();
863let token_str = pprust::token_kind_to_string(&exp.tok);
864865match self.current_closure.take() {
866Some(closure_spans) if self.token == TokenKind::Semi => {
867// Finding a semicolon instead of a comma
868 // after a closure body indicates that the
869 // closure body may be a block but the user
870 // forgot to put braces around its
871 // statements.
872873self.recover_missing_braces_around_closure_body(
874 closure_spans,
875 expect_err,
876 )?;
877878continue;
879 }
880881_ => {
882// Attempt to keep parsing if it was a similar separator.
883if exp.tok.similar_tokens().contains(&self.token.kind) {
884self.bump();
885 }
886 }
887 }
888889// If this was a missing `@` in a binding pattern
890 // bail with a suggestion
891 // https://github.com/rust-lang/rust/issues/72373
892if self.prev_token.is_ident() && self.token == token::DotDot {
893let 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!(
894"if you meant to bind the contents of the rest of the array \
895 pattern into `{}`, use `@`",
896 pprust::token_to_string(&self.prev_token)
897 );
898 expect_err
899 .with_span_suggestion_verbose(
900self.prev_token.span.shrink_to_hi().until(self.token.span),
901 msg,
902" @ ",
903 Applicability::MaybeIncorrect,
904 )
905 .emit();
906break;
907 }
908909// Attempt to keep parsing if it was an omitted separator.
910self.last_unexpected_token_span = None;
911match f(self) {
912Ok(t) => {
913// Parsed successfully, therefore most probably the code only
914 // misses a separator.
915expect_err
916 .with_span_suggestion_short(
917 sp,
918::alloc::__export::must_use({
::alloc::fmt::format(format_args!("missing `{0}`", token_str))
})format!("missing `{token_str}`"),
919 token_str,
920 Applicability::MaybeIncorrect,
921 )
922 .emit();
923924 v.push(t);
925continue;
926 }
927Err(e) => {
928// Parsing failed, therefore it must be something more serious
929 // than just a missing separator.
930for xx in &e.children {
931// Propagate the help message from sub error `e` to main
932 // error `expect_err`.
933expect_err.children.push(xx.clone());
934 }
935 e.cancel();
936if self.token == token::Colon {
937// We will try to recover in
938 // `maybe_recover_struct_lit_bad_delims`.
939return Err(expect_err);
940 } else if let [exp] = closes_expected
941 && exp.token_type == TokenType::CloseParen
942 {
943return Err(expect_err);
944 } else {
945 expect_err.emit();
946break;
947 }
948 }
949 }
950 }
951 }
952 }
953 }
954if sep.trailing_sep_allowed
955 && self.expect_any_with_type(closes_expected, closes_not_expected)
956 {
957 trailing = Trailing::Yes;
958break;
959 }
960961let t = f(self)?;
962 v.push(t);
963 }
964965Ok((v, trailing, recovered))
966 }
967968fn recover_missing_braces_around_closure_body(
969&mut self,
970 closure_spans: ClosureSpans,
971mut expect_err: Diag<'_>,
972 ) -> PResult<'a, ()> {
973let initial_semicolon = self.token.span;
974975while self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Semi,
token_type: crate::parser::token_type::TokenType::Semi,
}exp!(Semi)) {
976let _ = self
977.parse_stmt_without_recovery(false, ForceCollect::No, false)
978 .unwrap_or_else(|e| {
979 e.cancel();
980None
981});
982 }
983984expect_err985 .primary_message("closure bodies that contain statements must be surrounded by braces");
986987let preceding_pipe_span = closure_spans.closing_pipe;
988let following_token_span = self.token.span;
989990let 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]);
991first_note.push_span_label(
992initial_semicolon,
993"this `;` turns the preceding closure into a statement",
994 );
995first_note.push_span_label(
996closure_spans.body,
997"this expression is a statement because of the trailing semicolon",
998 );
999expect_err.span_note(first_note, "statement found outside of a block");
10001001let 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]);
1002second_note.push_span_label(closure_spans.whole_closure, "this is the parsed closure...");
1003second_note.push_span_label(
1004following_token_span,
1005"...but likely you meant the closure to end here",
1006 );
1007expect_err.span_note(second_note, "the closure body may be incorrectly delimited");
10081009expect_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]);
10101011let opening_suggestion_str = " {".to_string();
1012let closing_suggestion_str = "}".to_string();
10131014expect_err.multipart_suggestion(
1015"try adding braces",
1016::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![
1017 (preceding_pipe_span.shrink_to_hi(), opening_suggestion_str),
1018 (following_token_span.shrink_to_lo(), closing_suggestion_str),
1019 ],
1020 Applicability::MaybeIncorrect,
1021 );
10221023expect_err.emit();
10241025Ok(())
1026 }
10271028/// Parses a sequence, not including the delimiters. The function
1029 /// `f` must consume tokens until reaching the next separator or
1030 /// closing bracket.
1031fn parse_seq_to_before_end<T>(
1032&mut self,
1033 close: ExpTokenPair,
1034 sep: SeqSep,
1035 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1036 ) -> PResult<'a, (ThinVec<T>, Trailing, Recovered)> {
1037self.parse_seq_to_before_tokens(&[close], &[], sep, f)
1038 }
10391040/// Parses a sequence, including only the closing delimiter. The function
1041 /// `f` must consume tokens until reaching the next separator or
1042 /// closing bracket.
1043fn parse_seq_to_end<T>(
1044&mut self,
1045 close: ExpTokenPair,
1046 sep: SeqSep,
1047 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1048 ) -> PResult<'a, (ThinVec<T>, Trailing)> {
1049let (val, trailing, recovered) = self.parse_seq_to_before_end(close, sep, f)?;
1050if #[allow(non_exhaustive_omitted_patterns)] match recovered {
Recovered::No => true,
_ => false,
}matches!(recovered, Recovered::No) && !self.eat(close) {
1051self.dcx().span_delayed_bug(
1052self.token.span,
1053"recovered but `parse_seq_to_before_end` did not give us the close token",
1054 );
1055 }
1056Ok((val, trailing))
1057 }
10581059/// Parses a sequence, including both delimiters. The function
1060 /// `f` must consume tokens until reaching the next separator or
1061 /// closing bracket.
1062fn parse_unspanned_seq<T>(
1063&mut self,
1064 open: ExpTokenPair,
1065 close: ExpTokenPair,
1066 sep: SeqSep,
1067 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1068 ) -> PResult<'a, (ThinVec<T>, Trailing)> {
1069self.expect(open)?;
1070self.parse_seq_to_end(close, sep, f)
1071 }
10721073/// Parses a comma-separated sequence, including both delimiters.
1074 /// The function `f` must consume tokens until reaching the next separator or
1075 /// closing bracket.
1076fn parse_delim_comma_seq<T>(
1077&mut self,
1078 open: ExpTokenPair,
1079 close: ExpTokenPair,
1080 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1081 ) -> PResult<'a, (ThinVec<T>, Trailing)> {
1082self.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)
1083 }
10841085/// Parses a comma-separated sequence delimited by parentheses (e.g. `(x, y)`).
1086 /// The function `f` must consume tokens until reaching the next separator or
1087 /// closing bracket.
1088pub fn parse_paren_comma_seq<T>(
1089&mut self,
1090 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1091 ) -> PResult<'a, (ThinVec<T>, Trailing)> {
1092self.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)
1093 }
10941095/// Advance the parser by one token using provided token as the next one.
1096fn bump_with(&mut self, next: (Token, Spacing)) {
1097self.inlined_bump_with(next)
1098 }
10991100/// This always-inlined version should only be used on hot code paths.
1101#[inline(always)]
1102fn inlined_bump_with(&mut self, (next_token, next_spacing): (Token, Spacing)) {
1103// Update the current and previous tokens.
1104self.prev_token = mem::replace(&mut self.token, next_token);
1105self.token_spacing = next_spacing;
11061107// Diagnostics.
1108self.expected_token_types.clear();
1109 }
11101111/// Advance the parser by one token.
1112pub fn bump(&mut self) {
1113// Note: destructuring here would give nicer code, but it was found in #96210 to be slower
1114 // than `.0`/`.1` access.
1115let mut next = self.token_cursor.inlined_next();
1116self.num_bump_calls += 1;
1117// We got a token from the underlying cursor and no longer need to
1118 // worry about an unglued token. See `break_and_eat` for more details.
1119self.break_last_token = 0;
1120if next.0.span.is_dummy() {
1121// Tweak the location for better diagnostics, but keep syntactic context intact.
1122let fallback_span = self.token.span;
1123next.0.span = fallback_span.with_ctxt(next.0.span.ctxt());
1124 }
1125if 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!(
1126 next.0.kind,
1127 token::OpenInvisible(origin) | token::CloseInvisible(origin) if origin.skip()
1128 ));
1129self.inlined_bump_with(next)
1130 }
11311132/// Look-ahead `dist` tokens of `self.token` and get access to that token there.
1133 /// When `dist == 0` then the current token is looked at. `Eof` will be
1134 /// returned if the look-ahead is any distance past the end of the tokens.
1135pub fn look_ahead<R>(&self, dist: usize, looker: impl FnOnce(&Token) -> R) -> R {
1136if dist == 0 {
1137return looker(&self.token);
1138 }
11391140// Typically around 98% of the `dist > 0` cases have `dist == 1`, so we
1141 // have a fast special case for that.
1142if dist == 1 {
1143// The index is zero because the tree cursor's index always points
1144 // to the next token to be gotten.
1145match self.token_cursor.curr.curr() {
1146Some(tree) => {
1147// Indexing stayed within the current token tree.
1148match tree {
1149 TokenTree::Token(token, _) => return looker(token),
1150&TokenTree::Delimited(dspan, _, delim, _) => {
1151if !delim.skip() {
1152return looker(&Token::new(delim.as_open_token_kind(), dspan.open));
1153 }
1154 }
1155 }
1156 }
1157None => {
1158// The tree cursor lookahead went (one) past the end of the
1159 // current token tree. Try to return a close delimiter.
1160if let Some(last) = self.token_cursor.stack.last()
1161 && let Some(&TokenTree::Delimited(span, _, delim, _)) = last.curr()
1162 && !delim.skip()
1163 {
1164// We are not in the outermost token stream, so we have
1165 // delimiters. Also, those delimiters are not skipped.
1166return looker(&Token::new(delim.as_close_token_kind(), span.close));
1167 }
1168 }
1169 }
1170 }
11711172// Just clone the token cursor and use `next`, skipping delimiters as
1173 // necessary. Slow but simple.
1174let mut cursor = self.token_cursor.clone();
1175let mut i = 0;
1176let mut token = Token::dummy();
1177while i < dist {
1178 token = cursor.next().0;
1179if let token::OpenInvisible(origin) | token::CloseInvisible(origin) = token.kind
1180 && origin.skip()
1181 {
1182continue;
1183 }
1184 i += 1;
1185 }
1186looker(&token)
1187 }
11881189/// Like `lookahead`, but skips over token trees rather than tokens. Useful
1190 /// when looking past possible metavariable pasting sites.
1191pub fn tree_look_ahead<R>(
1192&self,
1193 dist: usize,
1194 looker: impl FnOnce(&TokenTree) -> R,
1195 ) -> Option<R> {
1196match (&dist, &0) {
(left_val, right_val) => {
if *left_val == *right_val {
let kind = ::core::panicking::AssertKind::Ne;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_ne!(dist, 0);
1197self.token_cursor.curr.look_ahead(dist - 1).map(looker)
1198 }
11991200/// Returns whether any of the given keywords are `dist` tokens ahead of the current one.
1201pub(crate) fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool {
1202self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw)))
1203 }
12041205/// Parses asyncness: `async` or nothing.
1206fn parse_coroutine_kind(&mut self, case: Case) -> Option<CoroutineKind> {
1207let span = self.token_uninterpolated_span();
1208if 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) {
1209// FIXME(gen_blocks): Do we want to unconditionally parse `gen` and then
1210 // error if edition <= 2024, like we do with async and edition <= 2018?
1211if self.token_uninterpolated_span().at_least_rust_2024()
1212 && 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)
1213 {
1214let gen_span = self.prev_token_uninterpolated_span();
1215Some(CoroutineKind::AsyncGen {
1216 span: span.to(gen_span),
1217 closure_id: DUMMY_NODE_ID,
1218 return_impl_trait_id: DUMMY_NODE_ID,
1219 })
1220 } else {
1221Some(CoroutineKind::Async {
1222span,
1223 closure_id: DUMMY_NODE_ID,
1224 return_impl_trait_id: DUMMY_NODE_ID,
1225 })
1226 }
1227 } else if self.token_uninterpolated_span().at_least_rust_2024()
1228 && 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)
1229 {
1230Some(CoroutineKind::Gen {
1231span,
1232 closure_id: DUMMY_NODE_ID,
1233 return_impl_trait_id: DUMMY_NODE_ID,
1234 })
1235 } else {
1236None1237 }
1238 }
12391240/// Parses fn unsafety: `unsafe`, `safe` or nothing.
1241fn parse_safety(&mut self, case: Case) -> Safety {
1242if 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) {
1243 Safety::Unsafe(self.prev_token_uninterpolated_span())
1244 } 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) {
1245 Safety::Safe(self.prev_token_uninterpolated_span())
1246 } else {
1247 Safety::Default1248 }
1249 }
12501251/// Parses constness: `const` or nothing.
1252fn parse_constness(&mut self, case: Case) -> Const {
1253self.parse_constness_(case, false)
1254 }
12551256/// Parses constness for closures (case sensitive, feature-gated)
1257fn parse_closure_constness(&mut self) -> Const {
1258let constness = self.parse_constness_(Case::Sensitive, true);
1259if let Const::Yes(span) = constness {
1260self.psess.gated_spans.gate(sym::const_closures, span);
1261 }
1262constness1263 }
12641265fn parse_constness_(&mut self, case: Case, is_closure: bool) -> Const {
1266// Avoid const blocks and const closures to be parsed as const items
1267if (self.check_const_closure() == is_closure)
1268 && !self.look_ahead(1, |t| *t == token::OpenBrace || t.is_metavar_block())
1269 && 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)
1270 {
1271 Const::Yes(self.prev_token_uninterpolated_span())
1272 } else {
1273 Const::No1274 }
1275 }
12761277/// Parses inline const expressions.
1278fn parse_const_block(&mut self, span: Span, pat: bool) -> PResult<'a, Box<Expr>> {
1279self.expect_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Const,
token_type: crate::parser::token_type::TokenType::KwConst,
}exp!(Const))?;
1280let (attrs, blk) = self.parse_inner_attrs_and_block(None)?;
1281let anon_const = AnonConst {
1282 id: DUMMY_NODE_ID,
1283 value: self.mk_expr(blk.span, ExprKind::Block(blk, None)),
1284 mgca_disambiguation: MgcaDisambiguation::AnonConst,
1285 };
1286let blk_span = anon_const.value.span;
1287let kind = if pat {
1288let guar = self1289 .dcx()
1290 .struct_span_err(blk_span, "const blocks cannot be used as patterns")
1291 .with_help(
1292"use a named `const`-item or an `if`-guard (`x if x == const { ... }`) instead",
1293 )
1294 .emit();
1295 ExprKind::Err(guar)
1296 } else {
1297 ExprKind::ConstBlock(anon_const)
1298 };
1299Ok(self.mk_expr_with_attrs(span.to(blk_span), kind, attrs))
1300 }
13011302/// Parses mutability (`mut` or nothing).
1303fn parse_mutability(&mut self) -> Mutability {
1304if 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 }
1305 }
13061307/// Parses reference binding mode (`ref`, `ref mut`, `ref pin const`, `ref pin mut`, or nothing).
1308fn parse_byref(&mut self) -> ByRef {
1309if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Ref,
token_type: crate::parser::token_type::TokenType::KwRef,
}exp!(Ref)) {
1310let (pinnedness, mutability) = self.parse_pin_and_mut();
1311 ByRef::Yes(pinnedness, mutability)
1312 } else {
1313 ByRef::No1314 }
1315 }
13161317/// Possibly parses mutability (`const` or `mut`).
1318fn parse_const_or_mut(&mut self) -> Option<Mutability> {
1319if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Mut,
token_type: crate::parser::token_type::TokenType::KwMut,
}exp!(Mut)) {
1320Some(Mutability::Mut)
1321 } 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)) {
1322Some(Mutability::Not)
1323 } else {
1324None1325 }
1326 }
13271328fn parse_field_name(&mut self) -> PResult<'a, Ident> {
1329if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = self.token.kind
1330 {
1331if let Some(suffix) = suffix {
1332self.dcx().emit_err(errors::InvalidLiteralSuffixOnTupleIndex {
1333 span: self.token.span,
1334suffix,
1335 });
1336 }
1337self.bump();
1338Ok(Ident::new(symbol, self.prev_token.span))
1339 } else {
1340self.parse_ident_common(true)
1341 }
1342 }
13431344fn parse_delim_args(&mut self) -> PResult<'a, Box<DelimArgs>> {
1345if let Some(args) = self.parse_delim_args_inner() {
1346Ok(Box::new(args))
1347 } else {
1348self.unexpected_any()
1349 }
1350 }
13511352fn parse_attr_args(&mut self) -> PResult<'a, AttrArgs> {
1353Ok(if let Some(args) = self.parse_delim_args_inner() {
1354 AttrArgs::Delimited(args)
1355 } else if self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Eq,
token_type: crate::parser::token_type::TokenType::Eq,
}exp!(Eq)) {
1356let eq_span = self.prev_token.span;
1357let expr = self.parse_expr_force_collect()?;
1358 AttrArgs::Eq { eq_span, expr }
1359 } else {
1360 AttrArgs::Empty1361 })
1362 }
13631364fn parse_delim_args_inner(&mut self) -> Option<DelimArgs> {
1365let delimited = self.check(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::OpenParen,
token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen))
1366 || self.check(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::OpenBracket,
token_type: crate::parser::token_type::TokenType::OpenBracket,
}exp!(OpenBracket))
1367 || self.check(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::OpenBrace,
token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace));
13681369delimited.then(|| {
1370let TokenTree::Delimited(dspan, _, delim, tokens) = self.parse_token_tree() else {
1371::core::panicking::panic("internal error: entered unreachable code")unreachable!()1372 };
1373DelimArgs { dspan, delim, tokens }
1374 })
1375 }
13761377/// Parses a single token tree from the input.
1378pub fn parse_token_tree(&mut self) -> TokenTree {
1379if self.token.kind.open_delim().is_some() {
1380// Clone the `TokenTree::Delimited` that we are currently
1381 // within. That's what we are going to return.
1382let tree = self.token_cursor.stack.last().unwrap().curr().unwrap().clone();
1383if 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(..));
13841385// Advance the token cursor through the entire delimited
1386 // sequence. After getting the `OpenDelim` we are *within* the
1387 // delimited sequence, i.e. at depth `d`. After getting the
1388 // matching `CloseDelim` we are *after* the delimited sequence,
1389 // i.e. at depth `d - 1`.
1390let target_depth = self.token_cursor.stack.len() - 1;
13911392if let Capturing::No = self.capture_state.capturing {
1393// We are not capturing tokens, so skip to the end of the
1394 // delimited sequence. This is a perf win when dealing with
1395 // declarative macros that pass large `tt` fragments through
1396 // multiple rules, as seen in the uom-0.37.0 crate.
1397self.token_cursor.curr.bump_to_end();
1398self.bump();
1399if true {
match (&self.token_cursor.stack.len(), &target_depth) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
};debug_assert_eq!(self.token_cursor.stack.len(), target_depth);
1400 } else {
1401loop {
1402// Advance one token at a time, so `TokenCursor::next()`
1403 // can capture these tokens if necessary.
1404self.bump();
1405if self.token_cursor.stack.len() == target_depth {
1406break;
1407 }
1408 }
1409 }
1410if 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());
14111412// Consume close delimiter
1413self.bump();
1414tree1415 } else {
1416if !!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());
1417let prev_spacing = self.token_spacing;
1418self.bump();
1419 TokenTree::Token(self.prev_token, prev_spacing)
1420 }
1421 }
14221423pub fn parse_tokens(&mut self) -> TokenStream {
1424let mut result = Vec::new();
1425loop {
1426if self.token.kind.is_close_delim_or_eof() {
1427break;
1428 } else {
1429result.push(self.parse_token_tree());
1430 }
1431 }
1432TokenStream::new(result)
1433 }
14341435/// Evaluates the closure with restrictions in place.
1436 ///
1437 /// Afters the closure is evaluated, restrictions are reset.
1438fn with_res<T>(&mut self, res: Restrictions, f: impl FnOnce(&mut Self) -> T) -> T {
1439let old = self.restrictions;
1440self.restrictions = res;
1441let res = f(self);
1442self.restrictions = old;
1443res1444 }
14451446/// Parses `pub` and `pub(in path)` plus shortcuts `pub(crate)` for `pub(in crate)`, `pub(self)`
1447 /// for `pub(in self)` and `pub(super)` for `pub(in super)`.
1448 /// If the following element can't be a tuple (i.e., it's a function definition), then
1449 /// it's not a tuple struct field), and the contents within the parentheses aren't valid,
1450 /// so emit a proper diagnostic.
1451// Public for rustfmt usage.
1452pub fn parse_visibility(&mut self, fbt: FollowedByType) -> PResult<'a, Visibility> {
1453if let Some(vis) = self1454 .eat_metavar_seq(MetaVarKind::Vis, |this| this.parse_visibility(FollowedByType::Yes))
1455 {
1456return Ok(vis);
1457 }
14581459if !self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Pub,
token_type: crate::parser::token_type::TokenType::KwPub,
}exp!(Pub)) {
1460// We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
1461 // keyword to grab a span from for inherited visibility; an empty span at the
1462 // beginning of the current token would seem to be the "Schelling span".
1463return Ok(Visibility {
1464 span: self.token.span.shrink_to_lo(),
1465 kind: VisibilityKind::Inherited,
1466 tokens: None,
1467 });
1468 }
1469let lo = self.prev_token.span;
14701471if self.check(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::OpenParen,
token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen)) {
1472// We don't `self.bump()` the `(` yet because this might be a struct definition where
1473 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
1474 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
1475 // by the following tokens.
1476if self.is_keyword_ahead(1, &[kw::In]) {
1477// Parse `pub(in path)`.
1478self.bump(); // `(`
1479self.bump(); // `in`
1480let path = self.parse_path(PathStyle::Mod)?; // `path`
1481self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::CloseParen,
token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen))?; // `)`
1482let vis = VisibilityKind::Restricted {
1483 path: Box::new(path),
1484 id: ast::DUMMY_NODE_ID,
1485 shorthand: false,
1486 };
1487return Ok(Visibility {
1488 span: lo.to(self.prev_token.span),
1489 kind: vis,
1490 tokens: None,
1491 });
1492 } else if self.look_ahead(2, |t| t == &token::CloseParen)
1493 && self.is_keyword_ahead(1, &[kw::Crate, kw::Super, kw::SelfLower])
1494 {
1495// Parse `pub(crate)`, `pub(self)`, or `pub(super)`.
1496self.bump(); // `(`
1497let path = self.parse_path(PathStyle::Mod)?; // `crate`/`super`/`self`
1498self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::CloseParen,
token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen))?; // `)`
1499let vis = VisibilityKind::Restricted {
1500 path: Box::new(path),
1501 id: ast::DUMMY_NODE_ID,
1502 shorthand: true,
1503 };
1504return Ok(Visibility {
1505 span: lo.to(self.prev_token.span),
1506 kind: vis,
1507 tokens: None,
1508 });
1509 } else if let FollowedByType::No = fbt {
1510// Provide this diagnostic if a type cannot follow;
1511 // in particular, if this is not a tuple struct.
1512self.recover_incorrect_vis_restriction()?;
1513// Emit diagnostic, but continue with public visibility.
1514}
1515 }
15161517Ok(Visibility { span: lo, kind: VisibilityKind::Public, tokens: None })
1518 }
15191520/// Recovery for e.g. `pub(something) fn ...` or `struct X { pub(something) y: Z }`
1521fn recover_incorrect_vis_restriction(&mut self) -> PResult<'a, ()> {
1522self.bump(); // `(`
1523let path = self.parse_path(PathStyle::Mod)?;
1524self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::CloseParen,
token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen))?; // `)`
15251526let path_str = pprust::path_to_string(&path);
1527self.dcx()
1528 .emit_err(IncorrectVisibilityRestriction { span: path.span, inner_str: path_str });
15291530Ok(())
1531 }
15321533/// Parses `extern string_literal?`.
1534fn parse_extern(&mut self, case: Case) -> Extern {
1535if 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) {
1536let mut extern_span = self.prev_token.span;
1537let abi = self.parse_abi();
1538if let Some(abi) = abi {
1539extern_span = extern_span.to(abi.span);
1540 }
1541Extern::from_abi(abi, extern_span)
1542 } else {
1543 Extern::None1544 }
1545 }
15461547/// Parses a string literal as an ABI spec.
1548fn parse_abi(&mut self) -> Option<StrLit> {
1549match self.parse_str_lit() {
1550Ok(str_lit) => Some(str_lit),
1551Err(Some(lit)) => match lit.kind {
1552 ast::LitKind::Err(_) => None,
1553_ => {
1554self.dcx().emit_err(NonStringAbiLiteral { span: lit.span });
1555None1556 }
1557 },
1558Err(None) => None,
1559 }
1560 }
15611562fn collect_tokens_no_attrs<R: HasAttrs + HasTokens>(
1563&mut self,
1564 f: impl FnOnce(&mut Self) -> PResult<'a, R>,
1565 ) -> PResult<'a, R> {
1566// The only reason to call `collect_tokens_no_attrs` is if you want tokens, so use
1567 // `ForceCollect::Yes`
1568self.collect_tokens(None, AttrWrapper::empty(), ForceCollect::Yes, |this, _attrs| {
1569Ok((f(this)?, Trailing::No, UsePreAttrPos::No))
1570 })
1571 }
15721573/// Checks for `::` or, potentially, `:::` and then look ahead after it.
1574fn check_path_sep_and_look_ahead(&mut self, looker: impl Fn(&Token) -> bool) -> bool {
1575if self.check(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::PathSep,
token_type: crate::parser::token_type::TokenType::PathSep,
}exp!(PathSep)) {
1576if self.may_recover() && self.look_ahead(1, |t| t.kind == token::Colon) {
1577if 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");
1578self.look_ahead(2, looker)
1579 } else {
1580self.look_ahead(1, looker)
1581 }
1582 } else {
1583false
1584}
1585 }
15861587/// `::{` or `::*`
1588fn is_import_coupler(&mut self) -> bool {
1589self.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))
1590 }
15911592// Debug view of the parser's token stream, up to `{lookahead}` tokens.
1593 // Only used when debugging.
1594#[allow(unused)]
1595pub(crate) fn debug_lookahead(&self, lookahead: usize) -> impl fmt::Debug {
1596 fmt::from_fn(move |f| {
1597let mut dbg_fmt = f.debug_struct("Parser"); // or at least, one view of
15981599 // we don't need N spans, but we want at least one, so print all of prev_token
1600dbg_fmt.field("prev_token", &self.prev_token);
1601let mut tokens = ::alloc::vec::Vec::new()vec![];
1602for i in 0..lookahead {
1603let tok = self.look_ahead(i, |tok| tok.kind);
1604let is_eof = tok == TokenKind::Eof;
1605 tokens.push(tok);
1606if is_eof {
1607// Don't look ahead past EOF.
1608break;
1609 }
1610 }
1611dbg_fmt.field_with("tokens", |field| field.debug_list().entries(tokens).finish());
1612dbg_fmt.field("approx_token_stream_pos", &self.num_bump_calls);
16131614// some fields are interesting for certain values, as they relate to macro parsing
1615if let Some(subparser) = self.subparser_name {
1616dbg_fmt.field("subparser_name", &subparser);
1617 }
1618if let Recovery::Forbidden = self.recovery {
1619dbg_fmt.field("recovery", &self.recovery);
1620 }
16211622// imply there's "more to know" than this view
1623dbg_fmt.finish_non_exhaustive()
1624 })
1625 }
16261627pub fn clear_expected_token_types(&mut self) {
1628self.expected_token_types.clear();
1629 }
16301631pub fn approx_token_stream_pos(&self) -> u32 {
1632self.num_bump_calls
1633 }
16341635/// For interpolated `self.token`, returns a span of the fragment to which
1636 /// the interpolated token refers. For all other tokens this is just a
1637 /// regular span. It is particularly important to use this for identifiers
1638 /// and lifetimes for which spans affect name resolution and edition
1639 /// checks. Note that keywords are also identifiers, so they should use
1640 /// this if they keep spans or perform edition checks.
1641pub fn token_uninterpolated_span(&self) -> Span {
1642match &self.token.kind {
1643 token::NtIdent(ident, _) | token::NtLifetime(ident, _) => ident.span,
1644 token::OpenInvisible(InvisibleOrigin::MetaVar(_)) => self.look_ahead(1, |t| t.span),
1645_ => self.token.span,
1646 }
1647 }
16481649/// Like `token_uninterpolated_span`, but works on `self.prev_token`.
1650pub fn prev_token_uninterpolated_span(&self) -> Span {
1651match &self.prev_token.kind {
1652 token::NtIdent(ident, _) | token::NtLifetime(ident, _) => ident.span,
1653 token::OpenInvisible(InvisibleOrigin::MetaVar(_)) => self.look_ahead(0, |t| t.span),
1654_ => self.prev_token.span,
1655 }
1656 }
16571658fn missing_semi_from_binop(
1659&self,
1660 kind_desc: &str,
1661 expr: &Expr,
1662 decl_lo: Option<Span>,
1663 ) -> Option<(Span, ErrorGuaranteed)> {
1664if self.token == TokenKind::Semi {
1665return None;
1666 }
1667if !self.may_recover() || expr.span.from_expansion() {
1668return None;
1669 }
1670let sm = self.psess.source_map();
1671if let ExprKind::Binary(op, lhs, rhs) = &expr.kind
1672 && sm.is_multiline(lhs.span.shrink_to_hi().until(rhs.span.shrink_to_lo()))
1673 && #[allow(non_exhaustive_omitted_patterns)] match op.node {
BinOpKind::Mul | BinOpKind::BitAnd => true,
_ => false,
}matches!(op.node, BinOpKind::Mul | BinOpKind::BitAnd)1674 && classify::expr_requires_semi_to_be_stmt(rhs)
1675 {
1676let lhs_end_span = lhs.span.shrink_to_hi();
1677let token_str = token_descr(&self.token);
1678let mut err = self1679 .dcx()
1680 .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}"));
1681err.span_label(self.token.span, "unexpected token");
16821683// Use the declaration start if provided, otherwise fall back to lhs_end_span.
1684let continuation_start = decl_lo.unwrap_or(lhs_end_span);
1685let continuation_span = continuation_start.until(rhs.span.shrink_to_hi());
1686err.span_label(
1687continuation_span,
1688::alloc::__export::must_use({
::alloc::fmt::format(format_args!("to finish parsing this {0}, expected this to be followed by a `;`",
kind_desc))
})format!(
1689"to finish parsing this {kind_desc}, expected this to be followed by a `;`",
1690 ),
1691 );
1692let op_desc = match op.node {
1693 BinOpKind::BitAnd => "a bit-and",
1694 BinOpKind::Mul => "a multiplication",
1695_ => "a binary",
1696 };
1697let mut note_spans = MultiSpan::new();
1698note_spans.push_span_label(lhs.span, "parsed as the left-hand expression");
1699note_spans.push_span_label(rhs.span, "parsed as the right-hand expression");
1700note_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}"));
1701err.span_note(
1702note_spans,
1703::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"),
1704 );
17051706err.span_suggestion(
1707lhs_end_span,
1708::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"),
1709";",
1710 Applicability::MaybeIncorrect,
1711 );
1712return Some((lhs.span, err.emit()));
1713 }
1714None1715 }
1716}
17171718// Metavar captures of various kinds.
1719#[derive(#[automatically_derived]
impl ::core::clone::Clone for ParseNtResult {
#[inline]
fn clone(&self) -> ParseNtResult {
match self {
ParseNtResult::Tt(__self_0) =>
ParseNtResult::Tt(::core::clone::Clone::clone(__self_0)),
ParseNtResult::Ident(__self_0, __self_1) =>
ParseNtResult::Ident(::core::clone::Clone::clone(__self_0),
::core::clone::Clone::clone(__self_1)),
ParseNtResult::Lifetime(__self_0, __self_1) =>
ParseNtResult::Lifetime(::core::clone::Clone::clone(__self_0),
::core::clone::Clone::clone(__self_1)),
ParseNtResult::Item(__self_0) =>
ParseNtResult::Item(::core::clone::Clone::clone(__self_0)),
ParseNtResult::Block(__self_0) =>
ParseNtResult::Block(::core::clone::Clone::clone(__self_0)),
ParseNtResult::Stmt(__self_0) =>
ParseNtResult::Stmt(::core::clone::Clone::clone(__self_0)),
ParseNtResult::Pat(__self_0, __self_1) =>
ParseNtResult::Pat(::core::clone::Clone::clone(__self_0),
::core::clone::Clone::clone(__self_1)),
ParseNtResult::Expr(__self_0, __self_1) =>
ParseNtResult::Expr(::core::clone::Clone::clone(__self_0),
::core::clone::Clone::clone(__self_1)),
ParseNtResult::Literal(__self_0) =>
ParseNtResult::Literal(::core::clone::Clone::clone(__self_0)),
ParseNtResult::Ty(__self_0) =>
ParseNtResult::Ty(::core::clone::Clone::clone(__self_0)),
ParseNtResult::Meta(__self_0) =>
ParseNtResult::Meta(::core::clone::Clone::clone(__self_0)),
ParseNtResult::Path(__self_0) =>
ParseNtResult::Path(::core::clone::Clone::clone(__self_0)),
ParseNtResult::Vis(__self_0) =>
ParseNtResult::Vis(::core::clone::Clone::clone(__self_0)),
}
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for ParseNtResult {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
ParseNtResult::Tt(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Tt",
&__self_0),
ParseNtResult::Ident(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f, "Ident",
__self_0, &__self_1),
ParseNtResult::Lifetime(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"Lifetime", __self_0, &__self_1),
ParseNtResult::Item(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Item",
&__self_0),
ParseNtResult::Block(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Block",
&__self_0),
ParseNtResult::Stmt(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Stmt",
&__self_0),
ParseNtResult::Pat(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f, "Pat",
__self_0, &__self_1),
ParseNtResult::Expr(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f, "Expr",
__self_0, &__self_1),
ParseNtResult::Literal(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Literal", &__self_0),
ParseNtResult::Ty(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Ty",
&__self_0),
ParseNtResult::Meta(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Meta",
&__self_0),
ParseNtResult::Path(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Path",
&__self_0),
ParseNtResult::Vis(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Vis",
&__self_0),
}
}
}Debug)]
1720pub enum ParseNtResult {
1721 Tt(TokenTree),
1722 Ident(Ident, IdentIsRaw),
1723 Lifetime(Ident, IdentIsRaw),
1724 Item(Box<ast::Item>),
1725 Block(Box<ast::Block>),
1726 Stmt(Box<ast::Stmt>),
1727 Pat(Box<ast::Pat>, NtPatKind),
1728 Expr(Box<ast::Expr>, NtExprKind),
1729 Literal(Box<ast::Expr>),
1730 Ty(Box<ast::Ty>),
1731 Meta(Box<ast::AttrItem>),
1732 Path(Box<ast::Path>),
1733 Vis(Box<ast::Visibility>),
1734}