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