8 pub use path::PathStyle;
12 use diagnostics::Error;
14 use crate::{Directory, DirectoryOwnership};
15 use crate::lexer::UnmatchedBrace;
17 use rustc_errors::{PResult, Applicability, DiagnosticBuilder, FatalError};
18 use rustc_data_structures::thin_vec::ThinVec;
19 use syntax::ast::{self, DUMMY_NODE_ID, AttrStyle, Attribute, CrateSugar, Extern, Ident, StrLit};
20 use syntax::ast::{IsAsync, MacArgs, MacDelimiter, Mutability, Visibility, VisibilityKind, Unsafety};
21 use syntax::print::pprust;
23 use syntax::token::{self, Token, TokenKind, DelimToken};
24 use syntax::tokenstream::{self, DelimSpan, TokenTree, TokenStream, TreeAndJoint};
25 use syntax::sess::ParseSess;
26 use syntax::struct_span_err;
27 use syntax::util::comments::{doc_comment_style, strip_doc_comment_decoration};
28 use syntax_pos::source_map::respan;
29 use syntax_pos::symbol::{kw, sym, Symbol};
30 use syntax_pos::{Span, BytePos, DUMMY_SP, FileName};
34 use std::{cmp, mem, slice};
35 use std::path::PathBuf;
37 use rustc_error_codes::*;
40 struct Restrictions: u8 {
41 const STMT_EXPR = 1 << 0;
42 const NO_STRUCT_LITERAL = 1 << 1;
46 #[derive(Clone, Copy, PartialEq, Debug)]
53 #[derive(Clone, Copy, PartialEq, Debug)]
59 /// Like `maybe_whole_expr`, but for things other than expressions.
61 macro_rules! maybe_whole {
62 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
63 if let token::Interpolated(nt) = &$p.token.kind {
64 if let token::$constructor(x) = &**nt {
73 /// If the next tokens are ill-formed `$ty::` recover them as `<$ty>::`.
75 macro_rules! maybe_recover_from_interpolated_ty_qpath {
76 ($self: expr, $allow_qpath_recovery: expr) => {
77 if $allow_qpath_recovery && $self.look_ahead(1, |t| t == &token::ModSep) {
78 if let token::Interpolated(nt) = &$self.token.kind {
79 if let token::NtTy(ty) = &**nt {
82 return $self.maybe_recover_from_bad_qpath_stage_2($self.prev_span, ty);
89 #[derive(Debug, Clone, Copy, PartialEq)]
101 // NOTE: `Ident`s are handled by `common.rs`.
104 pub struct Parser<'a> {
105 pub sess: &'a ParseSess,
106 /// The current normalized token.
107 /// "Normalized" means that some interpolated tokens
108 /// (`$i: ident` and `$l: lifetime` meta-variables) are replaced
109 /// with non-interpolated identifier and lifetime tokens they refer to.
110 /// Perhaps the normalized / non-normalized setup can be simplified somehow.
112 /// The span of the current non-normalized token.
113 meta_var_span: Option<Span>,
114 /// The span of the previous non-normalized token.
116 /// The kind of the previous normalized token (in simplified form).
117 prev_token_kind: PrevTokenKind,
118 restrictions: Restrictions,
119 /// Used to determine the path to externally loaded source files.
120 pub(super) directory: Directory<'a>,
121 /// `true` to parse sub-modules in other files.
122 pub(super) recurse_into_file_modules: bool,
123 /// Name of the root module this parser originated from. If `None`, then the
124 /// name is not known. This does not change while the parser is descending
125 /// into modules, and sub-parsers have new values for this name.
126 pub root_module_name: Option<String>,
127 expected_tokens: Vec<TokenType>,
128 token_cursor: TokenCursor,
129 desugar_doc_comments: bool,
130 /// `true` we should configure out of line modules as we parse.
132 /// This field is used to keep track of how many left angle brackets we have seen. This is
133 /// required in order to detect extra leading left angle brackets (`<` characters) and error
136 /// See the comments in the `parse_path_segment` function for more details.
137 unmatched_angle_bracket_count: u32,
138 max_angle_bracket_count: u32,
139 /// A list of all unclosed delimiters found by the lexer. If an entry is used for error recovery
140 /// it gets removed from here. Every entry left at the end gets emitted as an independent
142 pub(super) unclosed_delims: Vec<UnmatchedBrace>,
143 last_unexpected_token_span: Option<Span>,
144 pub last_type_ascription: Option<(Span, bool /* likely path typo */)>,
145 /// If present, this `Parser` is not parsing Rust code but rather a macro call.
146 subparser_name: Option<&'static str>,
149 impl<'a> Drop for Parser<'a> {
151 emit_unclosed_delims(&mut self.unclosed_delims, &self.sess);
157 frame: TokenCursorFrame,
158 stack: Vec<TokenCursorFrame>,
162 struct TokenCursorFrame {
163 delim: token::DelimToken,
166 tree_cursor: tokenstream::Cursor,
168 last_token: LastToken,
171 /// This is used in `TokenCursorFrame` above to track tokens that are consumed
172 /// by the parser, and then that's transitively used to record the tokens that
173 /// each parse AST item is created with.
175 /// Right now this has two states, either collecting tokens or not collecting
176 /// tokens. If we're collecting tokens we just save everything off into a local
177 /// `Vec`. This should eventually though likely save tokens from the original
178 /// token stream and just use slicing of token streams to avoid creation of a
179 /// whole new vector.
181 /// The second state is where we're passively not recording tokens, but the last
182 /// token is still tracked for when we want to start recording tokens. This
183 /// "last token" means that when we start recording tokens we'll want to ensure
184 /// that this, the first token, is included in the output.
186 /// You can find some more example usage of this in the `collect_tokens` method
190 Collecting(Vec<TreeAndJoint>),
191 Was(Option<TreeAndJoint>),
194 impl TokenCursorFrame {
195 fn new(span: DelimSpan, delim: DelimToken, tts: &TokenStream) -> Self {
199 open_delim: delim == token::NoDelim,
200 tree_cursor: tts.clone().into_trees(),
201 close_delim: delim == token::NoDelim,
202 last_token: LastToken::Was(None),
208 fn next(&mut self) -> Token {
210 let tree = if !self.frame.open_delim {
211 self.frame.open_delim = true;
212 TokenTree::open_tt(self.frame.span, self.frame.delim)
213 } else if let Some(tree) = self.frame.tree_cursor.next() {
215 } else if !self.frame.close_delim {
216 self.frame.close_delim = true;
217 TokenTree::close_tt(self.frame.span, self.frame.delim)
218 } else if let Some(frame) = self.stack.pop() {
222 return Token::new(token::Eof, DUMMY_SP);
225 match self.frame.last_token {
226 LastToken::Collecting(ref mut v) => v.push(tree.clone().into()),
227 LastToken::Was(ref mut t) => *t = Some(tree.clone().into()),
231 TokenTree::Token(token) => return token,
232 TokenTree::Delimited(sp, delim, tts) => {
233 let frame = TokenCursorFrame::new(sp, delim, &tts);
234 self.stack.push(mem::replace(&mut self.frame, frame));
240 fn next_desugared(&mut self) -> Token {
241 let (name, sp) = match self.next() {
242 Token { kind: token::DocComment(name), span } => (name, span),
246 let stripped = strip_doc_comment_decoration(&name.as_str());
248 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
249 // required to wrap the text.
250 let mut num_of_hashes = 0;
252 for ch in stripped.chars() {
255 '#' if count > 0 => count + 1,
258 num_of_hashes = cmp::max(num_of_hashes, count);
261 let delim_span = DelimSpan::from_single(sp);
262 let body = TokenTree::Delimited(
266 TokenTree::token(token::Ident(sym::doc, false), sp),
267 TokenTree::token(token::Eq, sp),
268 TokenTree::token(TokenKind::lit(
269 token::StrRaw(num_of_hashes), Symbol::intern(&stripped), None
272 .iter().cloned().collect::<TokenStream>().into(),
275 self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new(
278 &if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
279 [TokenTree::token(token::Pound, sp), TokenTree::token(token::Not, sp), body]
280 .iter().cloned().collect::<TokenStream>()
282 [TokenTree::token(token::Pound, sp), body]
283 .iter().cloned().collect::<TokenStream>()
291 #[derive(Clone, PartialEq)]
304 fn to_string(&self) -> String {
306 TokenType::Token(ref t) => format!("`{}`", pprust::token_kind_to_string(t)),
307 TokenType::Keyword(kw) => format!("`{}`", kw),
308 TokenType::Operator => "an operator".to_string(),
309 TokenType::Lifetime => "lifetime".to_string(),
310 TokenType::Ident => "identifier".to_string(),
311 TokenType::Path => "path".to_string(),
312 TokenType::Type => "type".to_string(),
313 TokenType::Const => "const".to_string(),
318 #[derive(Copy, Clone, Debug)]
319 enum TokenExpectType {
324 /// A sequence separator.
326 /// The separator token.
327 sep: Option<TokenKind>,
328 /// `true` if a trailing separator is allowed.
329 trailing_sep_allowed: bool,
333 fn trailing_allowed(t: TokenKind) -> SeqSep {
336 trailing_sep_allowed: true,
340 fn none() -> SeqSep {
343 trailing_sep_allowed: false,
348 pub enum FollowedByType { Yes, No }
350 impl<'a> Parser<'a> {
354 directory: Option<Directory<'a>>,
355 recurse_into_file_modules: bool,
356 desugar_doc_comments: bool,
357 subparser_name: Option<&'static str>,
359 let mut parser = Parser {
361 token: Token::dummy(),
364 prev_token_kind: PrevTokenKind::Other,
365 restrictions: Restrictions::empty(),
366 recurse_into_file_modules,
367 directory: Directory {
368 path: Cow::from(PathBuf::new()),
369 ownership: DirectoryOwnership::Owned { relative: None }
371 root_module_name: None,
372 expected_tokens: Vec::new(),
373 token_cursor: TokenCursor {
374 frame: TokenCursorFrame::new(
381 desugar_doc_comments,
383 unmatched_angle_bracket_count: 0,
384 max_angle_bracket_count: 0,
385 unclosed_delims: Vec::new(),
386 last_unexpected_token_span: None,
387 last_type_ascription: None,
391 parser.token = parser.next_tok();
393 if let Some(directory) = directory {
394 parser.directory = directory;
395 } else if !parser.token.span.is_dummy() {
396 if let Some(FileName::Real(path)) =
397 &sess.source_map().lookup_char_pos(parser.token.span.lo()).file.unmapped_path {
398 if let Some(directory_path) = path.parent() {
399 parser.directory.path = Cow::from(directory_path.to_path_buf());
404 parser.process_potential_macro_variable();
408 fn next_tok(&mut self) -> Token {
409 let mut next = if self.desugar_doc_comments {
410 self.token_cursor.next_desugared()
412 self.token_cursor.next()
414 if next.span.is_dummy() {
415 // Tweak the location for better diagnostics, but keep syntactic context intact.
416 next.span = self.prev_span.with_ctxt(next.span.ctxt());
421 /// Converts the current token to a string using `self`'s reader.
422 pub fn this_token_to_string(&self) -> String {
423 pprust::token_to_string(&self.token)
426 fn token_descr(&self) -> Option<&'static str> {
427 Some(match &self.token.kind {
428 _ if self.token.is_special_ident() => "reserved identifier",
429 _ if self.token.is_used_keyword() => "keyword",
430 _ if self.token.is_unused_keyword() => "reserved keyword",
431 token::DocComment(..) => "doc comment",
436 pub(super) fn this_token_descr(&self) -> String {
437 if let Some(prefix) = self.token_descr() {
438 format!("{} `{}`", prefix, self.this_token_to_string())
440 format!("`{}`", self.this_token_to_string())
444 crate fn unexpected<T>(&mut self) -> PResult<'a, T> {
445 match self.expect_one_of(&[], &[]) {
447 // We can get `Ok(true)` from `recover_closing_delimiter`
448 // which is called in `expected_one_of_not_found`.
449 Ok(_) => FatalError.raise(),
453 /// Expects and consumes the token `t`. Signals an error if the next token is not `t`.
454 pub fn expect(&mut self, t: &TokenKind) -> PResult<'a, bool /* recovered */> {
455 if self.expected_tokens.is_empty() {
456 if self.token == *t {
460 self.unexpected_try_recover(t)
463 self.expect_one_of(slice::from_ref(t), &[])
467 /// Expect next token to be edible or inedible token. If edible,
468 /// then consume it; if inedible, then return without consuming
469 /// anything. Signal a fatal error if next token is unexpected.
470 pub fn expect_one_of(
472 edible: &[TokenKind],
473 inedible: &[TokenKind],
474 ) -> PResult<'a, bool /* recovered */> {
475 if edible.contains(&self.token.kind) {
478 } else if inedible.contains(&self.token.kind) {
479 // leave it in the input
481 } else if self.last_unexpected_token_span == Some(self.token.span) {
484 self.expected_one_of_not_found(edible, inedible)
488 fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
489 self.parse_ident_common(true)
492 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, ast::Ident> {
493 match self.token.kind {
494 token::Ident(name, _) => {
495 if self.token.is_reserved_ident() {
496 let mut err = self.expected_ident_found();
503 let span = self.token.span;
505 Ok(Ident::new(name, span))
508 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
509 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
511 self.expected_ident_found()
517 /// Checks if the next token is `tok`, and returns `true` if so.
519 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
521 fn check(&mut self, tok: &TokenKind) -> bool {
522 let is_present = self.token == *tok;
523 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
527 /// Consumes a token 'tok' if it exists. Returns whether the given token was present.
528 pub fn eat(&mut self, tok: &TokenKind) -> bool {
529 let is_present = self.check(tok);
530 if is_present { self.bump() }
534 /// If the next token is the given keyword, returns `true` without eating it.
535 /// An expectation is also added for diagnostics purposes.
536 fn check_keyword(&mut self, kw: Symbol) -> bool {
537 self.expected_tokens.push(TokenType::Keyword(kw));
538 self.token.is_keyword(kw)
541 /// If the next token is the given keyword, eats it and returns `true`.
542 /// Otherwise, returns `false`. An expectation is also added for diagnostics purposes.
543 fn eat_keyword(&mut self, kw: Symbol) -> bool {
544 if self.check_keyword(kw) {
552 fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool {
553 if self.token.is_keyword(kw) {
561 /// If the given word is not a keyword, signals an error.
562 /// If the next token is not the given word, signals an error.
563 /// Otherwise, eats it.
564 fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> {
565 if !self.eat_keyword(kw) {
572 fn check_or_expected(&mut self, ok: bool, typ: TokenType) -> bool {
576 self.expected_tokens.push(typ);
581 fn check_ident(&mut self) -> bool {
582 self.check_or_expected(self.token.is_ident(), TokenType::Ident)
585 fn check_path(&mut self) -> bool {
586 self.check_or_expected(self.token.is_path_start(), TokenType::Path)
589 fn check_type(&mut self) -> bool {
590 self.check_or_expected(self.token.can_begin_type(), TokenType::Type)
593 fn check_const_arg(&mut self) -> bool {
594 self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const)
597 /// Checks to see if the next token is either `+` or `+=`.
598 /// Otherwise returns `false`.
599 fn check_plus(&mut self) -> bool {
600 self.check_or_expected(
601 self.token.is_like_plus(),
602 TokenType::Token(token::BinOp(token::Plus)),
606 /// Expects and consumes a `+`. if `+=` is seen, replaces it with a `=`
607 /// and continues. If a `+` is not seen, returns `false`.
609 /// This is used when token-splitting `+=` into `+`.
610 /// See issue #47856 for an example of when this may occur.
611 fn eat_plus(&mut self) -> bool {
612 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
613 match self.token.kind {
614 token::BinOp(token::Plus) => {
618 token::BinOpEq(token::Plus) => {
619 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
620 self.bump_with(token::Eq, span);
627 /// Expects and consumes an `&`. If `&&` is seen, replaces it with a single
628 /// `&` and continues. If an `&` is not seen, signals an error.
629 fn expect_and(&mut self) -> PResult<'a, ()> {
630 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
631 match self.token.kind {
632 token::BinOp(token::And) => {
637 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
638 Ok(self.bump_with(token::BinOp(token::And), span))
640 _ => self.unexpected()
644 /// Expects and consumes an `|`. If `||` is seen, replaces it with a single
645 /// `|` and continues. If an `|` is not seen, signals an error.
646 fn expect_or(&mut self) -> PResult<'a, ()> {
647 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or)));
648 match self.token.kind {
649 token::BinOp(token::Or) => {
654 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
655 Ok(self.bump_with(token::BinOp(token::Or), span))
657 _ => self.unexpected()
661 /// Attempts to consume a `<`. If `<<` is seen, replaces it with a single
662 /// `<` and continue. If `<-` is seen, replaces it with a single `<`
663 /// and continue. If a `<` is not seen, returns false.
665 /// This is meant to be used when parsing generics on a path to get the
667 fn eat_lt(&mut self) -> bool {
668 self.expected_tokens.push(TokenType::Token(token::Lt));
669 let ate = match self.token.kind {
674 token::BinOp(token::Shl) => {
675 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
676 self.bump_with(token::Lt, span);
680 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
681 self.bump_with(token::BinOp(token::Minus), span);
688 // See doc comment for `unmatched_angle_bracket_count`.
689 self.unmatched_angle_bracket_count += 1;
690 self.max_angle_bracket_count += 1;
691 debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count);
697 fn expect_lt(&mut self) -> PResult<'a, ()> {
705 /// Expects and consumes a single `>` token. if a `>>` is seen, replaces it
706 /// with a single `>` and continues. If a `>` is not seen, signals an error.
707 fn expect_gt(&mut self) -> PResult<'a, ()> {
708 self.expected_tokens.push(TokenType::Token(token::Gt));
709 let ate = match self.token.kind {
714 token::BinOp(token::Shr) => {
715 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
716 Some(self.bump_with(token::Gt, span))
718 token::BinOpEq(token::Shr) => {
719 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
720 Some(self.bump_with(token::Ge, span))
723 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
724 Some(self.bump_with(token::Eq, span))
731 // See doc comment for `unmatched_angle_bracket_count`.
732 if self.unmatched_angle_bracket_count > 0 {
733 self.unmatched_angle_bracket_count -= 1;
734 debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count);
739 None => self.unexpected(),
743 /// Parses a sequence, including the closing delimiter. The function
744 /// `f` must consume tokens until reaching the next separator or
746 fn parse_seq_to_end<T>(
750 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
751 ) -> PResult<'a, Vec<T>> {
752 let (val, _, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
759 /// Parses a sequence, not including the closing delimiter. The function
760 /// `f` must consume tokens until reaching the next separator or
762 fn parse_seq_to_before_end<T>(
766 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
767 ) -> PResult<'a, (Vec<T>, bool, bool)> {
768 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
771 fn expect_any_with_type(&mut self, kets: &[&TokenKind], expect: TokenExpectType) -> bool {
772 kets.iter().any(|k| {
774 TokenExpectType::Expect => self.check(k),
775 TokenExpectType::NoExpect => self.token == **k,
780 fn parse_seq_to_before_tokens<T>(
784 expect: TokenExpectType,
785 mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
786 ) -> PResult<'a, (Vec<T>, bool /* trailing */, bool /* recovered */)> {
787 let mut first = true;
788 let mut recovered = false;
789 let mut trailing = false;
791 while !self.expect_any_with_type(kets, expect) {
792 if let token::CloseDelim(..) | token::Eof = self.token.kind {
795 if let Some(ref t) = sep.sep {
799 match self.expect(t) {
805 Err(mut expect_err) => {
806 let sp = self.sess.source_map().next_point(self.prev_span);
807 let token_str = pprust::token_kind_to_string(t);
809 // Attempt to keep parsing if it was a similar separator.
810 if let Some(ref tokens) = t.similar_tokens() {
811 if tokens.contains(&self.token.kind) {
816 // Attempt to keep parsing if it was an omitted separator.
819 // Parsed successfully, therefore most probably the code only
820 // misses a separator.
822 .span_suggestion_short(
824 &format!("missing `{}`", token_str),
826 Applicability::MaybeIncorrect,
834 // Parsing failed, therefore it must be something more serious
835 // than just a missing separator.
846 if sep.trailing_sep_allowed && self.expect_any_with_type(kets, expect) {
855 Ok((v, trailing, recovered))
858 /// Parses a sequence, including the closing delimiter. The function
859 /// `f` must consume tokens until reaching the next separator or
861 fn parse_unspanned_seq<T>(
866 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
867 ) -> PResult<'a, (Vec<T>, bool)> {
869 let (result, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
873 Ok((result, trailing))
876 fn parse_delim_comma_seq<T>(
879 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
880 ) -> PResult<'a, (Vec<T>, bool)> {
881 self.parse_unspanned_seq(
882 &token::OpenDelim(delim),
883 &token::CloseDelim(delim),
884 SeqSep::trailing_allowed(token::Comma),
889 fn parse_paren_comma_seq<T>(
891 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
892 ) -> PResult<'a, (Vec<T>, bool)> {
893 self.parse_delim_comma_seq(token::Paren, f)
896 /// Advance the parser by one token.
897 pub fn bump(&mut self) {
898 if self.prev_token_kind == PrevTokenKind::Eof {
899 // Bumping after EOF is a bad sign, usually an infinite loop.
900 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
903 self.prev_span = self.meta_var_span.take().unwrap_or(self.token.span);
905 // Record last token kind for possible error recovery.
906 self.prev_token_kind = match self.token.kind {
907 token::DocComment(..) => PrevTokenKind::DocComment,
908 token::Comma => PrevTokenKind::Comma,
909 token::BinOp(token::Plus) => PrevTokenKind::Plus,
910 token::BinOp(token::Or) => PrevTokenKind::BitOr,
911 token::Interpolated(..) => PrevTokenKind::Interpolated,
912 token::Eof => PrevTokenKind::Eof,
913 token::Ident(..) => PrevTokenKind::Ident,
914 _ => PrevTokenKind::Other,
917 self.token = self.next_tok();
918 self.expected_tokens.clear();
919 // Check after each token.
920 self.process_potential_macro_variable();
923 /// Advances the parser using provided token as a next one. Use this when
924 /// consuming a part of a token. For example a single `<` from `<<`.
925 fn bump_with(&mut self, next: TokenKind, span: Span) {
926 self.prev_span = self.token.span.with_hi(span.lo());
927 // It would be incorrect to record the kind of the current token, but
928 // fortunately for tokens currently using `bump_with`, the
929 // `prev_token_kind` will be of no use anyway.
930 self.prev_token_kind = PrevTokenKind::Other;
931 self.token = Token::new(next, span);
932 self.expected_tokens.clear();
935 /// Look-ahead `dist` tokens of `self.token` and get access to that token there.
936 /// When `dist == 0` then the current token is looked at.
937 pub fn look_ahead<R>(&self, dist: usize, looker: impl FnOnce(&Token) -> R) -> R {
939 return looker(&self.token);
942 let frame = &self.token_cursor.frame;
943 looker(&match frame.tree_cursor.look_ahead(dist - 1) {
944 Some(tree) => match tree {
945 TokenTree::Token(token) => token,
946 TokenTree::Delimited(dspan, delim, _) =>
947 Token::new(token::OpenDelim(delim), dspan.open),
949 None => Token::new(token::CloseDelim(frame.delim), frame.span.close)
953 /// Returns whether any of the given keywords are `dist` tokens ahead of the current one.
954 fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool {
955 self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw)))
958 /// Parses asyncness: `async` or nothing.
959 fn parse_asyncness(&mut self) -> IsAsync {
960 if self.eat_keyword(kw::Async) {
962 closure_id: DUMMY_NODE_ID,
963 return_impl_trait_id: DUMMY_NODE_ID,
970 /// Parses unsafety: `unsafe` or nothing.
971 fn parse_unsafety(&mut self) -> Unsafety {
972 if self.eat_keyword(kw::Unsafe) {
979 /// Parses mutability (`mut` or nothing).
980 fn parse_mutability(&mut self) -> Mutability {
981 if self.eat_keyword(kw::Mut) {
984 Mutability::Immutable
988 /// Possibly parses mutability (`const` or `mut`).
989 fn parse_const_or_mut(&mut self) -> Option<Mutability> {
990 if self.eat_keyword(kw::Mut) {
991 Some(Mutability::Mutable)
992 } else if self.eat_keyword(kw::Const) {
993 Some(Mutability::Immutable)
999 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
1000 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) =
1002 self.expect_no_suffix(self.token.span, "a tuple index", suffix);
1004 Ok(Ident::new(symbol, self.prev_span))
1006 self.parse_ident_common(false)
1010 fn parse_mac_args(&mut self) -> PResult<'a, P<MacArgs>> {
1011 self.parse_mac_args_common(true).map(P)
1014 fn parse_attr_args(&mut self) -> PResult<'a, MacArgs> {
1015 self.parse_mac_args_common(false)
1018 fn parse_mac_args_common(&mut self, delimited_only: bool) -> PResult<'a, MacArgs> {
1019 Ok(if self.check(&token::OpenDelim(DelimToken::Paren)) ||
1020 self.check(&token::OpenDelim(DelimToken::Bracket)) ||
1021 self.check(&token::OpenDelim(DelimToken::Brace)) {
1022 match self.parse_token_tree() {
1023 TokenTree::Delimited(dspan, delim, tokens) =>
1024 // We've confirmed above that there is a delimiter so unwrapping is OK.
1025 MacArgs::Delimited(dspan, MacDelimiter::from_token(delim).unwrap(), tokens),
1026 _ => unreachable!(),
1028 } else if !delimited_only {
1029 if self.eat(&token::Eq) {
1030 let eq_span = self.prev_span;
1031 let mut is_interpolated_expr = false;
1032 if let token::Interpolated(nt) = &self.token.kind {
1033 if let token::NtExpr(..) = **nt {
1034 is_interpolated_expr = true;
1037 let token_tree = if is_interpolated_expr {
1038 // We need to accept arbitrary interpolated expressions to continue
1039 // supporting things like `doc = $expr` that work on stable.
1040 // Non-literal interpolated expressions are rejected after expansion.
1041 self.parse_token_tree()
1043 self.parse_unsuffixed_lit()?.token_tree()
1046 MacArgs::Eq(eq_span, token_tree.into())
1051 return self.unexpected();
1055 fn parse_or_use_outer_attributes(
1057 already_parsed_attrs: Option<ThinVec<Attribute>>,
1058 ) -> PResult<'a, ThinVec<Attribute>> {
1059 if let Some(attrs) = already_parsed_attrs {
1062 self.parse_outer_attributes().map(|a| a.into())
1066 pub fn process_potential_macro_variable(&mut self) {
1067 self.token = match self.token.kind {
1068 token::Dollar if self.token.span.from_expansion() &&
1069 self.look_ahead(1, |t| t.is_ident()) => {
1071 let name = match self.token.kind {
1072 token::Ident(name, _) => name,
1075 let span = self.prev_span.to(self.token.span);
1077 .struct_span_fatal(span, &format!("unknown macro variable `{}`", name))
1078 .span_label(span, "unknown macro variable")
1083 token::Interpolated(ref nt) => {
1084 self.meta_var_span = Some(self.token.span);
1085 // Interpolated identifier and lifetime tokens are replaced with usual identifier
1086 // and lifetime tokens, so the former are never encountered during normal parsing.
1088 token::NtIdent(ident, is_raw) =>
1089 Token::new(token::Ident(ident.name, is_raw), ident.span),
1090 token::NtLifetime(ident) =>
1091 Token::new(token::Lifetime(ident.name), ident.span),
1099 /// Parses a single token tree from the input.
1100 pub fn parse_token_tree(&mut self) -> TokenTree {
1101 match self.token.kind {
1102 token::OpenDelim(..) => {
1103 let frame = mem::replace(&mut self.token_cursor.frame,
1104 self.token_cursor.stack.pop().unwrap());
1105 self.token.span = frame.span.entire();
1107 TokenTree::Delimited(
1110 frame.tree_cursor.stream.into(),
1113 token::CloseDelim(_) | token::Eof => unreachable!(),
1115 let token = self.token.take();
1117 TokenTree::Token(token)
1122 /// Parses a stream of tokens into a list of `TokenTree`s, up to EOF.
1123 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
1124 let mut tts = Vec::new();
1125 while self.token != token::Eof {
1126 tts.push(self.parse_token_tree());
1131 pub fn parse_tokens(&mut self) -> TokenStream {
1132 let mut result = Vec::new();
1134 match self.token.kind {
1135 token::Eof | token::CloseDelim(..) => break,
1136 _ => result.push(self.parse_token_tree().into()),
1139 TokenStream::new(result)
1142 /// Evaluates the closure with restrictions in place.
1144 /// Afters the closure is evaluated, restrictions are reset.
1145 fn with_res<T>(&mut self, res: Restrictions, f: impl FnOnce(&mut Self) -> T) -> T {
1146 let old = self.restrictions;
1147 self.restrictions = res;
1149 self.restrictions = old;
1153 fn is_crate_vis(&self) -> bool {
1154 self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
1157 /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
1158 /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
1159 /// If the following element can't be a tuple (i.e., it's a function definition), then
1160 /// it's not a tuple struct field), and the contents within the parentheses isn't valid,
1161 /// so emit a proper diagnostic.
1162 pub fn parse_visibility(&mut self, fbt: FollowedByType) -> PResult<'a, Visibility> {
1163 maybe_whole!(self, NtVis, |x| x);
1165 self.expected_tokens.push(TokenType::Keyword(kw::Crate));
1166 if self.is_crate_vis() {
1167 self.bump(); // `crate`
1168 self.sess.gated_spans.gate(sym::crate_visibility_modifier, self.prev_span);
1169 return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
1172 if !self.eat_keyword(kw::Pub) {
1173 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
1174 // keyword to grab a span from for inherited visibility; an empty span at the
1175 // beginning of the current token would seem to be the "Schelling span".
1176 return Ok(respan(self.token.span.shrink_to_lo(), VisibilityKind::Inherited))
1178 let lo = self.prev_span;
1180 if self.check(&token::OpenDelim(token::Paren)) {
1181 // We don't `self.bump()` the `(` yet because this might be a struct definition where
1182 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
1183 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
1184 // by the following tokens.
1185 if self.is_keyword_ahead(1, &[kw::Crate])
1186 && self.look_ahead(2, |t| t != &token::ModSep) // account for `pub(crate::foo)`
1188 // Parse `pub(crate)`.
1190 self.bump(); // `crate`
1191 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1192 let vis = VisibilityKind::Crate(CrateSugar::PubCrate);
1193 return Ok(respan(lo.to(self.prev_span), vis));
1194 } else if self.is_keyword_ahead(1, &[kw::In]) {
1195 // Parse `pub(in path)`.
1197 self.bump(); // `in`
1198 let path = self.parse_path(PathStyle::Mod)?; // `path`
1199 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1200 let vis = VisibilityKind::Restricted {
1202 id: ast::DUMMY_NODE_ID,
1204 return Ok(respan(lo.to(self.prev_span), vis));
1205 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren))
1206 && self.is_keyword_ahead(1, &[kw::Super, kw::SelfLower])
1208 // Parse `pub(self)` or `pub(super)`.
1210 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
1211 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1212 let vis = VisibilityKind::Restricted {
1214 id: ast::DUMMY_NODE_ID,
1216 return Ok(respan(lo.to(self.prev_span), vis));
1217 } else if let FollowedByType::No = fbt {
1218 // Provide this diagnostic if a type cannot follow;
1219 // in particular, if this is not a tuple struct.
1220 self.recover_incorrect_vis_restriction()?;
1221 // Emit diagnostic, but continue with public visibility.
1225 Ok(respan(lo, VisibilityKind::Public))
1228 /// Recovery for e.g. `pub(something) fn ...` or `struct X { pub(something) y: Z }`
1229 fn recover_incorrect_vis_restriction(&mut self) -> PResult<'a, ()> {
1231 let path = self.parse_path(PathStyle::Mod)?;
1232 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1234 let msg = "incorrect visibility restriction";
1235 let suggestion = r##"some possible visibility restrictions are:
1236 `pub(crate)`: visible only on the current crate
1237 `pub(super)`: visible only in the current module's parent
1238 `pub(in path::to::module)`: visible only on the specified path"##;
1240 let path_str = pprust::path_to_string(&path);
1242 struct_span_err!(self.sess.span_diagnostic, path.span, E0704, "{}", msg)
1246 &format!("make this visible only to module `{}` with `in`", path_str),
1247 format!("in {}", path_str),
1248 Applicability::MachineApplicable,
1255 /// Parses `extern string_literal?`.
1256 fn parse_extern(&mut self) -> PResult<'a, Extern> {
1257 Ok(if self.eat_keyword(kw::Extern) {
1258 Extern::from_abi(self.parse_abi())
1264 /// Parses a string literal as an ABI spec.
1265 fn parse_abi(&mut self) -> Option<StrLit> {
1266 match self.parse_str_lit() {
1267 Ok(str_lit) => Some(str_lit),
1268 Err(Some(lit)) => match lit.kind {
1269 ast::LitKind::Err(_) => None,
1271 self.struct_span_err(lit.span, "non-string ABI literal")
1274 "specify the ABI with a string literal",
1275 "\"C\"".to_string(),
1276 Applicability::MaybeIncorrect,
1286 /// We are parsing `async fn`. If we are on Rust 2015, emit an error.
1287 fn ban_async_in_2015(&self, async_span: Span) {
1288 if async_span.rust_2015() {
1293 "`async fn` is not permitted in the 2015 edition",
1299 fn collect_tokens<R>(
1301 f: impl FnOnce(&mut Self) -> PResult<'a, R>,
1302 ) -> PResult<'a, (R, TokenStream)> {
1303 // Record all tokens we parse when parsing this item.
1304 let mut tokens = Vec::new();
1305 let prev_collecting = match self.token_cursor.frame.last_token {
1306 LastToken::Collecting(ref mut list) => {
1307 Some(mem::take(list))
1309 LastToken::Was(ref mut last) => {
1310 tokens.extend(last.take());
1314 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
1315 let prev = self.token_cursor.stack.len();
1317 let last_token = if self.token_cursor.stack.len() == prev {
1318 &mut self.token_cursor.frame.last_token
1319 } else if self.token_cursor.stack.get(prev).is_none() {
1320 // This can happen due to a bad interaction of two unrelated recovery mechanisms with
1321 // mismatched delimiters *and* recovery lookahead on the likely typo `pub ident(`
1323 return Ok((ret?, TokenStream::default()));
1325 &mut self.token_cursor.stack[prev].last_token
1328 // Pull out the tokens that we've collected from the call to `f` above.
1329 let mut collected_tokens = match *last_token {
1330 LastToken::Collecting(ref mut v) => mem::take(v),
1331 LastToken::Was(ref was) => {
1332 let msg = format!("our vector went away? - found Was({:?})", was);
1333 debug!("collect_tokens: {}", msg);
1334 self.sess.span_diagnostic.delay_span_bug(self.token.span, &msg);
1335 // This can happen due to a bad interaction of two unrelated recovery mechanisms
1336 // with mismatched delimiters *and* recovery lookahead on the likely typo
1337 // `pub ident(` (#62895, different but similar to the case above).
1338 return Ok((ret?, TokenStream::default()));
1342 // If we're not at EOF our current token wasn't actually consumed by
1343 // `f`, but it'll still be in our list that we pulled out. In that case
1345 let extra_token = if self.token != token::Eof {
1346 collected_tokens.pop()
1351 // If we were previously collecting tokens, then this was a recursive
1352 // call. In that case we need to record all the tokens we collected in
1353 // our parent list as well. To do that we push a clone of our stream
1354 // onto the previous list.
1355 match prev_collecting {
1357 list.extend(collected_tokens.iter().cloned());
1358 list.extend(extra_token);
1359 *last_token = LastToken::Collecting(list);
1362 *last_token = LastToken::Was(extra_token);
1366 Ok((ret?, TokenStream::new(collected_tokens)))
1370 fn is_import_coupler(&mut self) -> bool {
1371 self.check(&token::ModSep) &&
1372 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
1373 *t == token::BinOp(token::Star))
1377 crate fn make_unclosed_delims_error(
1378 unmatched: UnmatchedBrace,
1380 ) -> Option<DiagnosticBuilder<'_>> {
1381 // `None` here means an `Eof` was found. We already emit those errors elsewhere, we add them to
1382 // `unmatched_braces` only for error recovery in the `Parser`.
1383 let found_delim = unmatched.found_delim?;
1384 let mut err = sess.span_diagnostic.struct_span_err(unmatched.found_span, &format!(
1385 "incorrect close delimiter: `{}`",
1386 pprust::token_kind_to_string(&token::CloseDelim(found_delim)),
1388 err.span_label(unmatched.found_span, "incorrect close delimiter");
1389 if let Some(sp) = unmatched.candidate_span {
1390 err.span_label(sp, "close delimiter possibly meant for this");
1392 if let Some(sp) = unmatched.unclosed_span {
1393 err.span_label(sp, "un-closed delimiter");
1398 pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, sess: &ParseSess) {
1399 *sess.reached_eof.borrow_mut() |= unclosed_delims.iter()
1400 .any(|unmatched_delim| unmatched_delim.found_delim.is_none());
1401 for unmatched in unclosed_delims.drain(..) {
1402 make_unclosed_delims_error(unmatched, sess).map(|mut e| e.emit());