5 pub use module::{ModulePath, ModulePathSuccess};
9 pub use path::PathStyle;
13 use diagnostics::Error;
15 use crate::lexer::UnmatchedBrace;
16 use crate::{Directory, DirectoryOwnership};
19 use rustc_ast_pretty::pprust;
20 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder, FatalError, PResult};
21 use rustc_session::parse::ParseSess;
22 use rustc_span::source_map::respan;
23 use rustc_span::symbol::{kw, sym, Symbol};
24 use rustc_span::{FileName, Span, DUMMY_SP};
25 use syntax::ast::{self, AttrStyle, AttrVec, CrateSugar, Extern, Ident, Unsafety, DUMMY_NODE_ID};
26 use syntax::ast::{IsAsync, MacArgs, MacDelimiter, Mutability, StrLit, Visibility, VisibilityKind};
28 use syntax::token::{self, DelimToken, Token, TokenKind};
29 use syntax::tokenstream::{self, DelimSpan, TokenStream, TokenTree, TreeAndJoint};
30 use syntax::util::comments::{doc_comment_style, strip_doc_comment_decoration};
33 use std::path::PathBuf;
34 use std::{cmp, mem, slice};
37 struct Restrictions: u8 {
38 const STMT_EXPR = 1 << 0;
39 const NO_STRUCT_LITERAL = 1 << 1;
43 #[derive(Clone, Copy, PartialEq, Debug)]
50 #[derive(Clone, Copy, PartialEq, Debug)]
56 /// Like `maybe_whole_expr`, but for things other than expressions.
58 macro_rules! maybe_whole {
59 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
60 if let token::Interpolated(nt) = &$p.token.kind {
61 if let token::$constructor(x) = &**nt {
70 /// If the next tokens are ill-formed `$ty::` recover them as `<$ty>::`.
72 macro_rules! maybe_recover_from_interpolated_ty_qpath {
73 ($self: expr, $allow_qpath_recovery: expr) => {
74 if $allow_qpath_recovery && $self.look_ahead(1, |t| t == &token::ModSep) {
75 if let token::Interpolated(nt) = &$self.token.kind {
76 if let token::NtTy(ty) = &**nt {
79 return $self.maybe_recover_from_bad_qpath_stage_2($self.prev_span, ty);
86 #[derive(Debug, Clone, Copy, PartialEq)]
98 // NOTE: `Ident`s are handled by `common.rs`.
101 pub struct Parser<'a> {
102 pub sess: &'a ParseSess,
103 /// The current normalized token.
104 /// "Normalized" means that some interpolated tokens
105 /// (`$i: ident` and `$l: lifetime` meta-variables) are replaced
106 /// with non-interpolated identifier and lifetime tokens they refer to.
107 /// Perhaps the normalized / non-normalized setup can be simplified somehow.
109 /// The span of the current non-normalized token.
110 meta_var_span: Option<Span>,
111 /// The span of the previous non-normalized token.
113 /// The kind of the previous normalized token (in simplified form).
114 prev_token_kind: PrevTokenKind,
115 restrictions: Restrictions,
116 /// Used to determine the path to externally loaded source files.
117 pub(super) directory: Directory<'a>,
118 /// `true` to parse sub-modules in other files.
119 // Public for rustfmt usage.
120 pub recurse_into_file_modules: bool,
121 /// Name of the root module this parser originated from. If `None`, then the
122 /// name is not known. This does not change while the parser is descending
123 /// into modules, and sub-parsers have new values for this name.
124 pub root_module_name: Option<String>,
125 expected_tokens: Vec<TokenType>,
126 token_cursor: TokenCursor,
127 desugar_doc_comments: bool,
128 /// `true` we should configure out of line modules as we parse.
129 // Public for rustfmt usage.
131 /// This field is used to keep track of how many left angle brackets we have seen. This is
132 /// required in order to detect extra leading left angle brackets (`<` characters) and error
135 /// See the comments in the `parse_path_segment` function for more details.
136 unmatched_angle_bracket_count: u32,
137 max_angle_bracket_count: u32,
138 /// A list of all unclosed delimiters found by the lexer. If an entry is used for error recovery
139 /// it gets removed from here. Every entry left at the end gets emitted as an independent
141 pub(super) unclosed_delims: Vec<UnmatchedBrace>,
142 last_unexpected_token_span: Option<Span>,
143 pub last_type_ascription: Option<(Span, bool /* likely path typo */)>,
144 /// If present, this `Parser` is not parsing Rust code but rather a macro call.
145 subparser_name: Option<&'static str>,
148 impl<'a> Drop for Parser<'a> {
150 emit_unclosed_delims(&mut self.unclosed_delims, &self.sess);
156 frame: TokenCursorFrame,
157 stack: Vec<TokenCursorFrame>,
161 struct TokenCursorFrame {
162 delim: token::DelimToken,
165 tree_cursor: tokenstream::Cursor,
167 last_token: LastToken,
170 /// This is used in `TokenCursorFrame` above to track tokens that are consumed
171 /// by the parser, and then that's transitively used to record the tokens that
172 /// each parse AST item is created with.
174 /// Right now this has two states, either collecting tokens or not collecting
175 /// tokens. If we're collecting tokens we just save everything off into a local
176 /// `Vec`. This should eventually though likely save tokens from the original
177 /// token stream and just use slicing of token streams to avoid creation of a
178 /// whole new vector.
180 /// The second state is where we're passively not recording tokens, but the last
181 /// token is still tracked for when we want to start recording tokens. This
182 /// "last token" means that when we start recording tokens we'll want to ensure
183 /// that this, the first token, is included in the output.
185 /// You can find some more example usage of this in the `collect_tokens` method
189 Collecting(Vec<TreeAndJoint>),
190 Was(Option<TreeAndJoint>),
193 impl TokenCursorFrame {
194 fn new(span: DelimSpan, delim: DelimToken, tts: &TokenStream) -> Self {
198 open_delim: delim == token::NoDelim,
199 tree_cursor: tts.clone().into_trees(),
200 close_delim: delim == token::NoDelim,
201 last_token: LastToken::Was(None),
207 fn next(&mut self) -> Token {
209 let tree = if !self.frame.open_delim {
210 self.frame.open_delim = true;
211 TokenTree::open_tt(self.frame.span, self.frame.delim)
212 } else if let Some(tree) = self.frame.tree_cursor.next() {
214 } else if !self.frame.close_delim {
215 self.frame.close_delim = true;
216 TokenTree::close_tt(self.frame.span, self.frame.delim)
217 } else if let Some(frame) = self.stack.pop() {
221 return Token::new(token::Eof, DUMMY_SP);
224 match self.frame.last_token {
225 LastToken::Collecting(ref mut v) => v.push(tree.clone().into()),
226 LastToken::Was(ref mut t) => *t = Some(tree.clone().into()),
230 TokenTree::Token(token) => return token,
231 TokenTree::Delimited(sp, delim, tts) => {
232 let frame = TokenCursorFrame::new(sp, delim, &tts);
233 self.stack.push(mem::replace(&mut self.frame, frame));
239 fn next_desugared(&mut self) -> Token {
240 let (name, sp) = match self.next() {
241 Token { kind: token::DocComment(name), span } => (name, span),
245 let stripped = strip_doc_comment_decoration(&name.as_str());
247 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
248 // required to wrap the text.
249 let mut num_of_hashes = 0;
251 for ch in stripped.chars() {
254 '#' if count > 0 => count + 1,
257 num_of_hashes = cmp::max(num_of_hashes, count);
260 let delim_span = DelimSpan::from_single(sp);
261 let body = TokenTree::Delimited(
265 TokenTree::token(token::Ident(sym::doc, false), sp),
266 TokenTree::token(token::Eq, sp),
268 TokenKind::lit(token::StrRaw(num_of_hashes), Symbol::intern(&stripped), None),
274 .collect::<TokenStream>()
278 self.stack.push(mem::replace(
280 TokenCursorFrame::new(
283 &if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
284 [TokenTree::token(token::Pound, sp), TokenTree::token(token::Not, sp), body]
287 .collect::<TokenStream>()
289 [TokenTree::token(token::Pound, sp), body]
292 .collect::<TokenStream>()
301 #[derive(Clone, PartialEq)]
314 fn to_string(&self) -> String {
316 TokenType::Token(ref t) => format!("`{}`", pprust::token_kind_to_string(t)),
317 TokenType::Keyword(kw) => format!("`{}`", kw),
318 TokenType::Operator => "an operator".to_string(),
319 TokenType::Lifetime => "lifetime".to_string(),
320 TokenType::Ident => "identifier".to_string(),
321 TokenType::Path => "path".to_string(),
322 TokenType::Type => "type".to_string(),
323 TokenType::Const => "const".to_string(),
328 #[derive(Copy, Clone, Debug)]
329 enum TokenExpectType {
334 /// A sequence separator.
336 /// The separator token.
337 sep: Option<TokenKind>,
338 /// `true` if a trailing separator is allowed.
339 trailing_sep_allowed: bool,
343 fn trailing_allowed(t: TokenKind) -> SeqSep {
344 SeqSep { sep: Some(t), trailing_sep_allowed: true }
347 fn none() -> SeqSep {
348 SeqSep { sep: None, trailing_sep_allowed: false }
352 pub enum FollowedByType {
357 fn token_descr_opt(token: &Token) -> Option<&'static str> {
358 Some(match token.kind {
359 _ if token.is_special_ident() => "reserved identifier",
360 _ if token.is_used_keyword() => "keyword",
361 _ if token.is_unused_keyword() => "reserved keyword",
362 token::DocComment(..) => "doc comment",
367 pub(super) fn token_descr(token: &Token) -> String {
368 let token_str = pprust::token_to_string(token);
369 match token_descr_opt(token) {
370 Some(prefix) => format!("{} `{}`", prefix, token_str),
371 _ => format!("`{}`", token_str),
375 impl<'a> Parser<'a> {
379 directory: Option<Directory<'a>>,
380 recurse_into_file_modules: bool,
381 desugar_doc_comments: bool,
382 subparser_name: Option<&'static str>,
384 let mut parser = Parser {
386 token: Token::dummy(),
389 prev_token_kind: PrevTokenKind::Other,
390 restrictions: Restrictions::empty(),
391 recurse_into_file_modules,
392 directory: Directory {
393 path: Cow::from(PathBuf::new()),
394 ownership: DirectoryOwnership::Owned { relative: None },
396 root_module_name: None,
397 expected_tokens: Vec::new(),
398 token_cursor: TokenCursor {
399 frame: TokenCursorFrame::new(DelimSpan::dummy(), token::NoDelim, &tokens.into()),
402 desugar_doc_comments,
404 unmatched_angle_bracket_count: 0,
405 max_angle_bracket_count: 0,
406 unclosed_delims: Vec::new(),
407 last_unexpected_token_span: None,
408 last_type_ascription: None,
412 parser.token = parser.next_tok();
414 if let Some(directory) = directory {
415 parser.directory = directory;
416 } else if !parser.token.span.is_dummy() {
417 if let Some(FileName::Real(path)) =
418 &sess.source_map().lookup_char_pos(parser.token.span.lo()).file.unmapped_path
420 if let Some(directory_path) = path.parent() {
421 parser.directory.path = Cow::from(directory_path.to_path_buf());
426 parser.process_potential_macro_variable();
430 fn next_tok(&mut self) -> Token {
431 let mut next = if self.desugar_doc_comments {
432 self.token_cursor.next_desugared()
434 self.token_cursor.next()
436 if next.span.is_dummy() {
437 // Tweak the location for better diagnostics, but keep syntactic context intact.
438 next.span = self.prev_span.with_ctxt(next.span.ctxt());
443 crate fn unexpected<T>(&mut self) -> PResult<'a, T> {
444 match self.expect_one_of(&[], &[]) {
446 // We can get `Ok(true)` from `recover_closing_delimiter`
447 // which is called in `expected_one_of_not_found`.
448 Ok(_) => FatalError.raise(),
452 /// Expects and consumes the token `t`. Signals an error if the next token is not `t`.
453 pub fn expect(&mut self, t: &TokenKind) -> PResult<'a, bool /* recovered */> {
454 if self.expected_tokens.is_empty() {
455 if self.token == *t {
459 self.unexpected_try_recover(t)
462 self.expect_one_of(slice::from_ref(t), &[])
466 /// Expect next token to be edible or inedible token. If edible,
467 /// then consume it; if inedible, then return without consuming
468 /// anything. Signal a fatal error if next token is unexpected.
469 pub fn expect_one_of(
471 edible: &[TokenKind],
472 inedible: &[TokenKind],
473 ) -> PResult<'a, bool /* recovered */> {
474 if edible.contains(&self.token.kind) {
477 } else if inedible.contains(&self.token.kind) {
478 // leave it in the input
480 } else if self.last_unexpected_token_span == Some(self.token.span) {
483 self.expected_one_of_not_found(edible, inedible)
487 // Public for rustfmt usage.
488 pub 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))
507 _ => Err(if self.prev_token_kind == PrevTokenKind::DocComment {
508 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
510 self.expected_ident_found()
515 /// Checks if the next token is `tok`, and returns `true` if so.
517 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
519 fn check(&mut self, tok: &TokenKind) -> bool {
520 let is_present = self.token == *tok;
522 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);
536 /// If the next token is the given keyword, returns `true` without eating it.
537 /// An expectation is also added for diagnostics purposes.
538 fn check_keyword(&mut self, kw: Symbol) -> bool {
539 self.expected_tokens.push(TokenType::Keyword(kw));
540 self.token.is_keyword(kw)
543 /// If the next token is the given keyword, eats it and returns `true`.
544 /// Otherwise, returns `false`. An expectation is also added for diagnostics purposes.
545 // Public for rustfmt usage.
546 pub fn eat_keyword(&mut self, kw: Symbol) -> bool {
547 if self.check_keyword(kw) {
555 fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool {
556 if self.token.is_keyword(kw) {
564 /// If the given word is not a keyword, signals an error.
565 /// If the next token is not the given word, signals an error.
566 /// Otherwise, eats it.
567 fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> {
568 if !self.eat_keyword(kw) { self.unexpected() } else { Ok(()) }
571 fn check_or_expected(&mut self, ok: bool, typ: TokenType) -> bool {
575 self.expected_tokens.push(typ);
580 fn check_ident(&mut self) -> bool {
581 self.check_or_expected(self.token.is_ident(), TokenType::Ident)
584 fn check_path(&mut self) -> bool {
585 self.check_or_expected(self.token.is_path_start(), TokenType::Path)
588 fn check_type(&mut self) -> bool {
589 self.check_or_expected(self.token.can_begin_type(), TokenType::Type)
592 fn check_const_arg(&mut self) -> bool {
593 self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const)
596 /// Checks to see if the next token is either `+` or `+=`.
597 /// Otherwise returns `false`.
598 fn check_plus(&mut self) -> bool {
599 self.check_or_expected(
600 self.token.is_like_plus(),
601 TokenType::Token(token::BinOp(token::Plus)),
605 /// Expects and consumes a `+`. if `+=` is seen, replaces it with a `=`
606 /// and continues. If a `+` is not seen, returns `false`.
608 /// This is used when token-splitting `+=` into `+`.
609 /// See issue #47856 for an example of when this may occur.
610 fn eat_plus(&mut self) -> bool {
611 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
612 match self.token.kind {
613 token::BinOp(token::Plus) => {
617 token::BinOpEq(token::Plus) => {
618 let start_point = self.sess.source_map().start_point(self.token.span);
619 self.bump_with(token::Eq, self.token.span.with_lo(start_point.hi()));
626 /// Expects and consumes an `&`. If `&&` is seen, replaces it with a single
627 /// `&` and continues. If an `&` is not seen, signals an error.
628 fn expect_and(&mut self) -> PResult<'a, ()> {
629 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
630 match self.token.kind {
631 token::BinOp(token::And) => {
636 let start_point = self.sess.source_map().start_point(self.token.span);
638 .bump_with(token::BinOp(token::And), self.token.span.with_lo(start_point.hi())))
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 start_point = self.sess.source_map().start_point(self.token.span);
656 .bump_with(token::BinOp(token::Or), self.token.span.with_lo(start_point.hi())))
658 _ => self.unexpected(),
662 /// Attempts to consume a `<`. If `<<` is seen, replaces it with a single
663 /// `<` and continue. If `<-` is seen, replaces it with a single `<`
664 /// and continue. If a `<` is not seen, returns false.
666 /// This is meant to be used when parsing generics on a path to get the
668 fn eat_lt(&mut self) -> bool {
669 self.expected_tokens.push(TokenType::Token(token::Lt));
670 let ate = match self.token.kind {
675 token::BinOp(token::Shl) => {
676 let start_point = self.sess.source_map().start_point(self.token.span);
677 self.bump_with(token::Lt, self.token.span.with_lo(start_point.hi()));
681 let start_point = self.sess.source_map().start_point(self.token.span);
683 token::BinOp(token::Minus),
684 self.token.span.with_lo(start_point.hi()),
692 // See doc comment for `unmatched_angle_bracket_count`.
693 self.unmatched_angle_bracket_count += 1;
694 self.max_angle_bracket_count += 1;
695 debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count);
701 fn expect_lt(&mut self) -> PResult<'a, ()> {
702 if !self.eat_lt() { self.unexpected() } else { Ok(()) }
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 start_point = self.sess.source_map().start_point(self.token.span);
716 Some(self.bump_with(token::Gt, self.token.span.with_lo(start_point.hi())))
718 token::BinOpEq(token::Shr) => {
719 let start_point = self.sess.source_map().start_point(self.token.span);
720 Some(self.bump_with(token::Ge, self.token.span.with_lo(start_point.hi())))
723 let start_point = self.sess.source_map().start_point(self.token.span);
724 Some(self.bump_with(token::Eq, self.token.span.with_lo(start_point.hi())))
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 fn expect_any_with_type(&mut self, kets: &[&TokenKind], expect: TokenExpectType) -> bool {
744 kets.iter().any(|k| match expect {
745 TokenExpectType::Expect => self.check(k),
746 TokenExpectType::NoExpect => self.token == **k,
750 fn parse_seq_to_before_tokens<T>(
754 expect: TokenExpectType,
755 mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
756 ) -> PResult<'a, (Vec<T>, bool /* trailing */, bool /* recovered */)> {
757 let mut first = true;
758 let mut recovered = false;
759 let mut trailing = false;
761 while !self.expect_any_with_type(kets, expect) {
762 if let token::CloseDelim(..) | token::Eof = self.token.kind {
765 if let Some(ref t) = sep.sep {
769 match self.expect(t) {
775 Err(mut expect_err) => {
776 let sp = self.prev_span.shrink_to_hi();
777 let token_str = pprust::token_kind_to_string(t);
779 // Attempt to keep parsing if it was a similar separator.
780 if let Some(ref tokens) = t.similar_tokens() {
781 if tokens.contains(&self.token.kind) {
786 // Attempt to keep parsing if it was an omitted separator.
789 // Parsed successfully, therefore most probably the code only
790 // misses a separator.
792 .span_suggestion_short(
794 &format!("missing `{}`", token_str),
796 Applicability::MaybeIncorrect,
804 // Parsing failed, therefore it must be something more serious
805 // than just a missing separator.
816 if sep.trailing_sep_allowed && self.expect_any_with_type(kets, expect) {
825 Ok((v, trailing, recovered))
828 /// Parses a sequence, not including the closing delimiter. The function
829 /// `f` must consume tokens until reaching the next separator or
831 fn parse_seq_to_before_end<T>(
835 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
836 ) -> PResult<'a, (Vec<T>, bool, bool)> {
837 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
840 /// Parses a sequence, including the closing delimiter. The function
841 /// `f` must consume tokens until reaching the next separator or
843 fn parse_seq_to_end<T>(
847 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
848 ) -> PResult<'a, (Vec<T>, bool /* trailing */)> {
849 let (val, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
856 /// Parses a sequence, including the closing delimiter. The function
857 /// `f` must consume tokens until reaching the next separator or
859 fn parse_unspanned_seq<T>(
864 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
865 ) -> PResult<'a, (Vec<T>, bool)> {
867 self.parse_seq_to_end(ket, sep, f)
870 fn parse_delim_comma_seq<T>(
873 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
874 ) -> PResult<'a, (Vec<T>, bool)> {
875 self.parse_unspanned_seq(
876 &token::OpenDelim(delim),
877 &token::CloseDelim(delim),
878 SeqSep::trailing_allowed(token::Comma),
883 fn parse_paren_comma_seq<T>(
885 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
886 ) -> PResult<'a, (Vec<T>, bool)> {
887 self.parse_delim_comma_seq(token::Paren, f)
890 /// Advance the parser by one token.
891 pub fn bump(&mut self) {
892 if self.prev_token_kind == PrevTokenKind::Eof {
893 // Bumping after EOF is a bad sign, usually an infinite loop.
894 let msg = "attempted to bump the parser past EOF (may be stuck in a loop)";
895 self.span_bug(self.token.span, msg);
898 self.prev_span = self.meta_var_span.take().unwrap_or(self.token.span);
900 // Record last token kind for possible error recovery.
901 self.prev_token_kind = match self.token.kind {
902 token::DocComment(..) => PrevTokenKind::DocComment,
903 token::Comma => PrevTokenKind::Comma,
904 token::BinOp(token::Plus) => PrevTokenKind::Plus,
905 token::BinOp(token::Or) => PrevTokenKind::BitOr,
906 token::Interpolated(..) => PrevTokenKind::Interpolated,
907 token::Eof => PrevTokenKind::Eof,
908 token::Ident(..) => PrevTokenKind::Ident,
909 _ => PrevTokenKind::Other,
912 self.token = self.next_tok();
913 self.expected_tokens.clear();
914 // Check after each token.
915 self.process_potential_macro_variable();
918 /// Advances the parser using provided token as a next one. Use this when
919 /// consuming a part of a token. For example a single `<` from `<<`.
920 fn bump_with(&mut self, next: TokenKind, span: Span) {
921 self.prev_span = self.token.span.with_hi(span.lo());
922 // It would be incorrect to record the kind of the current token, but
923 // fortunately for tokens currently using `bump_with`, the
924 // `prev_token_kind` will be of no use anyway.
925 self.prev_token_kind = PrevTokenKind::Other;
926 self.token = Token::new(next, span);
927 self.expected_tokens.clear();
930 /// Look-ahead `dist` tokens of `self.token` and get access to that token there.
931 /// When `dist == 0` then the current token is looked at.
932 pub fn look_ahead<R>(&self, dist: usize, looker: impl FnOnce(&Token) -> R) -> R {
934 return looker(&self.token);
937 let frame = &self.token_cursor.frame;
938 looker(&match frame.tree_cursor.look_ahead(dist - 1) {
939 Some(tree) => match tree {
940 TokenTree::Token(token) => token,
941 TokenTree::Delimited(dspan, delim, _) => {
942 Token::new(token::OpenDelim(delim), dspan.open)
945 None => Token::new(token::CloseDelim(frame.delim), frame.span.close),
949 /// Returns whether any of the given keywords are `dist` tokens ahead of the current one.
950 fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool {
951 self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw)))
954 /// Parses asyncness: `async` or nothing.
955 fn parse_asyncness(&mut self) -> IsAsync {
956 if self.eat_keyword(kw::Async) {
957 IsAsync::Async { closure_id: DUMMY_NODE_ID, return_impl_trait_id: DUMMY_NODE_ID }
963 /// Parses unsafety: `unsafe` or nothing.
964 fn parse_unsafety(&mut self) -> Unsafety {
965 if self.eat_keyword(kw::Unsafe) { Unsafety::Unsafe } else { Unsafety::Normal }
968 /// Parses mutability (`mut` or nothing).
969 fn parse_mutability(&mut self) -> Mutability {
970 if self.eat_keyword(kw::Mut) { Mutability::Mut } else { Mutability::Not }
973 /// Possibly parses mutability (`const` or `mut`).
974 fn parse_const_or_mut(&mut self) -> Option<Mutability> {
975 if self.eat_keyword(kw::Mut) {
976 Some(Mutability::Mut)
977 } else if self.eat_keyword(kw::Const) {
978 Some(Mutability::Not)
984 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
985 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = self.token.kind
987 self.expect_no_suffix(self.token.span, "a tuple index", suffix);
989 Ok(Ident::new(symbol, self.prev_span))
991 self.parse_ident_common(false)
995 fn parse_mac_args(&mut self) -> PResult<'a, P<MacArgs>> {
996 self.parse_mac_args_common(true).map(P)
999 fn parse_attr_args(&mut self) -> PResult<'a, MacArgs> {
1000 self.parse_mac_args_common(false)
1003 fn parse_mac_args_common(&mut self, delimited_only: bool) -> PResult<'a, MacArgs> {
1005 if self.check(&token::OpenDelim(DelimToken::Paren))
1006 || self.check(&token::OpenDelim(DelimToken::Bracket))
1007 || self.check(&token::OpenDelim(DelimToken::Brace))
1009 match self.parse_token_tree() {
1010 TokenTree::Delimited(dspan, delim, tokens) =>
1011 // We've confirmed above that there is a delimiter so unwrapping is OK.
1013 MacArgs::Delimited(dspan, MacDelimiter::from_token(delim).unwrap(), tokens)
1015 _ => unreachable!(),
1017 } else if !delimited_only {
1018 if self.eat(&token::Eq) {
1019 let eq_span = self.prev_span;
1020 let mut is_interpolated_expr = false;
1021 if let token::Interpolated(nt) = &self.token.kind {
1022 if let token::NtExpr(..) = **nt {
1023 is_interpolated_expr = true;
1026 let token_tree = if is_interpolated_expr {
1027 // We need to accept arbitrary interpolated expressions to continue
1028 // supporting things like `doc = $expr` that work on stable.
1029 // Non-literal interpolated expressions are rejected after expansion.
1030 self.parse_token_tree()
1032 self.parse_unsuffixed_lit()?.token_tree()
1035 MacArgs::Eq(eq_span, token_tree.into())
1040 return self.unexpected();
1045 fn parse_or_use_outer_attributes(
1047 already_parsed_attrs: Option<AttrVec>,
1048 ) -> PResult<'a, AttrVec> {
1049 if let Some(attrs) = already_parsed_attrs {
1052 self.parse_outer_attributes().map(|a| a.into())
1056 pub fn process_potential_macro_variable(&mut self) {
1057 self.token = match self.token.kind {
1059 if self.token.span.from_expansion() && self.look_ahead(1, |t| t.is_ident()) =>
1062 let name = match self.token.kind {
1063 token::Ident(name, _) => name,
1064 _ => unreachable!(),
1066 let span = self.prev_span.to(self.token.span);
1067 self.struct_span_err(span, &format!("unknown macro variable `{}`", name))
1068 .span_label(span, "unknown macro variable")
1073 token::Interpolated(ref nt) => {
1074 self.meta_var_span = Some(self.token.span);
1075 // Interpolated identifier and lifetime tokens are replaced with usual identifier
1076 // and lifetime tokens, so the former are never encountered during normal parsing.
1078 token::NtIdent(ident, is_raw) => {
1079 Token::new(token::Ident(ident.name, is_raw), ident.span)
1081 token::NtLifetime(ident) => Token::new(token::Lifetime(ident.name), ident.span),
1089 /// Parses a single token tree from the input.
1090 pub fn parse_token_tree(&mut self) -> TokenTree {
1091 match self.token.kind {
1092 token::OpenDelim(..) => {
1093 let frame = mem::replace(
1094 &mut self.token_cursor.frame,
1095 self.token_cursor.stack.pop().unwrap(),
1097 self.token.span = frame.span.entire();
1099 TokenTree::Delimited(frame.span, frame.delim, frame.tree_cursor.stream.into())
1101 token::CloseDelim(_) | token::Eof => unreachable!(),
1103 let token = self.token.take();
1105 TokenTree::Token(token)
1110 /// Parses a stream of tokens into a list of `TokenTree`s, up to EOF.
1111 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
1112 let mut tts = Vec::new();
1113 while self.token != token::Eof {
1114 tts.push(self.parse_token_tree());
1119 pub fn parse_tokens(&mut self) -> TokenStream {
1120 let mut result = Vec::new();
1122 match self.token.kind {
1123 token::Eof | token::CloseDelim(..) => break,
1124 _ => result.push(self.parse_token_tree().into()),
1127 TokenStream::new(result)
1130 /// Evaluates the closure with restrictions in place.
1132 /// Afters the closure is evaluated, restrictions are reset.
1133 fn with_res<T>(&mut self, res: Restrictions, f: impl FnOnce(&mut Self) -> T) -> T {
1134 let old = self.restrictions;
1135 self.restrictions = res;
1137 self.restrictions = old;
1141 fn is_crate_vis(&self) -> bool {
1142 self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
1145 /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
1146 /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
1147 /// If the following element can't be a tuple (i.e., it's a function definition), then
1148 /// it's not a tuple struct field), and the contents within the parentheses isn't valid,
1149 /// so emit a proper diagnostic.
1150 pub fn parse_visibility(&mut self, fbt: FollowedByType) -> PResult<'a, Visibility> {
1151 maybe_whole!(self, NtVis, |x| x);
1153 self.expected_tokens.push(TokenType::Keyword(kw::Crate));
1154 if self.is_crate_vis() {
1155 self.bump(); // `crate`
1156 self.sess.gated_spans.gate(sym::crate_visibility_modifier, self.prev_span);
1157 return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
1160 if !self.eat_keyword(kw::Pub) {
1161 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
1162 // keyword to grab a span from for inherited visibility; an empty span at the
1163 // beginning of the current token would seem to be the "Schelling span".
1164 return Ok(respan(self.token.span.shrink_to_lo(), VisibilityKind::Inherited));
1166 let lo = self.prev_span;
1168 if self.check(&token::OpenDelim(token::Paren)) {
1169 // We don't `self.bump()` the `(` yet because this might be a struct definition where
1170 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
1171 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
1172 // by the following tokens.
1173 if self.is_keyword_ahead(1, &[kw::Crate]) && self.look_ahead(2, |t| t != &token::ModSep)
1174 // account for `pub(crate::foo)`
1176 // Parse `pub(crate)`.
1178 self.bump(); // `crate`
1179 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1180 let vis = VisibilityKind::Crate(CrateSugar::PubCrate);
1181 return Ok(respan(lo.to(self.prev_span), vis));
1182 } else if self.is_keyword_ahead(1, &[kw::In]) {
1183 // Parse `pub(in path)`.
1185 self.bump(); // `in`
1186 let path = self.parse_path(PathStyle::Mod)?; // `path`
1187 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1188 let vis = VisibilityKind::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
1189 return Ok(respan(lo.to(self.prev_span), vis));
1190 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren))
1191 && self.is_keyword_ahead(1, &[kw::Super, kw::SelfLower])
1193 // Parse `pub(self)` or `pub(super)`.
1195 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
1196 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1197 let vis = VisibilityKind::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
1198 return Ok(respan(lo.to(self.prev_span), vis));
1199 } else if let FollowedByType::No = fbt {
1200 // Provide this diagnostic if a type cannot follow;
1201 // in particular, if this is not a tuple struct.
1202 self.recover_incorrect_vis_restriction()?;
1203 // Emit diagnostic, but continue with public visibility.
1207 Ok(respan(lo, VisibilityKind::Public))
1210 /// Recovery for e.g. `pub(something) fn ...` or `struct X { pub(something) y: Z }`
1211 fn recover_incorrect_vis_restriction(&mut self) -> PResult<'a, ()> {
1213 let path = self.parse_path(PathStyle::Mod)?;
1214 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1216 let msg = "incorrect visibility restriction";
1217 let suggestion = r##"some possible visibility restrictions are:
1218 `pub(crate)`: visible only on the current crate
1219 `pub(super)`: visible only in the current module's parent
1220 `pub(in path::to::module)`: visible only on the specified path"##;
1222 let path_str = pprust::path_to_string(&path);
1224 struct_span_err!(self.sess.span_diagnostic, path.span, E0704, "{}", msg)
1228 &format!("make this visible only to module `{}` with `in`", path_str),
1229 format!("in {}", path_str),
1230 Applicability::MachineApplicable,
1237 /// Parses `extern string_literal?`.
1238 fn parse_extern(&mut self) -> PResult<'a, Extern> {
1239 Ok(if self.eat_keyword(kw::Extern) {
1240 Extern::from_abi(self.parse_abi())
1246 /// Parses a string literal as an ABI spec.
1247 fn parse_abi(&mut self) -> Option<StrLit> {
1248 match self.parse_str_lit() {
1249 Ok(str_lit) => Some(str_lit),
1250 Err(Some(lit)) => match lit.kind {
1251 ast::LitKind::Err(_) => None,
1253 self.struct_span_err(lit.span, "non-string ABI literal")
1256 "specify the ABI with a string literal",
1257 "\"C\"".to_string(),
1258 Applicability::MaybeIncorrect,
1268 /// We are parsing `async fn`. If we are on Rust 2015, emit an error.
1269 fn ban_async_in_2015(&self, async_span: Span) {
1270 if async_span.rust_2015() {
1275 "`async fn` is not permitted in the 2015 edition",
1281 fn collect_tokens<R>(
1283 f: impl FnOnce(&mut Self) -> PResult<'a, R>,
1284 ) -> PResult<'a, (R, TokenStream)> {
1285 // Record all tokens we parse when parsing this item.
1286 let mut tokens = Vec::new();
1287 let prev_collecting = match self.token_cursor.frame.last_token {
1288 LastToken::Collecting(ref mut list) => Some(mem::take(list)),
1289 LastToken::Was(ref mut last) => {
1290 tokens.extend(last.take());
1294 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
1295 let prev = self.token_cursor.stack.len();
1297 let last_token = if self.token_cursor.stack.len() == prev {
1298 &mut self.token_cursor.frame.last_token
1299 } else if self.token_cursor.stack.get(prev).is_none() {
1300 // This can happen due to a bad interaction of two unrelated recovery mechanisms with
1301 // mismatched delimiters *and* recovery lookahead on the likely typo `pub ident(`
1303 return Ok((ret?, TokenStream::default()));
1305 &mut self.token_cursor.stack[prev].last_token
1308 // Pull out the tokens that we've collected from the call to `f` above.
1309 let mut collected_tokens = match *last_token {
1310 LastToken::Collecting(ref mut v) => mem::take(v),
1311 LastToken::Was(ref was) => {
1312 let msg = format!("our vector went away? - found Was({:?})", was);
1313 debug!("collect_tokens: {}", msg);
1314 self.sess.span_diagnostic.delay_span_bug(self.token.span, &msg);
1315 // This can happen due to a bad interaction of two unrelated recovery mechanisms
1316 // with mismatched delimiters *and* recovery lookahead on the likely typo
1317 // `pub ident(` (#62895, different but similar to the case above).
1318 return Ok((ret?, TokenStream::default()));
1322 // If we're not at EOF our current token wasn't actually consumed by
1323 // `f`, but it'll still be in our list that we pulled out. In that case
1325 let extra_token = if self.token != token::Eof { collected_tokens.pop() } else { None };
1327 // If we were previously collecting tokens, then this was a recursive
1328 // call. In that case we need to record all the tokens we collected in
1329 // our parent list as well. To do that we push a clone of our stream
1330 // onto the previous list.
1331 match prev_collecting {
1333 list.extend(collected_tokens.iter().cloned());
1334 list.extend(extra_token);
1335 *last_token = LastToken::Collecting(list);
1338 *last_token = LastToken::Was(extra_token);
1342 Ok((ret?, TokenStream::new(collected_tokens)))
1346 fn is_import_coupler(&mut self) -> bool {
1347 self.check(&token::ModSep)
1348 && self.look_ahead(1, |t| {
1349 *t == token::OpenDelim(token::Brace) || *t == token::BinOp(token::Star)
1354 crate fn make_unclosed_delims_error(
1355 unmatched: UnmatchedBrace,
1357 ) -> Option<DiagnosticBuilder<'_>> {
1358 // `None` here means an `Eof` was found. We already emit those errors elsewhere, we add them to
1359 // `unmatched_braces` only for error recovery in the `Parser`.
1360 let found_delim = unmatched.found_delim?;
1361 let mut err = sess.span_diagnostic.struct_span_err(
1362 unmatched.found_span,
1364 "mismatched closing delimiter: `{}`",
1365 pprust::token_kind_to_string(&token::CloseDelim(found_delim)),
1368 err.span_label(unmatched.found_span, "mismatched closing delimiter");
1369 if let Some(sp) = unmatched.candidate_span {
1370 err.span_label(sp, "closing delimiter possibly meant for this");
1372 if let Some(sp) = unmatched.unclosed_span {
1373 err.span_label(sp, "unclosed delimiter");
1378 pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, sess: &ParseSess) {
1379 *sess.reached_eof.borrow_mut() |=
1380 unclosed_delims.iter().any(|unmatched_delim| unmatched_delim.found_delim.is_none());
1381 for unmatched in unclosed_delims.drain(..) {
1382 make_unclosed_delims_error(unmatched, sess).map(|mut e| e.emit());