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