8 pub use path::PathStyle;
12 use diagnostics::Error;
14 use crate::{Directory, DirectoryOwnership};
15 use crate::lexer::UnmatchedBrace;
18 self, DUMMY_NODE_ID, AttrStyle, Attribute, CrateSugar, Extern, Ident, StrLit,
19 IsAsync, MacDelimiter, Mutability, Visibility, VisibilityKind, Unsafety,
22 use syntax::print::pprust;
24 use syntax::token::{self, Token, TokenKind, DelimToken};
25 use syntax::tokenstream::{self, DelimSpan, TokenTree, TokenStream, TreeAndJoint};
26 use syntax::sess::ParseSess;
27 use syntax::source_map::respan;
28 use syntax::struct_span_err;
29 use syntax::util::comments::{doc_comment_style, strip_doc_comment_decoration};
30 use syntax_pos::symbol::{kw, sym, Symbol};
31 use syntax_pos::{Span, BytePos, DUMMY_SP, FileName};
32 use rustc_data_structures::thin_vec::ThinVec;
33 use errors::{PResult, Applicability, DiagnosticBuilder, FatalError};
37 use std::{cmp, mem, slice};
38 use std::path::PathBuf;
40 use rustc_error_codes::*;
43 struct Restrictions: u8 {
44 const STMT_EXPR = 1 << 0;
45 const NO_STRUCT_LITERAL = 1 << 1;
49 #[derive(Clone, Copy, PartialEq, Debug)]
56 #[derive(Clone, Copy, PartialEq, Debug)]
62 /// Like `maybe_whole_expr`, but for things other than expressions.
64 macro_rules! maybe_whole {
65 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
66 if let token::Interpolated(nt) = &$p.token.kind {
67 if let token::$constructor(x) = &**nt {
76 /// If the next tokens are ill-formed `$ty::` recover them as `<$ty>::`.
78 macro_rules! maybe_recover_from_interpolated_ty_qpath {
79 ($self: expr, $allow_qpath_recovery: expr) => {
80 if $allow_qpath_recovery && $self.look_ahead(1, |t| t == &token::ModSep) {
81 if let token::Interpolated(nt) = &$self.token.kind {
82 if let token::NtTy(ty) = &**nt {
85 return $self.maybe_recover_from_bad_qpath_stage_2($self.prev_span, ty);
92 #[derive(Debug, Clone, Copy, PartialEq)]
104 // NOTE: `Ident`s are handled by `common.rs`.
107 pub struct Parser<'a> {
108 pub sess: &'a ParseSess,
109 /// The current normalized token.
110 /// "Normalized" means that some interpolated tokens
111 /// (`$i: ident` and `$l: lifetime` meta-variables) are replaced
112 /// with non-interpolated identifier and lifetime tokens they refer to.
113 /// Perhaps the normalized / non-normalized setup can be simplified somehow.
115 /// The span of the current non-normalized token.
116 meta_var_span: Option<Span>,
117 /// The span of the previous non-normalized token.
119 /// The kind of the previous normalized token (in simplified form).
120 prev_token_kind: PrevTokenKind,
121 restrictions: Restrictions,
122 /// Used to determine the path to externally loaded source files.
123 pub(super) directory: Directory<'a>,
124 /// `true` to parse sub-modules in other files.
125 pub(super) recurse_into_file_modules: bool,
126 /// Name of the root module this parser originated from. If `None`, then the
127 /// name is not known. This does not change while the parser is descending
128 /// into modules, and sub-parsers have new values for this name.
129 pub root_module_name: Option<String>,
130 expected_tokens: Vec<TokenType>,
131 token_cursor: TokenCursor,
132 desugar_doc_comments: bool,
133 /// `true` we should configure out of line modules as we parse.
135 /// This field is used to keep track of how many left angle brackets we have seen. This is
136 /// required in order to detect extra leading left angle brackets (`<` characters) and error
139 /// See the comments in the `parse_path_segment` function for more details.
140 unmatched_angle_bracket_count: u32,
141 max_angle_bracket_count: u32,
142 /// A list of all unclosed delimiters found by the lexer. If an entry is used for error recovery
143 /// it gets removed from here. Every entry left at the end gets emitted as an independent
145 pub(super) unclosed_delims: Vec<UnmatchedBrace>,
146 last_unexpected_token_span: Option<Span>,
147 pub last_type_ascription: Option<(Span, bool /* likely path typo */)>,
148 /// If present, this `Parser` is not parsing Rust code but rather a macro call.
149 subparser_name: Option<&'static str>,
152 impl<'a> Drop for Parser<'a> {
154 emit_unclosed_delims(&mut self.unclosed_delims, &self.sess);
160 frame: TokenCursorFrame,
161 stack: Vec<TokenCursorFrame>,
165 struct TokenCursorFrame {
166 delim: token::DelimToken,
169 tree_cursor: tokenstream::Cursor,
171 last_token: LastToken,
174 /// This is used in `TokenCursorFrame` above to track tokens that are consumed
175 /// by the parser, and then that's transitively used to record the tokens that
176 /// each parse AST item is created with.
178 /// Right now this has two states, either collecting tokens or not collecting
179 /// tokens. If we're collecting tokens we just save everything off into a local
180 /// `Vec`. This should eventually though likely save tokens from the original
181 /// token stream and just use slicing of token streams to avoid creation of a
182 /// whole new vector.
184 /// The second state is where we're passively not recording tokens, but the last
185 /// token is still tracked for when we want to start recording tokens. This
186 /// "last token" means that when we start recording tokens we'll want to ensure
187 /// that this, the first token, is included in the output.
189 /// You can find some more example usage of this in the `collect_tokens` method
193 Collecting(Vec<TreeAndJoint>),
194 Was(Option<TreeAndJoint>),
197 impl TokenCursorFrame {
198 fn new(span: DelimSpan, delim: DelimToken, tts: &TokenStream) -> Self {
202 open_delim: delim == token::NoDelim,
203 tree_cursor: tts.clone().into_trees(),
204 close_delim: delim == token::NoDelim,
205 last_token: LastToken::Was(None),
211 fn next(&mut self) -> Token {
213 let tree = if !self.frame.open_delim {
214 self.frame.open_delim = true;
215 TokenTree::open_tt(self.frame.span, self.frame.delim)
216 } else if let Some(tree) = self.frame.tree_cursor.next() {
218 } else if !self.frame.close_delim {
219 self.frame.close_delim = true;
220 TokenTree::close_tt(self.frame.span, self.frame.delim)
221 } else if let Some(frame) = self.stack.pop() {
225 return Token::new(token::Eof, DUMMY_SP);
228 match self.frame.last_token {
229 LastToken::Collecting(ref mut v) => v.push(tree.clone().into()),
230 LastToken::Was(ref mut t) => *t = Some(tree.clone().into()),
234 TokenTree::Token(token) => return token,
235 TokenTree::Delimited(sp, delim, tts) => {
236 let frame = TokenCursorFrame::new(sp, delim, &tts);
237 self.stack.push(mem::replace(&mut self.frame, frame));
243 fn next_desugared(&mut self) -> Token {
244 let (name, sp) = match self.next() {
245 Token { kind: token::DocComment(name), span } => (name, span),
249 let stripped = strip_doc_comment_decoration(&name.as_str());
251 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
252 // required to wrap the text.
253 let mut num_of_hashes = 0;
255 for ch in stripped.chars() {
258 '#' if count > 0 => count + 1,
261 num_of_hashes = cmp::max(num_of_hashes, count);
264 let delim_span = DelimSpan::from_single(sp);
265 let body = TokenTree::Delimited(
269 TokenTree::token(token::Ident(sym::doc, false), sp),
270 TokenTree::token(token::Eq, sp),
271 TokenTree::token(TokenKind::lit(
272 token::StrRaw(num_of_hashes), Symbol::intern(&stripped), None
275 .iter().cloned().collect::<TokenStream>().into(),
278 self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new(
281 &if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
282 [TokenTree::token(token::Pound, sp), TokenTree::token(token::Not, sp), body]
283 .iter().cloned().collect::<TokenStream>()
285 [TokenTree::token(token::Pound, sp), body]
286 .iter().cloned().collect::<TokenStream>()
294 #[derive(Clone, PartialEq)]
307 fn to_string(&self) -> String {
309 TokenType::Token(ref t) => format!("`{}`", pprust::token_kind_to_string(t)),
310 TokenType::Keyword(kw) => format!("`{}`", kw),
311 TokenType::Operator => "an operator".to_string(),
312 TokenType::Lifetime => "lifetime".to_string(),
313 TokenType::Ident => "identifier".to_string(),
314 TokenType::Path => "path".to_string(),
315 TokenType::Type => "type".to_string(),
316 TokenType::Const => "const".to_string(),
321 #[derive(Copy, Clone, Debug)]
322 enum TokenExpectType {
327 /// A sequence separator.
329 /// The separator token.
330 sep: Option<TokenKind>,
331 /// `true` if a trailing separator is allowed.
332 trailing_sep_allowed: bool,
336 fn trailing_allowed(t: TokenKind) -> SeqSep {
339 trailing_sep_allowed: true,
343 fn none() -> SeqSep {
346 trailing_sep_allowed: false,
351 impl<'a> Parser<'a> {
355 directory: Option<Directory<'a>>,
356 recurse_into_file_modules: bool,
357 desugar_doc_comments: bool,
358 subparser_name: Option<&'static str>,
360 let mut parser = Parser {
362 token: Token::dummy(),
365 prev_token_kind: PrevTokenKind::Other,
366 restrictions: Restrictions::empty(),
367 recurse_into_file_modules,
368 directory: Directory {
369 path: Cow::from(PathBuf::new()),
370 ownership: DirectoryOwnership::Owned { relative: None }
372 root_module_name: None,
373 expected_tokens: Vec::new(),
374 token_cursor: TokenCursor {
375 frame: TokenCursorFrame::new(
382 desugar_doc_comments,
384 unmatched_angle_bracket_count: 0,
385 max_angle_bracket_count: 0,
386 unclosed_delims: Vec::new(),
387 last_unexpected_token_span: None,
388 last_type_ascription: None,
392 parser.token = parser.next_tok();
394 if let Some(directory) = directory {
395 parser.directory = directory;
396 } else if !parser.token.span.is_dummy() {
397 if let Some(FileName::Real(path)) =
398 &sess.source_map().lookup_char_pos(parser.token.span.lo()).file.unmapped_path {
399 if let Some(directory_path) = path.parent() {
400 parser.directory.path = Cow::from(directory_path.to_path_buf());
405 parser.process_potential_macro_variable();
409 fn next_tok(&mut self) -> Token {
410 let mut next = if self.desugar_doc_comments {
411 self.token_cursor.next_desugared()
413 self.token_cursor.next()
415 if next.span.is_dummy() {
416 // Tweak the location for better diagnostics, but keep syntactic context intact.
417 next.span = self.prev_span.with_ctxt(next.span.ctxt());
422 /// Converts the current token to a string using `self`'s reader.
423 pub fn this_token_to_string(&self) -> String {
424 pprust::token_to_string(&self.token)
427 fn token_descr(&self) -> Option<&'static str> {
428 Some(match &self.token.kind {
429 _ if self.token.is_special_ident() => "reserved identifier",
430 _ if self.token.is_used_keyword() => "keyword",
431 _ if self.token.is_unused_keyword() => "reserved keyword",
432 token::DocComment(..) => "doc comment",
437 pub(super) fn this_token_descr(&self) -> String {
438 if let Some(prefix) = self.token_descr() {
439 format!("{} `{}`", prefix, self.this_token_to_string())
441 format!("`{}`", self.this_token_to_string())
445 crate fn unexpected<T>(&mut self) -> PResult<'a, T> {
446 match self.expect_one_of(&[], &[]) {
448 // We can get `Ok(true)` from `recover_closing_delimiter`
449 // which is called in `expected_one_of_not_found`.
450 Ok(_) => FatalError.raise(),
454 /// Expects and consumes the token `t`. Signals an error if the next token is not `t`.
455 pub fn expect(&mut self, t: &TokenKind) -> PResult<'a, bool /* recovered */> {
456 if self.expected_tokens.is_empty() {
457 if self.token == *t {
461 self.unexpected_try_recover(t)
464 self.expect_one_of(slice::from_ref(t), &[])
468 /// Expect next token to be edible or inedible token. If edible,
469 /// then consume it; if inedible, then return without consuming
470 /// anything. Signal a fatal error if next token is unexpected.
471 pub fn expect_one_of(
473 edible: &[TokenKind],
474 inedible: &[TokenKind],
475 ) -> PResult<'a, bool /* recovered */> {
476 if edible.contains(&self.token.kind) {
479 } else if inedible.contains(&self.token.kind) {
480 // leave it in the input
482 } else if self.last_unexpected_token_span == Some(self.token.span) {
485 self.expected_one_of_not_found(edible, inedible)
489 fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
490 self.parse_ident_common(true)
493 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, ast::Ident> {
494 match self.token.kind {
495 token::Ident(name, _) => {
496 if self.token.is_reserved_ident() {
497 let mut err = self.expected_ident_found();
504 let span = self.token.span;
506 Ok(Ident::new(name, span))
509 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
510 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
512 self.expected_ident_found()
518 /// Checks if the next token is `tok`, and returns `true` if so.
520 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
522 fn check(&mut self, tok: &TokenKind) -> bool {
523 let is_present = self.token == *tok;
524 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
528 /// Consumes a token 'tok' if it exists. Returns whether the given token was present.
529 pub fn eat(&mut self, tok: &TokenKind) -> bool {
530 let is_present = self.check(tok);
531 if is_present { self.bump() }
535 /// If the next token is the given keyword, returns `true` without eating it.
536 /// An expectation is also added for diagnostics purposes.
537 fn check_keyword(&mut self, kw: Symbol) -> bool {
538 self.expected_tokens.push(TokenType::Keyword(kw));
539 self.token.is_keyword(kw)
542 /// If the next token is the given keyword, eats it and returns `true`.
543 /// Otherwise, returns `false`. An expectation is also added for diagnostics purposes.
544 fn eat_keyword(&mut self, kw: Symbol) -> bool {
545 if self.check_keyword(kw) {
553 fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool {
554 if self.token.is_keyword(kw) {
562 /// If the given word is not a keyword, signals an error.
563 /// If the next token is not the given word, signals an error.
564 /// Otherwise, eats it.
565 fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> {
566 if !self.eat_keyword(kw) {
573 fn check_or_expected(&mut self, ok: bool, typ: TokenType) -> bool {
577 self.expected_tokens.push(typ);
582 fn check_ident(&mut self) -> bool {
583 self.check_or_expected(self.token.is_ident(), TokenType::Ident)
586 fn check_path(&mut self) -> bool {
587 self.check_or_expected(self.token.is_path_start(), TokenType::Path)
590 fn check_type(&mut self) -> bool {
591 self.check_or_expected(self.token.can_begin_type(), TokenType::Type)
594 fn check_const_arg(&mut self) -> bool {
595 self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const)
598 /// Checks to see if the next token is either `+` or `+=`.
599 /// Otherwise returns `false`.
600 fn check_plus(&mut self) -> bool {
601 self.check_or_expected(
602 self.token.is_like_plus(),
603 TokenType::Token(token::BinOp(token::Plus)),
607 /// Expects and consumes a `+`. if `+=` is seen, replaces it with a `=`
608 /// and continues. If a `+` is not seen, returns `false`.
610 /// This is used when token-splitting `+=` into `+`.
611 /// See issue #47856 for an example of when this may occur.
612 fn eat_plus(&mut self) -> bool {
613 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
614 match self.token.kind {
615 token::BinOp(token::Plus) => {
619 token::BinOpEq(token::Plus) => {
620 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
621 self.bump_with(token::Eq, span);
628 /// Expects and consumes an `&`. If `&&` is seen, replaces it with a single
629 /// `&` and continues. If an `&` is not seen, signals an error.
630 fn expect_and(&mut self) -> PResult<'a, ()> {
631 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
632 match self.token.kind {
633 token::BinOp(token::And) => {
638 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
639 Ok(self.bump_with(token::BinOp(token::And), span))
641 _ => self.unexpected()
645 /// Expects and consumes an `|`. If `||` is seen, replaces it with a single
646 /// `|` and continues. If an `|` is not seen, signals an error.
647 fn expect_or(&mut self) -> PResult<'a, ()> {
648 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or)));
649 match self.token.kind {
650 token::BinOp(token::Or) => {
655 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
656 Ok(self.bump_with(token::BinOp(token::Or), span))
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 span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
677 self.bump_with(token::Lt, span);
681 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
682 self.bump_with(token::BinOp(token::Minus), span);
689 // See doc comment for `unmatched_angle_bracket_count`.
690 self.unmatched_angle_bracket_count += 1;
691 self.max_angle_bracket_count += 1;
692 debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count);
698 fn expect_lt(&mut self) -> PResult<'a, ()> {
706 /// Expects and consumes a single `>` token. if a `>>` is seen, replaces it
707 /// with a single `>` and continues. If a `>` is not seen, signals an error.
708 fn expect_gt(&mut self) -> PResult<'a, ()> {
709 self.expected_tokens.push(TokenType::Token(token::Gt));
710 let ate = match self.token.kind {
715 token::BinOp(token::Shr) => {
716 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
717 Some(self.bump_with(token::Gt, span))
719 token::BinOpEq(token::Shr) => {
720 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
721 Some(self.bump_with(token::Ge, span))
724 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
725 Some(self.bump_with(token::Eq, span))
732 // See doc comment for `unmatched_angle_bracket_count`.
733 if self.unmatched_angle_bracket_count > 0 {
734 self.unmatched_angle_bracket_count -= 1;
735 debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count);
740 None => self.unexpected(),
744 /// Parses a sequence, including the closing delimiter. The function
745 /// `f` must consume tokens until reaching the next separator or
747 fn parse_seq_to_end<T>(
751 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
752 ) -> PResult<'a, Vec<T>> {
753 let (val, _, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
760 /// Parses a sequence, not including the closing delimiter. The function
761 /// `f` must consume tokens until reaching the next separator or
763 fn parse_seq_to_before_end<T>(
767 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
768 ) -> PResult<'a, (Vec<T>, bool, bool)> {
769 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
772 fn expect_any_with_type(&mut self, kets: &[&TokenKind], expect: TokenExpectType) -> bool {
773 kets.iter().any(|k| {
775 TokenExpectType::Expect => self.check(k),
776 TokenExpectType::NoExpect => self.token == **k,
781 fn parse_seq_to_before_tokens<T>(
785 expect: TokenExpectType,
786 mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
787 ) -> PResult<'a, (Vec<T>, bool /* trailing */, bool /* recovered */)> {
788 let mut first = true;
789 let mut recovered = false;
790 let mut trailing = false;
792 while !self.expect_any_with_type(kets, expect) {
793 if let token::CloseDelim(..) | token::Eof = self.token.kind {
796 if let Some(ref t) = sep.sep {
800 match self.expect(t) {
807 // Attempt to keep parsing if it was a similar separator.
808 if let Some(ref tokens) = t.similar_tokens() {
809 if tokens.contains(&self.token.kind) {
814 // Attempt to keep parsing if it was an omitted separator.
829 if sep.trailing_sep_allowed && self.expect_any_with_type(kets, expect) {
838 Ok((v, trailing, recovered))
841 /// Parses a sequence, including the closing delimiter. The function
842 /// `f` must consume tokens until reaching the next separator or
844 fn parse_unspanned_seq<T>(
849 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
850 ) -> PResult<'a, (Vec<T>, bool)> {
852 let (result, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
856 Ok((result, trailing))
859 fn parse_delim_comma_seq<T>(
862 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
863 ) -> PResult<'a, (Vec<T>, bool)> {
864 self.parse_unspanned_seq(
865 &token::OpenDelim(delim),
866 &token::CloseDelim(delim),
867 SeqSep::trailing_allowed(token::Comma),
872 fn parse_paren_comma_seq<T>(
874 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
875 ) -> PResult<'a, (Vec<T>, bool)> {
876 self.parse_delim_comma_seq(token::Paren, f)
879 /// Advance the parser by one token.
880 pub fn bump(&mut self) {
881 if self.prev_token_kind == PrevTokenKind::Eof {
882 // Bumping after EOF is a bad sign, usually an infinite loop.
883 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
886 self.prev_span = self.meta_var_span.take().unwrap_or(self.token.span);
888 // Record last token kind for possible error recovery.
889 self.prev_token_kind = match self.token.kind {
890 token::DocComment(..) => PrevTokenKind::DocComment,
891 token::Comma => PrevTokenKind::Comma,
892 token::BinOp(token::Plus) => PrevTokenKind::Plus,
893 token::BinOp(token::Or) => PrevTokenKind::BitOr,
894 token::Interpolated(..) => PrevTokenKind::Interpolated,
895 token::Eof => PrevTokenKind::Eof,
896 token::Ident(..) => PrevTokenKind::Ident,
897 _ => PrevTokenKind::Other,
900 self.token = self.next_tok();
901 self.expected_tokens.clear();
902 // Check after each token.
903 self.process_potential_macro_variable();
906 /// Advances the parser using provided token as a next one. Use this when
907 /// consuming a part of a token. For example a single `<` from `<<`.
908 fn bump_with(&mut self, next: TokenKind, span: Span) {
909 self.prev_span = self.token.span.with_hi(span.lo());
910 // It would be incorrect to record the kind of the current token, but
911 // fortunately for tokens currently using `bump_with`, the
912 // `prev_token_kind` will be of no use anyway.
913 self.prev_token_kind = PrevTokenKind::Other;
914 self.token = Token::new(next, span);
915 self.expected_tokens.clear();
918 /// Look-ahead `dist` tokens of `self.token` and get access to that token there.
919 /// When `dist == 0` then the current token is looked at.
920 pub fn look_ahead<R>(&self, dist: usize, looker: impl FnOnce(&Token) -> R) -> R {
922 return looker(&self.token);
925 let frame = &self.token_cursor.frame;
926 looker(&match frame.tree_cursor.look_ahead(dist - 1) {
927 Some(tree) => match tree {
928 TokenTree::Token(token) => token,
929 TokenTree::Delimited(dspan, delim, _) =>
930 Token::new(token::OpenDelim(delim), dspan.open),
932 None => Token::new(token::CloseDelim(frame.delim), frame.span.close)
936 /// Returns whether any of the given keywords are `dist` tokens ahead of the current one.
937 fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool {
938 self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw)))
941 /// Parses asyncness: `async` or nothing.
942 fn parse_asyncness(&mut self) -> IsAsync {
943 if self.eat_keyword(kw::Async) {
945 closure_id: DUMMY_NODE_ID,
946 return_impl_trait_id: DUMMY_NODE_ID,
953 /// Parses unsafety: `unsafe` or nothing.
954 fn parse_unsafety(&mut self) -> Unsafety {
955 if self.eat_keyword(kw::Unsafe) {
962 /// Parses mutability (`mut` or nothing).
963 fn parse_mutability(&mut self) -> Mutability {
964 if self.eat_keyword(kw::Mut) {
967 Mutability::Immutable
971 /// Possibly parses mutability (`const` or `mut`).
972 fn parse_const_or_mut(&mut self) -> Option<Mutability> {
973 if self.eat_keyword(kw::Mut) {
974 Some(Mutability::Mutable)
975 } else if self.eat_keyword(kw::Const) {
976 Some(Mutability::Immutable)
982 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
983 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) =
985 self.expect_no_suffix(self.token.span, "a tuple index", suffix);
987 Ok(Ident::new(symbol, self.prev_span))
989 self.parse_ident_common(false)
993 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (MacDelimiter, TokenStream)> {
994 let delim = match self.token.kind {
995 token::OpenDelim(delim) => delim,
997 let msg = "expected open delimiter";
998 let mut err = self.fatal(msg);
999 err.span_label(self.token.span, msg);
1003 let tts = match self.parse_token_tree() {
1004 TokenTree::Delimited(_, _, tts) => tts,
1005 _ => unreachable!(),
1007 let delim = match delim {
1008 token::Paren => MacDelimiter::Parenthesis,
1009 token::Bracket => MacDelimiter::Bracket,
1010 token::Brace => MacDelimiter::Brace,
1011 token::NoDelim => self.bug("unexpected no delimiter"),
1013 Ok((delim, tts.into()))
1016 fn parse_or_use_outer_attributes(
1018 already_parsed_attrs: Option<ThinVec<Attribute>>,
1019 ) -> PResult<'a, ThinVec<Attribute>> {
1020 if let Some(attrs) = already_parsed_attrs {
1023 self.parse_outer_attributes().map(|a| a.into())
1027 pub fn process_potential_macro_variable(&mut self) {
1028 self.token = match self.token.kind {
1029 token::Dollar if self.token.span.from_expansion() &&
1030 self.look_ahead(1, |t| t.is_ident()) => {
1032 let name = match self.token.kind {
1033 token::Ident(name, _) => name,
1036 let span = self.prev_span.to(self.token.span);
1038 .struct_span_fatal(span, &format!("unknown macro variable `{}`", name))
1039 .span_label(span, "unknown macro variable")
1044 token::Interpolated(ref nt) => {
1045 self.meta_var_span = Some(self.token.span);
1046 // Interpolated identifier and lifetime tokens are replaced with usual identifier
1047 // and lifetime tokens, so the former are never encountered during normal parsing.
1049 token::NtIdent(ident, is_raw) =>
1050 Token::new(token::Ident(ident.name, is_raw), ident.span),
1051 token::NtLifetime(ident) =>
1052 Token::new(token::Lifetime(ident.name), ident.span),
1060 /// Parses a single token tree from the input.
1061 pub fn parse_token_tree(&mut self) -> TokenTree {
1062 match self.token.kind {
1063 token::OpenDelim(..) => {
1064 let frame = mem::replace(&mut self.token_cursor.frame,
1065 self.token_cursor.stack.pop().unwrap());
1066 self.token.span = frame.span.entire();
1068 TokenTree::Delimited(
1071 frame.tree_cursor.stream.into(),
1074 token::CloseDelim(_) | token::Eof => unreachable!(),
1076 let token = self.token.take();
1078 TokenTree::Token(token)
1083 /// Parses a stream of tokens into a list of `TokenTree`s, up to EOF.
1084 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
1085 let mut tts = Vec::new();
1086 while self.token != token::Eof {
1087 tts.push(self.parse_token_tree());
1092 pub fn parse_tokens(&mut self) -> TokenStream {
1093 let mut result = Vec::new();
1095 match self.token.kind {
1096 token::Eof | token::CloseDelim(..) => break,
1097 _ => result.push(self.parse_token_tree().into()),
1100 TokenStream::new(result)
1103 /// Evaluates the closure with restrictions in place.
1105 /// Afters the closure is evaluated, restrictions are reset.
1106 fn with_res<T>(&mut self, res: Restrictions, f: impl FnOnce(&mut Self) -> T) -> T {
1107 let old = self.restrictions;
1108 self.restrictions = res;
1110 self.restrictions = old;
1114 fn is_crate_vis(&self) -> bool {
1115 self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
1118 /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
1119 /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
1120 /// If the following element can't be a tuple (i.e., it's a function definition), then
1121 /// it's not a tuple struct field), and the contents within the parentheses isn't valid,
1122 /// so emit a proper diagnostic.
1123 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
1124 maybe_whole!(self, NtVis, |x| x);
1126 self.expected_tokens.push(TokenType::Keyword(kw::Crate));
1127 if self.is_crate_vis() {
1128 self.bump(); // `crate`
1129 self.sess.gated_spans.gate(sym::crate_visibility_modifier, self.prev_span);
1130 return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
1133 if !self.eat_keyword(kw::Pub) {
1134 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
1135 // keyword to grab a span from for inherited visibility; an empty span at the
1136 // beginning of the current token would seem to be the "Schelling span".
1137 return Ok(respan(self.token.span.shrink_to_lo(), VisibilityKind::Inherited))
1139 let lo = self.prev_span;
1141 if self.check(&token::OpenDelim(token::Paren)) {
1142 // We don't `self.bump()` the `(` yet because this might be a struct definition where
1143 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
1144 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
1145 // by the following tokens.
1146 if self.is_keyword_ahead(1, &[kw::Crate])
1147 && self.look_ahead(2, |t| t != &token::ModSep) // account for `pub(crate::foo)`
1149 // Parse `pub(crate)`.
1151 self.bump(); // `crate`
1152 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1153 let vis = VisibilityKind::Crate(CrateSugar::PubCrate);
1154 return Ok(respan(lo.to(self.prev_span), vis));
1155 } else if self.is_keyword_ahead(1, &[kw::In]) {
1156 // Parse `pub(in path)`.
1158 self.bump(); // `in`
1159 let path = self.parse_path(PathStyle::Mod)?; // `path`
1160 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1161 let vis = VisibilityKind::Restricted {
1163 id: ast::DUMMY_NODE_ID,
1165 return Ok(respan(lo.to(self.prev_span), vis));
1166 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren))
1167 && self.is_keyword_ahead(1, &[kw::Super, kw::SelfLower])
1169 // Parse `pub(self)` or `pub(super)`.
1171 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
1172 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1173 let vis = VisibilityKind::Restricted {
1175 id: ast::DUMMY_NODE_ID,
1177 return Ok(respan(lo.to(self.prev_span), vis));
1178 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct.
1179 self.recover_incorrect_vis_restriction()?;
1180 // Emit diagnostic, but continue with public visibility.
1184 Ok(respan(lo, VisibilityKind::Public))
1187 /// Recovery for e.g. `pub(something) fn ...` or `struct X { pub(something) y: Z }`
1188 fn recover_incorrect_vis_restriction(&mut self) -> PResult<'a, ()> {
1190 let path = self.parse_path(PathStyle::Mod)?;
1191 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1193 let msg = "incorrect visibility restriction";
1194 let suggestion = r##"some possible visibility restrictions are:
1195 `pub(crate)`: visible only on the current crate
1196 `pub(super)`: visible only in the current module's parent
1197 `pub(in path::to::module)`: visible only on the specified path"##;
1199 let path_str = pprust::path_to_string(&path);
1201 struct_span_err!(self.sess.span_diagnostic, path.span, E0704, "{}", msg)
1205 &format!("make this visible only to module `{}` with `in`", path_str),
1206 format!("in {}", path_str),
1207 Applicability::MachineApplicable,
1214 /// Parses `extern string_literal?`.
1215 fn parse_extern(&mut self) -> PResult<'a, Extern> {
1216 Ok(if self.eat_keyword(kw::Extern) {
1217 Extern::from_abi(self.parse_abi())
1223 /// Parses a string literal as an ABI spec.
1224 fn parse_abi(&mut self) -> Option<StrLit> {
1225 match self.parse_str_lit() {
1226 Ok(str_lit) => Some(str_lit),
1227 Err(Some(lit)) => match lit.kind {
1228 ast::LitKind::Err(_) => None,
1230 self.struct_span_err(lit.span, "non-string ABI literal")
1233 "specify the ABI with a string literal",
1234 "\"C\"".to_string(),
1235 Applicability::MaybeIncorrect,
1245 /// We are parsing `async fn`. If we are on Rust 2015, emit an error.
1246 fn ban_async_in_2015(&self, async_span: Span) {
1247 if async_span.rust_2015() {
1252 "`async fn` is not permitted in the 2015 edition",
1258 fn collect_tokens<R>(
1260 f: impl FnOnce(&mut Self) -> PResult<'a, R>,
1261 ) -> PResult<'a, (R, TokenStream)> {
1262 // Record all tokens we parse when parsing this item.
1263 let mut tokens = Vec::new();
1264 let prev_collecting = match self.token_cursor.frame.last_token {
1265 LastToken::Collecting(ref mut list) => {
1266 Some(mem::take(list))
1268 LastToken::Was(ref mut last) => {
1269 tokens.extend(last.take());
1273 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
1274 let prev = self.token_cursor.stack.len();
1276 let last_token = if self.token_cursor.stack.len() == prev {
1277 &mut self.token_cursor.frame.last_token
1278 } else if self.token_cursor.stack.get(prev).is_none() {
1279 // This can happen due to a bad interaction of two unrelated recovery mechanisms with
1280 // mismatched delimiters *and* recovery lookahead on the likely typo `pub ident(`
1282 return Ok((ret?, TokenStream::default()));
1284 &mut self.token_cursor.stack[prev].last_token
1287 // Pull out the tokens that we've collected from the call to `f` above.
1288 let mut collected_tokens = match *last_token {
1289 LastToken::Collecting(ref mut v) => mem::take(v),
1290 LastToken::Was(ref was) => {
1291 let msg = format!("our vector went away? - found Was({:?})", was);
1292 debug!("collect_tokens: {}", msg);
1293 self.sess.span_diagnostic.delay_span_bug(self.token.span, &msg);
1294 // This can happen due to a bad interaction of two unrelated recovery mechanisms
1295 // with mismatched delimiters *and* recovery lookahead on the likely typo
1296 // `pub ident(` (#62895, different but similar to the case above).
1297 return Ok((ret?, TokenStream::default()));
1301 // If we're not at EOF our current token wasn't actually consumed by
1302 // `f`, but it'll still be in our list that we pulled out. In that case
1304 let extra_token = if self.token != token::Eof {
1305 collected_tokens.pop()
1310 // If we were previously collecting tokens, then this was a recursive
1311 // call. In that case we need to record all the tokens we collected in
1312 // our parent list as well. To do that we push a clone of our stream
1313 // onto the previous list.
1314 match prev_collecting {
1316 list.extend(collected_tokens.iter().cloned());
1317 list.extend(extra_token);
1318 *last_token = LastToken::Collecting(list);
1321 *last_token = LastToken::Was(extra_token);
1325 Ok((ret?, TokenStream::new(collected_tokens)))
1329 fn is_import_coupler(&mut self) -> bool {
1330 self.check(&token::ModSep) &&
1331 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
1332 *t == token::BinOp(token::Star))
1336 crate fn make_unclosed_delims_error(
1337 unmatched: UnmatchedBrace,
1339 ) -> Option<DiagnosticBuilder<'_>> {
1340 // `None` here means an `Eof` was found. We already emit those errors elsewhere, we add them to
1341 // `unmatched_braces` only for error recovery in the `Parser`.
1342 let found_delim = unmatched.found_delim?;
1343 let mut err = sess.span_diagnostic.struct_span_err(unmatched.found_span, &format!(
1344 "incorrect close delimiter: `{}`",
1345 pprust::token_kind_to_string(&token::CloseDelim(found_delim)),
1347 err.span_label(unmatched.found_span, "incorrect close delimiter");
1348 if let Some(sp) = unmatched.candidate_span {
1349 err.span_label(sp, "close delimiter possibly meant for this");
1351 if let Some(sp) = unmatched.unclosed_span {
1352 err.span_label(sp, "un-closed delimiter");
1357 pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, sess: &ParseSess) {
1358 *sess.reached_eof.borrow_mut() |= unclosed_delims.iter()
1359 .any(|unmatched_delim| unmatched_delim.found_delim.is_none());
1360 for unmatched in unclosed_delims.drain(..) {
1361 make_unclosed_delims_error(unmatched, sess).map(|mut e| e.emit());