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 non-normalized token.
91 /// The current normalized token.
92 /// "Normalized" means that some interpolated tokens
93 /// (`$i: ident` and `$l: lifetime` meta-variables) are replaced
94 /// with non-interpolated identifier and lifetime tokens they refer to.
95 /// Use this if you need to check for `token::Ident` or `token::Lifetime` specifically,
96 /// this also includes edition checks for edition-specific keyword identifiers.
97 pub normalized_token: Token,
98 /// The previous non-normalized token.
99 pub prev_token: Token,
100 /// The previous normalized token.
101 /// Use this if you need to check for `token::Ident` or `token::Lifetime` specifically,
102 /// this also includes edition checks for edition-specific keyword identifiers.
103 pub normalized_prev_token: Token,
104 /// FIXME: Remove in favor of the equivalent `prev_token.span`.
106 restrictions: Restrictions,
107 /// Used to determine the path to externally loaded source files.
108 pub(super) directory: Directory,
109 /// `true` to parse sub-modules in other files.
110 // Public for rustfmt usage.
111 pub recurse_into_file_modules: bool,
112 /// Name of the root module this parser originated from. If `None`, then the
113 /// name is not known. This does not change while the parser is descending
114 /// into modules, and sub-parsers have new values for this name.
115 pub root_module_name: Option<String>,
116 expected_tokens: Vec<TokenType>,
117 token_cursor: TokenCursor,
118 desugar_doc_comments: bool,
119 /// `true` we should configure out of line modules as we parse.
120 // Public for rustfmt usage.
122 /// This field is used to keep track of how many left angle brackets we have seen. This is
123 /// required in order to detect extra leading left angle brackets (`<` characters) and error
126 /// See the comments in the `parse_path_segment` function for more details.
127 unmatched_angle_bracket_count: u32,
128 max_angle_bracket_count: u32,
129 /// A list of all unclosed delimiters found by the lexer. If an entry is used for error recovery
130 /// it gets removed from here. Every entry left at the end gets emitted as an independent
132 pub(super) unclosed_delims: Vec<UnmatchedBrace>,
133 last_unexpected_token_span: Option<Span>,
134 pub last_type_ascription: Option<(Span, bool /* likely path typo */)>,
135 /// If present, this `Parser` is not parsing Rust code but rather a macro call.
136 subparser_name: Option<&'static str>,
139 impl<'a> Drop for Parser<'a> {
141 emit_unclosed_delims(&mut self.unclosed_delims, &self.sess);
147 frame: TokenCursorFrame,
148 stack: Vec<TokenCursorFrame>,
152 struct TokenCursorFrame {
153 delim: token::DelimToken,
156 tree_cursor: tokenstream::Cursor,
158 last_token: LastToken,
161 /// This is used in `TokenCursorFrame` above to track tokens that are consumed
162 /// by the parser, and then that's transitively used to record the tokens that
163 /// each parse AST item is created with.
165 /// Right now this has two states, either collecting tokens or not collecting
166 /// tokens. If we're collecting tokens we just save everything off into a local
167 /// `Vec`. This should eventually though likely save tokens from the original
168 /// token stream and just use slicing of token streams to avoid creation of a
169 /// whole new vector.
171 /// The second state is where we're passively not recording tokens, but the last
172 /// token is still tracked for when we want to start recording tokens. This
173 /// "last token" means that when we start recording tokens we'll want to ensure
174 /// that this, the first token, is included in the output.
176 /// You can find some more example usage of this in the `collect_tokens` method
180 Collecting(Vec<TreeAndJoint>),
181 Was(Option<TreeAndJoint>),
184 impl TokenCursorFrame {
185 fn new(span: DelimSpan, delim: DelimToken, tts: &TokenStream) -> Self {
189 open_delim: delim == token::NoDelim,
190 tree_cursor: tts.clone().into_trees(),
191 close_delim: delim == token::NoDelim,
192 last_token: LastToken::Was(None),
198 fn next(&mut self) -> Token {
200 let tree = if !self.frame.open_delim {
201 self.frame.open_delim = true;
202 TokenTree::open_tt(self.frame.span, self.frame.delim)
203 } else if let Some(tree) = self.frame.tree_cursor.next() {
205 } else if !self.frame.close_delim {
206 self.frame.close_delim = true;
207 TokenTree::close_tt(self.frame.span, self.frame.delim)
208 } else if let Some(frame) = self.stack.pop() {
212 return Token::new(token::Eof, DUMMY_SP);
215 match self.frame.last_token {
216 LastToken::Collecting(ref mut v) => v.push(tree.clone().into()),
217 LastToken::Was(ref mut t) => *t = Some(tree.clone().into()),
221 TokenTree::Token(token) => return token,
222 TokenTree::Delimited(sp, delim, tts) => {
223 let frame = TokenCursorFrame::new(sp, delim, &tts);
224 self.stack.push(mem::replace(&mut self.frame, frame));
230 fn next_desugared(&mut self) -> Token {
231 let (name, sp) = match self.next() {
232 Token { kind: token::DocComment(name), span } => (name, span),
236 let stripped = strip_doc_comment_decoration(&name.as_str());
238 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
239 // required to wrap the text.
240 let mut num_of_hashes = 0;
242 for ch in stripped.chars() {
245 '#' if count > 0 => count + 1,
248 num_of_hashes = cmp::max(num_of_hashes, count);
251 let delim_span = DelimSpan::from_single(sp);
252 let body = TokenTree::Delimited(
256 TokenTree::token(token::Ident(sym::doc, false), sp),
257 TokenTree::token(token::Eq, sp),
259 TokenKind::lit(token::StrRaw(num_of_hashes), Symbol::intern(&stripped), None),
265 .collect::<TokenStream>(),
268 self.stack.push(mem::replace(
270 TokenCursorFrame::new(
273 &if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
274 [TokenTree::token(token::Pound, sp), TokenTree::token(token::Not, sp), body]
277 .collect::<TokenStream>()
279 [TokenTree::token(token::Pound, sp), body]
282 .collect::<TokenStream>()
291 #[derive(Clone, PartialEq)]
304 fn to_string(&self) -> String {
306 TokenType::Token(ref t) => format!("`{}`", pprust::token_kind_to_string(t)),
307 TokenType::Keyword(kw) => format!("`{}`", kw),
308 TokenType::Operator => "an operator".to_string(),
309 TokenType::Lifetime => "lifetime".to_string(),
310 TokenType::Ident => "identifier".to_string(),
311 TokenType::Path => "path".to_string(),
312 TokenType::Type => "type".to_string(),
313 TokenType::Const => "const".to_string(),
318 #[derive(Copy, Clone, Debug)]
319 enum TokenExpectType {
324 /// A sequence separator.
326 /// The separator token.
327 sep: Option<TokenKind>,
328 /// `true` if a trailing separator is allowed.
329 trailing_sep_allowed: bool,
333 fn trailing_allowed(t: TokenKind) -> SeqSep {
334 SeqSep { sep: Some(t), trailing_sep_allowed: true }
337 fn none() -> SeqSep {
338 SeqSep { sep: None, trailing_sep_allowed: false }
342 pub enum FollowedByType {
347 fn token_descr_opt(token: &Token) -> Option<&'static str> {
348 Some(match token.kind {
349 _ if token.is_special_ident() => "reserved identifier",
350 _ if token.is_used_keyword() => "keyword",
351 _ if token.is_unused_keyword() => "reserved keyword",
352 token::DocComment(..) => "doc comment",
357 pub(super) fn token_descr(token: &Token) -> String {
358 let token_str = pprust::token_to_string(token);
359 match token_descr_opt(token) {
360 Some(prefix) => format!("{} `{}`", prefix, token_str),
361 _ => format!("`{}`", token_str),
365 impl<'a> Parser<'a> {
369 directory: Option<Directory>,
370 recurse_into_file_modules: bool,
371 desugar_doc_comments: bool,
372 subparser_name: Option<&'static str>,
374 let mut parser = Parser {
376 token: Token::dummy(),
377 normalized_token: Token::dummy(),
378 prev_token: Token::dummy(),
379 normalized_prev_token: Token::dummy(),
381 restrictions: Restrictions::empty(),
382 recurse_into_file_modules,
383 directory: Directory {
384 path: PathBuf::new(),
385 ownership: DirectoryOwnership::Owned { relative: None },
387 root_module_name: None,
388 expected_tokens: Vec::new(),
389 token_cursor: TokenCursor {
390 frame: TokenCursorFrame::new(DelimSpan::dummy(), token::NoDelim, &tokens),
393 desugar_doc_comments,
395 unmatched_angle_bracket_count: 0,
396 max_angle_bracket_count: 0,
397 unclosed_delims: Vec::new(),
398 last_unexpected_token_span: None,
399 last_type_ascription: None,
403 // Make parser point to the first token.
406 if let Some(directory) = directory {
407 parser.directory = directory;
408 } else if !parser.token.span.is_dummy() {
409 if let Some(FileName::Real(path)) =
410 &sess.source_map().lookup_char_pos(parser.token.span.lo()).file.unmapped_path
412 if let Some(directory_path) = path.parent() {
413 parser.directory.path = directory_path.to_path_buf();
421 fn next_tok(&mut self, fallback_span: Span) -> Token {
422 let mut next = if self.desugar_doc_comments {
423 self.token_cursor.next_desugared()
425 self.token_cursor.next()
427 if next.span.is_dummy() {
428 // Tweak the location for better diagnostics, but keep syntactic context intact.
429 next.span = fallback_span.with_ctxt(next.span.ctxt());
434 crate fn unexpected<T>(&mut self) -> PResult<'a, T> {
435 match self.expect_one_of(&[], &[]) {
437 // We can get `Ok(true)` from `recover_closing_delimiter`
438 // which is called in `expected_one_of_not_found`.
439 Ok(_) => FatalError.raise(),
443 /// Expects and consumes the token `t`. Signals an error if the next token is not `t`.
444 pub fn expect(&mut self, t: &TokenKind) -> PResult<'a, bool /* recovered */> {
445 if self.expected_tokens.is_empty() {
446 if self.token == *t {
450 self.unexpected_try_recover(t)
453 self.expect_one_of(slice::from_ref(t), &[])
457 /// Expect next token to be edible or inedible token. If edible,
458 /// then consume it; if inedible, then return without consuming
459 /// anything. Signal a fatal error if next token is unexpected.
460 pub fn expect_one_of(
462 edible: &[TokenKind],
463 inedible: &[TokenKind],
464 ) -> PResult<'a, bool /* recovered */> {
465 if edible.contains(&self.token.kind) {
468 } else if inedible.contains(&self.token.kind) {
469 // leave it in the input
471 } else if self.last_unexpected_token_span == Some(self.token.span) {
474 self.expected_one_of_not_found(edible, inedible)
478 // Public for rustfmt usage.
479 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
480 self.parse_ident_common(true)
483 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, ast::Ident> {
484 match self.normalized_token.kind {
485 token::Ident(name, _) => {
486 if self.token.is_reserved_ident() {
487 let mut err = self.expected_ident_found();
495 Ok(Ident::new(name, self.normalized_prev_token.span))
497 _ => Err(match self.prev_token.kind {
498 TokenKind::DocComment(..) => {
499 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
501 _ => self.expected_ident_found(),
506 /// Checks if the next token is `tok`, and returns `true` if so.
508 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
510 fn check(&mut self, tok: &TokenKind) -> bool {
511 let is_present = self.token == *tok;
513 self.expected_tokens.push(TokenType::Token(tok.clone()));
518 /// Consumes a token 'tok' if it exists. Returns whether the given token was present.
519 pub fn eat(&mut self, tok: &TokenKind) -> bool {
520 let is_present = self.check(tok);
527 /// If the next token is the given keyword, returns `true` without eating it.
528 /// An expectation is also added for diagnostics purposes.
529 fn check_keyword(&mut self, kw: Symbol) -> bool {
530 self.expected_tokens.push(TokenType::Keyword(kw));
531 self.token.is_keyword(kw)
534 /// If the next token is the given keyword, eats it and returns `true`.
535 /// Otherwise, returns `false`. An expectation is also added for diagnostics purposes.
536 // Public for rustfmt usage.
537 pub fn eat_keyword(&mut self, kw: Symbol) -> bool {
538 if self.check_keyword(kw) {
546 fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool {
547 if self.token.is_keyword(kw) {
555 /// If the given word is not a keyword, signals an error.
556 /// If the next token is not the given word, signals an error.
557 /// Otherwise, eats it.
558 fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> {
559 if !self.eat_keyword(kw) { self.unexpected() } else { Ok(()) }
562 /// Is the given keyword `kw` followed by a non-reserved identifier?
563 fn is_kw_followed_by_ident(&self, kw: Symbol) -> bool {
564 self.token.is_keyword(kw) && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
567 fn check_or_expected(&mut self, ok: bool, typ: TokenType) -> bool {
571 self.expected_tokens.push(typ);
576 fn check_ident(&mut self) -> bool {
577 self.check_or_expected(self.token.is_ident(), TokenType::Ident)
580 fn check_path(&mut self) -> bool {
581 self.check_or_expected(self.token.is_path_start(), TokenType::Path)
584 fn check_type(&mut self) -> bool {
585 self.check_or_expected(self.token.can_begin_type(), TokenType::Type)
588 fn check_const_arg(&mut self) -> bool {
589 self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const)
592 /// Checks to see if the next token is either `+` or `+=`.
593 /// Otherwise returns `false`.
594 fn check_plus(&mut self) -> bool {
595 self.check_or_expected(
596 self.token.is_like_plus(),
597 TokenType::Token(token::BinOp(token::Plus)),
601 /// Eats the expected token if it's present possibly breaking
602 /// compound tokens like multi-character operators in process.
603 /// Returns `true` if the token was eaten.
604 fn break_and_eat(&mut self, expected: TokenKind) -> bool {
605 if self.token.kind == expected {
609 match self.token.kind.break_two_token_op() {
610 Some((first, second)) if first == expected => {
611 let first_span = self.sess.source_map().start_point(self.token.span);
612 let second_span = self.token.span.with_lo(first_span.hi());
613 self.set_token(Token::new(first, first_span));
614 self.bump_with(Token::new(second, second_span));
618 self.expected_tokens.push(TokenType::Token(expected));
624 /// Eats `+` possibly breaking tokens like `+=` in process.
625 fn eat_plus(&mut self) -> bool {
626 self.break_and_eat(token::BinOp(token::Plus))
629 /// Eats `&` possibly breaking tokens like `&&` in process.
630 /// Signals an error if `&` is not eaten.
631 fn expect_and(&mut self) -> PResult<'a, ()> {
632 if self.break_and_eat(token::BinOp(token::And)) { Ok(()) } else { self.unexpected() }
635 /// Eats `|` possibly breaking tokens like `||` in process.
636 /// Signals an error if `|` was not eaten.
637 fn expect_or(&mut self) -> PResult<'a, ()> {
638 if self.break_and_eat(token::BinOp(token::Or)) { Ok(()) } else { self.unexpected() }
641 /// Eats `<` possibly breaking tokens like `<<` in process.
642 fn eat_lt(&mut self) -> bool {
643 let ate = self.break_and_eat(token::Lt);
645 // See doc comment for `unmatched_angle_bracket_count`.
646 self.unmatched_angle_bracket_count += 1;
647 self.max_angle_bracket_count += 1;
648 debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count);
653 /// Eats `<` possibly breaking tokens like `<<` in process.
654 /// Signals an error if `<` was not eaten.
655 fn expect_lt(&mut self) -> PResult<'a, ()> {
656 if self.eat_lt() { Ok(()) } else { self.unexpected() }
659 /// Eats `>` possibly breaking tokens like `>>` in process.
660 /// Signals an error if `>` was not eaten.
661 fn expect_gt(&mut self) -> PResult<'a, ()> {
662 if self.break_and_eat(token::Gt) {
663 // See doc comment for `unmatched_angle_bracket_count`.
664 if self.unmatched_angle_bracket_count > 0 {
665 self.unmatched_angle_bracket_count -= 1;
666 debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count);
674 fn expect_any_with_type(&mut self, kets: &[&TokenKind], expect: TokenExpectType) -> bool {
675 kets.iter().any(|k| match expect {
676 TokenExpectType::Expect => self.check(k),
677 TokenExpectType::NoExpect => self.token == **k,
681 fn parse_seq_to_before_tokens<T>(
685 expect: TokenExpectType,
686 mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
687 ) -> PResult<'a, (Vec<T>, bool /* trailing */, bool /* recovered */)> {
688 let mut first = true;
689 let mut recovered = false;
690 let mut trailing = false;
692 while !self.expect_any_with_type(kets, expect) {
693 if let token::CloseDelim(..) | token::Eof = self.token.kind {
696 if let Some(ref t) = sep.sep {
700 match self.expect(t) {
706 Err(mut expect_err) => {
707 let sp = self.prev_span.shrink_to_hi();
708 let token_str = pprust::token_kind_to_string(t);
710 // Attempt to keep parsing if it was a similar separator.
711 if let Some(ref tokens) = t.similar_tokens() {
712 if tokens.contains(&self.token.kind) {
717 // Attempt to keep parsing if it was an omitted separator.
720 // Parsed successfully, therefore most probably the code only
721 // misses a separator.
723 .span_suggestion_short(
725 &format!("missing `{}`", token_str),
727 Applicability::MaybeIncorrect,
735 // Parsing failed, therefore it must be something more serious
736 // than just a missing separator.
747 if sep.trailing_sep_allowed && self.expect_any_with_type(kets, expect) {
756 Ok((v, trailing, recovered))
759 /// Parses a sequence, not including the closing delimiter. The function
760 /// `f` must consume tokens until reaching the next separator or
762 fn parse_seq_to_before_end<T>(
766 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
767 ) -> PResult<'a, (Vec<T>, bool, bool)> {
768 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
771 /// Parses a sequence, including the closing delimiter. The function
772 /// `f` must consume tokens until reaching the next separator or
774 fn parse_seq_to_end<T>(
778 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
779 ) -> PResult<'a, (Vec<T>, bool /* trailing */)> {
780 let (val, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
787 /// Parses a sequence, including the closing delimiter. The function
788 /// `f` must consume tokens until reaching the next separator or
790 fn parse_unspanned_seq<T>(
795 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
796 ) -> PResult<'a, (Vec<T>, bool)> {
798 self.parse_seq_to_end(ket, sep, f)
801 fn parse_delim_comma_seq<T>(
804 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
805 ) -> PResult<'a, (Vec<T>, bool)> {
806 self.parse_unspanned_seq(
807 &token::OpenDelim(delim),
808 &token::CloseDelim(delim),
809 SeqSep::trailing_allowed(token::Comma),
814 fn parse_paren_comma_seq<T>(
816 f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
817 ) -> PResult<'a, (Vec<T>, bool)> {
818 self.parse_delim_comma_seq(token::Paren, f)
821 // Interpolated identifier (`$i: ident`) and lifetime (`$l: lifetime`)
822 // tokens are replaced with usual identifier and lifetime tokens,
823 // so the former are never encountered during normal parsing.
824 crate fn set_token(&mut self, token: Token) {
826 self.normalized_token = match &self.token.kind {
827 token::Interpolated(nt) => match **nt {
828 token::NtIdent(ident, is_raw) => {
829 Token::new(token::Ident(ident.name, is_raw), ident.span)
831 token::NtLifetime(ident) => Token::new(token::Lifetime(ident.name), ident.span),
832 _ => self.token.clone(),
834 _ => self.token.clone(),
838 /// Advance the parser by one token using provided token as the next one.
839 fn bump_with(&mut self, next_token: Token) {
840 // Bumping after EOF is a bad sign, usually an infinite loop.
841 if self.prev_token.kind == TokenKind::Eof {
842 let msg = "attempted to bump the parser past EOF (may be stuck in a loop)";
843 self.span_bug(self.token.span, msg);
846 // Update the current and previous tokens.
847 self.prev_token = self.token.take();
848 self.normalized_prev_token = self.normalized_token.take();
849 self.set_token(next_token);
851 // Update fields derived from the previous token.
852 self.prev_span = self.prev_token.span;
855 self.expected_tokens.clear();
858 /// Advance the parser by one token.
859 pub fn bump(&mut self) {
860 let next_token = self.next_tok(self.token.span);
861 self.bump_with(next_token);
864 /// Look-ahead `dist` tokens of `self.token` and get access to that token there.
865 /// When `dist == 0` then the current token is looked at.
866 pub fn look_ahead<R>(&self, dist: usize, looker: impl FnOnce(&Token) -> R) -> R {
868 return looker(&self.token);
871 let frame = &self.token_cursor.frame;
872 looker(&match frame.tree_cursor.look_ahead(dist - 1) {
873 Some(tree) => match tree {
874 TokenTree::Token(token) => token,
875 TokenTree::Delimited(dspan, delim, _) => {
876 Token::new(token::OpenDelim(delim), dspan.open)
879 None => Token::new(token::CloseDelim(frame.delim), frame.span.close),
883 /// Returns whether any of the given keywords are `dist` tokens ahead of the current one.
884 fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool {
885 self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw)))
888 /// Parses asyncness: `async` or nothing.
889 fn parse_asyncness(&mut self) -> Async {
890 if self.eat_keyword(kw::Async) {
891 let span = self.normalized_prev_token.span;
892 Async::Yes { span, closure_id: DUMMY_NODE_ID, return_impl_trait_id: DUMMY_NODE_ID }
898 /// Parses unsafety: `unsafe` or nothing.
899 fn parse_unsafety(&mut self) -> Unsafe {
900 if self.eat_keyword(kw::Unsafe) { Unsafe::Yes(self.prev_span) } else { Unsafe::No }
903 /// Parses constness: `const` or nothing.
904 fn parse_constness(&mut self) -> Const {
905 if self.eat_keyword(kw::Const) { Const::Yes(self.prev_span) } else { Const::No }
908 /// Parses mutability (`mut` or nothing).
909 fn parse_mutability(&mut self) -> Mutability {
910 if self.eat_keyword(kw::Mut) { Mutability::Mut } else { Mutability::Not }
913 /// Possibly parses mutability (`const` or `mut`).
914 fn parse_const_or_mut(&mut self) -> Option<Mutability> {
915 if self.eat_keyword(kw::Mut) {
916 Some(Mutability::Mut)
917 } else if self.eat_keyword(kw::Const) {
918 Some(Mutability::Not)
924 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
925 if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = self.token.kind
927 self.expect_no_suffix(self.token.span, "a tuple index", suffix);
929 Ok(Ident::new(symbol, self.prev_span))
931 self.parse_ident_common(false)
935 fn parse_mac_args(&mut self) -> PResult<'a, P<MacArgs>> {
936 self.parse_mac_args_common(true).map(P)
939 fn parse_attr_args(&mut self) -> PResult<'a, MacArgs> {
940 self.parse_mac_args_common(false)
943 fn parse_mac_args_common(&mut self, delimited_only: bool) -> PResult<'a, MacArgs> {
945 if self.check(&token::OpenDelim(DelimToken::Paren))
946 || self.check(&token::OpenDelim(DelimToken::Bracket))
947 || self.check(&token::OpenDelim(DelimToken::Brace))
949 match self.parse_token_tree() {
950 TokenTree::Delimited(dspan, delim, tokens) =>
951 // We've confirmed above that there is a delimiter so unwrapping is OK.
953 MacArgs::Delimited(dspan, MacDelimiter::from_token(delim).unwrap(), tokens)
957 } else if !delimited_only {
958 if self.eat(&token::Eq) {
959 let eq_span = self.prev_span;
960 let mut is_interpolated_expr = false;
961 if let token::Interpolated(nt) = &self.token.kind {
962 if let token::NtExpr(..) = **nt {
963 is_interpolated_expr = true;
966 let token_tree = if is_interpolated_expr {
967 // We need to accept arbitrary interpolated expressions to continue
968 // supporting things like `doc = $expr` that work on stable.
969 // Non-literal interpolated expressions are rejected after expansion.
970 self.parse_token_tree()
972 self.parse_unsuffixed_lit()?.token_tree()
975 MacArgs::Eq(eq_span, token_tree.into())
980 return self.unexpected();
985 fn parse_or_use_outer_attributes(
987 already_parsed_attrs: Option<AttrVec>,
988 ) -> PResult<'a, AttrVec> {
989 if let Some(attrs) = already_parsed_attrs {
992 self.parse_outer_attributes().map(|a| a.into())
996 /// Parses a single token tree from the input.
997 pub fn parse_token_tree(&mut self) -> TokenTree {
998 match self.token.kind {
999 token::OpenDelim(..) => {
1000 let frame = mem::replace(
1001 &mut self.token_cursor.frame,
1002 self.token_cursor.stack.pop().unwrap(),
1004 self.set_token(Token::new(TokenKind::CloseDelim(frame.delim), frame.span.close));
1006 TokenTree::Delimited(frame.span, frame.delim, frame.tree_cursor.stream)
1008 token::CloseDelim(_) | token::Eof => unreachable!(),
1011 TokenTree::Token(self.prev_token.clone())
1016 /// Parses a stream of tokens into a list of `TokenTree`s, up to EOF.
1017 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
1018 let mut tts = Vec::new();
1019 while self.token != token::Eof {
1020 tts.push(self.parse_token_tree());
1025 pub fn parse_tokens(&mut self) -> TokenStream {
1026 let mut result = Vec::new();
1028 match self.token.kind {
1029 token::Eof | token::CloseDelim(..) => break,
1030 _ => result.push(self.parse_token_tree().into()),
1033 TokenStream::new(result)
1036 /// Evaluates the closure with restrictions in place.
1038 /// Afters the closure is evaluated, restrictions are reset.
1039 fn with_res<T>(&mut self, res: Restrictions, f: impl FnOnce(&mut Self) -> T) -> T {
1040 let old = self.restrictions;
1041 self.restrictions = res;
1043 self.restrictions = old;
1047 fn is_crate_vis(&self) -> bool {
1048 self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
1051 /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
1052 /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
1053 /// If the following element can't be a tuple (i.e., it's a function definition), then
1054 /// it's not a tuple struct field), and the contents within the parentheses isn't valid,
1055 /// so emit a proper diagnostic.
1056 pub fn parse_visibility(&mut self, fbt: FollowedByType) -> PResult<'a, Visibility> {
1057 maybe_whole!(self, NtVis, |x| x);
1059 self.expected_tokens.push(TokenType::Keyword(kw::Crate));
1060 if self.is_crate_vis() {
1061 self.bump(); // `crate`
1062 self.sess.gated_spans.gate(sym::crate_visibility_modifier, self.prev_span);
1063 return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
1066 if !self.eat_keyword(kw::Pub) {
1067 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
1068 // keyword to grab a span from for inherited visibility; an empty span at the
1069 // beginning of the current token would seem to be the "Schelling span".
1070 return Ok(respan(self.token.span.shrink_to_lo(), VisibilityKind::Inherited));
1072 let lo = self.prev_span;
1074 if self.check(&token::OpenDelim(token::Paren)) {
1075 // We don't `self.bump()` the `(` yet because this might be a struct definition where
1076 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
1077 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
1078 // by the following tokens.
1079 if self.is_keyword_ahead(1, &[kw::Crate]) && self.look_ahead(2, |t| t != &token::ModSep)
1080 // account for `pub(crate::foo)`
1082 // Parse `pub(crate)`.
1084 self.bump(); // `crate`
1085 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1086 let vis = VisibilityKind::Crate(CrateSugar::PubCrate);
1087 return Ok(respan(lo.to(self.prev_span), vis));
1088 } else if self.is_keyword_ahead(1, &[kw::In]) {
1089 // Parse `pub(in path)`.
1091 self.bump(); // `in`
1092 let path = self.parse_path(PathStyle::Mod)?; // `path`
1093 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1094 let vis = VisibilityKind::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
1095 return Ok(respan(lo.to(self.prev_span), vis));
1096 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren))
1097 && self.is_keyword_ahead(1, &[kw::Super, kw::SelfLower])
1099 // Parse `pub(self)` or `pub(super)`.
1101 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
1102 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1103 let vis = VisibilityKind::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
1104 return Ok(respan(lo.to(self.prev_span), vis));
1105 } else if let FollowedByType::No = fbt {
1106 // Provide this diagnostic if a type cannot follow;
1107 // in particular, if this is not a tuple struct.
1108 self.recover_incorrect_vis_restriction()?;
1109 // Emit diagnostic, but continue with public visibility.
1113 Ok(respan(lo, VisibilityKind::Public))
1116 /// Recovery for e.g. `pub(something) fn ...` or `struct X { pub(something) y: Z }`
1117 fn recover_incorrect_vis_restriction(&mut self) -> PResult<'a, ()> {
1119 let path = self.parse_path(PathStyle::Mod)?;
1120 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1122 let msg = "incorrect visibility restriction";
1123 let suggestion = r##"some possible visibility restrictions are:
1124 `pub(crate)`: visible only on the current crate
1125 `pub(super)`: visible only in the current module's parent
1126 `pub(in path::to::module)`: visible only on the specified path"##;
1128 let path_str = pprust::path_to_string(&path);
1130 struct_span_err!(self.sess.span_diagnostic, path.span, E0704, "{}", msg)
1134 &format!("make this visible only to module `{}` with `in`", path_str),
1135 format!("in {}", path_str),
1136 Applicability::MachineApplicable,
1143 /// Parses `extern string_literal?`.
1144 fn parse_extern(&mut self) -> PResult<'a, Extern> {
1145 Ok(if self.eat_keyword(kw::Extern) {
1146 Extern::from_abi(self.parse_abi())
1152 /// Parses a string literal as an ABI spec.
1153 fn parse_abi(&mut self) -> Option<StrLit> {
1154 match self.parse_str_lit() {
1155 Ok(str_lit) => Some(str_lit),
1156 Err(Some(lit)) => match lit.kind {
1157 ast::LitKind::Err(_) => None,
1159 self.struct_span_err(lit.span, "non-string ABI literal")
1162 "specify the ABI with a string literal",
1163 "\"C\"".to_string(),
1164 Applicability::MaybeIncorrect,
1174 fn collect_tokens<R>(
1176 f: impl FnOnce(&mut Self) -> PResult<'a, R>,
1177 ) -> PResult<'a, (R, TokenStream)> {
1178 // Record all tokens we parse when parsing this item.
1179 let mut tokens = Vec::new();
1180 let prev_collecting = match self.token_cursor.frame.last_token {
1181 LastToken::Collecting(ref mut list) => Some(mem::take(list)),
1182 LastToken::Was(ref mut last) => {
1183 tokens.extend(last.take());
1187 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
1188 let prev = self.token_cursor.stack.len();
1190 let last_token = if self.token_cursor.stack.len() == prev {
1191 &mut self.token_cursor.frame.last_token
1192 } else if self.token_cursor.stack.get(prev).is_none() {
1193 // This can happen due to a bad interaction of two unrelated recovery mechanisms with
1194 // mismatched delimiters *and* recovery lookahead on the likely typo `pub ident(`
1196 return Ok((ret?, TokenStream::default()));
1198 &mut self.token_cursor.stack[prev].last_token
1201 // Pull out the tokens that we've collected from the call to `f` above.
1202 let mut collected_tokens = match *last_token {
1203 LastToken::Collecting(ref mut v) => mem::take(v),
1204 LastToken::Was(ref was) => {
1205 let msg = format!("our vector went away? - found Was({:?})", was);
1206 debug!("collect_tokens: {}", msg);
1207 self.sess.span_diagnostic.delay_span_bug(self.token.span, &msg);
1208 // This can happen due to a bad interaction of two unrelated recovery mechanisms
1209 // with mismatched delimiters *and* recovery lookahead on the likely typo
1210 // `pub ident(` (#62895, different but similar to the case above).
1211 return Ok((ret?, TokenStream::default()));
1215 // If we're not at EOF our current token wasn't actually consumed by
1216 // `f`, but it'll still be in our list that we pulled out. In that case
1218 let extra_token = if self.token != token::Eof { collected_tokens.pop() } else { None };
1220 // If we were previously collecting tokens, then this was a recursive
1221 // call. In that case we need to record all the tokens we collected in
1222 // our parent list as well. To do that we push a clone of our stream
1223 // onto the previous list.
1224 match prev_collecting {
1226 list.extend(collected_tokens.iter().cloned());
1227 list.extend(extra_token);
1228 *last_token = LastToken::Collecting(list);
1231 *last_token = LastToken::Was(extra_token);
1235 Ok((ret?, TokenStream::new(collected_tokens)))
1239 fn is_import_coupler(&mut self) -> bool {
1240 self.check(&token::ModSep)
1241 && self.look_ahead(1, |t| {
1242 *t == token::OpenDelim(token::Brace) || *t == token::BinOp(token::Star)
1247 crate fn make_unclosed_delims_error(
1248 unmatched: UnmatchedBrace,
1250 ) -> Option<DiagnosticBuilder<'_>> {
1251 // `None` here means an `Eof` was found. We already emit those errors elsewhere, we add them to
1252 // `unmatched_braces` only for error recovery in the `Parser`.
1253 let found_delim = unmatched.found_delim?;
1254 let mut err = sess.span_diagnostic.struct_span_err(
1255 unmatched.found_span,
1257 "mismatched closing delimiter: `{}`",
1258 pprust::token_kind_to_string(&token::CloseDelim(found_delim)),
1261 err.span_label(unmatched.found_span, "mismatched closing delimiter");
1262 if let Some(sp) = unmatched.candidate_span {
1263 err.span_label(sp, "closing delimiter possibly meant for this");
1265 if let Some(sp) = unmatched.unclosed_span {
1266 err.span_label(sp, "unclosed delimiter");
1271 pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, sess: &ParseSess) {
1272 *sess.reached_eof.borrow_mut() |=
1273 unclosed_delims.iter().any(|unmatched_delim| unmatched_delim.found_delim.is_none());
1274 for unmatched in unclosed_delims.drain(..) {
1275 make_unclosed_delims_error(unmatched, sess).map(|mut e| {