7 pub use path
::PathStyle
;
11 use diagnostics
::Error
;
13 use crate::lexer
::UnmatchedBrace
;
16 use rustc_ast
::ast
::DUMMY_NODE_ID
;
17 use rustc_ast
::ast
::{self, AttrStyle, AttrVec, Const, CrateSugar, Extern, Unsafe}
;
19 Async
, MacArgs
, MacDelimiter
, Mutability
, StrLit
, Visibility
, VisibilityKind
,
21 use rustc_ast
::ptr
::P
;
22 use rustc_ast
::token
::{self, DelimToken, Token, TokenKind}
;
23 use rustc_ast
::tokenstream
::{self, DelimSpan, TokenStream, TokenTree, TreeAndJoint}
;
24 use rustc_ast
::util
::comments
::{doc_comment_style, strip_doc_comment_decoration}
;
25 use rustc_ast_pretty
::pprust
;
26 use rustc_errors
::{struct_span_err, Applicability, DiagnosticBuilder, FatalError, PResult}
;
27 use rustc_session
::parse
::ParseSess
;
28 use rustc_span
::source_map
::{respan, Span, DUMMY_SP}
;
29 use rustc_span
::symbol
::{kw, sym, Ident, Symbol}
;
31 use std
::{cmp, mem, slice}
;
34 struct Restrictions
: u8 {
35 const STMT_EXPR
= 1 << 0;
36 const NO_STRUCT_LITERAL
= 1 << 1;
40 #[derive(Clone, Copy, PartialEq, Debug)]
47 #[derive(Clone, Copy, PartialEq, Debug)]
53 /// Like `maybe_whole_expr`, but for things other than expressions.
55 macro_rules
! maybe_whole
{
56 ($p
:expr
, $constructor
:ident
, |$x
:ident
| $e
:expr
) => {
57 if let token
::Interpolated(nt
) = &$p
.token
.kind
{
58 if let token
::$
constructor(x
) = &**nt
{
67 /// If the next tokens are ill-formed `$ty::` recover them as `<$ty>::`.
69 macro_rules
! maybe_recover_from_interpolated_ty_qpath
{
70 ($
self: expr
, $allow_qpath_recovery
: expr
) => {
71 if $allow_qpath_recovery
&& $
self.look_ahead(1, |t
| t
== &token
::ModSep
) {
72 if let token
::Interpolated(nt
) = &$
self.token
.kind
{
73 if let token
::NtTy(ty
) = &**nt
{
76 return $
self.maybe_recover_from_bad_qpath_stage_2($
self.prev_token
.span
, ty
);
84 pub struct Parser
<'a
> {
85 pub sess
: &'a ParseSess
,
86 /// The current token.
88 /// The previous token.
89 pub prev_token
: Token
,
90 restrictions
: Restrictions
,
91 expected_tokens
: Vec
<TokenType
>,
92 token_cursor
: TokenCursor
,
93 desugar_doc_comments
: bool
,
94 /// This field is used to keep track of how many left angle brackets we have seen. This is
95 /// required in order to detect extra leading left angle brackets (`<` characters) and error
98 /// See the comments in the `parse_path_segment` function for more details.
99 unmatched_angle_bracket_count
: u32,
100 max_angle_bracket_count
: u32,
101 /// A list of all unclosed delimiters found by the lexer. If an entry is used for error recovery
102 /// it gets removed from here. Every entry left at the end gets emitted as an independent
104 pub(super) unclosed_delims
: Vec
<UnmatchedBrace
>,
105 last_unexpected_token_span
: Option
<Span
>,
106 pub last_type_ascription
: Option
<(Span
, bool
/* likely path typo */)>,
107 /// If present, this `Parser` is not parsing Rust code but rather a macro call.
108 subparser_name
: Option
<&'
static str>,
111 impl<'a
> Drop
for Parser
<'a
> {
113 emit_unclosed_delims(&mut self.unclosed_delims
, &self.sess
);
119 frame
: TokenCursorFrame
,
120 stack
: Vec
<TokenCursorFrame
>,
121 cur_token
: Option
<TreeAndJoint
>,
122 collecting
: Option
<Collecting
>,
126 struct TokenCursorFrame
{
127 delim
: token
::DelimToken
,
130 tree_cursor
: tokenstream
::Cursor
,
134 /// Used to track additional state needed by `collect_tokens`
135 #[derive(Clone, Debug)]
137 /// Holds the current tokens captured during the most
138 /// recent call to `collect_tokens`
139 buf
: Vec
<TreeAndJoint
>,
140 /// The depth of the `TokenCursor` stack at the time
141 /// collection was started. When we encounter a `TokenTree::Delimited`,
142 /// we want to record the `TokenTree::Delimited` itself,
143 /// but *not* any of the inner tokens while we are inside
144 /// the new frame (this would cause us to record duplicate tokens).
146 /// This `depth` fields tracks stack depth we are recording tokens.
147 /// Only tokens encountered at this depth will be recorded. See
148 /// `TokenCursor::next` for more details.
152 impl TokenCursorFrame
{
153 fn new(span
: DelimSpan
, delim
: DelimToken
, tts
: &TokenStream
) -> Self {
157 open_delim
: delim
== token
::NoDelim
,
158 tree_cursor
: tts
.clone().into_trees(),
159 close_delim
: delim
== token
::NoDelim
,
165 fn next(&mut self) -> Token
{
167 let tree
= if !self.frame
.open_delim
{
168 self.frame
.open_delim
= true;
169 TokenTree
::open_tt(self.frame
.span
, self.frame
.delim
).into()
170 } else if let Some(tree
) = self.frame
.tree_cursor
.next_with_joint() {
172 } else if !self.frame
.close_delim
{
173 self.frame
.close_delim
= true;
174 TokenTree
::close_tt(self.frame
.span
, self.frame
.delim
).into()
175 } else if let Some(frame
) = self.stack
.pop() {
179 return Token
::new(token
::Eof
, DUMMY_SP
);
182 // Don't set an open delimiter as our current token - we want
183 // to leave it as the full `TokenTree::Delimited` from the previous
184 // iteration of this loop
185 if !matches
!(tree
.0, TokenTree
::Token(Token { kind: TokenKind::OpenDelim(_), .. }
)) {
186 self.cur_token
= Some(tree
.clone());
189 if let Some(collecting
) = &mut self.collecting
{
190 if collecting
.depth
== self.stack
.len() {
192 "TokenCursor::next(): collected {:?} at depth {:?}",
196 collecting
.buf
.push(tree
.clone())
201 TokenTree
::Token(token
) => return token
,
202 TokenTree
::Delimited(sp
, delim
, tts
) => {
203 let frame
= TokenCursorFrame
::new(sp
, delim
, &tts
);
204 self.stack
.push(mem
::replace(&mut self.frame
, frame
));
210 fn next_desugared(&mut self) -> Token
{
211 let (name
, sp
) = match self.next() {
212 Token { kind: token::DocComment(name), span }
=> (name
, span
),
216 let stripped
= strip_doc_comment_decoration(&name
.as_str());
218 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
219 // required to wrap the text.
220 let mut num_of_hashes
= 0;
222 for ch
in stripped
.chars() {
225 '#' if count > 0 => count + 1,
228 num_of_hashes = cmp::max(num_of_hashes, count);
231 let delim_span = DelimSpan::from_single(sp);
232 let body = TokenTree::Delimited(
236 TokenTree::token(token::Ident(sym::doc, false), sp),
237 TokenTree::token(token::Eq, sp),
239 TokenKind::lit(token::StrRaw(num_of_hashes), Symbol::intern(&stripped), None),
245 .collect::<TokenStream>(),
248 self.stack.push(mem::replace(
250 TokenCursorFrame::new(
253 &if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
254 [TokenTree::token(token::Pound, sp), TokenTree::token(token::Not, sp), body]
257 .collect::<TokenStream>()
259 [TokenTree::token(token::Pound, sp), body]
262 .collect::<TokenStream>()
271 #[derive(Clone, PartialEq)]
284 fn to_string(&self) -> String {
286 TokenType::Token(ref t) => format!("`{}`
", pprust::token_kind_to_string(t)),
287 TokenType::Keyword(kw) => format!("`{}`
", kw),
288 TokenType::Operator => "an operator
".to_string(),
289 TokenType::Lifetime => "lifetime
".to_string(),
290 TokenType::Ident => "identifier
".to_string(),
291 TokenType::Path => "path
".to_string(),
292 TokenType::Type => "type".to_string(),
293 TokenType::Const => "const".to_string(),
298 #[derive(Copy, Clone, Debug)]
299 enum TokenExpectType {
304 /// A sequence separator.
306 /// The separator token.
307 sep: Option<TokenKind>,
308 /// `true` if a trailing separator is allowed.
309 trailing_sep_allowed: bool,
313 fn trailing_allowed(t: TokenKind) -> SeqSep {
314 SeqSep { sep: Some(t), trailing_sep_allowed: true }
317 fn none() -> SeqSep {
318 SeqSep { sep: None, trailing_sep_allowed: false }
322 pub enum FollowedByType {
327 fn token_descr_opt(token: &Token) -> Option<&'static str> {
328 Some(match token.kind {
329 _ if token.is_special_ident() => "reserved identifier
",
330 _ if token.is_used_keyword() => "keyword
",
331 _ if token.is_unused_keyword() => "reserved keyword
",
332 token::DocComment(..) => "doc comment
",
337 pub(super) fn token_descr(token: &Token) -> String {
338 let token_str = pprust::token_to_string(token);
339 match token_descr_opt(token) {
340 Some(prefix) => format!("{} `{}`
", prefix, token_str),
341 _ => format!("`{}`
", token_str),
345 impl<'a> Parser<'a> {
349 desugar_doc_comments: bool,
350 subparser_name: Option<&'static str>,
352 let mut parser = Parser {
354 token: Token::dummy(),
355 prev_token: Token::dummy(),
356 restrictions: Restrictions::empty(),
357 expected_tokens: Vec::new(),
358 token_cursor: TokenCursor {
359 frame: TokenCursorFrame::new(DelimSpan::dummy(), token::NoDelim, &tokens),
364 desugar_doc_comments,
365 unmatched_angle_bracket_count: 0,
366 max_angle_bracket_count: 0,
367 unclosed_delims: Vec::new(),
368 last_unexpected_token_span: None,
369 last_type_ascription: None,
373 // Make parser point to the first token.
379 fn next_tok(&mut self, fallback_span: Span) -> Token {
380 let mut next = if self.desugar_doc_comments {
381 self.token_cursor.next_desugared()
383 self.token_cursor.next()
385 if next.span.is_dummy() {
386 // Tweak the location for better diagnostics, but keep syntactic context intact.
387 next.span = fallback_span.with_ctxt(next.span.ctxt());
392 crate fn unexpected<T>(&mut self) -> PResult<'a, T> {
393 match self.expect_one_of(&[], &[]) {
395 // We can get `Ok(true)` from `recover_closing_delimiter`
396 // which is called in `expected_one_of_not_found`.
397 Ok(_) => FatalError.raise(),
401 /// Expects and consumes the token `t`. Signals an error if the next token is not `t`.
402 pub fn expect(&mut self, t: &TokenKind) -> PResult<'a, bool /* recovered */> {
403 if self.expected_tokens.is_empty() {
404 if self.token == *t {
408 self.unexpected_try_recover(t)
411 self.expect_one_of(slice::from_ref(t), &[])
415 /// Expect next token to be edible or inedible token. If edible,
416 /// then consume it; if inedible, then return without consuming
417 /// anything. Signal a fatal error if next token is unexpected.
418 pub fn expect_one_of(
420 edible: &[TokenKind],
421 inedible: &[TokenKind],
422 ) -> PResult<'a, bool /* recovered */> {
423 if edible.contains(&self.token.kind) {
426 } else if inedible.contains(&self.token.kind) {
427 // leave it in the input
429 } else if self.last_unexpected_token_span == Some(self.token.span) {
432 self.expected_one_of_not_found(edible, inedible)
436 // Public for rustfmt usage.
437 pub fn parse_ident(&mut self) -> PResult<'a, Ident> {
438 self.parse_ident_common(true)
441 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, Ident> {
442 match self.token.ident() {
443 Some((ident, is_raw)) => {
444 if !is_raw && ident.is_reserved() {
445 let mut err = self.expected_ident_found();
455 _ => Err(match self.prev_token.kind {
456 TokenKind::DocComment(..) => {
457 self.span_fatal_err(self.prev_token.span, Error::UselessDocComment)
459 _ => self.expected_ident_found(),
464 /// Checks if the next token is `tok`, and returns `true` if so.
466 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
468 fn check(&mut self, tok: &TokenKind) -> bool {
469 let is_present = self.token == *tok;
471 self.expected_tokens.push(TokenType::Token(tok.clone()));
476 /// Consumes a token 'tok' if it exists. Returns whether the given token was present.
477 pub fn eat(&mut self, tok: &TokenKind) -> bool {
478 let is_present = self.check(tok);
485 /// If the next token is the given keyword, returns `true` without eating it.
486 /// An expectation is also added for diagnostics purposes.
487 fn check_keyword(&mut self, kw: Symbol) -> bool {
488 self.expected_tokens.push(TokenType::Keyword(kw));
489 self.token.is_keyword(kw)
492 /// If the next token is the given keyword, eats it and returns `true`.
493 /// Otherwise, returns `false`. An expectation is also added for diagnostics purposes.
494 // Public for rustfmt usage.
495 pub fn eat_keyword(&mut self, kw: Symbol) -> bool {
496 if self.check_keyword(kw) {
504 fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool {
505 if self.token.is_keyword(kw) {
513 /// If the given word is not a keyword, signals an error.
514 /// If the next token is not the given word, signals an error.
515 /// Otherwise, eats it.
516 fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> {
517 if !self.eat_keyword(kw) { self.unexpected() } else { Ok(()) }
520 /// Is the given keyword `kw` followed by a non-reserved identifier?
521 fn is_kw_followed_by_ident(&self, kw: Symbol) -> bool {
522 self.token.is_keyword(kw) && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
525 fn check_or_expected(&mut self, ok: bool, typ: TokenType) -> bool {
529 self.expected_tokens.push(typ);
534 fn check_ident(&mut self) -> bool {
535 self.check_or_expected(self.token.is_ident(), TokenType::Ident)
538 fn check_path(&mut self) -> bool {
539 self.check_or_expected(self.token.is_path_start(), TokenType::Path)
542 fn check_type(&mut self) -> bool {
543 self.check_or_expected(self.token.can_begin_type(), TokenType::Type)
546 fn check_const_arg(&mut self) -> bool {
547 self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const)
550 /// Checks to see if the next token is either `+` or `+=`.
551 /// Otherwise returns `false`.
552 fn check_plus(&mut self) -> bool {
553 self.check_or_expected(
554 self.token.is_like_plus(),
555 TokenType::Token(token::BinOp(token::Plus)),
559 /// Eats the expected token if it's present possibly breaking
560 /// compound tokens like multi-character operators in process.
561 /// Returns `true` if the token was eaten.
562 fn break_and_eat(&mut self, expected: TokenKind) -> bool {
563 if self.token.kind == expected {
567 match self.token.kind.break_two_token_op() {
568 Some((first, second)) if first == expected => {
569 let first_span = self.sess.source_map().start_point(self.token.span);
570 let second_span = self.token.span.with_lo(first_span.hi());
571 self.token = Token::new(first, first_span);
572 self.bump_with(Token::new(second, second_span));
576 self.expected_tokens.push(TokenType::Token(expected));
582 /// Eats `+` possibly breaking tokens like `+=` in process.
583 fn eat_plus(&mut self) -> bool {
584 self.break_and_eat(token::BinOp(token::Plus))
587 /// Eats `&` possibly breaking tokens like `&&` in process.
588 /// Signals an error if `&` is not eaten.
589 fn expect_and(&mut self) -> PResult<'a, ()> {
590 if self.break_and_eat(token::BinOp(token::And)) { Ok(()) } else { self.unexpected() }
593 /// Eats `|` possibly breaking tokens like `||` in process.
594 /// Signals an error if `|` was not eaten.
595 fn expect_or(&mut self) -> PResult<'a, ()> {
596 if self.break_and_eat(token::BinOp(token::Or)) { Ok(()) } else { self.unexpected() }
599 /// Eats `<` possibly breaking tokens like `<<` in process.
600 fn eat_lt(&mut self) -> bool {
601 let ate = self.break_and_eat(token::Lt);
603 // See doc comment for `unmatched_angle_bracket_count`.
604 self.unmatched_angle_bracket_count += 1;
605 self.max_angle_bracket_count += 1;
606 debug!("eat_lt
: (increment
) count
={:?}
", self.unmatched_angle_bracket_count);
611 /// Eats `<` possibly breaking tokens like `<<` in process.
612 /// Signals an error if `<` was not eaten.
613 fn expect_lt(&mut self) -> PResult<'a, ()> {
614 if self.eat_lt() { Ok(()) } else { self.unexpected() }
617 /// Eats `>` possibly breaking tokens like `>>` in process.
618 /// Signals an error if `>` was not eaten.
619 fn expect_gt(&mut self) -> PResult<'a, ()> {
620 if self.break_and_eat(token::Gt) {
621 // See doc comment for `unmatched_angle_bracket_count`.
622 if self.unmatched_angle_bracket_count > 0 {
623 self.unmatched_angle_bracket_count -= 1;
624 debug!("expect_gt
: (decrement
) count
={:?}
", self.unmatched_angle_bracket_count);
632 fn expect_any_with_type(&mut self, kets: &[&TokenKind], expect: TokenExpectType) -> bool {
633 kets.iter().any(|k| match expect {
634 TokenExpectType::Expect => self.check(k),
635 TokenExpectType::NoExpect => self.token == **k,
639 fn parse_seq_to_before_tokens<T>(
643 expect: TokenExpectType,
644 mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
645 ) -> PResult<'a, (Vec<T>, bool /* trailing */, bool /* recovered */)> {
646 let mut first = true;
647 let mut recovered = false;
648 let mut trailing = false;
650 while !self.expect_any_with_type(kets, expect) {
651 if let token::CloseDelim(..) | token::Eof = self.token.kind {
654 if let Some(ref t) = sep.sep {
658 match self.expect(t) {
664 Err(mut expect_err) => {
665 let sp = self.prev_token.span.shrink_to_hi();
666 let token_str = pprust::token_kind_to_string(t);
668 // Attempt to keep parsing if it was a similar separator.
669 if let Some(ref tokens) = t.similar_tokens() {
670 if tokens.contains(&self.token.kind) {
675 // If this was a missing `@` in a binding pattern
676 // bail with a suggestion
677 // https://github.com/rust-lang/rust/issues/72373
678 if self.prev_token.is_ident() && self.token.kind == token::DotDot {
680 "if you meant to bind the contents of
\
681 the rest of the array pattern into `{}`
, use `@`
",
682 pprust::token_to_string(&self.prev_token)
685 .span_suggestion_verbose(
686 self.prev_token.span.shrink_to_hi().until(self.token.span),
689 Applicability::MaybeIncorrect,
695 // Attempt to keep parsing if it was an omitted separator.
698 // Parsed successfully, therefore most probably the code only
699 // misses a separator.
701 .span_suggestion_short(
702 self.sess.source_map().next_point(sp),
703 &format!("missing `{}`
", token_str),
705 Applicability::MaybeIncorrect,
713 // Parsing failed, therefore it must be something more serious
714 // than just a missing separator.
725 if sep.trailing_sep_allowed && self.expect_any_with_type(kets, expect) {
734 Ok((v, trailing, recovered))
737 /// Parses a sequence, not including the closing delimiter. The function
738 /// `f` must consume tokens until reaching the next separator or
740 fn parse_seq_to_before_end<T>(
744 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
745 ) -> PResult<'a, (Vec<T>, bool, bool)> {
746 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
749 /// Parses a sequence, including the closing delimiter. The function
750 /// `f` must consume tokens until reaching the next separator or
752 fn parse_seq_to_end<T>(
756 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
757 ) -> PResult<'a, (Vec<T>, bool /* trailing */)> {
758 let (val, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
765 /// Parses a sequence, including the closing delimiter. The function
766 /// `f` must consume tokens until reaching the next separator or
768 fn parse_unspanned_seq<T>(
773 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
774 ) -> PResult<'a, (Vec<T>, bool)> {
776 self.parse_seq_to_end(ket, sep, f)
779 fn parse_delim_comma_seq<T>(
782 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
783 ) -> PResult<'a, (Vec<T>, bool)> {
784 self.parse_unspanned_seq(
785 &token::OpenDelim(delim),
786 &token::CloseDelim(delim),
787 SeqSep::trailing_allowed(token::Comma),
792 fn parse_paren_comma_seq<T>(
794 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
795 ) -> PResult<'a, (Vec<T>, bool)> {
796 self.parse_delim_comma_seq(token::Paren, f)
799 /// Advance the parser by one token using provided token as the next one.
800 fn bump_with(&mut self, next_token: Token) {
801 // Bumping after EOF is a bad sign, usually an infinite loop.
802 if self.prev_token.kind == TokenKind::Eof {
803 let msg = "attempted to bump the parser past
EOF (may be stuck
in a
loop)";
804 self.span_bug(self.token.span, msg);
807 // Update the current and previous tokens.
808 self.prev_token = mem::replace(&mut self.token, next_token);
811 self.expected_tokens.clear();
814 /// Advance the parser by one token.
815 pub fn bump(&mut self) {
816 let next_token = self.next_tok(self.token.span);
817 self.bump_with(next_token);
820 /// Look-ahead `dist` tokens of `self.token` and get access to that token there.
821 /// When `dist == 0` then the current token is looked at.
822 pub fn look_ahead<R>(&self, dist: usize, looker: impl FnOnce(&Token) -> R) -> R {
824 return looker(&self.token);
827 let frame = &self.token_cursor.frame;
828 looker(&match frame.tree_cursor.look_ahead(dist - 1) {
829 Some(tree) => match tree {
830 TokenTree::Token(token) => token,
831 TokenTree::Delimited(dspan, delim, _) => {
832 Token::new(token::OpenDelim(delim), dspan.open)
835 None => Token::new(token::CloseDelim(frame.delim), frame.span.close),
839 /// Returns whether any of the given keywords are `dist` tokens ahead of the current one.
840 fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool {
841 self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw)))
844 /// Parses asyncness: `async` or nothing.
845 fn parse_asyncness(&mut self) -> Async {
846 if self.eat_keyword(kw::Async) {
847 let span = self.prev_token.uninterpolated_span();
848 Async::Yes { span, closure_id: DUMMY_NODE_ID, return_impl_trait_id: DUMMY_NODE_ID }
854 /// Parses unsafety: `unsafe` or nothing.
855 fn parse_unsafety(&mut self) -> Unsafe {
856 if self.eat_keyword(kw::Unsafe) {
857 Unsafe::Yes(self.prev_token.uninterpolated_span())
863 /// Parses constness: `const` or nothing.
864 fn parse_constness(&mut self) -> Const {
865 if self.eat_keyword(kw::Const) {
866 Const::Yes(self.prev_token.uninterpolated_span())
872 /// Parses mutability (`mut` or nothing).
873 fn parse_mutability(&mut self) -> Mutability {
874 if self.eat_keyword(kw::Mut) { Mutability::Mut } else { Mutability::Not }
877 /// Possibly parses mutability (`const` or `mut`).
878 fn parse_const_or_mut(&mut self) -> Option<Mutability> {
879 if self.eat_keyword(kw::Mut) {
880 Some(Mutability::Mut)
881 } else if self.eat_keyword(kw::Const) {
882 Some(Mutability::Not)
888 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
889 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = self.token.kind
891 self.expect_no_suffix(self.token.span, "a tuple index
", suffix);
893 Ok(Ident::new(symbol, self.prev_token.span))
895 self.parse_ident_common(false)
899 fn parse_mac_args(&mut self) -> PResult<'a, P<MacArgs>> {
900 self.parse_mac_args_common(true).map(P)
903 fn parse_attr_args(&mut self) -> PResult<'a, MacArgs> {
904 self.parse_mac_args_common(false)
907 fn parse_mac_args_common(&mut self, delimited_only: bool) -> PResult<'a, MacArgs> {
909 if self.check(&token::OpenDelim(DelimToken::Paren))
910 || self.check(&token::OpenDelim(DelimToken::Bracket))
911 || self.check(&token::OpenDelim(DelimToken::Brace))
913 match self.parse_token_tree() {
914 TokenTree::Delimited(dspan, delim, tokens) =>
915 // We've confirmed above that there is a delimiter so unwrapping is OK.
917 MacArgs::Delimited(dspan, MacDelimiter::from_token(delim).unwrap(), tokens)
921 } else if !delimited_only {
922 if self.eat(&token::Eq) {
923 let eq_span = self.prev_token.span;
924 let mut is_interpolated_expr = false;
925 if let token::Interpolated(nt) = &self.token.kind {
926 if let token::NtExpr(..) = **nt {
927 is_interpolated_expr = true;
930 let token_tree = if is_interpolated_expr {
931 // We need to accept arbitrary interpolated expressions to continue
932 // supporting things like `doc = $expr` that work on stable.
933 // Non-literal interpolated expressions are rejected after expansion.
934 self.parse_token_tree()
936 self.parse_unsuffixed_lit()?.token_tree()
939 MacArgs::Eq(eq_span, token_tree.into())
944 return self.unexpected();
949 fn parse_or_use_outer_attributes(
951 already_parsed_attrs: Option<AttrVec>,
952 ) -> PResult<'a, AttrVec> {
953 if let Some(attrs) = already_parsed_attrs {
956 self.parse_outer_attributes().map(|a| a.into())
960 /// Parses a single token tree from the input.
961 pub fn parse_token_tree(&mut self) -> TokenTree {
962 match self.token.kind {
963 token::OpenDelim(..) => {
964 let frame = mem::replace(
965 &mut self.token_cursor.frame,
966 self.token_cursor.stack.pop().unwrap(),
968 self.token = Token::new(TokenKind::CloseDelim(frame.delim), frame.span.close);
970 TokenTree::Delimited(frame.span, frame.delim, frame.tree_cursor.stream)
972 token::CloseDelim(_) | token::Eof => unreachable!(),
975 TokenTree::Token(self.prev_token.clone())
980 /// Parses a stream of tokens into a list of `TokenTree`s, up to EOF.
981 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
982 let mut tts = Vec::new();
983 while self.token != token::Eof {
984 tts.push(self.parse_token_tree());
989 pub fn parse_tokens(&mut self) -> TokenStream {
990 let mut result = Vec::new();
992 match self.token.kind {
993 token::Eof | token::CloseDelim(..) => break,
994 _ => result.push(self.parse_token_tree().into()),
997 TokenStream::new(result)
1000 /// Evaluates the closure with restrictions in place.
1002 /// Afters the closure is evaluated, restrictions are reset.
1003 fn with_res<T>(&mut self, res: Restrictions, f: impl FnOnce(&mut Self) -> T) -> T {
1004 let old = self.restrictions;
1005 self.restrictions = res;
1007 self.restrictions = old;
1011 fn is_crate_vis(&self) -> bool {
1012 self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
1015 /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
1016 /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
1017 /// If the following element can't be a tuple (i.e., it's a function definition), then
1018 /// it's not a tuple struct field), and the contents within the parentheses isn't valid,
1019 /// so emit a proper diagnostic.
1020 pub fn parse_visibility(&mut self, fbt: FollowedByType) -> PResult<'a, Visibility> {
1021 maybe_whole!(self, NtVis, |x| x);
1023 self.expected_tokens.push(TokenType::Keyword(kw::Crate));
1024 if self.is_crate_vis() {
1025 self.bump(); // `crate`
1026 self.sess.gated_spans.gate(sym::crate_visibility_modifier, self.prev_token.span);
1027 return Ok(respan(self.prev_token.span, VisibilityKind::Crate(CrateSugar::JustCrate)));
1030 if !self.eat_keyword(kw::Pub) {
1031 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
1032 // keyword to grab a span from for inherited visibility; an empty span at the
1033 // beginning of the current token would seem to be the "Schelling span
".
1034 return Ok(respan(self.token.span.shrink_to_lo(), VisibilityKind::Inherited));
1036 let lo = self.prev_token.span;
1038 if self.check(&token::OpenDelim(token::Paren)) {
1039 // We don't `self.bump()` the `(` yet because this might be a struct definition where
1040 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
1041 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
1042 // by the following tokens.
1043 if self.is_keyword_ahead(1, &[kw::Crate]) && self.look_ahead(2, |t| t != &token::ModSep)
1044 // account for `pub(crate::foo)`
1046 // Parse `pub(crate)`.
1048 self.bump(); // `crate`
1049 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1050 let vis = VisibilityKind::Crate(CrateSugar::PubCrate);
1051 return Ok(respan(lo.to(self.prev_token.span), vis));
1052 } else if self.is_keyword_ahead(1, &[kw::In]) {
1053 // Parse `pub(in path)`.
1055 self.bump(); // `in`
1056 let path = self.parse_path(PathStyle::Mod)?; // `path`
1057 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1058 let vis = VisibilityKind::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
1059 return Ok(respan(lo.to(self.prev_token.span), vis));
1060 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren))
1061 && self.is_keyword_ahead(1, &[kw::Super, kw::SelfLower])
1063 // Parse `pub(self)` or `pub(super)`.
1065 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
1066 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1067 let vis = VisibilityKind::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
1068 return Ok(respan(lo.to(self.prev_token.span), vis));
1069 } else if let FollowedByType::No = fbt {
1070 // Provide this diagnostic if a type cannot follow;
1071 // in particular, if this is not a tuple struct.
1072 self.recover_incorrect_vis_restriction()?;
1073 // Emit diagnostic, but continue with public visibility.
1077 Ok(respan(lo, VisibilityKind::Public))
1080 /// Recovery for e.g. `pub(something) fn ...` or `struct X { pub(something) y: Z }`
1081 fn recover_incorrect_vis_restriction(&mut self) -> PResult<'a, ()> {
1083 let path = self.parse_path(PathStyle::Mod)?;
1084 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1086 let msg = "incorrect visibility restriction
";
1087 let suggestion = r##"some possible visibility restrictions are
:
1088 `
pub(crate)`
: visible only on the current
crate
1089 `
pub(super)`
: visible only
in the current module's parent
1090 `
pub(in path
::to
::module
)`
: visible only on the specified path
"##;
1092 let path_str = pprust::path_to_string(&path);
1094 struct_span_err!(self.sess.span_diagnostic, path.span, E0704, "{}
", msg)
1098 &format!("make this visible only to module `{}` with `
in`
", path_str),
1099 format!("in {}
", path_str),
1100 Applicability::MachineApplicable,
1107 /// Parses `extern string_literal?`.
1108 fn parse_extern(&mut self) -> PResult<'a, Extern> {
1109 Ok(if self.eat_keyword(kw::Extern) {
1110 Extern::from_abi(self.parse_abi())
1116 /// Parses a string literal as an ABI spec.
1117 fn parse_abi(&mut self) -> Option<StrLit> {
1118 match self.parse_str_lit() {
1119 Ok(str_lit) => Some(str_lit),
1120 Err(Some(lit)) => match lit.kind {
1121 ast::LitKind::Err(_) => None,
1123 self.struct_span_err(lit.span, "non
-string ABI literal
")
1126 "specify the ABI with a string literal
",
1127 "\"C
\"".to_string(),
1128 Applicability::MaybeIncorrect,
1138 /// Records all tokens consumed by the provided callback,
1139 /// including the current token. These tokens are collected
1140 /// into a `TokenStream`, and returned along with the result
1141 /// of the callback.
1143 /// Note: If your callback consumes an opening delimiter
1144 /// (including the case where you call `collect_tokens`
1145 /// when the current token is an opening delimeter),
1146 /// you must also consume the corresponding closing delimiter.
1148 /// That is, you can consume
1149 /// `something ([{ }])` or `([{}])`, but not `([{}]`
1151 /// This restriction shouldn't be an issue in practice,
1152 /// since this function is used to record the tokens for
1153 /// a parsed AST item, which always has matching delimiters.
1154 pub fn collect_tokens<R>(
1156 f: impl FnOnce(&mut Self) -> PResult<'a, R>,
1157 ) -> PResult<'a, (R, TokenStream)> {
1158 // Record all tokens we parse when parsing this item.
1159 let tokens: Vec<TreeAndJoint> = self.token_cursor.cur_token.clone().into_iter().collect();
1160 debug!("collect_tokens
: starting with {:?}
", tokens);
1162 // We need special handling for the case where `collect_tokens` is called
1163 // on an opening delimeter (e.g. '('). At this point, we have already pushed
1164 // a new frame - however, we want to record the original `TokenTree::Delimited`,
1165 // for consistency with the case where we start recording one token earlier.
1166 // See `TokenCursor::next` to see how `cur_token` is set up.
1168 if matches!(self.token_cursor.cur_token, Some((TokenTree::Delimited(..), _))) {
1169 if self.token_cursor.stack.is_empty() {
1170 // There is nothing below us in the stack that
1171 // the function could consume, so the only thing it can legally
1172 // capture is the entire contents of the current frame.
1173 return Ok((f(self)?, TokenStream::new(tokens)));
1175 // We have already recorded the full `TokenTree::Delimited` when we created
1176 // our `tokens` vector at the start of this function. We are now inside
1177 // a new frame corresponding to the `TokenTree::Delimited` we already recoreded.
1178 // We don't want to record any of the tokens inside this frame, since they
1179 // will be duplicates of the tokens nested inside the `TokenTree::Delimited`.
1180 // Therefore, we set our recording depth to the *previous* frame. This allows
1181 // us to record a sequence like: `(foo).bar()`: the `(foo)` will be recored
1182 // as our initial `cur_token`, while the `.bar()` will be recored after we
1183 // pop the `(foo)` frame.
1184 self.token_cursor.stack.len() - 1
1186 self.token_cursor.stack.len()
1188 let prev_collecting =
1189 self.token_cursor.collecting.replace(Collecting { buf: tokens, depth: prev_depth });
1193 let mut collected_tokens = if let Some(collecting) = self.token_cursor.collecting.take() {
1196 let msg = "our vector went away?
";
1197 debug!("collect_tokens
: {}
", msg);
1198 self.sess.span_diagnostic.delay_span_bug(self.token.span, &msg);
1199 // This can happen due to a bad interaction of two unrelated recovery mechanisms
1200 // with mismatched delimiters *and* recovery lookahead on the likely typo
1201 // `pub ident(` (#62895, different but similar to the case above).
1202 return Ok((ret?, TokenStream::default()));
1205 debug!("collect_tokens
: got raw tokens {:?}
", collected_tokens);
1207 // If we're not at EOF our current token wasn't actually consumed by
1208 // `f`, but it'll still be in our list that we pulled out. In that case
1210 let extra_token = if self.token != token::Eof { collected_tokens.pop() } else { None };
1212 if let Some(mut collecting) = prev_collecting {
1213 // If we were previously collecting at the same depth,
1214 // then the previous call to `collect_tokens` needs to see
1215 // the tokens we just recorded.
1217 // If we were previously recording at an lower `depth`,
1218 // then the previous `collect_tokens` call already recorded
1219 // this entire frame in the form of a `TokenTree::Delimited`,
1220 // so there is nothing else for us to do.
1221 if collecting.depth == prev_depth {
1222 collecting.buf.extend(collected_tokens.iter().cloned());
1223 collecting.buf.extend(extra_token);
1224 debug!("collect_tokens
: updating previous buf to {:?}
", collecting);
1226 self.token_cursor.collecting = Some(collecting)
1229 Ok((ret?, TokenStream::new(collected_tokens)))
1233 fn is_import_coupler(&mut self) -> bool {
1234 self.check(&token::ModSep)
1235 && self.look_ahead(1, |t| {
1236 *t == token::OpenDelim(token::Brace) || *t == token::BinOp(token::Star)
1241 crate fn make_unclosed_delims_error(
1242 unmatched: UnmatchedBrace,
1244 ) -> Option<DiagnosticBuilder<'_>> {
1245 // `None` here means an `Eof` was found. We already emit those errors elsewhere, we add them to
1246 // `unmatched_braces` only for error recovery in the `Parser`.
1247 let found_delim = unmatched.found_delim?;
1248 let mut err = sess.span_diagnostic.struct_span_err(
1249 unmatched.found_span,
1251 "mismatched closing delimiter
: `{}`
",
1252 pprust::token_kind_to_string(&token::CloseDelim(found_delim)),
1255 err.span_label(unmatched.found_span, "mismatched closing delimiter
");
1256 if let Some(sp) = unmatched.candidate_span {
1257 err.span_label(sp, "closing delimiter possibly meant
for this
");
1259 if let Some(sp) = unmatched.unclosed_span {
1260 err.span_label(sp, "unclosed delimiter
");
1265 pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, sess: &ParseSess) {
1266 *sess.reached_eof.borrow_mut() |=
1267 unclosed_delims.iter().any(|unmatched_delim| unmatched_delim.found_delim.is_none());
1268 for unmatched in unclosed_delims.drain(..) {
1269 if let Some(mut e) = make_unclosed_delims_error(unmatched, sess) {