12 use crate::lexer::UnmatchedBrace;
13 use diagnostics::Error;
14 pub use path::PathStyle;
17 use rustc_ast::ast::DUMMY_NODE_ID;
18 use rustc_ast::ast::{self, AttrStyle, AttrVec, Const, CrateSugar, Extern, Unsafe};
20 Async, MacArgs, MacDelimiter, Mutability, StrLit, Visibility, VisibilityKind,
22 use rustc_ast::ptr::P;
23 use rustc_ast::token::{self, DelimToken, Token, TokenKind};
24 use rustc_ast::tokenstream::{self, DelimSpan, TokenStream, TokenTree, TreeAndJoint};
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 (data, attr_style, sp) = match self.next() {
212 Token { kind: token::DocComment(_, attr_style, data), span } => {
213 (data, attr_style, span)
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 data.as_str().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),
238 TokenTree::token(TokenKind::lit(token::StrRaw(num_of_hashes), data, None), sp),
242 .collect::<TokenStream>(),
245 self.stack.push(mem::replace(
247 TokenCursorFrame::new(
250 &if attr_style == AttrStyle::Inner {
251 [TokenTree::token(token::Pound, sp), TokenTree::token(token::Not, sp), body]
254 .collect::<TokenStream>()
256 [TokenTree::token(token::Pound, sp), body]
259 .collect::<TokenStream>()
268 #[derive(Clone, PartialEq)]
281 fn to_string(&self) -> String {
283 TokenType::Token(ref t) => format!("`{}`", pprust::token_kind_to_string(t)),
284 TokenType::Keyword(kw) => format!("`{}`", kw),
285 TokenType::Operator => "an operator".to_string(),
286 TokenType::Lifetime => "lifetime".to_string(),
287 TokenType::Ident => "identifier".to_string(),
288 TokenType::Path => "path".to_string(),
289 TokenType::Type => "type".to_string(),
290 TokenType::Const => "const".to_string(),
295 #[derive(Copy, Clone, Debug)]
296 enum TokenExpectType {
301 /// A sequence separator.
303 /// The separator token.
304 sep: Option<TokenKind>,
305 /// `true` if a trailing separator is allowed.
306 trailing_sep_allowed: bool,
310 fn trailing_allowed(t: TokenKind) -> SeqSep {
311 SeqSep { sep: Some(t), trailing_sep_allowed: true }
314 fn none() -> SeqSep {
315 SeqSep { sep: None, trailing_sep_allowed: false }
319 pub enum FollowedByType {
324 fn token_descr_opt(token: &Token) -> Option<&'static str> {
325 Some(match token.kind {
326 _ if token.is_special_ident() => "reserved identifier",
327 _ if token.is_used_keyword() => "keyword",
328 _ if token.is_unused_keyword() => "reserved keyword",
329 token::DocComment(..) => "doc comment",
334 pub(super) fn token_descr(token: &Token) -> String {
335 let token_str = pprust::token_to_string(token);
336 match token_descr_opt(token) {
337 Some(prefix) => format!("{} `{}`", prefix, token_str),
338 _ => format!("`{}`", token_str),
342 impl<'a> Parser<'a> {
346 desugar_doc_comments: bool,
347 subparser_name: Option<&'static str>,
349 let mut parser = Parser {
351 token: Token::dummy(),
352 prev_token: Token::dummy(),
353 restrictions: Restrictions::empty(),
354 expected_tokens: Vec::new(),
355 token_cursor: TokenCursor {
356 frame: TokenCursorFrame::new(DelimSpan::dummy(), token::NoDelim, &tokens),
361 desugar_doc_comments,
362 unmatched_angle_bracket_count: 0,
363 max_angle_bracket_count: 0,
364 unclosed_delims: Vec::new(),
365 last_unexpected_token_span: None,
366 last_type_ascription: None,
370 // Make parser point to the first token.
376 fn next_tok(&mut self, fallback_span: Span) -> Token {
377 let mut next = if self.desugar_doc_comments {
378 self.token_cursor.next_desugared()
380 self.token_cursor.next()
382 if next.span.is_dummy() {
383 // Tweak the location for better diagnostics, but keep syntactic context intact.
384 next.span = fallback_span.with_ctxt(next.span.ctxt());
389 crate fn unexpected<T>(&mut self) -> PResult<'a, T> {
390 match self.expect_one_of(&[], &[]) {
392 // We can get `Ok(true)` from `recover_closing_delimiter`
393 // which is called in `expected_one_of_not_found`.
394 Ok(_) => FatalError.raise(),
398 /// Expects and consumes the token `t`. Signals an error if the next token is not `t`.
399 pub fn expect(&mut self, t: &TokenKind) -> PResult<'a, bool /* recovered */> {
400 if self.expected_tokens.is_empty() {
401 if self.token == *t {
405 self.unexpected_try_recover(t)
408 self.expect_one_of(slice::from_ref(t), &[])
412 /// Expect next token to be edible or inedible token. If edible,
413 /// then consume it; if inedible, then return without consuming
414 /// anything. Signal a fatal error if next token is unexpected.
415 pub fn expect_one_of(
417 edible: &[TokenKind],
418 inedible: &[TokenKind],
419 ) -> PResult<'a, bool /* recovered */> {
420 if edible.contains(&self.token.kind) {
423 } else if inedible.contains(&self.token.kind) {
424 // leave it in the input
426 } else if self.last_unexpected_token_span == Some(self.token.span) {
429 self.expected_one_of_not_found(edible, inedible)
433 // Public for rustfmt usage.
434 pub fn parse_ident(&mut self) -> PResult<'a, Ident> {
435 self.parse_ident_common(true)
438 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, Ident> {
439 match self.token.ident() {
440 Some((ident, is_raw)) => {
441 if !is_raw && ident.is_reserved() {
442 let mut err = self.expected_ident_found();
452 _ => Err(match self.prev_token.kind {
453 TokenKind::DocComment(..) => {
454 self.span_fatal_err(self.prev_token.span, Error::UselessDocComment)
456 _ => self.expected_ident_found(),
461 /// Checks if the next token is `tok`, and returns `true` if so.
463 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
465 fn check(&mut self, tok: &TokenKind) -> bool {
466 let is_present = self.token == *tok;
468 self.expected_tokens.push(TokenType::Token(tok.clone()));
473 /// Consumes a token 'tok' if it exists. Returns whether the given token was present.
474 pub fn eat(&mut self, tok: &TokenKind) -> bool {
475 let is_present = self.check(tok);
482 /// If the next token is the given keyword, returns `true` without eating it.
483 /// An expectation is also added for diagnostics purposes.
484 fn check_keyword(&mut self, kw: Symbol) -> bool {
485 self.expected_tokens.push(TokenType::Keyword(kw));
486 self.token.is_keyword(kw)
489 /// If the next token is the given keyword, eats it and returns `true`.
490 /// Otherwise, returns `false`. An expectation is also added for diagnostics purposes.
491 // Public for rustfmt usage.
492 pub fn eat_keyword(&mut self, kw: Symbol) -> bool {
493 if self.check_keyword(kw) {
501 fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool {
502 if self.token.is_keyword(kw) {
510 /// If the given word is not a keyword, signals an error.
511 /// If the next token is not the given word, signals an error.
512 /// Otherwise, eats it.
513 fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> {
514 if !self.eat_keyword(kw) { self.unexpected() } else { Ok(()) }
517 /// Is the given keyword `kw` followed by a non-reserved identifier?
518 fn is_kw_followed_by_ident(&self, kw: Symbol) -> bool {
519 self.token.is_keyword(kw) && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
522 fn check_or_expected(&mut self, ok: bool, typ: TokenType) -> bool {
526 self.expected_tokens.push(typ);
531 fn check_ident(&mut self) -> bool {
532 self.check_or_expected(self.token.is_ident(), TokenType::Ident)
535 fn check_path(&mut self) -> bool {
536 self.check_or_expected(self.token.is_path_start(), TokenType::Path)
539 fn check_type(&mut self) -> bool {
540 self.check_or_expected(self.token.can_begin_type(), TokenType::Type)
543 fn check_const_arg(&mut self) -> bool {
544 self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const)
547 /// Checks to see if the next token is either `+` or `+=`.
548 /// Otherwise returns `false`.
549 fn check_plus(&mut self) -> bool {
550 self.check_or_expected(
551 self.token.is_like_plus(),
552 TokenType::Token(token::BinOp(token::Plus)),
556 /// Eats the expected token if it's present possibly breaking
557 /// compound tokens like multi-character operators in process.
558 /// Returns `true` if the token was eaten.
559 fn break_and_eat(&mut self, expected: TokenKind) -> bool {
560 if self.token.kind == expected {
564 match self.token.kind.break_two_token_op() {
565 Some((first, second)) if first == expected => {
566 let first_span = self.sess.source_map().start_point(self.token.span);
567 let second_span = self.token.span.with_lo(first_span.hi());
568 self.token = Token::new(first, first_span);
569 self.bump_with(Token::new(second, second_span));
573 self.expected_tokens.push(TokenType::Token(expected));
579 /// Eats `+` possibly breaking tokens like `+=` in process.
580 fn eat_plus(&mut self) -> bool {
581 self.break_and_eat(token::BinOp(token::Plus))
584 /// Eats `&` possibly breaking tokens like `&&` in process.
585 /// Signals an error if `&` is not eaten.
586 fn expect_and(&mut self) -> PResult<'a, ()> {
587 if self.break_and_eat(token::BinOp(token::And)) { Ok(()) } else { self.unexpected() }
590 /// Eats `|` possibly breaking tokens like `||` in process.
591 /// Signals an error if `|` was not eaten.
592 fn expect_or(&mut self) -> PResult<'a, ()> {
593 if self.break_and_eat(token::BinOp(token::Or)) { Ok(()) } else { self.unexpected() }
596 /// Eats `<` possibly breaking tokens like `<<` in process.
597 fn eat_lt(&mut self) -> bool {
598 let ate = self.break_and_eat(token::Lt);
600 // See doc comment for `unmatched_angle_bracket_count`.
601 self.unmatched_angle_bracket_count += 1;
602 self.max_angle_bracket_count += 1;
603 debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count);
608 /// Eats `<` possibly breaking tokens like `<<` in process.
609 /// Signals an error if `<` was not eaten.
610 fn expect_lt(&mut self) -> PResult<'a, ()> {
611 if self.eat_lt() { Ok(()) } else { self.unexpected() }
614 /// Eats `>` possibly breaking tokens like `>>` in process.
615 /// Signals an error if `>` was not eaten.
616 fn expect_gt(&mut self) -> PResult<'a, ()> {
617 if self.break_and_eat(token::Gt) {
618 // See doc comment for `unmatched_angle_bracket_count`.
619 if self.unmatched_angle_bracket_count > 0 {
620 self.unmatched_angle_bracket_count -= 1;
621 debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count);
629 fn expect_any_with_type(&mut self, kets: &[&TokenKind], expect: TokenExpectType) -> bool {
630 kets.iter().any(|k| match expect {
631 TokenExpectType::Expect => self.check(k),
632 TokenExpectType::NoExpect => self.token == **k,
636 fn parse_seq_to_before_tokens<T>(
640 expect: TokenExpectType,
641 mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
642 ) -> PResult<'a, (Vec<T>, bool /* trailing */, bool /* recovered */)> {
643 let mut first = true;
644 let mut recovered = false;
645 let mut trailing = false;
647 while !self.expect_any_with_type(kets, expect) {
648 if let token::CloseDelim(..) | token::Eof = self.token.kind {
651 if let Some(ref t) = sep.sep {
655 match self.expect(t) {
661 Err(mut expect_err) => {
662 let sp = self.prev_token.span.shrink_to_hi();
663 let token_str = pprust::token_kind_to_string(t);
665 // Attempt to keep parsing if it was a similar separator.
666 if let Some(ref tokens) = t.similar_tokens() {
667 if tokens.contains(&self.token.kind) {
672 // If this was a missing `@` in a binding pattern
673 // bail with a suggestion
674 // https://github.com/rust-lang/rust/issues/72373
675 if self.prev_token.is_ident() && self.token.kind == token::DotDot {
677 "if you meant to bind the contents of \
678 the rest of the array pattern into `{}`, use `@`",
679 pprust::token_to_string(&self.prev_token)
682 .span_suggestion_verbose(
683 self.prev_token.span.shrink_to_hi().until(self.token.span),
686 Applicability::MaybeIncorrect,
692 // Attempt to keep parsing if it was an omitted separator.
695 // Parsed successfully, therefore most probably the code only
696 // misses a separator.
698 .span_suggestion_short(
699 self.sess.source_map().next_point(sp),
700 &format!("missing `{}`", token_str),
702 Applicability::MaybeIncorrect,
710 // Parsing failed, therefore it must be something more serious
711 // than just a missing separator.
722 if sep.trailing_sep_allowed && self.expect_any_with_type(kets, expect) {
731 Ok((v, trailing, recovered))
734 /// Parses a sequence, not including the closing delimiter. The function
735 /// `f` must consume tokens until reaching the next separator or
737 fn parse_seq_to_before_end<T>(
741 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
742 ) -> PResult<'a, (Vec<T>, bool, bool)> {
743 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
746 /// Parses a sequence, including the closing delimiter. The function
747 /// `f` must consume tokens until reaching the next separator or
749 fn parse_seq_to_end<T>(
753 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
754 ) -> PResult<'a, (Vec<T>, bool /* trailing */)> {
755 let (val, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
762 /// Parses a sequence, including the closing delimiter. The function
763 /// `f` must consume tokens until reaching the next separator or
765 fn parse_unspanned_seq<T>(
770 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
771 ) -> PResult<'a, (Vec<T>, bool)> {
773 self.parse_seq_to_end(ket, sep, f)
776 fn parse_delim_comma_seq<T>(
779 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
780 ) -> PResult<'a, (Vec<T>, bool)> {
781 self.parse_unspanned_seq(
782 &token::OpenDelim(delim),
783 &token::CloseDelim(delim),
784 SeqSep::trailing_allowed(token::Comma),
789 fn parse_paren_comma_seq<T>(
791 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
792 ) -> PResult<'a, (Vec<T>, bool)> {
793 self.parse_delim_comma_seq(token::Paren, f)
796 /// Advance the parser by one token using provided token as the next one.
797 fn bump_with(&mut self, next_token: Token) {
798 // Bumping after EOF is a bad sign, usually an infinite loop.
799 if self.prev_token.kind == TokenKind::Eof {
800 let msg = "attempted to bump the parser past EOF (may be stuck in a loop)";
801 self.span_bug(self.token.span, msg);
804 // Update the current and previous tokens.
805 self.prev_token = mem::replace(&mut self.token, next_token);
808 self.expected_tokens.clear();
811 /// Advance the parser by one token.
812 pub fn bump(&mut self) {
813 let next_token = self.next_tok(self.token.span);
814 self.bump_with(next_token);
817 /// Look-ahead `dist` tokens of `self.token` and get access to that token there.
818 /// When `dist == 0` then the current token is looked at.
819 pub fn look_ahead<R>(&self, dist: usize, looker: impl FnOnce(&Token) -> R) -> R {
821 return looker(&self.token);
824 let frame = &self.token_cursor.frame;
825 looker(&match frame.tree_cursor.look_ahead(dist - 1) {
826 Some(tree) => match tree {
827 TokenTree::Token(token) => token,
828 TokenTree::Delimited(dspan, delim, _) => {
829 Token::new(token::OpenDelim(delim), dspan.open)
832 None => Token::new(token::CloseDelim(frame.delim), frame.span.close),
836 /// Returns whether any of the given keywords are `dist` tokens ahead of the current one.
837 fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool {
838 self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw)))
841 /// Parses asyncness: `async` or nothing.
842 fn parse_asyncness(&mut self) -> Async {
843 if self.eat_keyword(kw::Async) {
844 let span = self.prev_token.uninterpolated_span();
845 Async::Yes { span, closure_id: DUMMY_NODE_ID, return_impl_trait_id: DUMMY_NODE_ID }
851 /// Parses unsafety: `unsafe` or nothing.
852 fn parse_unsafety(&mut self) -> Unsafe {
853 if self.eat_keyword(kw::Unsafe) {
854 Unsafe::Yes(self.prev_token.uninterpolated_span())
860 /// Parses constness: `const` or nothing.
861 fn parse_constness(&mut self) -> Const {
862 if self.eat_keyword(kw::Const) {
863 Const::Yes(self.prev_token.uninterpolated_span())
869 /// Parses mutability (`mut` or nothing).
870 fn parse_mutability(&mut self) -> Mutability {
871 if self.eat_keyword(kw::Mut) { Mutability::Mut } else { Mutability::Not }
874 /// Possibly parses mutability (`const` or `mut`).
875 fn parse_const_or_mut(&mut self) -> Option<Mutability> {
876 if self.eat_keyword(kw::Mut) {
877 Some(Mutability::Mut)
878 } else if self.eat_keyword(kw::Const) {
879 Some(Mutability::Not)
885 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
886 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = self.token.kind
888 self.expect_no_suffix(self.token.span, "a tuple index", suffix);
890 Ok(Ident::new(symbol, self.prev_token.span))
892 self.parse_ident_common(false)
896 fn parse_mac_args(&mut self) -> PResult<'a, P<MacArgs>> {
897 self.parse_mac_args_common(true).map(P)
900 fn parse_attr_args(&mut self) -> PResult<'a, MacArgs> {
901 self.parse_mac_args_common(false)
904 fn parse_mac_args_common(&mut self, delimited_only: bool) -> PResult<'a, MacArgs> {
906 if self.check(&token::OpenDelim(DelimToken::Paren))
907 || self.check(&token::OpenDelim(DelimToken::Bracket))
908 || self.check(&token::OpenDelim(DelimToken::Brace))
910 match self.parse_token_tree() {
911 TokenTree::Delimited(dspan, delim, tokens) =>
912 // We've confirmed above that there is a delimiter so unwrapping is OK.
914 MacArgs::Delimited(dspan, MacDelimiter::from_token(delim).unwrap(), tokens)
918 } else if !delimited_only {
919 if self.eat(&token::Eq) {
920 let eq_span = self.prev_token.span;
921 let mut is_interpolated_expr = false;
922 if let token::Interpolated(nt) = &self.token.kind {
923 if let token::NtExpr(..) = **nt {
924 is_interpolated_expr = true;
927 let token_tree = if is_interpolated_expr {
928 // We need to accept arbitrary interpolated expressions to continue
929 // supporting things like `doc = $expr` that work on stable.
930 // Non-literal interpolated expressions are rejected after expansion.
931 self.parse_token_tree()
933 self.parse_unsuffixed_lit()?.token_tree()
936 MacArgs::Eq(eq_span, token_tree.into())
941 return self.unexpected();
946 fn parse_or_use_outer_attributes(
948 already_parsed_attrs: Option<AttrVec>,
949 ) -> PResult<'a, AttrVec> {
950 if let Some(attrs) = already_parsed_attrs {
953 self.parse_outer_attributes().map(|a| a.into())
957 /// Parses a single token tree from the input.
958 pub(crate) fn parse_token_tree(&mut self) -> TokenTree {
959 match self.token.kind {
960 token::OpenDelim(..) => {
961 let frame = mem::replace(
962 &mut self.token_cursor.frame,
963 self.token_cursor.stack.pop().unwrap(),
965 self.token = Token::new(TokenKind::CloseDelim(frame.delim), frame.span.close);
967 TokenTree::Delimited(frame.span, frame.delim, frame.tree_cursor.stream)
969 token::CloseDelim(_) | token::Eof => unreachable!(),
972 TokenTree::Token(self.prev_token.clone())
977 /// Parses a stream of tokens into a list of `TokenTree`s, up to EOF.
978 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
979 let mut tts = Vec::new();
980 while self.token != token::Eof {
981 tts.push(self.parse_token_tree());
986 pub fn parse_tokens(&mut self) -> TokenStream {
987 let mut result = Vec::new();
989 match self.token.kind {
990 token::Eof | token::CloseDelim(..) => break,
991 _ => result.push(self.parse_token_tree().into()),
994 TokenStream::new(result)
997 /// Evaluates the closure with restrictions in place.
999 /// Afters the closure is evaluated, restrictions are reset.
1000 fn with_res<T>(&mut self, res: Restrictions, f: impl FnOnce(&mut Self) -> T) -> T {
1001 let old = self.restrictions;
1002 self.restrictions = res;
1004 self.restrictions = old;
1008 fn is_crate_vis(&self) -> bool {
1009 self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
1012 /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
1013 /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
1014 /// If the following element can't be a tuple (i.e., it's a function definition), then
1015 /// it's not a tuple struct field), and the contents within the parentheses isn't valid,
1016 /// so emit a proper diagnostic.
1017 pub(crate) fn parse_visibility(&mut self, fbt: FollowedByType) -> PResult<'a, Visibility> {
1018 maybe_whole!(self, NtVis, |x| x);
1020 self.expected_tokens.push(TokenType::Keyword(kw::Crate));
1021 if self.is_crate_vis() {
1022 self.bump(); // `crate`
1023 self.sess.gated_spans.gate(sym::crate_visibility_modifier, self.prev_token.span);
1024 return Ok(respan(self.prev_token.span, VisibilityKind::Crate(CrateSugar::JustCrate)));
1027 if !self.eat_keyword(kw::Pub) {
1028 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
1029 // keyword to grab a span from for inherited visibility; an empty span at the
1030 // beginning of the current token would seem to be the "Schelling span".
1031 return Ok(respan(self.token.span.shrink_to_lo(), VisibilityKind::Inherited));
1033 let lo = self.prev_token.span;
1035 if self.check(&token::OpenDelim(token::Paren)) {
1036 // We don't `self.bump()` the `(` yet because this might be a struct definition where
1037 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
1038 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
1039 // by the following tokens.
1040 if self.is_keyword_ahead(1, &[kw::Crate]) && self.look_ahead(2, |t| t != &token::ModSep)
1041 // account for `pub(crate::foo)`
1043 // Parse `pub(crate)`.
1045 self.bump(); // `crate`
1046 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1047 let vis = VisibilityKind::Crate(CrateSugar::PubCrate);
1048 return Ok(respan(lo.to(self.prev_token.span), vis));
1049 } else if self.is_keyword_ahead(1, &[kw::In]) {
1050 // Parse `pub(in path)`.
1052 self.bump(); // `in`
1053 let path = self.parse_path(PathStyle::Mod)?; // `path`
1054 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1055 let vis = VisibilityKind::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
1056 return Ok(respan(lo.to(self.prev_token.span), vis));
1057 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren))
1058 && self.is_keyword_ahead(1, &[kw::Super, kw::SelfLower])
1060 // Parse `pub(self)` or `pub(super)`.
1062 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
1063 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1064 let vis = VisibilityKind::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
1065 return Ok(respan(lo.to(self.prev_token.span), vis));
1066 } else if let FollowedByType::No = fbt {
1067 // Provide this diagnostic if a type cannot follow;
1068 // in particular, if this is not a tuple struct.
1069 self.recover_incorrect_vis_restriction()?;
1070 // Emit diagnostic, but continue with public visibility.
1074 Ok(respan(lo, VisibilityKind::Public))
1077 /// Recovery for e.g. `pub(something) fn ...` or `struct X { pub(something) y: Z }`
1078 fn recover_incorrect_vis_restriction(&mut self) -> PResult<'a, ()> {
1080 let path = self.parse_path(PathStyle::Mod)?;
1081 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1083 let msg = "incorrect visibility restriction";
1084 let suggestion = r##"some possible visibility restrictions are:
1085 `pub(crate)`: visible only on the current crate
1086 `pub(super)`: visible only in the current module's parent
1087 `pub(in path::to::module)`: visible only on the specified path"##;
1089 let path_str = pprust::path_to_string(&path);
1091 struct_span_err!(self.sess.span_diagnostic, path.span, E0704, "{}", msg)
1095 &format!("make this visible only to module `{}` with `in`", path_str),
1096 format!("in {}", path_str),
1097 Applicability::MachineApplicable,
1104 /// Parses `extern string_literal?`.
1105 fn parse_extern(&mut self) -> PResult<'a, Extern> {
1106 Ok(if self.eat_keyword(kw::Extern) {
1107 Extern::from_abi(self.parse_abi())
1113 /// Parses a string literal as an ABI spec.
1114 fn parse_abi(&mut self) -> Option<StrLit> {
1115 match self.parse_str_lit() {
1116 Ok(str_lit) => Some(str_lit),
1117 Err(Some(lit)) => match lit.kind {
1118 ast::LitKind::Err(_) => None,
1120 self.struct_span_err(lit.span, "non-string ABI literal")
1123 "specify the ABI with a string literal",
1124 "\"C\"".to_string(),
1125 Applicability::MaybeIncorrect,
1135 /// Records all tokens consumed by the provided callback,
1136 /// including the current token. These tokens are collected
1137 /// into a `TokenStream`, and returned along with the result
1138 /// of the callback.
1140 /// Note: If your callback consumes an opening delimiter
1141 /// (including the case where you call `collect_tokens`
1142 /// when the current token is an opening delimeter),
1143 /// you must also consume the corresponding closing delimiter.
1145 /// That is, you can consume
1146 /// `something ([{ }])` or `([{}])`, but not `([{}]`
1148 /// This restriction shouldn't be an issue in practice,
1149 /// since this function is used to record the tokens for
1150 /// a parsed AST item, which always has matching delimiters.
1151 pub fn collect_tokens<R>(
1153 f: impl FnOnce(&mut Self) -> PResult<'a, R>,
1154 ) -> PResult<'a, (R, TokenStream)> {
1155 // Record all tokens we parse when parsing this item.
1156 let tokens: Vec<TreeAndJoint> = self.token_cursor.cur_token.clone().into_iter().collect();
1157 debug!("collect_tokens: starting with {:?}", tokens);
1159 // We need special handling for the case where `collect_tokens` is called
1160 // on an opening delimeter (e.g. '('). At this point, we have already pushed
1161 // a new frame - however, we want to record the original `TokenTree::Delimited`,
1162 // for consistency with the case where we start recording one token earlier.
1163 // See `TokenCursor::next` to see how `cur_token` is set up.
1165 if matches!(self.token_cursor.cur_token, Some((TokenTree::Delimited(..), _))) {
1166 if self.token_cursor.stack.is_empty() {
1167 // There is nothing below us in the stack that
1168 // the function could consume, so the only thing it can legally
1169 // capture is the entire contents of the current frame.
1170 return Ok((f(self)?, TokenStream::new(tokens)));
1172 // We have already recorded the full `TokenTree::Delimited` when we created
1173 // our `tokens` vector at the start of this function. We are now inside
1174 // a new frame corresponding to the `TokenTree::Delimited` we already recoreded.
1175 // We don't want to record any of the tokens inside this frame, since they
1176 // will be duplicates of the tokens nested inside the `TokenTree::Delimited`.
1177 // Therefore, we set our recording depth to the *previous* frame. This allows
1178 // us to record a sequence like: `(foo).bar()`: the `(foo)` will be recored
1179 // as our initial `cur_token`, while the `.bar()` will be recored after we
1180 // pop the `(foo)` frame.
1181 self.token_cursor.stack.len() - 1
1183 self.token_cursor.stack.len()
1185 let prev_collecting =
1186 self.token_cursor.collecting.replace(Collecting { buf: tokens, depth: prev_depth });
1190 let mut collected_tokens = if let Some(collecting) = self.token_cursor.collecting.take() {
1193 let msg = "our vector went away?";
1194 debug!("collect_tokens: {}", msg);
1195 self.sess.span_diagnostic.delay_span_bug(self.token.span, &msg);
1196 // This can happen due to a bad interaction of two unrelated recovery mechanisms
1197 // with mismatched delimiters *and* recovery lookahead on the likely typo
1198 // `pub ident(` (#62895, different but similar to the case above).
1199 return Ok((ret?, TokenStream::default()));
1202 debug!("collect_tokens: got raw tokens {:?}", collected_tokens);
1204 // If we're not at EOF our current token wasn't actually consumed by
1205 // `f`, but it'll still be in our list that we pulled out. In that case
1207 let extra_token = if self.token != token::Eof { collected_tokens.pop() } else { None };
1209 if let Some(mut collecting) = prev_collecting {
1210 // If we were previously collecting at the same depth,
1211 // then the previous call to `collect_tokens` needs to see
1212 // the tokens we just recorded.
1214 // If we were previously recording at an lower `depth`,
1215 // then the previous `collect_tokens` call already recorded
1216 // this entire frame in the form of a `TokenTree::Delimited`,
1217 // so there is nothing else for us to do.
1218 if collecting.depth == prev_depth {
1219 collecting.buf.extend(collected_tokens.iter().cloned());
1220 collecting.buf.extend(extra_token);
1221 debug!("collect_tokens: updating previous buf to {:?}", collecting);
1223 self.token_cursor.collecting = Some(collecting)
1226 Ok((ret?, TokenStream::new(collected_tokens)))
1230 fn is_import_coupler(&mut self) -> bool {
1231 self.check(&token::ModSep)
1232 && self.look_ahead(1, |t| {
1233 *t == token::OpenDelim(token::Brace) || *t == token::BinOp(token::Star)
1238 crate fn make_unclosed_delims_error(
1239 unmatched: UnmatchedBrace,
1241 ) -> Option<DiagnosticBuilder<'_>> {
1242 // `None` here means an `Eof` was found. We already emit those errors elsewhere, we add them to
1243 // `unmatched_braces` only for error recovery in the `Parser`.
1244 let found_delim = unmatched.found_delim?;
1245 let mut err = sess.span_diagnostic.struct_span_err(
1246 unmatched.found_span,
1248 "mismatched closing delimiter: `{}`",
1249 pprust::token_kind_to_string(&token::CloseDelim(found_delim)),
1252 err.span_label(unmatched.found_span, "mismatched closing delimiter");
1253 if let Some(sp) = unmatched.candidate_span {
1254 err.span_label(sp, "closing delimiter possibly meant for this");
1256 if let Some(sp) = unmatched.unclosed_span {
1257 err.span_label(sp, "unclosed delimiter");
1262 pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, sess: &ParseSess) {
1263 *sess.reached_eof.borrow_mut() |=
1264 unclosed_delims.iter().any(|unmatched_delim| unmatched_delim.found_delim.is_none());
1265 for unmatched in unclosed_delims.drain(..) {
1266 if let Some(mut e) = make_unclosed_delims_error(unmatched, sess) {