8 pub use path::PathStyle;
12 use diagnostics::Error;
15 self, DUMMY_NODE_ID, AttrStyle, Attribute, CrateSugar, Ident,
16 IsAsync, MacDelimiter, Mutability, StrStyle, Visibility, VisibilityKind, Unsafety,
18 use crate::parse::{PResult, Directory, DirectoryOwnership};
19 use crate::parse::lexer::UnmatchedBrace;
20 use crate::parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
21 use crate::parse::token::{self, Token, TokenKind, DelimToken};
22 use crate::print::pprust;
24 use crate::sess::ParseSess;
25 use crate::source_map::respan;
26 use crate::symbol::{kw, sym, Symbol};
27 use crate::tokenstream::{self, DelimSpan, TokenTree, TokenStream, TreeAndJoint};
30 use errors::{Applicability, DiagnosticBuilder, DiagnosticId, FatalError};
31 use rustc_target::spec::abi::{self, Abi};
32 use syntax_pos::{Span, BytePos, DUMMY_SP, FileName};
36 use std::{cmp, mem, slice};
37 use std::path::PathBuf;
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.open, 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.close, 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 impl<'a> Parser<'a> {
352 directory: Option<Directory<'a>>,
353 recurse_into_file_modules: bool,
354 desugar_doc_comments: bool,
355 subparser_name: Option<&'static str>,
357 let mut parser = Parser {
359 token: Token::dummy(),
362 prev_token_kind: PrevTokenKind::Other,
363 restrictions: Restrictions::empty(),
364 recurse_into_file_modules,
365 directory: Directory {
366 path: Cow::from(PathBuf::new()),
367 ownership: DirectoryOwnership::Owned { relative: None }
369 root_module_name: None,
370 expected_tokens: Vec::new(),
371 token_cursor: TokenCursor {
372 frame: TokenCursorFrame::new(
379 desugar_doc_comments,
381 unmatched_angle_bracket_count: 0,
382 max_angle_bracket_count: 0,
383 unclosed_delims: Vec::new(),
384 last_unexpected_token_span: None,
385 last_type_ascription: None,
389 parser.token = parser.next_tok();
391 if let Some(directory) = directory {
392 parser.directory = directory;
393 } else if !parser.token.span.is_dummy() {
394 if let Some(FileName::Real(path)) =
395 &sess.source_map().lookup_char_pos(parser.token.span.lo()).file.unmapped_path {
396 if let Some(directory_path) = path.parent() {
397 parser.directory.path = Cow::from(directory_path.to_path_buf());
402 parser.process_potential_macro_variable();
406 fn next_tok(&mut self) -> Token {
407 let mut next = if self.desugar_doc_comments {
408 self.token_cursor.next_desugared()
410 self.token_cursor.next()
412 if next.span.is_dummy() {
413 // Tweak the location for better diagnostics, but keep syntactic context intact.
414 next.span = self.prev_span.with_ctxt(next.span.ctxt());
419 /// Converts the current token to a string using `self`'s reader.
420 pub fn this_token_to_string(&self) -> String {
421 pprust::token_to_string(&self.token)
424 fn token_descr(&self) -> Option<&'static str> {
425 Some(match &self.token.kind {
426 _ if self.token.is_special_ident() => "reserved identifier",
427 _ if self.token.is_used_keyword() => "keyword",
428 _ if self.token.is_unused_keyword() => "reserved keyword",
429 token::DocComment(..) => "doc comment",
434 pub(super) fn this_token_descr(&self) -> String {
435 if let Some(prefix) = self.token_descr() {
436 format!("{} `{}`", prefix, self.this_token_to_string())
438 format!("`{}`", self.this_token_to_string())
442 crate fn unexpected<T>(&mut self) -> PResult<'a, T> {
443 match self.expect_one_of(&[], &[]) {
445 Ok(_) => unreachable!(),
449 /// Expects and consumes the token `t`. Signals an error if the next token is not `t`.
450 pub fn expect(&mut self, t: &TokenKind) -> PResult<'a, bool /* recovered */> {
451 if self.expected_tokens.is_empty() {
452 if self.token == *t {
456 self.unexpected_try_recover(t)
459 self.expect_one_of(slice::from_ref(t), &[])
463 /// Expect next token to be edible or inedible token. If edible,
464 /// then consume it; if inedible, then return without consuming
465 /// anything. Signal a fatal error if next token is unexpected.
466 pub fn expect_one_of(
468 edible: &[TokenKind],
469 inedible: &[TokenKind],
470 ) -> PResult<'a, bool /* recovered */> {
471 if edible.contains(&self.token.kind) {
474 } else if inedible.contains(&self.token.kind) {
475 // leave it in the input
477 } else if self.last_unexpected_token_span == Some(self.token.span) {
480 self.expected_one_of_not_found(edible, inedible)
484 fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
485 self.parse_ident_common(true)
488 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, ast::Ident> {
489 match self.token.kind {
490 token::Ident(name, _) => {
491 if self.token.is_reserved_ident() {
492 let mut err = self.expected_ident_found();
499 let span = self.token.span;
501 Ok(Ident::new(name, span))
504 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
505 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
507 self.expected_ident_found()
513 /// Checks if the next token is `tok`, and returns `true` if so.
515 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
517 fn check(&mut self, tok: &TokenKind) -> bool {
518 let is_present = self.token == *tok;
519 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
523 /// Consumes a token 'tok' if it exists. Returns whether the given token was present.
524 pub fn eat(&mut self, tok: &TokenKind) -> bool {
525 let is_present = self.check(tok);
526 if is_present { self.bump() }
530 /// If the next token is the given keyword, returns `true` without eating it.
531 /// An expectation is also added for diagnostics purposes.
532 fn check_keyword(&mut self, kw: Symbol) -> bool {
533 self.expected_tokens.push(TokenType::Keyword(kw));
534 self.token.is_keyword(kw)
537 /// If the next token is the given keyword, eats it and returns `true`.
538 /// Otherwise, returns `false`. An expectation is also added for diagnostics purposes.
539 fn eat_keyword(&mut self, kw: Symbol) -> bool {
540 if self.check_keyword(kw) {
548 fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool {
549 if self.token.is_keyword(kw) {
557 /// If the given word is not a keyword, signals an error.
558 /// If the next token is not the given word, signals an error.
559 /// Otherwise, eats it.
560 fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> {
561 if !self.eat_keyword(kw) {
568 fn check_or_expected(&mut self, ok: bool, typ: TokenType) -> bool {
572 self.expected_tokens.push(typ);
577 fn check_ident(&mut self) -> bool {
578 self.check_or_expected(self.token.is_ident(), TokenType::Ident)
581 fn check_path(&mut self) -> bool {
582 self.check_or_expected(self.token.is_path_start(), TokenType::Path)
585 fn check_type(&mut self) -> bool {
586 self.check_or_expected(self.token.can_begin_type(), TokenType::Type)
589 fn check_const_arg(&mut self) -> bool {
590 self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const)
593 /// Checks to see if the next token is either `+` or `+=`.
594 /// Otherwise returns `false`.
595 fn check_plus(&mut self) -> bool {
596 self.check_or_expected(
597 self.token.is_like_plus(),
598 TokenType::Token(token::BinOp(token::Plus)),
602 /// Expects and consumes a `+`. if `+=` is seen, replaces it with a `=`
603 /// and continues. If a `+` is not seen, returns `false`.
605 /// This is used when token-splitting `+=` into `+`.
606 /// See issue #47856 for an example of when this may occur.
607 fn eat_plus(&mut self) -> bool {
608 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
609 match self.token.kind {
610 token::BinOp(token::Plus) => {
614 token::BinOpEq(token::Plus) => {
615 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
616 self.bump_with(token::Eq, span);
623 /// Expects and consumes an `&`. If `&&` is seen, replaces it with a single
624 /// `&` and continues. If an `&` is not seen, signals an error.
625 fn expect_and(&mut self) -> PResult<'a, ()> {
626 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
627 match self.token.kind {
628 token::BinOp(token::And) => {
633 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
634 Ok(self.bump_with(token::BinOp(token::And), span))
636 _ => self.unexpected()
640 /// Expects and consumes an `|`. If `||` is seen, replaces it with a single
641 /// `|` and continues. If an `|` is not seen, signals an error.
642 fn expect_or(&mut self) -> PResult<'a, ()> {
643 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or)));
644 match self.token.kind {
645 token::BinOp(token::Or) => {
650 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
651 Ok(self.bump_with(token::BinOp(token::Or), span))
653 _ => self.unexpected()
657 /// Attempts to consume a `<`. If `<<` is seen, replaces it with a single
658 /// `<` and continue. If `<-` is seen, replaces it with a single `<`
659 /// and continue. If a `<` is not seen, returns false.
661 /// This is meant to be used when parsing generics on a path to get the
663 fn eat_lt(&mut self) -> bool {
664 self.expected_tokens.push(TokenType::Token(token::Lt));
665 let ate = match self.token.kind {
670 token::BinOp(token::Shl) => {
671 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
672 self.bump_with(token::Lt, span);
676 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
677 self.bump_with(token::BinOp(token::Minus), span);
684 // See doc comment for `unmatched_angle_bracket_count`.
685 self.unmatched_angle_bracket_count += 1;
686 self.max_angle_bracket_count += 1;
687 debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count);
693 fn expect_lt(&mut self) -> PResult<'a, ()> {
701 /// Expects and consumes a single `>` token. if a `>>` is seen, replaces it
702 /// with a single `>` and continues. If a `>` is not seen, signals an error.
703 fn expect_gt(&mut self) -> PResult<'a, ()> {
704 self.expected_tokens.push(TokenType::Token(token::Gt));
705 let ate = match self.token.kind {
710 token::BinOp(token::Shr) => {
711 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
712 Some(self.bump_with(token::Gt, span))
714 token::BinOpEq(token::Shr) => {
715 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
716 Some(self.bump_with(token::Ge, span))
719 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
720 Some(self.bump_with(token::Eq, span))
727 // See doc comment for `unmatched_angle_bracket_count`.
728 if self.unmatched_angle_bracket_count > 0 {
729 self.unmatched_angle_bracket_count -= 1;
730 debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count);
735 None => self.unexpected(),
739 /// Parses a sequence, including the closing delimiter. The function
740 /// `f` must consume tokens until reaching the next separator or
742 fn parse_seq_to_end<T>(
746 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
747 ) -> PResult<'a, Vec<T>> {
748 let (val, _, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
755 /// Parses a sequence, not including the closing delimiter. The function
756 /// `f` must consume tokens until reaching the next separator or
758 fn parse_seq_to_before_end<T>(
762 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
763 ) -> PResult<'a, (Vec<T>, bool, bool)> {
764 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
767 fn expect_any_with_type(&mut self, kets: &[&TokenKind], expect: TokenExpectType) -> bool {
768 kets.iter().any(|k| {
770 TokenExpectType::Expect => self.check(k),
771 TokenExpectType::NoExpect => self.token == **k,
776 fn parse_seq_to_before_tokens<T>(
780 expect: TokenExpectType,
781 mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
782 ) -> PResult<'a, (Vec<T>, bool /* trailing */, bool /* recovered */)> {
783 let mut first = true;
784 let mut recovered = false;
785 let mut trailing = false;
787 while !self.expect_any_with_type(kets, expect) {
788 if let token::CloseDelim(..) | token::Eof = self.token.kind {
791 if let Some(ref t) = sep.sep {
795 match self.expect(t) {
802 // Attempt to keep parsing if it was a similar separator.
803 if let Some(ref tokens) = t.similar_tokens() {
804 if tokens.contains(&self.token.kind) {
809 // Attempt to keep parsing if it was an omitted separator.
824 if sep.trailing_sep_allowed && self.expect_any_with_type(kets, expect) {
833 Ok((v, trailing, recovered))
836 /// Parses a sequence, including the closing delimiter. The function
837 /// `f` must consume tokens until reaching the next separator or
839 fn parse_unspanned_seq<T>(
844 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
845 ) -> PResult<'a, (Vec<T>, bool)> {
847 let (result, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
851 Ok((result, trailing))
854 fn parse_delim_comma_seq<T>(
857 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
858 ) -> PResult<'a, (Vec<T>, bool)> {
859 self.parse_unspanned_seq(
860 &token::OpenDelim(delim),
861 &token::CloseDelim(delim),
862 SeqSep::trailing_allowed(token::Comma),
867 fn parse_paren_comma_seq<T>(
869 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
870 ) -> PResult<'a, (Vec<T>, bool)> {
871 self.parse_delim_comma_seq(token::Paren, f)
874 /// Advance the parser by one token.
875 pub fn bump(&mut self) {
876 if self.prev_token_kind == PrevTokenKind::Eof {
877 // Bumping after EOF is a bad sign, usually an infinite loop.
878 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
881 self.prev_span = self.meta_var_span.take().unwrap_or(self.token.span);
883 // Record last token kind for possible error recovery.
884 self.prev_token_kind = match self.token.kind {
885 token::DocComment(..) => PrevTokenKind::DocComment,
886 token::Comma => PrevTokenKind::Comma,
887 token::BinOp(token::Plus) => PrevTokenKind::Plus,
888 token::BinOp(token::Or) => PrevTokenKind::BitOr,
889 token::Interpolated(..) => PrevTokenKind::Interpolated,
890 token::Eof => PrevTokenKind::Eof,
891 token::Ident(..) => PrevTokenKind::Ident,
892 _ => PrevTokenKind::Other,
895 self.token = self.next_tok();
896 self.expected_tokens.clear();
897 // Check after each token.
898 self.process_potential_macro_variable();
901 /// Advances the parser using provided token as a next one. Use this when
902 /// consuming a part of a token. For example a single `<` from `<<`.
903 fn bump_with(&mut self, next: TokenKind, span: Span) {
904 self.prev_span = self.token.span.with_hi(span.lo());
905 // It would be incorrect to record the kind of the current token, but
906 // fortunately for tokens currently using `bump_with`, the
907 // `prev_token_kind` will be of no use anyway.
908 self.prev_token_kind = PrevTokenKind::Other;
909 self.token = Token::new(next, span);
910 self.expected_tokens.clear();
913 /// Look-ahead `dist` tokens of `self.token` and get access to that token there.
914 /// When `dist == 0` then the current token is looked at.
915 pub fn look_ahead<R>(&self, dist: usize, looker: impl FnOnce(&Token) -> R) -> R {
917 return looker(&self.token);
920 let frame = &self.token_cursor.frame;
921 looker(&match frame.tree_cursor.look_ahead(dist - 1) {
922 Some(tree) => match tree {
923 TokenTree::Token(token) => token,
924 TokenTree::Delimited(dspan, delim, _) =>
925 Token::new(token::OpenDelim(delim), dspan.open),
927 None => Token::new(token::CloseDelim(frame.delim), frame.span.close)
931 /// Returns whether any of the given keywords are `dist` tokens ahead of the current one.
932 fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool {
933 self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw)))
936 /// Parses asyncness: `async` or nothing.
937 fn parse_asyncness(&mut self) -> IsAsync {
938 if self.eat_keyword(kw::Async) {
940 closure_id: DUMMY_NODE_ID,
941 return_impl_trait_id: DUMMY_NODE_ID,
948 /// Parses unsafety: `unsafe` or nothing.
949 fn parse_unsafety(&mut self) -> Unsafety {
950 if self.eat_keyword(kw::Unsafe) {
957 /// Parses mutability (`mut` or nothing).
958 fn parse_mutability(&mut self) -> Mutability {
959 if self.eat_keyword(kw::Mut) {
962 Mutability::Immutable
966 /// Possibly parses mutability (`const` or `mut`).
967 fn parse_const_or_mut(&mut self) -> Option<Mutability> {
968 if self.eat_keyword(kw::Mut) {
969 Some(Mutability::Mutable)
970 } else if self.eat_keyword(kw::Const) {
971 Some(Mutability::Immutable)
977 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
978 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) =
980 self.expect_no_suffix(self.token.span, "a tuple index", suffix);
982 Ok(Ident::new(symbol, self.prev_span))
984 self.parse_ident_common(false)
988 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (MacDelimiter, TokenStream)> {
989 let delim = match self.token.kind {
990 token::OpenDelim(delim) => delim,
992 let msg = "expected open delimiter";
993 let mut err = self.fatal(msg);
994 err.span_label(self.token.span, msg);
998 let tts = match self.parse_token_tree() {
999 TokenTree::Delimited(_, _, tts) => tts,
1000 _ => unreachable!(),
1002 let delim = match delim {
1003 token::Paren => MacDelimiter::Parenthesis,
1004 token::Bracket => MacDelimiter::Bracket,
1005 token::Brace => MacDelimiter::Brace,
1006 token::NoDelim => self.bug("unexpected no delimiter"),
1008 Ok((delim, tts.into()))
1011 fn parse_or_use_outer_attributes(
1013 already_parsed_attrs: Option<ThinVec<Attribute>>,
1014 ) -> PResult<'a, ThinVec<Attribute>> {
1015 if let Some(attrs) = already_parsed_attrs {
1018 self.parse_outer_attributes().map(|a| a.into())
1022 pub fn process_potential_macro_variable(&mut self) {
1023 self.token = match self.token.kind {
1024 token::Dollar if self.token.span.from_expansion() &&
1025 self.look_ahead(1, |t| t.is_ident()) => {
1027 let name = match self.token.kind {
1028 token::Ident(name, _) => name,
1031 let span = self.prev_span.to(self.token.span);
1033 .struct_span_fatal(span, &format!("unknown macro variable `{}`", name))
1034 .span_label(span, "unknown macro variable")
1039 token::Interpolated(ref nt) => {
1040 self.meta_var_span = Some(self.token.span);
1041 // Interpolated identifier and lifetime tokens are replaced with usual identifier
1042 // and lifetime tokens, so the former are never encountered during normal parsing.
1044 token::NtIdent(ident, is_raw) =>
1045 Token::new(token::Ident(ident.name, is_raw), ident.span),
1046 token::NtLifetime(ident) =>
1047 Token::new(token::Lifetime(ident.name), ident.span),
1055 /// Parses a single token tree from the input.
1056 pub fn parse_token_tree(&mut self) -> TokenTree {
1057 match self.token.kind {
1058 token::OpenDelim(..) => {
1059 let frame = mem::replace(&mut self.token_cursor.frame,
1060 self.token_cursor.stack.pop().unwrap());
1061 self.token.span = frame.span.entire();
1063 TokenTree::Delimited(
1066 frame.tree_cursor.stream.into(),
1069 token::CloseDelim(_) | token::Eof => unreachable!(),
1071 let token = self.token.take();
1073 TokenTree::Token(token)
1078 /// Parses a stream of tokens into a list of `TokenTree`s, up to EOF.
1079 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
1080 let mut tts = Vec::new();
1081 while self.token != token::Eof {
1082 tts.push(self.parse_token_tree());
1087 pub fn parse_tokens(&mut self) -> TokenStream {
1088 let mut result = Vec::new();
1090 match self.token.kind {
1091 token::Eof | token::CloseDelim(..) => break,
1092 _ => result.push(self.parse_token_tree().into()),
1095 TokenStream::new(result)
1098 /// Evaluates the closure with restrictions in place.
1100 /// Afters the closure is evaluated, restrictions are reset.
1101 fn with_res<T>(&mut self, res: Restrictions, f: impl FnOnce(&mut Self) -> T) -> T {
1102 let old = self.restrictions;
1103 self.restrictions = res;
1105 self.restrictions = old;
1109 fn is_crate_vis(&self) -> bool {
1110 self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
1113 /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
1114 /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
1115 /// If the following element can't be a tuple (i.e., it's a function definition), then
1116 /// it's not a tuple struct field), and the contents within the parentheses isn't valid,
1117 /// so emit a proper diagnostic.
1118 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
1119 maybe_whole!(self, NtVis, |x| x);
1121 self.expected_tokens.push(TokenType::Keyword(kw::Crate));
1122 if self.is_crate_vis() {
1123 self.bump(); // `crate`
1124 self.sess.gated_spans.crate_visibility_modifier.borrow_mut().push(self.prev_span);
1125 return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
1128 if !self.eat_keyword(kw::Pub) {
1129 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
1130 // keyword to grab a span from for inherited visibility; an empty span at the
1131 // beginning of the current token would seem to be the "Schelling span".
1132 return Ok(respan(self.token.span.shrink_to_lo(), VisibilityKind::Inherited))
1134 let lo = self.prev_span;
1136 if self.check(&token::OpenDelim(token::Paren)) {
1137 // We don't `self.bump()` the `(` yet because this might be a struct definition where
1138 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
1139 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
1140 // by the following tokens.
1141 if self.is_keyword_ahead(1, &[kw::Crate])
1142 && self.look_ahead(2, |t| t != &token::ModSep) // account for `pub(crate::foo)`
1144 // Parse `pub(crate)`.
1146 self.bump(); // `crate`
1147 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1148 let vis = VisibilityKind::Crate(CrateSugar::PubCrate);
1149 return Ok(respan(lo.to(self.prev_span), vis));
1150 } else if self.is_keyword_ahead(1, &[kw::In]) {
1151 // Parse `pub(in path)`.
1153 self.bump(); // `in`
1154 let path = self.parse_path(PathStyle::Mod)?; // `path`
1155 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1156 let vis = VisibilityKind::Restricted {
1158 id: ast::DUMMY_NODE_ID,
1160 return Ok(respan(lo.to(self.prev_span), vis));
1161 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren))
1162 && self.is_keyword_ahead(1, &[kw::Super, kw::SelfLower])
1164 // Parse `pub(self)` or `pub(super)`.
1166 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
1167 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1168 let vis = VisibilityKind::Restricted {
1170 id: ast::DUMMY_NODE_ID,
1172 return Ok(respan(lo.to(self.prev_span), vis));
1173 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct.
1174 self.recover_incorrect_vis_restriction()?;
1175 // Emit diagnostic, but continue with public visibility.
1179 Ok(respan(lo, VisibilityKind::Public))
1182 /// Recovery for e.g. `pub(something) fn ...` or `struct X { pub(something) y: Z }`
1183 fn recover_incorrect_vis_restriction(&mut self) -> PResult<'a, ()> {
1185 let path = self.parse_path(PathStyle::Mod)?;
1186 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1188 let msg = "incorrect visibility restriction";
1189 let suggestion = r##"some possible visibility restrictions are:
1190 `pub(crate)`: visible only on the current crate
1191 `pub(super)`: visible only in the current module's parent
1192 `pub(in path::to::module)`: visible only on the specified path"##;
1194 let path_str = pprust::path_to_string(&path);
1196 struct_span_err!(self.sess.span_diagnostic, path.span, E0704, "{}", msg)
1200 &format!("make this visible only to module `{}` with `in`", path_str),
1201 format!("in {}", path_str),
1202 Applicability::MachineApplicable,
1209 /// Parses `extern` followed by an optional ABI string, or nothing.
1210 fn parse_extern_abi(&mut self) -> PResult<'a, Abi> {
1211 if self.eat_keyword(kw::Extern) {
1212 Ok(self.parse_opt_abi()?.unwrap_or(Abi::C))
1218 /// Parses a string as an ABI spec on an extern type or module. Consumes
1219 /// the `extern` keyword, if one is found.
1220 fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
1221 match self.token.kind {
1222 token::Literal(token::Lit { kind: token::Str, symbol, suffix }) |
1223 token::Literal(token::Lit { kind: token::StrRaw(..), symbol, suffix }) => {
1224 self.expect_no_suffix(self.token.span, "an ABI spec", suffix);
1226 match abi::lookup(&symbol.as_str()) {
1227 Some(abi) => Ok(Some(abi)),
1229 self.error_on_invalid_abi(symbol);
1238 /// Emit an error where `symbol` is an invalid ABI.
1239 fn error_on_invalid_abi(&self, symbol: Symbol) {
1240 let prev_span = self.prev_span;
1242 self.sess.span_diagnostic,
1245 "invalid ABI: found `{}`",
1248 .span_label(prev_span, "invalid ABI")
1249 .help(&format!("valid ABIs: {}", abi::all_names().join(", ")))
1253 /// We are parsing `async fn`. If we are on Rust 2015, emit an error.
1254 fn ban_async_in_2015(&self, async_span: Span) {
1255 if async_span.rust_2015() {
1257 .struct_span_err_with_code(
1259 "`async fn` is not permitted in the 2015 edition",
1260 DiagnosticId::Error("E0670".into())
1266 fn collect_tokens<R>(
1268 f: impl FnOnce(&mut Self) -> PResult<'a, R>,
1269 ) -> PResult<'a, (R, TokenStream)> {
1270 // Record all tokens we parse when parsing this item.
1271 let mut tokens = Vec::new();
1272 let prev_collecting = match self.token_cursor.frame.last_token {
1273 LastToken::Collecting(ref mut list) => {
1274 Some(mem::take(list))
1276 LastToken::Was(ref mut last) => {
1277 tokens.extend(last.take());
1281 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
1282 let prev = self.token_cursor.stack.len();
1284 let last_token = if self.token_cursor.stack.len() == prev {
1285 &mut self.token_cursor.frame.last_token
1286 } else if self.token_cursor.stack.get(prev).is_none() {
1287 // This can happen due to a bad interaction of two unrelated recovery mechanisms with
1288 // mismatched delimiters *and* recovery lookahead on the likely typo `pub ident(`
1290 return Ok((ret?, TokenStream::default()));
1292 &mut self.token_cursor.stack[prev].last_token
1295 // Pull out the tokens that we've collected from the call to `f` above.
1296 let mut collected_tokens = match *last_token {
1297 LastToken::Collecting(ref mut v) => mem::take(v),
1298 LastToken::Was(ref was) => {
1299 let msg = format!("our vector went away? - found Was({:?})", was);
1300 debug!("collect_tokens: {}", msg);
1301 self.sess.span_diagnostic.delay_span_bug(self.token.span, &msg);
1302 // This can happen due to a bad interaction of two unrelated recovery mechanisms
1303 // with mismatched delimiters *and* recovery lookahead on the likely typo
1304 // `pub ident(` (#62895, different but similar to the case above).
1305 return Ok((ret?, TokenStream::default()));
1309 // If we're not at EOF our current token wasn't actually consumed by
1310 // `f`, but it'll still be in our list that we pulled out. In that case
1312 let extra_token = if self.token != token::Eof {
1313 collected_tokens.pop()
1318 // If we were previously collecting tokens, then this was a recursive
1319 // call. In that case we need to record all the tokens we collected in
1320 // our parent list as well. To do that we push a clone of our stream
1321 // onto the previous list.
1322 match prev_collecting {
1324 list.extend(collected_tokens.iter().cloned());
1325 list.extend(extra_token);
1326 *last_token = LastToken::Collecting(list);
1329 *last_token = LastToken::Was(extra_token);
1333 Ok((ret?, TokenStream::new(collected_tokens)))
1337 fn is_import_coupler(&mut self) -> bool {
1338 self.check(&token::ModSep) &&
1339 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
1340 *t == token::BinOp(token::Star))
1343 fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
1344 let ret = match self.token.kind {
1345 token::Literal(token::Lit { kind: token::Str, symbol, suffix }) =>
1346 (symbol, ast::StrStyle::Cooked, suffix),
1347 token::Literal(token::Lit { kind: token::StrRaw(n), symbol, suffix }) =>
1348 (symbol, ast::StrStyle::Raw(n), suffix),
1355 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
1356 match self.parse_optional_str() {
1357 Some((s, style, suf)) => {
1358 let sp = self.prev_span;
1359 self.expect_no_suffix(sp, "a string literal", suf);
1363 let msg = "expected string literal";
1364 let mut err = self.fatal(msg);
1365 err.span_label(self.token.span, msg);
1372 crate fn make_unclosed_delims_error(
1373 unmatched: UnmatchedBrace,
1375 ) -> Option<DiagnosticBuilder<'_>> {
1376 // `None` here means an `Eof` was found. We already emit those errors elsewhere, we add them to
1377 // `unmatched_braces` only for error recovery in the `Parser`.
1378 let found_delim = unmatched.found_delim?;
1379 let mut err = sess.span_diagnostic.struct_span_err(unmatched.found_span, &format!(
1380 "incorrect close delimiter: `{}`",
1381 pprust::token_kind_to_string(&token::CloseDelim(found_delim)),
1383 err.span_label(unmatched.found_span, "incorrect close delimiter");
1384 if let Some(sp) = unmatched.candidate_span {
1385 err.span_label(sp, "close delimiter possibly meant for this");
1387 if let Some(sp) = unmatched.unclosed_span {
1388 err.span_label(sp, "un-closed delimiter");
1393 pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, sess: &ParseSess) {
1394 *sess.reached_eof.borrow_mut() |= unclosed_delims.iter()
1395 .any(|unmatched_delim| unmatched_delim.found_delim.is_none());
1396 for unmatched in unclosed_delims.drain(..) {
1397 make_unclosed_delims_error(unmatched, sess).map(|mut e| e.emit());