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::util::comments::{doc_comment_style, strip_doc_comment_decoration};
26 use rustc_ast_pretty::pprust;
27 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder, FatalError, PResult};
28 use rustc_session::parse::ParseSess;
29 use rustc_span::source_map::{respan, Span, DUMMY_SP};
30 use rustc_span::symbol::{kw, sym, Ident, Symbol};
32 use std::{cmp, mem, slice};
35 struct Restrictions: u8 {
36 const STMT_EXPR = 1 << 0;
37 const NO_STRUCT_LITERAL = 1 << 1;
41 #[derive(Clone, Copy, PartialEq, Debug)]
48 #[derive(Clone, Copy, PartialEq, Debug)]
54 /// Like `maybe_whole_expr`, but for things other than expressions.
56 macro_rules! maybe_whole {
57 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
58 if let token::Interpolated(nt) = &$p.token.kind {
59 if let token::$constructor(x) = &**nt {
68 /// If the next tokens are ill-formed `$ty::` recover them as `<$ty>::`.
70 macro_rules! maybe_recover_from_interpolated_ty_qpath {
71 ($self: expr, $allow_qpath_recovery: expr) => {
72 if $allow_qpath_recovery && $self.look_ahead(1, |t| t == &token::ModSep) {
73 if let token::Interpolated(nt) = &$self.token.kind {
74 if let token::NtTy(ty) = &**nt {
77 return $self.maybe_recover_from_bad_qpath_stage_2($self.prev_token.span, ty);
85 pub struct Parser<'a> {
86 pub sess: &'a ParseSess,
87 /// The current token.
89 /// The previous token.
90 pub prev_token: Token,
91 restrictions: Restrictions,
92 expected_tokens: Vec<TokenType>,
93 token_cursor: TokenCursor,
94 desugar_doc_comments: bool,
95 /// This field is used to keep track of how many left angle brackets we have seen. This is
96 /// required in order to detect extra leading left angle brackets (`<` characters) and error
99 /// See the comments in the `parse_path_segment` function for more details.
100 unmatched_angle_bracket_count: u32,
101 max_angle_bracket_count: u32,
102 /// A list of all unclosed delimiters found by the lexer. If an entry is used for error recovery
103 /// it gets removed from here. Every entry left at the end gets emitted as an independent
105 pub(super) unclosed_delims: Vec<UnmatchedBrace>,
106 last_unexpected_token_span: Option<Span>,
107 /// Span pointing at the `:` for the last type ascription the parser has seen, and whether it
108 /// looked like it could have been a mistyped path or literal `Option:Some(42)`).
109 pub last_type_ascription: Option<(Span, bool /* likely path typo */)>,
110 /// If present, this `Parser` is not parsing Rust code but rather a macro call.
111 subparser_name: Option<&'static str>,
114 impl<'a> Drop for Parser<'a> {
116 emit_unclosed_delims(&mut self.unclosed_delims, &self.sess);
122 frame: TokenCursorFrame,
123 stack: Vec<TokenCursorFrame>,
124 cur_token: Option<TreeAndJoint>,
125 collecting: Option<Collecting>,
129 struct TokenCursorFrame {
130 delim: token::DelimToken,
133 tree_cursor: tokenstream::Cursor,
137 /// Used to track additional state needed by `collect_tokens`
138 #[derive(Clone, Debug)]
140 /// Holds the current tokens captured during the most
141 /// recent call to `collect_tokens`
142 buf: Vec<TreeAndJoint>,
143 /// The depth of the `TokenCursor` stack at the time
144 /// collection was started. When we encounter a `TokenTree::Delimited`,
145 /// we want to record the `TokenTree::Delimited` itself,
146 /// but *not* any of the inner tokens while we are inside
147 /// the new frame (this would cause us to record duplicate tokens).
149 /// This `depth` fields tracks stack depth we are recording tokens.
150 /// Only tokens encountered at this depth will be recorded. See
151 /// `TokenCursor::next` for more details.
155 impl TokenCursorFrame {
156 fn new(span: DelimSpan, delim: DelimToken, tts: &TokenStream) -> Self {
160 open_delim: delim == token::NoDelim,
161 tree_cursor: tts.clone().into_trees(),
162 close_delim: delim == token::NoDelim,
168 fn next(&mut self) -> Token {
170 let tree = if !self.frame.open_delim {
171 self.frame.open_delim = true;
172 TokenTree::open_tt(self.frame.span, self.frame.delim).into()
173 } else if let Some(tree) = self.frame.tree_cursor.next_with_joint() {
175 } else if !self.frame.close_delim {
176 self.frame.close_delim = true;
177 TokenTree::close_tt(self.frame.span, self.frame.delim).into()
178 } else if let Some(frame) = self.stack.pop() {
182 return Token::new(token::Eof, DUMMY_SP);
185 // Don't set an open delimiter as our current token - we want
186 // to leave it as the full `TokenTree::Delimited` from the previous
187 // iteration of this loop
188 if !matches!(tree.0, TokenTree::Token(Token { kind: TokenKind::OpenDelim(_), .. })) {
189 self.cur_token = Some(tree.clone());
192 if let Some(collecting) = &mut self.collecting {
193 if collecting.depth == self.stack.len() {
195 "TokenCursor::next(): collected {:?} at depth {:?}",
199 collecting.buf.push(tree.clone())
204 TokenTree::Token(token) => return token,
205 TokenTree::Delimited(sp, delim, tts) => {
206 let frame = TokenCursorFrame::new(sp, delim, &tts);
207 self.stack.push(mem::replace(&mut self.frame, frame));
213 fn next_desugared(&mut self) -> Token {
214 let (name, sp) = match self.next() {
215 Token { kind: token::DocComment(name), span } => (name, span),
219 let stripped = strip_doc_comment_decoration(name);
221 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
222 // required to wrap the text.
223 let mut num_of_hashes = 0;
225 for ch in stripped.chars() {
228 '#' if count > 0 => count + 1,
231 num_of_hashes = cmp::max(num_of_hashes, count);
234 let delim_span = DelimSpan::from_single(sp);
235 let body = TokenTree::Delimited(
239 TokenTree::token(token::Ident(sym::doc, false), sp),
240 TokenTree::token(token::Eq, sp),
242 TokenKind::lit(token::StrRaw(num_of_hashes), Symbol::intern(&stripped), None),
248 .collect::<TokenStream>(),
251 self.stack.push(mem::replace(
253 TokenCursorFrame::new(
256 &if doc_comment_style(name) == AttrStyle::Inner {
257 [TokenTree::token(token::Pound, sp), TokenTree::token(token::Not, sp), body]
260 .collect::<TokenStream>()
262 [TokenTree::token(token::Pound, sp), body]
265 .collect::<TokenStream>()
274 #[derive(Clone, PartialEq)]
287 fn to_string(&self) -> String {
289 TokenType::Token(ref t) => format!("`{}`", pprust::token_kind_to_string(t)),
290 TokenType::Keyword(kw) => format!("`{}`", kw),
291 TokenType::Operator => "an operator".to_string(),
292 TokenType::Lifetime => "lifetime".to_string(),
293 TokenType::Ident => "identifier".to_string(),
294 TokenType::Path => "path".to_string(),
295 TokenType::Type => "type".to_string(),
296 TokenType::Const => "const".to_string(),
301 #[derive(Copy, Clone, Debug)]
302 enum TokenExpectType {
307 /// A sequence separator.
309 /// The separator token.
310 sep: Option<TokenKind>,
311 /// `true` if a trailing separator is allowed.
312 trailing_sep_allowed: bool,
316 fn trailing_allowed(t: TokenKind) -> SeqSep {
317 SeqSep { sep: Some(t), trailing_sep_allowed: true }
320 fn none() -> SeqSep {
321 SeqSep { sep: None, trailing_sep_allowed: false }
325 pub enum FollowedByType {
330 fn token_descr_opt(token: &Token) -> Option<&'static str> {
331 Some(match token.kind {
332 _ if token.is_special_ident() => "reserved identifier",
333 _ if token.is_used_keyword() => "keyword",
334 _ if token.is_unused_keyword() => "reserved keyword",
335 token::DocComment(..) => "doc comment",
340 pub(super) fn token_descr(token: &Token) -> String {
341 let token_str = pprust::token_to_string(token);
342 match token_descr_opt(token) {
343 Some(prefix) => format!("{} `{}`", prefix, token_str),
344 _ => format!("`{}`", token_str),
348 impl<'a> Parser<'a> {
352 desugar_doc_comments: bool,
353 subparser_name: Option<&'static str>,
355 let mut parser = Parser {
357 token: Token::dummy(),
358 prev_token: Token::dummy(),
359 restrictions: Restrictions::empty(),
360 expected_tokens: Vec::new(),
361 token_cursor: TokenCursor {
362 frame: TokenCursorFrame::new(DelimSpan::dummy(), token::NoDelim, &tokens),
367 desugar_doc_comments,
368 unmatched_angle_bracket_count: 0,
369 max_angle_bracket_count: 0,
370 unclosed_delims: Vec::new(),
371 last_unexpected_token_span: None,
372 last_type_ascription: None,
376 // Make parser point to the first token.
382 fn next_tok(&mut self, fallback_span: Span) -> Token {
383 let mut next = if self.desugar_doc_comments {
384 self.token_cursor.next_desugared()
386 self.token_cursor.next()
388 if next.span.is_dummy() {
389 // Tweak the location for better diagnostics, but keep syntactic context intact.
390 next.span = fallback_span.with_ctxt(next.span.ctxt());
395 crate fn unexpected<T>(&mut self) -> PResult<'a, T> {
396 match self.expect_one_of(&[], &[]) {
398 // We can get `Ok(true)` from `recover_closing_delimiter`
399 // which is called in `expected_one_of_not_found`.
400 Ok(_) => FatalError.raise(),
404 /// Expects and consumes the token `t`. Signals an error if the next token is not `t`.
405 pub fn expect(&mut self, t: &TokenKind) -> PResult<'a, bool /* recovered */> {
406 if self.expected_tokens.is_empty() {
407 if self.token == *t {
411 self.unexpected_try_recover(t)
414 self.expect_one_of(slice::from_ref(t), &[])
418 /// Expect next token to be edible or inedible token. If edible,
419 /// then consume it; if inedible, then return without consuming
420 /// anything. Signal a fatal error if next token is unexpected.
421 pub fn expect_one_of(
423 edible: &[TokenKind],
424 inedible: &[TokenKind],
425 ) -> PResult<'a, bool /* recovered */> {
426 if edible.contains(&self.token.kind) {
429 } else if inedible.contains(&self.token.kind) {
430 // leave it in the input
432 } else if self.last_unexpected_token_span == Some(self.token.span) {
435 self.expected_one_of_not_found(edible, inedible)
439 // Public for rustfmt usage.
440 pub fn parse_ident(&mut self) -> PResult<'a, Ident> {
441 self.parse_ident_common(true)
444 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, Ident> {
445 match self.token.ident() {
446 Some((ident, is_raw)) => {
447 if !is_raw && ident.is_reserved() {
448 let mut err = self.expected_ident_found();
458 _ => Err(match self.prev_token.kind {
459 TokenKind::DocComment(..) => {
460 self.span_fatal_err(self.prev_token.span, Error::UselessDocComment)
462 _ => self.expected_ident_found(),
467 /// Checks if the next token is `tok`, and returns `true` if so.
469 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
471 fn check(&mut self, tok: &TokenKind) -> bool {
472 let is_present = self.token == *tok;
474 self.expected_tokens.push(TokenType::Token(tok.clone()));
479 /// Consumes a token 'tok' if it exists. Returns whether the given token was present.
480 pub fn eat(&mut self, tok: &TokenKind) -> bool {
481 let is_present = self.check(tok);
488 /// If the next token is the given keyword, returns `true` without eating it.
489 /// An expectation is also added for diagnostics purposes.
490 fn check_keyword(&mut self, kw: Symbol) -> bool {
491 self.expected_tokens.push(TokenType::Keyword(kw));
492 self.token.is_keyword(kw)
495 /// If the next token is the given keyword, eats it and returns `true`.
496 /// Otherwise, returns `false`. An expectation is also added for diagnostics purposes.
497 // Public for rustfmt usage.
498 pub fn eat_keyword(&mut self, kw: Symbol) -> bool {
499 if self.check_keyword(kw) {
507 fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool {
508 if self.token.is_keyword(kw) {
516 /// If the given word is not a keyword, signals an error.
517 /// If the next token is not the given word, signals an error.
518 /// Otherwise, eats it.
519 fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> {
520 if !self.eat_keyword(kw) { self.unexpected() } else { Ok(()) }
523 /// Is the given keyword `kw` followed by a non-reserved identifier?
524 fn is_kw_followed_by_ident(&self, kw: Symbol) -> bool {
525 self.token.is_keyword(kw) && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
528 fn check_or_expected(&mut self, ok: bool, typ: TokenType) -> bool {
532 self.expected_tokens.push(typ);
537 fn check_ident(&mut self) -> bool {
538 self.check_or_expected(self.token.is_ident(), TokenType::Ident)
541 fn check_path(&mut self) -> bool {
542 self.check_or_expected(self.token.is_path_start(), TokenType::Path)
545 fn check_type(&mut self) -> bool {
546 self.check_or_expected(self.token.can_begin_type(), TokenType::Type)
549 fn check_const_arg(&mut self) -> bool {
550 self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const)
553 /// Checks to see if the next token is either `+` or `+=`.
554 /// Otherwise returns `false`.
555 fn check_plus(&mut self) -> bool {
556 self.check_or_expected(
557 self.token.is_like_plus(),
558 TokenType::Token(token::BinOp(token::Plus)),
562 /// Eats the expected token if it's present possibly breaking
563 /// compound tokens like multi-character operators in process.
564 /// Returns `true` if the token was eaten.
565 fn break_and_eat(&mut self, expected: TokenKind) -> bool {
566 if self.token.kind == expected {
570 match self.token.kind.break_two_token_op() {
571 Some((first, second)) if first == expected => {
572 let first_span = self.sess.source_map().start_point(self.token.span);
573 let second_span = self.token.span.with_lo(first_span.hi());
574 self.token = Token::new(first, first_span);
575 self.bump_with(Token::new(second, second_span));
579 self.expected_tokens.push(TokenType::Token(expected));
585 /// Eats `+` possibly breaking tokens like `+=` in process.
586 fn eat_plus(&mut self) -> bool {
587 self.break_and_eat(token::BinOp(token::Plus))
590 /// Eats `&` possibly breaking tokens like `&&` in process.
591 /// Signals an error if `&` is not eaten.
592 fn expect_and(&mut self) -> PResult<'a, ()> {
593 if self.break_and_eat(token::BinOp(token::And)) { Ok(()) } else { self.unexpected() }
596 /// Eats `|` possibly breaking tokens like `||` in process.
597 /// Signals an error if `|` was not eaten.
598 fn expect_or(&mut self) -> PResult<'a, ()> {
599 if self.break_and_eat(token::BinOp(token::Or)) { Ok(()) } else { self.unexpected() }
602 /// Eats `<` possibly breaking tokens like `<<` in process.
603 fn eat_lt(&mut self) -> bool {
604 let ate = self.break_and_eat(token::Lt);
606 // See doc comment for `unmatched_angle_bracket_count`.
607 self.unmatched_angle_bracket_count += 1;
608 self.max_angle_bracket_count += 1;
609 debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count);
614 /// Eats `<` possibly breaking tokens like `<<` in process.
615 /// Signals an error if `<` was not eaten.
616 fn expect_lt(&mut self) -> PResult<'a, ()> {
617 if self.eat_lt() { Ok(()) } else { self.unexpected() }
620 /// Eats `>` possibly breaking tokens like `>>` in process.
621 /// Signals an error if `>` was not eaten.
622 fn expect_gt(&mut self) -> PResult<'a, ()> {
623 if self.break_and_eat(token::Gt) {
624 // See doc comment for `unmatched_angle_bracket_count`.
625 if self.unmatched_angle_bracket_count > 0 {
626 self.unmatched_angle_bracket_count -= 1;
627 debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count);
635 fn expect_any_with_type(&mut self, kets: &[&TokenKind], expect: TokenExpectType) -> bool {
636 kets.iter().any(|k| match expect {
637 TokenExpectType::Expect => self.check(k),
638 TokenExpectType::NoExpect => self.token == **k,
642 fn parse_seq_to_before_tokens<T>(
646 expect: TokenExpectType,
647 mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
648 ) -> PResult<'a, (Vec<T>, bool /* trailing */, bool /* recovered */)> {
649 let mut first = true;
650 let mut recovered = false;
651 let mut trailing = false;
653 while !self.expect_any_with_type(kets, expect) {
654 if let token::CloseDelim(..) | token::Eof = self.token.kind {
657 if let Some(ref t) = sep.sep {
661 match self.expect(t) {
667 Err(mut expect_err) => {
668 let sp = self.prev_token.span.shrink_to_hi();
669 let token_str = pprust::token_kind_to_string(t);
671 // Attempt to keep parsing if it was a similar separator.
672 if let Some(ref tokens) = t.similar_tokens() {
673 if tokens.contains(&self.token.kind) {
678 // If this was a missing `@` in a binding pattern
679 // bail with a suggestion
680 // https://github.com/rust-lang/rust/issues/72373
681 if self.prev_token.is_ident() && self.token.kind == token::DotDot {
683 "if you meant to bind the contents of \
684 the rest of the array pattern into `{}`, use `@`",
685 pprust::token_to_string(&self.prev_token)
688 .span_suggestion_verbose(
689 self.prev_token.span.shrink_to_hi().until(self.token.span),
692 Applicability::MaybeIncorrect,
698 // Attempt to keep parsing if it was an omitted separator.
701 // Parsed successfully, therefore most probably the code only
702 // misses a separator.
704 .span_suggestion_short(
705 self.sess.source_map().next_point(sp),
706 &format!("missing `{}`", token_str),
708 Applicability::MaybeIncorrect,
716 // Parsing failed, therefore it must be something more serious
717 // than just a missing separator.
728 if sep.trailing_sep_allowed && self.expect_any_with_type(kets, expect) {
737 Ok((v, trailing, recovered))
740 /// Parses a sequence, not including the closing delimiter. The function
741 /// `f` must consume tokens until reaching the next separator or
743 fn parse_seq_to_before_end<T>(
747 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
748 ) -> PResult<'a, (Vec<T>, bool, bool)> {
749 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
752 /// Parses a sequence, including the closing delimiter. The function
753 /// `f` must consume tokens until reaching the next separator or
755 fn parse_seq_to_end<T>(
759 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
760 ) -> PResult<'a, (Vec<T>, bool /* trailing */)> {
761 let (val, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
768 /// Parses a sequence, including the closing delimiter. The function
769 /// `f` must consume tokens until reaching the next separator or
771 fn parse_unspanned_seq<T>(
776 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
777 ) -> PResult<'a, (Vec<T>, bool)> {
779 self.parse_seq_to_end(ket, sep, f)
782 fn parse_delim_comma_seq<T>(
785 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
786 ) -> PResult<'a, (Vec<T>, bool)> {
787 self.parse_unspanned_seq(
788 &token::OpenDelim(delim),
789 &token::CloseDelim(delim),
790 SeqSep::trailing_allowed(token::Comma),
795 fn parse_paren_comma_seq<T>(
797 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
798 ) -> PResult<'a, (Vec<T>, bool)> {
799 self.parse_delim_comma_seq(token::Paren, f)
802 /// Advance the parser by one token using provided token as the next one.
803 fn bump_with(&mut self, next_token: Token) {
804 // Bumping after EOF is a bad sign, usually an infinite loop.
805 if self.prev_token.kind == TokenKind::Eof {
806 let msg = "attempted to bump the parser past EOF (may be stuck in a loop)";
807 self.span_bug(self.token.span, msg);
810 // Update the current and previous tokens.
811 self.prev_token = mem::replace(&mut self.token, next_token);
814 self.expected_tokens.clear();
817 /// Advance the parser by one token.
818 pub fn bump(&mut self) {
819 let next_token = self.next_tok(self.token.span);
820 self.bump_with(next_token);
823 /// Look-ahead `dist` tokens of `self.token` and get access to that token there.
824 /// When `dist == 0` then the current token is looked at.
825 pub fn look_ahead<R>(&self, dist: usize, looker: impl FnOnce(&Token) -> R) -> R {
827 return looker(&self.token);
830 let frame = &self.token_cursor.frame;
831 looker(&match frame.tree_cursor.look_ahead(dist - 1) {
832 Some(tree) => match tree {
833 TokenTree::Token(token) => token,
834 TokenTree::Delimited(dspan, delim, _) => {
835 Token::new(token::OpenDelim(delim), dspan.open)
838 None => Token::new(token::CloseDelim(frame.delim), frame.span.close),
842 /// Returns whether any of the given keywords are `dist` tokens ahead of the current one.
843 fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool {
844 self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw)))
847 /// Parses asyncness: `async` or nothing.
848 fn parse_asyncness(&mut self) -> Async {
849 if self.eat_keyword(kw::Async) {
850 let span = self.prev_token.uninterpolated_span();
851 Async::Yes { span, closure_id: DUMMY_NODE_ID, return_impl_trait_id: DUMMY_NODE_ID }
857 /// Parses unsafety: `unsafe` or nothing.
858 fn parse_unsafety(&mut self) -> Unsafe {
859 if self.eat_keyword(kw::Unsafe) {
860 Unsafe::Yes(self.prev_token.uninterpolated_span())
866 /// Parses constness: `const` or nothing.
867 fn parse_constness(&mut self) -> Const {
868 if self.eat_keyword(kw::Const) {
869 Const::Yes(self.prev_token.uninterpolated_span())
875 /// Parses mutability (`mut` or nothing).
876 fn parse_mutability(&mut self) -> Mutability {
877 if self.eat_keyword(kw::Mut) { Mutability::Mut } else { Mutability::Not }
880 /// Possibly parses mutability (`const` or `mut`).
881 fn parse_const_or_mut(&mut self) -> Option<Mutability> {
882 if self.eat_keyword(kw::Mut) {
883 Some(Mutability::Mut)
884 } else if self.eat_keyword(kw::Const) {
885 Some(Mutability::Not)
891 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
892 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = self.token.kind
894 self.expect_no_suffix(self.token.span, "a tuple index", suffix);
896 Ok(Ident::new(symbol, self.prev_token.span))
898 self.parse_ident_common(false)
902 fn parse_mac_args(&mut self) -> PResult<'a, P<MacArgs>> {
903 self.parse_mac_args_common(true).map(P)
906 fn parse_attr_args(&mut self) -> PResult<'a, MacArgs> {
907 self.parse_mac_args_common(false)
910 fn parse_mac_args_common(&mut self, delimited_only: bool) -> PResult<'a, MacArgs> {
912 if self.check(&token::OpenDelim(DelimToken::Paren))
913 || self.check(&token::OpenDelim(DelimToken::Bracket))
914 || self.check(&token::OpenDelim(DelimToken::Brace))
916 match self.parse_token_tree() {
917 TokenTree::Delimited(dspan, delim, tokens) =>
918 // We've confirmed above that there is a delimiter so unwrapping is OK.
920 MacArgs::Delimited(dspan, MacDelimiter::from_token(delim).unwrap(), tokens)
924 } else if !delimited_only {
925 if self.eat(&token::Eq) {
926 let eq_span = self.prev_token.span;
927 let mut is_interpolated_expr = false;
928 if let token::Interpolated(nt) = &self.token.kind {
929 if let token::NtExpr(..) = **nt {
930 is_interpolated_expr = true;
933 let token_tree = if is_interpolated_expr {
934 // We need to accept arbitrary interpolated expressions to continue
935 // supporting things like `doc = $expr` that work on stable.
936 // Non-literal interpolated expressions are rejected after expansion.
937 self.parse_token_tree()
939 self.parse_unsuffixed_lit()?.token_tree()
942 MacArgs::Eq(eq_span, token_tree.into())
947 return self.unexpected();
952 fn parse_or_use_outer_attributes(
954 already_parsed_attrs: Option<AttrVec>,
955 ) -> PResult<'a, AttrVec> {
956 if let Some(attrs) = already_parsed_attrs {
959 self.parse_outer_attributes().map(|a| a.into())
963 /// Parses a single token tree from the input.
964 pub(crate) fn parse_token_tree(&mut self) -> TokenTree {
965 match self.token.kind {
966 token::OpenDelim(..) => {
967 let frame = mem::replace(
968 &mut self.token_cursor.frame,
969 self.token_cursor.stack.pop().unwrap(),
971 self.token = Token::new(TokenKind::CloseDelim(frame.delim), frame.span.close);
973 TokenTree::Delimited(frame.span, frame.delim, frame.tree_cursor.stream)
975 token::CloseDelim(_) | token::Eof => unreachable!(),
978 TokenTree::Token(self.prev_token.clone())
983 /// Parses a stream of tokens into a list of `TokenTree`s, up to EOF.
984 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
985 let mut tts = Vec::new();
986 while self.token != token::Eof {
987 tts.push(self.parse_token_tree());
992 pub fn parse_tokens(&mut self) -> TokenStream {
993 let mut result = Vec::new();
995 match self.token.kind {
996 token::Eof | token::CloseDelim(..) => break,
997 _ => result.push(self.parse_token_tree().into()),
1000 TokenStream::new(result)
1003 /// Evaluates the closure with restrictions in place.
1005 /// Afters the closure is evaluated, restrictions are reset.
1006 fn with_res<T>(&mut self, res: Restrictions, f: impl FnOnce(&mut Self) -> T) -> T {
1007 let old = self.restrictions;
1008 self.restrictions = res;
1010 self.restrictions = old;
1014 fn is_crate_vis(&self) -> bool {
1015 self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
1018 /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
1019 /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
1020 /// If the following element can't be a tuple (i.e., it's a function definition), then
1021 /// it's not a tuple struct field), and the contents within the parentheses isn't valid,
1022 /// so emit a proper diagnostic.
1023 pub(crate) fn parse_visibility(&mut self, fbt: FollowedByType) -> PResult<'a, Visibility> {
1024 maybe_whole!(self, NtVis, |x| x);
1026 self.expected_tokens.push(TokenType::Keyword(kw::Crate));
1027 if self.is_crate_vis() {
1028 self.bump(); // `crate`
1029 self.sess.gated_spans.gate(sym::crate_visibility_modifier, self.prev_token.span);
1030 return Ok(respan(self.prev_token.span, VisibilityKind::Crate(CrateSugar::JustCrate)));
1033 if !self.eat_keyword(kw::Pub) {
1034 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
1035 // keyword to grab a span from for inherited visibility; an empty span at the
1036 // beginning of the current token would seem to be the "Schelling span".
1037 return Ok(respan(self.token.span.shrink_to_lo(), VisibilityKind::Inherited));
1039 let lo = self.prev_token.span;
1041 if self.check(&token::OpenDelim(token::Paren)) {
1042 // We don't `self.bump()` the `(` yet because this might be a struct definition where
1043 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
1044 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
1045 // by the following tokens.
1046 if self.is_keyword_ahead(1, &[kw::Crate]) && self.look_ahead(2, |t| t != &token::ModSep)
1047 // account for `pub(crate::foo)`
1049 // Parse `pub(crate)`.
1051 self.bump(); // `crate`
1052 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1053 let vis = VisibilityKind::Crate(CrateSugar::PubCrate);
1054 return Ok(respan(lo.to(self.prev_token.span), vis));
1055 } else if self.is_keyword_ahead(1, &[kw::In]) {
1056 // Parse `pub(in path)`.
1058 self.bump(); // `in`
1059 let path = self.parse_path(PathStyle::Mod)?; // `path`
1060 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1061 let vis = VisibilityKind::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
1062 return Ok(respan(lo.to(self.prev_token.span), vis));
1063 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren))
1064 && self.is_keyword_ahead(1, &[kw::Super, kw::SelfLower])
1066 // Parse `pub(self)` or `pub(super)`.
1068 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
1069 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1070 let vis = VisibilityKind::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
1071 return Ok(respan(lo.to(self.prev_token.span), vis));
1072 } else if let FollowedByType::No = fbt {
1073 // Provide this diagnostic if a type cannot follow;
1074 // in particular, if this is not a tuple struct.
1075 self.recover_incorrect_vis_restriction()?;
1076 // Emit diagnostic, but continue with public visibility.
1080 Ok(respan(lo, VisibilityKind::Public))
1083 /// Recovery for e.g. `pub(something) fn ...` or `struct X { pub(something) y: Z }`
1084 fn recover_incorrect_vis_restriction(&mut self) -> PResult<'a, ()> {
1086 let path = self.parse_path(PathStyle::Mod)?;
1087 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1089 let msg = "incorrect visibility restriction";
1090 let suggestion = r##"some possible visibility restrictions are:
1091 `pub(crate)`: visible only on the current crate
1092 `pub(super)`: visible only in the current module's parent
1093 `pub(in path::to::module)`: visible only on the specified path"##;
1095 let path_str = pprust::path_to_string(&path);
1097 struct_span_err!(self.sess.span_diagnostic, path.span, E0704, "{}", msg)
1101 &format!("make this visible only to module `{}` with `in`", path_str),
1102 format!("in {}", path_str),
1103 Applicability::MachineApplicable,
1110 /// Parses `extern string_literal?`.
1111 fn parse_extern(&mut self) -> PResult<'a, Extern> {
1112 Ok(if self.eat_keyword(kw::Extern) {
1113 Extern::from_abi(self.parse_abi())
1119 /// Parses a string literal as an ABI spec.
1120 fn parse_abi(&mut self) -> Option<StrLit> {
1121 match self.parse_str_lit() {
1122 Ok(str_lit) => Some(str_lit),
1123 Err(Some(lit)) => match lit.kind {
1124 ast::LitKind::Err(_) => None,
1126 self.struct_span_err(lit.span, "non-string ABI literal")
1129 "specify the ABI with a string literal",
1130 "\"C\"".to_string(),
1131 Applicability::MaybeIncorrect,
1141 /// Records all tokens consumed by the provided callback,
1142 /// including the current token. These tokens are collected
1143 /// into a `TokenStream`, and returned along with the result
1144 /// of the callback.
1146 /// Note: If your callback consumes an opening delimiter
1147 /// (including the case where you call `collect_tokens`
1148 /// when the current token is an opening delimeter),
1149 /// you must also consume the corresponding closing delimiter.
1151 /// That is, you can consume
1152 /// `something ([{ }])` or `([{}])`, but not `([{}]`
1154 /// This restriction shouldn't be an issue in practice,
1155 /// since this function is used to record the tokens for
1156 /// a parsed AST item, which always has matching delimiters.
1157 pub fn collect_tokens<R>(
1159 f: impl FnOnce(&mut Self) -> PResult<'a, R>,
1160 ) -> PResult<'a, (R, TokenStream)> {
1161 // Record all tokens we parse when parsing this item.
1162 let tokens: Vec<TreeAndJoint> = self.token_cursor.cur_token.clone().into_iter().collect();
1163 debug!("collect_tokens: starting with {:?}", tokens);
1165 // We need special handling for the case where `collect_tokens` is called
1166 // on an opening delimeter (e.g. '('). At this point, we have already pushed
1167 // a new frame - however, we want to record the original `TokenTree::Delimited`,
1168 // for consistency with the case where we start recording one token earlier.
1169 // See `TokenCursor::next` to see how `cur_token` is set up.
1171 if matches!(self.token_cursor.cur_token, Some((TokenTree::Delimited(..), _))) {
1172 if self.token_cursor.stack.is_empty() {
1173 // There is nothing below us in the stack that
1174 // the function could consume, so the only thing it can legally
1175 // capture is the entire contents of the current frame.
1176 return Ok((f(self)?, TokenStream::new(tokens)));
1178 // We have already recorded the full `TokenTree::Delimited` when we created
1179 // our `tokens` vector at the start of this function. We are now inside
1180 // a new frame corresponding to the `TokenTree::Delimited` we already recoreded.
1181 // We don't want to record any of the tokens inside this frame, since they
1182 // will be duplicates of the tokens nested inside the `TokenTree::Delimited`.
1183 // Therefore, we set our recording depth to the *previous* frame. This allows
1184 // us to record a sequence like: `(foo).bar()`: the `(foo)` will be recored
1185 // as our initial `cur_token`, while the `.bar()` will be recored after we
1186 // pop the `(foo)` frame.
1187 self.token_cursor.stack.len() - 1
1189 self.token_cursor.stack.len()
1191 let prev_collecting =
1192 self.token_cursor.collecting.replace(Collecting { buf: tokens, depth: prev_depth });
1196 let mut collected_tokens = if let Some(collecting) = self.token_cursor.collecting.take() {
1199 let msg = "our vector went away?";
1200 debug!("collect_tokens: {}", msg);
1201 self.sess.span_diagnostic.delay_span_bug(self.token.span, &msg);
1202 // This can happen due to a bad interaction of two unrelated recovery mechanisms
1203 // with mismatched delimiters *and* recovery lookahead on the likely typo
1204 // `pub ident(` (#62895, different but similar to the case above).
1205 return Ok((ret?, TokenStream::default()));
1208 debug!("collect_tokens: got raw tokens {:?}", collected_tokens);
1210 // If we're not at EOF our current token wasn't actually consumed by
1211 // `f`, but it'll still be in our list that we pulled out. In that case
1213 let extra_token = if self.token != token::Eof { collected_tokens.pop() } else { None };
1215 if let Some(mut collecting) = prev_collecting {
1216 // If we were previously collecting at the same depth,
1217 // then the previous call to `collect_tokens` needs to see
1218 // the tokens we just recorded.
1220 // If we were previously recording at an lower `depth`,
1221 // then the previous `collect_tokens` call already recorded
1222 // this entire frame in the form of a `TokenTree::Delimited`,
1223 // so there is nothing else for us to do.
1224 if collecting.depth == prev_depth {
1225 collecting.buf.extend(collected_tokens.iter().cloned());
1226 collecting.buf.extend(extra_token);
1227 debug!("collect_tokens: updating previous buf to {:?}", collecting);
1229 self.token_cursor.collecting = Some(collecting)
1232 Ok((ret?, TokenStream::new(collected_tokens)))
1236 fn is_import_coupler(&mut self) -> bool {
1237 self.check(&token::ModSep)
1238 && self.look_ahead(1, |t| {
1239 *t == token::OpenDelim(token::Brace) || *t == token::BinOp(token::Star)
1244 crate fn make_unclosed_delims_error(
1245 unmatched: UnmatchedBrace,
1247 ) -> Option<DiagnosticBuilder<'_>> {
1248 // `None` here means an `Eof` was found. We already emit those errors elsewhere, we add them to
1249 // `unmatched_braces` only for error recovery in the `Parser`.
1250 let found_delim = unmatched.found_delim?;
1251 let mut err = sess.span_diagnostic.struct_span_err(
1252 unmatched.found_span,
1254 "mismatched closing delimiter: `{}`",
1255 pprust::token_kind_to_string(&token::CloseDelim(found_delim)),
1258 err.span_label(unmatched.found_span, "mismatched closing delimiter");
1259 if let Some(sp) = unmatched.candidate_span {
1260 err.span_label(sp, "closing delimiter possibly meant for this");
1262 if let Some(sp) = unmatched.unclosed_span {
1263 err.span_label(sp, "unclosed delimiter");
1268 pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, sess: &ParseSess) {
1269 *sess.reached_eof.borrow_mut() |=
1270 unclosed_delims.iter().any(|unmatched_delim| unmatched_delim.found_delim.is_none());
1271 for unmatched in unclosed_delims.drain(..) {
1272 if let Some(mut e) = make_unclosed_delims_error(unmatched, sess) {