4 pub use item::AliasKind;
6 pub use module::{ModulePath, ModulePathSuccess};
9 pub use path::PathStyle;
12 use super::diagnostics::Error;
15 self, DUMMY_NODE_ID, AttrStyle, Attribute, CrateSugar, Ident,
16 IsAsync, MacDelimiter, Mutability, StrStyle, Visibility, VisibilityKind, Unsafety,
18 use crate::parse::{ParseSess, PResult, Directory, DirectoryOwnership, SeqSep, literal, token};
19 use crate::parse::lexer::UnmatchedBrace;
20 use crate::parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
21 use crate::parse::token::{Token, TokenKind, DelimToken};
22 use crate::print::pprust;
24 use crate::source_map::respan;
25 use crate::symbol::{kw, sym, Symbol};
26 use crate::tokenstream::{self, DelimSpan, TokenTree, TokenStream, TreeAndJoint};
29 use errors::{Applicability, DiagnosticId, FatalError};
30 use rustc_target::spec::abi::{self, Abi};
31 use syntax_pos::{Span, BytePos, DUMMY_SP, FileName};
35 use std::{cmp, mem, slice};
36 use std::path::PathBuf;
39 struct Restrictions: u8 {
40 const STMT_EXPR = 1 << 0;
41 const NO_STRUCT_LITERAL = 1 << 1;
45 #[derive(Clone, Copy, PartialEq, Debug)]
46 crate enum SemiColonMode {
52 #[derive(Clone, Copy, PartialEq, Debug)]
53 crate enum BlockMode {
58 /// Like `maybe_whole_expr`, but for things other than expressions.
60 macro_rules! maybe_whole {
61 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
62 if let token::Interpolated(nt) = &$p.token.kind {
63 if let token::$constructor(x) = &**nt {
72 /// If the next tokens are ill-formed `$ty::` recover them as `<$ty>::`.
74 macro_rules! maybe_recover_from_interpolated_ty_qpath {
75 ($self: expr, $allow_qpath_recovery: expr) => {
76 if $allow_qpath_recovery && $self.look_ahead(1, |t| t == &token::ModSep) {
77 if let token::Interpolated(nt) = &$self.token.kind {
78 if let token::NtTy(ty) = &**nt {
81 return $self.maybe_recover_from_bad_qpath_stage_2($self.prev_span, ty);
88 fn maybe_append(mut lhs: Vec<Attribute>, mut rhs: Option<Vec<Attribute>>) -> Vec<Attribute> {
89 if let Some(ref mut rhs) = rhs {
95 #[derive(Debug, Clone, Copy, PartialEq)]
107 // NOTE: `Ident`s are handled by `common.rs`.
110 pub struct Parser<'a> {
111 pub sess: &'a ParseSess,
112 /// The current normalized token.
113 /// "Normalized" means that some interpolated tokens
114 /// (`$i: ident` and `$l: lifetime` meta-variables) are replaced
115 /// with non-interpolated identifier and lifetime tokens they refer to.
116 /// Perhaps the normalized / non-normalized setup can be simplified somehow.
118 /// The span of the current non-normalized token.
119 meta_var_span: Option<Span>,
120 /// The span of the previous non-normalized token.
122 /// The kind of the previous normalized token (in simplified form).
123 prev_token_kind: PrevTokenKind,
124 restrictions: Restrictions,
125 /// Used to determine the path to externally loaded source files.
126 crate directory: Directory<'a>,
127 /// `true` to parse sub-modules in other files.
128 pub recurse_into_file_modules: bool,
129 /// Name of the root module this parser originated from. If `None`, then the
130 /// name is not known. This does not change while the parser is descending
131 /// into modules, and sub-parsers have new values for this name.
132 pub root_module_name: Option<String>,
133 crate expected_tokens: Vec<TokenType>,
134 token_cursor: TokenCursor,
135 desugar_doc_comments: bool,
136 /// `true` we should configure out of line modules as we parse.
138 /// This field is used to keep track of how many left angle brackets we have seen. This is
139 /// required in order to detect extra leading left angle brackets (`<` characters) and error
142 /// See the comments in the `parse_path_segment` function for more details.
143 crate unmatched_angle_bracket_count: u32,
144 crate max_angle_bracket_count: u32,
145 /// A list of all unclosed delimiters found by the lexer. If an entry is used for error recovery
146 /// it gets removed from here. Every entry left at the end gets emitted as an independent
148 crate unclosed_delims: Vec<UnmatchedBrace>,
149 crate last_unexpected_token_span: Option<Span>,
150 crate last_type_ascription: Option<(Span, bool /* likely path typo */)>,
151 /// If present, this `Parser` is not parsing Rust code but rather a macro call.
152 crate subparser_name: Option<&'static str>,
155 impl<'a> Drop for Parser<'a> {
157 let diag = self.diagnostic();
158 emit_unclosed_delims(&mut self.unclosed_delims, diag);
164 frame: TokenCursorFrame,
165 stack: Vec<TokenCursorFrame>,
169 struct TokenCursorFrame {
170 delim: token::DelimToken,
173 tree_cursor: tokenstream::Cursor,
175 last_token: LastToken,
178 /// This is used in `TokenCursorFrame` above to track tokens that are consumed
179 /// by the parser, and then that's transitively used to record the tokens that
180 /// each parse AST item is created with.
182 /// Right now this has two states, either collecting tokens or not collecting
183 /// tokens. If we're collecting tokens we just save everything off into a local
184 /// `Vec`. This should eventually though likely save tokens from the original
185 /// token stream and just use slicing of token streams to avoid creation of a
186 /// whole new vector.
188 /// The second state is where we're passively not recording tokens, but the last
189 /// token is still tracked for when we want to start recording tokens. This
190 /// "last token" means that when we start recording tokens we'll want to ensure
191 /// that this, the first token, is included in the output.
193 /// You can find some more example usage of this in the `collect_tokens` method
196 crate enum LastToken {
197 Collecting(Vec<TreeAndJoint>),
198 Was(Option<TreeAndJoint>),
201 impl TokenCursorFrame {
202 fn new(span: DelimSpan, delim: DelimToken, tts: &TokenStream) -> Self {
206 open_delim: delim == token::NoDelim,
207 tree_cursor: tts.clone().into_trees(),
208 close_delim: delim == token::NoDelim,
209 last_token: LastToken::Was(None),
215 fn next(&mut self) -> Token {
217 let tree = if !self.frame.open_delim {
218 self.frame.open_delim = true;
219 TokenTree::open_tt(self.frame.span.open, self.frame.delim)
220 } else if let Some(tree) = self.frame.tree_cursor.next() {
222 } else if !self.frame.close_delim {
223 self.frame.close_delim = true;
224 TokenTree::close_tt(self.frame.span.close, self.frame.delim)
225 } else if let Some(frame) = self.stack.pop() {
229 return Token::new(token::Eof, DUMMY_SP);
232 match self.frame.last_token {
233 LastToken::Collecting(ref mut v) => v.push(tree.clone().into()),
234 LastToken::Was(ref mut t) => *t = Some(tree.clone().into()),
238 TokenTree::Token(token) => return token,
239 TokenTree::Delimited(sp, delim, tts) => {
240 let frame = TokenCursorFrame::new(sp, delim, &tts);
241 self.stack.push(mem::replace(&mut self.frame, frame));
247 fn next_desugared(&mut self) -> Token {
248 let (name, sp) = match self.next() {
249 Token { kind: token::DocComment(name), span } => (name, span),
253 let stripped = strip_doc_comment_decoration(&name.as_str());
255 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
256 // required to wrap the text.
257 let mut num_of_hashes = 0;
259 for ch in stripped.chars() {
262 '#' if count > 0 => count + 1,
265 num_of_hashes = cmp::max(num_of_hashes, count);
268 let delim_span = DelimSpan::from_single(sp);
269 let body = TokenTree::Delimited(
273 TokenTree::token(token::Ident(sym::doc, false), sp),
274 TokenTree::token(token::Eq, sp),
275 TokenTree::token(TokenKind::lit(
276 token::StrRaw(num_of_hashes), Symbol::intern(&stripped), None
279 .iter().cloned().collect::<TokenStream>().into(),
282 self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new(
285 &if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
286 [TokenTree::token(token::Pound, sp), TokenTree::token(token::Not, sp), body]
287 .iter().cloned().collect::<TokenStream>().into()
289 [TokenTree::token(token::Pound, sp), body]
290 .iter().cloned().collect::<TokenStream>().into()
298 #[derive(Clone, PartialEq)]
299 crate enum TokenType {
311 crate fn to_string(&self) -> String {
313 TokenType::Token(ref t) => format!("`{}`", pprust::token_kind_to_string(t)),
314 TokenType::Keyword(kw) => format!("`{}`", kw),
315 TokenType::Operator => "an operator".to_string(),
316 TokenType::Lifetime => "lifetime".to_string(),
317 TokenType::Ident => "identifier".to_string(),
318 TokenType::Path => "path".to_string(),
319 TokenType::Type => "type".to_string(),
320 TokenType::Const => "const".to_string(),
325 #[derive(Copy, Clone, Debug)]
326 crate enum TokenExpectType {
331 impl<'a> Parser<'a> {
335 directory: Option<Directory<'a>>,
336 recurse_into_file_modules: bool,
337 desugar_doc_comments: bool,
338 subparser_name: Option<&'static str>,
340 let mut parser = Parser {
342 token: Token::dummy(),
345 prev_token_kind: PrevTokenKind::Other,
346 restrictions: Restrictions::empty(),
347 recurse_into_file_modules,
348 directory: Directory {
349 path: Cow::from(PathBuf::new()),
350 ownership: DirectoryOwnership::Owned { relative: None }
352 root_module_name: None,
353 expected_tokens: Vec::new(),
354 token_cursor: TokenCursor {
355 frame: TokenCursorFrame::new(
362 desugar_doc_comments,
364 unmatched_angle_bracket_count: 0,
365 max_angle_bracket_count: 0,
366 unclosed_delims: Vec::new(),
367 last_unexpected_token_span: None,
368 last_type_ascription: None,
372 parser.token = parser.next_tok();
374 if let Some(directory) = directory {
375 parser.directory = directory;
376 } else if !parser.token.span.is_dummy() {
377 if let Some(FileName::Real(path)) =
378 &sess.source_map().lookup_char_pos(parser.token.span.lo()).file.unmapped_path {
379 if let Some(directory_path) = path.parent() {
380 parser.directory.path = Cow::from(directory_path.to_path_buf());
385 parser.process_potential_macro_variable();
389 fn next_tok(&mut self) -> Token {
390 let mut next = if self.desugar_doc_comments {
391 self.token_cursor.next_desugared()
393 self.token_cursor.next()
395 if next.span.is_dummy() {
396 // Tweak the location for better diagnostics, but keep syntactic context intact.
397 next.span = self.prev_span.with_ctxt(next.span.ctxt());
402 /// Converts the current token to a string using `self`'s reader.
403 pub fn this_token_to_string(&self) -> String {
404 pprust::token_to_string(&self.token)
407 crate fn token_descr(&self) -> Option<&'static str> {
408 Some(match &self.token.kind {
409 _ if self.token.is_special_ident() => "reserved identifier",
410 _ if self.token.is_used_keyword() => "keyword",
411 _ if self.token.is_unused_keyword() => "reserved keyword",
412 token::DocComment(..) => "doc comment",
417 crate fn this_token_descr(&self) -> String {
418 if let Some(prefix) = self.token_descr() {
419 format!("{} `{}`", prefix, self.this_token_to_string())
421 format!("`{}`", self.this_token_to_string())
425 crate fn unexpected<T>(&mut self) -> PResult<'a, T> {
426 match self.expect_one_of(&[], &[]) {
428 Ok(_) => unreachable!(),
432 /// Expects and consumes the token `t`. Signals an error if the next token is not `t`.
433 pub fn expect(&mut self, t: &TokenKind) -> PResult<'a, bool /* recovered */> {
434 if self.expected_tokens.is_empty() {
435 if self.token == *t {
439 self.unexpected_try_recover(t)
442 self.expect_one_of(slice::from_ref(t), &[])
446 /// Expect next token to be edible or inedible token. If edible,
447 /// then consume it; if inedible, then return without consuming
448 /// anything. Signal a fatal error if next token is unexpected.
449 pub fn expect_one_of(
451 edible: &[TokenKind],
452 inedible: &[TokenKind],
453 ) -> PResult<'a, bool /* recovered */> {
454 if edible.contains(&self.token.kind) {
457 } else if inedible.contains(&self.token.kind) {
458 // leave it in the input
460 } else if self.last_unexpected_token_span == Some(self.token.span) {
463 self.expected_one_of_not_found(edible, inedible)
467 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
468 self.parse_ident_common(true)
471 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, ast::Ident> {
472 match self.token.kind {
473 token::Ident(name, _) => {
474 if self.token.is_reserved_ident() {
475 let mut err = self.expected_ident_found();
482 let span = self.token.span;
484 Ok(Ident::new(name, span))
487 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
488 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
490 self.expected_ident_found()
496 /// Checks if the next token is `tok`, and returns `true` if so.
498 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
500 crate fn check(&mut self, tok: &TokenKind) -> bool {
501 let is_present = self.token == *tok;
502 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
506 /// Consumes a token 'tok' if it exists. Returns whether the given token was present.
507 pub fn eat(&mut self, tok: &TokenKind) -> bool {
508 let is_present = self.check(tok);
509 if is_present { self.bump() }
513 /// If the next token is the given keyword, returns `true` without eating it.
514 /// An expectation is also added for diagnostics purposes.
515 fn check_keyword(&mut self, kw: Symbol) -> bool {
516 self.expected_tokens.push(TokenType::Keyword(kw));
517 self.token.is_keyword(kw)
520 /// If the next token is the given keyword, eats it and returns `true`.
521 /// Otherwise, returns `false`. An expectation is also added for diagnostics purposes.
522 pub fn eat_keyword(&mut self, kw: Symbol) -> bool {
523 if self.check_keyword(kw) {
531 fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool {
532 if self.token.is_keyword(kw) {
540 /// If the given word is not a keyword, signals an error.
541 /// If the next token is not the given word, signals an error.
542 /// Otherwise, eats it.
543 fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> {
544 if !self.eat_keyword(kw) {
551 fn check_or_expected(&mut self, ok: bool, typ: TokenType) -> bool {
555 self.expected_tokens.push(typ);
560 crate fn check_ident(&mut self) -> bool {
561 self.check_or_expected(self.token.is_ident(), TokenType::Ident)
564 fn check_path(&mut self) -> bool {
565 self.check_or_expected(self.token.is_path_start(), TokenType::Path)
568 fn check_type(&mut self) -> bool {
569 self.check_or_expected(self.token.can_begin_type(), TokenType::Type)
572 fn check_const_arg(&mut self) -> bool {
573 self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const)
576 /// Checks to see if the next token is either `+` or `+=`.
577 /// Otherwise returns `false`.
578 fn check_plus(&mut self) -> bool {
579 self.check_or_expected(
580 self.token.is_like_plus(),
581 TokenType::Token(token::BinOp(token::Plus)),
585 /// Expects and consumes a `+`. if `+=` is seen, replaces it with a `=`
586 /// and continues. If a `+` is not seen, returns `false`.
588 /// This is used when token-splitting `+=` into `+`.
589 /// See issue #47856 for an example of when this may occur.
590 fn eat_plus(&mut self) -> bool {
591 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
592 match self.token.kind {
593 token::BinOp(token::Plus) => {
597 token::BinOpEq(token::Plus) => {
598 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
599 self.bump_with(token::Eq, span);
606 /// Expects and consumes an `&`. If `&&` is seen, replaces it with a single
607 /// `&` and continues. If an `&` is not seen, signals an error.
608 fn expect_and(&mut self) -> PResult<'a, ()> {
609 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
610 match self.token.kind {
611 token::BinOp(token::And) => {
616 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
617 Ok(self.bump_with(token::BinOp(token::And), span))
619 _ => self.unexpected()
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_or(&mut self) -> PResult<'a, ()> {
626 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or)));
627 match self.token.kind {
628 token::BinOp(token::Or) => {
633 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
634 Ok(self.bump_with(token::BinOp(token::Or), span))
636 _ => self.unexpected()
640 fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
641 literal::expect_no_suffix(&self.sess.span_diagnostic, sp, kind, suffix)
644 /// Attempts to consume a `<`. If `<<` is seen, replaces it with a single
645 /// `<` and continue. If `<-` is seen, replaces it with a single `<`
646 /// and continue. If a `<` is not seen, returns false.
648 /// This is meant to be used when parsing generics on a path to get the
650 fn eat_lt(&mut self) -> bool {
651 self.expected_tokens.push(TokenType::Token(token::Lt));
652 let ate = match self.token.kind {
657 token::BinOp(token::Shl) => {
658 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
659 self.bump_with(token::Lt, span);
663 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
664 self.bump_with(token::BinOp(token::Minus), span);
671 // See doc comment for `unmatched_angle_bracket_count`.
672 self.unmatched_angle_bracket_count += 1;
673 self.max_angle_bracket_count += 1;
674 debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count);
680 fn expect_lt(&mut self) -> PResult<'a, ()> {
688 /// Expects and consumes a single `>` token. if a `>>` is seen, replaces it
689 /// with a single `>` and continues. If a `>` is not seen, signals an error.
690 fn expect_gt(&mut self) -> PResult<'a, ()> {
691 self.expected_tokens.push(TokenType::Token(token::Gt));
692 let ate = match self.token.kind {
697 token::BinOp(token::Shr) => {
698 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
699 Some(self.bump_with(token::Gt, span))
701 token::BinOpEq(token::Shr) => {
702 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
703 Some(self.bump_with(token::Ge, span))
706 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
707 Some(self.bump_with(token::Eq, span))
714 // See doc comment for `unmatched_angle_bracket_count`.
715 if self.unmatched_angle_bracket_count > 0 {
716 self.unmatched_angle_bracket_count -= 1;
717 debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count);
722 None => self.unexpected(),
726 /// Parses a sequence, including the closing delimiter. The function
727 /// `f` must consume tokens until reaching the next separator or
729 pub fn parse_seq_to_end<T>(
733 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
734 ) -> PResult<'a, Vec<T>> {
735 let (val, _, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
742 /// Parses a sequence, not including the closing delimiter. The function
743 /// `f` must consume tokens until reaching the next separator or
745 pub fn parse_seq_to_before_end<T>(
749 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
750 ) -> PResult<'a, (Vec<T>, bool, bool)> {
751 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
754 fn expect_any_with_type(&mut self, kets: &[&TokenKind], expect: TokenExpectType) -> bool {
755 kets.iter().any(|k| {
757 TokenExpectType::Expect => self.check(k),
758 TokenExpectType::NoExpect => self.token == **k,
763 crate fn parse_seq_to_before_tokens<T>(
767 expect: TokenExpectType,
768 mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
769 ) -> PResult<'a, (Vec<T>, bool /* trailing */, bool /* recovered */)> {
770 let mut first = true;
771 let mut recovered = false;
772 let mut trailing = false;
774 while !self.expect_any_with_type(kets, expect) {
775 if let token::CloseDelim(..) | token::Eof = self.token.kind {
778 if let Some(ref t) = sep.sep {
782 match self.expect(t) {
789 // Attempt to keep parsing if it was a similar separator.
790 if let Some(ref tokens) = t.similar_tokens() {
791 if tokens.contains(&self.token.kind) {
796 // Attempt to keep parsing if it was an omitted separator.
811 if sep.trailing_sep_allowed && self.expect_any_with_type(kets, expect) {
820 Ok((v, trailing, recovered))
823 /// Parses a sequence, including the closing delimiter. The function
824 /// `f` must consume tokens until reaching the next separator or
826 fn parse_unspanned_seq<T>(
831 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
832 ) -> PResult<'a, (Vec<T>, bool)> {
834 let (result, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
838 Ok((result, trailing))
841 fn parse_delim_comma_seq<T>(
844 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
845 ) -> PResult<'a, (Vec<T>, bool)> {
846 self.parse_unspanned_seq(
847 &token::OpenDelim(delim),
848 &token::CloseDelim(delim),
849 SeqSep::trailing_allowed(token::Comma),
854 fn parse_paren_comma_seq<T>(
856 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
857 ) -> PResult<'a, (Vec<T>, bool)> {
858 self.parse_delim_comma_seq(token::Paren, f)
861 /// Advance the parser by one token.
862 pub fn bump(&mut self) {
863 if self.prev_token_kind == PrevTokenKind::Eof {
864 // Bumping after EOF is a bad sign, usually an infinite loop.
865 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
868 self.prev_span = self.meta_var_span.take().unwrap_or(self.token.span);
870 // Record last token kind for possible error recovery.
871 self.prev_token_kind = match self.token.kind {
872 token::DocComment(..) => PrevTokenKind::DocComment,
873 token::Comma => PrevTokenKind::Comma,
874 token::BinOp(token::Plus) => PrevTokenKind::Plus,
875 token::BinOp(token::Or) => PrevTokenKind::BitOr,
876 token::Interpolated(..) => PrevTokenKind::Interpolated,
877 token::Eof => PrevTokenKind::Eof,
878 token::Ident(..) => PrevTokenKind::Ident,
879 _ => PrevTokenKind::Other,
882 self.token = self.next_tok();
883 self.expected_tokens.clear();
884 // Check after each token.
885 self.process_potential_macro_variable();
888 /// Advances the parser using provided token as a next one. Use this when
889 /// consuming a part of a token. For example a single `<` from `<<`.
890 fn bump_with(&mut self, next: TokenKind, span: Span) {
891 self.prev_span = self.token.span.with_hi(span.lo());
892 // It would be incorrect to record the kind of the current token, but
893 // fortunately for tokens currently using `bump_with`, the
894 // `prev_token_kind` will be of no use anyway.
895 self.prev_token_kind = PrevTokenKind::Other;
896 self.token = Token::new(next, span);
897 self.expected_tokens.clear();
900 /// Look-ahead `dist` tokens of `self.token` and get access to that token there.
901 /// When `dist == 0` then the current token is looked at.
902 pub fn look_ahead<R>(&self, dist: usize, looker: impl FnOnce(&Token) -> R) -> R {
904 return looker(&self.token);
907 let frame = &self.token_cursor.frame;
908 looker(&match frame.tree_cursor.look_ahead(dist - 1) {
909 Some(tree) => match tree {
910 TokenTree::Token(token) => token,
911 TokenTree::Delimited(dspan, delim, _) =>
912 Token::new(token::OpenDelim(delim), dspan.open),
914 None => Token::new(token::CloseDelim(frame.delim), frame.span.close)
918 /// Returns whether any of the given keywords are `dist` tokens ahead of the current one.
919 fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool {
920 self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw)))
923 /// Parses asyncness: `async` or nothing.
924 fn parse_asyncness(&mut self) -> IsAsync {
925 if self.eat_keyword(kw::Async) {
927 closure_id: DUMMY_NODE_ID,
928 return_impl_trait_id: DUMMY_NODE_ID,
935 /// Parses unsafety: `unsafe` or nothing.
936 fn parse_unsafety(&mut self) -> Unsafety {
937 if self.eat_keyword(kw::Unsafe) {
944 /// Parses mutability (`mut` or nothing).
945 fn parse_mutability(&mut self) -> Mutability {
946 if self.eat_keyword(kw::Mut) {
949 Mutability::Immutable
953 /// Possibly parses mutability (`const` or `mut`).
954 fn parse_const_or_mut(&mut self) -> Option<Mutability> {
955 if self.eat_keyword(kw::Mut) {
956 Some(Mutability::Mutable)
957 } else if self.eat_keyword(kw::Const) {
958 Some(Mutability::Immutable)
964 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
965 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) =
967 self.expect_no_suffix(self.token.span, "a tuple index", suffix);
969 Ok(Ident::new(symbol, self.prev_span))
971 self.parse_ident_common(false)
975 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (MacDelimiter, TokenStream)> {
976 let delim = match self.token.kind {
977 token::OpenDelim(delim) => delim,
979 let msg = "expected open delimiter";
980 let mut err = self.fatal(msg);
981 err.span_label(self.token.span, msg);
985 let tts = match self.parse_token_tree() {
986 TokenTree::Delimited(_, _, tts) => tts,
989 let delim = match delim {
990 token::Paren => MacDelimiter::Parenthesis,
991 token::Bracket => MacDelimiter::Bracket,
992 token::Brace => MacDelimiter::Brace,
993 token::NoDelim => self.bug("unexpected no delimiter"),
995 Ok((delim, tts.into()))
998 fn parse_or_use_outer_attributes(
1000 already_parsed_attrs: Option<ThinVec<Attribute>>,
1001 ) -> PResult<'a, ThinVec<Attribute>> {
1002 if let Some(attrs) = already_parsed_attrs {
1005 self.parse_outer_attributes().map(|a| a.into())
1009 crate fn process_potential_macro_variable(&mut self) {
1010 self.token = match self.token.kind {
1011 token::Dollar if self.token.span.from_expansion() &&
1012 self.look_ahead(1, |t| t.is_ident()) => {
1014 let name = match self.token.kind {
1015 token::Ident(name, _) => name,
1018 let span = self.prev_span.to(self.token.span);
1020 .struct_span_fatal(span, &format!("unknown macro variable `{}`", name))
1021 .span_label(span, "unknown macro variable")
1026 token::Interpolated(ref nt) => {
1027 self.meta_var_span = Some(self.token.span);
1028 // Interpolated identifier and lifetime tokens are replaced with usual identifier
1029 // and lifetime tokens, so the former are never encountered during normal parsing.
1031 token::NtIdent(ident, is_raw) =>
1032 Token::new(token::Ident(ident.name, is_raw), ident.span),
1033 token::NtLifetime(ident) =>
1034 Token::new(token::Lifetime(ident.name), ident.span),
1042 /// Parses a single token tree from the input.
1043 crate fn parse_token_tree(&mut self) -> TokenTree {
1044 match self.token.kind {
1045 token::OpenDelim(..) => {
1046 let frame = mem::replace(&mut self.token_cursor.frame,
1047 self.token_cursor.stack.pop().unwrap());
1048 self.token.span = frame.span.entire();
1050 TokenTree::Delimited(
1053 frame.tree_cursor.stream.into(),
1056 token::CloseDelim(_) | token::Eof => unreachable!(),
1058 let token = self.token.take();
1060 TokenTree::Token(token)
1065 /// Parses a stream of tokens into a list of `TokenTree`s, up to EOF.
1066 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
1067 let mut tts = Vec::new();
1068 while self.token != token::Eof {
1069 tts.push(self.parse_token_tree());
1074 pub fn parse_tokens(&mut self) -> TokenStream {
1075 let mut result = Vec::new();
1077 match self.token.kind {
1078 token::Eof | token::CloseDelim(..) => break,
1079 _ => result.push(self.parse_token_tree().into()),
1082 TokenStream::new(result)
1085 /// Evaluates the closure with restrictions in place.
1087 /// Afters the closure is evaluated, restrictions are reset.
1088 fn with_res<T>(&mut self, res: Restrictions, f: impl FnOnce(&mut Self) -> T) -> T {
1089 let old = self.restrictions;
1090 self.restrictions = res;
1092 self.restrictions = old;
1096 fn is_crate_vis(&self) -> bool {
1097 self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
1100 /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
1101 /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
1102 /// If the following element can't be a tuple (i.e., it's a function definition), then
1103 /// it's not a tuple struct field), and the contents within the parentheses isn't valid,
1104 /// so emit a proper diagnostic.
1105 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
1106 maybe_whole!(self, NtVis, |x| x);
1108 self.expected_tokens.push(TokenType::Keyword(kw::Crate));
1109 if self.is_crate_vis() {
1110 self.bump(); // `crate`
1111 return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
1114 if !self.eat_keyword(kw::Pub) {
1115 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
1116 // keyword to grab a span from for inherited visibility; an empty span at the
1117 // beginning of the current token would seem to be the "Schelling span".
1118 return Ok(respan(self.token.span.shrink_to_lo(), VisibilityKind::Inherited))
1120 let lo = self.prev_span;
1122 if self.check(&token::OpenDelim(token::Paren)) {
1123 // We don't `self.bump()` the `(` yet because this might be a struct definition where
1124 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
1125 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
1126 // by the following tokens.
1127 if self.is_keyword_ahead(1, &[kw::Crate])
1128 && self.look_ahead(2, |t| t != &token::ModSep) // account for `pub(crate::foo)`
1130 // Parse `pub(crate)`.
1132 self.bump(); // `crate`
1133 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1134 let vis = VisibilityKind::Crate(CrateSugar::PubCrate);
1135 return Ok(respan(lo.to(self.prev_span), vis));
1136 } else if self.is_keyword_ahead(1, &[kw::In]) {
1137 // Parse `pub(in path)`.
1139 self.bump(); // `in`
1140 let path = self.parse_path(PathStyle::Mod)?; // `path`
1141 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1142 let vis = VisibilityKind::Restricted {
1144 id: ast::DUMMY_NODE_ID,
1146 return Ok(respan(lo.to(self.prev_span), vis));
1147 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren))
1148 && self.is_keyword_ahead(1, &[kw::Super, kw::SelfLower])
1150 // Parse `pub(self)` or `pub(super)`.
1152 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
1153 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1154 let vis = VisibilityKind::Restricted {
1156 id: ast::DUMMY_NODE_ID,
1158 return Ok(respan(lo.to(self.prev_span), vis));
1159 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct.
1160 self.recover_incorrect_vis_restriction()?;
1161 // Emit diagnostic, but continue with public visibility.
1165 Ok(respan(lo, VisibilityKind::Public))
1168 /// Recovery for e.g. `pub(something) fn ...` or `struct X { pub(something) y: Z }`
1169 fn recover_incorrect_vis_restriction(&mut self) -> PResult<'a, ()> {
1171 let path = self.parse_path(PathStyle::Mod)?;
1172 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1174 let msg = "incorrect visibility restriction";
1175 let suggestion = r##"some possible visibility restrictions are:
1176 `pub(crate)`: visible only on the current crate
1177 `pub(super)`: visible only in the current module's parent
1178 `pub(in path::to::module)`: visible only on the specified path"##;
1180 let path_str = pprust::path_to_string(&path);
1182 struct_span_err!(self.sess.span_diagnostic, path.span, E0704, "{}", msg)
1186 &format!("make this visible only to module `{}` with `in`", path_str),
1187 format!("in {}", path_str),
1188 Applicability::MachineApplicable,
1195 /// Parses `extern` followed by an optional ABI string, or nothing.
1196 fn parse_extern_abi(&mut self) -> PResult<'a, Abi> {
1197 if self.eat_keyword(kw::Extern) {
1198 Ok(self.parse_opt_abi()?.unwrap_or(Abi::C))
1204 /// Parses a string as an ABI spec on an extern type or module. Consumes
1205 /// the `extern` keyword, if one is found.
1206 fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
1207 match self.token.kind {
1208 token::Literal(token::Lit { kind: token::Str, symbol, suffix }) |
1209 token::Literal(token::Lit { kind: token::StrRaw(..), symbol, suffix }) => {
1210 self.expect_no_suffix(self.token.span, "an ABI spec", suffix);
1212 match abi::lookup(&symbol.as_str()) {
1213 Some(abi) => Ok(Some(abi)),
1215 self.error_on_invalid_abi(symbol);
1224 /// Emit an error where `symbol` is an invalid ABI.
1225 fn error_on_invalid_abi(&self, symbol: Symbol) {
1226 let prev_span = self.prev_span;
1228 self.sess.span_diagnostic,
1231 "invalid ABI: found `{}`",
1234 .span_label(prev_span, "invalid ABI")
1235 .help(&format!("valid ABIs: {}", abi::all_names().join(", ")))
1239 /// We are parsing `async fn`. If we are on Rust 2015, emit an error.
1240 fn ban_async_in_2015(&self, async_span: Span) {
1241 if async_span.rust_2015() {
1243 .struct_span_err_with_code(
1245 "`async fn` is not permitted in the 2015 edition",
1246 DiagnosticId::Error("E0670".into())
1252 fn collect_tokens<R>(
1254 f: impl FnOnce(&mut Self) -> PResult<'a, R>,
1255 ) -> PResult<'a, (R, TokenStream)> {
1256 // Record all tokens we parse when parsing this item.
1257 let mut tokens = Vec::new();
1258 let prev_collecting = match self.token_cursor.frame.last_token {
1259 LastToken::Collecting(ref mut list) => {
1260 Some(mem::take(list))
1262 LastToken::Was(ref mut last) => {
1263 tokens.extend(last.take());
1267 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
1268 let prev = self.token_cursor.stack.len();
1270 let last_token = if self.token_cursor.stack.len() == prev {
1271 &mut self.token_cursor.frame.last_token
1272 } else if self.token_cursor.stack.get(prev).is_none() {
1273 // This can happen due to a bad interaction of two unrelated recovery mechanisms with
1274 // mismatched delimiters *and* recovery lookahead on the likely typo `pub ident(`
1276 return Ok((ret?, TokenStream::new(vec![])));
1278 &mut self.token_cursor.stack[prev].last_token
1281 // Pull out the tokens that we've collected from the call to `f` above.
1282 let mut collected_tokens = match *last_token {
1283 LastToken::Collecting(ref mut v) => mem::take(v),
1284 LastToken::Was(ref was) => {
1285 let msg = format!("our vector went away? - found Was({:?})", was);
1286 debug!("collect_tokens: {}", msg);
1287 self.sess.span_diagnostic.delay_span_bug(self.token.span, &msg);
1288 // This can happen due to a bad interaction of two unrelated recovery mechanisms
1289 // with mismatched delimiters *and* recovery lookahead on the likely typo
1290 // `pub ident(` (#62895, different but similar to the case above).
1291 return Ok((ret?, TokenStream::new(vec![])));
1295 // If we're not at EOF our current token wasn't actually consumed by
1296 // `f`, but it'll still be in our list that we pulled out. In that case
1298 let extra_token = if self.token != token::Eof {
1299 collected_tokens.pop()
1304 // If we were previously collecting tokens, then this was a recursive
1305 // call. In that case we need to record all the tokens we collected in
1306 // our parent list as well. To do that we push a clone of our stream
1307 // onto the previous list.
1308 match prev_collecting {
1310 list.extend(collected_tokens.iter().cloned());
1311 list.extend(extra_token);
1312 *last_token = LastToken::Collecting(list);
1315 *last_token = LastToken::Was(extra_token);
1319 Ok((ret?, TokenStream::new(collected_tokens)))
1323 fn is_import_coupler(&mut self) -> bool {
1324 self.check(&token::ModSep) &&
1325 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
1326 *t == token::BinOp(token::Star))
1329 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
1330 let ret = match self.token.kind {
1331 token::Literal(token::Lit { kind: token::Str, symbol, suffix }) =>
1332 (symbol, ast::StrStyle::Cooked, suffix),
1333 token::Literal(token::Lit { kind: token::StrRaw(n), symbol, suffix }) =>
1334 (symbol, ast::StrStyle::Raw(n), suffix),
1341 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
1342 match self.parse_optional_str() {
1343 Some((s, style, suf)) => {
1344 let sp = self.prev_span;
1345 self.expect_no_suffix(sp, "a string literal", suf);
1349 let msg = "expected string literal";
1350 let mut err = self.fatal(msg);
1351 err.span_label(self.token.span, msg);
1357 fn report_invalid_macro_expansion_item(&self) {
1358 self.struct_span_err(
1360 "macros that expand to items must be delimited with braces or followed by a semicolon",
1361 ).multipart_suggestion(
1362 "change the delimiters to curly braces",
1364 (self.prev_span.with_hi(self.prev_span.lo() + BytePos(1)), String::from(" {")),
1365 (self.prev_span.with_lo(self.prev_span.hi() - BytePos(1)), '}'.to_string()),
1367 Applicability::MaybeIncorrect,
1369 self.sess.source_map.next_point(self.prev_span),
1372 Applicability::MaybeIncorrect,
1377 pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, handler: &errors::Handler) {
1378 for unmatched in unclosed_delims.iter() {
1379 let mut err = handler.struct_span_err(unmatched.found_span, &format!(
1380 "incorrect close delimiter: `{}`",
1381 pprust::token_kind_to_string(&token::CloseDelim(unmatched.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");
1392 unclosed_delims.clear();