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::DUMMY_NODE_ID;
26 use syntax::ast::{self, AttrStyle, AttrVec, Const, CrateSugar, Extern, Ident, Unsafe};
27 use syntax::ast::{Async, MacArgs, MacDelimiter, Mutability, StrLit, Visibility, VisibilityKind};
29 use syntax::token::{self, DelimToken, Token, TokenKind};
30 use syntax::tokenstream::{self, DelimSpan, TokenStream, TokenTree, TreeAndJoint};
31 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);
87 pub struct Parser<'a> {
88 pub sess: &'a ParseSess,
89 /// The current normalized token.
90 /// "Normalized" means that some interpolated tokens
91 /// (`$i: ident` and `$l: lifetime` meta-variables) are replaced
92 /// with non-interpolated identifier and lifetime tokens they refer to.
93 /// Use span from this token if you need an isolated span.
95 /// The current non-normalized token if it's different from `token`.
96 /// Preferable use is through the `unnormalized_token()` getter.
97 /// Use span from this token if you need to concatenate it with some neighbouring spans.
98 pub unnormalized_token: Option<Token>,
99 /// The previous normalized token.
100 /// Use span from this token if you need an isolated span.
102 /// The previous non-normalized token if it's different from `prev_token`.
103 /// Preferable use is through the `unnormalized_prev_token()` getter.
104 /// Use span from this token if you need to concatenate it with some neighbouring spans.
105 unnormalized_prev_token: Option<Token>,
106 /// Equivalent to `unnormalized_prev_token().span`.
107 /// FIXME: Remove in favor of `(unnormalized_)prev_token().span`.
109 restrictions: Restrictions,
110 /// Used to determine the path to externally loaded source files.
111 pub(super) directory: Directory,
112 /// `true` to parse sub-modules in other files.
113 // Public for rustfmt usage.
114 pub recurse_into_file_modules: bool,
115 /// Name of the root module this parser originated from. If `None`, then the
116 /// name is not known. This does not change while the parser is descending
117 /// into modules, and sub-parsers have new values for this name.
118 pub root_module_name: Option<String>,
119 expected_tokens: Vec<TokenType>,
120 token_cursor: TokenCursor,
121 desugar_doc_comments: bool,
122 /// `true` we should configure out of line modules as we parse.
123 // Public for rustfmt usage.
125 /// This field is used to keep track of how many left angle brackets we have seen. This is
126 /// required in order to detect extra leading left angle brackets (`<` characters) and error
129 /// See the comments in the `parse_path_segment` function for more details.
130 unmatched_angle_bracket_count: u32,
131 max_angle_bracket_count: u32,
132 /// A list of all unclosed delimiters found by the lexer. If an entry is used for error recovery
133 /// it gets removed from here. Every entry left at the end gets emitted as an independent
135 pub(super) unclosed_delims: Vec<UnmatchedBrace>,
136 last_unexpected_token_span: Option<Span>,
137 pub last_type_ascription: Option<(Span, bool /* likely path typo */)>,
138 /// If present, this `Parser` is not parsing Rust code but rather a macro call.
139 subparser_name: Option<&'static str>,
142 impl<'a> Drop for Parser<'a> {
144 emit_unclosed_delims(&mut self.unclosed_delims, &self.sess);
150 frame: TokenCursorFrame,
151 stack: Vec<TokenCursorFrame>,
155 struct TokenCursorFrame {
156 delim: token::DelimToken,
159 tree_cursor: tokenstream::Cursor,
161 last_token: LastToken,
164 /// This is used in `TokenCursorFrame` above to track tokens that are consumed
165 /// by the parser, and then that's transitively used to record the tokens that
166 /// each parse AST item is created with.
168 /// Right now this has two states, either collecting tokens or not collecting
169 /// tokens. If we're collecting tokens we just save everything off into a local
170 /// `Vec`. This should eventually though likely save tokens from the original
171 /// token stream and just use slicing of token streams to avoid creation of a
172 /// whole new vector.
174 /// The second state is where we're passively not recording tokens, but the last
175 /// token is still tracked for when we want to start recording tokens. This
176 /// "last token" means that when we start recording tokens we'll want to ensure
177 /// that this, the first token, is included in the output.
179 /// You can find some more example usage of this in the `collect_tokens` method
183 Collecting(Vec<TreeAndJoint>),
184 Was(Option<TreeAndJoint>),
187 impl TokenCursorFrame {
188 fn new(span: DelimSpan, delim: DelimToken, tts: &TokenStream) -> Self {
192 open_delim: delim == token::NoDelim,
193 tree_cursor: tts.clone().into_trees(),
194 close_delim: delim == token::NoDelim,
195 last_token: LastToken::Was(None),
201 fn next(&mut self) -> Token {
203 let tree = if !self.frame.open_delim {
204 self.frame.open_delim = true;
205 TokenTree::open_tt(self.frame.span, self.frame.delim)
206 } else if let Some(tree) = self.frame.tree_cursor.next() {
208 } else if !self.frame.close_delim {
209 self.frame.close_delim = true;
210 TokenTree::close_tt(self.frame.span, self.frame.delim)
211 } else if let Some(frame) = self.stack.pop() {
215 return Token::new(token::Eof, DUMMY_SP);
218 match self.frame.last_token {
219 LastToken::Collecting(ref mut v) => v.push(tree.clone().into()),
220 LastToken::Was(ref mut t) => *t = Some(tree.clone().into()),
224 TokenTree::Token(token) => return token,
225 TokenTree::Delimited(sp, delim, tts) => {
226 let frame = TokenCursorFrame::new(sp, delim, &tts);
227 self.stack.push(mem::replace(&mut self.frame, frame));
233 fn next_desugared(&mut self) -> Token {
234 let (name, sp) = match self.next() {
235 Token { kind: token::DocComment(name), span } => (name, span),
239 let stripped = strip_doc_comment_decoration(&name.as_str());
241 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
242 // required to wrap the text.
243 let mut num_of_hashes = 0;
245 for ch in stripped.chars() {
248 '#' if count > 0 => count + 1,
251 num_of_hashes = cmp::max(num_of_hashes, count);
254 let delim_span = DelimSpan::from_single(sp);
255 let body = TokenTree::Delimited(
259 TokenTree::token(token::Ident(sym::doc, false), sp),
260 TokenTree::token(token::Eq, sp),
262 TokenKind::lit(token::StrRaw(num_of_hashes), Symbol::intern(&stripped), None),
268 .collect::<TokenStream>()
272 self.stack.push(mem::replace(
274 TokenCursorFrame::new(
277 &if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
278 [TokenTree::token(token::Pound, sp), TokenTree::token(token::Not, sp), body]
281 .collect::<TokenStream>()
283 [TokenTree::token(token::Pound, sp), body]
286 .collect::<TokenStream>()
295 #[derive(Clone, PartialEq)]
308 fn to_string(&self) -> String {
310 TokenType::Token(ref t) => format!("`{}`", pprust::token_kind_to_string(t)),
311 TokenType::Keyword(kw) => format!("`{}`", kw),
312 TokenType::Operator => "an operator".to_string(),
313 TokenType::Lifetime => "lifetime".to_string(),
314 TokenType::Ident => "identifier".to_string(),
315 TokenType::Path => "path".to_string(),
316 TokenType::Type => "type".to_string(),
317 TokenType::Const => "const".to_string(),
322 #[derive(Copy, Clone, Debug)]
323 enum TokenExpectType {
328 /// A sequence separator.
330 /// The separator token.
331 sep: Option<TokenKind>,
332 /// `true` if a trailing separator is allowed.
333 trailing_sep_allowed: bool,
337 fn trailing_allowed(t: TokenKind) -> SeqSep {
338 SeqSep { sep: Some(t), trailing_sep_allowed: true }
341 fn none() -> SeqSep {
342 SeqSep { sep: None, trailing_sep_allowed: false }
346 pub enum FollowedByType {
351 fn token_descr_opt(token: &Token) -> Option<&'static str> {
352 Some(match token.kind {
353 _ if token.is_special_ident() => "reserved identifier",
354 _ if token.is_used_keyword() => "keyword",
355 _ if token.is_unused_keyword() => "reserved keyword",
356 token::DocComment(..) => "doc comment",
361 pub(super) fn token_descr(token: &Token) -> String {
362 let token_str = pprust::token_to_string(token);
363 match token_descr_opt(token) {
364 Some(prefix) => format!("{} `{}`", prefix, token_str),
365 _ => format!("`{}`", token_str),
369 impl<'a> Parser<'a> {
373 directory: Option<Directory>,
374 recurse_into_file_modules: bool,
375 desugar_doc_comments: bool,
376 subparser_name: Option<&'static str>,
378 let mut parser = Parser {
380 token: Token::dummy(),
381 unnormalized_token: None,
382 prev_token: Token::dummy(),
383 unnormalized_prev_token: None,
385 restrictions: Restrictions::empty(),
386 recurse_into_file_modules,
387 directory: Directory {
388 path: PathBuf::new(),
389 ownership: DirectoryOwnership::Owned { relative: None },
391 root_module_name: None,
392 expected_tokens: Vec::new(),
393 token_cursor: TokenCursor {
394 frame: TokenCursorFrame::new(DelimSpan::dummy(), token::NoDelim, &tokens.into()),
397 desugar_doc_comments,
399 unmatched_angle_bracket_count: 0,
400 max_angle_bracket_count: 0,
401 unclosed_delims: Vec::new(),
402 last_unexpected_token_span: None,
403 last_type_ascription: None,
407 // Make parser point to the first token.
410 if let Some(directory) = directory {
411 parser.directory = directory;
412 } else if !parser.token.span.is_dummy() {
413 if let Some(FileName::Real(path)) =
414 &sess.source_map().lookup_char_pos(parser.token.span.lo()).file.unmapped_path
416 if let Some(directory_path) = path.parent() {
417 parser.directory.path = directory_path.to_path_buf();
425 fn unnormalized_token(&self) -> &Token {
426 self.unnormalized_token.as_ref().unwrap_or(&self.token)
429 fn unnormalized_prev_token(&self) -> &Token {
430 self.unnormalized_prev_token.as_ref().unwrap_or(&self.prev_token)
433 fn next_tok(&mut self, fallback_span: Span) -> Token {
434 let mut next = if self.desugar_doc_comments {
435 self.token_cursor.next_desugared()
437 self.token_cursor.next()
439 if next.span.is_dummy() {
440 // Tweak the location for better diagnostics, but keep syntactic context intact.
441 next.span = fallback_span.with_ctxt(next.span.ctxt());
446 crate fn unexpected<T>(&mut self) -> PResult<'a, T> {
447 match self.expect_one_of(&[], &[]) {
449 // We can get `Ok(true)` from `recover_closing_delimiter`
450 // which is called in `expected_one_of_not_found`.
451 Ok(_) => FatalError.raise(),
455 /// Expects and consumes the token `t`. Signals an error if the next token is not `t`.
456 pub fn expect(&mut self, t: &TokenKind) -> PResult<'a, bool /* recovered */> {
457 if self.expected_tokens.is_empty() {
458 if self.token == *t {
462 self.unexpected_try_recover(t)
465 self.expect_one_of(slice::from_ref(t), &[])
469 /// Expect next token to be edible or inedible token. If edible,
470 /// then consume it; if inedible, then return without consuming
471 /// anything. Signal a fatal error if next token is unexpected.
472 pub fn expect_one_of(
474 edible: &[TokenKind],
475 inedible: &[TokenKind],
476 ) -> PResult<'a, bool /* recovered */> {
477 if edible.contains(&self.token.kind) {
480 } else if inedible.contains(&self.token.kind) {
481 // leave it in the input
483 } else if self.last_unexpected_token_span == Some(self.token.span) {
486 self.expected_one_of_not_found(edible, inedible)
490 // Public for rustfmt usage.
491 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
492 self.parse_ident_common(true)
495 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, ast::Ident> {
496 match self.token.kind {
497 token::Ident(name, _) => {
498 if self.token.is_reserved_ident() {
499 let mut err = self.expected_ident_found();
506 let span = self.token.span;
508 Ok(Ident::new(name, span))
510 _ => Err(match self.prev_token.kind {
511 TokenKind::DocComment(..) => {
512 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
514 _ => self.expected_ident_found(),
519 /// Checks if the next token is `tok`, and returns `true` if so.
521 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
523 fn check(&mut self, tok: &TokenKind) -> bool {
524 let is_present = self.token == *tok;
526 self.expected_tokens.push(TokenType::Token(tok.clone()));
531 /// Consumes a token 'tok' if it exists. Returns whether the given token was present.
532 pub fn eat(&mut self, tok: &TokenKind) -> bool {
533 let is_present = self.check(tok);
540 /// If the next token is the given keyword, returns `true` without eating it.
541 /// An expectation is also added for diagnostics purposes.
542 fn check_keyword(&mut self, kw: Symbol) -> bool {
543 self.expected_tokens.push(TokenType::Keyword(kw));
544 self.token.is_keyword(kw)
547 /// If the next token is the given keyword, eats it and returns `true`.
548 /// Otherwise, returns `false`. An expectation is also added for diagnostics purposes.
549 // Public for rustfmt usage.
550 pub fn eat_keyword(&mut self, kw: Symbol) -> bool {
551 if self.check_keyword(kw) {
559 fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool {
560 if self.token.is_keyword(kw) {
568 /// If the given word is not a keyword, signals an error.
569 /// If the next token is not the given word, signals an error.
570 /// Otherwise, eats it.
571 fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> {
572 if !self.eat_keyword(kw) { self.unexpected() } else { Ok(()) }
575 /// Is the given keyword `kw` followed by a non-reserved identifier?
576 fn is_kw_followed_by_ident(&self, kw: Symbol) -> bool {
577 self.token.is_keyword(kw) && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
580 fn check_or_expected(&mut self, ok: bool, typ: TokenType) -> bool {
584 self.expected_tokens.push(typ);
589 fn check_ident(&mut self) -> bool {
590 self.check_or_expected(self.token.is_ident(), TokenType::Ident)
593 fn check_path(&mut self) -> bool {
594 self.check_or_expected(self.token.is_path_start(), TokenType::Path)
597 fn check_type(&mut self) -> bool {
598 self.check_or_expected(self.token.can_begin_type(), TokenType::Type)
601 fn check_const_arg(&mut self) -> bool {
602 self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const)
605 /// Checks to see if the next token is either `+` or `+=`.
606 /// Otherwise returns `false`.
607 fn check_plus(&mut self) -> bool {
608 self.check_or_expected(
609 self.token.is_like_plus(),
610 TokenType::Token(token::BinOp(token::Plus)),
614 /// Expects and consumes a `+`. if `+=` is seen, replaces it with a `=`
615 /// and continues. If a `+` is not seen, returns `false`.
617 /// This is used when token-splitting `+=` into `+`.
618 /// See issue #47856 for an example of when this may occur.
619 fn eat_plus(&mut self) -> bool {
620 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
621 match self.token.kind {
622 token::BinOp(token::Plus) => {
626 token::BinOpEq(token::Plus) => {
627 let start_point = self.sess.source_map().start_point(self.token.span);
628 self.bump_with(token::Eq, self.token.span.with_lo(start_point.hi()));
635 /// Expects and consumes an `&`. If `&&` is seen, replaces it with a single
636 /// `&` and continues. If an `&` is not seen, signals an error.
637 fn expect_and(&mut self) -> PResult<'a, ()> {
638 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
639 match self.token.kind {
640 token::BinOp(token::And) => {
645 let start_point = self.sess.source_map().start_point(self.token.span);
647 .bump_with(token::BinOp(token::And), self.token.span.with_lo(start_point.hi())))
649 _ => self.unexpected(),
653 /// Expects and consumes an `|`. If `||` is seen, replaces it with a single
654 /// `|` and continues. If an `|` is not seen, signals an error.
655 fn expect_or(&mut self) -> PResult<'a, ()> {
656 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or)));
657 match self.token.kind {
658 token::BinOp(token::Or) => {
663 let start_point = self.sess.source_map().start_point(self.token.span);
665 .bump_with(token::BinOp(token::Or), self.token.span.with_lo(start_point.hi())))
667 _ => self.unexpected(),
671 /// Attempts to consume a `<`. If `<<` is seen, replaces it with a single
672 /// `<` and continue. If `<-` is seen, replaces it with a single `<`
673 /// and continue. If a `<` is not seen, returns false.
675 /// This is meant to be used when parsing generics on a path to get the
677 fn eat_lt(&mut self) -> bool {
678 self.expected_tokens.push(TokenType::Token(token::Lt));
679 let ate = match self.token.kind {
684 token::BinOp(token::Shl) => {
685 let start_point = self.sess.source_map().start_point(self.token.span);
686 self.bump_with(token::Lt, self.token.span.with_lo(start_point.hi()));
690 let start_point = self.sess.source_map().start_point(self.token.span);
692 token::BinOp(token::Minus),
693 self.token.span.with_lo(start_point.hi()),
701 // See doc comment for `unmatched_angle_bracket_count`.
702 self.unmatched_angle_bracket_count += 1;
703 self.max_angle_bracket_count += 1;
704 debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count);
710 fn expect_lt(&mut self) -> PResult<'a, ()> {
711 if !self.eat_lt() { self.unexpected() } else { Ok(()) }
714 /// Expects and consumes a single `>` token. if a `>>` is seen, replaces it
715 /// with a single `>` and continues. If a `>` is not seen, signals an error.
716 fn expect_gt(&mut self) -> PResult<'a, ()> {
717 self.expected_tokens.push(TokenType::Token(token::Gt));
718 let ate = match self.token.kind {
723 token::BinOp(token::Shr) => {
724 let start_point = self.sess.source_map().start_point(self.token.span);
725 Some(self.bump_with(token::Gt, self.token.span.with_lo(start_point.hi())))
727 token::BinOpEq(token::Shr) => {
728 let start_point = self.sess.source_map().start_point(self.token.span);
729 Some(self.bump_with(token::Ge, self.token.span.with_lo(start_point.hi())))
732 let start_point = self.sess.source_map().start_point(self.token.span);
733 Some(self.bump_with(token::Eq, self.token.span.with_lo(start_point.hi())))
740 // See doc comment for `unmatched_angle_bracket_count`.
741 if self.unmatched_angle_bracket_count > 0 {
742 self.unmatched_angle_bracket_count -= 1;
743 debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count);
748 None => self.unexpected(),
752 fn expect_any_with_type(&mut self, kets: &[&TokenKind], expect: TokenExpectType) -> bool {
753 kets.iter().any(|k| match expect {
754 TokenExpectType::Expect => self.check(k),
755 TokenExpectType::NoExpect => self.token == **k,
759 fn parse_seq_to_before_tokens<T>(
763 expect: TokenExpectType,
764 mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
765 ) -> PResult<'a, (Vec<T>, bool /* trailing */, bool /* recovered */)> {
766 let mut first = true;
767 let mut recovered = false;
768 let mut trailing = false;
770 while !self.expect_any_with_type(kets, expect) {
771 if let token::CloseDelim(..) | token::Eof = self.token.kind {
774 if let Some(ref t) = sep.sep {
778 match self.expect(t) {
784 Err(mut expect_err) => {
785 let sp = self.prev_span.shrink_to_hi();
786 let token_str = pprust::token_kind_to_string(t);
788 // Attempt to keep parsing if it was a similar separator.
789 if let Some(ref tokens) = t.similar_tokens() {
790 if tokens.contains(&self.token.kind) {
795 // Attempt to keep parsing if it was an omitted separator.
798 // Parsed successfully, therefore most probably the code only
799 // misses a separator.
801 .span_suggestion_short(
803 &format!("missing `{}`", token_str),
805 Applicability::MaybeIncorrect,
813 // Parsing failed, therefore it must be something more serious
814 // than just a missing separator.
825 if sep.trailing_sep_allowed && self.expect_any_with_type(kets, expect) {
834 Ok((v, trailing, recovered))
837 /// Parses a sequence, not including the closing delimiter. The function
838 /// `f` must consume tokens until reaching the next separator or
840 fn parse_seq_to_before_end<T>(
844 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
845 ) -> PResult<'a, (Vec<T>, bool, bool)> {
846 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
849 /// Parses a sequence, including the closing delimiter. The function
850 /// `f` must consume tokens until reaching the next separator or
852 fn parse_seq_to_end<T>(
856 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
857 ) -> PResult<'a, (Vec<T>, bool /* trailing */)> {
858 let (val, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
865 /// Parses a sequence, including the closing delimiter. The function
866 /// `f` must consume tokens until reaching the next separator or
868 fn parse_unspanned_seq<T>(
873 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
874 ) -> PResult<'a, (Vec<T>, bool)> {
876 self.parse_seq_to_end(ket, sep, f)
879 fn parse_delim_comma_seq<T>(
882 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
883 ) -> PResult<'a, (Vec<T>, bool)> {
884 self.parse_unspanned_seq(
885 &token::OpenDelim(delim),
886 &token::CloseDelim(delim),
887 SeqSep::trailing_allowed(token::Comma),
892 fn parse_paren_comma_seq<T>(
894 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
895 ) -> PResult<'a, (Vec<T>, bool)> {
896 self.parse_delim_comma_seq(token::Paren, f)
899 // Interpolated identifier (`$i: ident`) and lifetime (`$l: lifetime`)
900 // tokens are replaced with usual identifier and lifetime tokens,
901 // so the former are never encountered during normal parsing.
902 fn normalize_token(token: &Token) -> Option<Token> {
904 token::Interpolated(nt) => match **nt {
905 token::NtIdent(ident, is_raw) => {
906 Some(Token::new(token::Ident(ident.name, is_raw), ident.span))
908 token::NtLifetime(ident) => {
909 Some(Token::new(token::Lifetime(ident.name), ident.span))
917 /// Advance the parser by one token.
918 pub fn bump(&mut self) {
919 if self.prev_token.kind == TokenKind::Eof {
920 // Bumping after EOF is a bad sign, usually an infinite loop.
921 let msg = "attempted to bump the parser past EOF (may be stuck in a loop)";
922 self.span_bug(self.token.span, msg);
925 // Update the current and previous tokens.
926 self.prev_token = self.token.take();
927 self.unnormalized_prev_token = self.unnormalized_token.take();
928 self.token = self.next_tok(self.unnormalized_prev_token().span);
929 if let Some(normalized_token) = Self::normalize_token(&self.token) {
930 self.unnormalized_token = Some(mem::replace(&mut self.token, normalized_token));
933 // Update fields derived from the previous token.
934 self.prev_span = self.unnormalized_prev_token().span;
936 self.expected_tokens.clear();
939 /// Advances the parser using provided token as a next one. Use this when
940 /// consuming a part of a token. For example a single `<` from `<<`.
941 /// FIXME: this function sets the previous token data to some semi-nonsensical values
942 /// which kind of work because they are currently used in very limited ways in practice.
943 /// Correct token kinds and spans need to be calculated instead.
944 fn bump_with(&mut self, next: TokenKind, span: Span) {
945 // Update the current and previous tokens.
946 self.prev_token = self.token.take();
947 self.unnormalized_prev_token = self.unnormalized_token.take();
948 self.token = Token::new(next, span);
949 if let Some(normalized_token) = Self::normalize_token(&self.token) {
950 self.unnormalized_token = Some(mem::replace(&mut self.token, normalized_token));
953 // Update fields derived from the previous token.
954 self.prev_span = self.unnormalized_prev_token().span.with_hi(span.lo());
956 self.expected_tokens.clear();
959 /// Look-ahead `dist` tokens of `self.token` and get access to that token there.
960 /// When `dist == 0` then the current token is looked at.
961 pub fn look_ahead<R>(&self, dist: usize, looker: impl FnOnce(&Token) -> R) -> R {
963 return looker(&self.token);
966 let frame = &self.token_cursor.frame;
967 looker(&match frame.tree_cursor.look_ahead(dist - 1) {
968 Some(tree) => match tree {
969 TokenTree::Token(token) => token,
970 TokenTree::Delimited(dspan, delim, _) => {
971 Token::new(token::OpenDelim(delim), dspan.open)
974 None => Token::new(token::CloseDelim(frame.delim), frame.span.close),
978 /// Returns whether any of the given keywords are `dist` tokens ahead of the current one.
979 fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool {
980 self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw)))
983 /// Parses asyncness: `async` or nothing.
984 fn parse_asyncness(&mut self) -> Async {
985 if self.eat_keyword(kw::Async) {
986 let span = self.prev_span;
987 Async::Yes { span, closure_id: DUMMY_NODE_ID, return_impl_trait_id: DUMMY_NODE_ID }
993 /// Parses unsafety: `unsafe` or nothing.
994 fn parse_unsafety(&mut self) -> Unsafe {
995 if self.eat_keyword(kw::Unsafe) { Unsafe::Yes(self.prev_span) } else { Unsafe::No }
998 /// Parses constness: `const` or nothing.
999 fn parse_constness(&mut self) -> Const {
1000 if self.eat_keyword(kw::Const) { Const::Yes(self.prev_span) } else { Const::No }
1003 /// Parses mutability (`mut` or nothing).
1004 fn parse_mutability(&mut self) -> Mutability {
1005 if self.eat_keyword(kw::Mut) { Mutability::Mut } else { Mutability::Not }
1008 /// Possibly parses mutability (`const` or `mut`).
1009 fn parse_const_or_mut(&mut self) -> Option<Mutability> {
1010 if self.eat_keyword(kw::Mut) {
1011 Some(Mutability::Mut)
1012 } else if self.eat_keyword(kw::Const) {
1013 Some(Mutability::Not)
1019 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
1020 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = self.token.kind
1022 self.expect_no_suffix(self.token.span, "a tuple index", suffix);
1024 Ok(Ident::new(symbol, self.prev_span))
1026 self.parse_ident_common(false)
1030 fn parse_mac_args(&mut self) -> PResult<'a, P<MacArgs>> {
1031 self.parse_mac_args_common(true).map(P)
1034 fn parse_attr_args(&mut self) -> PResult<'a, MacArgs> {
1035 self.parse_mac_args_common(false)
1038 fn parse_mac_args_common(&mut self, delimited_only: bool) -> PResult<'a, MacArgs> {
1040 if self.check(&token::OpenDelim(DelimToken::Paren))
1041 || self.check(&token::OpenDelim(DelimToken::Bracket))
1042 || self.check(&token::OpenDelim(DelimToken::Brace))
1044 match self.parse_token_tree() {
1045 TokenTree::Delimited(dspan, delim, tokens) =>
1046 // We've confirmed above that there is a delimiter so unwrapping is OK.
1048 MacArgs::Delimited(dspan, MacDelimiter::from_token(delim).unwrap(), tokens)
1050 _ => unreachable!(),
1052 } else if !delimited_only {
1053 if self.eat(&token::Eq) {
1054 let eq_span = self.prev_span;
1055 let mut is_interpolated_expr = false;
1056 if let token::Interpolated(nt) = &self.token.kind {
1057 if let token::NtExpr(..) = **nt {
1058 is_interpolated_expr = true;
1061 let token_tree = if is_interpolated_expr {
1062 // We need to accept arbitrary interpolated expressions to continue
1063 // supporting things like `doc = $expr` that work on stable.
1064 // Non-literal interpolated expressions are rejected after expansion.
1065 self.parse_token_tree()
1067 self.parse_unsuffixed_lit()?.token_tree()
1070 MacArgs::Eq(eq_span, token_tree.into())
1075 return self.unexpected();
1080 fn parse_or_use_outer_attributes(
1082 already_parsed_attrs: Option<AttrVec>,
1083 ) -> PResult<'a, AttrVec> {
1084 if let Some(attrs) = already_parsed_attrs {
1087 self.parse_outer_attributes().map(|a| a.into())
1091 /// Parses a single token tree from the input.
1092 pub fn parse_token_tree(&mut self) -> TokenTree {
1093 match self.token.kind {
1094 token::OpenDelim(..) => {
1095 let frame = mem::replace(
1096 &mut self.token_cursor.frame,
1097 self.token_cursor.stack.pop().unwrap(),
1099 self.token = Token::new(TokenKind::CloseDelim(frame.delim), frame.span.close);
1100 self.unnormalized_token = None;
1102 TokenTree::Delimited(frame.span, frame.delim, frame.tree_cursor.stream.into())
1104 token::CloseDelim(_) | token::Eof => unreachable!(),
1107 TokenTree::Token(self.prev_token.clone())
1112 /// Parses a stream of tokens into a list of `TokenTree`s, up to EOF.
1113 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
1114 let mut tts = Vec::new();
1115 while self.token != token::Eof {
1116 tts.push(self.parse_token_tree());
1121 pub fn parse_tokens(&mut self) -> TokenStream {
1122 let mut result = Vec::new();
1124 match self.token.kind {
1125 token::Eof | token::CloseDelim(..) => break,
1126 _ => result.push(self.parse_token_tree().into()),
1129 TokenStream::new(result)
1132 /// Evaluates the closure with restrictions in place.
1134 /// Afters the closure is evaluated, restrictions are reset.
1135 fn with_res<T>(&mut self, res: Restrictions, f: impl FnOnce(&mut Self) -> T) -> T {
1136 let old = self.restrictions;
1137 self.restrictions = res;
1139 self.restrictions = old;
1143 fn is_crate_vis(&self) -> bool {
1144 self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
1147 /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
1148 /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
1149 /// If the following element can't be a tuple (i.e., it's a function definition), then
1150 /// it's not a tuple struct field), and the contents within the parentheses isn't valid,
1151 /// so emit a proper diagnostic.
1152 pub fn parse_visibility(&mut self, fbt: FollowedByType) -> PResult<'a, Visibility> {
1153 maybe_whole!(self, NtVis, |x| x);
1155 self.expected_tokens.push(TokenType::Keyword(kw::Crate));
1156 if self.is_crate_vis() {
1157 self.bump(); // `crate`
1158 self.sess.gated_spans.gate(sym::crate_visibility_modifier, self.prev_span);
1159 return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
1162 if !self.eat_keyword(kw::Pub) {
1163 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
1164 // keyword to grab a span from for inherited visibility; an empty span at the
1165 // beginning of the current token would seem to be the "Schelling span".
1166 return Ok(respan(self.token.span.shrink_to_lo(), VisibilityKind::Inherited));
1168 let lo = self.prev_span;
1170 if self.check(&token::OpenDelim(token::Paren)) {
1171 // We don't `self.bump()` the `(` yet because this might be a struct definition where
1172 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
1173 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
1174 // by the following tokens.
1175 if self.is_keyword_ahead(1, &[kw::Crate]) && self.look_ahead(2, |t| t != &token::ModSep)
1176 // account for `pub(crate::foo)`
1178 // Parse `pub(crate)`.
1180 self.bump(); // `crate`
1181 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1182 let vis = VisibilityKind::Crate(CrateSugar::PubCrate);
1183 return Ok(respan(lo.to(self.prev_span), vis));
1184 } else if self.is_keyword_ahead(1, &[kw::In]) {
1185 // Parse `pub(in path)`.
1187 self.bump(); // `in`
1188 let path = self.parse_path(PathStyle::Mod)?; // `path`
1189 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1190 let vis = VisibilityKind::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
1191 return Ok(respan(lo.to(self.prev_span), vis));
1192 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren))
1193 && self.is_keyword_ahead(1, &[kw::Super, kw::SelfLower])
1195 // Parse `pub(self)` or `pub(super)`.
1197 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
1198 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1199 let vis = VisibilityKind::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
1200 return Ok(respan(lo.to(self.prev_span), vis));
1201 } else if let FollowedByType::No = fbt {
1202 // Provide this diagnostic if a type cannot follow;
1203 // in particular, if this is not a tuple struct.
1204 self.recover_incorrect_vis_restriction()?;
1205 // Emit diagnostic, but continue with public visibility.
1209 Ok(respan(lo, VisibilityKind::Public))
1212 /// Recovery for e.g. `pub(something) fn ...` or `struct X { pub(something) y: Z }`
1213 fn recover_incorrect_vis_restriction(&mut self) -> PResult<'a, ()> {
1215 let path = self.parse_path(PathStyle::Mod)?;
1216 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1218 let msg = "incorrect visibility restriction";
1219 let suggestion = r##"some possible visibility restrictions are:
1220 `pub(crate)`: visible only on the current crate
1221 `pub(super)`: visible only in the current module's parent
1222 `pub(in path::to::module)`: visible only on the specified path"##;
1224 let path_str = pprust::path_to_string(&path);
1226 struct_span_err!(self.sess.span_diagnostic, path.span, E0704, "{}", msg)
1230 &format!("make this visible only to module `{}` with `in`", path_str),
1231 format!("in {}", path_str),
1232 Applicability::MachineApplicable,
1239 /// Parses `extern string_literal?`.
1240 fn parse_extern(&mut self) -> PResult<'a, Extern> {
1241 Ok(if self.eat_keyword(kw::Extern) {
1242 Extern::from_abi(self.parse_abi())
1248 /// Parses a string literal as an ABI spec.
1249 fn parse_abi(&mut self) -> Option<StrLit> {
1250 match self.parse_str_lit() {
1251 Ok(str_lit) => Some(str_lit),
1252 Err(Some(lit)) => match lit.kind {
1253 ast::LitKind::Err(_) => None,
1255 self.struct_span_err(lit.span, "non-string ABI literal")
1258 "specify the ABI with a string literal",
1259 "\"C\"".to_string(),
1260 Applicability::MaybeIncorrect,
1270 fn collect_tokens<R>(
1272 f: impl FnOnce(&mut Self) -> PResult<'a, R>,
1273 ) -> PResult<'a, (R, TokenStream)> {
1274 // Record all tokens we parse when parsing this item.
1275 let mut tokens = Vec::new();
1276 let prev_collecting = match self.token_cursor.frame.last_token {
1277 LastToken::Collecting(ref mut list) => Some(mem::take(list)),
1278 LastToken::Was(ref mut last) => {
1279 tokens.extend(last.take());
1283 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
1284 let prev = self.token_cursor.stack.len();
1286 let last_token = if self.token_cursor.stack.len() == prev {
1287 &mut self.token_cursor.frame.last_token
1288 } else if self.token_cursor.stack.get(prev).is_none() {
1289 // This can happen due to a bad interaction of two unrelated recovery mechanisms with
1290 // mismatched delimiters *and* recovery lookahead on the likely typo `pub ident(`
1292 return Ok((ret?, TokenStream::default()));
1294 &mut self.token_cursor.stack[prev].last_token
1297 // Pull out the tokens that we've collected from the call to `f` above.
1298 let mut collected_tokens = match *last_token {
1299 LastToken::Collecting(ref mut v) => mem::take(v),
1300 LastToken::Was(ref was) => {
1301 let msg = format!("our vector went away? - found Was({:?})", was);
1302 debug!("collect_tokens: {}", msg);
1303 self.sess.span_diagnostic.delay_span_bug(self.token.span, &msg);
1304 // This can happen due to a bad interaction of two unrelated recovery mechanisms
1305 // with mismatched delimiters *and* recovery lookahead on the likely typo
1306 // `pub ident(` (#62895, different but similar to the case above).
1307 return Ok((ret?, TokenStream::default()));
1311 // If we're not at EOF our current token wasn't actually consumed by
1312 // `f`, but it'll still be in our list that we pulled out. In that case
1314 let extra_token = if self.token != token::Eof { collected_tokens.pop() } else { None };
1316 // If we were previously collecting tokens, then this was a recursive
1317 // call. In that case we need to record all the tokens we collected in
1318 // our parent list as well. To do that we push a clone of our stream
1319 // onto the previous list.
1320 match prev_collecting {
1322 list.extend(collected_tokens.iter().cloned());
1323 list.extend(extra_token);
1324 *last_token = LastToken::Collecting(list);
1327 *last_token = LastToken::Was(extra_token);
1331 Ok((ret?, TokenStream::new(collected_tokens)))
1335 fn is_import_coupler(&mut self) -> bool {
1336 self.check(&token::ModSep)
1337 && self.look_ahead(1, |t| {
1338 *t == token::OpenDelim(token::Brace) || *t == token::BinOp(token::Star)
1343 crate fn make_unclosed_delims_error(
1344 unmatched: UnmatchedBrace,
1346 ) -> Option<DiagnosticBuilder<'_>> {
1347 // `None` here means an `Eof` was found. We already emit those errors elsewhere, we add them to
1348 // `unmatched_braces` only for error recovery in the `Parser`.
1349 let found_delim = unmatched.found_delim?;
1350 let mut err = sess.span_diagnostic.struct_span_err(
1351 unmatched.found_span,
1353 "mismatched closing delimiter: `{}`",
1354 pprust::token_kind_to_string(&token::CloseDelim(found_delim)),
1357 err.span_label(unmatched.found_span, "mismatched closing delimiter");
1358 if let Some(sp) = unmatched.candidate_span {
1359 err.span_label(sp, "closing delimiter possibly meant for this");
1361 if let Some(sp) = unmatched.unclosed_span {
1362 err.span_label(sp, "unclosed delimiter");
1367 pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, sess: &ParseSess) {
1368 *sess.reached_eof.borrow_mut() |=
1369 unclosed_delims.iter().any(|unmatched_delim| unmatched_delim.found_delim.is_none());
1370 for unmatched in unclosed_delims.drain(..) {
1371 make_unclosed_delims_error(unmatched, sess).map(|mut e| {