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