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