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