]> git.lizzy.rs Git - rust.git/blob - src/librustc_parse/parser/mod.rs
parser: Remove `Parser::prev_span`
[rust.git] / src / librustc_parse / parser / mod.rs
1 pub mod attr;
2 mod expr;
3 mod item;
4 mod module;
5 pub use module::{ModulePath, ModulePathSuccess};
6 mod pat;
7 mod path;
8 mod ty;
9 pub use path::PathStyle;
10 mod diagnostics;
11 mod generics;
12 mod stmt;
13 use diagnostics::Error;
14
15 use crate::lexer::UnmatchedBrace;
16 use crate::{Directory, DirectoryOwnership};
17
18 use log::debug;
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};
28 use syntax::ptr::P;
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};
32
33 use std::path::PathBuf;
34 use std::{cmp, mem, slice};
35
36 bitflags::bitflags! {
37     struct Restrictions: u8 {
38         const STMT_EXPR         = 1 << 0;
39         const NO_STRUCT_LITERAL = 1 << 1;
40     }
41 }
42
43 #[derive(Clone, Copy, PartialEq, Debug)]
44 enum SemiColonMode {
45     Break,
46     Ignore,
47     Comma,
48 }
49
50 #[derive(Clone, Copy, PartialEq, Debug)]
51 enum BlockMode {
52     Break,
53     Ignore,
54 }
55
56 /// Like `maybe_whole_expr`, but for things other than expressions.
57 #[macro_export]
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 {
62                 let $x = x.clone();
63                 $p.bump();
64                 return Ok($e);
65             }
66         }
67     };
68 }
69
70 /// If the next tokens are ill-formed `$ty::` recover them as `<$ty>::`.
71 #[macro_export]
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 {
77                     let ty = ty.clone();
78                     $self.bump();
79                     return $self.maybe_recover_from_bad_qpath_stage_2($self.prev_token.span, ty);
80                 }
81             }
82         }
83     };
84 }
85
86 #[derive(Clone)]
87 pub struct Parser<'a> {
88     pub sess: &'a ParseSess,
89     /// The current non-normalized token.
90     pub token: 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     restrictions: Restrictions,
105     /// Used to determine the path to externally loaded source files.
106     pub(super) directory: Directory,
107     /// `true` to parse sub-modules in other files.
108     // Public for rustfmt usage.
109     pub recurse_into_file_modules: bool,
110     /// Name of the root module this parser originated from. If `None`, then the
111     /// name is not known. This does not change while the parser is descending
112     /// into modules, and sub-parsers have new values for this name.
113     pub root_module_name: Option<String>,
114     expected_tokens: Vec<TokenType>,
115     token_cursor: TokenCursor,
116     desugar_doc_comments: bool,
117     /// `true` we should configure out of line modules as we parse.
118     // Public for rustfmt usage.
119     pub cfg_mods: bool,
120     /// This field is used to keep track of how many left angle brackets we have seen. This is
121     /// required in order to detect extra leading left angle brackets (`<` characters) and error
122     /// appropriately.
123     ///
124     /// See the comments in the `parse_path_segment` function for more details.
125     unmatched_angle_bracket_count: u32,
126     max_angle_bracket_count: u32,
127     /// A list of all unclosed delimiters found by the lexer. If an entry is used for error recovery
128     /// it gets removed from here. Every entry left at the end gets emitted as an independent
129     /// error.
130     pub(super) unclosed_delims: Vec<UnmatchedBrace>,
131     last_unexpected_token_span: Option<Span>,
132     pub last_type_ascription: Option<(Span, bool /* likely path typo */)>,
133     /// If present, this `Parser` is not parsing Rust code but rather a macro call.
134     subparser_name: Option<&'static str>,
135 }
136
137 impl<'a> Drop for Parser<'a> {
138     fn drop(&mut self) {
139         emit_unclosed_delims(&mut self.unclosed_delims, &self.sess);
140     }
141 }
142
143 #[derive(Clone)]
144 struct TokenCursor {
145     frame: TokenCursorFrame,
146     stack: Vec<TokenCursorFrame>,
147 }
148
149 #[derive(Clone)]
150 struct TokenCursorFrame {
151     delim: token::DelimToken,
152     span: DelimSpan,
153     open_delim: bool,
154     tree_cursor: tokenstream::Cursor,
155     close_delim: bool,
156     last_token: LastToken,
157 }
158
159 /// This is used in `TokenCursorFrame` above to track tokens that are consumed
160 /// by the parser, and then that's transitively used to record the tokens that
161 /// each parse AST item is created with.
162 ///
163 /// Right now this has two states, either collecting tokens or not collecting
164 /// tokens. If we're collecting tokens we just save everything off into a local
165 /// `Vec`. This should eventually though likely save tokens from the original
166 /// token stream and just use slicing of token streams to avoid creation of a
167 /// whole new vector.
168 ///
169 /// The second state is where we're passively not recording tokens, but the last
170 /// token is still tracked for when we want to start recording tokens. This
171 /// "last token" means that when we start recording tokens we'll want to ensure
172 /// that this, the first token, is included in the output.
173 ///
174 /// You can find some more example usage of this in the `collect_tokens` method
175 /// on the parser.
176 #[derive(Clone)]
177 enum LastToken {
178     Collecting(Vec<TreeAndJoint>),
179     Was(Option<TreeAndJoint>),
180 }
181
182 impl TokenCursorFrame {
183     fn new(span: DelimSpan, delim: DelimToken, tts: &TokenStream) -> Self {
184         TokenCursorFrame {
185             delim,
186             span,
187             open_delim: delim == token::NoDelim,
188             tree_cursor: tts.clone().into_trees(),
189             close_delim: delim == token::NoDelim,
190             last_token: LastToken::Was(None),
191         }
192     }
193 }
194
195 impl TokenCursor {
196     fn next(&mut self) -> Token {
197         loop {
198             let tree = if !self.frame.open_delim {
199                 self.frame.open_delim = true;
200                 TokenTree::open_tt(self.frame.span, self.frame.delim)
201             } else if let Some(tree) = self.frame.tree_cursor.next() {
202                 tree
203             } else if !self.frame.close_delim {
204                 self.frame.close_delim = true;
205                 TokenTree::close_tt(self.frame.span, self.frame.delim)
206             } else if let Some(frame) = self.stack.pop() {
207                 self.frame = frame;
208                 continue;
209             } else {
210                 return Token::new(token::Eof, DUMMY_SP);
211             };
212
213             match self.frame.last_token {
214                 LastToken::Collecting(ref mut v) => v.push(tree.clone().into()),
215                 LastToken::Was(ref mut t) => *t = Some(tree.clone().into()),
216             }
217
218             match tree {
219                 TokenTree::Token(token) => return token,
220                 TokenTree::Delimited(sp, delim, tts) => {
221                     let frame = TokenCursorFrame::new(sp, delim, &tts);
222                     self.stack.push(mem::replace(&mut self.frame, frame));
223                 }
224             }
225         }
226     }
227
228     fn next_desugared(&mut self) -> Token {
229         let (name, sp) = match self.next() {
230             Token { kind: token::DocComment(name), span } => (name, span),
231             tok => return tok,
232         };
233
234         let stripped = strip_doc_comment_decoration(&name.as_str());
235
236         // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
237         // required to wrap the text.
238         let mut num_of_hashes = 0;
239         let mut count = 0;
240         for ch in stripped.chars() {
241             count = match ch {
242                 '"' => 1,
243                 '#' if count > 0 => count + 1,
244                 _ => 0,
245             };
246             num_of_hashes = cmp::max(num_of_hashes, count);
247         }
248
249         let delim_span = DelimSpan::from_single(sp);
250         let body = TokenTree::Delimited(
251             delim_span,
252             token::Bracket,
253             [
254                 TokenTree::token(token::Ident(sym::doc, false), sp),
255                 TokenTree::token(token::Eq, sp),
256                 TokenTree::token(
257                     TokenKind::lit(token::StrRaw(num_of_hashes), Symbol::intern(&stripped), None),
258                     sp,
259                 ),
260             ]
261             .iter()
262             .cloned()
263             .collect::<TokenStream>(),
264         );
265
266         self.stack.push(mem::replace(
267             &mut self.frame,
268             TokenCursorFrame::new(
269                 delim_span,
270                 token::NoDelim,
271                 &if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
272                     [TokenTree::token(token::Pound, sp), TokenTree::token(token::Not, sp), body]
273                         .iter()
274                         .cloned()
275                         .collect::<TokenStream>()
276                 } else {
277                     [TokenTree::token(token::Pound, sp), body]
278                         .iter()
279                         .cloned()
280                         .collect::<TokenStream>()
281                 },
282             ),
283         ));
284
285         self.next()
286     }
287 }
288
289 #[derive(Clone, PartialEq)]
290 enum TokenType {
291     Token(TokenKind),
292     Keyword(Symbol),
293     Operator,
294     Lifetime,
295     Ident,
296     Path,
297     Type,
298     Const,
299 }
300
301 impl TokenType {
302     fn to_string(&self) -> String {
303         match *self {
304             TokenType::Token(ref t) => format!("`{}`", pprust::token_kind_to_string(t)),
305             TokenType::Keyword(kw) => format!("`{}`", kw),
306             TokenType::Operator => "an operator".to_string(),
307             TokenType::Lifetime => "lifetime".to_string(),
308             TokenType::Ident => "identifier".to_string(),
309             TokenType::Path => "path".to_string(),
310             TokenType::Type => "type".to_string(),
311             TokenType::Const => "const".to_string(),
312         }
313     }
314 }
315
316 #[derive(Copy, Clone, Debug)]
317 enum TokenExpectType {
318     Expect,
319     NoExpect,
320 }
321
322 /// A sequence separator.
323 struct SeqSep {
324     /// The separator token.
325     sep: Option<TokenKind>,
326     /// `true` if a trailing separator is allowed.
327     trailing_sep_allowed: bool,
328 }
329
330 impl SeqSep {
331     fn trailing_allowed(t: TokenKind) -> SeqSep {
332         SeqSep { sep: Some(t), trailing_sep_allowed: true }
333     }
334
335     fn none() -> SeqSep {
336         SeqSep { sep: None, trailing_sep_allowed: false }
337     }
338 }
339
340 pub enum FollowedByType {
341     Yes,
342     No,
343 }
344
345 fn token_descr_opt(token: &Token) -> Option<&'static str> {
346     Some(match token.kind {
347         _ if token.is_special_ident() => "reserved identifier",
348         _ if token.is_used_keyword() => "keyword",
349         _ if token.is_unused_keyword() => "reserved keyword",
350         token::DocComment(..) => "doc comment",
351         _ => return None,
352     })
353 }
354
355 pub(super) fn token_descr(token: &Token) -> String {
356     let token_str = pprust::token_to_string(token);
357     match token_descr_opt(token) {
358         Some(prefix) => format!("{} `{}`", prefix, token_str),
359         _ => format!("`{}`", token_str),
360     }
361 }
362
363 impl<'a> Parser<'a> {
364     pub fn new(
365         sess: &'a ParseSess,
366         tokens: TokenStream,
367         directory: Option<Directory>,
368         recurse_into_file_modules: bool,
369         desugar_doc_comments: bool,
370         subparser_name: Option<&'static str>,
371     ) -> Self {
372         let mut parser = Parser {
373             sess,
374             token: Token::dummy(),
375             normalized_token: Token::dummy(),
376             prev_token: Token::dummy(),
377             normalized_prev_token: Token::dummy(),
378             restrictions: Restrictions::empty(),
379             recurse_into_file_modules,
380             directory: Directory {
381                 path: PathBuf::new(),
382                 ownership: DirectoryOwnership::Owned { relative: None },
383             },
384             root_module_name: None,
385             expected_tokens: Vec::new(),
386             token_cursor: TokenCursor {
387                 frame: TokenCursorFrame::new(DelimSpan::dummy(), token::NoDelim, &tokens),
388                 stack: Vec::new(),
389             },
390             desugar_doc_comments,
391             cfg_mods: true,
392             unmatched_angle_bracket_count: 0,
393             max_angle_bracket_count: 0,
394             unclosed_delims: Vec::new(),
395             last_unexpected_token_span: None,
396             last_type_ascription: None,
397             subparser_name,
398         };
399
400         // Make parser point to the first token.
401         parser.bump();
402
403         if let Some(directory) = directory {
404             parser.directory = directory;
405         } else if !parser.token.span.is_dummy() {
406             if let Some(FileName::Real(path)) =
407                 &sess.source_map().lookup_char_pos(parser.token.span.lo()).file.unmapped_path
408             {
409                 if let Some(directory_path) = path.parent() {
410                     parser.directory.path = directory_path.to_path_buf();
411                 }
412             }
413         }
414
415         parser
416     }
417
418     fn next_tok(&mut self, fallback_span: Span) -> Token {
419         let mut next = if self.desugar_doc_comments {
420             self.token_cursor.next_desugared()
421         } else {
422             self.token_cursor.next()
423         };
424         if next.span.is_dummy() {
425             // Tweak the location for better diagnostics, but keep syntactic context intact.
426             next.span = fallback_span.with_ctxt(next.span.ctxt());
427         }
428         next
429     }
430
431     crate fn unexpected<T>(&mut self) -> PResult<'a, T> {
432         match self.expect_one_of(&[], &[]) {
433             Err(e) => Err(e),
434             // We can get `Ok(true)` from `recover_closing_delimiter`
435             // which is called in `expected_one_of_not_found`.
436             Ok(_) => FatalError.raise(),
437         }
438     }
439
440     /// Expects and consumes the token `t`. Signals an error if the next token is not `t`.
441     pub fn expect(&mut self, t: &TokenKind) -> PResult<'a, bool /* recovered */> {
442         if self.expected_tokens.is_empty() {
443             if self.token == *t {
444                 self.bump();
445                 Ok(false)
446             } else {
447                 self.unexpected_try_recover(t)
448             }
449         } else {
450             self.expect_one_of(slice::from_ref(t), &[])
451         }
452     }
453
454     /// Expect next token to be edible or inedible token.  If edible,
455     /// then consume it; if inedible, then return without consuming
456     /// anything.  Signal a fatal error if next token is unexpected.
457     pub fn expect_one_of(
458         &mut self,
459         edible: &[TokenKind],
460         inedible: &[TokenKind],
461     ) -> PResult<'a, bool /* recovered */> {
462         if edible.contains(&self.token.kind) {
463             self.bump();
464             Ok(false)
465         } else if inedible.contains(&self.token.kind) {
466             // leave it in the input
467             Ok(false)
468         } else if self.last_unexpected_token_span == Some(self.token.span) {
469             FatalError.raise();
470         } else {
471             self.expected_one_of_not_found(edible, inedible)
472         }
473     }
474
475     // Public for rustfmt usage.
476     pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
477         self.parse_ident_common(true)
478     }
479
480     fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, ast::Ident> {
481         match self.normalized_token.kind {
482             token::Ident(name, _) => {
483                 if self.token.is_reserved_ident() {
484                     let mut err = self.expected_ident_found();
485                     if recover {
486                         err.emit();
487                     } else {
488                         return Err(err);
489                     }
490                 }
491                 self.bump();
492                 Ok(Ident::new(name, self.normalized_prev_token.span))
493             }
494             _ => Err(match self.prev_token.kind {
495                 TokenKind::DocComment(..) => {
496                     self.span_fatal_err(self.prev_token.span, Error::UselessDocComment)
497                 }
498                 _ => self.expected_ident_found(),
499             }),
500         }
501     }
502
503     /// Checks if the next token is `tok`, and returns `true` if so.
504     ///
505     /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
506     /// encountered.
507     fn check(&mut self, tok: &TokenKind) -> bool {
508         let is_present = self.token == *tok;
509         if !is_present {
510             self.expected_tokens.push(TokenType::Token(tok.clone()));
511         }
512         is_present
513     }
514
515     /// Consumes a token 'tok' if it exists. Returns whether the given token was present.
516     pub fn eat(&mut self, tok: &TokenKind) -> bool {
517         let is_present = self.check(tok);
518         if is_present {
519             self.bump()
520         }
521         is_present
522     }
523
524     /// If the next token is the given keyword, returns `true` without eating it.
525     /// An expectation is also added for diagnostics purposes.
526     fn check_keyword(&mut self, kw: Symbol) -> bool {
527         self.expected_tokens.push(TokenType::Keyword(kw));
528         self.token.is_keyword(kw)
529     }
530
531     /// If the next token is the given keyword, eats it and returns `true`.
532     /// Otherwise, returns `false`. An expectation is also added for diagnostics purposes.
533     // Public for rustfmt usage.
534     pub fn eat_keyword(&mut self, kw: Symbol) -> bool {
535         if self.check_keyword(kw) {
536             self.bump();
537             true
538         } else {
539             false
540         }
541     }
542
543     fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool {
544         if self.token.is_keyword(kw) {
545             self.bump();
546             true
547         } else {
548             false
549         }
550     }
551
552     /// If the given word is not a keyword, signals an error.
553     /// If the next token is not the given word, signals an error.
554     /// Otherwise, eats it.
555     fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> {
556         if !self.eat_keyword(kw) { self.unexpected() } else { Ok(()) }
557     }
558
559     /// Is the given keyword `kw` followed by a non-reserved identifier?
560     fn is_kw_followed_by_ident(&self, kw: Symbol) -> bool {
561         self.token.is_keyword(kw) && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
562     }
563
564     fn check_or_expected(&mut self, ok: bool, typ: TokenType) -> bool {
565         if ok {
566             true
567         } else {
568             self.expected_tokens.push(typ);
569             false
570         }
571     }
572
573     fn check_ident(&mut self) -> bool {
574         self.check_or_expected(self.token.is_ident(), TokenType::Ident)
575     }
576
577     fn check_path(&mut self) -> bool {
578         self.check_or_expected(self.token.is_path_start(), TokenType::Path)
579     }
580
581     fn check_type(&mut self) -> bool {
582         self.check_or_expected(self.token.can_begin_type(), TokenType::Type)
583     }
584
585     fn check_const_arg(&mut self) -> bool {
586         self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const)
587     }
588
589     /// Checks to see if the next token is either `+` or `+=`.
590     /// Otherwise returns `false`.
591     fn check_plus(&mut self) -> bool {
592         self.check_or_expected(
593             self.token.is_like_plus(),
594             TokenType::Token(token::BinOp(token::Plus)),
595         )
596     }
597
598     /// Eats the expected token if it's present possibly breaking
599     /// compound tokens like multi-character operators in process.
600     /// Returns `true` if the token was eaten.
601     fn break_and_eat(&mut self, expected: TokenKind) -> bool {
602         if self.token.kind == expected {
603             self.bump();
604             return true;
605         }
606         match self.token.kind.break_two_token_op() {
607             Some((first, second)) if first == expected => {
608                 let first_span = self.sess.source_map().start_point(self.token.span);
609                 let second_span = self.token.span.with_lo(first_span.hi());
610                 self.set_token(Token::new(first, first_span));
611                 self.bump_with(Token::new(second, second_span));
612                 true
613             }
614             _ => {
615                 self.expected_tokens.push(TokenType::Token(expected));
616                 false
617             }
618         }
619     }
620
621     /// Eats `+` possibly breaking tokens like `+=` in process.
622     fn eat_plus(&mut self) -> bool {
623         self.break_and_eat(token::BinOp(token::Plus))
624     }
625
626     /// Eats `&` possibly breaking tokens like `&&` in process.
627     /// Signals an error if `&` is not eaten.
628     fn expect_and(&mut self) -> PResult<'a, ()> {
629         if self.break_and_eat(token::BinOp(token::And)) { Ok(()) } else { self.unexpected() }
630     }
631
632     /// Eats `|` possibly breaking tokens like `||` in process.
633     /// Signals an error if `|` was not eaten.
634     fn expect_or(&mut self) -> PResult<'a, ()> {
635         if self.break_and_eat(token::BinOp(token::Or)) { Ok(()) } else { self.unexpected() }
636     }
637
638     /// Eats `<` possibly breaking tokens like `<<` in process.
639     fn eat_lt(&mut self) -> bool {
640         let ate = self.break_and_eat(token::Lt);
641         if ate {
642             // See doc comment for `unmatched_angle_bracket_count`.
643             self.unmatched_angle_bracket_count += 1;
644             self.max_angle_bracket_count += 1;
645             debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count);
646         }
647         ate
648     }
649
650     /// Eats `<` possibly breaking tokens like `<<` in process.
651     /// Signals an error if `<` was not eaten.
652     fn expect_lt(&mut self) -> PResult<'a, ()> {
653         if self.eat_lt() { Ok(()) } else { self.unexpected() }
654     }
655
656     /// Eats `>` possibly breaking tokens like `>>` in process.
657     /// Signals an error if `>` was not eaten.
658     fn expect_gt(&mut self) -> PResult<'a, ()> {
659         if self.break_and_eat(token::Gt) {
660             // See doc comment for `unmatched_angle_bracket_count`.
661             if self.unmatched_angle_bracket_count > 0 {
662                 self.unmatched_angle_bracket_count -= 1;
663                 debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count);
664             }
665             Ok(())
666         } else {
667             self.unexpected()
668         }
669     }
670
671     fn expect_any_with_type(&mut self, kets: &[&TokenKind], expect: TokenExpectType) -> bool {
672         kets.iter().any(|k| match expect {
673             TokenExpectType::Expect => self.check(k),
674             TokenExpectType::NoExpect => self.token == **k,
675         })
676     }
677
678     fn parse_seq_to_before_tokens<T>(
679         &mut self,
680         kets: &[&TokenKind],
681         sep: SeqSep,
682         expect: TokenExpectType,
683         mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
684     ) -> PResult<'a, (Vec<T>, bool /* trailing */, bool /* recovered */)> {
685         let mut first = true;
686         let mut recovered = false;
687         let mut trailing = false;
688         let mut v = vec![];
689         while !self.expect_any_with_type(kets, expect) {
690             if let token::CloseDelim(..) | token::Eof = self.token.kind {
691                 break;
692             }
693             if let Some(ref t) = sep.sep {
694                 if first {
695                     first = false;
696                 } else {
697                     match self.expect(t) {
698                         Ok(false) => {}
699                         Ok(true) => {
700                             recovered = true;
701                             break;
702                         }
703                         Err(mut expect_err) => {
704                             let sp = self.prev_token.span.shrink_to_hi();
705                             let token_str = pprust::token_kind_to_string(t);
706
707                             // Attempt to keep parsing if it was a similar separator.
708                             if let Some(ref tokens) = t.similar_tokens() {
709                                 if tokens.contains(&self.token.kind) {
710                                     self.bump();
711                                 }
712                             }
713
714                             // Attempt to keep parsing if it was an omitted separator.
715                             match f(self) {
716                                 Ok(t) => {
717                                     // Parsed successfully, therefore most probably the code only
718                                     // misses a separator.
719                                     expect_err
720                                         .span_suggestion_short(
721                                             sp,
722                                             &format!("missing `{}`", token_str),
723                                             token_str,
724                                             Applicability::MaybeIncorrect,
725                                         )
726                                         .emit();
727
728                                     v.push(t);
729                                     continue;
730                                 }
731                                 Err(mut e) => {
732                                     // Parsing failed, therefore it must be something more serious
733                                     // than just a missing separator.
734                                     expect_err.emit();
735
736                                     e.cancel();
737                                     break;
738                                 }
739                             }
740                         }
741                     }
742                 }
743             }
744             if sep.trailing_sep_allowed && self.expect_any_with_type(kets, expect) {
745                 trailing = true;
746                 break;
747             }
748
749             let t = f(self)?;
750             v.push(t);
751         }
752
753         Ok((v, trailing, recovered))
754     }
755
756     /// Parses a sequence, not including the closing delimiter. The function
757     /// `f` must consume tokens until reaching the next separator or
758     /// closing bracket.
759     fn parse_seq_to_before_end<T>(
760         &mut self,
761         ket: &TokenKind,
762         sep: SeqSep,
763         f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
764     ) -> PResult<'a, (Vec<T>, bool, bool)> {
765         self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
766     }
767
768     /// Parses a sequence, including the closing delimiter. The function
769     /// `f` must consume tokens until reaching the next separator or
770     /// closing bracket.
771     fn parse_seq_to_end<T>(
772         &mut self,
773         ket: &TokenKind,
774         sep: SeqSep,
775         f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
776     ) -> PResult<'a, (Vec<T>, bool /* trailing */)> {
777         let (val, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
778         if !recovered {
779             self.eat(ket);
780         }
781         Ok((val, trailing))
782     }
783
784     /// Parses a sequence, including the closing delimiter. The function
785     /// `f` must consume tokens until reaching the next separator or
786     /// closing bracket.
787     fn parse_unspanned_seq<T>(
788         &mut self,
789         bra: &TokenKind,
790         ket: &TokenKind,
791         sep: SeqSep,
792         f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
793     ) -> PResult<'a, (Vec<T>, bool)> {
794         self.expect(bra)?;
795         self.parse_seq_to_end(ket, sep, f)
796     }
797
798     fn parse_delim_comma_seq<T>(
799         &mut self,
800         delim: DelimToken,
801         f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
802     ) -> PResult<'a, (Vec<T>, bool)> {
803         self.parse_unspanned_seq(
804             &token::OpenDelim(delim),
805             &token::CloseDelim(delim),
806             SeqSep::trailing_allowed(token::Comma),
807             f,
808         )
809     }
810
811     fn parse_paren_comma_seq<T>(
812         &mut self,
813         f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
814     ) -> PResult<'a, (Vec<T>, bool)> {
815         self.parse_delim_comma_seq(token::Paren, f)
816     }
817
818     // Interpolated identifier (`$i: ident`) and lifetime (`$l: lifetime`)
819     // tokens are replaced with usual identifier and lifetime tokens,
820     // so the former are never encountered during normal parsing.
821     crate fn set_token(&mut self, token: Token) {
822         self.token = token;
823         self.normalized_token = match &self.token.kind {
824             token::Interpolated(nt) => match **nt {
825                 token::NtIdent(ident, is_raw) => {
826                     Token::new(token::Ident(ident.name, is_raw), ident.span)
827                 }
828                 token::NtLifetime(ident) => Token::new(token::Lifetime(ident.name), ident.span),
829                 _ => self.token.clone(),
830             },
831             _ => self.token.clone(),
832         }
833     }
834
835     /// Advance the parser by one token using provided token as the next one.
836     fn bump_with(&mut self, next_token: Token) {
837         // Bumping after EOF is a bad sign, usually an infinite loop.
838         if self.prev_token.kind == TokenKind::Eof {
839             let msg = "attempted to bump the parser past EOF (may be stuck in a loop)";
840             self.span_bug(self.token.span, msg);
841         }
842
843         // Update the current and previous tokens.
844         self.prev_token = self.token.take();
845         self.normalized_prev_token = self.normalized_token.take();
846         self.set_token(next_token);
847
848         // Diagnostics.
849         self.expected_tokens.clear();
850     }
851
852     /// Advance the parser by one token.
853     pub fn bump(&mut self) {
854         let next_token = self.next_tok(self.token.span);
855         self.bump_with(next_token);
856     }
857
858     /// Look-ahead `dist` tokens of `self.token` and get access to that token there.
859     /// When `dist == 0` then the current token is looked at.
860     pub fn look_ahead<R>(&self, dist: usize, looker: impl FnOnce(&Token) -> R) -> R {
861         if dist == 0 {
862             return looker(&self.token);
863         }
864
865         let frame = &self.token_cursor.frame;
866         looker(&match frame.tree_cursor.look_ahead(dist - 1) {
867             Some(tree) => match tree {
868                 TokenTree::Token(token) => token,
869                 TokenTree::Delimited(dspan, delim, _) => {
870                     Token::new(token::OpenDelim(delim), dspan.open)
871                 }
872             },
873             None => Token::new(token::CloseDelim(frame.delim), frame.span.close),
874         })
875     }
876
877     /// Returns whether any of the given keywords are `dist` tokens ahead of the current one.
878     fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool {
879         self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw)))
880     }
881
882     /// Parses asyncness: `async` or nothing.
883     fn parse_asyncness(&mut self) -> Async {
884         if self.eat_keyword(kw::Async) {
885             let span = self.normalized_prev_token.span;
886             Async::Yes { span, closure_id: DUMMY_NODE_ID, return_impl_trait_id: DUMMY_NODE_ID }
887         } else {
888             Async::No
889         }
890     }
891
892     /// Parses unsafety: `unsafe` or nothing.
893     fn parse_unsafety(&mut self) -> Unsafe {
894         if self.eat_keyword(kw::Unsafe) {
895             Unsafe::Yes(self.normalized_prev_token.span)
896         } else {
897             Unsafe::No
898         }
899     }
900
901     /// Parses constness: `const` or nothing.
902     fn parse_constness(&mut self) -> Const {
903         if self.eat_keyword(kw::Const) {
904             Const::Yes(self.normalized_prev_token.span)
905         } else {
906             Const::No
907         }
908     }
909
910     /// Parses mutability (`mut` or nothing).
911     fn parse_mutability(&mut self) -> Mutability {
912         if self.eat_keyword(kw::Mut) { Mutability::Mut } else { Mutability::Not }
913     }
914
915     /// Possibly parses mutability (`const` or `mut`).
916     fn parse_const_or_mut(&mut self) -> Option<Mutability> {
917         if self.eat_keyword(kw::Mut) {
918             Some(Mutability::Mut)
919         } else if self.eat_keyword(kw::Const) {
920             Some(Mutability::Not)
921         } else {
922             None
923         }
924     }
925
926     fn parse_field_name(&mut self) -> PResult<'a, Ident> {
927         if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = self.token.kind
928         {
929             self.expect_no_suffix(self.token.span, "a tuple index", suffix);
930             self.bump();
931             Ok(Ident::new(symbol, self.prev_token.span))
932         } else {
933             self.parse_ident_common(false)
934         }
935     }
936
937     fn parse_mac_args(&mut self) -> PResult<'a, P<MacArgs>> {
938         self.parse_mac_args_common(true).map(P)
939     }
940
941     fn parse_attr_args(&mut self) -> PResult<'a, MacArgs> {
942         self.parse_mac_args_common(false)
943     }
944
945     fn parse_mac_args_common(&mut self, delimited_only: bool) -> PResult<'a, MacArgs> {
946         Ok(
947             if self.check(&token::OpenDelim(DelimToken::Paren))
948                 || self.check(&token::OpenDelim(DelimToken::Bracket))
949                 || self.check(&token::OpenDelim(DelimToken::Brace))
950             {
951                 match self.parse_token_tree() {
952                     TokenTree::Delimited(dspan, delim, tokens) =>
953                     // We've confirmed above that there is a delimiter so unwrapping is OK.
954                     {
955                         MacArgs::Delimited(dspan, MacDelimiter::from_token(delim).unwrap(), tokens)
956                     }
957                     _ => unreachable!(),
958                 }
959             } else if !delimited_only {
960                 if self.eat(&token::Eq) {
961                     let eq_span = self.prev_token.span;
962                     let mut is_interpolated_expr = false;
963                     if let token::Interpolated(nt) = &self.token.kind {
964                         if let token::NtExpr(..) = **nt {
965                             is_interpolated_expr = true;
966                         }
967                     }
968                     let token_tree = if is_interpolated_expr {
969                         // We need to accept arbitrary interpolated expressions to continue
970                         // supporting things like `doc = $expr` that work on stable.
971                         // Non-literal interpolated expressions are rejected after expansion.
972                         self.parse_token_tree()
973                     } else {
974                         self.parse_unsuffixed_lit()?.token_tree()
975                     };
976
977                     MacArgs::Eq(eq_span, token_tree.into())
978                 } else {
979                     MacArgs::Empty
980                 }
981             } else {
982                 return self.unexpected();
983             },
984         )
985     }
986
987     fn parse_or_use_outer_attributes(
988         &mut self,
989         already_parsed_attrs: Option<AttrVec>,
990     ) -> PResult<'a, AttrVec> {
991         if let Some(attrs) = already_parsed_attrs {
992             Ok(attrs)
993         } else {
994             self.parse_outer_attributes().map(|a| a.into())
995         }
996     }
997
998     /// Parses a single token tree from the input.
999     pub fn parse_token_tree(&mut self) -> TokenTree {
1000         match self.token.kind {
1001             token::OpenDelim(..) => {
1002                 let frame = mem::replace(
1003                     &mut self.token_cursor.frame,
1004                     self.token_cursor.stack.pop().unwrap(),
1005                 );
1006                 self.set_token(Token::new(TokenKind::CloseDelim(frame.delim), frame.span.close));
1007                 self.bump();
1008                 TokenTree::Delimited(frame.span, frame.delim, frame.tree_cursor.stream)
1009             }
1010             token::CloseDelim(_) | token::Eof => unreachable!(),
1011             _ => {
1012                 self.bump();
1013                 TokenTree::Token(self.prev_token.clone())
1014             }
1015         }
1016     }
1017
1018     /// Parses a stream of tokens into a list of `TokenTree`s, up to EOF.
1019     pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
1020         let mut tts = Vec::new();
1021         while self.token != token::Eof {
1022             tts.push(self.parse_token_tree());
1023         }
1024         Ok(tts)
1025     }
1026
1027     pub fn parse_tokens(&mut self) -> TokenStream {
1028         let mut result = Vec::new();
1029         loop {
1030             match self.token.kind {
1031                 token::Eof | token::CloseDelim(..) => break,
1032                 _ => result.push(self.parse_token_tree().into()),
1033             }
1034         }
1035         TokenStream::new(result)
1036     }
1037
1038     /// Evaluates the closure with restrictions in place.
1039     ///
1040     /// Afters the closure is evaluated, restrictions are reset.
1041     fn with_res<T>(&mut self, res: Restrictions, f: impl FnOnce(&mut Self) -> T) -> T {
1042         let old = self.restrictions;
1043         self.restrictions = res;
1044         let res = f(self);
1045         self.restrictions = old;
1046         res
1047     }
1048
1049     fn is_crate_vis(&self) -> bool {
1050         self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
1051     }
1052
1053     /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
1054     /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
1055     /// If the following element can't be a tuple (i.e., it's a function definition), then
1056     /// it's not a tuple struct field), and the contents within the parentheses isn't valid,
1057     /// so emit a proper diagnostic.
1058     pub fn parse_visibility(&mut self, fbt: FollowedByType) -> PResult<'a, Visibility> {
1059         maybe_whole!(self, NtVis, |x| x);
1060
1061         self.expected_tokens.push(TokenType::Keyword(kw::Crate));
1062         if self.is_crate_vis() {
1063             self.bump(); // `crate`
1064             self.sess.gated_spans.gate(sym::crate_visibility_modifier, self.prev_token.span);
1065             return Ok(respan(self.prev_token.span, VisibilityKind::Crate(CrateSugar::JustCrate)));
1066         }
1067
1068         if !self.eat_keyword(kw::Pub) {
1069             // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
1070             // keyword to grab a span from for inherited visibility; an empty span at the
1071             // beginning of the current token would seem to be the "Schelling span".
1072             return Ok(respan(self.token.span.shrink_to_lo(), VisibilityKind::Inherited));
1073         }
1074         let lo = self.prev_token.span;
1075
1076         if self.check(&token::OpenDelim(token::Paren)) {
1077             // We don't `self.bump()` the `(` yet because this might be a struct definition where
1078             // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
1079             // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
1080             // by the following tokens.
1081             if self.is_keyword_ahead(1, &[kw::Crate]) && self.look_ahead(2, |t| t != &token::ModSep)
1082             // account for `pub(crate::foo)`
1083             {
1084                 // Parse `pub(crate)`.
1085                 self.bump(); // `(`
1086                 self.bump(); // `crate`
1087                 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1088                 let vis = VisibilityKind::Crate(CrateSugar::PubCrate);
1089                 return Ok(respan(lo.to(self.prev_token.span), vis));
1090             } else if self.is_keyword_ahead(1, &[kw::In]) {
1091                 // Parse `pub(in path)`.
1092                 self.bump(); // `(`
1093                 self.bump(); // `in`
1094                 let path = self.parse_path(PathStyle::Mod)?; // `path`
1095                 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1096                 let vis = VisibilityKind::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
1097                 return Ok(respan(lo.to(self.prev_token.span), vis));
1098             } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren))
1099                 && self.is_keyword_ahead(1, &[kw::Super, kw::SelfLower])
1100             {
1101                 // Parse `pub(self)` or `pub(super)`.
1102                 self.bump(); // `(`
1103                 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
1104                 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1105                 let vis = VisibilityKind::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
1106                 return Ok(respan(lo.to(self.prev_token.span), vis));
1107             } else if let FollowedByType::No = fbt {
1108                 // Provide this diagnostic if a type cannot follow;
1109                 // in particular, if this is not a tuple struct.
1110                 self.recover_incorrect_vis_restriction()?;
1111                 // Emit diagnostic, but continue with public visibility.
1112             }
1113         }
1114
1115         Ok(respan(lo, VisibilityKind::Public))
1116     }
1117
1118     /// Recovery for e.g. `pub(something) fn ...` or `struct X { pub(something) y: Z }`
1119     fn recover_incorrect_vis_restriction(&mut self) -> PResult<'a, ()> {
1120         self.bump(); // `(`
1121         let path = self.parse_path(PathStyle::Mod)?;
1122         self.expect(&token::CloseDelim(token::Paren))?; // `)`
1123
1124         let msg = "incorrect visibility restriction";
1125         let suggestion = r##"some possible visibility restrictions are:
1126 `pub(crate)`: visible only on the current crate
1127 `pub(super)`: visible only in the current module's parent
1128 `pub(in path::to::module)`: visible only on the specified path"##;
1129
1130         let path_str = pprust::path_to_string(&path);
1131
1132         struct_span_err!(self.sess.span_diagnostic, path.span, E0704, "{}", msg)
1133             .help(suggestion)
1134             .span_suggestion(
1135                 path.span,
1136                 &format!("make this visible only to module `{}` with `in`", path_str),
1137                 format!("in {}", path_str),
1138                 Applicability::MachineApplicable,
1139             )
1140             .emit();
1141
1142         Ok(())
1143     }
1144
1145     /// Parses `extern string_literal?`.
1146     fn parse_extern(&mut self) -> PResult<'a, Extern> {
1147         Ok(if self.eat_keyword(kw::Extern) {
1148             Extern::from_abi(self.parse_abi())
1149         } else {
1150             Extern::None
1151         })
1152     }
1153
1154     /// Parses a string literal as an ABI spec.
1155     fn parse_abi(&mut self) -> Option<StrLit> {
1156         match self.parse_str_lit() {
1157             Ok(str_lit) => Some(str_lit),
1158             Err(Some(lit)) => match lit.kind {
1159                 ast::LitKind::Err(_) => None,
1160                 _ => {
1161                     self.struct_span_err(lit.span, "non-string ABI literal")
1162                         .span_suggestion(
1163                             lit.span,
1164                             "specify the ABI with a string literal",
1165                             "\"C\"".to_string(),
1166                             Applicability::MaybeIncorrect,
1167                         )
1168                         .emit();
1169                     None
1170                 }
1171             },
1172             Err(None) => None,
1173         }
1174     }
1175
1176     fn collect_tokens<R>(
1177         &mut self,
1178         f: impl FnOnce(&mut Self) -> PResult<'a, R>,
1179     ) -> PResult<'a, (R, TokenStream)> {
1180         // Record all tokens we parse when parsing this item.
1181         let mut tokens = Vec::new();
1182         let prev_collecting = match self.token_cursor.frame.last_token {
1183             LastToken::Collecting(ref mut list) => Some(mem::take(list)),
1184             LastToken::Was(ref mut last) => {
1185                 tokens.extend(last.take());
1186                 None
1187             }
1188         };
1189         self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
1190         let prev = self.token_cursor.stack.len();
1191         let ret = f(self);
1192         let last_token = if self.token_cursor.stack.len() == prev {
1193             &mut self.token_cursor.frame.last_token
1194         } else if self.token_cursor.stack.get(prev).is_none() {
1195             // This can happen due to a bad interaction of two unrelated recovery mechanisms with
1196             // mismatched delimiters *and* recovery lookahead on the likely typo `pub ident(`
1197             // (#62881).
1198             return Ok((ret?, TokenStream::default()));
1199         } else {
1200             &mut self.token_cursor.stack[prev].last_token
1201         };
1202
1203         // Pull out the tokens that we've collected from the call to `f` above.
1204         let mut collected_tokens = match *last_token {
1205             LastToken::Collecting(ref mut v) => mem::take(v),
1206             LastToken::Was(ref was) => {
1207                 let msg = format!("our vector went away? - found Was({:?})", was);
1208                 debug!("collect_tokens: {}", msg);
1209                 self.sess.span_diagnostic.delay_span_bug(self.token.span, &msg);
1210                 // This can happen due to a bad interaction of two unrelated recovery mechanisms
1211                 // with mismatched delimiters *and* recovery lookahead on the likely typo
1212                 // `pub ident(` (#62895, different but similar to the case above).
1213                 return Ok((ret?, TokenStream::default()));
1214             }
1215         };
1216
1217         // If we're not at EOF our current token wasn't actually consumed by
1218         // `f`, but it'll still be in our list that we pulled out. In that case
1219         // put it back.
1220         let extra_token = if self.token != token::Eof { collected_tokens.pop() } else { None };
1221
1222         // If we were previously collecting tokens, then this was a recursive
1223         // call. In that case we need to record all the tokens we collected in
1224         // our parent list as well. To do that we push a clone of our stream
1225         // onto the previous list.
1226         match prev_collecting {
1227             Some(mut list) => {
1228                 list.extend(collected_tokens.iter().cloned());
1229                 list.extend(extra_token);
1230                 *last_token = LastToken::Collecting(list);
1231             }
1232             None => {
1233                 *last_token = LastToken::Was(extra_token);
1234             }
1235         }
1236
1237         Ok((ret?, TokenStream::new(collected_tokens)))
1238     }
1239
1240     /// `::{` or `::*`
1241     fn is_import_coupler(&mut self) -> bool {
1242         self.check(&token::ModSep)
1243             && self.look_ahead(1, |t| {
1244                 *t == token::OpenDelim(token::Brace) || *t == token::BinOp(token::Star)
1245             })
1246     }
1247 }
1248
1249 crate fn make_unclosed_delims_error(
1250     unmatched: UnmatchedBrace,
1251     sess: &ParseSess,
1252 ) -> Option<DiagnosticBuilder<'_>> {
1253     // `None` here means an `Eof` was found. We already emit those errors elsewhere, we add them to
1254     // `unmatched_braces` only for error recovery in the `Parser`.
1255     let found_delim = unmatched.found_delim?;
1256     let mut err = sess.span_diagnostic.struct_span_err(
1257         unmatched.found_span,
1258         &format!(
1259             "mismatched closing delimiter: `{}`",
1260             pprust::token_kind_to_string(&token::CloseDelim(found_delim)),
1261         ),
1262     );
1263     err.span_label(unmatched.found_span, "mismatched closing delimiter");
1264     if let Some(sp) = unmatched.candidate_span {
1265         err.span_label(sp, "closing delimiter possibly meant for this");
1266     }
1267     if let Some(sp) = unmatched.unclosed_span {
1268         err.span_label(sp, "unclosed delimiter");
1269     }
1270     Some(err)
1271 }
1272
1273 pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, sess: &ParseSess) {
1274     *sess.reached_eof.borrow_mut() |=
1275         unclosed_delims.iter().any(|unmatched_delim| unmatched_delim.found_delim.is_none());
1276     for unmatched in unclosed_delims.drain(..) {
1277         make_unclosed_delims_error(unmatched, sess).map(|mut e| {
1278             e.emit();
1279         });
1280     }
1281 }