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;
23pub(crate) use expr::ForbiddenLetReason;
24// Public to use it for custom `if` expressions in rustfmt forks like https://github.com/tucant/rustfmt
25pub use expr::LetChainsPolicy;
26pub(crate) use item::{FnContext, FnParseMode};
27pub use pat::{CommaRecoveryMode, RecoverColon, RecoverComma};
28pub use path::PathStyle;
29use rustc_ast::token::{
30self, IdentIsRaw, InvisibleOrigin, MetaVarKind, NtExprKind, NtPatKind, Token, TokenKind,
31};
32use rustc_ast::tokenstream::{
33ParserRange, ParserReplacement, Spacing, TokenCursor, TokenStream, TokenTree, TokenTreeCursor,
34};
35use rustc_ast::util::case::Case;
36use rustc_ast::{
37selfas ast, AnonConst, AttrArgs, AttrId, BlockCheckMode, 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::{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};
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 {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_eq(&self) -> () {
let _: ::core::cmp::AssertParamIsEq<u8>;
}
}
#[automatically_derived]
impl ::core::cmp::PartialOrd for InternalBitFlags {
#[inline]
fn partial_cmp(&self, other: &InternalBitFlags)
-> ::core::option::Option<::core::cmp::Ordering> {
::core::cmp::PartialOrd::partial_cmp(&self.0, &other.0)
}
}
#[automatically_derived]
impl ::core::cmp::Ord for InternalBitFlags {
#[inline]
fn cmp(&self, other: &InternalBitFlags) -> ::core::cmp::Ordering {
::core::cmp::Ord::cmp(&self.0, &other.0)
}
}
#[automatically_derived]
impl ::core::hash::Hash for InternalBitFlags {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) -> () {
::core::hash::Hash::hash(&self.0, state)
}
}
impl ::bitflags::__private::PublicFlags for Restrictions {
type Primitive = u8;
type Internal = InternalBitFlags;
}
impl ::bitflags::__private::core::default::Default for
InternalBitFlags {
#[inline]
fn default() -> Self { InternalBitFlags::empty() }
}
impl ::bitflags::__private::core::fmt::Debug for InternalBitFlags {
fn fmt(&self,
f: &mut ::bitflags::__private::core::fmt::Formatter<'_>)
-> ::bitflags::__private::core::fmt::Result {
if self.is_empty() {
f.write_fmt(format_args!("{0:#x}",
<u8 as ::bitflags::Bits>::EMPTY))
} else {
::bitflags::__private::core::fmt::Display::fmt(self, f)
}
}
}
impl ::bitflags::__private::core::fmt::Display for InternalBitFlags {
fn fmt(&self,
f: &mut ::bitflags::__private::core::fmt::Formatter<'_>)
-> ::bitflags::__private::core::fmt::Result {
::bitflags::parser::to_writer(&Restrictions(*self), f)
}
}
impl ::bitflags::__private::core::str::FromStr for InternalBitFlags {
type Err = ::bitflags::parser::ParseError;
fn from_str(s: &str)
->
::bitflags::__private::core::result::Result<Self,
Self::Err> {
::bitflags::parser::from_str::<Restrictions>(s).map(|flags|
flags.0)
}
}
impl ::bitflags::__private::core::convert::AsRef<u8> for
InternalBitFlags {
fn as_ref(&self) -> &u8 { &self.0 }
}
impl ::bitflags::__private::core::convert::From<u8> for
InternalBitFlags {
fn from(bits: u8) -> Self { Self::from_bits_retain(bits) }
}
#[allow(dead_code, deprecated, unused_attributes)]
impl InternalBitFlags {
/// Get a flags value with all bits unset.
#[inline]
pub const fn empty() -> Self {
Self(<u8 as ::bitflags::Bits>::EMPTY)
}
/// Get a flags value with all known bits set.
#[inline]
pub const fn all() -> Self {
let mut truncated = <u8 as ::bitflags::Bits>::EMPTY;
let mut i = 0;
{
{
let flag =
<Restrictions as
::bitflags::Flags>::FLAGS[i].value().bits();
truncated = truncated | flag;
i += 1;
}
};
{
{
let flag =
<Restrictions as
::bitflags::Flags>::FLAGS[i].value().bits();
truncated = truncated | flag;
i += 1;
}
};
{
{
let flag =
<Restrictions as
::bitflags::Flags>::FLAGS[i].value().bits();
truncated = truncated | flag;
i += 1;
}
};
{
{
let flag =
<Restrictions as
::bitflags::Flags>::FLAGS[i].value().bits();
truncated = truncated | flag;
i += 1;
}
};
{
{
let flag =
<Restrictions as
::bitflags::Flags>::FLAGS[i].value().bits();
truncated = truncated | flag;
i += 1;
}
};
{
{
let flag =
<Restrictions as
::bitflags::Flags>::FLAGS[i].value().bits();
truncated = truncated | flag;
i += 1;
}
};
let _ = i;
Self(truncated)
}
/// Get the underlying bits value.
///
/// The returned value is exactly the bits set in this flags value.
#[inline]
pub const fn bits(&self) -> u8 { self.0 }
/// Convert from a bits value.
///
/// This method will return `None` if any unknown bits are set.
#[inline]
pub const fn from_bits(bits: u8)
-> ::bitflags::__private::core::option::Option<Self> {
let truncated = Self::from_bits_truncate(bits).0;
if truncated == bits {
::bitflags::__private::core::option::Option::Some(Self(bits))
} else { ::bitflags::__private::core::option::Option::None }
}
/// Convert from a bits value, unsetting any unknown bits.
#[inline]
pub const fn from_bits_truncate(bits: u8) -> Self {
Self(bits & Self::all().0)
}
/// Convert from a bits value exactly.
#[inline]
pub const fn from_bits_retain(bits: u8) -> Self { Self(bits) }
/// Get a flags value with the bits of a flag with the given name set.
///
/// This method will return `None` if `name` is empty or doesn't
/// correspond to any named flag.
#[inline]
pub fn from_name(name: &str)
-> ::bitflags::__private::core::option::Option<Self> {
{
if name == "STMT_EXPR" {
return ::bitflags::__private::core::option::Option::Some(Self(Restrictions::STMT_EXPR.bits()));
}
};
;
{
if name == "NO_STRUCT_LITERAL" {
return ::bitflags::__private::core::option::Option::Some(Self(Restrictions::NO_STRUCT_LITERAL.bits()));
}
};
;
{
if name == "CONST_EXPR" {
return ::bitflags::__private::core::option::Option::Some(Self(Restrictions::CONST_EXPR.bits()));
}
};
;
{
if name == "ALLOW_LET" {
return ::bitflags::__private::core::option::Option::Some(Self(Restrictions::ALLOW_LET.bits()));
}
};
;
{
if name == "IN_IF_GUARD" {
return ::bitflags::__private::core::option::Option::Some(Self(Restrictions::IN_IF_GUARD.bits()));
}
};
;
{
if name == "IS_PAT" {
return ::bitflags::__private::core::option::Option::Some(Self(Restrictions::IS_PAT.bits()));
}
};
;
let _ = name;
::bitflags::__private::core::option::Option::None
}
/// Whether all bits in this flags value are unset.
#[inline]
pub const fn is_empty(&self) -> bool {
self.0 == <u8 as ::bitflags::Bits>::EMPTY
}
/// Whether all known bits in this flags value are set.
#[inline]
pub const fn is_all(&self) -> bool {
Self::all().0 | self.0 == self.0
}
/// Whether any set bits in a source flags value are also set in a target flags value.
#[inline]
pub const fn intersects(&self, other: Self) -> bool {
self.0 & other.0 != <u8 as ::bitflags::Bits>::EMPTY
}
/// Whether all set bits in a source flags value are also set in a target flags value.
#[inline]
pub const fn contains(&self, other: Self) -> bool {
self.0 & other.0 == other.0
}
/// The bitwise or (`|`) of the bits in two flags values.
#[inline]
pub fn insert(&mut self, other: Self) {
*self = Self(self.0).union(other);
}
/// The intersection of a source flags value with the complement of a target flags
/// value (`&!`).
///
/// This method is not equivalent to `self & !other` when `other` has unknown bits set.
/// `remove` won't truncate `other`, but the `!` operator will.
#[inline]
pub fn remove(&mut self, other: Self) {
*self = Self(self.0).difference(other);
}
/// The bitwise exclusive-or (`^`) of the bits in two flags values.
#[inline]
pub fn toggle(&mut self, other: Self) {
*self = Self(self.0).symmetric_difference(other);
}
/// Call `insert` when `value` is `true` or `remove` when `value` is `false`.
#[inline]
pub fn set(&mut self, other: Self, value: bool) {
if value { self.insert(other); } else { self.remove(other); }
}
/// The bitwise and (`&`) of the bits in two flags values.
#[inline]
#[must_use]
pub const fn intersection(self, other: Self) -> Self {
Self(self.0 & other.0)
}
/// The bitwise or (`|`) of the bits in two flags values.
#[inline]
#[must_use]
pub const fn union(self, other: Self) -> Self {
Self(self.0 | other.0)
}
/// The intersection of a source flags value with the complement of a target flags
/// value (`&!`).
///
/// This method is not equivalent to `self & !other` when `other` has unknown bits set.
/// `difference` won't truncate `other`, but the `!` operator will.
#[inline]
#[must_use]
pub const fn difference(self, other: Self) -> Self {
Self(self.0 & !other.0)
}
/// The bitwise exclusive-or (`^`) of the bits in two flags values.
#[inline]
#[must_use]
pub const fn symmetric_difference(self, other: Self) -> Self {
Self(self.0 ^ other.0)
}
/// The bitwise negation (`!`) of the bits in a flags value, truncating the result.
#[inline]
#[must_use]
pub const fn complement(self) -> Self {
Self::from_bits_truncate(!self.0)
}
}
impl ::bitflags::__private::core::fmt::Binary for InternalBitFlags {
fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
-> ::bitflags::__private::core::fmt::Result {
let inner = self.0;
::bitflags::__private::core::fmt::Binary::fmt(&inner, f)
}
}
impl ::bitflags::__private::core::fmt::Octal for InternalBitFlags {
fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
-> ::bitflags::__private::core::fmt::Result {
let inner = self.0;
::bitflags::__private::core::fmt::Octal::fmt(&inner, f)
}
}
impl ::bitflags::__private::core::fmt::LowerHex for InternalBitFlags {
fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
-> ::bitflags::__private::core::fmt::Result {
let inner = self.0;
::bitflags::__private::core::fmt::LowerHex::fmt(&inner, f)
}
}
impl ::bitflags::__private::core::fmt::UpperHex for InternalBitFlags {
fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
-> ::bitflags::__private::core::fmt::Result {
let inner = self.0;
::bitflags::__private::core::fmt::UpperHex::fmt(&inner, f)
}
}
impl ::bitflags::__private::core::ops::BitOr for InternalBitFlags {
type Output = Self;
/// The bitwise or (`|`) of the bits in two flags values.
#[inline]
fn bitor(self, other: InternalBitFlags) -> Self {
self.union(other)
}
}
impl ::bitflags::__private::core::ops::BitOrAssign for
InternalBitFlags {
/// The bitwise or (`|`) of the bits in two flags values.
#[inline]
fn bitor_assign(&mut self, other: Self) { self.insert(other); }
}
impl ::bitflags::__private::core::ops::BitXor for InternalBitFlags {
type Output = Self;
/// The bitwise exclusive-or (`^`) of the bits in two flags values.
#[inline]
fn bitxor(self, other: Self) -> Self {
self.symmetric_difference(other)
}
}
impl ::bitflags::__private::core::ops::BitXorAssign for
InternalBitFlags {
/// The bitwise exclusive-or (`^`) of the bits in two flags values.
#[inline]
fn bitxor_assign(&mut self, other: Self) { self.toggle(other); }
}
impl ::bitflags::__private::core::ops::BitAnd for InternalBitFlags {
type Output = Self;
/// The bitwise and (`&`) of the bits in two flags values.
#[inline]
fn bitand(self, other: Self) -> Self { self.intersection(other) }
}
impl ::bitflags::__private::core::ops::BitAndAssign for
InternalBitFlags {
/// The bitwise and (`&`) of the bits in two flags values.
#[inline]
fn bitand_assign(&mut self, other: Self) {
*self =
Self::from_bits_retain(self.bits()).intersection(other);
}
}
impl ::bitflags::__private::core::ops::Sub for InternalBitFlags {
type Output = Self;
/// The intersection of a source flags value with the complement of a target flags value (`&!`).
///
/// This method is not equivalent to `self & !other` when `other` has unknown bits set.
/// `difference` won't truncate `other`, but the `!` operator will.
#[inline]
fn sub(self, other: Self) -> Self { self.difference(other) }
}
impl ::bitflags::__private::core::ops::SubAssign for InternalBitFlags
{
/// The intersection of a source flags value with the complement of a target flags value (`&!`).
///
/// This method is not equivalent to `self & !other` when `other` has unknown bits set.
/// `difference` won't truncate `other`, but the `!` operator will.
#[inline]
fn sub_assign(&mut self, other: Self) { self.remove(other); }
}
impl ::bitflags::__private::core::ops::Not for InternalBitFlags {
type Output = Self;
/// The bitwise negation (`!`) of the bits in a flags value, truncating the result.
#[inline]
fn not(self) -> Self { self.complement() }
}
impl ::bitflags::__private::core::iter::Extend<InternalBitFlags> for
InternalBitFlags {
/// The bitwise or (`|`) of the bits in each flags value.
fn extend<T: ::bitflags::__private::core::iter::IntoIterator<Item
= Self>>(&mut self, iterator: T) {
for item in iterator { self.insert(item) }
}
}
impl ::bitflags::__private::core::iter::FromIterator<InternalBitFlags>
for InternalBitFlags {
/// The bitwise or (`|`) of the bits in each flags value.
fn from_iter<T: ::bitflags::__private::core::iter::IntoIterator<Item
= Self>>(iterator: T) -> Self {
use ::bitflags::__private::core::iter::Extend;
let mut result = Self::empty();
result.extend(iterator);
result
}
}
impl InternalBitFlags {
/// Yield a set of contained flags values.
///
/// Each yielded flags value will correspond to a defined named flag. Any unknown bits
/// will be yielded together as a final flags value.
#[inline]
pub const fn iter(&self) -> ::bitflags::iter::Iter<Restrictions> {
::bitflags::iter::Iter::__private_const_new(<Restrictions as
::bitflags::Flags>::FLAGS,
Restrictions::from_bits_retain(self.bits()),
Restrictions::from_bits_retain(self.bits()))
}
/// Yield a set of contained named flags values.
///
/// This method is like [`iter`](#method.iter), except only yields bits in contained named flags.
/// Any unknown bits, or bits not corresponding to a contained flag will not be yielded.
#[inline]
pub const fn iter_names(&self)
-> ::bitflags::iter::IterNames<Restrictions> {
::bitflags::iter::IterNames::__private_const_new(<Restrictions
as ::bitflags::Flags>::FLAGS,
Restrictions::from_bits_retain(self.bits()),
Restrictions::from_bits_retain(self.bits()))
}
}
impl ::bitflags::__private::core::iter::IntoIterator for
InternalBitFlags {
type Item = Restrictions;
type IntoIter = ::bitflags::iter::Iter<Restrictions>;
fn into_iter(self) -> Self::IntoIter { self.iter() }
}
impl InternalBitFlags {
/// Returns a mutable reference to the raw value of the flags currently stored.
#[inline]
pub fn bits_mut(&mut self) -> &mut u8 { &mut self.0 }
}
#[allow(dead_code, deprecated, unused_attributes)]
impl Restrictions {
/// Get a flags value with all bits unset.
#[inline]
pub const fn empty() -> Self { Self(InternalBitFlags::empty()) }
/// Get a flags value with all known bits set.
#[inline]
pub const fn all() -> Self { Self(InternalBitFlags::all()) }
/// Get the underlying bits value.
///
/// The returned value is exactly the bits set in this flags value.
#[inline]
pub const fn bits(&self) -> u8 { self.0.bits() }
/// Convert from a bits value.
///
/// This method will return `None` if any unknown bits are set.
#[inline]
pub const fn from_bits(bits: u8)
-> ::bitflags::__private::core::option::Option<Self> {
match InternalBitFlags::from_bits(bits) {
::bitflags::__private::core::option::Option::Some(bits) =>
::bitflags::__private::core::option::Option::Some(Self(bits)),
::bitflags::__private::core::option::Option::None =>
::bitflags::__private::core::option::Option::None,
}
}
/// Convert from a bits value, unsetting any unknown bits.
#[inline]
pub const fn from_bits_truncate(bits: u8) -> Self {
Self(InternalBitFlags::from_bits_truncate(bits))
}
/// Convert from a bits value exactly.
#[inline]
pub const fn from_bits_retain(bits: u8) -> Self {
Self(InternalBitFlags::from_bits_retain(bits))
}
/// Get a flags value with the bits of a flag with the given name set.
///
/// This method will return `None` if `name` is empty or doesn't
/// correspond to any named flag.
#[inline]
pub fn from_name(name: &str)
-> ::bitflags::__private::core::option::Option<Self> {
match InternalBitFlags::from_name(name) {
::bitflags::__private::core::option::Option::Some(bits) =>
::bitflags::__private::core::option::Option::Some(Self(bits)),
::bitflags::__private::core::option::Option::None =>
::bitflags::__private::core::option::Option::None,
}
}
/// Whether all bits in this flags value are unset.
#[inline]
pub const fn is_empty(&self) -> bool { self.0.is_empty() }
/// Whether all known bits in this flags value are set.
#[inline]
pub const fn is_all(&self) -> bool { self.0.is_all() }
/// Whether any set bits in a source flags value are also set in a target flags value.
#[inline]
pub const fn intersects(&self, other: Self) -> bool {
self.0.intersects(other.0)
}
/// Whether all set bits in a source flags value are also set in a target flags value.
#[inline]
pub const fn contains(&self, other: Self) -> bool {
self.0.contains(other.0)
}
/// The bitwise or (`|`) of the bits in two flags values.
#[inline]
pub fn insert(&mut self, other: Self) { self.0.insert(other.0) }
/// The intersection of a source flags value with the complement of a target flags
/// value (`&!`).
///
/// This method is not equivalent to `self & !other` when `other` has unknown bits set.
/// `remove` won't truncate `other`, but the `!` operator will.
#[inline]
pub fn remove(&mut self, other: Self) { self.0.remove(other.0) }
/// The bitwise exclusive-or (`^`) of the bits in two flags values.
#[inline]
pub fn toggle(&mut self, other: Self) { self.0.toggle(other.0) }
/// Call `insert` when `value` is `true` or `remove` when `value` is `false`.
#[inline]
pub fn set(&mut self, other: Self, value: bool) {
self.0.set(other.0, value)
}
/// The bitwise and (`&`) of the bits in two flags values.
#[inline]
#[must_use]
pub const fn intersection(self, other: Self) -> Self {
Self(self.0.intersection(other.0))
}
/// The bitwise or (`|`) of the bits in two flags values.
#[inline]
#[must_use]
pub const fn union(self, other: Self) -> Self {
Self(self.0.union(other.0))
}
/// The intersection of a source flags value with the complement of a target flags
/// value (`&!`).
///
/// This method is not equivalent to `self & !other` when `other` has unknown bits set.
/// `difference` won't truncate `other`, but the `!` operator will.
#[inline]
#[must_use]
pub const fn difference(self, other: Self) -> Self {
Self(self.0.difference(other.0))
}
/// The bitwise exclusive-or (`^`) of the bits in two flags values.
#[inline]
#[must_use]
pub const fn symmetric_difference(self, other: Self) -> Self {
Self(self.0.symmetric_difference(other.0))
}
/// The bitwise negation (`!`) of the bits in a flags value, truncating the result.
#[inline]
#[must_use]
pub const fn complement(self) -> Self {
Self(self.0.complement())
}
}
impl ::bitflags::__private::core::fmt::Binary for Restrictions {
fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
-> ::bitflags::__private::core::fmt::Result {
let inner = self.0;
::bitflags::__private::core::fmt::Binary::fmt(&inner, f)
}
}
impl ::bitflags::__private::core::fmt::Octal for Restrictions {
fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
-> ::bitflags::__private::core::fmt::Result {
let inner = self.0;
::bitflags::__private::core::fmt::Octal::fmt(&inner, f)
}
}
impl ::bitflags::__private::core::fmt::LowerHex for Restrictions {
fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
-> ::bitflags::__private::core::fmt::Result {
let inner = self.0;
::bitflags::__private::core::fmt::LowerHex::fmt(&inner, f)
}
}
impl ::bitflags::__private::core::fmt::UpperHex for Restrictions {
fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
-> ::bitflags::__private::core::fmt::Result {
let inner = self.0;
::bitflags::__private::core::fmt::UpperHex::fmt(&inner, f)
}
}
impl ::bitflags::__private::core::ops::BitOr for Restrictions {
type Output = Self;
/// The bitwise or (`|`) of the bits in two flags values.
#[inline]
fn bitor(self, other: Restrictions) -> Self { self.union(other) }
}
impl ::bitflags::__private::core::ops::BitOrAssign for Restrictions {
/// The bitwise or (`|`) of the bits in two flags values.
#[inline]
fn bitor_assign(&mut self, other: Self) { self.insert(other); }
}
impl ::bitflags::__private::core::ops::BitXor for Restrictions {
type Output = Self;
/// The bitwise exclusive-or (`^`) of the bits in two flags values.
#[inline]
fn bitxor(self, other: Self) -> Self {
self.symmetric_difference(other)
}
}
impl ::bitflags::__private::core::ops::BitXorAssign for Restrictions {
/// The bitwise exclusive-or (`^`) of the bits in two flags values.
#[inline]
fn bitxor_assign(&mut self, other: Self) { self.toggle(other); }
}
impl ::bitflags::__private::core::ops::BitAnd for Restrictions {
type Output = Self;
/// The bitwise and (`&`) of the bits in two flags values.
#[inline]
fn bitand(self, other: Self) -> Self { self.intersection(other) }
}
impl ::bitflags::__private::core::ops::BitAndAssign for Restrictions {
/// The bitwise and (`&`) of the bits in two flags values.
#[inline]
fn bitand_assign(&mut self, other: Self) {
*self =
Self::from_bits_retain(self.bits()).intersection(other);
}
}
impl ::bitflags::__private::core::ops::Sub for Restrictions {
type Output = Self;
/// The intersection of a source flags value with the complement of a target flags value (`&!`).
///
/// This method is not equivalent to `self & !other` when `other` has unknown bits set.
/// `difference` won't truncate `other`, but the `!` operator will.
#[inline]
fn sub(self, other: Self) -> Self { self.difference(other) }
}
impl ::bitflags::__private::core::ops::SubAssign for Restrictions {
/// The intersection of a source flags value with the complement of a target flags value (`&!`).
///
/// This method is not equivalent to `self & !other` when `other` has unknown bits set.
/// `difference` won't truncate `other`, but the `!` operator will.
#[inline]
fn sub_assign(&mut self, other: Self) { self.remove(other); }
}
impl ::bitflags::__private::core::ops::Not for Restrictions {
type Output = Self;
/// The bitwise negation (`!`) of the bits in a flags value, truncating the result.
#[inline]
fn not(self) -> Self { self.complement() }
}
impl ::bitflags::__private::core::iter::Extend<Restrictions> for
Restrictions {
/// The bitwise or (`|`) of the bits in each flags value.
fn extend<T: ::bitflags::__private::core::iter::IntoIterator<Item
= Self>>(&mut self, iterator: T) {
for item in iterator { self.insert(item) }
}
}
impl ::bitflags::__private::core::iter::FromIterator<Restrictions> for
Restrictions {
/// The bitwise or (`|`) of the bits in each flags value.
fn from_iter<T: ::bitflags::__private::core::iter::IntoIterator<Item
= Self>>(iterator: T) -> Self {
use ::bitflags::__private::core::iter::Extend;
let mut result = Self::empty();
result.extend(iterator);
result
}
}
impl Restrictions {
/// Yield a set of contained flags values.
///
/// Each yielded flags value will correspond to a defined named flag. Any unknown bits
/// will be yielded together as a final flags value.
#[inline]
pub const fn iter(&self) -> ::bitflags::iter::Iter<Restrictions> {
::bitflags::iter::Iter::__private_const_new(<Restrictions as
::bitflags::Flags>::FLAGS,
Restrictions::from_bits_retain(self.bits()),
Restrictions::from_bits_retain(self.bits()))
}
/// Yield a set of contained named flags values.
///
/// This method is like [`iter`](#method.iter), except only yields bits in contained named flags.
/// Any unknown bits, or bits not corresponding to a contained flag will not be yielded.
#[inline]
pub const fn iter_names(&self)
-> ::bitflags::iter::IterNames<Restrictions> {
::bitflags::iter::IterNames::__private_const_new(<Restrictions
as ::bitflags::Flags>::FLAGS,
Restrictions::from_bits_retain(self.bits()),
Restrictions::from_bits_retain(self.bits()))
}
}
impl ::bitflags::__private::core::iter::IntoIterator for Restrictions
{
type Item = Restrictions;
type IntoIter = ::bitflags::iter::Iter<Restrictions>;
fn into_iter(self) -> Self::IntoIter { self.iter() }
}
};Clone, #[automatically_derived]
impl ::core::marker::Copy for Restrictions { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for Restrictions {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Restrictions",
&&self.0)
}
}Debug)]
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/// If the next tokens are ill-formed `$ty::` recover them as `<$ty>::`.
149#[macro_export]
150macro_rules!maybe_recover_from_interpolated_ty_qpath {
151 ($self: expr, $allow_qpath_recovery: expr) => {
152if $allow_qpath_recovery
153&& $self.may_recover()
154 && let Some(mv_kind) = $self.token.is_metavar_seq()
155 && let token::MetaVarKind::Ty { .. } = mv_kind
156 && $self.check_noexpect_past_close_delim(&token::PathSep)
157 {
158// Reparse the type, then move to recovery.
159let ty = $self
160.eat_metavar_seq(mv_kind, |this| this.parse_ty_no_question_mark_recover())
161 .expect("metavar seq ty");
162163return $self.maybe_recover_from_bad_qpath_stage_2($self.prev_token.span, ty);
164 }
165 };
166}
167168#[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)]
169pub enum Recovery {
170 Allowed,
171 Forbidden,
172}
173174#[derive(#[automatically_derived]
impl<'a> ::core::clone::Clone for Parser<'a> {
#[inline]
fn clone(&self) -> Parser<'a> {
Parser {
psess: ::core::clone::Clone::clone(&self.psess),
token: ::core::clone::Clone::clone(&self.token),
token_spacing: ::core::clone::Clone::clone(&self.token_spacing),
prev_token: ::core::clone::Clone::clone(&self.prev_token),
capture_cfg: ::core::clone::Clone::clone(&self.capture_cfg),
restrictions: ::core::clone::Clone::clone(&self.restrictions),
expected_token_types: ::core::clone::Clone::clone(&self.expected_token_types),
token_cursor: ::core::clone::Clone::clone(&self.token_cursor),
num_bump_calls: ::core::clone::Clone::clone(&self.num_bump_calls),
break_last_token: ::core::clone::Clone::clone(&self.break_last_token),
unmatched_angle_bracket_count: ::core::clone::Clone::clone(&self.unmatched_angle_bracket_count),
angle_bracket_nesting: ::core::clone::Clone::clone(&self.angle_bracket_nesting),
parsing_generics: ::core::clone::Clone::clone(&self.parsing_generics),
last_unexpected_token_span: ::core::clone::Clone::clone(&self.last_unexpected_token_span),
subparser_name: ::core::clone::Clone::clone(&self.subparser_name),
capture_state: ::core::clone::Clone::clone(&self.capture_state),
current_closure: ::core::clone::Clone::clone(&self.current_closure),
recovery: ::core::clone::Clone::clone(&self.recovery),
}
}
}Clone)]
175pub struct Parser<'a> {
176pub psess: &'a ParseSess,
177/// The current token.
178pub token: Token = Token::dummy(),
179/// The spacing for the current token.
180token_spacing: Spacing = Spacing::Alone,
181/// The previous token.
182pub prev_token: Token = Token::dummy(),
183pub capture_cfg: bool = false,
184 restrictions: Restrictions = Restrictions::empty(),
185 expected_token_types: TokenTypeSet = TokenTypeSet::new(),
186 token_cursor: TokenCursor,
187// The number of calls to `bump`, i.e. the position in the token stream.
188num_bump_calls: u32 = 0,
189// During parsing we may sometimes need to "unglue" a glued token into two
190 // or three component tokens (e.g. `>>` into `>` and `>`, or `>>=` into `>`
191 // and `>` and `=`), so the parser can consume them one at a time. This
192 // process bypasses the normal capturing mechanism (e.g. `num_bump_calls`
193 // will not be incremented), since the "unglued" tokens due not exist in
194 // the original `TokenStream`.
195 //
196 // If we end up consuming all the component tokens, this is not an issue,
197 // because we'll end up capturing the single "glued" token.
198 //
199 // However, sometimes we may want to capture not all of the original
200 // token. For example, capturing the `Vec<u8>` in `Option<Vec<u8>>`
201 // requires us to unglue the trailing `>>` token. The `break_last_token`
202 // field is used to track these tokens. They get appended to the captured
203 // stream when we evaluate a `LazyAttrTokenStream`.
204 //
205 // This value is always 0, 1, or 2. It can only reach 2 when splitting
206 // `>>=` or `<<=`.
207break_last_token: u32 = 0,
208/// This field is used to keep track of how many left angle brackets we have seen. This is
209 /// required in order to detect extra leading left angle brackets (`<` characters) and error
210 /// appropriately.
211 ///
212 /// See the comments in the `parse_path_segment` function for more details.
213unmatched_angle_bracket_count: u16 = 0,
214 angle_bracket_nesting: u16 = 0,
215/// Keep track of when we're within `<...>` for proper error recovery.
216parsing_generics: bool = false,
217218 last_unexpected_token_span: Option<Span> = None,
219/// If present, this `Parser` is not parsing Rust code but rather a macro call.
220subparser_name: Option<&'static str>,
221 capture_state: CaptureState,
222/// This allows us to recover when the user forget to add braces around
223 /// multiple statements in the closure body.
224current_closure: Option<ClosureSpans> = None,
225/// Whether the parser is allowed to do recovery.
226 /// This is disabled when parsing macro arguments, see #103534
227recovery: Recovery = Recovery::Allowed,
228}
229230// This type is used a lot, e.g. it's cloned when matching many declarative macro rules with
231// nonterminals. Make sure it doesn't unintentionally get bigger. We only check a few arches
232// though, because `TokenTypeSet(u128)` alignment varies on others, changing the total size.
233#[cfg(all(target_pointer_width = "64", any(target_arch = "aarch64", target_arch = "x86_64")))]
234const _: [(); 288] = [(); ::std::mem::size_of::<Parser<'_>>()];rustc_data_structures::static_assert_size!(Parser<'_>, 288);
235236/// Stores span information about a closure.
237#[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)]
238struct ClosureSpans {
239 whole_closure: Span,
240 closing_pipe: Span,
241 body: Span,
242}
243244/// Controls how we capture tokens. Capturing can be expensive,
245/// so we try to avoid performing capturing in cases where
246/// we will never need an `AttrTokenStream`.
247#[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)]
248enum Capturing {
249/// We aren't performing any capturing - this is the default mode.
250No,
251/// We are capturing tokens
252Yes,
253}
254255// This state is used by `Parser::collect_tokens`.
256#[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)]
257struct CaptureState {
258 capturing: Capturing,
259 parser_replacements: Vec<ParserReplacement>,
260 inner_attr_parser_ranges: FxHashMap<AttrId, ParserRange>,
261// `IntervalSet` is good for perf because attrs are mostly added to this
262 // set in contiguous ranges.
263seen_attrs: IntervalSet<AttrId>,
264}
265266/// A sequence separator.
267#[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)]
268struct SeqSep {
269/// The separator token.
270sep: Option<ExpTokenPair>,
271/// `true` if a trailing separator is allowed.
272trailing_sep_allowed: bool,
273}
274275impl SeqSep {
276fn trailing_allowed(sep: ExpTokenPair) -> SeqSep {
277SeqSep { sep: Some(sep), trailing_sep_allowed: true }
278 }
279280fn none() -> SeqSep {
281SeqSep { sep: None, trailing_sep_allowed: false }
282 }
283}
284285#[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)]
286pub enum FollowedByType {
287 Yes,
288 No,
289}
290291#[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)]
292pub enum Trailing {
293 No,
294 Yes,
295}
296297impl From<bool> for Trailing {
298fn from(b: bool) -> Trailing {
299if b { Trailing::Yes } else { Trailing::No }
300 }
301}
302303#[derive(#[automatically_derived]
impl ::core::clone::Clone for TokenDescription {
#[inline]
fn clone(&self) -> TokenDescription {
let _: ::core::clone::AssertParamIsClone<MetaVarKind>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for TokenDescription { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for TokenDescription {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
TokenDescription::ReservedIdentifier =>
::core::fmt::Formatter::write_str(f, "ReservedIdentifier"),
TokenDescription::Keyword =>
::core::fmt::Formatter::write_str(f, "Keyword"),
TokenDescription::ReservedKeyword =>
::core::fmt::Formatter::write_str(f, "ReservedKeyword"),
TokenDescription::DocComment =>
::core::fmt::Formatter::write_str(f, "DocComment"),
TokenDescription::MetaVar(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"MetaVar", &__self_0),
}
}
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for TokenDescription {
#[inline]
fn eq(&self, other: &TokenDescription) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(TokenDescription::MetaVar(__self_0),
TokenDescription::MetaVar(__arg1_0)) =>
__self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for TokenDescription {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_eq(&self) -> () {
let _: ::core::cmp::AssertParamIsEq<MetaVarKind>;
}
}Eq)]
304pub(super) enum TokenDescription {
305 ReservedIdentifier,
306 Keyword,
307 ReservedKeyword,
308 DocComment,
309310// Expanded metavariables are wrapped in invisible delimiters which aren't
311 // pretty-printed. In error messages we must handle these specially
312 // otherwise we get confusing things in messages like "expected `(`, found
313 // ``". It's better to say e.g. "expected `(`, found type metavariable".
314MetaVar(MetaVarKind),
315}
316317impl TokenDescription {
318pub(super) fn from_token(token: &Token) -> Option<Self> {
319match token.kind {
320_ if token.is_special_ident() => Some(TokenDescription::ReservedIdentifier),
321_ if token.is_used_keyword() => Some(TokenDescription::Keyword),
322_ if token.is_unused_keyword() => Some(TokenDescription::ReservedKeyword),
323 token::DocComment(..) => Some(TokenDescription::DocComment),
324 token::OpenInvisible(InvisibleOrigin::MetaVar(kind)) => {
325Some(TokenDescription::MetaVar(kind))
326 }
327_ => None,
328 }
329 }
330}
331332pub fn token_descr(token: &Token) -> String {
333let s = pprust::token_to_string(token).to_string();
334335match (TokenDescription::from_token(token), &token.kind) {
336 (Some(TokenDescription::ReservedIdentifier), _) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("reserved identifier `{0}`", s))
})format!("reserved identifier `{s}`"),
337 (Some(TokenDescription::Keyword), _) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("keyword `{0}`", s))
})format!("keyword `{s}`"),
338 (Some(TokenDescription::ReservedKeyword), _) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("reserved keyword `{0}`", s))
})format!("reserved keyword `{s}`"),
339 (Some(TokenDescription::DocComment), _) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("doc comment `{0}`", s))
})format!("doc comment `{s}`"),
340// Deliberately doesn't print `s`, which is empty.
341 (Some(TokenDescription::MetaVar(kind)), _) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` metavariable", kind))
})format!("`{kind}` metavariable"),
342 (None, TokenKind::NtIdent(..)) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("identifier `{0}`", s))
})format!("identifier `{s}`"),
343 (None, TokenKind::NtLifetime(..)) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("lifetime `{0}`", s))
})format!("lifetime `{s}`"),
344 (None, _) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", s))
})format!("`{s}`"),
345 }
346}
347348impl<'a> Parser<'a> {
349pub fn new(
350 psess: &'a ParseSess,
351 stream: TokenStream,
352 subparser_name: Option<&'static str>,
353 ) -> Self {
354let mut parser = Parser {
355psess,
356 token_cursor: TokenCursor { curr: TokenTreeCursor::new(stream), stack: Vec::new() },
357subparser_name,
358 capture_state: CaptureState {
359 capturing: Capturing::No,
360 parser_replacements: Vec::new(),
361 inner_attr_parser_ranges: Default::default(),
362 seen_attrs: IntervalSet::new(u32::MAXas usize),
363 },
364 ..
365 };
366367// Make parser point to the first token.
368parser.bump();
369370// Change this from 1 back to 0 after the bump. This eases debugging of
371 // `Parser::collect_tokens` because 0-indexed token positions are nicer
372 // than 1-indexed token positions.
373parser.num_bump_calls = 0;
374375parser376 }
377378#[inline]
379pub fn recovery(mut self, recovery: Recovery) -> Self {
380self.recovery = recovery;
381self382 }
383384#[inline]
385fn with_recovery<T>(&mut self, recovery: Recovery, f: impl FnOnce(&mut Self) -> T) -> T {
386let old = mem::replace(&mut self.recovery, recovery);
387let res = f(self);
388self.recovery = old;
389res390 }
391392/// Whether the parser is allowed to recover from broken code.
393 ///
394 /// If this returns false, recovering broken code into valid code (especially if this recovery does lookahead)
395 /// is not allowed. All recovery done by the parser must be gated behind this check.
396 ///
397 /// Technically, this only needs to restrict eager recovery by doing lookahead at more tokens.
398 /// But making the distinction is very subtle, and simply forbidding all recovery is a lot simpler to uphold.
399#[inline]
400fn may_recover(&self) -> bool {
401#[allow(non_exhaustive_omitted_patterns)] match self.recovery {
Recovery::Allowed => true,
_ => false,
}matches!(self.recovery, Recovery::Allowed)402 }
403404/// Version of [`unexpected`](Parser::unexpected) that "returns" any type in the `Ok`
405 /// (both those functions never return "Ok", and so can lie like that in the type).
406pub fn unexpected_any<T>(&mut self) -> PResult<'a, T> {
407match self.expect_one_of(&[], &[]) {
408Err(e) => Err(e),
409// We can get `Ok(true)` from `recover_closing_delimiter`
410 // which is called in `expected_one_of_not_found`.
411Ok(_) => FatalError.raise(),
412 }
413 }
414415pub fn unexpected(&mut self) -> PResult<'a, ()> {
416self.unexpected_any()
417 }
418419/// Expects and consumes the token `t`. Signals an error if the next token is not `t`.
420pub fn expect(&mut self, exp: ExpTokenPair) -> PResult<'a, Recovered> {
421if self.expected_token_types.is_empty() {
422if self.token == exp.tok {
423self.bump();
424Ok(Recovered::No)
425 } else {
426self.unexpected_try_recover(&exp.tok)
427 }
428 } else {
429self.expect_one_of(slice::from_ref(&exp), &[])
430 }
431 }
432433/// Expect next token to be edible or inedible token. If edible,
434 /// then consume it; if inedible, then return without consuming
435 /// anything. Signal a fatal error if next token is unexpected.
436fn expect_one_of(
437&mut self,
438 edible: &[ExpTokenPair],
439 inedible: &[ExpTokenPair],
440 ) -> PResult<'a, Recovered> {
441if edible.iter().any(|exp| exp.tok == self.token.kind) {
442self.bump();
443Ok(Recovered::No)
444 } else if inedible.iter().any(|exp| exp.tok == self.token.kind) {
445// leave it in the input
446Ok(Recovered::No)
447 } else if self.token != token::Eof448 && self.last_unexpected_token_span == Some(self.token.span)
449 {
450FatalError.raise();
451 } else {
452self.expected_one_of_not_found(edible, inedible)
453 .map(|error_guaranteed| Recovered::Yes(error_guaranteed))
454 }
455 }
456457// Public for rustfmt usage.
458pub fn parse_ident(&mut self) -> PResult<'a, Ident> {
459self.parse_ident_common(self.may_recover())
460 }
461462pub(crate) fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, Ident> {
463let (ident, is_raw) = self.ident_or_err(recover)?;
464465if is_raw == IdentIsRaw::No && ident.is_reserved() {
466let err = self.expected_ident_found_err();
467if recover {
468err.emit();
469 } else {
470return Err(err);
471 }
472 }
473self.bump();
474Ok(ident)
475 }
476477fn ident_or_err(&mut self, recover: bool) -> PResult<'a, (Ident, IdentIsRaw)> {
478match self.token.ident() {
479Some(ident) => Ok(ident),
480None => self.expected_ident_found(recover),
481 }
482 }
483484/// Checks if the next token is `tok`, and returns `true` if so.
485 ///
486 /// This method will automatically add `tok` to `expected_token_types` if `tok` is not
487 /// encountered.
488#[inline]
489pub fn check(&mut self, exp: ExpTokenPair) -> bool {
490let is_present = self.token == exp.tok;
491if !is_present {
492self.expected_token_types.insert(exp.token_type);
493 }
494is_present495 }
496497#[inline]
498 #[must_use]
499fn check_noexpect(&self, tok: &TokenKind) -> bool {
500self.token == *tok501 }
502503// Check the first token after the delimiter that closes the current
504 // delimited sequence. (Panics if used in the outermost token stream, which
505 // has no delimiters.) It uses a clone of the relevant tree cursor to skip
506 // past the entire `TokenTree::Delimited` in a single step, avoiding the
507 // need for unbounded token lookahead.
508 //
509 // Primarily used when `self.token` matches `OpenInvisible(_))`, to look
510 // ahead through the current metavar expansion.
511fn check_noexpect_past_close_delim(&self, tok: &TokenKind) -> bool {
512let mut tree_cursor = self.token_cursor.stack.last().unwrap().clone();
513tree_cursor.bump();
514#[allow(non_exhaustive_omitted_patterns)] match tree_cursor.curr() {
Some(TokenTree::Token(token::Token { kind, .. }, _)) if kind == tok =>
true,
_ => false,
}matches!(
515 tree_cursor.curr(),
516Some(TokenTree::Token(token::Token { kind, .. }, _)) if kind == tok
517 )518 }
519520/// Consumes a token 'tok' if it exists. Returns whether the given token was present.
521 ///
522 /// the main purpose of this function is to reduce the cluttering of the suggestions list
523 /// which using the normal eat method could introduce in some cases.
524#[inline]
525 #[must_use]
526fn eat_noexpect(&mut self, tok: &TokenKind) -> bool {
527let is_present = self.check_noexpect(tok);
528if is_present {
529self.bump()
530 }
531is_present532 }
533534/// Consumes a token 'tok' if it exists. Returns whether the given token was present.
535#[inline]
536 #[must_use]
537pub fn eat(&mut self, exp: ExpTokenPair) -> bool {
538let is_present = self.check(exp);
539if is_present {
540self.bump()
541 }
542is_present543 }
544545/// If the next token is the given keyword, returns `true` without eating it.
546 /// An expectation is also added for diagnostics purposes.
547#[inline]
548 #[must_use]
549fn check_keyword(&mut self, exp: ExpKeywordPair) -> bool {
550let is_keyword = self.token.is_keyword(exp.kw);
551if !is_keyword {
552self.expected_token_types.insert(exp.token_type);
553 }
554is_keyword555 }
556557#[inline]
558 #[must_use]
559fn check_keyword_case(&mut self, exp: ExpKeywordPair, case: Case) -> bool {
560if self.check_keyword(exp) {
561true
562} else if case == Case::Insensitive563 && let Some((ident, IdentIsRaw::No)) = self.token.ident()
564// Do an ASCII case-insensitive match, because all keywords are ASCII.
565&& ident.as_str().eq_ignore_ascii_case(exp.kw.as_str())
566 {
567true
568} else {
569false
570}
571 }
572573/// If the next token is the given keyword, eats it and returns `true`.
574 /// Otherwise, returns `false`. An expectation is also added for diagnostics purposes.
575// Public for rustc_builtin_macros and rustfmt usage.
576#[inline]
577 #[must_use]
578pub fn eat_keyword(&mut self, exp: ExpKeywordPair) -> bool {
579let is_keyword = self.check_keyword(exp);
580if is_keyword {
581self.bump();
582 }
583is_keyword584 }
585586/// Eats a keyword, optionally ignoring the case.
587 /// If the case differs (and is ignored) an error is issued.
588 /// This is useful for recovery.
589#[inline]
590 #[must_use]
591fn eat_keyword_case(&mut self, exp: ExpKeywordPair, case: Case) -> bool {
592if self.eat_keyword(exp) {
593true
594} else if case == Case::Insensitive595 && let Some((ident, IdentIsRaw::No)) = self.token.ident()
596// Do an ASCII case-insensitive match, because all keywords are ASCII.
597&& ident.as_str().eq_ignore_ascii_case(exp.kw.as_str())
598 {
599let kw = exp.kw.as_str();
600let is_upper = kw.chars().all(char::is_uppercase);
601let is_lower = kw.chars().all(char::is_lowercase);
602603let case = match (is_upper, is_lower) {
604 (true, true) => {
605{
::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")606 }
607 (true, false) => errors::Case::Upper,
608 (false, true) => errors::Case::Lower,
609 (false, false) => errors::Case::Mixed,
610 };
611612self.dcx().emit_err(errors::KwBadCase { span: ident.span, kw, case });
613self.bump();
614true
615} else {
616false
617}
618 }
619620/// If the next token is the given keyword, eats it and returns `true`.
621 /// Otherwise, returns `false`. No expectation is added.
622// Public for rustc_builtin_macros usage.
623#[inline]
624 #[must_use]
625pub fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool {
626let is_keyword = self.token.is_keyword(kw);
627if is_keyword {
628self.bump();
629 }
630is_keyword631 }
632633/// If the given word is not a keyword, signals an error.
634 /// If the next token is not the given word, signals an error.
635 /// Otherwise, eats it.
636pub fn expect_keyword(&mut self, exp: ExpKeywordPair) -> PResult<'a, ()> {
637if !self.eat_keyword(exp) { self.unexpected() } else { Ok(()) }
638 }
639640/// Consume a sequence produced by a metavar expansion, if present.
641pub fn eat_metavar_seq<T>(
642&mut self,
643 mv_kind: MetaVarKind,
644 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
645 ) -> Option<T> {
646self.eat_metavar_seq_with_matcher(|mvk| mvk == mv_kind, f)
647 }
648649/// A slightly more general form of `eat_metavar_seq`, for use with the
650 /// `MetaVarKind` variants that have parameters, where an exact match isn't
651 /// desired.
652fn eat_metavar_seq_with_matcher<T>(
653&mut self,
654 match_mv_kind: impl Fn(MetaVarKind) -> bool,
655mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
656 ) -> Option<T> {
657if let token::OpenInvisible(InvisibleOrigin::MetaVar(mv_kind)) = self.token.kind
658 && match_mv_kind(mv_kind)
659 {
660self.bump();
661662// Recovery is disabled when parsing macro arguments, so it must
663 // also be disabled when reparsing pasted macro arguments,
664 // otherwise we get inconsistent results (e.g. #137874).
665let res = self.with_recovery(Recovery::Forbidden, |this| f(this));
666667let res = match res {
668Ok(res) => res,
669Err(err) => {
670// This can occur in unusual error cases, e.g. #139445.
671err.delay_as_bug();
672return None;
673 }
674 };
675676if let token::CloseInvisible(InvisibleOrigin::MetaVar(mv_kind)) = self.token.kind
677 && match_mv_kind(mv_kind)
678 {
679self.bump();
680Some(res)
681 } else {
682// This can occur when invalid syntax is passed to a decl macro. E.g. see #139248,
683 // where the reparse attempt of an invalid expr consumed the trailing invisible
684 // delimiter.
685self.dcx()
686 .span_delayed_bug(self.token.span, "no close delim with reparsing {mv_kind:?}");
687None688 }
689 } else {
690None691 }
692 }
693694/// Is the given keyword `kw` followed by a non-reserved identifier?
695fn is_kw_followed_by_ident(&self, kw: Symbol) -> bool {
696self.token.is_keyword(kw) && self.look_ahead(1, |t| t.is_non_reserved_ident())
697 }
698699#[inline]
700fn check_or_expected(&mut self, ok: bool, token_type: TokenType) -> bool {
701if !ok {
702self.expected_token_types.insert(token_type);
703 }
704ok705 }
706707fn check_ident(&mut self) -> bool {
708self.check_or_expected(self.token.is_ident(), TokenType::Ident)
709 }
710711fn check_path(&mut self) -> bool {
712self.check_or_expected(self.token.is_path_start(), TokenType::Path)
713 }
714715fn check_type(&mut self) -> bool {
716self.check_or_expected(self.token.can_begin_type(), TokenType::Type)
717 }
718719fn check_const_arg(&mut self) -> bool {
720let is_mcg_arg = self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const);
721let is_mgca_arg = self.is_keyword_ahead(0, &[kw::Const])
722 && self.look_ahead(1, |t| *t == token::OpenBrace);
723is_mcg_arg || is_mgca_arg724 }
725726fn check_const_closure(&self) -> bool {
727self.is_keyword_ahead(0, &[kw::Const])
728 && self.look_ahead(1, |t| match &t.kind {
729// async closures do not work with const closures, so we do not parse that here.
730token::Ident(kw::Move | kw::Use | kw::Static, IdentIsRaw::No)
731 | token::OrOr732 | token::Or => true,
733_ => false,
734 })
735 }
736737fn check_inline_const(&self, dist: usize) -> bool {
738self.is_keyword_ahead(dist, &[kw::Const])
739 && self.look_ahead(dist + 1, |t| match &t.kind {
740 token::OpenBrace => true,
741 token::OpenInvisible(InvisibleOrigin::MetaVar(MetaVarKind::Block)) => true,
742_ => false,
743 })
744 }
745746/// Checks to see if the next token is either `+` or `+=`.
747 /// Otherwise returns `false`.
748#[inline]
749fn check_plus(&mut self) -> bool {
750self.check_or_expected(self.token.is_like_plus(), TokenType::Plus)
751 }
752753/// Eats the expected token if it's present possibly breaking
754 /// compound tokens like multi-character operators in process.
755 /// Returns `true` if the token was eaten.
756fn break_and_eat(&mut self, exp: ExpTokenPair) -> bool {
757if self.token == exp.tok {
758self.bump();
759return true;
760 }
761match self.token.kind.break_two_token_op(1) {
762Some((first, second)) if first == exp.tok => {
763let first_span = self.psess.source_map().start_point(self.token.span);
764let second_span = self.token.span.with_lo(first_span.hi());
765self.token = Token::new(first, first_span);
766// Keep track of this token - if we end token capturing now,
767 // we'll want to append this token to the captured stream.
768 //
769 // If we consume any additional tokens, then this token
770 // is not needed (we'll capture the entire 'glued' token),
771 // and `bump` will set this field to 0.
772self.break_last_token += 1;
773// Use the spacing of the glued token as the spacing of the
774 // unglued second token.
775self.bump_with((Token::new(second, second_span), self.token_spacing));
776true
777}
778_ => {
779self.expected_token_types.insert(exp.token_type);
780false
781}
782 }
783 }
784785/// Eats `+` possibly breaking tokens like `+=` in process.
786fn eat_plus(&mut self) -> bool {
787self.break_and_eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Plus,
token_type: crate::parser::token_type::TokenType::Plus,
}exp!(Plus))
788 }
789790/// Eats `&` possibly breaking tokens like `&&` in process.
791 /// Signals an error if `&` is not eaten.
792fn expect_and(&mut self) -> PResult<'a, ()> {
793if 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() }
794 }
795796/// Eats `|` possibly breaking tokens like `||` in process.
797 /// Signals an error if `|` was not eaten.
798fn expect_or(&mut self) -> PResult<'a, ()> {
799if 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() }
800 }
801802/// Eats `<` possibly breaking tokens like `<<` in process.
803fn eat_lt(&mut self) -> bool {
804let 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));
805if ate {
806// See doc comment for `unmatched_angle_bracket_count`.
807self.unmatched_angle_bracket_count += 1;
808{
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:808",
"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(808u32),
::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);
809 }
810ate811 }
812813/// Eats `<` possibly breaking tokens like `<<` in process.
814 /// Signals an error if `<` was not eaten.
815fn expect_lt(&mut self) -> PResult<'a, ()> {
816if self.eat_lt() { Ok(()) } else { self.unexpected() }
817 }
818819/// Eats `>` possibly breaking tokens like `>>` in process.
820 /// Signals an error if `>` was not eaten.
821fn expect_gt(&mut self) -> PResult<'a, ()> {
822if self.break_and_eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Gt,
token_type: crate::parser::token_type::TokenType::Gt,
}exp!(Gt)) {
823// See doc comment for `unmatched_angle_bracket_count`.
824if self.unmatched_angle_bracket_count > 0 {
825self.unmatched_angle_bracket_count -= 1;
826{
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:826",
"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(826u32),
::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);
827 }
828Ok(())
829 } else {
830self.unexpected()
831 }
832 }
833834/// Checks if the next token is contained within `closes`, and returns `true` if so.
835fn expect_any_with_type(
836&mut self,
837 closes_expected: &[ExpTokenPair],
838 closes_not_expected: &[&TokenKind],
839 ) -> bool {
840closes_expected.iter().any(|&close| self.check(close))
841 || closes_not_expected.iter().any(|k| self.check_noexpect(k))
842 }
843844/// Parses a sequence until the specified delimiters. The function
845 /// `f` must consume tokens until reaching the next separator or
846 /// closing bracket.
847fn parse_seq_to_before_tokens<T>(
848&mut self,
849 closes_expected: &[ExpTokenPair],
850 closes_not_expected: &[&TokenKind],
851 sep: SeqSep,
852mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
853 ) -> PResult<'a, (ThinVec<T>, Trailing, Recovered)> {
854let mut first = true;
855let mut recovered = Recovered::No;
856let mut trailing = Trailing::No;
857let mut v = ThinVec::new();
858859while !self.expect_any_with_type(closes_expected, closes_not_expected) {
860if self.token.kind.is_close_delim_or_eof() {
861break;
862 }
863if let Some(exp) = sep.sep {
864if first {
865// no separator for the first element
866first = false;
867 } else {
868// check for separator
869match self.expect(exp) {
870Ok(Recovered::No) => {
871self.current_closure.take();
872 }
873Ok(Recovered::Yes(guar)) => {
874self.current_closure.take();
875 recovered = Recovered::Yes(guar);
876break;
877 }
878Err(mut expect_err) => {
879let sp = self.prev_token.span.shrink_to_hi();
880let token_str = pprust::token_kind_to_string(&exp.tok);
881882match self.current_closure.take() {
883Some(closure_spans) if self.token == TokenKind::Semi => {
884// Finding a semicolon instead of a comma
885 // after a closure body indicates that the
886 // closure body may be a block but the user
887 // forgot to put braces around its
888 // statements.
889890self.recover_missing_braces_around_closure_body(
891 closure_spans,
892 expect_err,
893 )?;
894895continue;
896 }
897898_ => {
899// Attempt to keep parsing if it was a similar separator.
900if exp.tok.similar_tokens().contains(&self.token.kind) {
901self.bump();
902 }
903 }
904 }
905906// If this was a missing `@` in a binding pattern
907 // bail with a suggestion
908 // https://github.com/rust-lang/rust/issues/72373
909if self.prev_token.is_ident() && self.token == token::DotDot {
910let 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!(
911"if you meant to bind the contents of the rest of the array \
912 pattern into `{}`, use `@`",
913 pprust::token_to_string(&self.prev_token)
914 );
915 expect_err
916 .with_span_suggestion_verbose(
917self.prev_token.span.shrink_to_hi().until(self.token.span),
918 msg,
919" @ ",
920 Applicability::MaybeIncorrect,
921 )
922 .emit();
923break;
924 }
925926// Attempt to keep parsing if it was an omitted separator.
927self.last_unexpected_token_span = None;
928match f(self) {
929Ok(t) => {
930// Parsed successfully, therefore most probably the code only
931 // misses a separator.
932expect_err
933 .with_span_suggestion_short(
934 sp,
935::alloc::__export::must_use({
::alloc::fmt::format(format_args!("missing `{0}`", token_str))
})format!("missing `{token_str}`"),
936 token_str,
937 Applicability::MaybeIncorrect,
938 )
939 .emit();
940941 v.push(t);
942continue;
943 }
944Err(e) => {
945// Parsing failed, therefore it must be something more serious
946 // than just a missing separator.
947for xx in &e.children {
948// Propagate the help message from sub error `e` to main
949 // error `expect_err`.
950expect_err.children.push(xx.clone());
951 }
952 e.cancel();
953if self.token == token::Colon {
954// We will try to recover in
955 // `maybe_recover_struct_lit_bad_delims`.
956return Err(expect_err);
957 } else if let [exp] = closes_expected
958 && exp.token_type == TokenType::CloseParen
959 {
960return Err(expect_err);
961 } else {
962 expect_err.emit();
963break;
964 }
965 }
966 }
967 }
968 }
969 }
970 }
971if sep.trailing_sep_allowed
972 && self.expect_any_with_type(closes_expected, closes_not_expected)
973 {
974 trailing = Trailing::Yes;
975break;
976 }
977978let t = f(self)?;
979 v.push(t);
980 }
981982Ok((v, trailing, recovered))
983 }
984985fn recover_missing_braces_around_closure_body(
986&mut self,
987 closure_spans: ClosureSpans,
988mut expect_err: Diag<'_>,
989 ) -> PResult<'a, ()> {
990let initial_semicolon = self.token.span;
991992while self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Semi,
token_type: crate::parser::token_type::TokenType::Semi,
}exp!(Semi)) {
993let _ = self
994.parse_stmt_without_recovery(false, ForceCollect::No, false)
995 .unwrap_or_else(|e| {
996 e.cancel();
997None
998});
999 }
10001001expect_err1002 .primary_message("closure bodies that contain statements must be surrounded by braces");
10031004let preceding_pipe_span = closure_spans.closing_pipe;
1005let following_token_span = self.token.span;
10061007let mut first_note = MultiSpan::from(<[_]>::into_vec(::alloc::boxed::box_new([initial_semicolon]))vec![initial_semicolon]);
1008first_note.push_span_label(
1009initial_semicolon,
1010"this `;` turns the preceding closure into a statement",
1011 );
1012first_note.push_span_label(
1013closure_spans.body,
1014"this expression is a statement because of the trailing semicolon",
1015 );
1016expect_err.span_note(first_note, "statement found outside of a block");
10171018let mut second_note = MultiSpan::from(<[_]>::into_vec(::alloc::boxed::box_new([closure_spans.whole_closure]))vec![closure_spans.whole_closure]);
1019second_note.push_span_label(closure_spans.whole_closure, "this is the parsed closure...");
1020second_note.push_span_label(
1021following_token_span,
1022"...but likely you meant the closure to end here",
1023 );
1024expect_err.span_note(second_note, "the closure body may be incorrectly delimited");
10251026expect_err.span(<[_]>::into_vec(::alloc::boxed::box_new([preceding_pipe_span,
following_token_span]))vec![preceding_pipe_span, following_token_span]);
10271028let opening_suggestion_str = " {".to_string();
1029let closing_suggestion_str = "}".to_string();
10301031expect_err.multipart_suggestion(
1032"try adding braces",
1033<[_]>::into_vec(::alloc::boxed::box_new([(preceding_pipe_span.shrink_to_hi(),
opening_suggestion_str),
(following_token_span.shrink_to_lo(),
closing_suggestion_str)]))vec![
1034 (preceding_pipe_span.shrink_to_hi(), opening_suggestion_str),
1035 (following_token_span.shrink_to_lo(), closing_suggestion_str),
1036 ],
1037 Applicability::MaybeIncorrect,
1038 );
10391040expect_err.emit();
10411042Ok(())
1043 }
10441045/// Parses a sequence, not including the delimiters. The function
1046 /// `f` must consume tokens until reaching the next separator or
1047 /// closing bracket.
1048fn parse_seq_to_before_end<T>(
1049&mut self,
1050 close: ExpTokenPair,
1051 sep: SeqSep,
1052 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1053 ) -> PResult<'a, (ThinVec<T>, Trailing, Recovered)> {
1054self.parse_seq_to_before_tokens(&[close], &[], sep, f)
1055 }
10561057/// Parses a sequence, including only the closing delimiter. The function
1058 /// `f` must consume tokens until reaching the next separator or
1059 /// closing bracket.
1060fn parse_seq_to_end<T>(
1061&mut self,
1062 close: ExpTokenPair,
1063 sep: SeqSep,
1064 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1065 ) -> PResult<'a, (ThinVec<T>, Trailing)> {
1066let (val, trailing, recovered) = self.parse_seq_to_before_end(close, sep, f)?;
1067if #[allow(non_exhaustive_omitted_patterns)] match recovered {
Recovered::No => true,
_ => false,
}matches!(recovered, Recovered::No) && !self.eat(close) {
1068self.dcx().span_delayed_bug(
1069self.token.span,
1070"recovered but `parse_seq_to_before_end` did not give us the close token",
1071 );
1072 }
1073Ok((val, trailing))
1074 }
10751076/// Parses a sequence, including both delimiters. The function
1077 /// `f` must consume tokens until reaching the next separator or
1078 /// closing bracket.
1079fn parse_unspanned_seq<T>(
1080&mut self,
1081 open: ExpTokenPair,
1082 close: ExpTokenPair,
1083 sep: SeqSep,
1084 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1085 ) -> PResult<'a, (ThinVec<T>, Trailing)> {
1086self.expect(open)?;
1087self.parse_seq_to_end(close, sep, f)
1088 }
10891090/// Parses a comma-separated sequence, including both delimiters.
1091 /// The function `f` must consume tokens until reaching the next separator or
1092 /// closing bracket.
1093fn parse_delim_comma_seq<T>(
1094&mut self,
1095 open: ExpTokenPair,
1096 close: ExpTokenPair,
1097 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1098 ) -> PResult<'a, (ThinVec<T>, Trailing)> {
1099self.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)
1100 }
11011102/// Parses a comma-separated sequence delimited by parentheses (e.g. `(x, y)`).
1103 /// The function `f` must consume tokens until reaching the next separator or
1104 /// closing bracket.
1105pub fn parse_paren_comma_seq<T>(
1106&mut self,
1107 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1108 ) -> PResult<'a, (ThinVec<T>, Trailing)> {
1109self.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)
1110 }
11111112/// Advance the parser by one token using provided token as the next one.
1113fn bump_with(&mut self, next: (Token, Spacing)) {
1114self.inlined_bump_with(next)
1115 }
11161117/// This always-inlined version should only be used on hot code paths.
1118#[inline(always)]
1119fn inlined_bump_with(&mut self, (next_token, next_spacing): (Token, Spacing)) {
1120// Update the current and previous tokens.
1121self.prev_token = mem::replace(&mut self.token, next_token);
1122self.token_spacing = next_spacing;
11231124// Diagnostics.
1125self.expected_token_types.clear();
1126 }
11271128/// Advance the parser by one token.
1129pub fn bump(&mut self) {
1130// Note: destructuring here would give nicer code, but it was found in #96210 to be slower
1131 // than `.0`/`.1` access.
1132let mut next = self.token_cursor.inlined_next();
1133self.num_bump_calls += 1;
1134// We got a token from the underlying cursor and no longer need to
1135 // worry about an unglued token. See `break_and_eat` for more details.
1136self.break_last_token = 0;
1137if next.0.span.is_dummy() {
1138// Tweak the location for better diagnostics, but keep syntactic context intact.
1139let fallback_span = self.token.span;
1140next.0.span = fallback_span.with_ctxt(next.0.span.ctxt());
1141 }
1142if 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!(
1143 next.0.kind,
1144 token::OpenInvisible(origin) | token::CloseInvisible(origin) if origin.skip()
1145 ));
1146self.inlined_bump_with(next)
1147 }
11481149/// Look-ahead `dist` tokens of `self.token` and get access to that token there.
1150 /// When `dist == 0` then the current token is looked at. `Eof` will be
1151 /// returned if the look-ahead is any distance past the end of the tokens.
1152pub fn look_ahead<R>(&self, dist: usize, looker: impl FnOnce(&Token) -> R) -> R {
1153if dist == 0 {
1154return looker(&self.token);
1155 }
11561157// Typically around 98% of the `dist > 0` cases have `dist == 1`, so we
1158 // have a fast special case for that.
1159if dist == 1 {
1160// The index is zero because the tree cursor's index always points
1161 // to the next token to be gotten.
1162match self.token_cursor.curr.curr() {
1163Some(tree) => {
1164// Indexing stayed within the current token tree.
1165match tree {
1166 TokenTree::Token(token, _) => return looker(token),
1167&TokenTree::Delimited(dspan, _, delim, _) => {
1168if !delim.skip() {
1169return looker(&Token::new(delim.as_open_token_kind(), dspan.open));
1170 }
1171 }
1172 }
1173 }
1174None => {
1175// The tree cursor lookahead went (one) past the end of the
1176 // current token tree. Try to return a close delimiter.
1177if let Some(last) = self.token_cursor.stack.last()
1178 && let Some(&TokenTree::Delimited(span, _, delim, _)) = last.curr()
1179 && !delim.skip()
1180 {
1181// We are not in the outermost token stream, so we have
1182 // delimiters. Also, those delimiters are not skipped.
1183return looker(&Token::new(delim.as_close_token_kind(), span.close));
1184 }
1185 }
1186 }
1187 }
11881189// Just clone the token cursor and use `next`, skipping delimiters as
1190 // necessary. Slow but simple.
1191let mut cursor = self.token_cursor.clone();
1192let mut i = 0;
1193let mut token = Token::dummy();
1194while i < dist {
1195 token = cursor.next().0;
1196if let token::OpenInvisible(origin) | token::CloseInvisible(origin) = token.kind
1197 && origin.skip()
1198 {
1199continue;
1200 }
1201 i += 1;
1202 }
1203looker(&token)
1204 }
12051206/// Like `lookahead`, but skips over token trees rather than tokens. Useful
1207 /// when looking past possible metavariable pasting sites.
1208pub fn tree_look_ahead<R>(
1209&self,
1210 dist: usize,
1211 looker: impl FnOnce(&TokenTree) -> R,
1212 ) -> Option<R> {
1213match (&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);
1214self.token_cursor.curr.look_ahead(dist - 1).map(looker)
1215 }
12161217/// Returns whether any of the given keywords are `dist` tokens ahead of the current one.
1218pub(crate) fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool {
1219self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw)))
1220 }
12211222/// Parses asyncness: `async` or nothing.
1223fn parse_coroutine_kind(&mut self, case: Case) -> Option<CoroutineKind> {
1224let span = self.token_uninterpolated_span();
1225if 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) {
1226// FIXME(gen_blocks): Do we want to unconditionally parse `gen` and then
1227 // error if edition <= 2024, like we do with async and edition <= 2018?
1228if self.token_uninterpolated_span().at_least_rust_2024()
1229 && 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)
1230 {
1231let gen_span = self.prev_token_uninterpolated_span();
1232Some(CoroutineKind::AsyncGen {
1233 span: span.to(gen_span),
1234 closure_id: DUMMY_NODE_ID,
1235 return_impl_trait_id: DUMMY_NODE_ID,
1236 })
1237 } else {
1238Some(CoroutineKind::Async {
1239span,
1240 closure_id: DUMMY_NODE_ID,
1241 return_impl_trait_id: DUMMY_NODE_ID,
1242 })
1243 }
1244 } else if self.token_uninterpolated_span().at_least_rust_2024()
1245 && 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)
1246 {
1247Some(CoroutineKind::Gen {
1248span,
1249 closure_id: DUMMY_NODE_ID,
1250 return_impl_trait_id: DUMMY_NODE_ID,
1251 })
1252 } else {
1253None1254 }
1255 }
12561257/// Parses fn unsafety: `unsafe`, `safe` or nothing.
1258fn parse_safety(&mut self, case: Case) -> Safety {
1259if 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) {
1260 Safety::Unsafe(self.prev_token_uninterpolated_span())
1261 } 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) {
1262 Safety::Safe(self.prev_token_uninterpolated_span())
1263 } else {
1264 Safety::Default1265 }
1266 }
12671268/// Parses constness: `const` or nothing.
1269fn parse_constness(&mut self, case: Case) -> Const {
1270self.parse_constness_(case, false)
1271 }
12721273/// Parses constness for closures (case sensitive, feature-gated)
1274fn parse_closure_constness(&mut self) -> Const {
1275let constness = self.parse_constness_(Case::Sensitive, true);
1276if let Const::Yes(span) = constness {
1277self.psess.gated_spans.gate(sym::const_closures, span);
1278 }
1279constness1280 }
12811282fn parse_constness_(&mut self, case: Case, is_closure: bool) -> Const {
1283// Avoid const blocks and const closures to be parsed as const items
1284if (self.check_const_closure() == is_closure)
1285 && !self.look_ahead(1, |t| *t == token::OpenBrace || t.is_metavar_block())
1286 && 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)
1287 {
1288 Const::Yes(self.prev_token_uninterpolated_span())
1289 } else {
1290 Const::No1291 }
1292 }
12931294fn parse_mgca_const_block(&mut self, gate_syntax: bool) -> PResult<'a, AnonConst> {
1295let kw_span = self.prev_token.span;
1296let value = self.parse_expr_block(None, kw_span, BlockCheckMode::Default)?;
1297if gate_syntax {
1298self.psess.gated_spans.gate(sym::min_generic_const_args, kw_span.to(value.span));
1299 }
1300Ok(AnonConst {
1301 id: ast::DUMMY_NODE_ID,
1302value,
1303 mgca_disambiguation: MgcaDisambiguation::AnonConst,
1304 })
1305 }
13061307/// Parses inline const expressions.
1308fn parse_const_block(&mut self, span: Span) -> PResult<'a, Box<Expr>> {
1309self.expect_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Const,
token_type: crate::parser::token_type::TokenType::KwConst,
}exp!(Const))?;
1310let (attrs, blk) = self.parse_inner_attrs_and_block(None)?;
1311let anon_const = AnonConst {
1312 id: DUMMY_NODE_ID,
1313 value: self.mk_expr(blk.span, ExprKind::Block(blk, None)),
1314 mgca_disambiguation: MgcaDisambiguation::AnonConst,
1315 };
1316let blk_span = anon_const.value.span;
1317let kind = ExprKind::ConstBlock(anon_const);
1318Ok(self.mk_expr_with_attrs(span.to(blk_span), kind, attrs))
1319 }
13201321/// Parses mutability (`mut` or nothing).
1322fn parse_mutability(&mut self) -> Mutability {
1323if 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 }
1324 }
13251326/// Parses reference binding mode (`ref`, `ref mut`, `ref pin const`, `ref pin mut`, or nothing).
1327fn parse_byref(&mut self) -> ByRef {
1328if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Ref,
token_type: crate::parser::token_type::TokenType::KwRef,
}exp!(Ref)) {
1329let (pinnedness, mutability) = self.parse_pin_and_mut();
1330 ByRef::Yes(pinnedness, mutability)
1331 } else {
1332 ByRef::No1333 }
1334 }
13351336/// Possibly parses mutability (`const` or `mut`).
1337fn parse_const_or_mut(&mut self) -> Option<Mutability> {
1338if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Mut,
token_type: crate::parser::token_type::TokenType::KwMut,
}exp!(Mut)) {
1339Some(Mutability::Mut)
1340 } 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)) {
1341Some(Mutability::Not)
1342 } else {
1343None1344 }
1345 }
13461347fn parse_field_name(&mut self) -> PResult<'a, Ident> {
1348if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = self.token.kind
1349 {
1350if let Some(suffix) = suffix {
1351self.dcx().emit_err(errors::InvalidLiteralSuffixOnTupleIndex {
1352 span: self.token.span,
1353suffix,
1354 });
1355 }
1356self.bump();
1357Ok(Ident::new(symbol, self.prev_token.span))
1358 } else {
1359self.parse_ident_common(true)
1360 }
1361 }
13621363fn parse_delim_args(&mut self) -> PResult<'a, Box<DelimArgs>> {
1364if let Some(args) = self.parse_delim_args_inner() {
1365Ok(Box::new(args))
1366 } else {
1367self.unexpected_any()
1368 }
1369 }
13701371fn parse_attr_args(&mut self) -> PResult<'a, AttrArgs> {
1372Ok(if let Some(args) = self.parse_delim_args_inner() {
1373 AttrArgs::Delimited(args)
1374 } else if self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Eq,
token_type: crate::parser::token_type::TokenType::Eq,
}exp!(Eq)) {
1375let eq_span = self.prev_token.span;
1376let expr = self.parse_expr_force_collect()?;
1377 AttrArgs::Eq { eq_span, expr }
1378 } else {
1379 AttrArgs::Empty1380 })
1381 }
13821383fn parse_delim_args_inner(&mut self) -> Option<DelimArgs> {
1384let delimited = self.check(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::OpenParen,
token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen))
1385 || self.check(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::OpenBracket,
token_type: crate::parser::token_type::TokenType::OpenBracket,
}exp!(OpenBracket))
1386 || self.check(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::OpenBrace,
token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace));
13871388delimited.then(|| {
1389let TokenTree::Delimited(dspan, _, delim, tokens) = self.parse_token_tree() else {
1390::core::panicking::panic("internal error: entered unreachable code")unreachable!()1391 };
1392DelimArgs { dspan, delim, tokens }
1393 })
1394 }
13951396/// Parses a single token tree from the input.
1397pub fn parse_token_tree(&mut self) -> TokenTree {
1398if self.token.kind.open_delim().is_some() {
1399// Clone the `TokenTree::Delimited` that we are currently
1400 // within. That's what we are going to return.
1401let tree = self.token_cursor.stack.last().unwrap().curr().unwrap().clone();
1402if 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(..));
14031404// Advance the token cursor through the entire delimited
1405 // sequence. After getting the `OpenDelim` we are *within* the
1406 // delimited sequence, i.e. at depth `d`. After getting the
1407 // matching `CloseDelim` we are *after* the delimited sequence,
1408 // i.e. at depth `d - 1`.
1409let target_depth = self.token_cursor.stack.len() - 1;
14101411if let Capturing::No = self.capture_state.capturing {
1412// We are not capturing tokens, so skip to the end of the
1413 // delimited sequence. This is a perf win when dealing with
1414 // declarative macros that pass large `tt` fragments through
1415 // multiple rules, as seen in the uom-0.37.0 crate.
1416self.token_cursor.curr.bump_to_end();
1417self.bump();
1418if 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);
1419 } else {
1420loop {
1421// Advance one token at a time, so `TokenCursor::next()`
1422 // can capture these tokens if necessary.
1423self.bump();
1424if self.token_cursor.stack.len() == target_depth {
1425break;
1426 }
1427 }
1428 }
1429if 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());
14301431// Consume close delimiter
1432self.bump();
1433tree1434 } else {
1435if !!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());
1436let prev_spacing = self.token_spacing;
1437self.bump();
1438 TokenTree::Token(self.prev_token, prev_spacing)
1439 }
1440 }
14411442pub fn parse_tokens(&mut self) -> TokenStream {
1443let mut result = Vec::new();
1444loop {
1445if self.token.kind.is_close_delim_or_eof() {
1446break;
1447 } else {
1448result.push(self.parse_token_tree());
1449 }
1450 }
1451TokenStream::new(result)
1452 }
14531454/// Evaluates the closure with restrictions in place.
1455 ///
1456 /// Afters the closure is evaluated, restrictions are reset.
1457fn with_res<T>(&mut self, res: Restrictions, f: impl FnOnce(&mut Self) -> T) -> T {
1458let old = self.restrictions;
1459self.restrictions = res;
1460let res = f(self);
1461self.restrictions = old;
1462res1463 }
14641465/// Parses `pub` and `pub(in path)` plus shortcuts `pub(crate)` for `pub(in crate)`, `pub(self)`
1466 /// for `pub(in self)` and `pub(super)` for `pub(in super)`.
1467 /// If the following element can't be a tuple (i.e., it's a function definition), then
1468 /// it's not a tuple struct field), and the contents within the parentheses aren't valid,
1469 /// so emit a proper diagnostic.
1470// Public for rustfmt usage.
1471pub fn parse_visibility(&mut self, fbt: FollowedByType) -> PResult<'a, Visibility> {
1472if let Some(vis) = self1473 .eat_metavar_seq(MetaVarKind::Vis, |this| this.parse_visibility(FollowedByType::Yes))
1474 {
1475return Ok(vis);
1476 }
14771478if !self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Pub,
token_type: crate::parser::token_type::TokenType::KwPub,
}exp!(Pub)) {
1479// We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
1480 // keyword to grab a span from for inherited visibility; an empty span at the
1481 // beginning of the current token would seem to be the "Schelling span".
1482return Ok(Visibility {
1483 span: self.token.span.shrink_to_lo(),
1484 kind: VisibilityKind::Inherited,
1485 tokens: None,
1486 });
1487 }
1488let lo = self.prev_token.span;
14891490if self.check(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::OpenParen,
token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen)) {
1491// We don't `self.bump()` the `(` yet because this might be a struct definition where
1492 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
1493 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
1494 // by the following tokens.
1495if self.is_keyword_ahead(1, &[kw::In]) {
1496// Parse `pub(in path)`.
1497self.bump(); // `(`
1498self.bump(); // `in`
1499let path = self.parse_path(PathStyle::Mod)?; // `path`
1500self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::CloseParen,
token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen))?; // `)`
1501let vis = VisibilityKind::Restricted {
1502 path: Box::new(path),
1503 id: ast::DUMMY_NODE_ID,
1504 shorthand: false,
1505 };
1506return Ok(Visibility {
1507 span: lo.to(self.prev_token.span),
1508 kind: vis,
1509 tokens: None,
1510 });
1511 } else if self.look_ahead(2, |t| t == &token::CloseParen)
1512 && self.is_keyword_ahead(1, &[kw::Crate, kw::Super, kw::SelfLower])
1513 {
1514// Parse `pub(crate)`, `pub(self)`, or `pub(super)`.
1515self.bump(); // `(`
1516let path = self.parse_path(PathStyle::Mod)?; // `crate`/`super`/`self`
1517self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::CloseParen,
token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen))?; // `)`
1518let vis = VisibilityKind::Restricted {
1519 path: Box::new(path),
1520 id: ast::DUMMY_NODE_ID,
1521 shorthand: true,
1522 };
1523return Ok(Visibility {
1524 span: lo.to(self.prev_token.span),
1525 kind: vis,
1526 tokens: None,
1527 });
1528 } else if let FollowedByType::No = fbt {
1529// Provide this diagnostic if a type cannot follow;
1530 // in particular, if this is not a tuple struct.
1531self.recover_incorrect_vis_restriction()?;
1532// Emit diagnostic, but continue with public visibility.
1533}
1534 }
15351536Ok(Visibility { span: lo, kind: VisibilityKind::Public, tokens: None })
1537 }
15381539/// Recovery for e.g. `pub(something) fn ...` or `struct X { pub(something) y: Z }`
1540fn recover_incorrect_vis_restriction(&mut self) -> PResult<'a, ()> {
1541self.bump(); // `(`
1542let path = self.parse_path(PathStyle::Mod)?;
1543self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::CloseParen,
token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen))?; // `)`
15441545let path_str = pprust::path_to_string(&path);
1546self.dcx()
1547 .emit_err(IncorrectVisibilityRestriction { span: path.span, inner_str: path_str });
15481549Ok(())
1550 }
15511552/// Parses `extern string_literal?`.
1553fn parse_extern(&mut self, case: Case) -> Extern {
1554if 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) {
1555let mut extern_span = self.prev_token.span;
1556let abi = self.parse_abi();
1557if let Some(abi) = abi {
1558extern_span = extern_span.to(abi.span);
1559 }
1560Extern::from_abi(abi, extern_span)
1561 } else {
1562 Extern::None1563 }
1564 }
15651566/// Parses a string literal as an ABI spec.
1567fn parse_abi(&mut self) -> Option<StrLit> {
1568match self.parse_str_lit() {
1569Ok(str_lit) => Some(str_lit),
1570Err(Some(lit)) => match lit.kind {
1571 ast::LitKind::Err(_) => None,
1572_ => {
1573self.dcx().emit_err(NonStringAbiLiteral { span: lit.span });
1574None1575 }
1576 },
1577Err(None) => None,
1578 }
1579 }
15801581fn collect_tokens_no_attrs<R: HasAttrs + HasTokens>(
1582&mut self,
1583 f: impl FnOnce(&mut Self) -> PResult<'a, R>,
1584 ) -> PResult<'a, R> {
1585// The only reason to call `collect_tokens_no_attrs` is if you want tokens, so use
1586 // `ForceCollect::Yes`
1587self.collect_tokens(None, AttrWrapper::empty(), ForceCollect::Yes, |this, _attrs| {
1588Ok((f(this)?, Trailing::No, UsePreAttrPos::No))
1589 })
1590 }
15911592/// Checks for `::` or, potentially, `:::` and then look ahead after it.
1593fn check_path_sep_and_look_ahead(&mut self, looker: impl Fn(&Token) -> bool) -> bool {
1594if self.check(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::PathSep,
token_type: crate::parser::token_type::TokenType::PathSep,
}exp!(PathSep)) {
1595if self.may_recover() && self.look_ahead(1, |t| t.kind == token::Colon) {
1596if 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");
1597self.look_ahead(2, looker)
1598 } else {
1599self.look_ahead(1, looker)
1600 }
1601 } else {
1602false
1603}
1604 }
16051606/// `::{` or `::*`
1607fn is_import_coupler(&mut self) -> bool {
1608self.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))
1609 }
16101611// Debug view of the parser's token stream, up to `{lookahead}` tokens.
1612 // Only used when debugging.
1613#[allow(unused)]
1614pub(crate) fn debug_lookahead(&self, lookahead: usize) -> impl fmt::Debug {
1615 fmt::from_fn(move |f| {
1616let mut dbg_fmt = f.debug_struct("Parser"); // or at least, one view of
16171618 // we don't need N spans, but we want at least one, so print all of prev_token
1619dbg_fmt.field("prev_token", &self.prev_token);
1620let mut tokens = ::alloc::vec::Vec::new()vec![];
1621for i in 0..lookahead {
1622let tok = self.look_ahead(i, |tok| tok.kind);
1623let is_eof = tok == TokenKind::Eof;
1624 tokens.push(tok);
1625if is_eof {
1626// Don't look ahead past EOF.
1627break;
1628 }
1629 }
1630dbg_fmt.field_with("tokens", |field| field.debug_list().entries(tokens).finish());
1631dbg_fmt.field("approx_token_stream_pos", &self.num_bump_calls);
16321633// some fields are interesting for certain values, as they relate to macro parsing
1634if let Some(subparser) = self.subparser_name {
1635dbg_fmt.field("subparser_name", &subparser);
1636 }
1637if let Recovery::Forbidden = self.recovery {
1638dbg_fmt.field("recovery", &self.recovery);
1639 }
16401641// imply there's "more to know" than this view
1642dbg_fmt.finish_non_exhaustive()
1643 })
1644 }
16451646pub fn clear_expected_token_types(&mut self) {
1647self.expected_token_types.clear();
1648 }
16491650pub fn approx_token_stream_pos(&self) -> u32 {
1651self.num_bump_calls
1652 }
16531654/// For interpolated `self.token`, returns a span of the fragment to which
1655 /// the interpolated token refers. For all other tokens this is just a
1656 /// regular span. It is particularly important to use this for identifiers
1657 /// and lifetimes for which spans affect name resolution and edition
1658 /// checks. Note that keywords are also identifiers, so they should use
1659 /// this if they keep spans or perform edition checks.
1660pub fn token_uninterpolated_span(&self) -> Span {
1661match &self.token.kind {
1662 token::NtIdent(ident, _) | token::NtLifetime(ident, _) => ident.span,
1663 token::OpenInvisible(InvisibleOrigin::MetaVar(_)) => self.look_ahead(1, |t| t.span),
1664_ => self.token.span,
1665 }
1666 }
16671668/// Like `token_uninterpolated_span`, but works on `self.prev_token`.
1669pub fn prev_token_uninterpolated_span(&self) -> Span {
1670match &self.prev_token.kind {
1671 token::NtIdent(ident, _) | token::NtLifetime(ident, _) => ident.span,
1672 token::OpenInvisible(InvisibleOrigin::MetaVar(_)) => self.look_ahead(0, |t| t.span),
1673_ => self.prev_token.span,
1674 }
1675 }
1676}
16771678// Metavar captures of various kinds.
1679#[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)]
1680pub enum ParseNtResult {
1681 Tt(TokenTree),
1682 Ident(Ident, IdentIsRaw),
1683 Lifetime(Ident, IdentIsRaw),
1684 Item(Box<ast::Item>),
1685 Block(Box<ast::Block>),
1686 Stmt(Box<ast::Stmt>),
1687 Pat(Box<ast::Pat>, NtPatKind),
1688 Expr(Box<ast::Expr>, NtExprKind),
1689 Literal(Box<ast::Expr>),
1690 Ty(Box<ast::Ty>),
1691 Meta(Box<ast::AttrItem>),
1692 Path(Box<ast::Path>),
1693 Vis(Box<ast::Visibility>),
1694}