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