]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/parse/parser.rs
Rollup merge of #64895 - davidtwco:issue-64130-async-error-definition, r=nikomatsakis
[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     fn check_keyword(&mut self, kw: Symbol) -> bool {
515         self.expected_tokens.push(TokenType::Keyword(kw));
516         self.token.is_keyword(kw)
517     }
518
519     /// If the next token is the given keyword, eats it and returns
520     /// `true`. Otherwise, returns `false`.
521     pub fn eat_keyword(&mut self, kw: Symbol) -> bool {
522         if self.check_keyword(kw) {
523             self.bump();
524             true
525         } else {
526             false
527         }
528     }
529
530     fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool {
531         if self.token.is_keyword(kw) {
532             self.bump();
533             true
534         } else {
535             false
536         }
537     }
538
539     /// If the given word is not a keyword, signals an error.
540     /// If the next token is not the given word, signals an error.
541     /// Otherwise, eats it.
542     fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> {
543         if !self.eat_keyword(kw) {
544             self.unexpected()
545         } else {
546             Ok(())
547         }
548     }
549
550     crate fn check_ident(&mut self) -> bool {
551         if self.token.is_ident() {
552             true
553         } else {
554             self.expected_tokens.push(TokenType::Ident);
555             false
556         }
557     }
558
559     fn check_path(&mut self) -> bool {
560         if self.token.is_path_start() {
561             true
562         } else {
563             self.expected_tokens.push(TokenType::Path);
564             false
565         }
566     }
567
568     fn check_type(&mut self) -> bool {
569         if self.token.can_begin_type() {
570             true
571         } else {
572             self.expected_tokens.push(TokenType::Type);
573             false
574         }
575     }
576
577     fn check_const_arg(&mut self) -> bool {
578         if self.token.can_begin_const_arg() {
579             true
580         } else {
581             self.expected_tokens.push(TokenType::Const);
582             false
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     /// Checks to see if the next token is either `+` or `+=`.
608     /// Otherwise returns `false`.
609     fn check_plus(&mut self) -> bool {
610         if self.token.is_like_plus() {
611             true
612         }
613         else {
614             self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
615             false
616         }
617     }
618
619     /// Expects and consumes an `&`. If `&&` is seen, replaces it with a single
620     /// `&` and continues. If an `&` is not seen, signals an error.
621     fn expect_and(&mut self) -> PResult<'a, ()> {
622         self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
623         match self.token.kind {
624             token::BinOp(token::And) => {
625                 self.bump();
626                 Ok(())
627             }
628             token::AndAnd => {
629                 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
630                 Ok(self.bump_with(token::BinOp(token::And), span))
631             }
632             _ => self.unexpected()
633         }
634     }
635
636     /// Expects and consumes an `|`. If `||` is seen, replaces it with a single
637     /// `|` and continues. If an `|` is not seen, signals an error.
638     fn expect_or(&mut self) -> PResult<'a, ()> {
639         self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or)));
640         match self.token.kind {
641             token::BinOp(token::Or) => {
642                 self.bump();
643                 Ok(())
644             }
645             token::OrOr => {
646                 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
647                 Ok(self.bump_with(token::BinOp(token::Or), span))
648             }
649             _ => self.unexpected()
650         }
651     }
652
653     fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
654         literal::expect_no_suffix(&self.sess.span_diagnostic, sp, kind, suffix)
655     }
656
657     /// Attempts to consume a `<`. If `<<` is seen, replaces it with a single
658     /// `<` and continue. If `<-` is seen, replaces it with a single `<`
659     /// and continue. If a `<` is not seen, returns false.
660     ///
661     /// This is meant to be used when parsing generics on a path to get the
662     /// starting token.
663     fn eat_lt(&mut self) -> bool {
664         self.expected_tokens.push(TokenType::Token(token::Lt));
665         let ate = match self.token.kind {
666             token::Lt => {
667                 self.bump();
668                 true
669             }
670             token::BinOp(token::Shl) => {
671                 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
672                 self.bump_with(token::Lt, span);
673                 true
674             }
675             token::LArrow => {
676                 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
677                 self.bump_with(token::BinOp(token::Minus), span);
678                 true
679             }
680             _ => false,
681         };
682
683         if ate {
684             // See doc comment for `unmatched_angle_bracket_count`.
685             self.unmatched_angle_bracket_count += 1;
686             self.max_angle_bracket_count += 1;
687             debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count);
688         }
689
690         ate
691     }
692
693     fn expect_lt(&mut self) -> PResult<'a, ()> {
694         if !self.eat_lt() {
695             self.unexpected()
696         } else {
697             Ok(())
698         }
699     }
700
701     /// Expects and consumes a single `>` token. if a `>>` is seen, replaces it
702     /// with a single `>` and continues. If a `>` is not seen, signals an error.
703     fn expect_gt(&mut self) -> PResult<'a, ()> {
704         self.expected_tokens.push(TokenType::Token(token::Gt));
705         let ate = match self.token.kind {
706             token::Gt => {
707                 self.bump();
708                 Some(())
709             }
710             token::BinOp(token::Shr) => {
711                 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
712                 Some(self.bump_with(token::Gt, span))
713             }
714             token::BinOpEq(token::Shr) => {
715                 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
716                 Some(self.bump_with(token::Ge, span))
717             }
718             token::Ge => {
719                 let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1));
720                 Some(self.bump_with(token::Eq, span))
721             }
722             _ => None,
723         };
724
725         match ate {
726             Some(_) => {
727                 // See doc comment for `unmatched_angle_bracket_count`.
728                 if self.unmatched_angle_bracket_count > 0 {
729                     self.unmatched_angle_bracket_count -= 1;
730                     debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count);
731                 }
732
733                 Ok(())
734             },
735             None => self.unexpected(),
736         }
737     }
738
739     /// Parses a sequence, including the closing delimiter. The function
740     /// `f` must consume tokens until reaching the next separator or
741     /// closing bracket.
742     pub fn parse_seq_to_end<T>(
743         &mut self,
744         ket: &TokenKind,
745         sep: SeqSep,
746         f: impl FnMut(&mut Parser<'a>) -> PResult<'a,  T>,
747     ) -> PResult<'a, Vec<T>> {
748         let (val, _, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
749         if !recovered {
750             self.bump();
751         }
752         Ok(val)
753     }
754
755     /// Parses a sequence, not including the closing delimiter. The function
756     /// `f` must consume tokens until reaching the next separator or
757     /// closing bracket.
758     pub fn parse_seq_to_before_end<T>(
759         &mut self,
760         ket: &TokenKind,
761         sep: SeqSep,
762         f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
763     ) -> PResult<'a, (Vec<T>, bool, bool)> {
764         self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
765     }
766
767     fn expect_any_with_type(&mut self, kets: &[&TokenKind], expect: TokenExpectType) -> bool {
768         kets.iter().any(|k| {
769             match expect {
770                 TokenExpectType::Expect => self.check(k),
771                 TokenExpectType::NoExpect => self.token == **k,
772             }
773         })
774     }
775
776     crate fn parse_seq_to_before_tokens<T>(
777         &mut self,
778         kets: &[&TokenKind],
779         sep: SeqSep,
780         expect: TokenExpectType,
781         mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
782     ) -> PResult<'a, (Vec<T>, bool /* trailing */, bool /* recovered */)> {
783         let mut first = true;
784         let mut recovered = false;
785         let mut trailing = false;
786         let mut v = vec![];
787         while !self.expect_any_with_type(kets, expect) {
788             if let token::CloseDelim(..) | token::Eof = self.token.kind {
789                 break
790             }
791             if let Some(ref t) = sep.sep {
792                 if first {
793                     first = false;
794                 } else {
795                     match self.expect(t) {
796                         Ok(false) => {}
797                         Ok(true) => {
798                             recovered = true;
799                             break;
800                         }
801                         Err(mut e) => {
802                             // Attempt to keep parsing if it was a similar separator.
803                             if let Some(ref tokens) = t.similar_tokens() {
804                                 if tokens.contains(&self.token.kind) {
805                                     self.bump();
806                                 }
807                             }
808                             e.emit();
809                             // Attempt to keep parsing if it was an omitted separator.
810                             match f(self) {
811                                 Ok(t) => {
812                                     v.push(t);
813                                     continue;
814                                 },
815                                 Err(mut e) => {
816                                     e.cancel();
817                                     break;
818                                 }
819                             }
820                         }
821                     }
822                 }
823             }
824             if sep.trailing_sep_allowed && self.expect_any_with_type(kets, expect) {
825                 trailing = true;
826                 break;
827             }
828
829             let t = f(self)?;
830             v.push(t);
831         }
832
833         Ok((v, trailing, recovered))
834     }
835
836     /// Parses a sequence, including the closing delimiter. The function
837     /// `f` must consume tokens until reaching the next separator or
838     /// closing bracket.
839     fn parse_unspanned_seq<T>(
840         &mut self,
841         bra: &TokenKind,
842         ket: &TokenKind,
843         sep: SeqSep,
844         f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
845     ) -> PResult<'a, (Vec<T>, bool)> {
846         self.expect(bra)?;
847         let (result, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
848         if !recovered {
849             self.eat(ket);
850         }
851         Ok((result, trailing))
852     }
853
854     fn parse_delim_comma_seq<T>(
855         &mut self,
856         delim: DelimToken,
857         f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
858     ) -> PResult<'a, (Vec<T>, bool)> {
859         self.parse_unspanned_seq(
860             &token::OpenDelim(delim),
861             &token::CloseDelim(delim),
862             SeqSep::trailing_allowed(token::Comma),
863             f,
864         )
865     }
866
867     fn parse_paren_comma_seq<T>(
868         &mut self,
869         f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>,
870     ) -> PResult<'a, (Vec<T>, bool)> {
871         self.parse_delim_comma_seq(token::Paren, f)
872     }
873
874     /// Advance the parser by one token.
875     pub fn bump(&mut self) {
876         if self.prev_token_kind == PrevTokenKind::Eof {
877             // Bumping after EOF is a bad sign, usually an infinite loop.
878             self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
879         }
880
881         self.prev_span = self.meta_var_span.take().unwrap_or(self.token.span);
882
883         // Record last token kind for possible error recovery.
884         self.prev_token_kind = match self.token.kind {
885             token::DocComment(..) => PrevTokenKind::DocComment,
886             token::Comma => PrevTokenKind::Comma,
887             token::BinOp(token::Plus) => PrevTokenKind::Plus,
888             token::BinOp(token::Or) => PrevTokenKind::BitOr,
889             token::Interpolated(..) => PrevTokenKind::Interpolated,
890             token::Eof => PrevTokenKind::Eof,
891             token::Ident(..) => PrevTokenKind::Ident,
892             _ => PrevTokenKind::Other,
893         };
894
895         self.token = self.next_tok();
896         self.expected_tokens.clear();
897         // Check after each token.
898         self.process_potential_macro_variable();
899     }
900
901     /// Advances the parser using provided token as a next one. Use this when
902     /// consuming a part of a token. For example a single `<` from `<<`.
903     fn bump_with(&mut self, next: TokenKind, span: Span) {
904         self.prev_span = self.token.span.with_hi(span.lo());
905         // It would be incorrect to record the kind of the current token, but
906         // fortunately for tokens currently using `bump_with`, the
907         // `prev_token_kind` will be of no use anyway.
908         self.prev_token_kind = PrevTokenKind::Other;
909         self.token = Token::new(next, span);
910         self.expected_tokens.clear();
911     }
912
913     pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
914         F: FnOnce(&Token) -> R,
915     {
916         if dist == 0 {
917             return f(&self.token);
918         }
919
920         let frame = &self.token_cursor.frame;
921         f(&match frame.tree_cursor.look_ahead(dist - 1) {
922             Some(tree) => match tree {
923                 TokenTree::Token(token) => token,
924                 TokenTree::Delimited(dspan, delim, _) =>
925                     Token::new(token::OpenDelim(delim), dspan.open),
926             }
927             None => Token::new(token::CloseDelim(frame.delim), frame.span.close)
928         })
929     }
930
931     /// Returns whether any of the given keywords are `dist` tokens ahead of the current one.
932     fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool {
933         self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw)))
934     }
935
936     /// Parses asyncness: `async` or nothing.
937     fn parse_asyncness(&mut self) -> IsAsync {
938         if self.eat_keyword(kw::Async) {
939             IsAsync::Async {
940                 closure_id: DUMMY_NODE_ID,
941                 return_impl_trait_id: DUMMY_NODE_ID,
942             }
943         } else {
944             IsAsync::NotAsync
945         }
946     }
947
948     /// Parses unsafety: `unsafe` or nothing.
949     fn parse_unsafety(&mut self) -> Unsafety {
950         if self.eat_keyword(kw::Unsafe) {
951             Unsafety::Unsafe
952         } else {
953             Unsafety::Normal
954         }
955     }
956
957     fn is_named_argument(&self) -> bool {
958         let offset = match self.token.kind {
959             token::Interpolated(ref nt) => match **nt {
960                 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
961                 _ => 0,
962             }
963             token::BinOp(token::And) | token::AndAnd => 1,
964             _ if self.token.is_keyword(kw::Mut) => 1,
965             _ => 0,
966         };
967
968         self.look_ahead(offset, |t| t.is_ident()) &&
969         self.look_ahead(offset + 1, |t| t == &token::Colon)
970     }
971
972     /// Skips unexpected attributes and doc comments in this position and emits an appropriate
973     /// error.
974     /// This version of parse param doesn't necessarily require identifier names.
975     fn parse_param_general(
976         &mut self,
977         is_self_allowed: bool,
978         is_trait_item: bool,
979         allow_c_variadic: bool,
980         is_name_required: impl Fn(&token::Token) -> bool,
981     ) -> PResult<'a, Param> {
982         let lo = self.token.span;
983         let attrs = self.parse_outer_attributes()?;
984
985         // Possibly parse `self`. Recover if we parsed it and it wasn't allowed here.
986         if let Some(mut param) = self.parse_self_param()? {
987             param.attrs = attrs.into();
988             return if is_self_allowed {
989                 Ok(param)
990             } else {
991                 self.recover_bad_self_param(param, is_trait_item)
992             };
993         }
994
995         let is_name_required = is_name_required(&self.token);
996         let (pat, ty) = if is_name_required || self.is_named_argument() {
997             debug!("parse_param_general parse_pat (is_name_required:{})", is_name_required);
998
999             let pat = self.parse_fn_param_pat()?;
1000             if let Err(mut err) = self.expect(&token::Colon) {
1001                 if let Some(ident) = self.parameter_without_type(
1002                     &mut err,
1003                     pat,
1004                     is_name_required,
1005                     is_trait_item,
1006                 ) {
1007                     err.emit();
1008                     return Ok(dummy_arg(ident));
1009                 } else {
1010                     return Err(err);
1011                 }
1012             }
1013
1014             self.eat_incorrect_doc_comment_for_param_type();
1015             (pat, self.parse_ty_common(true, true, allow_c_variadic)?)
1016         } else {
1017             debug!("parse_param_general ident_to_pat");
1018             let parser_snapshot_before_ty = self.clone();
1019             self.eat_incorrect_doc_comment_for_param_type();
1020             let mut ty = self.parse_ty_common(true, true, allow_c_variadic);
1021             if ty.is_ok() && self.token != token::Comma &&
1022                self.token != token::CloseDelim(token::Paren) {
1023                 // This wasn't actually a type, but a pattern looking like a type,
1024                 // so we are going to rollback and re-parse for recovery.
1025                 ty = self.unexpected();
1026             }
1027             match ty {
1028                 Ok(ty) => {
1029                     let ident = Ident::new(kw::Invalid, self.prev_span);
1030                     let bm = BindingMode::ByValue(Mutability::Immutable);
1031                     let pat = self.mk_pat_ident(ty.span, bm, ident);
1032                     (pat, ty)
1033                 }
1034                 Err(mut err) => {
1035                     // If this is a C-variadic argument and we hit an error, return the
1036                     // error.
1037                     if self.token == token::DotDotDot {
1038                         return Err(err);
1039                     }
1040                     // Recover from attempting to parse the argument as a type without pattern.
1041                     err.cancel();
1042                     mem::replace(self, parser_snapshot_before_ty);
1043                     self.recover_arg_parse()?
1044                 }
1045             }
1046         };
1047
1048         let span = lo.to(self.token.span);
1049
1050         Ok(Param {
1051             attrs: attrs.into(),
1052             id: ast::DUMMY_NODE_ID,
1053             is_placeholder: false,
1054             pat,
1055             span,
1056             ty,
1057         })
1058     }
1059
1060     /// Parses mutability (`mut` or nothing).
1061     fn parse_mutability(&mut self) -> Mutability {
1062         if self.eat_keyword(kw::Mut) {
1063             Mutability::Mutable
1064         } else {
1065             Mutability::Immutable
1066         }
1067     }
1068
1069     fn parse_field_name(&mut self) -> PResult<'a, Ident> {
1070         if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) =
1071                 self.token.kind {
1072             self.expect_no_suffix(self.token.span, "a tuple index", suffix);
1073             self.bump();
1074             Ok(Ident::new(symbol, self.prev_span))
1075         } else {
1076             self.parse_ident_common(false)
1077         }
1078     }
1079
1080     fn expect_delimited_token_tree(&mut self) -> PResult<'a, (MacDelimiter, TokenStream)> {
1081         let delim = match self.token.kind {
1082             token::OpenDelim(delim) => delim,
1083             _ => {
1084                 let msg = "expected open delimiter";
1085                 let mut err = self.fatal(msg);
1086                 err.span_label(self.token.span, msg);
1087                 return Err(err)
1088             }
1089         };
1090         let tts = match self.parse_token_tree() {
1091             TokenTree::Delimited(_, _, tts) => tts,
1092             _ => unreachable!(),
1093         };
1094         let delim = match delim {
1095             token::Paren => MacDelimiter::Parenthesis,
1096             token::Bracket => MacDelimiter::Bracket,
1097             token::Brace => MacDelimiter::Brace,
1098             token::NoDelim => self.bug("unexpected no delimiter"),
1099         };
1100         Ok((delim, tts.into()))
1101     }
1102
1103     fn parse_or_use_outer_attributes(&mut self,
1104                                      already_parsed_attrs: Option<ThinVec<Attribute>>)
1105                                      -> PResult<'a, ThinVec<Attribute>> {
1106         if let Some(attrs) = already_parsed_attrs {
1107             Ok(attrs)
1108         } else {
1109             self.parse_outer_attributes().map(|a| a.into())
1110         }
1111     }
1112
1113     crate fn process_potential_macro_variable(&mut self) {
1114         self.token = match self.token.kind {
1115             token::Dollar if self.token.span.from_expansion() &&
1116                              self.look_ahead(1, |t| t.is_ident()) => {
1117                 self.bump();
1118                 let name = match self.token.kind {
1119                     token::Ident(name, _) => name,
1120                     _ => unreachable!()
1121                 };
1122                 let span = self.prev_span.to(self.token.span);
1123                 self.diagnostic()
1124                     .struct_span_fatal(span, &format!("unknown macro variable `{}`", name))
1125                     .span_label(span, "unknown macro variable")
1126                     .emit();
1127                 self.bump();
1128                 return
1129             }
1130             token::Interpolated(ref nt) => {
1131                 self.meta_var_span = Some(self.token.span);
1132                 // Interpolated identifier and lifetime tokens are replaced with usual identifier
1133                 // and lifetime tokens, so the former are never encountered during normal parsing.
1134                 match **nt {
1135                     token::NtIdent(ident, is_raw) =>
1136                         Token::new(token::Ident(ident.name, is_raw), ident.span),
1137                     token::NtLifetime(ident) =>
1138                         Token::new(token::Lifetime(ident.name), ident.span),
1139                     _ => return,
1140                 }
1141             }
1142             _ => return,
1143         };
1144     }
1145
1146     /// Parses a single token tree from the input.
1147     crate fn parse_token_tree(&mut self) -> TokenTree {
1148         match self.token.kind {
1149             token::OpenDelim(..) => {
1150                 let frame = mem::replace(&mut self.token_cursor.frame,
1151                                          self.token_cursor.stack.pop().unwrap());
1152                 self.token.span = frame.span.entire();
1153                 self.bump();
1154                 TokenTree::Delimited(
1155                     frame.span,
1156                     frame.delim,
1157                     frame.tree_cursor.stream.into(),
1158                 )
1159             },
1160             token::CloseDelim(_) | token::Eof => unreachable!(),
1161             _ => {
1162                 let token = self.token.take();
1163                 self.bump();
1164                 TokenTree::Token(token)
1165             }
1166         }
1167     }
1168
1169     /// Parses a stream of tokens into a list of `TokenTree`s, up to EOF.
1170     pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
1171         let mut tts = Vec::new();
1172         while self.token != token::Eof {
1173             tts.push(self.parse_token_tree());
1174         }
1175         Ok(tts)
1176     }
1177
1178     pub fn parse_tokens(&mut self) -> TokenStream {
1179         let mut result = Vec::new();
1180         loop {
1181             match self.token.kind {
1182                 token::Eof | token::CloseDelim(..) => break,
1183                 _ => result.push(self.parse_token_tree().into()),
1184             }
1185         }
1186         TokenStream::new(result)
1187     }
1188
1189     /// Evaluates the closure with restrictions in place.
1190     ///
1191     /// Afters the closure is evaluated, restrictions are reset.
1192     fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
1193         where F: FnOnce(&mut Self) -> T
1194     {
1195         let old = self.restrictions;
1196         self.restrictions = r;
1197         let r = f(self);
1198         self.restrictions = old;
1199         return r;
1200
1201     }
1202
1203     fn parse_fn_params(&mut self, named_params: bool, allow_c_variadic: bool)
1204                      -> PResult<'a, Vec<Param>> {
1205         let sp = self.token.span;
1206         let mut c_variadic = false;
1207         let (params, _): (Vec<Option<Param>>, _) = self.parse_paren_comma_seq(|p| {
1208             let do_not_enforce_named_arguments_for_c_variadic =
1209                 |token: &token::Token| -> bool {
1210                     if token == &token::DotDotDot {
1211                         false
1212                     } else {
1213                         named_params
1214                     }
1215                 };
1216             match p.parse_param_general(
1217                 false,
1218                 false,
1219                 allow_c_variadic,
1220                 do_not_enforce_named_arguments_for_c_variadic
1221             ) {
1222                 Ok(param) => {
1223                     if let TyKind::CVarArgs = param.ty.kind {
1224                         c_variadic = true;
1225                         if p.token != token::CloseDelim(token::Paren) {
1226                             let span = p.token.span;
1227                             p.span_err(span,
1228                                 "`...` must be the last argument of a C-variadic function");
1229                             // FIXME(eddyb) this should probably still push `CVarArgs`.
1230                             // Maybe AST validation/HIR lowering should emit the above error?
1231                             Ok(None)
1232                         } else {
1233                             Ok(Some(param))
1234                         }
1235                     } else {
1236                         Ok(Some(param))
1237                     }
1238                 },
1239                 Err(mut e) => {
1240                     e.emit();
1241                     let lo = p.prev_span;
1242                     // Skip every token until next possible arg or end.
1243                     p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
1244                     // Create a placeholder argument for proper arg count (issue #34264).
1245                     let span = lo.to(p.prev_span);
1246                     Ok(Some(dummy_arg(Ident::new(kw::Invalid, span))))
1247                 }
1248             }
1249         })?;
1250
1251         let params: Vec<_> = params.into_iter().filter_map(|x| x).collect();
1252
1253         if c_variadic && params.len() <= 1 {
1254             self.span_err(sp,
1255                           "C-variadic function must be declared with at least one named argument");
1256         }
1257
1258         Ok(params)
1259     }
1260
1261     /// Returns the parsed optional self parameter and whether a self shortcut was used.
1262     ///
1263     /// See `parse_self_param_with_attrs` to collect attributes.
1264     fn parse_self_param(&mut self) -> PResult<'a, Option<Param>> {
1265         let expect_ident = |this: &mut Self| match this.token.kind {
1266             // Preserve hygienic context.
1267             token::Ident(name, _) =>
1268                 { let span = this.token.span; this.bump(); Ident::new(name, span) }
1269             _ => unreachable!()
1270         };
1271         let isolated_self = |this: &mut Self, n| {
1272             this.look_ahead(n, |t| t.is_keyword(kw::SelfLower)) &&
1273             this.look_ahead(n + 1, |t| t != &token::ModSep)
1274         };
1275
1276         // Parse optional `self` parameter of a method.
1277         // Only a limited set of initial token sequences is considered `self` parameters; anything
1278         // else is parsed as a normal function parameter list, so some lookahead is required.
1279         let eself_lo = self.token.span;
1280         let (eself, eself_ident, eself_hi) = match self.token.kind {
1281             token::BinOp(token::And) => {
1282                 // `&self`
1283                 // `&mut self`
1284                 // `&'lt self`
1285                 // `&'lt mut self`
1286                 // `&not_self`
1287                 (if isolated_self(self, 1) {
1288                     self.bump();
1289                     SelfKind::Region(None, Mutability::Immutable)
1290                 } else if self.is_keyword_ahead(1, &[kw::Mut]) &&
1291                           isolated_self(self, 2) {
1292                     self.bump();
1293                     self.bump();
1294                     SelfKind::Region(None, Mutability::Mutable)
1295                 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
1296                           isolated_self(self, 2) {
1297                     self.bump();
1298                     let lt = self.expect_lifetime();
1299                     SelfKind::Region(Some(lt), Mutability::Immutable)
1300                 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
1301                           self.is_keyword_ahead(2, &[kw::Mut]) &&
1302                           isolated_self(self, 3) {
1303                     self.bump();
1304                     let lt = self.expect_lifetime();
1305                     self.bump();
1306                     SelfKind::Region(Some(lt), Mutability::Mutable)
1307                 } else {
1308                     return Ok(None);
1309                 }, expect_ident(self), self.prev_span)
1310             }
1311             token::BinOp(token::Star) => {
1312                 // `*self`
1313                 // `*const self`
1314                 // `*mut self`
1315                 // `*not_self`
1316                 // Emit special error for `self` cases.
1317                 let msg = "cannot pass `self` by raw pointer";
1318                 (if isolated_self(self, 1) {
1319                     self.bump();
1320                     self.struct_span_err(self.token.span, msg)
1321                         .span_label(self.token.span, msg)
1322                         .emit();
1323                     SelfKind::Value(Mutability::Immutable)
1324                 } else if self.look_ahead(1, |t| t.is_mutability()) &&
1325                           isolated_self(self, 2) {
1326                     self.bump();
1327                     self.bump();
1328                     self.struct_span_err(self.token.span, msg)
1329                         .span_label(self.token.span, msg)
1330                         .emit();
1331                     SelfKind::Value(Mutability::Immutable)
1332                 } else {
1333                     return Ok(None);
1334                 }, expect_ident(self), self.prev_span)
1335             }
1336             token::Ident(..) => {
1337                 if isolated_self(self, 0) {
1338                     // `self`
1339                     // `self: TYPE`
1340                     let eself_ident = expect_ident(self);
1341                     let eself_hi = self.prev_span;
1342                     (if self.eat(&token::Colon) {
1343                         let ty = self.parse_ty()?;
1344                         SelfKind::Explicit(ty, Mutability::Immutable)
1345                     } else {
1346                         SelfKind::Value(Mutability::Immutable)
1347                     }, eself_ident, eself_hi)
1348                 } else if self.token.is_keyword(kw::Mut) &&
1349                           isolated_self(self, 1) {
1350                     // `mut self`
1351                     // `mut self: TYPE`
1352                     self.bump();
1353                     let eself_ident = expect_ident(self);
1354                     let eself_hi = self.prev_span;
1355                     (if self.eat(&token::Colon) {
1356                         let ty = self.parse_ty()?;
1357                         SelfKind::Explicit(ty, Mutability::Mutable)
1358                     } else {
1359                         SelfKind::Value(Mutability::Mutable)
1360                     }, eself_ident, eself_hi)
1361                 } else {
1362                     return Ok(None);
1363                 }
1364             }
1365             _ => return Ok(None),
1366         };
1367
1368         let eself = source_map::respan(eself_lo.to(eself_hi), eself);
1369         Ok(Some(Param::from_self(ThinVec::default(), eself, eself_ident)))
1370     }
1371
1372     /// Parses the parameter list and result type of a function that may have a `self` parameter.
1373     fn parse_fn_decl_with_self(
1374         &mut self,
1375         is_name_required: impl Copy + Fn(&token::Token) -> bool,
1376     ) -> PResult<'a, P<FnDecl>> {
1377         // Parse the arguments, starting out with `self` being allowed...
1378         let mut is_self_allowed = true;
1379         let (mut inputs, _): (Vec<_>, _) = self.parse_paren_comma_seq(|p| {
1380             let res = p.parse_param_general(is_self_allowed, true, false, is_name_required);
1381             // ...but now that we've parsed the first argument, `self` is no longer allowed.
1382             is_self_allowed = false;
1383             res
1384         })?;
1385
1386         // Replace duplicated recovered params with `_` pattern to avoid unecessary errors.
1387         self.deduplicate_recovered_params_names(&mut inputs);
1388
1389         Ok(P(FnDecl {
1390             inputs,
1391             output: self.parse_ret_ty(true)?,
1392         }))
1393     }
1394
1395     fn is_crate_vis(&self) -> bool {
1396         self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
1397     }
1398
1399     /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
1400     /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
1401     /// If the following element can't be a tuple (i.e., it's a function definition), then
1402     /// it's not a tuple struct field), and the contents within the parentheses isn't valid,
1403     /// so emit a proper diagnostic.
1404     pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
1405         maybe_whole!(self, NtVis, |x| x);
1406
1407         self.expected_tokens.push(TokenType::Keyword(kw::Crate));
1408         if self.is_crate_vis() {
1409             self.bump(); // `crate`
1410             return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
1411         }
1412
1413         if !self.eat_keyword(kw::Pub) {
1414             // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
1415             // keyword to grab a span from for inherited visibility; an empty span at the
1416             // beginning of the current token would seem to be the "Schelling span".
1417             return Ok(respan(self.token.span.shrink_to_lo(), VisibilityKind::Inherited))
1418         }
1419         let lo = self.prev_span;
1420
1421         if self.check(&token::OpenDelim(token::Paren)) {
1422             // We don't `self.bump()` the `(` yet because this might be a struct definition where
1423             // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
1424             // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
1425             // by the following tokens.
1426             if self.is_keyword_ahead(1, &[kw::Crate]) &&
1427                 self.look_ahead(2, |t| t != &token::ModSep) // account for `pub(crate::foo)`
1428             {
1429                 // `pub(crate)`
1430                 self.bump(); // `(`
1431                 self.bump(); // `crate`
1432                 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1433                 let vis = respan(
1434                     lo.to(self.prev_span),
1435                     VisibilityKind::Crate(CrateSugar::PubCrate),
1436                 );
1437                 return Ok(vis)
1438             } else if self.is_keyword_ahead(1, &[kw::In]) {
1439                 // `pub(in path)`
1440                 self.bump(); // `(`
1441                 self.bump(); // `in`
1442                 let path = self.parse_path(PathStyle::Mod)?; // `path`
1443                 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1444                 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
1445                     path: P(path),
1446                     id: ast::DUMMY_NODE_ID,
1447                 });
1448                 return Ok(vis)
1449             } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
1450                       self.is_keyword_ahead(1, &[kw::Super, kw::SelfLower])
1451             {
1452                 // `pub(self)` or `pub(super)`
1453                 self.bump(); // `(`
1454                 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
1455                 self.expect(&token::CloseDelim(token::Paren))?; // `)`
1456                 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
1457                     path: P(path),
1458                     id: ast::DUMMY_NODE_ID,
1459                 });
1460                 return Ok(vis)
1461             } else if !can_take_tuple {  // Provide this diagnostic if this is not a tuple struct
1462                 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
1463                 self.bump(); // `(`
1464                 let msg = "incorrect visibility restriction";
1465                 let suggestion = r##"some possible visibility restrictions are:
1466 `pub(crate)`: visible only on the current crate
1467 `pub(super)`: visible only in the current module's parent
1468 `pub(in path::to::module)`: visible only on the specified path"##;
1469                 let path = self.parse_path(PathStyle::Mod)?;
1470                 let sp = path.span;
1471                 let help_msg = format!("make this visible only to module `{}` with `in`", path);
1472                 self.expect(&token::CloseDelim(token::Paren))?;  // `)`
1473                 struct_span_err!(self.sess.span_diagnostic, sp, E0704, "{}", msg)
1474                     .help(suggestion)
1475                     .span_suggestion(
1476                         sp,
1477                         &help_msg,
1478                         format!("in {}", path),
1479                         Applicability::MachineApplicable,
1480                     )
1481                     .emit(); // Emit diagnostic, but continue with public visibility.
1482             }
1483         }
1484
1485         Ok(respan(lo, VisibilityKind::Public))
1486     }
1487
1488     /// Parses a string as an ABI spec on an extern type or module. Consumes
1489     /// the `extern` keyword, if one is found.
1490     fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
1491         match self.token.kind {
1492             token::Literal(token::Lit { kind: token::Str, symbol, suffix }) |
1493             token::Literal(token::Lit { kind: token::StrRaw(..), symbol, suffix }) => {
1494                 let sp = self.token.span;
1495                 self.expect_no_suffix(sp, "an ABI spec", suffix);
1496                 self.bump();
1497                 match abi::lookup(&symbol.as_str()) {
1498                     Some(abi) => Ok(Some(abi)),
1499                     None => {
1500                         let prev_span = self.prev_span;
1501                         struct_span_err!(
1502                             self.sess.span_diagnostic,
1503                             prev_span,
1504                             E0703,
1505                             "invalid ABI: found `{}`",
1506                             symbol
1507                         )
1508                         .span_label(prev_span, "invalid ABI")
1509                         .help(&format!("valid ABIs: {}", abi::all_names().join(", ")))
1510                         .emit();
1511                         Ok(None)
1512                     }
1513                 }
1514             }
1515
1516             _ => Ok(None),
1517         }
1518     }
1519
1520     /// We are parsing `async fn`. If we are on Rust 2015, emit an error.
1521     fn ban_async_in_2015(&self, async_span: Span) {
1522         if async_span.rust_2015() {
1523             self.diagnostic()
1524                 .struct_span_err_with_code(
1525                     async_span,
1526                     "`async fn` is not permitted in the 2015 edition",
1527                     DiagnosticId::Error("E0670".into())
1528                 )
1529                 .emit();
1530         }
1531     }
1532
1533     fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
1534         where F: FnOnce(&mut Self) -> PResult<'a, R>
1535     {
1536         // Record all tokens we parse when parsing this item.
1537         let mut tokens = Vec::new();
1538         let prev_collecting = match self.token_cursor.frame.last_token {
1539             LastToken::Collecting(ref mut list) => {
1540                 Some(mem::take(list))
1541             }
1542             LastToken::Was(ref mut last) => {
1543                 tokens.extend(last.take());
1544                 None
1545             }
1546         };
1547         self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
1548         let prev = self.token_cursor.stack.len();
1549         let ret = f(self);
1550         let last_token = if self.token_cursor.stack.len() == prev {
1551             &mut self.token_cursor.frame.last_token
1552         } else if self.token_cursor.stack.get(prev).is_none() {
1553             // This can happen due to a bad interaction of two unrelated recovery mechanisms with
1554             // mismatched delimiters *and* recovery lookahead on the likely typo `pub ident(`
1555             // (#62881).
1556             return Ok((ret?, TokenStream::new(vec![])));
1557         } else {
1558             &mut self.token_cursor.stack[prev].last_token
1559         };
1560
1561         // Pull out the tokens that we've collected from the call to `f` above.
1562         let mut collected_tokens = match *last_token {
1563             LastToken::Collecting(ref mut v) => mem::take(v),
1564             LastToken::Was(ref was) => {
1565                 let msg = format!("our vector went away? - found Was({:?})", was);
1566                 debug!("collect_tokens: {}", msg);
1567                 self.sess.span_diagnostic.delay_span_bug(self.token.span, &msg);
1568                 // This can happen due to a bad interaction of two unrelated recovery mechanisms
1569                 // with mismatched delimiters *and* recovery lookahead on the likely typo
1570                 // `pub ident(` (#62895, different but similar to the case above).
1571                 return Ok((ret?, TokenStream::new(vec![])));
1572             }
1573         };
1574
1575         // If we're not at EOF our current token wasn't actually consumed by
1576         // `f`, but it'll still be in our list that we pulled out. In that case
1577         // put it back.
1578         let extra_token = if self.token != token::Eof {
1579             collected_tokens.pop()
1580         } else {
1581             None
1582         };
1583
1584         // If we were previously collecting tokens, then this was a recursive
1585         // call. In that case we need to record all the tokens we collected in
1586         // our parent list as well. To do that we push a clone of our stream
1587         // onto the previous list.
1588         match prev_collecting {
1589             Some(mut list) => {
1590                 list.extend(collected_tokens.iter().cloned());
1591                 list.extend(extra_token);
1592                 *last_token = LastToken::Collecting(list);
1593             }
1594             None => {
1595                 *last_token = LastToken::Was(extra_token);
1596             }
1597         }
1598
1599         Ok((ret?, TokenStream::new(collected_tokens)))
1600     }
1601
1602     /// `::{` or `::*`
1603     fn is_import_coupler(&mut self) -> bool {
1604         self.check(&token::ModSep) &&
1605             self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
1606                                    *t == token::BinOp(token::Star))
1607     }
1608
1609     pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
1610         let ret = match self.token.kind {
1611             token::Literal(token::Lit { kind: token::Str, symbol, suffix }) =>
1612                 (symbol, ast::StrStyle::Cooked, suffix),
1613             token::Literal(token::Lit { kind: token::StrRaw(n), symbol, suffix }) =>
1614                 (symbol, ast::StrStyle::Raw(n), suffix),
1615             _ => return None
1616         };
1617         self.bump();
1618         Some(ret)
1619     }
1620
1621     pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
1622         match self.parse_optional_str() {
1623             Some((s, style, suf)) => {
1624                 let sp = self.prev_span;
1625                 self.expect_no_suffix(sp, "a string literal", suf);
1626                 Ok((s, style))
1627             }
1628             _ => {
1629                 let msg = "expected string literal";
1630                 let mut err = self.fatal(msg);
1631                 err.span_label(self.token.span, msg);
1632                 Err(err)
1633             }
1634         }
1635     }
1636
1637     fn report_invalid_macro_expansion_item(&self) {
1638         self.struct_span_err(
1639             self.prev_span,
1640             "macros that expand to items must be delimited with braces or followed by a semicolon",
1641         ).multipart_suggestion(
1642             "change the delimiters to curly braces",
1643             vec![
1644                 (self.prev_span.with_hi(self.prev_span.lo() + BytePos(1)), String::from(" {")),
1645                 (self.prev_span.with_lo(self.prev_span.hi() - BytePos(1)), '}'.to_string()),
1646             ],
1647             Applicability::MaybeIncorrect,
1648         ).span_suggestion(
1649             self.sess.source_map.next_point(self.prev_span),
1650             "add a semicolon",
1651             ';'.to_string(),
1652             Applicability::MaybeIncorrect,
1653         ).emit();
1654     }
1655 }
1656
1657 pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, handler: &errors::Handler) {
1658     for unmatched in unclosed_delims.iter() {
1659         let mut err = handler.struct_span_err(unmatched.found_span, &format!(
1660             "incorrect close delimiter: `{}`",
1661             pprust::token_kind_to_string(&token::CloseDelim(unmatched.found_delim)),
1662         ));
1663         err.span_label(unmatched.found_span, "incorrect close delimiter");
1664         if let Some(sp) = unmatched.candidate_span {
1665             err.span_label(sp, "close delimiter possibly meant for this");
1666         }
1667         if let Some(sp) = unmatched.unclosed_span {
1668             err.span_label(sp, "un-closed delimiter");
1669         }
1670         err.emit();
1671     }
1672     unclosed_delims.clear();
1673 }