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