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