5 pub use module::{ModulePath, ModulePathSuccess};
9 pub use path::PathStyle;
13 use diagnostics::Error;
15 use crate::lexer::UnmatchedBrace;
16 use crate::{Directory, DirectoryOwnership};
19 use rustc_ast_pretty::pprust;
20 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder, FatalError, PResult};
21 use rustc_session::parse::ParseSess;
22 use rustc_span::source_map::respan;
23 use rustc_span::symbol::{kw, sym, Symbol};
24 use rustc_span::{FileName, Span, DUMMY_SP};
25 use syntax::ast::DUMMY_NODE_ID;
26 use syntax::ast::{self, AttrStyle, AttrVec, Const, CrateSugar, Extern, Ident, Unsafe};
27 use syntax::ast::{Async, MacArgs, MacDelimiter, Mutability, StrLit, Visibility, VisibilityKind};
29 use syntax::token::{self, DelimToken, Token, TokenKind};
30 use syntax::tokenstream::{self, DelimSpan, TokenStream, TokenTree, TreeAndJoint};
31 use syntax::util::comments::{doc_comment_style, strip_doc_comment_decoration};
33 use std::path::PathBuf;
34 use std::{cmp, mem, slice};
37 struct Restrictions: u8 {
38 const STMT_EXPR = 1 << 0;
39 const NO_STRUCT_LITERAL = 1 << 1;
43 #[derive(Clone, Copy, PartialEq, Debug)]
50 #[derive(Clone, Copy, PartialEq, Debug)]
56 /// Like `maybe_whole_expr`, but for things other than expressions.
58 macro_rules! maybe_whole {
59 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
60 if let token::Interpolated(nt) = &$p.token.kind {
61 if let token::$constructor(x) = &**nt {
70 /// If the next tokens are ill-formed `$ty::` recover them as `<$ty>::`.
72 macro_rules! maybe_recover_from_interpolated_ty_qpath {
73 ($self: expr, $allow_qpath_recovery: expr) => {
74 if $allow_qpath_recovery && $self.look_ahead(1, |t| t == &token::ModSep) {
75 if let token::Interpolated(nt) = &$self.token.kind {
76 if let token::NtTy(ty) = &**nt {
79 return $self.maybe_recover_from_bad_qpath_stage_2($self.prev_span, ty);
87 pub struct Parser<'a> {
88 pub sess: &'a ParseSess,
89 /// The current normalized token.
90 /// "Normalized" means that some interpolated tokens
91 /// (`$i: ident` and `$l: lifetime` meta-variables) are replaced
92 /// with non-interpolated identifier and lifetime tokens they refer to.
93 /// Use span from this token if you need an isolated span.
95 /// The current non-normalized token if it's different from `token`.
96 /// Use span from this token if you need to concatenate it with some neighbouring spans.
97 unnormalized_token: Token,
98 /// The previous normalized token.
99 /// Use span from this token if you need an isolated span.
101 /// The previous non-normalized token if it's different from `prev_token`.
102 /// Use span from this token if you need to concatenate it with some neighbouring spans.
103 unnormalized_prev_token: Token,
104 /// Equivalent to `unnormalized_prev_token.span`.
105 /// FIXME: Remove in favor of `(unnormalized_)prev_token.span`.
107 restrictions: Restrictions,
108 /// Used to determine the path to externally loaded source files.
109 pub(super) directory: Directory,
110 /// `true` to parse sub-modules in other files.
111 // Public for rustfmt usage.
112 pub recurse_into_file_modules: bool,
113 /// Name of the root module this parser originated from. If `None`, then the
114 /// name is not known. This does not change while the parser is descending
115 /// into modules, and sub-parsers have new values for this name.
116 pub root_module_name: Option<String>,
117 expected_tokens: Vec<TokenType>,
118 token_cursor: TokenCursor,
119 desugar_doc_comments: bool,
120 /// `true` we should configure out of line modules as we parse.
121 // Public for rustfmt usage.
123 /// This field is used to keep track of how many left angle brackets we have seen. This is
124 /// required in order to detect extra leading left angle brackets (`<` characters) and error
127 /// See the comments in the `parse_path_segment` function for more details.
128 unmatched_angle_bracket_count: u32,
129 max_angle_bracket_count: u32,
130 /// A list of all unclosed delimiters found by the lexer. If an entry is used for error recovery
131 /// it gets removed from here. Every entry left at the end gets emitted as an independent
133 pub(super) unclosed_delims: Vec<UnmatchedBrace>,
134 last_unexpected_token_span: Option<Span>,
135 pub last_type_ascription: Option<(Span, bool /* likely path typo */)>,
136 /// If present, this `Parser` is not parsing Rust code but rather a macro call.
137 subparser_name: Option<&'static str>,
140 impl<'a> Drop for Parser<'a> {
142 emit_unclosed_delims(&mut self.unclosed_delims, &self.sess);
148 frame: TokenCursorFrame,
149 stack: Vec<TokenCursorFrame>,
153 struct TokenCursorFrame {
154 delim: token::DelimToken,
157 tree_cursor: tokenstream::Cursor,
159 last_token: LastToken,
162 /// This is used in `TokenCursorFrame` above to track tokens that are consumed
163 /// by the parser, and then that's transitively used to record the tokens that
164 /// each parse AST item is created with.
166 /// Right now this has two states, either collecting tokens or not collecting
167 /// tokens. If we're collecting tokens we just save everything off into a local
168 /// `Vec`. This should eventually though likely save tokens from the original
169 /// token stream and just use slicing of token streams to avoid creation of a
170 /// whole new vector.
172 /// The second state is where we're passively not recording tokens, but the last
173 /// token is still tracked for when we want to start recording tokens. This
174 /// "last token" means that when we start recording tokens we'll want to ensure
175 /// that this, the first token, is included in the output.
177 /// You can find some more example usage of this in the `collect_tokens` method
181 Collecting(Vec<TreeAndJoint>),
182 Was(Option<TreeAndJoint>),
185 impl TokenCursorFrame {
186 fn new(span: DelimSpan, delim: DelimToken, tts: &TokenStream) -> Self {
190 open_delim: delim == token::NoDelim,
191 tree_cursor: tts.clone().into_trees(),
192 close_delim: delim == token::NoDelim,
193 last_token: LastToken::Was(None),
199 fn next(&mut self) -> Token {
201 let tree = if !self.frame.open_delim {
202 self.frame.open_delim = true;
203 TokenTree::open_tt(self.frame.span, self.frame.delim)
204 } else if let Some(tree) = self.frame.tree_cursor.next() {
206 } else if !self.frame.close_delim {
207 self.frame.close_delim = true;
208 TokenTree::close_tt(self.frame.span, self.frame.delim)
209 } else if let Some(frame) = self.stack.pop() {
213 return Token::new(token::Eof, DUMMY_SP);
216 match self.frame.last_token {
217 LastToken::Collecting(ref mut v) => v.push(tree.clone().into()),
218 LastToken::Was(ref mut t) => *t = Some(tree.clone().into()),
222 TokenTree::Token(token) => return token,
223 TokenTree::Delimited(sp, delim, tts) => {
224 let frame = TokenCursorFrame::new(sp, delim, &tts);
225 self.stack.push(mem::replace(&mut self.frame, frame));
231 fn next_desugared(&mut self) -> Token {
232 let (name, sp) = match self.next() {
233 Token { kind: token::DocComment(name), span } => (name, span),
237 let stripped = strip_doc_comment_decoration(&name.as_str());
239 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
240 // required to wrap the text.
241 let mut num_of_hashes = 0;
243 for ch in stripped.chars() {
246 '#' if count > 0 => count + 1,
249 num_of_hashes = cmp::max(num_of_hashes, count);
252 let delim_span = DelimSpan::from_single(sp);
253 let body = TokenTree::Delimited(
257 TokenTree::token(token::Ident(sym::doc, false), sp),
258 TokenTree::token(token::Eq, sp),
260 TokenKind::lit(token::StrRaw(num_of_hashes), Symbol::intern(&stripped), None),
266 .collect::<TokenStream>()
270 self.stack.push(mem::replace(
272 TokenCursorFrame::new(
275 &if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
276 [TokenTree::token(token::Pound, sp), TokenTree::token(token::Not, sp), body]
279 .collect::<TokenStream>()
281 [TokenTree::token(token::Pound, sp), body]
284 .collect::<TokenStream>()
293 #[derive(Clone, PartialEq)]
306 fn to_string(&self) -> String {
308 TokenType::Token(ref t) => format!("`{}`", pprust::token_kind_to_string(t)),
309 TokenType::Keyword(kw) => format!("`{}`", kw),
310 TokenType::Operator => "an operator".to_string(),
311 TokenType::Lifetime => "lifetime".to_string(),
312 TokenType::Ident => "identifier".to_string(),
313 TokenType::Path => "path".to_string(),
314 TokenType::Type => "type".to_string(),
315 TokenType::Const => "const".to_string(),
320 #[derive(Copy, Clone, Debug)]
321 enum TokenExpectType {
326 /// A sequence separator.
328 /// The separator token.
329 sep: Option<TokenKind>,
330 /// `true` if a trailing separator is allowed.
331 trailing_sep_allowed: bool,
335 fn trailing_allowed(t: TokenKind) -> SeqSep {
336 SeqSep { sep: Some(t), trailing_sep_allowed: true }
339 fn none() -> SeqSep {
340 SeqSep { sep: None, trailing_sep_allowed: false }
344 pub enum FollowedByType {
349 fn token_descr_opt(token: &Token) -> Option<&'static str> {
350 Some(match token.kind {
351 _ if token.is_special_ident() => "reserved identifier",
352 _ if token.is_used_keyword() => "keyword",
353 _ if token.is_unused_keyword() => "reserved keyword",
354 token::DocComment(..) => "doc comment",
359 pub(super) fn token_descr(token: &Token) -> String {
360 let token_str = pprust::token_to_string(token);
361 match token_descr_opt(token) {
362 Some(prefix) => format!("{} `{}`", prefix, token_str),
363 _ => format!("`{}`", token_str),
367 impl<'a> Parser<'a> {
371 directory: Option<Directory>,
372 recurse_into_file_modules: bool,
373 desugar_doc_comments: bool,
374 subparser_name: Option<&'static str>,
376 let mut parser = Parser {
378 token: Token::dummy(),
379 unnormalized_token: Token::dummy(),
380 prev_token: Token::dummy(),
381 unnormalized_prev_token: Token::dummy(),
383 restrictions: Restrictions::empty(),
384 recurse_into_file_modules,
385 directory: Directory {
386 path: PathBuf::new(),
387 ownership: DirectoryOwnership::Owned { relative: None },
389 root_module_name: None,
390 expected_tokens: Vec::new(),
391 token_cursor: TokenCursor {
392 frame: TokenCursorFrame::new(DelimSpan::dummy(), token::NoDelim, &tokens.into()),
395 desugar_doc_comments,
397 unmatched_angle_bracket_count: 0,
398 max_angle_bracket_count: 0,
399 unclosed_delims: Vec::new(),
400 last_unexpected_token_span: None,
401 last_type_ascription: None,
405 // Make parser point to the first token.
408 if let Some(directory) = directory {
409 parser.directory = directory;
410 } else if !parser.token.span.is_dummy() {
411 if let Some(FileName::Real(path)) =
412 &sess.source_map().lookup_char_pos(parser.token.span.lo()).file.unmapped_path
414 if let Some(directory_path) = path.parent() {
415 parser.directory.path = directory_path.to_path_buf();
423 fn next_tok(&mut self, fallback_span: Span) -> Token {
424 let mut next = if self.desugar_doc_comments {
425 self.token_cursor.next_desugared()
427 self.token_cursor.next()
429 if next.span.is_dummy() {
430 // Tweak the location for better diagnostics, but keep syntactic context intact.
431 next.span = fallback_span.with_ctxt(next.span.ctxt());
436 crate fn unexpected<T>(&mut self) -> PResult<'a, T> {
437 match self.expect_one_of(&[], &[]) {
439 // We can get `Ok(true)` from `recover_closing_delimiter`
440 // which is called in `expected_one_of_not_found`.
441 Ok(_) => FatalError.raise(),
445 /// Expects and consumes the token `t`. Signals an error if the next token is not `t`.
446 pub fn expect(&mut self, t: &TokenKind) -> PResult<'a, bool /* recovered */> {
447 if self.expected_tokens.is_empty() {
448 if self.token == *t {
452 self.unexpected_try_recover(t)
455 self.expect_one_of(slice::from_ref(t), &[])
459 /// Expect next token to be edible or inedible token. If edible,
460 /// then consume it; if inedible, then return without consuming
461 /// anything. Signal a fatal error if next token is unexpected.
462 pub fn expect_one_of(
464 edible: &[TokenKind],
465 inedible: &[TokenKind],
466 ) -> PResult<'a, bool /* recovered */> {
467 if edible.contains(&self.token.kind) {
470 } else if inedible.contains(&self.token.kind) {
471 // leave it in the input
473 } else if self.last_unexpected_token_span == Some(self.token.span) {
476 self.expected_one_of_not_found(edible, inedible)
480 // Public for rustfmt usage.
481 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
482 self.parse_ident_common(true)
485 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, ast::Ident> {
486 match self.token.kind {
487 token::Ident(name, _) => {
488 if self.token.is_reserved_ident() {
489 let mut err = self.expected_ident_found();
496 let span = self.token.span;
498 Ok(Ident::new(name, span))
500 _ => Err(match self.prev_token.kind {
501 TokenKind::DocComment(..) => {
502 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
504 _ => self.expected_ident_found(),
509 /// Checks if the next token is `tok`, and returns `true` if so.
511 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
513 fn check(&mut self, tok: &TokenKind) -> bool {
514 let is_present = self.token == *tok;
516 self.expected_tokens.push(TokenType::Token(tok.clone()));
521 /// Consumes a token 'tok' if it exists. Returns whether the given token was present.
522 pub fn eat(&mut self, tok: &TokenKind) -> bool {
523 let is_present = self.check(tok);
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 // Public for rustfmt usage.
540 pub fn eat_keyword(&mut self, kw: Symbol) -> bool {
541 if self.check_keyword(kw) {
549 fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool {
550 if self.token.is_keyword(kw) {
558 /// If the given word is not a keyword, signals an error.
559 /// If the next token is not the given word, signals an error.
560 /// Otherwise, eats it.
561 fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> {
562 if !self.eat_keyword(kw) { self.unexpected() } else { Ok(()) }
565 /// Is the given keyword `kw` followed by a non-reserved identifier?
566 fn is_kw_followed_by_ident(&self, kw: Symbol) -> bool {
567 self.token.is_keyword(kw) && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
570 fn check_or_expected(&mut self, ok: bool, typ: TokenType) -> bool {
574 self.expected_tokens.push(typ);
579 fn check_ident(&mut self) -> bool {
580 self.check_or_expected(self.token.is_ident(), TokenType::Ident)
583 fn check_path(&mut self) -> bool {
584 self.check_or_expected(self.token.is_path_start(), TokenType::Path)
587 fn check_type(&mut self) -> bool {
588 self.check_or_expected(self.token.can_begin_type(), TokenType::Type)
591 fn check_const_arg(&mut self) -> bool {
592 self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const)
595 /// Checks to see if the next token is either `+` or `+=`.
596 /// Otherwise returns `false`.
597 fn check_plus(&mut self) -> bool {
598 self.check_or_expected(
599 self.token.is_like_plus(),
600 TokenType::Token(token::BinOp(token::Plus)),
604 /// Eats the expected token if it's present possibly breaking
605 /// compound tokens like multi-character operators in process.
606 /// Returns `true` if the token was eaten.
607 fn break_and_eat(&mut self, expected: TokenKind) -> bool {
608 if self.token.kind == expected {
612 match self.token.kind.break_two_token_op() {
613 Some((first, second)) if first == expected => {
614 let first_span = self.sess.source_map().start_point(self.token.span);
615 let second_span = self.token.span.with_lo(first_span.hi());
616 self.set_token(Token::new(first, first_span));
617 self.bump_with(Token::new(second, second_span));
621 self.expected_tokens.push(TokenType::Token(expected));
627 /// Eats `+` possibly breaking tokens like `+=` in process.
628 fn eat_plus(&mut self) -> bool {
629 self.break_and_eat(token::BinOp(token::Plus))
632 /// Eats `&` possibly breaking tokens like `&&` in process.
633 /// Signals an error if `&` is not eaten.
634 fn expect_and(&mut self) -> PResult<'a, ()> {
635 if self.break_and_eat(token::BinOp(token::And)) { Ok(()) } else { self.unexpected() }
638 /// Eats `|` possibly breaking tokens like `||` in process.
639 /// Signals an error if `|` was not eaten.
640 fn expect_or(&mut self) -> PResult<'a, ()> {
641 if self.break_and_eat(token::BinOp(token::Or)) { Ok(()) } else { self.unexpected() }
644 /// Eats `<` possibly breaking tokens like `<<` in process.
645 fn eat_lt(&mut self) -> bool {
646 let ate = self.break_and_eat(token::Lt);
648 // See doc comment for `unmatched_angle_bracket_count`.
649 self.unmatched_angle_bracket_count += 1;
650 self.max_angle_bracket_count += 1;
651 debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count);
656 /// Eats `<` possibly breaking tokens like `<<` in process.
657 /// Signals an error if `<` was not eaten.
658 fn expect_lt(&mut self) -> PResult<'a, ()> {
659 if self.eat_lt() { Ok(()) } else { self.unexpected() }
662 /// Eats `>` possibly breaking tokens like `>>` in process.
663 /// Signals an error if `>` was not eaten.
664 fn expect_gt(&mut self) -> PResult<'a, ()> {
665 if self.break_and_eat(token::Gt) {
666 // See doc comment for `unmatched_angle_bracket_count`.
667 if self.unmatched_angle_bracket_count > 0 {
668 self.unmatched_angle_bracket_count -= 1;
669 debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count);
677 fn expect_any_with_type(&mut self, kets: &[&TokenKind], expect: TokenExpectType) -> bool {
678 kets.iter().any(|k| match expect {
679 TokenExpectType::Expect => self.check(k),
680 TokenExpectType::NoExpect => self.token == **k,
684 fn parse_seq_to_before_tokens<T>(
688 expect: TokenExpectType,
689 mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
690 ) -> PResult<'a, (Vec<T>, bool /* trailing */, bool /* recovered */)> {
691 let mut first = true;
692 let mut recovered = false;
693 let mut trailing = false;
695 while !self.expect_any_with_type(kets, expect) {
696 if let token::CloseDelim(..) | token::Eof = self.token.kind {
699 if let Some(ref t) = sep.sep {
703 match self.expect(t) {
709 Err(mut expect_err) => {
710 let sp = self.prev_span.shrink_to_hi();
711 let token_str = pprust::token_kind_to_string(t);
713 // Attempt to keep parsing if it was a similar separator.
714 if let Some(ref tokens) = t.similar_tokens() {
715 if tokens.contains(&self.token.kind) {
720 // Attempt to keep parsing if it was an omitted separator.
723 // Parsed successfully, therefore most probably the code only
724 // misses a separator.
726 .span_suggestion_short(
728 &format!("missing `{}`", token_str),
730 Applicability::MaybeIncorrect,
738 // Parsing failed, therefore it must be something more serious
739 // than just a missing separator.
750 if sep.trailing_sep_allowed && self.expect_any_with_type(kets, expect) {
759 Ok((v, trailing, recovered))
762 /// Parses a sequence, not including the closing delimiter. The function
763 /// `f` must consume tokens until reaching the next separator or
765 fn parse_seq_to_before_end<T>(
769 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
770 ) -> PResult<'a, (Vec<T>, bool, bool)> {
771 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
774 /// Parses a sequence, including the closing delimiter. The function
775 /// `f` must consume tokens until reaching the next separator or
777 fn parse_seq_to_end<T>(
781 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
782 ) -> PResult<'a, (Vec<T>, bool /* trailing */)> {
783 let (val, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
790 /// Parses a sequence, including the closing delimiter. The function
791 /// `f` must consume tokens until reaching the next separator or
793 fn parse_unspanned_seq<T>(
798 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
799 ) -> PResult<'a, (Vec<T>, bool)> {
801 self.parse_seq_to_end(ket, sep, f)
804 fn parse_delim_comma_seq<T>(
807 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
808 ) -> PResult<'a, (Vec<T>, bool)> {
809 self.parse_unspanned_seq(
810 &token::OpenDelim(delim),
811 &token::CloseDelim(delim),
812 SeqSep::trailing_allowed(token::Comma),
817 fn parse_paren_comma_seq<T>(
819 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
820 ) -> PResult<'a, (Vec<T>, bool)> {
821 self.parse_delim_comma_seq(token::Paren, f)
824 // Interpolated identifier (`$i: ident`) and lifetime (`$l: lifetime`)
825 // tokens are replaced with usual identifier and lifetime tokens,
826 // so the former are never encountered during normal parsing.
827 crate fn set_token(&mut self, token: Token) {
828 self.unnormalized_token = token;
829 self.token = match &self.unnormalized_token.kind {
830 token::Interpolated(nt) => match **nt {
831 token::NtIdent(ident, is_raw) => {
832 Token::new(token::Ident(ident.name, is_raw), ident.span)
834 token::NtLifetime(ident) => Token::new(token::Lifetime(ident.name), ident.span),
835 _ => self.unnormalized_token.clone(),
837 _ => self.unnormalized_token.clone(),
841 /// Advance the parser by one token using provided token as the next one.
842 fn bump_with(&mut self, next_token: Token) {
843 // Bumping after EOF is a bad sign, usually an infinite loop.
844 if self.prev_token.kind == TokenKind::Eof {
845 let msg = "attempted to bump the parser past EOF (may be stuck in a loop)";
846 self.span_bug(self.token.span, msg);
849 // Update the current and previous tokens.
850 self.prev_token = self.token.take();
851 self.unnormalized_prev_token = self.unnormalized_token.take();
852 self.set_token(next_token);
854 // Update fields derived from the previous token.
855 self.prev_span = self.unnormalized_prev_token.span;
858 self.expected_tokens.clear();
861 /// Advance the parser by one token.
862 pub fn bump(&mut self) {
863 let next_token = self.next_tok(self.unnormalized_token.span);
864 self.bump_with(next_token);
867 /// Look-ahead `dist` tokens of `self.token` and get access to that token there.
868 /// When `dist == 0` then the current token is looked at.
869 pub fn look_ahead<R>(&self, dist: usize, looker: impl FnOnce(&Token) -> R) -> R {
871 return looker(&self.token);
874 let frame = &self.token_cursor.frame;
875 looker(&match frame.tree_cursor.look_ahead(dist - 1) {
876 Some(tree) => match tree {
877 TokenTree::Token(token) => token,
878 TokenTree::Delimited(dspan, delim, _) => {
879 Token::new(token::OpenDelim(delim), dspan.open)
882 None => Token::new(token::CloseDelim(frame.delim), frame.span.close),
886 /// Returns whether any of the given keywords are `dist` tokens ahead of the current one.
887 fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool {
888 self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw)))
891 /// Parses asyncness: `async` or nothing.
892 fn parse_asyncness(&mut self) -> Async {
893 if self.eat_keyword(kw::Async) {
894 let span = self.prev_span;
895 Async::Yes { span, closure_id: DUMMY_NODE_ID, return_impl_trait_id: DUMMY_NODE_ID }
901 /// Parses unsafety: `unsafe` or nothing.
902 fn parse_unsafety(&mut self) -> Unsafe {
903 if self.eat_keyword(kw::Unsafe) { Unsafe::Yes(self.prev_span) } else { Unsafe::No }
906 /// Parses constness: `const` or nothing.
907 fn parse_constness(&mut self) -> Const {
908 if self.eat_keyword(kw::Const) { Const::Yes(self.prev_span) } else { Const::No }
911 /// Parses mutability (`mut` or nothing).
912 fn parse_mutability(&mut self) -> Mutability {
913 if self.eat_keyword(kw::Mut) { Mutability::Mut } else { Mutability::Not }
916 /// Possibly parses mutability (`const` or `mut`).
917 fn parse_const_or_mut(&mut self) -> Option<Mutability> {
918 if self.eat_keyword(kw::Mut) {
919 Some(Mutability::Mut)
920 } else if self.eat_keyword(kw::Const) {
921 Some(Mutability::Not)
927 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
928 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = self.token.kind
930 self.expect_no_suffix(self.token.span, "a tuple index", suffix);
932 Ok(Ident::new(symbol, self.prev_span))
934 self.parse_ident_common(false)
938 fn parse_mac_args(&mut self) -> PResult<'a, P<MacArgs>> {
939 self.parse_mac_args_common(true).map(P)
942 fn parse_attr_args(&mut self) -> PResult<'a, MacArgs> {
943 self.parse_mac_args_common(false)
946 fn parse_mac_args_common(&mut self, delimited_only: bool) -> PResult<'a, MacArgs> {
948 if self.check(&token::OpenDelim(DelimToken::Paren))
949 || self.check(&token::OpenDelim(DelimToken::Bracket))
950 || self.check(&token::OpenDelim(DelimToken::Brace))
952 match self.parse_token_tree() {
953 TokenTree::Delimited(dspan, delim, tokens) =>
954 // We've confirmed above that there is a delimiter so unwrapping is OK.
956 MacArgs::Delimited(dspan, MacDelimiter::from_token(delim).unwrap(), tokens)
960 } else if !delimited_only {
961 if self.eat(&token::Eq) {
962 let eq_span = self.prev_span;
963 let mut is_interpolated_expr = false;
964 if let token::Interpolated(nt) = &self.token.kind {
965 if let token::NtExpr(..) = **nt {
966 is_interpolated_expr = true;
969 let token_tree = if is_interpolated_expr {
970 // We need to accept arbitrary interpolated expressions to continue
971 // supporting things like `doc = $expr` that work on stable.
972 // Non-literal interpolated expressions are rejected after expansion.
973 self.parse_token_tree()
975 self.parse_unsuffixed_lit()?.token_tree()
978 MacArgs::Eq(eq_span, token_tree.into())
983 return self.unexpected();
988 fn parse_or_use_outer_attributes(
990 already_parsed_attrs: Option<AttrVec>,
991 ) -> PResult<'a, AttrVec> {
992 if let Some(attrs) = already_parsed_attrs {
995 self.parse_outer_attributes().map(|a| a.into())
999 /// Parses a single token tree from the input.
1000 pub fn parse_token_tree(&mut self) -> TokenTree {
1001 match self.token.kind {
1002 token::OpenDelim(..) => {
1003 let frame = mem::replace(
1004 &mut self.token_cursor.frame,
1005 self.token_cursor.stack.pop().unwrap(),
1007 self.set_token(Token::new(TokenKind::CloseDelim(frame.delim), frame.span.close));
1009 TokenTree::Delimited(frame.span, frame.delim, frame.tree_cursor.stream.into())
1011 token::CloseDelim(_) | token::Eof => unreachable!(),
1014 TokenTree::Token(self.prev_token.clone())
1019 /// Parses a stream of tokens into a list of `TokenTree`s, up to EOF.
1020 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
1021 let mut tts = Vec::new();
1022 while self.token != token::Eof {
1023 tts.push(self.parse_token_tree());
1028 pub fn parse_tokens(&mut self) -> TokenStream {
1029 let mut result = Vec::new();
1031 match self.token.kind {
1032 token::Eof | token::CloseDelim(..) => break,
1033 _ => result.push(self.parse_token_tree().into()),
1036 TokenStream::new(result)
1039 /// Evaluates the closure with restrictions in place.
1041 /// Afters the closure is evaluated, restrictions are reset.
1042 fn with_res<T>(&mut self, res: Restrictions, f: impl FnOnce(&mut Self) -> T) -> T {
1043 let old = self.restrictions;
1044 self.restrictions = res;
1046 self.restrictions = old;
1050 fn is_crate_vis(&self) -> bool {
1051 self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
1054 /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
1055 /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
1056 /// If the following element can't be a tuple (i.e., it's a function definition), then
1057 /// it's not a tuple struct field), and the contents within the parentheses isn't valid,
1058 /// so emit a proper diagnostic.
1059 pub fn parse_visibility(&mut self, fbt: FollowedByType) -> PResult<'a, Visibility> {
1060 maybe_whole!(self, NtVis, |x| x);
1062 self.expected_tokens.push(TokenType::Keyword(kw::Crate));
1063 if self.is_crate_vis() {
1064 self.bump(); // `crate`
1065 self.sess.gated_spans.gate(sym::crate_visibility_modifier, self.prev_span);
1066 return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
1069 if !self.eat_keyword(kw::Pub) {
1070 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
1071 // keyword to grab a span from for inherited visibility; an empty span at the
1072 // beginning of the current token would seem to be the "Schelling span".
1073 return Ok(respan(self.token.span.shrink_to_lo(), VisibilityKind::Inherited));
1075 let lo = self.prev_span;
1077 if self.check(&token::OpenDelim(token::Paren)) {
1078 // We don't `self.bump()` the `(` yet because this might be a struct definition where
1079 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
1080 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
1081 // by the following tokens.
1082 if self.is_keyword_ahead(1, &[kw::Crate]) && self.look_ahead(2, |t| t != &token::ModSep)
1083 // account for `pub(crate::foo)`
1085 // Parse `pub(crate)`.
1087 self.bump(); // `crate`
1088 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1089 let vis = VisibilityKind::Crate(CrateSugar::PubCrate);
1090 return Ok(respan(lo.to(self.prev_span), vis));
1091 } else if self.is_keyword_ahead(1, &[kw::In]) {
1092 // Parse `pub(in path)`.
1094 self.bump(); // `in`
1095 let path = self.parse_path(PathStyle::Mod)?; // `path`
1096 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1097 let vis = VisibilityKind::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
1098 return Ok(respan(lo.to(self.prev_span), vis));
1099 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren))
1100 && self.is_keyword_ahead(1, &[kw::Super, kw::SelfLower])
1102 // Parse `pub(self)` or `pub(super)`.
1104 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
1105 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1106 let vis = VisibilityKind::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
1107 return Ok(respan(lo.to(self.prev_span), vis));
1108 } else if let FollowedByType::No = fbt {
1109 // Provide this diagnostic if a type cannot follow;
1110 // in particular, if this is not a tuple struct.
1111 self.recover_incorrect_vis_restriction()?;
1112 // Emit diagnostic, but continue with public visibility.
1116 Ok(respan(lo, VisibilityKind::Public))
1119 /// Recovery for e.g. `pub(something) fn ...` or `struct X { pub(something) y: Z }`
1120 fn recover_incorrect_vis_restriction(&mut self) -> PResult<'a, ()> {
1122 let path = self.parse_path(PathStyle::Mod)?;
1123 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1125 let msg = "incorrect visibility restriction";
1126 let suggestion = r##"some possible visibility restrictions are:
1127 `pub(crate)`: visible only on the current crate
1128 `pub(super)`: visible only in the current module's parent
1129 `pub(in path::to::module)`: visible only on the specified path"##;
1131 let path_str = pprust::path_to_string(&path);
1133 struct_span_err!(self.sess.span_diagnostic, path.span, E0704, "{}", msg)
1137 &format!("make this visible only to module `{}` with `in`", path_str),
1138 format!("in {}", path_str),
1139 Applicability::MachineApplicable,
1146 /// Parses `extern string_literal?`.
1147 fn parse_extern(&mut self) -> PResult<'a, Extern> {
1148 Ok(if self.eat_keyword(kw::Extern) {
1149 Extern::from_abi(self.parse_abi())
1155 /// Parses a string literal as an ABI spec.
1156 fn parse_abi(&mut self) -> Option<StrLit> {
1157 match self.parse_str_lit() {
1158 Ok(str_lit) => Some(str_lit),
1159 Err(Some(lit)) => match lit.kind {
1160 ast::LitKind::Err(_) => None,
1162 self.struct_span_err(lit.span, "non-string ABI literal")
1165 "specify the ABI with a string literal",
1166 "\"C\"".to_string(),
1167 Applicability::MaybeIncorrect,
1177 fn collect_tokens<R>(
1179 f: impl FnOnce(&mut Self) -> PResult<'a, R>,
1180 ) -> PResult<'a, (R, TokenStream)> {
1181 // Record all tokens we parse when parsing this item.
1182 let mut tokens = Vec::new();
1183 let prev_collecting = match self.token_cursor.frame.last_token {
1184 LastToken::Collecting(ref mut list) => Some(mem::take(list)),
1185 LastToken::Was(ref mut last) => {
1186 tokens.extend(last.take());
1190 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
1191 let prev = self.token_cursor.stack.len();
1193 let last_token = if self.token_cursor.stack.len() == prev {
1194 &mut self.token_cursor.frame.last_token
1195 } else if self.token_cursor.stack.get(prev).is_none() {
1196 // This can happen due to a bad interaction of two unrelated recovery mechanisms with
1197 // mismatched delimiters *and* recovery lookahead on the likely typo `pub ident(`
1199 return Ok((ret?, TokenStream::default()));
1201 &mut self.token_cursor.stack[prev].last_token
1204 // Pull out the tokens that we've collected from the call to `f` above.
1205 let mut collected_tokens = match *last_token {
1206 LastToken::Collecting(ref mut v) => mem::take(v),
1207 LastToken::Was(ref was) => {
1208 let msg = format!("our vector went away? - found Was({:?})", was);
1209 debug!("collect_tokens: {}", msg);
1210 self.sess.span_diagnostic.delay_span_bug(self.token.span, &msg);
1211 // This can happen due to a bad interaction of two unrelated recovery mechanisms
1212 // with mismatched delimiters *and* recovery lookahead on the likely typo
1213 // `pub ident(` (#62895, different but similar to the case above).
1214 return Ok((ret?, TokenStream::default()));
1218 // If we're not at EOF our current token wasn't actually consumed by
1219 // `f`, but it'll still be in our list that we pulled out. In that case
1221 let extra_token = if self.token != token::Eof { collected_tokens.pop() } else { None };
1223 // If we were previously collecting tokens, then this was a recursive
1224 // call. In that case we need to record all the tokens we collected in
1225 // our parent list as well. To do that we push a clone of our stream
1226 // onto the previous list.
1227 match prev_collecting {
1229 list.extend(collected_tokens.iter().cloned());
1230 list.extend(extra_token);
1231 *last_token = LastToken::Collecting(list);
1234 *last_token = LastToken::Was(extra_token);
1238 Ok((ret?, TokenStream::new(collected_tokens)))
1242 fn is_import_coupler(&mut self) -> bool {
1243 self.check(&token::ModSep)
1244 && self.look_ahead(1, |t| {
1245 *t == token::OpenDelim(token::Brace) || *t == token::BinOp(token::Star)
1250 crate fn make_unclosed_delims_error(
1251 unmatched: UnmatchedBrace,
1253 ) -> Option<DiagnosticBuilder<'_>> {
1254 // `None` here means an `Eof` was found. We already emit those errors elsewhere, we add them to
1255 // `unmatched_braces` only for error recovery in the `Parser`.
1256 let found_delim = unmatched.found_delim?;
1257 let mut err = sess.span_diagnostic.struct_span_err(
1258 unmatched.found_span,
1260 "mismatched closing delimiter: `{}`",
1261 pprust::token_kind_to_string(&token::CloseDelim(found_delim)),
1264 err.span_label(unmatched.found_span, "mismatched closing delimiter");
1265 if let Some(sp) = unmatched.candidate_span {
1266 err.span_label(sp, "closing delimiter possibly meant for this");
1268 if let Some(sp) = unmatched.unclosed_span {
1269 err.span_label(sp, "unclosed delimiter");
1274 pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, sess: &ParseSess) {
1275 *sess.reached_eof.borrow_mut() |=
1276 unclosed_delims.iter().any(|unmatched_delim| unmatched_delim.found_delim.is_none());
1277 for unmatched in unclosed_delims.drain(..) {
1278 make_unclosed_delims_error(unmatched, sess).map(|mut e| {