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::{debug_assert_matches, fmt, mem, slice};
2021use attr_wrapper::{AttrWrapper, UsePreAttrPos};
22pub use diagnostics::AttemptLocalParseRecovery;
23// Public to use it for custom `if` expressions in rustfmt forks like https://github.com/tucant/rustfmt
24pub use expr::LetChainsPolicy;
25pub(crate) use item::{FnContext, FnParseMode};
26pub use pat::{CommaRecoveryMode, RecoverColon, RecoverComma};
27pub use path::PathStyle;
28use rustc_ast::token::{
29self, IdentIsRaw, InvisibleOrigin, MetaVarKind, NtExprKind, NtPatKind, Token, TokenKind,
30};
31use rustc_ast::tokenstream::{
32ParserRange, ParserReplacement, Spacing, TokenCursor, TokenStream, TokenTree, WithTokens,
33};
34use rustc_ast::util::case::Case;
35use rustc_ast::util::classify;
36use rustc_ast::{
37selfas ast, AnonConst, AttrArgs, AttrId, BinOpKind, ByRef, Const, CoroutineKind,
38DUMMY_NODE_ID, DelimArgs, Expr, ExprKind, Extern, HasTokens, ImplRestriction, MutRestriction,
39Mutability, Recovered, RestrictionKind, Safety, StrLit, Visibility, VisibilityKind,
40};
41use rustc_ast_pretty::pprust;
42use rustc_data_structures::fx::FxHashMap;
43use rustc_errors::{Applicability, Diag, FatalError, MultiSpan, PResult};
44use rustc_index::interval::IntervalSet;
45use rustc_session::parse::ParseSess;
46use rustc_span::{ErrorGuaranteed, Ident, Span, Symbol, kw, sym};
47use thin_vec::ThinVec;
48use token_type::TokenTypeSet;
49pub use token_type::{ExpKeywordPair, ExpTokenPair, TokenType};
50use tracing::debug;
5152use crate::diagnostics::{
53IncorrectImplRestriction, IncorrectMutRestriction, IncorrectVisibilityRestriction,
54NonStringAbiLiteral, TokenDescription,
55};
56use crate::exp;
5758#[cfg(test)]
59mod tests;
6061// Ideally, these tests would be in `rustc_ast`. But they depend on having a
62// parser, so they are here.
63#[cfg(test)]
64mod tokenstream {
65mod tests;
66}
6768bitflags::bitflags! {
69/// Restrictions applied while parsing.
70 ///
71 /// The parser maintains a bitset of restrictions it will honor while
72 /// parsing. This is essentially used as a way of tracking state of what
73 /// is being parsed and to change behavior based on that.
74#[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_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<u8>;
}
}
#[automatically_derived]
impl ::core::cmp::PartialOrd for InternalBitFlags {
#[inline]
fn partial_cmp(&self, other: &InternalBitFlags)
-> ::core::option::Option<::core::cmp::Ordering> {
::core::option::Option::Some(::core::cmp::Ord::cmp(self,
other))
}
}
#[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)]
75struct Restrictions: u8 {
76/// Restricts expressions for use in statement position.
77 ///
78 /// When expressions are used in various places, like statements or
79 /// match arms, this is used to stop parsing once certain tokens are
80 /// reached.
81 ///
82 /// For example, `if true {} & 1` with `STMT_EXPR` in effect is parsed
83 /// as two separate expression statements (`if` and a reference to 1).
84 /// Otherwise it is parsed as a bitwise AND where `if` is on the left
85 /// and 1 is on the right.
86const STMT_EXPR = 1 << 0;
87/// Do not allow struct literals.
88 ///
89 /// There are several places in the grammar where we don't want to
90 /// allow struct literals because they can require lookahead, or
91 /// otherwise could be ambiguous or cause confusion. For example,
92 /// `if Foo {} {}` isn't clear if it is `Foo{}` struct literal, or
93 /// just `Foo` is the condition, followed by a consequent block,
94 /// followed by an empty block.
95 ///
96 /// See [RFC 92](https://rust-lang.github.io/rfcs/0092-struct-grammar.html).
97const NO_STRUCT_LITERAL = 1 << 1;
98/// Used to provide better error messages for const generic arguments.
99 ///
100 /// An un-braced const generic argument is limited to a very small
101 /// subset of expressions. This is used to detect the situation where
102 /// an expression outside of that subset is used, and to suggest to
103 /// wrap the expression in braces.
104const CONST_EXPR = 1 << 2;
105/// Allows `let` expressions.
106 ///
107 /// `let pattern = scrutinee` is parsed as an expression, but it is
108 /// only allowed in let chains (`if` and `while` conditions).
109 /// Otherwise it is not an expression (note that `let` in statement
110 /// positions is treated as a `StmtKind::Let` statement, which has a
111 /// slightly different grammar).
112const ALLOW_LET = 1 << 3;
113/// Used to detect a missing `=>` in a match guard.
114 ///
115 /// This is used for error handling in a match guard to give a better
116 /// error message if the `=>` is missing. It is set when parsing the
117 /// guard expression.
118const IN_IF_GUARD = 1 << 4;
119/// Used to detect the incorrect use of expressions in patterns.
120 ///
121 /// This is used for error handling while parsing a pattern. During
122 /// error recovery, this will be set to try to parse the pattern as an
123 /// expression, but halts parsing the expression when reaching certain
124 /// tokens like `=`.
125const IS_PAT = 1 << 5;
126 }
127}
128129#[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)]
130enum SemiColonMode {
131 Break,
132 Ignore,
133 Comma,
134}
135136#[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)]
137enum BlockMode {
138 Break,
139 Ignore,
140}
141142/// Whether or not we should force collection of tokens for an AST node,
143/// regardless of whether or not it has attributes
144#[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)]
145pub enum ForceCollect {
146 Yes,
147 No,
148}
149150/// Whether to accept `const { ... }` as a shorthand for `const _: () = const { ... }`.
151#[derive(#[automatically_derived]
impl ::core::clone::Clone for AllowConstBlockItems {
#[inline]
fn clone(&self) -> AllowConstBlockItems { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for AllowConstBlockItems { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for AllowConstBlockItems {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
AllowConstBlockItems::Yes => "Yes",
AllowConstBlockItems::No => "No",
AllowConstBlockItems::DoesNotMatter => "DoesNotMatter",
})
}
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for AllowConstBlockItems {
#[inline]
fn eq(&self, other: &AllowConstBlockItems) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for AllowConstBlockItems {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {}
}Eq)]
152pub enum AllowConstBlockItems {
153 Yes,
154 No,
155 DoesNotMatter,
156}
157158/// If the next tokens are ill-formed `$ty::` recover them as `<$ty>::`.
159#[macro_export]
160macro_rules!maybe_recover_from_interpolated_ty_qpath {
161 ($self: expr, $allow_qpath_recovery: expr) => {
162if $allow_qpath_recovery
163&& $self.may_recover()
164 && let Some(mv_kind) = $self.token.is_metavar_seq()
165 && let token::MetaVarKind::Ty { .. } = mv_kind
166 && $self.check_noexpect_past_close_delim(&token::PathSep)
167 {
168// Reparse the type, then move to recovery.
169let ty = $self
170.eat_metavar_seq(mv_kind, |this| this.parse_ty_no_question_mark_recover())
171 .expect("metavar seq ty");
172173return $self.maybe_recover_from_bad_qpath_stage_2($self.prev_token.span, ty);
174 }
175 };
176}
177178#[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)]
179pub enum Recovery {
180 Allowed,
181 Forbidden,
182}
183184#[derive(#[automatically_derived]
impl<'a> ::core::clone::Clone for Parser<'a> {
#[inline]
fn clone(&self) -> Parser<'a> {
Parser {
psess: ::core::clone::Clone::clone(&self.psess),
token: ::core::clone::Clone::clone(&self.token),
token_spacing: ::core::clone::Clone::clone(&self.token_spacing),
prev_token: ::core::clone::Clone::clone(&self.prev_token),
capture_cfg: ::core::clone::Clone::clone(&self.capture_cfg),
restrictions: ::core::clone::Clone::clone(&self.restrictions),
expected_token_types: ::core::clone::Clone::clone(&self.expected_token_types),
token_cursor: ::core::clone::Clone::clone(&self.token_cursor),
num_bump_calls: ::core::clone::Clone::clone(&self.num_bump_calls),
break_last_token: ::core::clone::Clone::clone(&self.break_last_token),
unmatched_angle_bracket_count: ::core::clone::Clone::clone(&self.unmatched_angle_bracket_count),
angle_bracket_nesting: ::core::clone::Clone::clone(&self.angle_bracket_nesting),
parsing_generics: ::core::clone::Clone::clone(&self.parsing_generics),
last_unexpected_token_span: ::core::clone::Clone::clone(&self.last_unexpected_token_span),
subparser_name: ::core::clone::Clone::clone(&self.subparser_name),
capture_state: ::core::clone::Clone::clone(&self.capture_state),
current_closure: ::core::clone::Clone::clone(&self.current_closure),
recovery: ::core::clone::Clone::clone(&self.recovery),
in_fn_body: ::core::clone::Clone::clone(&self.in_fn_body),
fn_body_missing_semi_guar: ::core::clone::Clone::clone(&self.fn_body_missing_semi_guar),
}
}
}Clone)]
185pub struct Parser<'a> {
186pub psess: &'a ParseSess,
187/// The current token.
188pub token: Token = Token::dummy(),
189/// The spacing for the current token.
190token_spacing: Spacing = Spacing::Alone,
191/// The previous token.
192pub prev_token: Token = Token::dummy(),
193pub capture_cfg: bool = false,
194 restrictions: Restrictions = Restrictions::empty(),
195 expected_token_types: TokenTypeSet = TokenTypeSet::new(),
196 token_cursor: TokenCursor,
197// The number of calls to `bump`, i.e. the position in the token stream.
198num_bump_calls: u32 = 0,
199// During parsing we may sometimes need to "unglue" a glued token into two
200 // or three component tokens (e.g. `>>` into `>` and `>`, or `>>=` into `>`
201 // and `>` and `=`), so the parser can consume them one at a time. This
202 // process bypasses the normal capturing mechanism (e.g. `num_bump_calls`
203 // will not be incremented), since the "unglued" tokens due not exist in
204 // the original `TokenStream`.
205 //
206 // If we end up consuming all the component tokens, this is not an issue,
207 // because we'll end up capturing the single "glued" token.
208 //
209 // However, sometimes we may want to capture not all of the original
210 // token. For example, capturing the `Vec<u8>` in `Option<Vec<u8>>`
211 // requires us to unglue the trailing `>>` token. The `break_last_token`
212 // field is used to track these tokens. They get appended to the captured
213 // stream when we evaluate a `LazyAttrTokenStream`.
214 //
215 // This value is always 0, 1, or 2. It can only reach 2 when splitting
216 // `>>=` or `<<=`.
217break_last_token: u32 = 0,
218/// This field is used to keep track of how many left angle brackets we have seen. This is
219 /// required in order to detect extra leading left angle brackets (`<` characters) and error
220 /// appropriately.
221 ///
222 /// See the comments in the `parse_path_segment` function for more details.
223unmatched_angle_bracket_count: u16 = 0,
224 angle_bracket_nesting: u16 = 0,
225/// Keep track of when we're within `<...>` for proper error recovery.
226parsing_generics: bool = false,
227228 last_unexpected_token_span: Option<Span> = None,
229/// If present, this `Parser` is not parsing Rust code but rather a macro call.
230subparser_name: Option<&'static str>,
231 capture_state: CaptureState,
232/// This allows us to recover when the user forget to add braces around
233 /// multiple statements in the closure body.
234current_closure: Option<ClosureSpans> = None,
235/// Whether the parser is allowed to do recovery.
236 /// This is disabled when parsing macro arguments, see #103534
237recovery: Recovery = Recovery::Allowed,
238/// Whether we're parsing a function body.
239in_fn_body: bool = false,
240/// Whether we have detected a missing semicolon in function body.
241pub fn_body_missing_semi_guar: Option<ErrorGuaranteed> = None,
242}
243244// This type is used a lot, e.g. it's cloned when matching many declarative macro rules with
245// nonterminals. Make sure it doesn't unintentionally get bigger. We only check a few arches
246// though, because `TokenTypeSet(u128)` alignment varies on others, changing the total size.
247#[cfg(all(target_pointer_width = "64", any(target_arch = "aarch64", target_arch = "x86_64")))]
248const _: [(); 288] = [(); ::std::mem::size_of::<Parser<'_>>()];rustc_data_structures::static_assert_size!(Parser<'_>, 288);
249250/// Stores span information about a closure.
251#[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)]
252struct ClosureSpans {
253 whole_closure: Span,
254 closing_pipe: Span,
255 body: Span,
256}
257258/// Controls how we capture tokens. Capturing can be expensive,
259/// so we try to avoid performing capturing in cases where
260/// we will never need an `AttrTokenStream`.
261#[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)]
262enum Capturing {
263/// We aren't performing any capturing - this is the default mode.
264No,
265/// We are capturing tokens
266Yes,
267}
268269// This state is used by `Parser::collect_tokens`.
270#[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)]
271struct CaptureState {
272 capturing: Capturing,
273 parser_replacements: Vec<ParserReplacement>,
274 inner_attr_parser_ranges: FxHashMap<AttrId, ParserRange>,
275// `IntervalSet` is good for perf because attrs are mostly added to this
276 // set in contiguous ranges.
277seen_attrs: IntervalSet<AttrId>,
278}
279280/// A sequence separator.
281#[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)]
282struct SeqSep {
283/// The separator token.
284sep: Option<ExpTokenPair>,
285/// `true` if a trailing separator is allowed.
286trailing_sep_allowed: bool,
287}
288289impl SeqSep {
290fn trailing_allowed(sep: ExpTokenPair) -> SeqSep {
291SeqSep { sep: Some(sep), trailing_sep_allowed: true }
292 }
293294fn none() -> SeqSep {
295SeqSep { sep: None, trailing_sep_allowed: false }
296 }
297}
298299/// Whether parsing `impl` or `mut` restrictions.
300#[derive(#[automatically_derived]
impl ::core::clone::Clone for ParsingRestrictionKind {
#[inline]
fn clone(&self) -> ParsingRestrictionKind { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for ParsingRestrictionKind { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for ParsingRestrictionKind {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
ParsingRestrictionKind::Impl => "Impl",
ParsingRestrictionKind::Mut => "Mut",
})
}
}Debug)]
301enum ParsingRestrictionKind {
302 Impl,
303 Mut,
304}
305306#[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)]
307pub enum FollowedByType {
308 Yes,
309 No,
310}
311312#[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)]
313pub enum Trailing {
314 No,
315 Yes,
316}
317318impl From<bool> for Trailing {
319fn from(b: bool) -> Trailing {
320if b { Trailing::Yes } else { Trailing::No }
321 }
322}
323324pub fn token_descr(token: &Token) -> String {
325let s = pprust::token_to_string(token).to_string();
326327match (TokenDescription::from_token(token), &token.kind) {
328 (Some(TokenDescription::ReservedIdentifier), _) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("reserved identifier `{0}`", s))
})format!("reserved identifier `{s}`"),
329 (Some(TokenDescription::Keyword), _) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("keyword `{0}`", s))
})format!("keyword `{s}`"),
330 (Some(TokenDescription::ReservedKeyword), _) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("reserved keyword `{0}`", s))
})format!("reserved keyword `{s}`"),
331 (Some(TokenDescription::DocComment), _) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("doc comment `{0}`", s))
})format!("doc comment `{s}`"),
332// Deliberately doesn't print `s`, which is empty.
333 (Some(TokenDescription::MetaVar(kind)), _) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` metavariable", kind))
})format!("`{kind}` metavariable"),
334 (None, TokenKind::NtIdent(..)) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("identifier `{0}`", s))
})format!("identifier `{s}`"),
335 (None, TokenKind::NtLifetime(..)) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("lifetime `{0}`", s))
})format!("lifetime `{s}`"),
336 (None, _) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", s))
})format!("`{s}`"),
337 }
338}
339340impl<'a> Parser<'a> {
341pub fn new(
342 psess: &'a ParseSess,
343 stream: TokenStream,
344 subparser_name: Option<&'static str>,
345 ) -> Self {
346let mut parser = Parser {
347psess,
348 token_cursor: TokenCursor::new(stream),
349subparser_name,
350 capture_state: CaptureState {
351 capturing: Capturing::No,
352 parser_replacements: Vec::new(),
353 inner_attr_parser_ranges: Default::default(),
354 seen_attrs: IntervalSet::new(u32::MAXas usize),
355 },
356 ..
357 };
358359// Make parser point to the first token.
360parser.bump();
361362// Change this from 1 back to 0 after the bump. This eases debugging of
363 // `Parser::collect_tokens` because 0-indexed token positions are nicer
364 // than 1-indexed token positions.
365parser.num_bump_calls = 0;
366367parser368 }
369370#[inline]
371pub fn recovery(mut self, recovery: Recovery) -> Self {
372self.recovery = recovery;
373self374 }
375376#[inline]
377fn with_recovery<T>(&mut self, recovery: Recovery, f: impl FnOnce(&mut Self) -> T) -> T {
378let old = mem::replace(&mut self.recovery, recovery);
379let res = f(self);
380self.recovery = old;
381res382 }
383384/// Whether the parser is allowed to recover from broken code.
385 ///
386 /// If this returns false, recovering broken code into valid code (especially if this recovery does lookahead)
387 /// is not allowed. All recovery done by the parser must be gated behind this check.
388 ///
389 /// Technically, this only needs to restrict eager recovery by doing lookahead at more tokens.
390 /// But making the distinction is very subtle, and simply forbidding all recovery is a lot simpler to uphold.
391#[inline]
392fn may_recover(&self) -> bool {
393#[allow(non_exhaustive_omitted_patterns)] match self.recovery {
Recovery::Allowed => true,
_ => false,
}matches!(self.recovery, Recovery::Allowed)394 }
395396/// Version of [`unexpected`](Parser::unexpected) that "returns" any type in the `Ok`
397 /// (both those functions never return "Ok", and so can lie like that in the type).
398pub fn unexpected_any<T>(&mut self) -> PResult<'a, T> {
399match self.expect_one_of(&[], &[]) {
400Err(e) => Err(e),
401// We can get `Ok(true)` from `recover_closing_delimiter`
402 // which is called in `expected_one_of_not_found`.
403Ok(_) => FatalError.raise(),
404 }
405 }
406407pub fn unexpected(&mut self) -> PResult<'a, ()> {
408self.unexpected_any()
409 }
410411/// Expects and consumes the token `t`. Signals an error if the next token is not `t`.
412pub fn expect(&mut self, exp: ExpTokenPair) -> PResult<'a, Recovered> {
413if self.expected_token_types.is_empty() {
414if self.token == exp.tok {
415self.bump();
416Ok(Recovered::No)
417 } else {
418Err(self.unexpected_err(&exp.tok))
419 }
420 } else {
421self.expect_one_of(slice::from_ref(&exp), &[])
422 }
423 }
424425/// Expect next token to be edible or inedible token. If edible,
426 /// then consume it; if inedible, then return without consuming
427 /// anything. Signal a fatal error if next token is unexpected.
428fn expect_one_of(
429&mut self,
430 edible: &[ExpTokenPair],
431 inedible: &[ExpTokenPair],
432 ) -> PResult<'a, Recovered> {
433if edible.iter().any(|exp| exp.tok == self.token.kind) {
434self.bump();
435Ok(Recovered::No)
436 } else if inedible.iter().any(|exp| exp.tok == self.token.kind) {
437// leave it in the input
438Ok(Recovered::No)
439 } else if self.token != token::Eof440 && self.last_unexpected_token_span == Some(self.token.span)
441 {
442FatalError.raise();
443 } else {
444self.expected_one_of_not_found(edible, inedible)
445 .map(|error_guaranteed| Recovered::Yes(error_guaranteed))
446 }
447 }
448449// Public for rustfmt usage.
450pub fn parse_ident(&mut self) -> PResult<'a, Ident> {
451self.parse_ident_common(self.may_recover())
452 }
453454pub(crate) fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, Ident> {
455let (ident, is_raw) = self.ident_or_err(recover)?;
456457if is_raw == IdentIsRaw::No && ident.is_reserved() {
458let err = self.expected_ident_found_err();
459if recover {
460err.emit();
461 } else {
462return Err(err);
463 }
464 }
465self.bump();
466Ok(ident)
467 }
468469fn ident_or_err(&mut self, recover: bool) -> PResult<'a, (Ident, IdentIsRaw)> {
470match self.token.ident() {
471Some(ident) => Ok(ident),
472None => self.expected_ident_found(recover),
473 }
474 }
475476/// Checks if the next token is `tok`, and returns `true` if so.
477 ///
478 /// This method will automatically add `tok` to `expected_token_types` if `tok` is not
479 /// encountered.
480#[inline]
481pub fn check(&mut self, exp: ExpTokenPair) -> bool {
482let is_present = self.token == exp.tok;
483if !is_present {
484self.expected_token_types.insert(exp.token_type);
485 }
486is_present487 }
488489#[inline]
490 #[must_use]
491fn check_noexpect(&self, tok: &TokenKind) -> bool {
492self.token == *tok493 }
494495// Check the first token after the delimiter that closes the current
496 // delimited sequence. (Panics if used in the outermost token stream, which
497 // has no delimiters.) It uses a clone of the relevant tree cursor to skip
498 // past the entire `TokenTree::Delimited` in a single step, avoiding the
499 // need for unbounded token lookahead.
500 //
501 // Primarily used when `self.token` matches `OpenInvisible(_))`, to look
502 // ahead through the current metavar expansion.
503fn check_noexpect_past_close_delim(&self, tok: &TokenKind) -> bool {
504#[allow(non_exhaustive_omitted_patterns)] match self.token_cursor.look_ahead_past_close_delim()
{
Some(TokenTree::Token(token::Token { kind, .. }, _)) if kind == tok =>
true,
_ => false,
}matches!(
505self.token_cursor.look_ahead_past_close_delim(),
506Some(TokenTree::Token(token::Token { kind, .. }, _)) if kind == tok
507 )508 }
509510/// Consumes a token 'tok' if it exists. Returns whether the given token was present.
511 ///
512 /// the main purpose of this function is to reduce the cluttering of the suggestions list
513 /// which using the normal eat method could introduce in some cases.
514#[inline]
515 #[must_use]
516fn eat_noexpect(&mut self, tok: &TokenKind) -> bool {
517let is_present = self.check_noexpect(tok);
518if is_present {
519self.bump()
520 }
521is_present522 }
523524/// Consumes a token 'tok' if it exists. Returns whether the given token was present.
525#[inline]
526 #[must_use]
527pub fn eat(&mut self, exp: ExpTokenPair) -> bool {
528let is_present = self.check(exp);
529if is_present {
530self.bump()
531 }
532is_present533 }
534535/// If the next token is the given keyword, returns `true` without eating it.
536 /// An expectation is also added for diagnostics purposes.
537#[inline]
538 #[must_use]
539fn check_keyword(&mut self, exp: ExpKeywordPair) -> bool {
540let is_keyword = self.token.is_keyword(exp.kw);
541if !is_keyword {
542self.expected_token_types.insert(exp.token_type);
543 }
544is_keyword545 }
546547#[inline]
548 #[must_use]
549fn check_keyword_case(&mut self, exp: ExpKeywordPair, case: Case) -> bool {
550if self.check_keyword(exp) {
551true
552} else if case == Case::Insensitive553 && let Some((ident, IdentIsRaw::No)) = self.token.ident()
554// Do an ASCII case-insensitive match, because all keywords are ASCII.
555&& ident.as_str().eq_ignore_ascii_case(exp.kw.as_str())
556 {
557true
558} else {
559false
560}
561 }
562563/// If the next token is the given keyword, eats it and returns `true`.
564 /// Otherwise, returns `false`. An expectation is also added for diagnostics purposes.
565// Public for rustc_builtin_macros and rustfmt usage.
566#[inline]
567 #[must_use]
568pub fn eat_keyword(&mut self, exp: ExpKeywordPair) -> bool {
569let is_keyword = self.check_keyword(exp);
570if is_keyword {
571self.bump();
572 }
573is_keyword574 }
575576/// Eats a keyword, optionally ignoring the case.
577 /// If the case differs (and is ignored) an error is issued.
578 /// This is useful for recovery.
579#[inline]
580 #[must_use]
581fn eat_keyword_case(&mut self, exp: ExpKeywordPair, case: Case) -> bool {
582if self.eat_keyword(exp) {
583true
584} else if case == Case::Insensitive585 && let Some((ident, IdentIsRaw::No)) = self.token.ident()
586// Do an ASCII case-insensitive match, because all keywords are ASCII.
587&& ident.as_str().eq_ignore_ascii_case(exp.kw.as_str())
588 {
589let kw = exp.kw.as_str();
590let is_upper = kw.chars().all(char::is_uppercase);
591let is_lower = kw.chars().all(char::is_lowercase);
592593let case = match (is_upper, is_lower) {
594 (true, true) => {
595{
::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")596 }
597 (true, false) => crate::diagnostics::Case::Upper,
598 (false, true) => crate::diagnostics::Case::Lower,
599 (false, false) => crate::diagnostics::Case::Mixed,
600 };
601602self.dcx().emit_err(crate::diagnostics::KwBadCase { span: ident.span, kw, case });
603self.bump();
604true
605} else {
606false
607}
608 }
609610/// If the next token is the given keyword, eats it and returns `true`.
611 /// Otherwise, returns `false`. No expectation is added.
612// Public for rustc_builtin_macros usage.
613#[inline]
614 #[must_use]
615pub fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool {
616let is_keyword = self.token.is_keyword(kw);
617if is_keyword {
618self.bump();
619 }
620is_keyword621 }
622623/// If the given word is not a keyword, signals an error.
624 /// If the next token is not the given word, signals an error.
625 /// Otherwise, eats it.
626pub fn expect_keyword(&mut self, exp: ExpKeywordPair) -> PResult<'a, ()> {
627if !self.eat_keyword(exp) { self.unexpected() } else { Ok(()) }
628 }
629630/// Consume a sequence produced by a metavar expansion, if present.
631pub fn eat_metavar_seq<T>(
632&mut self,
633 mv_kind: MetaVarKind,
634 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
635 ) -> Option<T> {
636self.eat_metavar_seq_with_matcher(|mvk| mvk == mv_kind, f)
637 }
638639/// A slightly more general form of `eat_metavar_seq`, for use with the
640 /// `MetaVarKind` variants that have parameters, where an exact match isn't
641 /// desired.
642fn eat_metavar_seq_with_matcher<T>(
643&mut self,
644 match_mv_kind: impl Fn(MetaVarKind) -> bool,
645mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
646 ) -> Option<T> {
647if let token::OpenInvisible(InvisibleOrigin::MetaVar(mv_kind)) = self.token.kind
648 && match_mv_kind(mv_kind)
649 {
650self.bump();
651652// Recovery is disabled when parsing macro arguments, so it must
653 // also be disabled when reparsing pasted macro arguments,
654 // otherwise we get inconsistent results (e.g. #137874).
655let res = self.with_recovery(Recovery::Forbidden, |this| f(this));
656657let res = match res {
658Ok(res) => res,
659Err(err) => {
660// This can occur in unusual error cases, e.g. #139445.
661err.delay_as_bug();
662return None;
663 }
664 };
665666if let token::CloseInvisible(InvisibleOrigin::MetaVar(mv_kind)) = self.token.kind
667 && match_mv_kind(mv_kind)
668 {
669self.bump();
670Some(res)
671 } else {
672// This can occur when invalid syntax is passed to a decl macro. E.g. see #139248,
673 // where the reparse attempt of an invalid expr consumed the trailing invisible
674 // delimiter.
675self.dcx()
676 .span_delayed_bug(self.token.span, "no close delim with reparsing {mv_kind:?}");
677None678 }
679 } else {
680None681 }
682 }
683684/// Is the given keyword `kw` followed by a non-reserved identifier?
685fn is_kw_followed_by_ident(&self, kw: Symbol) -> bool {
686self.token.is_keyword(kw) && self.look_ahead(1, |t| t.is_non_reserved_ident())
687 }
688689#[inline]
690fn check_or_expected(&mut self, ok: bool, token_type: TokenType) -> bool {
691if !ok {
692self.expected_token_types.insert(token_type);
693 }
694ok695 }
696697fn check_ident(&mut self) -> bool {
698self.check_or_expected(self.token.is_ident(), TokenType::Ident)
699 }
700701fn check_path(&mut self) -> bool {
702self.check_or_expected(self.token.is_path_start(), TokenType::Path)
703 }
704705fn check_type(&mut self) -> bool {
706self.check_or_expected(self.token.can_begin_type(), TokenType::Type)
707 }
708709fn check_const_arg(&mut self) -> bool {
710let is_mcg_arg = self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const);
711let is_mgca_arg = self.is_keyword_ahead(0, &[kw::Const])
712 && self.look_ahead(1, |t| *t == token::OpenBrace);
713is_mcg_arg || is_mgca_arg714 }
715716fn check_const_closure(&self) -> bool {
717self.is_keyword_ahead(0, &[kw::Const])
718 && self.look_ahead(1, |t| match &t.kind {
719// async closures do not work with const closures, so we do not parse that here.
720token::Ident(kw::Move | kw::Use | kw::Static, IdentIsRaw::No)
721 | token::OrOr722 | token::Or => true,
723_ => false,
724 })
725 }
726727fn check_inline_const(&self, dist: usize) -> bool {
728self.is_keyword_ahead(dist, &[kw::Const])
729 && self.look_ahead(dist + 1, |t| match &t.kind {
730 token::OpenBrace => true,
731 token::OpenInvisible(InvisibleOrigin::MetaVar(MetaVarKind::Block)) => true,
732_ => false,
733 })
734 }
735736/// Checks to see if the next token is either `+` or `+=`.
737 /// Otherwise returns `false`.
738#[inline]
739fn check_plus(&mut self) -> bool {
740self.check_or_expected(self.token.is_like_plus(), TokenType::Plus)
741 }
742743/// Eats the expected token if it's present possibly breaking
744 /// compound tokens like multi-character operators in process.
745 /// Returns `true` if the token was eaten.
746fn break_and_eat(&mut self, exp: ExpTokenPair) -> bool {
747if self.token == exp.tok {
748self.bump();
749return true;
750 }
751match self.token.kind.break_two_token_op(1) {
752Some((first, second)) if first == exp.tok => {
753let first_span = self.psess.source_map().start_point(self.token.span);
754let second_span = self.token.span.with_lo(first_span.hi());
755self.token = Token::new(first, first_span);
756// Keep track of this token - if we end token capturing now,
757 // we'll want to append this token to the captured stream.
758 //
759 // If we consume any additional tokens, then this token
760 // is not needed (we'll capture the entire 'glued' token),
761 // and `bump` will set this field to 0.
762self.break_last_token += 1;
763// Use the spacing of the glued token as the spacing of the
764 // unglued second token.
765self.bump_with((Token::new(second, second_span), self.token_spacing));
766true
767}
768_ => {
769self.expected_token_types.insert(exp.token_type);
770false
771}
772 }
773 }
774775/// Eats `+` possibly breaking tokens like `+=` in process.
776fn eat_plus(&mut self) -> bool {
777self.break_and_eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Plus,
token_type: crate::parser::token_type::TokenType::Plus,
}exp!(Plus))
778 }
779780/// Eats `&` possibly breaking tokens like `&&` in process.
781 /// Signals an error if `&` is not eaten.
782fn expect_and(&mut self) -> PResult<'a, ()> {
783if 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() }
784 }
785786/// Eats `|` possibly breaking tokens like `||` in process.
787 /// Signals an error if `|` was not eaten.
788fn expect_or(&mut self) -> PResult<'a, ()> {
789if 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() }
790 }
791792/// Eats `<` possibly breaking tokens like `<<` in process.
793fn eat_lt(&mut self) -> bool {
794let 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));
795if ate {
796// See doc comment for `unmatched_angle_bracket_count`.
797self.unmatched_angle_bracket_count += 1;
798{
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:798",
"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(798u32),
::tracing_core::__macro_support::Option::Some("rustc_parse::parser"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("eat_lt: (increment) count={0:?}",
self.unmatched_angle_bracket_count) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count);
799 }
800ate801 }
802803/// Eats `<` possibly breaking tokens like `<<` in process.
804 /// Signals an error if `<` was not eaten.
805fn expect_lt(&mut self) -> PResult<'a, ()> {
806if self.eat_lt() { Ok(()) } else { self.unexpected() }
807 }
808809/// Eats `>` possibly breaking tokens like `>>` in process.
810 /// Signals an error if `>` was not eaten.
811fn expect_gt(&mut self) -> PResult<'a, ()> {
812if self.break_and_eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Gt,
token_type: crate::parser::token_type::TokenType::Gt,
}exp!(Gt)) {
813// See doc comment for `unmatched_angle_bracket_count`.
814if self.unmatched_angle_bracket_count > 0 {
815self.unmatched_angle_bracket_count -= 1;
816{
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:816",
"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(816u32),
::tracing_core::__macro_support::Option::Some("rustc_parse::parser"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("expect_gt: (decrement) count={0:?}",
self.unmatched_angle_bracket_count) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count);
817 }
818Ok(())
819 } else {
820self.unexpected()
821 }
822 }
823824/// Checks if the next token is contained within `closes`, and returns `true` if so.
825fn expect_any_with_type(
826&mut self,
827 closes_expected: &[ExpTokenPair],
828 closes_not_expected: &[&TokenKind],
829 ) -> bool {
830closes_expected.iter().any(|&close| self.check(close))
831 || closes_not_expected.iter().any(|k| self.check_noexpect(k))
832 }
833834/// Parses a sequence until the specified delimiters. The function
835 /// `f` must consume tokens until reaching the next separator or
836 /// closing bracket.
837fn parse_seq_to_before_tokens<T>(
838&mut self,
839 closes_expected: &[ExpTokenPair],
840 closes_not_expected: &[&TokenKind],
841 sep: SeqSep,
842mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
843 ) -> PResult<'a, (ThinVec<T>, Trailing, Recovered)> {
844let mut first = true;
845let mut recovered = Recovered::No;
846let mut trailing = Trailing::No;
847let mut v = ThinVec::new();
848849while !self.expect_any_with_type(closes_expected, closes_not_expected) {
850if self.token.kind.is_close_delim_or_eof() {
851break;
852 }
853if let Some(exp) = sep.sep {
854if first {
855// no separator for the first element
856first = false;
857 } else {
858// check for separator
859match self.expect(exp) {
860Ok(Recovered::No) => {
861self.current_closure.take();
862 }
863Ok(Recovered::Yes(guar)) => {
864self.current_closure.take();
865 recovered = Recovered::Yes(guar);
866break;
867 }
868Err(mut expect_err) => {
869let sp = self.prev_token.span.shrink_to_hi();
870let token_str = pprust::token_kind_to_string(&exp.tok);
871872match self.current_closure.take() {
873Some(closure_spans) if self.token == TokenKind::Semi => {
874// Finding a semicolon instead of a comma
875 // after a closure body indicates that the
876 // closure body may be a block but the user
877 // forgot to put braces around its
878 // statements.
879880self.recover_missing_braces_around_closure_body(
881 closure_spans,
882 expect_err,
883 )?;
884885continue;
886 }
887888_ => {
889// Attempt to keep parsing if it was a similar separator.
890if exp.tok.similar_tokens().contains(&self.token.kind) {
891self.bump();
892 }
893 }
894 }
895896// If this was a missing `@` in a binding pattern
897 // bail with a suggestion
898 // https://github.com/rust-lang/rust/issues/72373
899if self.prev_token.is_ident() && self.token == token::DotDot {
900let 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!(
901"if you meant to bind the contents of the rest of the array \
902 pattern into `{}`, use `@`",
903 pprust::token_to_string(&self.prev_token)
904 );
905 expect_err
906 .with_span_suggestion_verbose(
907self.prev_token.span.shrink_to_hi().until(self.token.span),
908 msg,
909" @ ",
910 Applicability::MaybeIncorrect,
911 )
912 .emit();
913break;
914 }
915916// Attempt to keep parsing if it was an omitted separator.
917 // `&raw <expr>` already has a specific suggestion for missing
918 // `const`/`mut`, so don't recover `<expr>` as the next element in
919 // a comma-separated list.
920if exp.token_type == TokenType::Comma && self.is_expected_raw_ref_mut()
921 {
922return Err(expect_err);
923 }
924self.last_unexpected_token_span = None;
925match f(self) {
926Ok(t) => {
927// Parsed successfully, therefore most probably the code only
928 // misses a separator.
929expect_err
930 .with_span_suggestion_short(
931 sp,
932::alloc::__export::must_use({
::alloc::fmt::format(format_args!("missing `{0}`", token_str))
})format!("missing `{token_str}`"),
933 token_str,
934 Applicability::MaybeIncorrect,
935 )
936 .emit();
937938 v.push(t);
939continue;
940 }
941Err(e) => {
942// Parsing failed, therefore it must be something more serious
943 // than just a missing separator.
944for xx in &e.children {
945// Propagate the help message from sub error `e` to main
946 // error `expect_err`.
947expect_err.children.push(xx.clone());
948 }
949 e.cancel();
950if self.token == token::Colon {
951// We will try to recover in
952 // `maybe_recover_struct_lit_bad_delims`.
953return Err(expect_err);
954 } else if let [exp] = closes_expected
955 && exp.token_type == TokenType::CloseParen
956 {
957return Err(expect_err);
958 } else {
959 expect_err.emit();
960break;
961 }
962 }
963 }
964 }
965 }
966 }
967 }
968if sep.trailing_sep_allowed
969 && self.expect_any_with_type(closes_expected, closes_not_expected)
970 {
971 trailing = Trailing::Yes;
972break;
973 }
974975let t = f(self)?;
976 v.push(t);
977 }
978979Ok((v, trailing, recovered))
980 }
981982fn recover_missing_braces_around_closure_body(
983&mut self,
984 closure_spans: ClosureSpans,
985mut expect_err: Diag<'_>,
986 ) -> PResult<'a, ()> {
987let initial_semicolon = self.token.span;
988989while self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Semi,
token_type: crate::parser::token_type::TokenType::Semi,
}exp!(Semi)) {
990let _ = self
991.parse_stmt_without_recovery(false, ForceCollect::No, false)
992 .unwrap_or_else(|e| {
993 e.cancel();
994None
995});
996 }
997998expect_err999 .primary_message("closure bodies that contain statements must be surrounded by braces");
10001001let preceding_pipe_span = closure_spans.closing_pipe;
1002let following_token_span = self.token.span;
10031004let mut first_note = MultiSpan::from(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[initial_semicolon]))vec![initial_semicolon]);
1005first_note.push_span_label(
1006initial_semicolon,
1007"this `;` turns the preceding closure into a statement",
1008 );
1009first_note.push_span_label(
1010closure_spans.body,
1011"this expression is a statement because of the trailing semicolon",
1012 );
1013expect_err.span_note(first_note, "statement found outside of a block");
10141015let mut second_note = MultiSpan::from(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[closure_spans.whole_closure]))vec![closure_spans.whole_closure]);
1016second_note.push_span_label(closure_spans.whole_closure, "this is the parsed closure...");
1017second_note.push_span_label(
1018following_token_span,
1019"...but likely you meant the closure to end here",
1020 );
1021expect_err.span_note(second_note, "the closure body may be incorrectly delimited");
10221023expect_err.span(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[preceding_pipe_span, following_token_span]))vec![preceding_pipe_span, following_token_span]);
10241025let opening_suggestion_str = " {".to_string();
1026let closing_suggestion_str = "}".to_string();
10271028expect_err.multipart_suggestion(
1029"try adding braces",
1030::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(preceding_pipe_span.shrink_to_hi(), opening_suggestion_str),
(following_token_span.shrink_to_lo(),
closing_suggestion_str)]))vec![
1031 (preceding_pipe_span.shrink_to_hi(), opening_suggestion_str),
1032 (following_token_span.shrink_to_lo(), closing_suggestion_str),
1033 ],
1034 Applicability::MaybeIncorrect,
1035 );
10361037expect_err.emit();
10381039Ok(())
1040 }
10411042/// Parses a sequence, not including the delimiters. The function
1043 /// `f` must consume tokens until reaching the next separator or
1044 /// closing bracket.
1045fn parse_seq_to_before_end<T>(
1046&mut self,
1047 close: ExpTokenPair,
1048 sep: SeqSep,
1049 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1050 ) -> PResult<'a, (ThinVec<T>, Trailing, Recovered)> {
1051self.parse_seq_to_before_tokens(&[close], &[], sep, f)
1052 }
10531054/// Parses a sequence, including only the closing delimiter. The function
1055 /// `f` must consume tokens until reaching the next separator or
1056 /// closing bracket.
1057fn parse_seq_to_end<T>(
1058&mut self,
1059 close: ExpTokenPair,
1060 sep: SeqSep,
1061 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1062 ) -> PResult<'a, (ThinVec<T>, Trailing)> {
1063let (val, trailing, recovered) = self.parse_seq_to_before_end(close, sep, f)?;
1064if #[allow(non_exhaustive_omitted_patterns)] match recovered {
Recovered::No => true,
_ => false,
}matches!(recovered, Recovered::No) && !self.eat(close) {
1065self.dcx().span_delayed_bug(
1066self.token.span,
1067"recovered but `parse_seq_to_before_end` did not give us the close token",
1068 );
1069 }
1070Ok((val, trailing))
1071 }
10721073/// Parses a sequence, including both delimiters. The function
1074 /// `f` must consume tokens until reaching the next separator or
1075 /// closing bracket.
1076fn parse_unspanned_seq<T>(
1077&mut self,
1078 open: ExpTokenPair,
1079 close: ExpTokenPair,
1080 sep: SeqSep,
1081 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1082 ) -> PResult<'a, (ThinVec<T>, Trailing)> {
1083self.expect(open)?;
1084self.parse_seq_to_end(close, sep, f)
1085 }
10861087/// Parses a comma-separated sequence, including both delimiters.
1088 /// The function `f` must consume tokens until reaching the next separator or
1089 /// closing bracket.
1090pub fn parse_delim_comma_seq<T>(
1091&mut self,
1092 open: ExpTokenPair,
1093 close: ExpTokenPair,
1094 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1095 ) -> PResult<'a, (ThinVec<T>, Trailing)> {
1096self.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)
1097 }
10981099/// Parses a comma-separated sequence delimited by parentheses (e.g. `(x, y)`).
1100 /// The function `f` must consume tokens until reaching the next separator or
1101 /// closing bracket.
1102pub fn parse_paren_comma_seq<T>(
1103&mut self,
1104 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1105 ) -> PResult<'a, (ThinVec<T>, Trailing)> {
1106self.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)
1107 }
11081109/// Advance the parser by one token using provided token as the next one.
1110fn bump_with(&mut self, next: (Token, Spacing)) {
1111self.inlined_bump_with(next)
1112 }
11131114/// This always-inlined version should only be used on hot code paths.
1115#[inline(always)]
1116fn inlined_bump_with(&mut self, (next_token, next_spacing): (Token, Spacing)) {
1117// Update the current and previous tokens.
1118self.prev_token = mem::replace(&mut self.token, next_token);
1119self.token_spacing = next_spacing;
11201121// Diagnostics.
1122self.expected_token_types.clear();
1123 }
11241125/// Advance the parser by one token.
1126pub fn bump(&mut self) {
1127// Note: destructuring here would give nicer code, but it was found in #96210 to be slower
1128 // than `.0`/`.1` access.
1129let mut next = self.token_cursor.inlined_next();
1130self.num_bump_calls += 1;
1131// We got a token from the underlying cursor and no longer need to
1132 // worry about an unglued token. See `break_and_eat` for more details.
1133self.break_last_token = 0;
1134if next.0.span.is_dummy() {
1135// Tweak the location for better diagnostics, but keep syntactic context intact.
1136let fallback_span = self.token.span;
1137next.0.span = fallback_span.with_ctxt(next.0.span.ctxt());
1138 }
1139if 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!(
1140 next.0.kind,
1141 token::OpenInvisible(origin) | token::CloseInvisible(origin) if origin.skip()
1142 ));
1143self.inlined_bump_with(next)
1144 }
11451146/// Look-ahead `dist` tokens of `self.token` and get access to that token there.
1147 /// When `dist == 0` then the current token is looked at. `Eof` will be
1148 /// returned if the look-ahead is any distance past the end of the tokens.
1149pub fn look_ahead<R>(&self, dist: usize, looker: impl FnOnce(&Token) -> R) -> R {
1150if dist == 0 {
1151return looker(&self.token);
1152 }
11531154// Typically around 98% of the `dist > 0` cases have `dist == 1`, so we
1155 // have a fast special case for that.
1156if dist == 1 {
1157// `look_ahead(0)` returns the *next* token.
1158match self.token_cursor.look_ahead(0) {
1159Some(tree) => {
1160// Indexing stayed within the current token tree.
1161match tree {
1162 TokenTree::Token(token, _) => return looker(token),
1163&TokenTree::Delimited(dspan, _, delim, _) => {
1164if !delim.skip() {
1165return looker(&Token::new(delim.as_open_token_kind(), dspan.open));
1166 }
1167 }
1168 }
1169 }
1170None => {
1171// The tree cursor lookahead went (one) past the end of the
1172 // current token tree. Try to return a close delimiter.
1173if let Some((delim, span)) = self.token_cursor.parent_delim_and_span()
1174 && !delim.skip()
1175 {
1176// We are not in the outermost token stream, so we have
1177 // delimiters. Also, those delimiters are not skipped.
1178return looker(&Token::new(delim.as_close_token_kind(), span.close));
1179 }
1180 }
1181 }
1182 }
11831184// Just clone the token cursor and use `next`, skipping delimiters as
1185 // necessary. Slow but simple.
1186let mut cursor = self.token_cursor.clone();
1187let mut i = 0;
1188let mut token = Token::dummy();
1189while i < dist {
1190 token = cursor.next().0;
1191if let token::OpenInvisible(origin) | token::CloseInvisible(origin) = token.kind
1192 && origin.skip()
1193 {
1194continue;
1195 }
1196 i += 1;
1197 }
1198looker(&token)
1199 }
12001201/// Like `look_ahead`, but skips over token trees rather than tokens. Useful
1202 /// when looking past possible metavariable pasting sites.
1203pub fn tree_look_ahead<R>(
1204&self,
1205 dist: usize,
1206 looker: impl FnOnce(&TokenTree) -> R,
1207 ) -> Option<R> {
1208{
match (&dist, &0) {
(left_val, right_val) => {
if *left_val == *right_val {
let kind = ::core::panicking::AssertKind::Ne;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_ne!(dist, 0);
1209self.token_cursor.look_ahead(dist - 1).map(looker)
1210 }
12111212/// Returns whether any of the given keywords are `dist` tokens ahead of the current one.
1213pub(crate) fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool {
1214self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw)))
1215 }
12161217/// Parses asyncness: `async` or nothing.
1218fn parse_coroutine_kind(&mut self, case: Case) -> Option<CoroutineKind> {
1219let span = self.token_uninterpolated_span();
1220if 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) {
1221// FIXME(gen_blocks): Do we want to unconditionally parse `gen` and then
1222 // error if edition <= 2024, like we do with async and edition <= 2018?
1223if self.token_uninterpolated_span().at_least_rust_2024()
1224 && 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)
1225 {
1226let gen_span = self.prev_token_uninterpolated_span();
1227Some(CoroutineKind::AsyncGen {
1228 span: span.to(gen_span),
1229 closure_id: DUMMY_NODE_ID,
1230 return_impl_trait_id: DUMMY_NODE_ID,
1231 })
1232 } else {
1233Some(CoroutineKind::Async {
1234span,
1235 closure_id: DUMMY_NODE_ID,
1236 return_impl_trait_id: DUMMY_NODE_ID,
1237 })
1238 }
1239 } else if self.token_uninterpolated_span().at_least_rust_2024()
1240 && 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)
1241 {
1242Some(CoroutineKind::Gen {
1243span,
1244 closure_id: DUMMY_NODE_ID,
1245 return_impl_trait_id: DUMMY_NODE_ID,
1246 })
1247 } else {
1248None1249 }
1250 }
12511252/// Parses fn unsafety: `unsafe`, `safe` or nothing.
1253fn parse_safety(&mut self, case: Case) -> Safety {
1254if 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) {
1255 Safety::Unsafe(self.prev_token_uninterpolated_span())
1256 } 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) {
1257 Safety::Safe(self.prev_token_uninterpolated_span())
1258 } else {
1259 Safety::Default1260 }
1261 }
12621263/// Parses constness: `const` or nothing.
1264fn parse_constness(&mut self, case: Case) -> Const {
1265self.parse_constness_(case, false)
1266 }
12671268/// Parses constness for closures (case sensitive, feature-gated)
1269fn parse_closure_constness(&mut self) -> Const {
1270let constness = self.parse_constness_(Case::Sensitive, true);
1271if let Const::Yes(span) = constness {
1272self.psess.gated_spans.gate(sym::const_closures, span);
1273 }
1274constness1275 }
12761277fn parse_constness_(&mut self, case: Case, is_closure: bool) -> Const {
1278// Avoid const blocks and const closures to be parsed as const items
1279if (self.check_const_closure() == is_closure)
1280 && !self.look_ahead(1, |t| *t == token::OpenBrace || t.is_metavar_block())
1281 && 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)
1282 {
1283 Const::Yes(self.prev_token_uninterpolated_span())
1284 } else {
1285 Const::No1286 }
1287 }
12881289/// Parses inline const expressions.
1290fn parse_const_block(&mut self, span: Span, pat: bool) -> PResult<'a, Box<Expr>> {
1291self.expect_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Const,
token_type: crate::parser::token_type::TokenType::KwConst,
}exp!(Const))?;
1292let (attrs, blk) = self.parse_inner_attrs_and_block(None)?;
1293let anon_const = AnonConst {
1294 id: DUMMY_NODE_ID,
1295 value: self.mk_expr(blk.span, ExprKind::Block(blk, None)),
1296 };
1297let blk_span = anon_const.value.span;
1298let kind = if pat {
1299let guar = self1300 .dcx()
1301 .struct_span_err(blk_span, "const blocks cannot be used as patterns")
1302 .with_help(
1303"use a named `const`-item or an `if`-guard (`x if x == const { ... }`) instead",
1304 )
1305 .emit();
1306 ExprKind::Err(guar)
1307 } else {
1308 ExprKind::ConstBlock(anon_const)
1309 };
1310Ok(self.mk_expr_with_attrs(span.to(blk_span), kind, attrs))
1311 }
13121313/// Parse nothing or `mut`.
1314fn parse_mutability(&mut self) -> Mutability {
1315if 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 }
1316 }
13171318/// Parse nothing or a by-reference mode.
1319 ///
1320 /// ```ebnf
1321 /// ByRef = "ref" PinAndMut?
1322 /// ```
1323fn parse_byref(&mut self) -> ByRef {
1324if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Ref,
token_type: crate::parser::token_type::TokenType::KwRef,
}exp!(Ref)) {
1325let (pinnedness, mutability) = self.parse_pin_and_mut();
1326 ByRef::Yes(pinnedness, mutability)
1327 } else {
1328 ByRef::No1329 }
1330 }
13311332/// Parse nothing or "explicit" mutability.
1333 ///
1334 /// ```ebnf
1335 /// MutOrConst = "mut" | "const"
1336 /// ```
1337fn parse_mut_or_const(&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 }
13461347/// Parse a field name.
1348 ///
1349 /// ```enbf
1350 /// FieldName = IntLit | Ident
1351 /// ```
1352pub fn parse_field_name(&mut self) -> PResult<'a, Ident> {
1353if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = self.token.kind
1354 {
1355if let Some(suffix) = suffix {
1356self.dcx().emit_err(crate::diagnostics::InvalidLiteralSuffixOnTupleIndex {
1357 span: self.token.span,
1358suffix,
1359 });
1360 }
1361self.bump();
1362Ok(Ident::new(symbol, self.prev_token.span))
1363 } else {
1364self.parse_ident_common(true)
1365 }
1366 }
13671368fn parse_delim_args(&mut self) -> PResult<'a, Box<DelimArgs>> {
1369if let Some(args) = self.parse_delim_args_inner() {
1370Ok(Box::new(args))
1371 } else {
1372self.unexpected_any()
1373 }
1374 }
13751376fn parse_attr_args(&mut self) -> PResult<'a, AttrArgs> {
1377Ok(if let Some(args) = self.parse_delim_args_inner() {
1378 AttrArgs::Delimited(args)
1379 } else if self.eat(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::Eq,
token_type: crate::parser::token_type::TokenType::Eq,
}exp!(Eq)) {
1380let eq_span = self.prev_token.span;
1381let expr = self.parse_expr_force_collect()?;
1382 AttrArgs::Eq { eq_span, expr }
1383 } else {
1384 AttrArgs::Empty1385 })
1386 }
13871388fn parse_delim_args_inner(&mut self) -> Option<DelimArgs> {
1389let delimited = self.check(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::OpenParen,
token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen))
1390 || self.check(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::OpenBracket,
token_type: crate::parser::token_type::TokenType::OpenBracket,
}exp!(OpenBracket))
1391 || self.check(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::OpenBrace,
token_type: crate::parser::token_type::TokenType::OpenBrace,
}exp!(OpenBrace));
13921393delimited.then(|| {
1394let TokenTree::Delimited(dspan, _, delim, tokens) = self.parse_token_tree() else {
1395::core::panicking::panic("internal error: entered unreachable code")unreachable!()1396 };
1397DelimArgs { dspan, delim, tokens }
1398 })
1399 }
14001401/// Parses a single token tree from the input.
1402pub fn parse_token_tree(&mut self) -> TokenTree {
1403if self.token.kind.open_delim().is_some() {
1404// Clone the `TokenTree::Delimited` that we are currently
1405 // within. That's what we are going to return.
1406let tree = self.token_cursor.clone_enclosing_delim();
1407if 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(..));
14081409// Advance the token cursor through the entire delimited
1410 // sequence. After getting the `OpenDelim` we are *within* the
1411 // delimited sequence, i.e. at depth `d`. After getting the
1412 // matching `CloseDelim` we are *after* the delimited sequence,
1413 // i.e. at depth `d - 1`.
1414let target_depth = self.token_cursor.depth() - 1;
14151416if let Capturing::No = self.capture_state.capturing {
1417// We are not capturing tokens, so skip to the end of the
1418 // delimited sequence. This is a perf win when dealing with
1419 // declarative macros that pass large `tt` fragments through
1420 // multiple rules, as seen in the uom-0.37.0 crate.
1421self.token_cursor.bump_to_end();
1422self.bump();
1423if true {
{
match (&self.token_cursor.depth(), &target_depth) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};debug_assert_eq!(self.token_cursor.depth(), target_depth);
1424 } else {
1425loop {
1426// Advance one token at a time, so `TokenCursor::next()`
1427 // can capture these tokens if necessary.
1428self.bump();
1429if self.token_cursor.depth() == target_depth {
1430break;
1431 }
1432 }
1433 }
1434if 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());
14351436// Consume close delimiter
1437self.bump();
1438tree1439 } else {
1440if !!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());
1441let prev_spacing = self.token_spacing;
1442self.bump();
1443 TokenTree::Token(self.prev_token, prev_spacing)
1444 }
1445 }
14461447pub fn parse_tokens(&mut self) -> TokenStream {
1448let mut result = Vec::new();
1449loop {
1450if self.token.kind.is_close_delim_or_eof() {
1451break;
1452 } else {
1453result.push(self.parse_token_tree());
1454 }
1455 }
1456TokenStream::new(result)
1457 }
14581459/// Evaluates the closure with restrictions in place.
1460 ///
1461 /// Afters the closure is evaluated, restrictions are reset.
1462fn with_res<T>(&mut self, res: Restrictions, f: impl FnOnce(&mut Self) -> T) -> T {
1463let old = self.restrictions;
1464self.restrictions = res;
1465let res = f(self);
1466self.restrictions = old;
1467res1468 }
14691470/// Parses `pub` and `pub(in path)` plus shortcuts `pub(crate)` for `pub(in crate)`, `pub(self)`
1471 /// for `pub(in self)` and `pub(super)` for `pub(in super)`.
1472 /// If the following element can't be a tuple (i.e., it's a function definition), then
1473 /// it's not a tuple struct field), and the contents within the parentheses aren't valid,
1474 /// so emit a proper diagnostic.
1475// Public for rustfmt usage.
1476pub fn parse_visibility(&mut self, fbt: FollowedByType) -> PResult<'a, Visibility> {
1477if let Some(vis) = self1478 .eat_metavar_seq(MetaVarKind::Vis, |this| this.parse_visibility(FollowedByType::Yes))
1479 {
1480return Ok(vis);
1481 }
14821483if !self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Pub,
token_type: crate::parser::token_type::TokenType::KwPub,
}exp!(Pub)) {
1484// We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
1485 // keyword to grab a span from for inherited visibility; an empty span at the
1486 // beginning of the current token would seem to be the "Schelling span".
1487return Ok(Visibility {
1488 span: self.token.span.shrink_to_lo(),
1489 kind: VisibilityKind::Inherited,
1490 });
1491 }
1492let lo = self.prev_token.span;
14931494if self.check(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::OpenParen,
token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen)) {
1495// We don't `self.bump()` the `(` yet because this might be a struct definition where
1496 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
1497 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
1498 // by the following tokens.
1499if self.is_keyword_ahead(1, &[kw::In]) {
1500// Parse `pub(in path)`.
1501self.bump(); // `(`
1502self.bump(); // `in`
1503let path = self.parse_path(PathStyle::Mod)?; // `path`
1504self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::CloseParen,
token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen))?; // `)`
1505let vis = VisibilityKind::Restricted {
1506 path: Box::new(path),
1507 id: ast::DUMMY_NODE_ID,
1508 shorthand: false,
1509 };
1510return Ok(Visibility { span: lo.to(self.prev_token.span), kind: vis });
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 { span: lo.to(self.prev_token.span), kind: vis });
1524 } else if let FollowedByType::No = fbt {
1525// Provide this diagnostic if a type cannot follow;
1526 // in particular, if this is not a tuple struct.
1527self.recover_incorrect_vis_restriction()?;
1528// Emit diagnostic, but continue with public visibility.
1529}
1530 }
15311532Ok(Visibility { span: lo, kind: VisibilityKind::Public })
1533 }
15341535/// Recovery for e.g. `pub(something) fn ...` or `struct X { pub(something) y: Z }`
1536fn recover_incorrect_vis_restriction(&mut self) -> PResult<'a, ()> {
1537self.bump(); // `(`
1538let path = self.parse_path(PathStyle::Mod)?;
1539self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::CloseParen,
token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen))?; // `)`
15401541let path_str = pprust::path_to_string(&path);
1542self.dcx()
1543 .emit_err(IncorrectVisibilityRestriction { span: path.span, inner_str: path_str });
15441545Ok(())
1546 }
15471548/// Parses an optional `impl` restriction.
1549 /// Enforces the `impl_restriction` feature gate whenever an explicit restriction is encountered.
1550fn parse_impl_restriction(&mut self) -> PResult<'a, ImplRestriction> {
1551if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Impl,
token_type: crate::parser::token_type::TokenType::KwImpl,
}exp!(Impl)) {
1552let (kind, span, gated_span) = self.parse_restriction(ParsingRestrictionKind::Impl)?;
1553self.psess.gated_spans.gate(sym::impl_restriction, gated_span);
1554return Ok(ImplRestriction { kind, span });
1555 }
1556Ok(ImplRestriction {
1557 kind: RestrictionKind::Unrestricted,
1558 span: self.token.span.shrink_to_lo(),
1559 })
1560 }
15611562/// Parses an optional `mut` restriction.
1563 /// Enforces the `mut_restriction` feature gate whenever an explicit restriction is encountered.
1564fn parse_mut_restriction(&mut self) -> PResult<'a, MutRestriction> {
1565if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::Mut,
token_type: crate::parser::token_type::TokenType::KwMut,
}exp!(Mut)) {
1566let (kind, span, gated_span) = self.parse_restriction(ParsingRestrictionKind::Mut)?;
1567self.psess.gated_spans.gate(sym::mut_restriction, gated_span);
1568return Ok(MutRestriction { kind, span });
1569 }
1570Ok(MutRestriction {
1571 kind: RestrictionKind::Unrestricted,
1572// NOTE: this span is later thrown away
1573 // as a part of FieldDef size optimization.
1574span: self.token.span.shrink_to_lo(),
1575 })
1576 }
15771578/// Parses `impl` or `mut` restrictions.
1579 /// Returns the parsed restriction and its span, as well as the gated span.
1580fn parse_restriction(
1581&mut self,
1582 restriction_kind: ParsingRestrictionKind,
1583 ) -> PResult<'a, (RestrictionKind, Span, Span)> {
1584let lo = self.prev_token.span;
1585// No units or tuples are allowed to follow `impl` or `mut` here, so we can safely bump `(`.
1586self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::OpenParen,
token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen))?;
1587if self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
kw: rustc_span::symbol::kw::In,
token_type: crate::parser::token_type::TokenType::KwIn,
}exp!(In)) {
1588let path = self.parse_path(PathStyle::Mod)?; // `in path`
1589self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::CloseParen,
token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen))?; // `)`
1590let restriction = RestrictionKind::Restricted {
1591 path: Box::new(path),
1592 id: ast::DUMMY_NODE_ID,
1593 shorthand: false,
1594 };
1595let span = lo.to(self.prev_token.span);
1596Ok((restriction, span, span))
1597 } else if self.look_ahead(1, |t| t == &token::CloseParen)
1598 && self.is_keyword_ahead(0, &[kw::Crate, kw::Super, kw::SelfLower])
1599 {
1600let path = self.parse_path(PathStyle::Mod)?; // `crate`/`super`/`self`
1601self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::CloseParen,
token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen))?; // `)`
1602let restriction = RestrictionKind::Restricted {
1603 path: Box::new(path),
1604 id: ast::DUMMY_NODE_ID,
1605 shorthand: true,
1606 };
1607let span = lo.to(self.prev_token.span);
1608Ok((restriction, span, span))
1609 } else {
1610// Emit diagnostic, but continue with no restrictions.
1611 // Recovery for `impl(something) trait` or `mut (something) field`.
1612let path = self.parse_path(PathStyle::Mod)?;
1613self.expect(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::CloseParen,
token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen))?; // `)`
1614let path_str = pprust::path_to_string(&path);
1615let end = self.prev_token.span;
1616match restriction_kind {
1617 ParsingRestrictionKind::Impl => {
1618self.dcx().emit_err(IncorrectImplRestriction {
1619 span: path.span,
1620 inner_str: path_str,
1621 });
1622 }
1623 ParsingRestrictionKind::Mut => {
1624self.dcx()
1625 .emit_err(IncorrectMutRestriction { span: path.span, inner_str: path_str });
1626 }
1627 }
1628Ok((RestrictionKind::Unrestricted, self.token.span.shrink_to_lo(), lo.to(end)))
1629 }
1630 }
16311632/// Parses `extern string_literal?`.
1633fn parse_extern(&mut self, case: Case) -> Extern {
1634if 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) {
1635let mut extern_span = self.prev_token.span;
1636let abi = self.parse_abi();
1637if let Some(abi) = abi {
1638extern_span = extern_span.to(abi.span);
1639 }
1640Extern::from_abi(abi, extern_span)
1641 } else {
1642 Extern::None1643 }
1644 }
16451646/// Parses a string literal as an ABI spec.
1647fn parse_abi(&mut self) -> Option<StrLit> {
1648match self.parse_str_lit() {
1649Ok(str_lit) => Some(str_lit),
1650Err(Some(lit)) => match lit.kind {
1651 ast::LitKind::Err(_) => None,
1652_ => {
1653self.dcx().emit_err(NonStringAbiLiteral { span: lit.span });
1654None1655 }
1656 },
1657Err(None) => None,
1658 }
1659 }
16601661fn collect_tokens_no_attrs<R: HasTokens>(
1662&mut self,
1663 f: impl FnOnce(&mut Self) -> PResult<'a, R>,
1664 ) -> PResult<'a, R> {
1665// The only reason to call `collect_tokens_no_attrs` is if you want tokens, so use
1666 // `ForceCollect::Yes`
1667self.collect_tokens(None, AttrWrapper::empty(), ForceCollect::Yes, |this, _attrs| {
1668Ok((f(this)?, Trailing::No, UsePreAttrPos::No))
1669 })
1670 }
16711672/// Checks for `::` or, potentially, `:::` and then look ahead after it.
1673fn check_path_sep_and_look_ahead(&mut self, looker: impl Fn(&Token) -> bool) -> bool {
1674if self.check(crate::parser::token_type::ExpTokenPair {
tok: rustc_ast::token::PathSep,
token_type: crate::parser::token_type::TokenType::PathSep,
}exp!(PathSep)) {
1675if self.may_recover() && self.look_ahead(1, |t| t.kind == token::Colon) {
1676if 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");
1677self.look_ahead(2, looker)
1678 } else {
1679self.look_ahead(1, looker)
1680 }
1681 } else {
1682false
1683}
1684 }
16851686/// `::{` or `::*`
1687fn is_import_coupler(&mut self) -> bool {
1688self.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))
1689 }
16901691// Debug view of the parser's token stream, up to `{lookahead}` tokens.
1692 // Only used when debugging.
1693#[allow(unused)]
1694pub(crate) fn debug_lookahead(&self, lookahead: usize) -> impl fmt::Debug {
1695 fmt::from_fn(move |f| {
1696let mut dbg_fmt = f.debug_struct("Parser"); // or at least, one view of
16971698 // we don't need N spans, but we want at least one, so print all of prev_token
1699dbg_fmt.field("prev_token", &self.prev_token);
1700let mut tokens = ::alloc::vec::Vec::new()vec![];
1701for i in 0..lookahead {
1702let tok = self.look_ahead(i, |tok| tok.kind);
1703let is_eof = tok == TokenKind::Eof;
1704 tokens.push(tok);
1705if is_eof {
1706// Don't look ahead past EOF.
1707break;
1708 }
1709 }
1710dbg_fmt.field_with("tokens", |field| field.debug_list().entries(tokens).finish());
1711dbg_fmt.field("approx_token_stream_pos", &self.num_bump_calls);
17121713// some fields are interesting for certain values, as they relate to macro parsing
1714if let Some(subparser) = self.subparser_name {
1715dbg_fmt.field("subparser_name", &subparser);
1716 }
1717if let Recovery::Forbidden = self.recovery {
1718dbg_fmt.field("recovery", &self.recovery);
1719 }
17201721// imply there's "more to know" than this view
1722dbg_fmt.finish_non_exhaustive()
1723 })
1724 }
17251726pub fn clear_expected_token_types(&mut self) {
1727self.expected_token_types.clear();
1728 }
17291730pub fn approx_token_stream_pos(&self) -> u32 {
1731self.num_bump_calls
1732 }
17331734/// For interpolated `self.token`, returns a span of the fragment to which
1735 /// the interpolated token refers. For all other tokens this is just a
1736 /// regular span. It is particularly important to use this for identifiers
1737 /// and lifetimes for which spans affect name resolution and edition
1738 /// checks. Note that keywords are also identifiers, so they should use
1739 /// this if they keep spans or perform edition checks.
1740pub fn token_uninterpolated_span(&self) -> Span {
1741match &self.token.kind {
1742 token::NtIdent(ident, _) | token::NtLifetime(ident, _) => ident.span,
1743 token::OpenInvisible(InvisibleOrigin::MetaVar(_)) => self.look_ahead(1, |t| t.span),
1744_ => self.token.span,
1745 }
1746 }
17471748/// Like `token_uninterpolated_span`, but works on `self.prev_token`.
1749pub fn prev_token_uninterpolated_span(&self) -> Span {
1750match &self.prev_token.kind {
1751 token::NtIdent(ident, _) | token::NtLifetime(ident, _) => ident.span,
1752 token::OpenInvisible(InvisibleOrigin::MetaVar(_)) => self.look_ahead(0, |t| t.span),
1753_ => self.prev_token.span,
1754 }
1755 }
17561757fn missing_semi_from_binop(
1758&self,
1759 kind_desc: &str,
1760 expr: &Expr,
1761 decl_lo: Option<Span>,
1762 ) -> Option<(Span, ErrorGuaranteed)> {
1763if self.token == TokenKind::Semi {
1764return None;
1765 }
1766if !self.may_recover() || expr.span.from_expansion() {
1767return None;
1768 }
1769let sm = self.psess.source_map();
1770if let ExprKind::Binary(op, lhs, rhs) = &expr.kind
1771 && sm.is_multiline(lhs.span.shrink_to_hi().until(rhs.span.shrink_to_lo()))
1772 && #[allow(non_exhaustive_omitted_patterns)] match op.node {
BinOpKind::Mul | BinOpKind::BitAnd => true,
_ => false,
}matches!(op.node, BinOpKind::Mul | BinOpKind::BitAnd)1773 && classify::expr_requires_semi_to_be_stmt(rhs)
1774 {
1775let lhs_end_span = lhs.span.shrink_to_hi();
1776let token_str = token_descr(&self.token);
1777let mut err = self1778 .dcx()
1779 .struct_span_err(lhs_end_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected `;`, found {0}",
token_str))
})format!("expected `;`, found {token_str}"));
1780err.span_label(self.token.span, "unexpected token");
17811782// Use the declaration start if provided, otherwise fall back to lhs_end_span.
1783let continuation_start = decl_lo.unwrap_or(lhs_end_span);
1784let continuation_span = continuation_start.until(rhs.span.shrink_to_hi());
1785err.span_label(
1786continuation_span,
1787::alloc::__export::must_use({
::alloc::fmt::format(format_args!("to finish parsing this {0}, expected this to be followed by a `;`",
kind_desc))
})format!(
1788"to finish parsing this {kind_desc}, expected this to be followed by a `;`",
1789 ),
1790 );
1791let op_desc = match op.node {
1792 BinOpKind::BitAnd => "a bit-and",
1793 BinOpKind::Mul => "a multiplication",
1794_ => "a binary",
1795 };
1796let mut note_spans = MultiSpan::new();
1797note_spans.push_span_label(lhs.span, "parsed as the left-hand expression");
1798note_spans.push_span_label(rhs.span, "parsed as the right-hand expression");
1799note_spans.push_span_label(op.span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this was parsed as {0}", op_desc))
})format!("this was parsed as {op_desc}"));
1800err.span_note(
1801note_spans,
1802::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the {0} was parsed as having {1} binary expression",
kind_desc, op_desc))
})format!("the {kind_desc} was parsed as having {op_desc} binary expression"),
1803 );
18041805err.span_suggestion_verbose(
1806lhs_end_span,
1807::alloc::__export::must_use({
::alloc::fmt::format(format_args!("you may have meant to write a `;` to terminate the {0} earlier",
kind_desc))
})format!("you may have meant to write a `;` to terminate the {kind_desc} earlier"),
1808";",
1809 Applicability::MaybeIncorrect,
1810 );
1811return Some((lhs.span, err.emit()));
1812 }
1813None1814 }
1815}
18161817// Metavar captures of various kinds. The more complex node kinds (e.g. `Item`, `Expr`) store
1818// tokens in the node itself because those tokens are needed for non-terminal parsing and for other
1819// reasons (e.g. cfg expansion). Simpler node kinds (e.g. `Block`, `Path`) only need tokens for
1820// non-terminal parsing so here they store the tokens next to the node, keeping the node size
1821// smaller.
1822#[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)),
ParseNtResult::Guard(__self_0) =>
ParseNtResult::Guard(::core::clone::Clone::clone(__self_0)),
}
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for ParseNtResult {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
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),
ParseNtResult::Guard(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Guard",
&__self_0),
}
}
}Debug)]
1823pub enum ParseNtResult {
1824 Tt(TokenTree),
1825 Ident(Ident, IdentIsRaw),
1826 Lifetime(Ident, IdentIsRaw),
1827 Item(Box<ast::Item>),
1828 Block(WithTokens<Box<ast::Block>>),
1829 Stmt(Box<ast::Stmt>),
1830 Pat(WithTokens<Box<ast::Pat>>, NtPatKind),
1831 Expr(Box<ast::Expr>, NtExprKind),
1832 Literal(Box<ast::Expr>),
1833 Ty(WithTokens<Box<ast::Ty>>),
1834// These tokens are for the attr item, e.g. just the `foo` within `#[foo]` or `#![foo]`.
1835Meta(WithTokens<Box<ast::AttrItem>>),
1836 Path(WithTokens<Box<ast::Path>>),
1837 Vis(WithTokens<Box<ast::Visibility>>),
1838 Guard(Box<ast::Guard>),
1839}