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