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