]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/parse/parser.rs
671b313c7f24ba4a101883d02ce58b56910367a4
[rust.git] / src / libsyntax / parse / parser.rs
1 // ignore-tidy-filelength
2
3 use crate::ast::{AngleBracketedArgs, AsyncArgument, ParenthesizedArgs, AttrStyle, BareFnTy};
4 use crate::ast::{GenericBound, TraitBoundModifier};
5 use crate::ast::Unsafety;
6 use crate::ast::{Mod, AnonConst, Arg, ArgSource, Arm, Guard, Attribute, BindingMode, TraitItemKind};
7 use crate::ast::Block;
8 use crate::ast::{BlockCheckMode, CaptureBy, Movability};
9 use crate::ast::{Constness, Crate};
10 use crate::ast::Defaultness;
11 use crate::ast::EnumDef;
12 use crate::ast::{Expr, ExprKind, RangeLimits};
13 use crate::ast::{Field, FnDecl, FnHeader};
14 use crate::ast::{ForeignItem, ForeignItemKind, FunctionRetTy};
15 use crate::ast::{GenericParam, GenericParamKind};
16 use crate::ast::GenericArg;
17 use crate::ast::{Ident, ImplItem, IsAsync, IsAuto, Item, ItemKind};
18 use crate::ast::{Label, Lifetime};
19 use crate::ast::{Local, LocalSource};
20 use crate::ast::MacStmtStyle;
21 use crate::ast::{Mac, Mac_, MacDelimiter};
22 use crate::ast::{MutTy, Mutability};
23 use crate::ast::{Pat, PatKind, PathSegment};
24 use crate::ast::{PolyTraitRef, QSelf};
25 use crate::ast::{Stmt, StmtKind};
26 use crate::ast::{VariantData, StructField};
27 use crate::ast::StrStyle;
28 use crate::ast::SelfKind;
29 use crate::ast::{TraitItem, TraitRef, TraitObjectSyntax};
30 use crate::ast::{Ty, TyKind, TypeBinding, GenericBounds};
31 use crate::ast::{Visibility, VisibilityKind, WhereClause, CrateSugar};
32 use crate::ast::{UseTree, UseTreeKind};
33 use crate::ast::{BinOpKind, UnOp};
34 use crate::ast::{RangeEnd, RangeSyntax};
35 use crate::{ast, attr};
36 use crate::ext::base::DummyResult;
37 use crate::source_map::{self, SourceMap, Spanned, respan};
38 use crate::parse::{SeqSep, classify, literal, token};
39 use crate::parse::lexer::{TokenAndSpan, UnmatchedBrace};
40 use crate::parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
41 use crate::parse::token::DelimToken;
42 use crate::parse::{new_sub_parser_from_file, ParseSess, Directory, DirectoryOwnership};
43 use crate::util::parser::{AssocOp, Fixity};
44 use crate::print::pprust;
45 use crate::ptr::P;
46 use crate::parse::PResult;
47 use crate::ThinVec;
48 use crate::tokenstream::{self, DelimSpan, TokenTree, TokenStream, TreeAndJoint};
49 use crate::symbol::{kw, sym, Symbol};
50 use crate::parse::diagnostics::{Error, dummy_arg};
51
52 use errors::{Applicability, DiagnosticBuilder, DiagnosticId, FatalError};
53 use rustc_target::spec::abi::{self, Abi};
54 use syntax_pos::{Span, BytePos, DUMMY_SP, FileName, hygiene::CompilerDesugaringKind};
55 use log::debug;
56
57 use std::borrow::Cow;
58 use std::cmp;
59 use std::mem;
60 use std::path::{self, Path, PathBuf};
61 use std::slice;
62
63 #[derive(Debug)]
64 /// Whether the type alias or associated type is a concrete type or an existential type
65 pub enum AliasKind {
66     /// Just a new name for the same type
67     Weak(P<Ty>),
68     /// Only trait impls of the type will be usable, not the actual type itself
69     Existential(GenericBounds),
70 }
71
72 bitflags::bitflags! {
73     struct Restrictions: u8 {
74         const STMT_EXPR         = 1 << 0;
75         const NO_STRUCT_LITERAL = 1 << 1;
76     }
77 }
78
79 type ItemInfo = (Ident, ItemKind, Option<Vec<Attribute>>);
80
81 /// Specifies how to parse a path.
82 #[derive(Copy, Clone, PartialEq)]
83 pub enum PathStyle {
84     /// In some contexts, notably in expressions, paths with generic arguments are ambiguous
85     /// with something else. For example, in expressions `segment < ....` can be interpreted
86     /// as a comparison and `segment ( ....` can be interpreted as a function call.
87     /// In all such contexts the non-path interpretation is preferred by default for practical
88     /// reasons, but the path interpretation can be forced by the disambiguator `::`, e.g.
89     /// `x<y>` - comparisons, `x::<y>` - unambiguously a path.
90     Expr,
91     /// In other contexts, notably in types, no ambiguity exists and paths can be written
92     /// without the disambiguator, e.g., `x<y>` - unambiguously a path.
93     /// Paths with disambiguators are still accepted, `x::<Y>` - unambiguously a path too.
94     Type,
95     /// A path with generic arguments disallowed, e.g., `foo::bar::Baz`, used in imports,
96     /// visibilities or attributes.
97     /// Technically, this variant is unnecessary and e.g., `Expr` can be used instead
98     /// (paths in "mod" contexts have to be checked later for absence of generic arguments
99     /// anyway, due to macros), but it is used to avoid weird suggestions about expected
100     /// tokens when something goes wrong.
101     Mod,
102 }
103
104 #[derive(Clone, Copy, PartialEq, Debug)]
105 crate enum SemiColonMode {
106     Break,
107     Ignore,
108     Comma,
109 }
110
111 #[derive(Clone, Copy, PartialEq, Debug)]
112 crate enum BlockMode {
113     Break,
114     Ignore,
115 }
116
117 /// Possibly accepts an `token::Interpolated` expression (a pre-parsed expression
118 /// dropped into the token stream, which happens while parsing the result of
119 /// macro expansion). Placement of these is not as complex as I feared it would
120 /// be. The important thing is to make sure that lookahead doesn't balk at
121 /// `token::Interpolated` tokens.
122 macro_rules! maybe_whole_expr {
123     ($p:expr) => {
124         if let token::Interpolated(nt) = &$p.token {
125             match &**nt {
126                 token::NtExpr(e) | token::NtLiteral(e) => {
127                     let e = e.clone();
128                     $p.bump();
129                     return Ok(e);
130                 }
131                 token::NtPath(path) => {
132                     let path = path.clone();
133                     $p.bump();
134                     return Ok($p.mk_expr($p.span, ExprKind::Path(None, path), ThinVec::new()));
135                 }
136                 token::NtBlock(block) => {
137                     let block = block.clone();
138                     $p.bump();
139                     return Ok($p.mk_expr($p.span, ExprKind::Block(block, None), ThinVec::new()));
140                 }
141                 _ => {},
142             };
143         }
144     }
145 }
146
147 /// As maybe_whole_expr, but for things other than expressions
148 macro_rules! maybe_whole {
149     ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
150         if let token::Interpolated(nt) = &$p.token {
151             if let token::$constructor(x) = &**nt {
152                 let $x = x.clone();
153                 $p.bump();
154                 return Ok($e);
155             }
156         }
157     };
158 }
159
160 /// If the next tokens are ill-formed `$ty::` recover them as `<$ty>::`.
161 macro_rules! maybe_recover_from_interpolated_ty_qpath {
162     ($self: expr, $allow_qpath_recovery: expr) => {
163         if $allow_qpath_recovery && $self.look_ahead(1, |t| t == &token::ModSep) {
164             if let token::Interpolated(nt) = &$self.token {
165                 if let token::NtTy(ty) = &**nt {
166                     let ty = ty.clone();
167                     $self.bump();
168                     return $self.maybe_recover_from_bad_qpath_stage_2($self.prev_span, ty);
169                 }
170             }
171         }
172     }
173 }
174
175 fn maybe_append(mut lhs: Vec<Attribute>, mut rhs: Option<Vec<Attribute>>) -> Vec<Attribute> {
176     if let Some(ref mut rhs) = rhs {
177         lhs.append(rhs);
178     }
179     lhs
180 }
181
182 #[derive(Debug, Clone, Copy, PartialEq)]
183 enum PrevTokenKind {
184     DocComment,
185     Comma,
186     Plus,
187     Interpolated,
188     Eof,
189     Ident,
190     BitOr,
191     Other,
192 }
193
194 /* ident is handled by common.rs */
195
196 #[derive(Clone)]
197 pub struct Parser<'a> {
198     pub sess: &'a ParseSess,
199     /// the current token:
200     pub token: token::Token,
201     /// the span of the current token:
202     pub span: Span,
203     /// the span of the previous token:
204     meta_var_span: Option<Span>,
205     pub prev_span: Span,
206     /// the previous token kind
207     prev_token_kind: PrevTokenKind,
208     restrictions: Restrictions,
209     /// Used to determine the path to externally loaded source files
210     crate directory: Directory<'a>,
211     /// Whether to parse sub-modules in other files.
212     pub recurse_into_file_modules: bool,
213     /// Name of the root module this parser originated from. If `None`, then the
214     /// name is not known. This does not change while the parser is descending
215     /// into modules, and sub-parsers have new values for this name.
216     pub root_module_name: Option<String>,
217     crate expected_tokens: Vec<TokenType>,
218     crate token_cursor: TokenCursor,
219     desugar_doc_comments: bool,
220     /// Whether we should configure out of line modules as we parse.
221     pub cfg_mods: bool,
222     /// This field is used to keep track of how many left angle brackets we have seen. This is
223     /// required in order to detect extra leading left angle brackets (`<` characters) and error
224     /// appropriately.
225     ///
226     /// See the comments in the `parse_path_segment` function for more details.
227     crate unmatched_angle_bracket_count: u32,
228     crate max_angle_bracket_count: u32,
229     /// List of all unclosed delimiters found by the lexer. If an entry is used for error recovery
230     /// it gets removed from here. Every entry left at the end gets emitted as an independent
231     /// error.
232     crate unclosed_delims: Vec<UnmatchedBrace>,
233     crate last_unexpected_token_span: Option<Span>,
234     /// If present, this `Parser` is not parsing Rust code but rather a macro call.
235     crate subparser_name: Option<&'static str>,
236 }
237
238 impl<'a> Drop for Parser<'a> {
239     fn drop(&mut self) {
240         let diag = self.diagnostic();
241         emit_unclosed_delims(&mut self.unclosed_delims, diag);
242     }
243 }
244
245 #[derive(Clone)]
246 crate struct TokenCursor {
247     crate frame: TokenCursorFrame,
248     crate stack: Vec<TokenCursorFrame>,
249 }
250
251 #[derive(Clone)]
252 crate struct TokenCursorFrame {
253     crate delim: token::DelimToken,
254     crate span: DelimSpan,
255     crate open_delim: bool,
256     crate tree_cursor: tokenstream::Cursor,
257     crate close_delim: bool,
258     crate last_token: LastToken,
259 }
260
261 /// This is used in `TokenCursorFrame` above to track tokens that are consumed
262 /// by the parser, and then that's transitively used to record the tokens that
263 /// each parse AST item is created with.
264 ///
265 /// Right now this has two states, either collecting tokens or not collecting
266 /// tokens. If we're collecting tokens we just save everything off into a local
267 /// `Vec`. This should eventually though likely save tokens from the original
268 /// token stream and just use slicing of token streams to avoid creation of a
269 /// whole new vector.
270 ///
271 /// The second state is where we're passively not recording tokens, but the last
272 /// token is still tracked for when we want to start recording tokens. This
273 /// "last token" means that when we start recording tokens we'll want to ensure
274 /// that this, the first token, is included in the output.
275 ///
276 /// You can find some more example usage of this in the `collect_tokens` method
277 /// on the parser.
278 #[derive(Clone)]
279 crate enum LastToken {
280     Collecting(Vec<TreeAndJoint>),
281     Was(Option<TreeAndJoint>),
282 }
283
284 impl TokenCursorFrame {
285     fn new(sp: DelimSpan, delim: DelimToken, tts: &TokenStream) -> Self {
286         TokenCursorFrame {
287             delim: delim,
288             span: sp,
289             open_delim: delim == token::NoDelim,
290             tree_cursor: tts.clone().into_trees(),
291             close_delim: delim == token::NoDelim,
292             last_token: LastToken::Was(None),
293         }
294     }
295 }
296
297 impl TokenCursor {
298     fn next(&mut self) -> TokenAndSpan {
299         loop {
300             let tree = if !self.frame.open_delim {
301                 self.frame.open_delim = true;
302                 TokenTree::open_tt(self.frame.span.open, self.frame.delim)
303             } else if let Some(tree) = self.frame.tree_cursor.next() {
304                 tree
305             } else if !self.frame.close_delim {
306                 self.frame.close_delim = true;
307                 TokenTree::close_tt(self.frame.span.close, self.frame.delim)
308             } else if let Some(frame) = self.stack.pop() {
309                 self.frame = frame;
310                 continue
311             } else {
312                 return TokenAndSpan { tok: token::Eof, sp: DUMMY_SP }
313             };
314
315             match self.frame.last_token {
316                 LastToken::Collecting(ref mut v) => v.push(tree.clone().into()),
317                 LastToken::Was(ref mut t) => *t = Some(tree.clone().into()),
318             }
319
320             match tree {
321                 TokenTree::Token(sp, tok) => return TokenAndSpan { tok: tok, sp: sp },
322                 TokenTree::Delimited(sp, delim, tts) => {
323                     let frame = TokenCursorFrame::new(sp, delim, &tts);
324                     self.stack.push(mem::replace(&mut self.frame, frame));
325                 }
326             }
327         }
328     }
329
330     fn next_desugared(&mut self) -> TokenAndSpan {
331         let (sp, name) = match self.next() {
332             TokenAndSpan { sp, tok: token::DocComment(name) } => (sp, name),
333             tok => return tok,
334         };
335
336         let stripped = strip_doc_comment_decoration(&name.as_str());
337
338         // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
339         // required to wrap the text.
340         let mut num_of_hashes = 0;
341         let mut count = 0;
342         for ch in stripped.chars() {
343             count = match ch {
344                 '"' => 1,
345                 '#' if count > 0 => count + 1,
346                 _ => 0,
347             };
348             num_of_hashes = cmp::max(num_of_hashes, count);
349         }
350
351         let delim_span = DelimSpan::from_single(sp);
352         let body = TokenTree::Delimited(
353             delim_span,
354             token::Bracket,
355             [
356                 TokenTree::Token(sp, token::Ident(ast::Ident::with_empty_ctxt(sym::doc), false)),
357                 TokenTree::Token(sp, token::Eq),
358                 TokenTree::Token(sp, token::Token::lit(
359                     token::StrRaw(num_of_hashes), Symbol::intern(&stripped), None
360                 )),
361             ]
362             .iter().cloned().collect::<TokenStream>().into(),
363         );
364
365         self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new(
366             delim_span,
367             token::NoDelim,
368             &if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
369                 [TokenTree::Token(sp, token::Pound), TokenTree::Token(sp, token::Not), body]
370                     .iter().cloned().collect::<TokenStream>().into()
371             } else {
372                 [TokenTree::Token(sp, token::Pound), body]
373                     .iter().cloned().collect::<TokenStream>().into()
374             },
375         )));
376
377         self.next()
378     }
379 }
380
381 #[derive(Clone, PartialEq)]
382 crate enum TokenType {
383     Token(token::Token),
384     Keyword(Symbol),
385     Operator,
386     Lifetime,
387     Ident,
388     Path,
389     Type,
390     Const,
391 }
392
393 impl TokenType {
394     crate fn to_string(&self) -> String {
395         match *self {
396             TokenType::Token(ref t) => format!("`{}`", pprust::token_to_string(t)),
397             TokenType::Keyword(kw) => format!("`{}`", kw),
398             TokenType::Operator => "an operator".to_string(),
399             TokenType::Lifetime => "lifetime".to_string(),
400             TokenType::Ident => "identifier".to_string(),
401             TokenType::Path => "path".to_string(),
402             TokenType::Type => "type".to_string(),
403             TokenType::Const => "const".to_string(),
404         }
405     }
406 }
407
408 /// Returns `true` if `IDENT t` can start a type -- `IDENT::a::b`, `IDENT<u8, u8>`,
409 /// `IDENT<<u8 as Trait>::AssocTy>`.
410 ///
411 /// Types can also be of the form `IDENT(u8, u8) -> u8`, however this assumes
412 /// that `IDENT` is not the ident of a fn trait.
413 fn can_continue_type_after_non_fn_ident(t: &token::Token) -> bool {
414     t == &token::ModSep || t == &token::Lt ||
415     t == &token::BinOp(token::Shl)
416 }
417
418 /// Information about the path to a module.
419 pub struct ModulePath {
420     name: String,
421     path_exists: bool,
422     pub result: Result<ModulePathSuccess, Error>,
423 }
424
425 pub struct ModulePathSuccess {
426     pub path: PathBuf,
427     pub directory_ownership: DirectoryOwnership,
428     warn: bool,
429 }
430
431 #[derive(Debug)]
432 enum LhsExpr {
433     NotYetParsed,
434     AttributesParsed(ThinVec<Attribute>),
435     AlreadyParsed(P<Expr>),
436 }
437
438 impl From<Option<ThinVec<Attribute>>> for LhsExpr {
439     fn from(o: Option<ThinVec<Attribute>>) -> Self {
440         if let Some(attrs) = o {
441             LhsExpr::AttributesParsed(attrs)
442         } else {
443             LhsExpr::NotYetParsed
444         }
445     }
446 }
447
448 impl From<P<Expr>> for LhsExpr {
449     fn from(expr: P<Expr>) -> Self {
450         LhsExpr::AlreadyParsed(expr)
451     }
452 }
453
454 #[derive(Copy, Clone, Debug)]
455 crate enum TokenExpectType {
456     Expect,
457     NoExpect,
458 }
459
460 impl<'a> Parser<'a> {
461     pub fn new(
462         sess: &'a ParseSess,
463         tokens: TokenStream,
464         directory: Option<Directory<'a>>,
465         recurse_into_file_modules: bool,
466         desugar_doc_comments: bool,
467         subparser_name: Option<&'static str>,
468     ) -> Self {
469         let mut parser = Parser {
470             sess,
471             token: token::Whitespace,
472             span: DUMMY_SP,
473             prev_span: DUMMY_SP,
474             meta_var_span: None,
475             prev_token_kind: PrevTokenKind::Other,
476             restrictions: Restrictions::empty(),
477             recurse_into_file_modules,
478             directory: Directory {
479                 path: Cow::from(PathBuf::new()),
480                 ownership: DirectoryOwnership::Owned { relative: None }
481             },
482             root_module_name: None,
483             expected_tokens: Vec::new(),
484             token_cursor: TokenCursor {
485                 frame: TokenCursorFrame::new(
486                     DelimSpan::dummy(),
487                     token::NoDelim,
488                     &tokens.into(),
489                 ),
490                 stack: Vec::new(),
491             },
492             desugar_doc_comments,
493             cfg_mods: true,
494             unmatched_angle_bracket_count: 0,
495             max_angle_bracket_count: 0,
496             unclosed_delims: Vec::new(),
497             last_unexpected_token_span: None,
498             subparser_name,
499         };
500
501         let tok = parser.next_tok();
502         parser.token = tok.tok;
503         parser.span = tok.sp;
504
505         if let Some(directory) = directory {
506             parser.directory = directory;
507         } else if !parser.span.is_dummy() {
508             if let FileName::Real(mut path) = sess.source_map().span_to_unmapped_path(parser.span) {
509                 path.pop();
510                 parser.directory.path = Cow::from(path);
511             }
512         }
513
514         parser.process_potential_macro_variable();
515         parser
516     }
517
518     fn next_tok(&mut self) -> TokenAndSpan {
519         let mut next = if self.desugar_doc_comments {
520             self.token_cursor.next_desugared()
521         } else {
522             self.token_cursor.next()
523         };
524         if next.sp.is_dummy() {
525             // Tweak the location for better diagnostics, but keep syntactic context intact.
526             next.sp = self.prev_span.with_ctxt(next.sp.ctxt());
527         }
528         next
529     }
530
531     /// Converts the current token to a string using `self`'s reader.
532     pub fn this_token_to_string(&self) -> String {
533         pprust::token_to_string(&self.token)
534     }
535
536     crate fn token_descr(&self) -> Option<&'static str> {
537         Some(match &self.token {
538             t if t.is_special_ident() => "reserved identifier",
539             t if t.is_used_keyword() => "keyword",
540             t if t.is_unused_keyword() => "reserved keyword",
541             token::DocComment(..) => "doc comment",
542             _ => return None,
543         })
544     }
545
546     crate fn this_token_descr(&self) -> String {
547         if let Some(prefix) = self.token_descr() {
548             format!("{} `{}`", prefix, self.this_token_to_string())
549         } else {
550             format!("`{}`", self.this_token_to_string())
551         }
552     }
553
554     crate fn unexpected<T>(&mut self) -> PResult<'a, T> {
555         match self.expect_one_of(&[], &[]) {
556             Err(e) => Err(e),
557             Ok(_) => unreachable!(),
558         }
559     }
560
561     /// Expects and consumes the token `t`. Signals an error if the next token is not `t`.
562     pub fn expect(&mut self, t: &token::Token) -> PResult<'a, bool /* recovered */> {
563         if self.expected_tokens.is_empty() {
564             if self.token == *t {
565                 self.bump();
566                 Ok(false)
567             } else {
568                 self.unexpected_try_recover(t)
569             }
570         } else {
571             self.expect_one_of(slice::from_ref(t), &[])
572         }
573     }
574
575     /// Expect next token to be edible or inedible token.  If edible,
576     /// then consume it; if inedible, then return without consuming
577     /// anything.  Signal a fatal error if next token is unexpected.
578     pub fn expect_one_of(
579         &mut self,
580         edible: &[token::Token],
581         inedible: &[token::Token],
582     ) -> PResult<'a, bool /* recovered */> {
583         if edible.contains(&self.token) {
584             self.bump();
585             Ok(false)
586         } else if inedible.contains(&self.token) {
587             // leave it in the input
588             Ok(false)
589         } else if self.last_unexpected_token_span == Some(self.span) {
590             FatalError.raise();
591         } else {
592             self.expected_one_of_not_found(edible, inedible)
593         }
594     }
595
596     /// Returns the span of expr, if it was not interpolated or the span of the interpolated token.
597     fn interpolated_or_expr_span(
598         &self,
599         expr: PResult<'a, P<Expr>>,
600     ) -> PResult<'a, (Span, P<Expr>)> {
601         expr.map(|e| {
602             if self.prev_token_kind == PrevTokenKind::Interpolated {
603                 (self.prev_span, e)
604             } else {
605                 (e.span, e)
606             }
607         })
608     }
609
610     pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
611         self.parse_ident_common(true)
612     }
613
614     fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, ast::Ident> {
615         match self.token {
616             token::Ident(ident, _) => {
617                 if self.token.is_reserved_ident() {
618                     let mut err = self.expected_ident_found();
619                     if recover {
620                         err.emit();
621                     } else {
622                         return Err(err);
623                     }
624                 }
625                 let span = self.span;
626                 self.bump();
627                 Ok(Ident::new(ident.name, span))
628             }
629             _ => {
630                 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
631                         self.span_fatal_err(self.prev_span, Error::UselessDocComment)
632                     } else {
633                         self.expected_ident_found()
634                     })
635             }
636         }
637     }
638
639     /// Checks if the next token is `tok`, and returns `true` if so.
640     ///
641     /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
642     /// encountered.
643     crate fn check(&mut self, tok: &token::Token) -> bool {
644         let is_present = self.token == *tok;
645         if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
646         is_present
647     }
648
649     /// Consumes a token 'tok' if it exists. Returns whether the given token was present.
650     pub fn eat(&mut self, tok: &token::Token) -> bool {
651         let is_present = self.check(tok);
652         if is_present { self.bump() }
653         is_present
654     }
655
656     fn check_keyword(&mut self, kw: Symbol) -> bool {
657         self.expected_tokens.push(TokenType::Keyword(kw));
658         self.token.is_keyword(kw)
659     }
660
661     /// If the next token is the given keyword, eats it and returns
662     /// `true`. Otherwise, returns `false`.
663     pub fn eat_keyword(&mut self, kw: Symbol) -> bool {
664         if self.check_keyword(kw) {
665             self.bump();
666             true
667         } else {
668             false
669         }
670     }
671
672     fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool {
673         if self.token.is_keyword(kw) {
674             self.bump();
675             true
676         } else {
677             false
678         }
679     }
680
681     /// If the given word is not a keyword, signals an error.
682     /// If the next token is not the given word, signals an error.
683     /// Otherwise, eats it.
684     fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> {
685         if !self.eat_keyword(kw) {
686             self.unexpected()
687         } else {
688             Ok(())
689         }
690     }
691
692     crate fn check_ident(&mut self) -> bool {
693         if self.token.is_ident() {
694             true
695         } else {
696             self.expected_tokens.push(TokenType::Ident);
697             false
698         }
699     }
700
701     fn check_path(&mut self) -> bool {
702         if self.token.is_path_start() {
703             true
704         } else {
705             self.expected_tokens.push(TokenType::Path);
706             false
707         }
708     }
709
710     fn check_type(&mut self) -> bool {
711         if self.token.can_begin_type() {
712             true
713         } else {
714             self.expected_tokens.push(TokenType::Type);
715             false
716         }
717     }
718
719     fn check_const_arg(&mut self) -> bool {
720         if self.token.can_begin_const_arg() {
721             true
722         } else {
723             self.expected_tokens.push(TokenType::Const);
724             false
725         }
726     }
727
728     /// Expects and consumes a `+`. if `+=` is seen, replaces it with a `=`
729     /// and continues. If a `+` is not seen, returns `false`.
730     ///
731     /// This is used when token-splitting `+=` into `+`.
732     /// See issue #47856 for an example of when this may occur.
733     fn eat_plus(&mut self) -> bool {
734         self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
735         match self.token {
736             token::BinOp(token::Plus) => {
737                 self.bump();
738                 true
739             }
740             token::BinOpEq(token::Plus) => {
741                 let span = self.span.with_lo(self.span.lo() + BytePos(1));
742                 self.bump_with(token::Eq, span);
743                 true
744             }
745             _ => false,
746         }
747     }
748
749
750     /// Checks to see if the next token is either `+` or `+=`.
751     /// Otherwise returns `false`.
752     fn check_plus(&mut self) -> bool {
753         if self.token.is_like_plus() {
754             true
755         }
756         else {
757             self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
758             false
759         }
760     }
761
762     /// Expects and consumes an `&`. If `&&` is seen, replaces it with a single
763     /// `&` and continues. If an `&` is not seen, signals an error.
764     fn expect_and(&mut self) -> PResult<'a, ()> {
765         self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
766         match self.token {
767             token::BinOp(token::And) => {
768                 self.bump();
769                 Ok(())
770             }
771             token::AndAnd => {
772                 let span = self.span.with_lo(self.span.lo() + BytePos(1));
773                 Ok(self.bump_with(token::BinOp(token::And), span))
774             }
775             _ => self.unexpected()
776         }
777     }
778
779     /// Expects and consumes an `|`. If `||` is seen, replaces it with a single
780     /// `|` and continues. If an `|` is not seen, signals an error.
781     fn expect_or(&mut self) -> PResult<'a, ()> {
782         self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or)));
783         match self.token {
784             token::BinOp(token::Or) => {
785                 self.bump();
786                 Ok(())
787             }
788             token::OrOr => {
789                 let span = self.span.with_lo(self.span.lo() + BytePos(1));
790                 Ok(self.bump_with(token::BinOp(token::Or), span))
791             }
792             _ => self.unexpected()
793         }
794     }
795
796     fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
797         literal::expect_no_suffix(&self.sess.span_diagnostic, sp, kind, suffix)
798     }
799
800     /// Attempts to consume a `<`. If `<<` is seen, replaces it with a single
801     /// `<` and continue. If `<-` is seen, replaces it with a single `<`
802     /// and continue. If a `<` is not seen, returns false.
803     ///
804     /// This is meant to be used when parsing generics on a path to get the
805     /// starting token.
806     fn eat_lt(&mut self) -> bool {
807         self.expected_tokens.push(TokenType::Token(token::Lt));
808         let ate = match self.token {
809             token::Lt => {
810                 self.bump();
811                 true
812             }
813             token::BinOp(token::Shl) => {
814                 let span = self.span.with_lo(self.span.lo() + BytePos(1));
815                 self.bump_with(token::Lt, span);
816                 true
817             }
818             token::LArrow => {
819                 let span = self.span.with_lo(self.span.lo() + BytePos(1));
820                 self.bump_with(token::BinOp(token::Minus), span);
821                 true
822             }
823             _ => false,
824         };
825
826         if ate {
827             // See doc comment for `unmatched_angle_bracket_count`.
828             self.unmatched_angle_bracket_count += 1;
829             self.max_angle_bracket_count += 1;
830             debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count);
831         }
832
833         ate
834     }
835
836     fn expect_lt(&mut self) -> PResult<'a, ()> {
837         if !self.eat_lt() {
838             self.unexpected()
839         } else {
840             Ok(())
841         }
842     }
843
844     /// Expects and consumes a single `>` token. if a `>>` is seen, replaces it
845     /// with a single `>` and continues. If a `>` is not seen, signals an error.
846     fn expect_gt(&mut self) -> PResult<'a, ()> {
847         self.expected_tokens.push(TokenType::Token(token::Gt));
848         let ate = match self.token {
849             token::Gt => {
850                 self.bump();
851                 Some(())
852             }
853             token::BinOp(token::Shr) => {
854                 let span = self.span.with_lo(self.span.lo() + BytePos(1));
855                 Some(self.bump_with(token::Gt, span))
856             }
857             token::BinOpEq(token::Shr) => {
858                 let span = self.span.with_lo(self.span.lo() + BytePos(1));
859                 Some(self.bump_with(token::Ge, span))
860             }
861             token::Ge => {
862                 let span = self.span.with_lo(self.span.lo() + BytePos(1));
863                 Some(self.bump_with(token::Eq, span))
864             }
865             _ => None,
866         };
867
868         match ate {
869             Some(_) => {
870                 // See doc comment for `unmatched_angle_bracket_count`.
871                 if self.unmatched_angle_bracket_count > 0 {
872                     self.unmatched_angle_bracket_count -= 1;
873                     debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count);
874                 }
875
876                 Ok(())
877             },
878             None => self.unexpected(),
879         }
880     }
881
882     /// Parses a sequence, including the closing delimiter. The function
883     /// `f` must consume tokens until reaching the next separator or
884     /// closing bracket.
885     pub fn parse_seq_to_end<T, F>(&mut self,
886                                   ket: &token::Token,
887                                   sep: SeqSep,
888                                   f: F)
889                                   -> PResult<'a, Vec<T>> where
890         F: FnMut(&mut Parser<'a>) -> PResult<'a,  T>,
891     {
892         let (val, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
893         if !recovered {
894             self.bump();
895         }
896         Ok(val)
897     }
898
899     /// Parses a sequence, not including the closing delimiter. The function
900     /// `f` must consume tokens until reaching the next separator or
901     /// closing bracket.
902     pub fn parse_seq_to_before_end<T, F>(
903         &mut self,
904         ket: &token::Token,
905         sep: SeqSep,
906         f: F,
907     ) -> PResult<'a, (Vec<T>, bool)>
908         where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
909     {
910         self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
911     }
912
913     crate fn parse_seq_to_before_tokens<T, F>(
914         &mut self,
915         kets: &[&token::Token],
916         sep: SeqSep,
917         expect: TokenExpectType,
918         mut f: F,
919     ) -> PResult<'a, (Vec<T>, bool /* recovered */)>
920         where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
921     {
922         let mut first = true;
923         let mut recovered = false;
924         let mut v = vec![];
925         while !kets.iter().any(|k| {
926                 match expect {
927                     TokenExpectType::Expect => self.check(k),
928                     TokenExpectType::NoExpect => self.token == **k,
929                 }
930             }) {
931             match self.token {
932                 token::CloseDelim(..) | token::Eof => break,
933                 _ => {}
934             };
935             if let Some(ref t) = sep.sep {
936                 if first {
937                     first = false;
938                 } else {
939                     match self.expect(t) {
940                         Ok(false) => {}
941                         Ok(true) => {
942                             recovered = true;
943                             break;
944                         }
945                         Err(mut e) => {
946                             // Attempt to keep parsing if it was a similar separator
947                             if let Some(ref tokens) = t.similar_tokens() {
948                                 if tokens.contains(&self.token) {
949                                     self.bump();
950                                 }
951                             }
952                             e.emit();
953                             // Attempt to keep parsing if it was an omitted separator
954                             match f(self) {
955                                 Ok(t) => {
956                                     v.push(t);
957                                     continue;
958                                 },
959                                 Err(mut e) => {
960                                     e.cancel();
961                                     break;
962                                 }
963                             }
964                         }
965                     }
966                 }
967             }
968             if sep.trailing_sep_allowed && kets.iter().any(|k| {
969                 match expect {
970                     TokenExpectType::Expect => self.check(k),
971                     TokenExpectType::NoExpect => self.token == **k,
972                 }
973             }) {
974                 break;
975             }
976
977             let t = f(self)?;
978             v.push(t);
979         }
980
981         Ok((v, recovered))
982     }
983
984     /// Parses a sequence, including the closing delimiter. The function
985     /// `f` must consume tokens until reaching the next separator or
986     /// closing bracket.
987     fn parse_unspanned_seq<T, F>(
988         &mut self,
989         bra: &token::Token,
990         ket: &token::Token,
991         sep: SeqSep,
992         f: F,
993     ) -> PResult<'a, Vec<T>> where
994         F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
995     {
996         self.expect(bra)?;
997         let (result, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
998         if !recovered {
999             self.eat(ket);
1000         }
1001         Ok(result)
1002     }
1003
1004     /// Advance the parser by one token
1005     pub fn bump(&mut self) {
1006         if self.prev_token_kind == PrevTokenKind::Eof {
1007             // Bumping after EOF is a bad sign, usually an infinite loop.
1008             self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
1009         }
1010
1011         self.prev_span = self.meta_var_span.take().unwrap_or(self.span);
1012
1013         // Record last token kind for possible error recovery.
1014         self.prev_token_kind = match self.token {
1015             token::DocComment(..) => PrevTokenKind::DocComment,
1016             token::Comma => PrevTokenKind::Comma,
1017             token::BinOp(token::Plus) => PrevTokenKind::Plus,
1018             token::BinOp(token::Or) => PrevTokenKind::BitOr,
1019             token::Interpolated(..) => PrevTokenKind::Interpolated,
1020             token::Eof => PrevTokenKind::Eof,
1021             token::Ident(..) => PrevTokenKind::Ident,
1022             _ => PrevTokenKind::Other,
1023         };
1024
1025         let next = self.next_tok();
1026         self.span = next.sp;
1027         self.token = next.tok;
1028         self.expected_tokens.clear();
1029         // check after each token
1030         self.process_potential_macro_variable();
1031     }
1032
1033     /// Advance the parser using provided token as a next one. Use this when
1034     /// consuming a part of a token. For example a single `<` from `<<`.
1035     fn bump_with(&mut self, next: token::Token, span: Span) {
1036         self.prev_span = self.span.with_hi(span.lo());
1037         // It would be incorrect to record the kind of the current token, but
1038         // fortunately for tokens currently using `bump_with`, the
1039         // prev_token_kind will be of no use anyway.
1040         self.prev_token_kind = PrevTokenKind::Other;
1041         self.span = span;
1042         self.token = next;
1043         self.expected_tokens.clear();
1044     }
1045
1046     pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
1047         F: FnOnce(&token::Token) -> R,
1048     {
1049         if dist == 0 {
1050             return f(&self.token)
1051         }
1052
1053         f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1054             Some(tree) => match tree {
1055                 TokenTree::Token(_, tok) => tok,
1056                 TokenTree::Delimited(_, delim, _) => token::OpenDelim(delim),
1057             },
1058             None => token::CloseDelim(self.token_cursor.frame.delim),
1059         })
1060     }
1061
1062     crate fn look_ahead_span(&self, dist: usize) -> Span {
1063         if dist == 0 {
1064             return self.span
1065         }
1066
1067         match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1068             Some(TokenTree::Token(span, _)) => span,
1069             Some(TokenTree::Delimited(span, ..)) => span.entire(),
1070             None => self.look_ahead_span(dist - 1),
1071         }
1072     }
1073
1074     /// Returns whether any of the given keywords are `dist` tokens ahead of the current one.
1075     fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool {
1076         self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw)))
1077     }
1078
1079     /// Is the current token one of the keywords that signals a bare function type?
1080     fn token_is_bare_fn_keyword(&mut self) -> bool {
1081         self.check_keyword(kw::Fn) ||
1082             self.check_keyword(kw::Unsafe) ||
1083             self.check_keyword(kw::Extern)
1084     }
1085
1086     /// Parses a `TyKind::BareFn` type.
1087     fn parse_ty_bare_fn(&mut self, generic_params: Vec<GenericParam>) -> PResult<'a, TyKind> {
1088         /*
1089
1090         [unsafe] [extern "ABI"] fn (S) -> T
1091          ^~~~^           ^~~~^     ^~^    ^
1092            |               |        |     |
1093            |               |        |   Return type
1094            |               |      Argument types
1095            |               |
1096            |              ABI
1097         Function Style
1098         */
1099
1100         let unsafety = self.parse_unsafety();
1101         let abi = if self.eat_keyword(kw::Extern) {
1102             self.parse_opt_abi()?.unwrap_or(Abi::C)
1103         } else {
1104             Abi::Rust
1105         };
1106
1107         self.expect_keyword(kw::Fn)?;
1108         let (inputs, c_variadic) = self.parse_fn_args(false, true)?;
1109         let ret_ty = self.parse_ret_ty(false)?;
1110         let decl = P(FnDecl {
1111             inputs,
1112             output: ret_ty,
1113             c_variadic,
1114         });
1115         Ok(TyKind::BareFn(P(BareFnTy {
1116             abi,
1117             unsafety,
1118             generic_params,
1119             decl,
1120         })))
1121     }
1122
1123     /// Parses asyncness: `async` or nothing.
1124     fn parse_asyncness(&mut self) -> IsAsync {
1125         if self.eat_keyword(kw::Async) {
1126             IsAsync::Async {
1127                 closure_id: ast::DUMMY_NODE_ID,
1128                 return_impl_trait_id: ast::DUMMY_NODE_ID,
1129                 arguments: Vec::new(),
1130             }
1131         } else {
1132             IsAsync::NotAsync
1133         }
1134     }
1135
1136     /// Parses unsafety: `unsafe` or nothing.
1137     fn parse_unsafety(&mut self) -> Unsafety {
1138         if self.eat_keyword(kw::Unsafe) {
1139             Unsafety::Unsafe
1140         } else {
1141             Unsafety::Normal
1142         }
1143     }
1144
1145     /// Parses the items in a trait declaration.
1146     pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1147         maybe_whole!(self, NtTraitItem, |x| x);
1148         let attrs = self.parse_outer_attributes()?;
1149         let mut unclosed_delims = vec![];
1150         let (mut item, tokens) = self.collect_tokens(|this| {
1151             let item = this.parse_trait_item_(at_end, attrs);
1152             unclosed_delims.append(&mut this.unclosed_delims);
1153             item
1154         })?;
1155         self.unclosed_delims.append(&mut unclosed_delims);
1156         // See `parse_item` for why this clause is here.
1157         if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
1158             item.tokens = Some(tokens);
1159         }
1160         Ok(item)
1161     }
1162
1163     fn parse_trait_item_(&mut self,
1164                          at_end: &mut bool,
1165                          mut attrs: Vec<Attribute>) -> PResult<'a, TraitItem> {
1166         let lo = self.span;
1167         self.eat_bad_pub();
1168         let (name, node, generics) = if self.eat_keyword(kw::Type) {
1169             self.parse_trait_item_assoc_ty()?
1170         } else if self.is_const_item() {
1171             self.expect_keyword(kw::Const)?;
1172             let ident = self.parse_ident()?;
1173             self.expect(&token::Colon)?;
1174             let ty = self.parse_ty()?;
1175             let default = if self.eat(&token::Eq) {
1176                 let expr = self.parse_expr()?;
1177                 self.expect(&token::Semi)?;
1178                 Some(expr)
1179             } else {
1180                 self.expect(&token::Semi)?;
1181                 None
1182             };
1183             (ident, TraitItemKind::Const(ty, default), ast::Generics::default())
1184         } else if let Some(mac) = self.parse_assoc_macro_invoc("trait", None, &mut false)? {
1185             // trait item macro.
1186             (Ident::invalid(), ast::TraitItemKind::Macro(mac), ast::Generics::default())
1187         } else {
1188             let (constness, unsafety, mut asyncness, abi) = self.parse_fn_front_matter()?;
1189
1190             let ident = self.parse_ident()?;
1191             let mut generics = self.parse_generics()?;
1192
1193             let mut decl = self.parse_fn_decl_with_self(|p: &mut Parser<'a>| {
1194                 // This is somewhat dubious; We don't want to allow
1195                 // argument names to be left off if there is a
1196                 // definition...
1197
1198                 // We don't allow argument names to be left off in edition 2018.
1199                 p.parse_arg_general(p.span.rust_2018(), true, false)
1200             })?;
1201             generics.where_clause = self.parse_where_clause()?;
1202             self.construct_async_arguments(&mut asyncness, &mut decl);
1203
1204             let sig = ast::MethodSig {
1205                 header: FnHeader {
1206                     unsafety,
1207                     constness,
1208                     abi,
1209                     asyncness,
1210                 },
1211                 decl,
1212             };
1213
1214             let body = match self.token {
1215                 token::Semi => {
1216                     self.bump();
1217                     *at_end = true;
1218                     debug!("parse_trait_methods(): parsing required method");
1219                     None
1220                 }
1221                 token::OpenDelim(token::Brace) => {
1222                     debug!("parse_trait_methods(): parsing provided method");
1223                     *at_end = true;
1224                     let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1225                     attrs.extend(inner_attrs.iter().cloned());
1226                     Some(body)
1227                 }
1228                 token::Interpolated(ref nt) => {
1229                     match **nt {
1230                         token::NtBlock(..) => {
1231                             *at_end = true;
1232                             let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1233                             attrs.extend(inner_attrs.iter().cloned());
1234                             Some(body)
1235                         }
1236                         _ => {
1237                             return self.expected_semi_or_open_brace();
1238                         }
1239                     }
1240                 }
1241                 _ => {
1242                     return self.expected_semi_or_open_brace();
1243                 }
1244             };
1245             (ident, ast::TraitItemKind::Method(sig, body), generics)
1246         };
1247
1248         Ok(TraitItem {
1249             id: ast::DUMMY_NODE_ID,
1250             ident: name,
1251             attrs,
1252             generics,
1253             node,
1254             span: lo.to(self.prev_span),
1255             tokens: None,
1256         })
1257     }
1258
1259     /// Parses an optional return type `[ -> TY ]` in a function declaration.
1260     fn parse_ret_ty(&mut self, allow_plus: bool) -> PResult<'a, FunctionRetTy> {
1261         if self.eat(&token::RArrow) {
1262             Ok(FunctionRetTy::Ty(self.parse_ty_common(allow_plus, true, false)?))
1263         } else {
1264             Ok(FunctionRetTy::Default(self.span.shrink_to_lo()))
1265         }
1266     }
1267
1268     /// Parses a type.
1269     pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1270         self.parse_ty_common(true, true, false)
1271     }
1272
1273     /// Parses a type in restricted contexts where `+` is not permitted.
1274     ///
1275     /// Example 1: `&'a TYPE`
1276     ///     `+` is prohibited to maintain operator priority (P(+) < P(&)).
1277     /// Example 2: `value1 as TYPE + value2`
1278     ///     `+` is prohibited to avoid interactions with expression grammar.
1279     fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1280         self.parse_ty_common(false, true, false)
1281     }
1282
1283     fn parse_ty_common(&mut self, allow_plus: bool, allow_qpath_recovery: bool,
1284                        allow_c_variadic: bool) -> PResult<'a, P<Ty>> {
1285         maybe_recover_from_interpolated_ty_qpath!(self, allow_qpath_recovery);
1286         maybe_whole!(self, NtTy, |x| x);
1287
1288         let lo = self.span;
1289         let mut impl_dyn_multi = false;
1290         let node = if self.eat(&token::OpenDelim(token::Paren)) {
1291             // `(TYPE)` is a parenthesized type.
1292             // `(TYPE,)` is a tuple with a single field of type TYPE.
1293             let mut ts = vec![];
1294             let mut last_comma = false;
1295             while self.token != token::CloseDelim(token::Paren) {
1296                 ts.push(self.parse_ty()?);
1297                 if self.eat(&token::Comma) {
1298                     last_comma = true;
1299                 } else {
1300                     last_comma = false;
1301                     break;
1302                 }
1303             }
1304             let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1305             self.expect(&token::CloseDelim(token::Paren))?;
1306
1307             if ts.len() == 1 && !last_comma {
1308                 let ty = ts.into_iter().nth(0).unwrap().into_inner();
1309                 let maybe_bounds = allow_plus && self.token.is_like_plus();
1310                 match ty.node {
1311                     // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1312                     TyKind::Path(None, ref path) if maybe_bounds => {
1313                         self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1314                     }
1315                     TyKind::TraitObject(ref bounds, TraitObjectSyntax::None)
1316                             if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1317                         let path = match bounds[0] {
1318                             GenericBound::Trait(ref pt, ..) => pt.trait_ref.path.clone(),
1319                             GenericBound::Outlives(..) => self.bug("unexpected lifetime bound"),
1320                         };
1321                         self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1322                     }
1323                     // `(TYPE)`
1324                     _ => TyKind::Paren(P(ty))
1325                 }
1326             } else {
1327                 TyKind::Tup(ts)
1328             }
1329         } else if self.eat(&token::Not) {
1330             // Never type `!`
1331             TyKind::Never
1332         } else if self.eat(&token::BinOp(token::Star)) {
1333             // Raw pointer
1334             TyKind::Ptr(self.parse_ptr()?)
1335         } else if self.eat(&token::OpenDelim(token::Bracket)) {
1336             // Array or slice
1337             let t = self.parse_ty()?;
1338             // Parse optional `; EXPR` in `[TYPE; EXPR]`
1339             let t = match self.maybe_parse_fixed_length_of_vec()? {
1340                 None => TyKind::Slice(t),
1341                 Some(length) => TyKind::Array(t, AnonConst {
1342                     id: ast::DUMMY_NODE_ID,
1343                     value: length,
1344                 }),
1345             };
1346             self.expect(&token::CloseDelim(token::Bracket))?;
1347             t
1348         } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1349             // Reference
1350             self.expect_and()?;
1351             self.parse_borrowed_pointee()?
1352         } else if self.eat_keyword_noexpect(kw::Typeof) {
1353             // `typeof(EXPR)`
1354             // In order to not be ambiguous, the type must be surrounded by parens.
1355             self.expect(&token::OpenDelim(token::Paren))?;
1356             let e = AnonConst {
1357                 id: ast::DUMMY_NODE_ID,
1358                 value: self.parse_expr()?,
1359             };
1360             self.expect(&token::CloseDelim(token::Paren))?;
1361             TyKind::Typeof(e)
1362         } else if self.eat_keyword(kw::Underscore) {
1363             // A type to be inferred `_`
1364             TyKind::Infer
1365         } else if self.token_is_bare_fn_keyword() {
1366             // Function pointer type
1367             self.parse_ty_bare_fn(Vec::new())?
1368         } else if self.check_keyword(kw::For) {
1369             // Function pointer type or bound list (trait object type) starting with a poly-trait.
1370             //   `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1371             //   `for<'lt> Trait1<'lt> + Trait2 + 'a`
1372             let lo = self.span;
1373             let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1374             if self.token_is_bare_fn_keyword() {
1375                 self.parse_ty_bare_fn(lifetime_defs)?
1376             } else {
1377                 let path = self.parse_path(PathStyle::Type)?;
1378                 let parse_plus = allow_plus && self.check_plus();
1379                 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1380             }
1381         } else if self.eat_keyword(kw::Impl) {
1382             // Always parse bounds greedily for better error recovery.
1383             let bounds = self.parse_generic_bounds(None)?;
1384             impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1385             TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds)
1386         } else if self.check_keyword(kw::Dyn) &&
1387                   (self.span.rust_2018() ||
1388                    self.look_ahead(1, |t| t.can_begin_bound() &&
1389                                           !can_continue_type_after_non_fn_ident(t))) {
1390             self.bump(); // `dyn`
1391             // Always parse bounds greedily for better error recovery.
1392             let bounds = self.parse_generic_bounds(None)?;
1393             impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1394             TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn)
1395         } else if self.check(&token::Question) ||
1396                   self.check_lifetime() && self.look_ahead(1, |t| t.is_like_plus()) {
1397             // Bound list (trait object type)
1398             TyKind::TraitObject(self.parse_generic_bounds_common(allow_plus, None)?,
1399                                 TraitObjectSyntax::None)
1400         } else if self.eat_lt() {
1401             // Qualified path
1402             let (qself, path) = self.parse_qpath(PathStyle::Type)?;
1403             TyKind::Path(Some(qself), path)
1404         } else if self.token.is_path_start() {
1405             // Simple path
1406             let path = self.parse_path(PathStyle::Type)?;
1407             if self.eat(&token::Not) {
1408                 // Macro invocation in type position
1409                 let (delim, tts) = self.expect_delimited_token_tree()?;
1410                 let node = Mac_ { path, tts, delim };
1411                 TyKind::Mac(respan(lo.to(self.prev_span), node))
1412             } else {
1413                 // Just a type path or bound list (trait object type) starting with a trait.
1414                 //   `Type`
1415                 //   `Trait1 + Trait2 + 'a`
1416                 if allow_plus && self.check_plus() {
1417                     self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1418                 } else {
1419                     TyKind::Path(None, path)
1420                 }
1421             }
1422         } else if self.check(&token::DotDotDot) {
1423             if allow_c_variadic {
1424                 self.eat(&token::DotDotDot);
1425                 TyKind::CVarArgs
1426             } else {
1427                 return Err(self.fatal(
1428                     "only foreign functions are allowed to be C-variadic"
1429                 ));
1430             }
1431         } else {
1432             let msg = format!("expected type, found {}", self.this_token_descr());
1433             return Err(self.fatal(&msg));
1434         };
1435
1436         let span = lo.to(self.prev_span);
1437         let ty = P(Ty { node, span, id: ast::DUMMY_NODE_ID });
1438
1439         // Try to recover from use of `+` with incorrect priority.
1440         self.maybe_report_ambiguous_plus(allow_plus, impl_dyn_multi, &ty);
1441         self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1442         self.maybe_recover_from_bad_qpath(ty, allow_qpath_recovery)
1443     }
1444
1445     fn parse_remaining_bounds(&mut self, generic_params: Vec<GenericParam>, path: ast::Path,
1446                               lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1447         let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span));
1448         let mut bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)];
1449         if parse_plus {
1450             self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded
1451             bounds.append(&mut self.parse_generic_bounds(Some(self.prev_span))?);
1452         }
1453         Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
1454     }
1455
1456     fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1457         let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1458         let mutbl = self.parse_mutability();
1459         let ty = self.parse_ty_no_plus()?;
1460         return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1461     }
1462
1463     fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1464         let mutbl = if self.eat_keyword(kw::Mut) {
1465             Mutability::Mutable
1466         } else if self.eat_keyword(kw::Const) {
1467             Mutability::Immutable
1468         } else {
1469             let span = self.prev_span;
1470             let msg = "expected mut or const in raw pointer type";
1471             self.struct_span_err(span, msg)
1472                 .span_label(span, msg)
1473                 .help("use `*mut T` or `*const T` as appropriate")
1474                 .emit();
1475             Mutability::Immutable
1476         };
1477         let t = self.parse_ty_no_plus()?;
1478         Ok(MutTy { ty: t, mutbl: mutbl })
1479     }
1480
1481     fn is_named_argument(&self) -> bool {
1482         let offset = match self.token {
1483             token::Interpolated(ref nt) => match **nt {
1484                 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1485                 _ => 0,
1486             }
1487             token::BinOp(token::And) | token::AndAnd => 1,
1488             _ if self.token.is_keyword(kw::Mut) => 1,
1489             _ => 0,
1490         };
1491
1492         self.look_ahead(offset, |t| t.is_ident()) &&
1493         self.look_ahead(offset + 1, |t| t == &token::Colon)
1494     }
1495
1496     /// Skips unexpected attributes and doc comments in this position and emits an appropriate
1497     /// error.
1498     /// This version of parse arg doesn't necessarily require identifier names.
1499     fn parse_arg_general(
1500         &mut self,
1501         require_name: bool,
1502         is_trait_item: bool,
1503         allow_c_variadic: bool,
1504     ) -> PResult<'a, Arg> {
1505         if let Ok(Some(arg)) = self.parse_self_arg() {
1506             return self.recover_bad_self_arg(arg, is_trait_item);
1507         }
1508
1509         let (pat, ty) = if require_name || self.is_named_argument() {
1510             debug!("parse_arg_general parse_pat (require_name:{})", require_name);
1511             self.eat_incorrect_doc_comment("method arguments");
1512             let pat = self.parse_pat(Some("argument name"))?;
1513
1514             if let Err(mut err) = self.expect(&token::Colon) {
1515                 if let Some(ident) = self.argument_without_type(
1516                     &mut err,
1517                     pat,
1518                     require_name,
1519                     is_trait_item,
1520                 ) {
1521                     err.emit();
1522                     return Ok(dummy_arg(ident));
1523                 } else {
1524                     return Err(err);
1525                 }
1526             }
1527
1528             self.eat_incorrect_doc_comment("a method argument's type");
1529             (pat, self.parse_ty_common(true, true, allow_c_variadic)?)
1530         } else {
1531             debug!("parse_arg_general ident_to_pat");
1532             let parser_snapshot_before_ty = self.clone();
1533             self.eat_incorrect_doc_comment("a method argument's type");
1534             let mut ty = self.parse_ty_common(true, true, allow_c_variadic);
1535             if ty.is_ok() && self.token != token::Comma &&
1536                self.token != token::CloseDelim(token::Paren) {
1537                 // This wasn't actually a type, but a pattern looking like a type,
1538                 // so we are going to rollback and re-parse for recovery.
1539                 ty = self.unexpected();
1540             }
1541             match ty {
1542                 Ok(ty) => {
1543                     let ident = Ident::new(kw::Invalid, self.prev_span);
1544                     let pat = P(Pat {
1545                         id: ast::DUMMY_NODE_ID,
1546                         node: PatKind::Ident(
1547                             BindingMode::ByValue(Mutability::Immutable), ident, None),
1548                         span: ty.span,
1549                     });
1550                     (pat, ty)
1551                 }
1552                 Err(mut err) => {
1553                     // If this is a C-variadic argument and we hit an error, return the
1554                     // error.
1555                     if self.token == token::DotDotDot {
1556                         return Err(err);
1557                     }
1558                     // Recover from attempting to parse the argument as a type without pattern.
1559                     err.cancel();
1560                     mem::replace(self, parser_snapshot_before_ty);
1561                     self.recover_arg_parse()?
1562                 }
1563             }
1564         };
1565
1566         Ok(Arg { ty, pat, id: ast::DUMMY_NODE_ID, source: ast::ArgSource::Normal })
1567     }
1568
1569     /// Parses an argument in a lambda header (e.g., `|arg, arg|`).
1570     fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1571         let pat = self.parse_pat(Some("argument name"))?;
1572         let t = if self.eat(&token::Colon) {
1573             self.parse_ty()?
1574         } else {
1575             P(Ty {
1576                 id: ast::DUMMY_NODE_ID,
1577                 node: TyKind::Infer,
1578                 span: self.prev_span,
1579             })
1580         };
1581         Ok(Arg {
1582             ty: t,
1583             pat,
1584             id: ast::DUMMY_NODE_ID,
1585             source: ast::ArgSource::Normal,
1586         })
1587     }
1588
1589     fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1590         if self.eat(&token::Semi) {
1591             Ok(Some(self.parse_expr()?))
1592         } else {
1593             Ok(None)
1594         }
1595     }
1596
1597     /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`).
1598     crate fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1599         maybe_whole_expr!(self);
1600
1601         let minus_lo = self.span;
1602         let minus_present = self.eat(&token::BinOp(token::Minus));
1603         let lo = self.span;
1604         let literal = self.parse_lit()?;
1605         let hi = self.prev_span;
1606         let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
1607
1608         if minus_present {
1609             let minus_hi = self.prev_span;
1610             let unary = self.mk_unary(UnOp::Neg, expr);
1611             Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
1612         } else {
1613             Ok(expr)
1614         }
1615     }
1616
1617     fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
1618         match self.token {
1619             token::Ident(ident, _) if self.token.is_path_segment_keyword() => {
1620                 let span = self.span;
1621                 self.bump();
1622                 Ok(Ident::new(ident.name, span))
1623             }
1624             _ => self.parse_ident(),
1625         }
1626     }
1627
1628     fn parse_ident_or_underscore(&mut self) -> PResult<'a, ast::Ident> {
1629         match self.token {
1630             token::Ident(ident, false) if ident.name == kw::Underscore => {
1631                 let span = self.span;
1632                 self.bump();
1633                 Ok(Ident::new(ident.name, span))
1634             }
1635             _ => self.parse_ident(),
1636         }
1637     }
1638
1639     /// Parses a qualified path.
1640     /// Assumes that the leading `<` has been parsed already.
1641     ///
1642     /// `qualified_path = <type [as trait_ref]>::path`
1643     ///
1644     /// # Examples
1645     /// `<T>::default`
1646     /// `<T as U>::a`
1647     /// `<T as U>::F::a<S>` (without disambiguator)
1648     /// `<T as U>::F::a::<S>` (with disambiguator)
1649     fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, ast::Path)> {
1650         let lo = self.prev_span;
1651         let ty = self.parse_ty()?;
1652
1653         // `path` will contain the prefix of the path up to the `>`,
1654         // if any (e.g., `U` in the `<T as U>::*` examples
1655         // above). `path_span` has the span of that path, or an empty
1656         // span in the case of something like `<T>::Bar`.
1657         let (mut path, path_span);
1658         if self.eat_keyword(kw::As) {
1659             let path_lo = self.span;
1660             path = self.parse_path(PathStyle::Type)?;
1661             path_span = path_lo.to(self.prev_span);
1662         } else {
1663             path = ast::Path { segments: Vec::new(), span: DUMMY_SP };
1664             path_span = self.span.to(self.span);
1665         }
1666
1667         // See doc comment for `unmatched_angle_bracket_count`.
1668         self.expect(&token::Gt)?;
1669         if self.unmatched_angle_bracket_count > 0 {
1670             self.unmatched_angle_bracket_count -= 1;
1671             debug!("parse_qpath: (decrement) count={:?}", self.unmatched_angle_bracket_count);
1672         }
1673
1674         self.expect(&token::ModSep)?;
1675
1676         let qself = QSelf { ty, path_span, position: path.segments.len() };
1677         self.parse_path_segments(&mut path.segments, style)?;
1678
1679         Ok((qself, ast::Path { segments: path.segments, span: lo.to(self.prev_span) }))
1680     }
1681
1682     /// Parses simple paths.
1683     ///
1684     /// `path = [::] segment+`
1685     /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
1686     ///
1687     /// # Examples
1688     /// `a::b::C<D>` (without disambiguator)
1689     /// `a::b::C::<D>` (with disambiguator)
1690     /// `Fn(Args)` (without disambiguator)
1691     /// `Fn::(Args)` (with disambiguator)
1692     pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1693         maybe_whole!(self, NtPath, |path| {
1694             if style == PathStyle::Mod &&
1695                path.segments.iter().any(|segment| segment.args.is_some()) {
1696                 self.diagnostic().span_err(path.span, "unexpected generic arguments in path");
1697             }
1698             path
1699         });
1700
1701         let lo = self.meta_var_span.unwrap_or(self.span);
1702         let mut segments = Vec::new();
1703         let mod_sep_ctxt = self.span.ctxt();
1704         if self.eat(&token::ModSep) {
1705             segments.push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
1706         }
1707         self.parse_path_segments(&mut segments, style)?;
1708
1709         Ok(ast::Path { segments, span: lo.to(self.prev_span) })
1710     }
1711
1712     /// Like `parse_path`, but also supports parsing `Word` meta items into paths for
1713     /// backwards-compatibility. This is used when parsing derive macro paths in `#[derive]`
1714     /// attributes.
1715     pub fn parse_path_allowing_meta(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1716         let meta_ident = match self.token {
1717             token::Interpolated(ref nt) => match **nt {
1718                 token::NtMeta(ref meta) => match meta.node {
1719                     ast::MetaItemKind::Word => Some(meta.path.clone()),
1720                     _ => None,
1721                 },
1722                 _ => None,
1723             },
1724             _ => None,
1725         };
1726         if let Some(path) = meta_ident {
1727             self.bump();
1728             return Ok(path);
1729         }
1730         self.parse_path(style)
1731     }
1732
1733     crate fn parse_path_segments(&mut self,
1734                            segments: &mut Vec<PathSegment>,
1735                            style: PathStyle)
1736                            -> PResult<'a, ()> {
1737         loop {
1738             let segment = self.parse_path_segment(style)?;
1739             if style == PathStyle::Expr {
1740                 // In order to check for trailing angle brackets, we must have finished
1741                 // recursing (`parse_path_segment` can indirectly call this function),
1742                 // that is, the next token must be the highlighted part of the below example:
1743                 //
1744                 // `Foo::<Bar as Baz<T>>::Qux`
1745                 //                      ^ here
1746                 //
1747                 // As opposed to the below highlight (if we had only finished the first
1748                 // recursion):
1749                 //
1750                 // `Foo::<Bar as Baz<T>>::Qux`
1751                 //                     ^ here
1752                 //
1753                 // `PathStyle::Expr` is only provided at the root invocation and never in
1754                 // `parse_path_segment` to recurse and therefore can be checked to maintain
1755                 // this invariant.
1756                 self.check_trailing_angle_brackets(&segment, token::ModSep);
1757             }
1758             segments.push(segment);
1759
1760             if self.is_import_coupler() || !self.eat(&token::ModSep) {
1761                 return Ok(());
1762             }
1763         }
1764     }
1765
1766     fn parse_path_segment(&mut self, style: PathStyle) -> PResult<'a, PathSegment> {
1767         let ident = self.parse_path_segment_ident()?;
1768
1769         let is_args_start = |token: &token::Token| match *token {
1770             token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren)
1771             | token::LArrow => true,
1772             _ => false,
1773         };
1774         let check_args_start = |this: &mut Self| {
1775             this.expected_tokens.extend_from_slice(
1776                 &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))]
1777             );
1778             is_args_start(&this.token)
1779         };
1780
1781         Ok(if style == PathStyle::Type && check_args_start(self) ||
1782               style != PathStyle::Mod && self.check(&token::ModSep)
1783                                       && self.look_ahead(1, |t| is_args_start(t)) {
1784             // We use `style == PathStyle::Expr` to check if this is in a recursion or not. If
1785             // it isn't, then we reset the unmatched angle bracket count as we're about to start
1786             // parsing a new path.
1787             if style == PathStyle::Expr {
1788                 self.unmatched_angle_bracket_count = 0;
1789                 self.max_angle_bracket_count = 0;
1790             }
1791
1792             // Generic arguments are found - `<`, `(`, `::<` or `::(`.
1793             self.eat(&token::ModSep);
1794             let lo = self.span;
1795             let args = if self.eat_lt() {
1796                 // `<'a, T, A = U>`
1797                 let (args, bindings) =
1798                     self.parse_generic_args_with_leaning_angle_bracket_recovery(style, lo)?;
1799                 self.expect_gt()?;
1800                 let span = lo.to(self.prev_span);
1801                 AngleBracketedArgs { args, bindings, span }.into()
1802             } else {
1803                 // `(T, U) -> R`
1804                 self.bump(); // `(`
1805                 let (inputs, recovered) = self.parse_seq_to_before_tokens(
1806                     &[&token::CloseDelim(token::Paren)],
1807                     SeqSep::trailing_allowed(token::Comma),
1808                     TokenExpectType::Expect,
1809                     |p| p.parse_ty())?;
1810                 if !recovered {
1811                     self.bump(); // `)`
1812                 }
1813                 let span = lo.to(self.prev_span);
1814                 let output = if self.eat(&token::RArrow) {
1815                     Some(self.parse_ty_common(false, false, false)?)
1816                 } else {
1817                     None
1818                 };
1819                 ParenthesizedArgs { inputs, output, span }.into()
1820             };
1821
1822             PathSegment { ident, args, id: ast::DUMMY_NODE_ID }
1823         } else {
1824             // Generic arguments are not found.
1825             PathSegment::from_ident(ident)
1826         })
1827     }
1828
1829     crate fn check_lifetime(&mut self) -> bool {
1830         self.expected_tokens.push(TokenType::Lifetime);
1831         self.token.is_lifetime()
1832     }
1833
1834     /// Parses a single lifetime `'a` or panics.
1835     crate fn expect_lifetime(&mut self) -> Lifetime {
1836         if let Some(ident) = self.token.lifetime() {
1837             let span = self.span;
1838             self.bump();
1839             Lifetime { ident: Ident::new(ident.name, span), id: ast::DUMMY_NODE_ID }
1840         } else {
1841             self.span_bug(self.span, "not a lifetime")
1842         }
1843     }
1844
1845     fn eat_label(&mut self) -> Option<Label> {
1846         if let Some(ident) = self.token.lifetime() {
1847             let span = self.span;
1848             self.bump();
1849             Some(Label { ident: Ident::new(ident.name, span) })
1850         } else {
1851             None
1852         }
1853     }
1854
1855     /// Parses mutability (`mut` or nothing).
1856     fn parse_mutability(&mut self) -> Mutability {
1857         if self.eat_keyword(kw::Mut) {
1858             Mutability::Mutable
1859         } else {
1860             Mutability::Immutable
1861         }
1862     }
1863
1864     fn parse_field_name(&mut self) -> PResult<'a, Ident> {
1865         if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = self.token {
1866             self.expect_no_suffix(self.span, "a tuple index", suffix);
1867             self.bump();
1868             Ok(Ident::new(symbol, self.prev_span))
1869         } else {
1870             self.parse_ident_common(false)
1871         }
1872     }
1873
1874     /// Parse ident (COLON expr)?
1875     fn parse_field(&mut self) -> PResult<'a, Field> {
1876         let attrs = self.parse_outer_attributes()?;
1877         let lo = self.span;
1878
1879         // Check if a colon exists one ahead. This means we're parsing a fieldname.
1880         let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| {
1881             t == &token::Colon || t == &token::Eq
1882         }) {
1883             let fieldname = self.parse_field_name()?;
1884
1885             // Check for an equals token. This means the source incorrectly attempts to
1886             // initialize a field with an eq rather than a colon.
1887             if self.token == token::Eq {
1888                 self.diagnostic()
1889                     .struct_span_err(self.span, "expected `:`, found `=`")
1890                     .span_suggestion(
1891                         fieldname.span.shrink_to_hi().to(self.span),
1892                         "replace equals symbol with a colon",
1893                         ":".to_string(),
1894                         Applicability::MachineApplicable,
1895                     )
1896                     .emit();
1897             }
1898             self.bump(); // `:`
1899             (fieldname, self.parse_expr()?, false)
1900         } else {
1901             let fieldname = self.parse_ident_common(false)?;
1902
1903             // Mimic `x: x` for the `x` field shorthand.
1904             let path = ast::Path::from_ident(fieldname);
1905             let expr = self.mk_expr(fieldname.span, ExprKind::Path(None, path), ThinVec::new());
1906             (fieldname, expr, true)
1907         };
1908         Ok(ast::Field {
1909             ident: fieldname,
1910             span: lo.to(expr.span),
1911             expr,
1912             is_shorthand,
1913             attrs: attrs.into(),
1914         })
1915     }
1916
1917     crate fn mk_expr(&self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
1918         P(Expr { node, span, attrs, id: ast::DUMMY_NODE_ID })
1919     }
1920
1921     fn mk_unary(&self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
1922         ExprKind::Unary(unop, expr)
1923     }
1924
1925     fn mk_binary(&self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
1926         ExprKind::Binary(binop, lhs, rhs)
1927     }
1928
1929     fn mk_call(&self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
1930         ExprKind::Call(f, args)
1931     }
1932
1933     fn mk_index(&self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
1934         ExprKind::Index(expr, idx)
1935     }
1936
1937     fn mk_range(&self,
1938                     start: Option<P<Expr>>,
1939                     end: Option<P<Expr>>,
1940                     limits: RangeLimits)
1941                     -> PResult<'a, ast::ExprKind> {
1942         if end.is_none() && limits == RangeLimits::Closed {
1943             Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
1944         } else {
1945             Ok(ExprKind::Range(start, end, limits))
1946         }
1947     }
1948
1949     fn mk_assign_op(&self, binop: ast::BinOp,
1950                         lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
1951         ExprKind::AssignOp(binop, lhs, rhs)
1952     }
1953
1954     fn expect_delimited_token_tree(&mut self) -> PResult<'a, (MacDelimiter, TokenStream)> {
1955         let delim = match self.token {
1956             token::OpenDelim(delim) => delim,
1957             _ => {
1958                 let msg = "expected open delimiter";
1959                 let mut err = self.fatal(msg);
1960                 err.span_label(self.span, msg);
1961                 return Err(err)
1962             }
1963         };
1964         let tts = match self.parse_token_tree() {
1965             TokenTree::Delimited(_, _, tts) => tts,
1966             _ => unreachable!(),
1967         };
1968         let delim = match delim {
1969             token::Paren => MacDelimiter::Parenthesis,
1970             token::Bracket => MacDelimiter::Bracket,
1971             token::Brace => MacDelimiter::Brace,
1972             token::NoDelim => self.bug("unexpected no delimiter"),
1973         };
1974         Ok((delim, tts.into()))
1975     }
1976
1977     /// At the bottom (top?) of the precedence hierarchy,
1978     /// Parses things like parenthesized exprs, macros, `return`, etc.
1979     ///
1980     /// N.B., this does not parse outer attributes, and is private because it only works
1981     /// correctly if called from `parse_dot_or_call_expr()`.
1982     fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
1983         maybe_recover_from_interpolated_ty_qpath!(self, true);
1984         maybe_whole_expr!(self);
1985
1986         // Outer attributes are already parsed and will be
1987         // added to the return value after the fact.
1988         //
1989         // Therefore, prevent sub-parser from parsing
1990         // attributes by giving them a empty "already parsed" list.
1991         let mut attrs = ThinVec::new();
1992
1993         let lo = self.span;
1994         let mut hi = self.span;
1995
1996         let ex: ExprKind;
1997
1998         // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
1999         match self.token {
2000             token::OpenDelim(token::Paren) => {
2001                 self.bump();
2002
2003                 attrs.extend(self.parse_inner_attributes()?);
2004
2005                 // (e) is parenthesized e
2006                 // (e,) is a tuple with only one field, e
2007                 let mut es = vec![];
2008                 let mut trailing_comma = false;
2009                 let mut recovered = false;
2010                 while self.token != token::CloseDelim(token::Paren) {
2011                     es.push(match self.parse_expr() {
2012                         Ok(es) => es,
2013                         Err(err) => {
2014                             // recover from parse error in tuple list
2015                             return Ok(self.recover_seq_parse_error(token::Paren, lo, Err(err)));
2016                         }
2017                     });
2018                     recovered = self.expect_one_of(
2019                         &[],
2020                         &[token::Comma, token::CloseDelim(token::Paren)],
2021                     )?;
2022                     if self.eat(&token::Comma) {
2023                         trailing_comma = true;
2024                     } else {
2025                         trailing_comma = false;
2026                         break;
2027                     }
2028                 }
2029                 if !recovered {
2030                     self.bump();
2031                 }
2032
2033                 hi = self.prev_span;
2034                 ex = if es.len() == 1 && !trailing_comma {
2035                     ExprKind::Paren(es.into_iter().nth(0).unwrap())
2036                 } else {
2037                     ExprKind::Tup(es)
2038                 };
2039             }
2040             token::OpenDelim(token::Brace) => {
2041                 return self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs);
2042             }
2043             token::BinOp(token::Or) | token::OrOr => {
2044                 return self.parse_lambda_expr(attrs);
2045             }
2046             token::OpenDelim(token::Bracket) => {
2047                 self.bump();
2048
2049                 attrs.extend(self.parse_inner_attributes()?);
2050
2051                 if self.eat(&token::CloseDelim(token::Bracket)) {
2052                     // Empty vector.
2053                     ex = ExprKind::Array(Vec::new());
2054                 } else {
2055                     // Nonempty vector.
2056                     let first_expr = self.parse_expr()?;
2057                     if self.eat(&token::Semi) {
2058                         // Repeating array syntax: [ 0; 512 ]
2059                         let count = AnonConst {
2060                             id: ast::DUMMY_NODE_ID,
2061                             value: self.parse_expr()?,
2062                         };
2063                         self.expect(&token::CloseDelim(token::Bracket))?;
2064                         ex = ExprKind::Repeat(first_expr, count);
2065                     } else if self.eat(&token::Comma) {
2066                         // Vector with two or more elements.
2067                         let remaining_exprs = self.parse_seq_to_end(
2068                             &token::CloseDelim(token::Bracket),
2069                             SeqSep::trailing_allowed(token::Comma),
2070                             |p| Ok(p.parse_expr()?)
2071                         )?;
2072                         let mut exprs = vec![first_expr];
2073                         exprs.extend(remaining_exprs);
2074                         ex = ExprKind::Array(exprs);
2075                     } else {
2076                         // Vector with one element.
2077                         self.expect(&token::CloseDelim(token::Bracket))?;
2078                         ex = ExprKind::Array(vec![first_expr]);
2079                     }
2080                 }
2081                 hi = self.prev_span;
2082             }
2083             _ => {
2084                 if self.eat_lt() {
2085                     let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
2086                     hi = path.span;
2087                     return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2088                 }
2089                 if self.span.rust_2018() && self.check_keyword(kw::Async) {
2090                     return if self.is_async_block() { // check for `async {` and `async move {`
2091                         self.parse_async_block(attrs)
2092                     } else {
2093                         self.parse_lambda_expr(attrs)
2094                     };
2095                 }
2096                 if self.check_keyword(kw::Move) || self.check_keyword(kw::Static) {
2097                     return self.parse_lambda_expr(attrs);
2098                 }
2099                 if self.eat_keyword(kw::If) {
2100                     return self.parse_if_expr(attrs);
2101                 }
2102                 if self.eat_keyword(kw::For) {
2103                     let lo = self.prev_span;
2104                     return self.parse_for_expr(None, lo, attrs);
2105                 }
2106                 if self.eat_keyword(kw::While) {
2107                     let lo = self.prev_span;
2108                     return self.parse_while_expr(None, lo, attrs);
2109                 }
2110                 if let Some(label) = self.eat_label() {
2111                     let lo = label.ident.span;
2112                     self.expect(&token::Colon)?;
2113                     if self.eat_keyword(kw::While) {
2114                         return self.parse_while_expr(Some(label), lo, attrs)
2115                     }
2116                     if self.eat_keyword(kw::For) {
2117                         return self.parse_for_expr(Some(label), lo, attrs)
2118                     }
2119                     if self.eat_keyword(kw::Loop) {
2120                         return self.parse_loop_expr(Some(label), lo, attrs)
2121                     }
2122                     if self.token == token::OpenDelim(token::Brace) {
2123                         return self.parse_block_expr(Some(label),
2124                                                      lo,
2125                                                      BlockCheckMode::Default,
2126                                                      attrs);
2127                     }
2128                     let msg = "expected `while`, `for`, `loop` or `{` after a label";
2129                     let mut err = self.fatal(msg);
2130                     err.span_label(self.span, msg);
2131                     return Err(err);
2132                 }
2133                 if self.eat_keyword(kw::Loop) {
2134                     let lo = self.prev_span;
2135                     return self.parse_loop_expr(None, lo, attrs);
2136                 }
2137                 if self.eat_keyword(kw::Continue) {
2138                     let label = self.eat_label();
2139                     let ex = ExprKind::Continue(label);
2140                     let hi = self.prev_span;
2141                     return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2142                 }
2143                 if self.eat_keyword(kw::Match) {
2144                     let match_sp = self.prev_span;
2145                     return self.parse_match_expr(attrs).map_err(|mut err| {
2146                         err.span_label(match_sp, "while parsing this match expression");
2147                         err
2148                     });
2149                 }
2150                 if self.eat_keyword(kw::Unsafe) {
2151                     return self.parse_block_expr(
2152                         None,
2153                         lo,
2154                         BlockCheckMode::Unsafe(ast::UserProvided),
2155                         attrs);
2156                 }
2157                 if self.is_do_catch_block() {
2158                     let mut db = self.fatal("found removed `do catch` syntax");
2159                     db.help("Following RFC #2388, the new non-placeholder syntax is `try`");
2160                     return Err(db);
2161                 }
2162                 if self.is_try_block() {
2163                     let lo = self.span;
2164                     assert!(self.eat_keyword(kw::Try));
2165                     return self.parse_try_block(lo, attrs);
2166                 }
2167                 if self.eat_keyword(kw::Return) {
2168                     if self.token.can_begin_expr() {
2169                         let e = self.parse_expr()?;
2170                         hi = e.span;
2171                         ex = ExprKind::Ret(Some(e));
2172                     } else {
2173                         ex = ExprKind::Ret(None);
2174                     }
2175                 } else if self.eat_keyword(kw::Break) {
2176                     let label = self.eat_label();
2177                     let e = if self.token.can_begin_expr()
2178                                && !(self.token == token::OpenDelim(token::Brace)
2179                                     && self.restrictions.contains(
2180                                            Restrictions::NO_STRUCT_LITERAL)) {
2181                         Some(self.parse_expr()?)
2182                     } else {
2183                         None
2184                     };
2185                     ex = ExprKind::Break(label, e);
2186                     hi = self.prev_span;
2187                 } else if self.eat_keyword(kw::Yield) {
2188                     if self.token.can_begin_expr() {
2189                         let e = self.parse_expr()?;
2190                         hi = e.span;
2191                         ex = ExprKind::Yield(Some(e));
2192                     } else {
2193                         ex = ExprKind::Yield(None);
2194                     }
2195                 } else if self.token.is_keyword(kw::Let) {
2196                     // Catch this syntax error here, instead of in `parse_ident`, so
2197                     // that we can explicitly mention that let is not to be used as an expression
2198                     let mut db = self.fatal("expected expression, found statement (`let`)");
2199                     db.span_label(self.span, "expected expression");
2200                     db.note("variable declaration using `let` is a statement");
2201                     return Err(db);
2202                 } else if self.span.rust_2018() && self.eat_keyword(kw::Await) {
2203                     let (await_hi, e_kind) = self.parse_await_macro_or_alt(lo, self.prev_span)?;
2204                     hi = await_hi;
2205                     ex = e_kind;
2206                 } else if self.token.is_path_start() {
2207                     let path = self.parse_path(PathStyle::Expr)?;
2208
2209                     // `!`, as an operator, is prefix, so we know this isn't that
2210                     if self.eat(&token::Not) {
2211                         // MACRO INVOCATION expression
2212                         let (delim, tts) = self.expect_delimited_token_tree()?;
2213                         hi = self.prev_span;
2214                         ex = ExprKind::Mac(respan(lo.to(hi), Mac_ { path, tts, delim }));
2215                     } else if self.check(&token::OpenDelim(token::Brace)) {
2216                         if let Some(expr) = self.maybe_parse_struct_expr(lo, &path, &attrs) {
2217                             return expr;
2218                         } else {
2219                             hi = path.span;
2220                             ex = ExprKind::Path(None, path);
2221                         }
2222                     } else {
2223                         hi = path.span;
2224                         ex = ExprKind::Path(None, path);
2225                     }
2226                 } else {
2227                     if !self.unclosed_delims.is_empty() && self.check(&token::Semi) {
2228                         // Don't complain about bare semicolons after unclosed braces
2229                         // recovery in order to keep the error count down. Fixing the
2230                         // delimiters will possibly also fix the bare semicolon found in
2231                         // expression context. For example, silence the following error:
2232                         // ```
2233                         // error: expected expression, found `;`
2234                         //  --> file.rs:2:13
2235                         //   |
2236                         // 2 |     foo(bar(;
2237                         //   |             ^ expected expression
2238                         // ```
2239                         self.bump();
2240                         return Ok(self.mk_expr(self.span, ExprKind::Err, ThinVec::new()));
2241                     }
2242                     match self.parse_literal_maybe_minus() {
2243                         Ok(expr) => {
2244                             hi = expr.span;
2245                             ex = expr.node.clone();
2246                         }
2247                         Err(mut err) => {
2248                             self.cancel(&mut err);
2249                             return Err(self.expected_expression_found());
2250                         }
2251                     }
2252                 }
2253             }
2254         }
2255
2256         let expr = self.mk_expr(lo.to(hi), ex, attrs);
2257         self.maybe_recover_from_bad_qpath(expr, true)
2258     }
2259
2260     /// Parse `await!(<expr>)` calls, or alternatively recover from incorrect but reasonable
2261     /// alternative syntaxes `await <expr>`, `await? <expr>`, `await(<expr>)` and
2262     /// `await { <expr> }`.
2263     fn parse_await_macro_or_alt(
2264         &mut self,
2265         lo: Span,
2266         await_sp: Span,
2267     ) -> PResult<'a, (Span, ExprKind)> {
2268         if self.token == token::Not {
2269             // Handle correct `await!(<expr>)`.
2270             // FIXME: make this an error when `await!` is no longer supported
2271             // https://github.com/rust-lang/rust/issues/60610
2272             self.expect(&token::Not)?;
2273             self.expect(&token::OpenDelim(token::Paren))?;
2274             let expr = self.parse_expr().map_err(|mut err| {
2275                 err.span_label(await_sp, "while parsing this await macro call");
2276                 err
2277             })?;
2278             self.expect(&token::CloseDelim(token::Paren))?;
2279             Ok((self.prev_span, ExprKind::Await(ast::AwaitOrigin::MacroLike, expr)))
2280         } else { // Handle `await <expr>`.
2281             self.parse_incorrect_await_syntax(lo, await_sp)
2282         }
2283     }
2284
2285     fn maybe_parse_struct_expr(
2286         &mut self,
2287         lo: Span,
2288         path: &ast::Path,
2289         attrs: &ThinVec<Attribute>,
2290     ) -> Option<PResult<'a, P<Expr>>> {
2291         let struct_allowed = !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
2292         let certainly_not_a_block = || self.look_ahead(1, |t| t.is_ident()) && (
2293             // `{ ident, ` cannot start a block
2294             self.look_ahead(2, |t| t == &token::Comma) ||
2295             self.look_ahead(2, |t| t == &token::Colon) && (
2296                 // `{ ident: token, ` cannot start a block
2297                 self.look_ahead(4, |t| t == &token::Comma) ||
2298                 // `{ ident: ` cannot start a block unless it's a type ascription `ident: Type`
2299                 self.look_ahead(3, |t| !t.can_begin_type())
2300             )
2301         );
2302
2303         if struct_allowed || certainly_not_a_block() {
2304             // This is a struct literal, but we don't can't accept them here
2305             let expr = self.parse_struct_expr(lo, path.clone(), attrs.clone());
2306             if let (Ok(expr), false) = (&expr, struct_allowed) {
2307                 let mut err = self.diagnostic().struct_span_err(
2308                     expr.span,
2309                     "struct literals are not allowed here",
2310                 );
2311                 err.multipart_suggestion(
2312                     "surround the struct literal with parentheses",
2313                     vec![
2314                         (lo.shrink_to_lo(), "(".to_string()),
2315                         (expr.span.shrink_to_hi(), ")".to_string()),
2316                     ],
2317                     Applicability::MachineApplicable,
2318                 );
2319                 err.emit();
2320             }
2321             return Some(expr);
2322         }
2323         None
2324     }
2325
2326     fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2327                          -> PResult<'a, P<Expr>> {
2328         let struct_sp = lo.to(self.prev_span);
2329         self.bump();
2330         let mut fields = Vec::new();
2331         let mut base = None;
2332
2333         attrs.extend(self.parse_inner_attributes()?);
2334
2335         while self.token != token::CloseDelim(token::Brace) {
2336             if self.eat(&token::DotDot) {
2337                 let exp_span = self.prev_span;
2338                 match self.parse_expr() {
2339                     Ok(e) => {
2340                         base = Some(e);
2341                     }
2342                     Err(mut e) => {
2343                         e.emit();
2344                         self.recover_stmt();
2345                     }
2346                 }
2347                 if self.token == token::Comma {
2348                     let mut err = self.sess.span_diagnostic.mut_span_err(
2349                         exp_span.to(self.prev_span),
2350                         "cannot use a comma after the base struct",
2351                     );
2352                     err.span_suggestion_short(
2353                         self.span,
2354                         "remove this comma",
2355                         String::new(),
2356                         Applicability::MachineApplicable
2357                     );
2358                     err.note("the base struct must always be the last field");
2359                     err.emit();
2360                     self.recover_stmt();
2361                 }
2362                 break;
2363             }
2364
2365             let mut recovery_field = None;
2366             if let token::Ident(ident, _) = self.token {
2367                 if !self.token.is_reserved_ident() && self.look_ahead(1, |t| *t == token::Colon) {
2368                     // Use in case of error after field-looking code: `S { foo: () with a }`
2369                     let mut ident = ident.clone();
2370                     ident.span = self.span;
2371                     recovery_field = Some(ast::Field {
2372                         ident,
2373                         span: self.span,
2374                         expr: self.mk_expr(self.span, ExprKind::Err, ThinVec::new()),
2375                         is_shorthand: false,
2376                         attrs: ThinVec::new(),
2377                     });
2378                 }
2379             }
2380             let mut parsed_field = None;
2381             match self.parse_field() {
2382                 Ok(f) => parsed_field = Some(f),
2383                 Err(mut e) => {
2384                     e.span_label(struct_sp, "while parsing this struct");
2385                     e.emit();
2386
2387                     // If the next token is a comma, then try to parse
2388                     // what comes next as additional fields, rather than
2389                     // bailing out until next `}`.
2390                     if self.token != token::Comma {
2391                         self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2392                         if self.token != token::Comma {
2393                             break;
2394                         }
2395                     }
2396                 }
2397             }
2398
2399             match self.expect_one_of(&[token::Comma],
2400                                      &[token::CloseDelim(token::Brace)]) {
2401                 Ok(_) => if let Some(f) = parsed_field.or(recovery_field) {
2402                     // only include the field if there's no parse error for the field name
2403                     fields.push(f);
2404                 }
2405                 Err(mut e) => {
2406                     if let Some(f) = recovery_field {
2407                         fields.push(f);
2408                     }
2409                     e.span_label(struct_sp, "while parsing this struct");
2410                     e.emit();
2411                     self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2412                     self.eat(&token::Comma);
2413                 }
2414             }
2415         }
2416
2417         let span = lo.to(self.span);
2418         self.expect(&token::CloseDelim(token::Brace))?;
2419         return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2420     }
2421
2422     fn parse_or_use_outer_attributes(&mut self,
2423                                      already_parsed_attrs: Option<ThinVec<Attribute>>)
2424                                      -> PResult<'a, ThinVec<Attribute>> {
2425         if let Some(attrs) = already_parsed_attrs {
2426             Ok(attrs)
2427         } else {
2428             self.parse_outer_attributes().map(|a| a.into())
2429         }
2430     }
2431
2432     /// Parses a block or unsafe block.
2433     crate fn parse_block_expr(
2434         &mut self,
2435         opt_label: Option<Label>,
2436         lo: Span,
2437         blk_mode: BlockCheckMode,
2438         outer_attrs: ThinVec<Attribute>,
2439     ) -> PResult<'a, P<Expr>> {
2440         self.expect(&token::OpenDelim(token::Brace))?;
2441
2442         let mut attrs = outer_attrs;
2443         attrs.extend(self.parse_inner_attributes()?);
2444
2445         let blk = self.parse_block_tail(lo, blk_mode)?;
2446         return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs));
2447     }
2448
2449     /// Parses `a.b` or `a(13)` or `a[4]` or just `a`.
2450     fn parse_dot_or_call_expr(&mut self,
2451                                   already_parsed_attrs: Option<ThinVec<Attribute>>)
2452                                   -> PResult<'a, P<Expr>> {
2453         let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2454
2455         let b = self.parse_bottom_expr();
2456         let (span, b) = self.interpolated_or_expr_span(b)?;
2457         self.parse_dot_or_call_expr_with(b, span, attrs)
2458     }
2459
2460     fn parse_dot_or_call_expr_with(&mut self,
2461                                        e0: P<Expr>,
2462                                        lo: Span,
2463                                        mut attrs: ThinVec<Attribute>)
2464                                        -> PResult<'a, P<Expr>> {
2465         // Stitch the list of outer attributes onto the return value.
2466         // A little bit ugly, but the best way given the current code
2467         // structure
2468         self.parse_dot_or_call_expr_with_(e0, lo)
2469         .map(|expr|
2470             expr.map(|mut expr| {
2471                 attrs.extend::<Vec<_>>(expr.attrs.into());
2472                 expr.attrs = attrs;
2473                 match expr.node {
2474                     ExprKind::If(..) | ExprKind::IfLet(..) => {
2475                         if !expr.attrs.is_empty() {
2476                             // Just point to the first attribute in there...
2477                             let span = expr.attrs[0].span;
2478
2479                             self.span_err(span,
2480                                 "attributes are not yet allowed on `if` \
2481                                 expressions");
2482                         }
2483                     }
2484                     _ => {}
2485                 }
2486                 expr
2487             })
2488         )
2489     }
2490
2491     // Assuming we have just parsed `.`, continue parsing into an expression.
2492     fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2493         if self.span.rust_2018() && self.eat_keyword(kw::Await) {
2494             let span = lo.to(self.prev_span);
2495             let await_expr = self.mk_expr(
2496                 span,
2497                 ExprKind::Await(ast::AwaitOrigin::FieldLike, self_arg),
2498                 ThinVec::new(),
2499             );
2500             self.recover_from_await_method_call();
2501             return Ok(await_expr);
2502         }
2503         let segment = self.parse_path_segment(PathStyle::Expr)?;
2504         self.check_trailing_angle_brackets(&segment, token::OpenDelim(token::Paren));
2505
2506         Ok(match self.token {
2507             token::OpenDelim(token::Paren) => {
2508                 // Method call `expr.f()`
2509                 let mut args = self.parse_unspanned_seq(
2510                     &token::OpenDelim(token::Paren),
2511                     &token::CloseDelim(token::Paren),
2512                     SeqSep::trailing_allowed(token::Comma),
2513                     |p| Ok(p.parse_expr()?)
2514                 )?;
2515                 args.insert(0, self_arg);
2516
2517                 let span = lo.to(self.prev_span);
2518                 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
2519             }
2520             _ => {
2521                 // Field access `expr.f`
2522                 if let Some(args) = segment.args {
2523                     self.span_err(args.span(),
2524                                   "field expressions may not have generic arguments");
2525                 }
2526
2527                 let span = lo.to(self.prev_span);
2528                 self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), ThinVec::new())
2529             }
2530         })
2531     }
2532
2533     fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2534         let mut e = e0;
2535         let mut hi;
2536         loop {
2537             // expr?
2538             while self.eat(&token::Question) {
2539                 let hi = self.prev_span;
2540                 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
2541             }
2542
2543             // expr.f
2544             if self.eat(&token::Dot) {
2545                 match self.token {
2546                     token::Ident(..) => {
2547                         e = self.parse_dot_suffix(e, lo)?;
2548                     }
2549                     token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) => {
2550                         let span = self.span;
2551                         self.bump();
2552                         let field = ExprKind::Field(e, Ident::new(symbol, span));
2553                         e = self.mk_expr(lo.to(span), field, ThinVec::new());
2554
2555                         self.expect_no_suffix(span, "a tuple index", suffix);
2556                     }
2557                     token::Literal(token::Lit { kind: token::Float, symbol, .. }) => {
2558                       self.bump();
2559                       let fstr = symbol.as_str();
2560                       let msg = format!("unexpected token: `{}`", symbol);
2561                       let mut err = self.diagnostic().struct_span_err(self.prev_span, &msg);
2562                       err.span_label(self.prev_span, "unexpected token");
2563                       if fstr.chars().all(|x| "0123456789.".contains(x)) {
2564                           let float = match fstr.parse::<f64>().ok() {
2565                               Some(f) => f,
2566                               None => continue,
2567                           };
2568                           let sugg = pprust::to_string(|s| {
2569                               use crate::print::pprust::PrintState;
2570                               s.popen()?;
2571                               s.print_expr(&e)?;
2572                               s.s.word( ".")?;
2573                               s.print_usize(float.trunc() as usize)?;
2574                               s.pclose()?;
2575                               s.s.word(".")?;
2576                               s.s.word(fstr.splitn(2, ".").last().unwrap().to_string())
2577                           });
2578                           err.span_suggestion(
2579                               lo.to(self.prev_span),
2580                               "try parenthesizing the first index",
2581                               sugg,
2582                               Applicability::MachineApplicable
2583                           );
2584                       }
2585                       return Err(err);
2586
2587                     }
2588                     _ => {
2589                         // FIXME Could factor this out into non_fatal_unexpected or something.
2590                         let actual = self.this_token_to_string();
2591                         self.span_err(self.span, &format!("unexpected token: `{}`", actual));
2592                     }
2593                 }
2594                 continue;
2595             }
2596             if self.expr_is_complete(&e) { break; }
2597             match self.token {
2598                 // expr(...)
2599                 token::OpenDelim(token::Paren) => {
2600                     let seq = self.parse_unspanned_seq(
2601                         &token::OpenDelim(token::Paren),
2602                         &token::CloseDelim(token::Paren),
2603                         SeqSep::trailing_allowed(token::Comma),
2604                         |p| Ok(p.parse_expr()?)
2605                     ).map(|es| {
2606                         let nd = self.mk_call(e, es);
2607                         let hi = self.prev_span;
2608                         self.mk_expr(lo.to(hi), nd, ThinVec::new())
2609                     });
2610                     e = self.recover_seq_parse_error(token::Paren, lo, seq);
2611                 }
2612
2613                 // expr[...]
2614                 // Could be either an index expression or a slicing expression.
2615                 token::OpenDelim(token::Bracket) => {
2616                     self.bump();
2617                     let ix = self.parse_expr()?;
2618                     hi = self.span;
2619                     self.expect(&token::CloseDelim(token::Bracket))?;
2620                     let index = self.mk_index(e, ix);
2621                     e = self.mk_expr(lo.to(hi), index, ThinVec::new())
2622                 }
2623                 _ => return Ok(e)
2624             }
2625         }
2626         return Ok(e);
2627     }
2628
2629     crate fn process_potential_macro_variable(&mut self) {
2630         let (token, span) = match self.token {
2631             token::Dollar if self.span.ctxt() != syntax_pos::hygiene::SyntaxContext::empty() &&
2632                              self.look_ahead(1, |t| t.is_ident()) => {
2633                 self.bump();
2634                 let name = match self.token {
2635                     token::Ident(ident, _) => ident,
2636                     _ => unreachable!()
2637                 };
2638                 let mut err = self.fatal(&format!("unknown macro variable `{}`", name));
2639                 err.span_label(self.span, "unknown macro variable");
2640                 err.emit();
2641                 self.bump();
2642                 return
2643             }
2644             token::Interpolated(ref nt) => {
2645                 self.meta_var_span = Some(self.span);
2646                 // Interpolated identifier and lifetime tokens are replaced with usual identifier
2647                 // and lifetime tokens, so the former are never encountered during normal parsing.
2648                 match **nt {
2649                     token::NtIdent(ident, is_raw) => (token::Ident(ident, is_raw), ident.span),
2650                     token::NtLifetime(ident) => (token::Lifetime(ident), ident.span),
2651                     _ => return,
2652                 }
2653             }
2654             _ => return,
2655         };
2656         self.token = token;
2657         self.span = span;
2658     }
2659
2660     /// Parses a single token tree from the input.
2661     crate fn parse_token_tree(&mut self) -> TokenTree {
2662         match self.token {
2663             token::OpenDelim(..) => {
2664                 let frame = mem::replace(&mut self.token_cursor.frame,
2665                                          self.token_cursor.stack.pop().unwrap());
2666                 self.span = frame.span.entire();
2667                 self.bump();
2668                 TokenTree::Delimited(
2669                     frame.span,
2670                     frame.delim,
2671                     frame.tree_cursor.stream.into(),
2672                 )
2673             },
2674             token::CloseDelim(_) | token::Eof => unreachable!(),
2675             _ => {
2676                 let (token, span) = (mem::replace(&mut self.token, token::Whitespace), self.span);
2677                 self.bump();
2678                 TokenTree::Token(span, token)
2679             }
2680         }
2681     }
2682
2683     // parse a stream of tokens into a list of TokenTree's,
2684     // up to EOF.
2685     pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2686         let mut tts = Vec::new();
2687         while self.token != token::Eof {
2688             tts.push(self.parse_token_tree());
2689         }
2690         Ok(tts)
2691     }
2692
2693     pub fn parse_tokens(&mut self) -> TokenStream {
2694         let mut result = Vec::new();
2695         loop {
2696             match self.token {
2697                 token::Eof | token::CloseDelim(..) => break,
2698                 _ => result.push(self.parse_token_tree().into()),
2699             }
2700         }
2701         TokenStream::new(result)
2702     }
2703
2704     /// Parse a prefix-unary-operator expr
2705     fn parse_prefix_expr(&mut self,
2706                              already_parsed_attrs: Option<ThinVec<Attribute>>)
2707                              -> PResult<'a, P<Expr>> {
2708         let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2709         let lo = self.span;
2710         // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2711         let (hi, ex) = match self.token {
2712             token::Not => {
2713                 self.bump();
2714                 let e = self.parse_prefix_expr(None);
2715                 let (span, e) = self.interpolated_or_expr_span(e)?;
2716                 (lo.to(span), self.mk_unary(UnOp::Not, e))
2717             }
2718             // Suggest `!` for bitwise negation when encountering a `~`
2719             token::Tilde => {
2720                 self.bump();
2721                 let e = self.parse_prefix_expr(None);
2722                 let (span, e) = self.interpolated_or_expr_span(e)?;
2723                 let span_of_tilde = lo;
2724                 let mut err = self.diagnostic()
2725                     .struct_span_err(span_of_tilde, "`~` cannot be used as a unary operator");
2726                 err.span_suggestion_short(
2727                     span_of_tilde,
2728                     "use `!` to perform bitwise negation",
2729                     "!".to_owned(),
2730                     Applicability::MachineApplicable
2731                 );
2732                 err.emit();
2733                 (lo.to(span), self.mk_unary(UnOp::Not, e))
2734             }
2735             token::BinOp(token::Minus) => {
2736                 self.bump();
2737                 let e = self.parse_prefix_expr(None);
2738                 let (span, e) = self.interpolated_or_expr_span(e)?;
2739                 (lo.to(span), self.mk_unary(UnOp::Neg, e))
2740             }
2741             token::BinOp(token::Star) => {
2742                 self.bump();
2743                 let e = self.parse_prefix_expr(None);
2744                 let (span, e) = self.interpolated_or_expr_span(e)?;
2745                 (lo.to(span), self.mk_unary(UnOp::Deref, e))
2746             }
2747             token::BinOp(token::And) | token::AndAnd => {
2748                 self.expect_and()?;
2749                 let m = self.parse_mutability();
2750                 let e = self.parse_prefix_expr(None);
2751                 let (span, e) = self.interpolated_or_expr_span(e)?;
2752                 (lo.to(span), ExprKind::AddrOf(m, e))
2753             }
2754             token::Ident(..) if self.token.is_keyword(kw::Box) => {
2755                 self.bump();
2756                 let e = self.parse_prefix_expr(None);
2757                 let (span, e) = self.interpolated_or_expr_span(e)?;
2758                 (lo.to(span), ExprKind::Box(e))
2759             }
2760             token::Ident(..) if self.token.is_ident_named(sym::not) => {
2761                 // `not` is just an ordinary identifier in Rust-the-language,
2762                 // but as `rustc`-the-compiler, we can issue clever diagnostics
2763                 // for confused users who really want to say `!`
2764                 let token_cannot_continue_expr = |t: &token::Token| match *t {
2765                     // These tokens can start an expression after `!`, but
2766                     // can't continue an expression after an ident
2767                     token::Ident(ident, is_raw) => token::ident_can_begin_expr(ident, is_raw),
2768                     token::Literal(..) | token::Pound => true,
2769                     token::Interpolated(ref nt) => match **nt {
2770                         token::NtIdent(..) | token::NtExpr(..) |
2771                         token::NtBlock(..) | token::NtPath(..) => true,
2772                         _ => false,
2773                     },
2774                     _ => false
2775                 };
2776                 let cannot_continue_expr = self.look_ahead(1, token_cannot_continue_expr);
2777                 if cannot_continue_expr {
2778                     self.bump();
2779                     // Emit the error ...
2780                     let mut err = self.diagnostic()
2781                         .struct_span_err(self.span,
2782                                          &format!("unexpected {} after identifier",
2783                                                   self.this_token_descr()));
2784                     // span the `not` plus trailing whitespace to avoid
2785                     // trailing whitespace after the `!` in our suggestion
2786                     let to_replace = self.sess.source_map()
2787                         .span_until_non_whitespace(lo.to(self.span));
2788                     err.span_suggestion_short(
2789                         to_replace,
2790                         "use `!` to perform logical negation",
2791                         "!".to_owned(),
2792                         Applicability::MachineApplicable
2793                     );
2794                     err.emit();
2795                     // â€”and recover! (just as if we were in the block
2796                     // for the `token::Not` arm)
2797                     let e = self.parse_prefix_expr(None);
2798                     let (span, e) = self.interpolated_or_expr_span(e)?;
2799                     (lo.to(span), self.mk_unary(UnOp::Not, e))
2800                 } else {
2801                     return self.parse_dot_or_call_expr(Some(attrs));
2802                 }
2803             }
2804             _ => { return self.parse_dot_or_call_expr(Some(attrs)); }
2805         };
2806         return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2807     }
2808
2809     /// Parses an associative expression.
2810     ///
2811     /// This parses an expression accounting for associativity and precedence of the operators in
2812     /// the expression.
2813     #[inline]
2814     fn parse_assoc_expr(&mut self,
2815                             already_parsed_attrs: Option<ThinVec<Attribute>>)
2816                             -> PResult<'a, P<Expr>> {
2817         self.parse_assoc_expr_with(0, already_parsed_attrs.into())
2818     }
2819
2820     /// Parses an associative expression with operators of at least `min_prec` precedence.
2821     fn parse_assoc_expr_with(&mut self,
2822                                  min_prec: usize,
2823                                  lhs: LhsExpr)
2824                                  -> PResult<'a, P<Expr>> {
2825         let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
2826             expr
2827         } else {
2828             let attrs = match lhs {
2829                 LhsExpr::AttributesParsed(attrs) => Some(attrs),
2830                 _ => None,
2831             };
2832             if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token) {
2833                 return self.parse_prefix_range_expr(attrs);
2834             } else {
2835                 self.parse_prefix_expr(attrs)?
2836             }
2837         };
2838
2839         match (self.expr_is_complete(&lhs), AssocOp::from_token(&self.token)) {
2840             (true, None) => {
2841                 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
2842                 return Ok(lhs);
2843             }
2844             (false, _) => {} // continue parsing the expression
2845             // An exhaustive check is done in the following block, but these are checked first
2846             // because they *are* ambiguous but also reasonable looking incorrect syntax, so we
2847             // want to keep their span info to improve diagnostics in these cases in a later stage.
2848             (true, Some(AssocOp::Multiply)) | // `{ 42 } *foo = bar;` or `{ 42 } * 3`
2849             (true, Some(AssocOp::Subtract)) | // `{ 42 } -5`
2850             (true, Some(AssocOp::Add)) => { // `{ 42 } + 42
2851                 // These cases are ambiguous and can't be identified in the parser alone
2852                 let sp = self.sess.source_map().start_point(self.span);
2853                 self.sess.ambiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span);
2854                 return Ok(lhs);
2855             }
2856             (true, Some(ref op)) if !op.can_continue_expr_unambiguously() => {
2857                 return Ok(lhs);
2858             }
2859             (true, Some(_)) => {
2860                 // We've found an expression that would be parsed as a statement, but the next
2861                 // token implies this should be parsed as an expression.
2862                 // For example: `if let Some(x) = x { x } else { 0 } / 2`
2863                 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &format!(
2864                     "expected expression, found `{}`",
2865                     pprust::token_to_string(&self.token),
2866                 ));
2867                 err.span_label(self.span, "expected expression");
2868                 self.sess.expr_parentheses_needed(
2869                     &mut err,
2870                     lhs.span,
2871                     Some(pprust::expr_to_string(&lhs),
2872                 ));
2873                 err.emit();
2874             }
2875         }
2876         self.expected_tokens.push(TokenType::Operator);
2877         while let Some(op) = AssocOp::from_token(&self.token) {
2878
2879             // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
2880             // it refers to. Interpolated identifiers are unwrapped early and never show up here
2881             // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
2882             // it as "interpolated", it doesn't change the answer for non-interpolated idents.
2883             let lhs_span = match (self.prev_token_kind, &lhs.node) {
2884                 (PrevTokenKind::Interpolated, _) => self.prev_span,
2885                 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
2886                     if path.segments.len() == 1 => self.prev_span,
2887                 _ => lhs.span,
2888             };
2889
2890             let cur_op_span = self.span;
2891             let restrictions = if op.is_assign_like() {
2892                 self.restrictions & Restrictions::NO_STRUCT_LITERAL
2893             } else {
2894                 self.restrictions
2895             };
2896             let prec = op.precedence();
2897             if prec < min_prec {
2898                 break;
2899             }
2900             // Check for deprecated `...` syntax
2901             if self.token == token::DotDotDot && op == AssocOp::DotDotEq {
2902                 self.err_dotdotdot_syntax(self.span);
2903             }
2904
2905             self.bump();
2906             if op.is_comparison() {
2907                 self.check_no_chained_comparison(&lhs, &op);
2908             }
2909             // Special cases:
2910             if op == AssocOp::As {
2911                 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
2912                 continue
2913             } else if op == AssocOp::Colon {
2914                 let maybe_path = self.could_ascription_be_path(&lhs.node);
2915                 let next_sp = self.span;
2916
2917                 lhs = match self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type) {
2918                     Ok(lhs) => lhs,
2919                     Err(mut err) => {
2920                         self.bad_type_ascription(
2921                             &mut err,
2922                             lhs_span,
2923                             cur_op_span,
2924                             next_sp,
2925                             maybe_path,
2926                         );
2927                         return Err(err);
2928                     }
2929                 };
2930                 continue
2931             } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
2932                 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
2933                 // generalise it to the Fixity::None code.
2934                 //
2935                 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
2936                 // two variants are handled with `parse_prefix_range_expr` call above.
2937                 let rhs = if self.is_at_start_of_range_notation_rhs() {
2938                     Some(self.parse_assoc_expr_with(prec + 1, LhsExpr::NotYetParsed)?)
2939                 } else {
2940                     None
2941                 };
2942                 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
2943                     x.span
2944                 } else {
2945                     cur_op_span
2946                 });
2947                 let limits = if op == AssocOp::DotDot {
2948                     RangeLimits::HalfOpen
2949                 } else {
2950                     RangeLimits::Closed
2951                 };
2952
2953                 let r = self.mk_range(Some(lhs), rhs, limits)?;
2954                 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
2955                 break
2956             }
2957
2958             let fixity = op.fixity();
2959             let prec_adjustment = match fixity {
2960                 Fixity::Right => 0,
2961                 Fixity::Left => 1,
2962                 // We currently have no non-associative operators that are not handled above by
2963                 // the special cases. The code is here only for future convenience.
2964                 Fixity::None => 1,
2965             };
2966             let rhs = self.with_res(
2967                 restrictions - Restrictions::STMT_EXPR,
2968                 |this| this.parse_assoc_expr_with(prec + prec_adjustment, LhsExpr::NotYetParsed)
2969             )?;
2970
2971             // Make sure that the span of the parent node is larger than the span of lhs and rhs,
2972             // including the attributes.
2973             let lhs_span = lhs
2974                 .attrs
2975                 .iter()
2976                 .filter(|a| a.style == AttrStyle::Outer)
2977                 .next()
2978                 .map_or(lhs_span, |a| a.span);
2979             let span = lhs_span.to(rhs.span);
2980             lhs = match op {
2981                 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
2982                 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
2983                 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
2984                 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
2985                 AssocOp::Greater | AssocOp::GreaterEqual => {
2986                     let ast_op = op.to_ast_binop().unwrap();
2987                     let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs);
2988                     self.mk_expr(span, binary, ThinVec::new())
2989                 }
2990                 AssocOp::Assign => self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
2991                 AssocOp::AssignOp(k) => {
2992                     let aop = match k {
2993                         token::Plus =>    BinOpKind::Add,
2994                         token::Minus =>   BinOpKind::Sub,
2995                         token::Star =>    BinOpKind::Mul,
2996                         token::Slash =>   BinOpKind::Div,
2997                         token::Percent => BinOpKind::Rem,
2998                         token::Caret =>   BinOpKind::BitXor,
2999                         token::And =>     BinOpKind::BitAnd,
3000                         token::Or =>      BinOpKind::BitOr,
3001                         token::Shl =>     BinOpKind::Shl,
3002                         token::Shr =>     BinOpKind::Shr,
3003                     };
3004                     let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs);
3005                     self.mk_expr(span, aopexpr, ThinVec::new())
3006                 }
3007                 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
3008                     self.bug("AssocOp should have been handled by special case")
3009                 }
3010             };
3011
3012             if let Fixity::None = fixity { break }
3013         }
3014         Ok(lhs)
3015     }
3016
3017     fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
3018                            expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
3019                            -> PResult<'a, P<Expr>> {
3020         let mk_expr = |this: &mut Self, rhs: P<Ty>| {
3021             this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
3022         };
3023
3024         // Save the state of the parser before parsing type normally, in case there is a
3025         // LessThan comparison after this cast.
3026         let parser_snapshot_before_type = self.clone();
3027         match self.parse_ty_no_plus() {
3028             Ok(rhs) => {
3029                 Ok(mk_expr(self, rhs))
3030             }
3031             Err(mut type_err) => {
3032                 // Rewind to before attempting to parse the type with generics, to recover
3033                 // from situations like `x as usize < y` in which we first tried to parse
3034                 // `usize < y` as a type with generic arguments.
3035                 let parser_snapshot_after_type = self.clone();
3036                 mem::replace(self, parser_snapshot_before_type);
3037
3038                 match self.parse_path(PathStyle::Expr) {
3039                     Ok(path) => {
3040                         let (op_noun, op_verb) = match self.token {
3041                             token::Lt => ("comparison", "comparing"),
3042                             token::BinOp(token::Shl) => ("shift", "shifting"),
3043                             _ => {
3044                                 // We can end up here even without `<` being the next token, for
3045                                 // example because `parse_ty_no_plus` returns `Err` on keywords,
3046                                 // but `parse_path` returns `Ok` on them due to error recovery.
3047                                 // Return original error and parser state.
3048                                 mem::replace(self, parser_snapshot_after_type);
3049                                 return Err(type_err);
3050                             }
3051                         };
3052
3053                         // Successfully parsed the type path leaving a `<` yet to parse.
3054                         type_err.cancel();
3055
3056                         // Report non-fatal diagnostics, keep `x as usize` as an expression
3057                         // in AST and continue parsing.
3058                         let msg = format!("`<` is interpreted as a start of generic \
3059                                            arguments for `{}`, not a {}", path, op_noun);
3060                         let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &msg);
3061                         err.span_label(self.look_ahead_span(1).to(parser_snapshot_after_type.span),
3062                                        "interpreted as generic arguments");
3063                         err.span_label(self.span, format!("not interpreted as {}", op_noun));
3064
3065                         let expr = mk_expr(self, P(Ty {
3066                             span: path.span,
3067                             node: TyKind::Path(None, path),
3068                             id: ast::DUMMY_NODE_ID
3069                         }));
3070
3071                         let expr_str = self.sess.source_map().span_to_snippet(expr.span)
3072                                                 .unwrap_or_else(|_| pprust::expr_to_string(&expr));
3073                         err.span_suggestion(
3074                             expr.span,
3075                             &format!("try {} the cast value", op_verb),
3076                             format!("({})", expr_str),
3077                             Applicability::MachineApplicable
3078                         );
3079                         err.emit();
3080
3081                         Ok(expr)
3082                     }
3083                     Err(mut path_err) => {
3084                         // Couldn't parse as a path, return original error and parser state.
3085                         path_err.cancel();
3086                         mem::replace(self, parser_snapshot_after_type);
3087                         Err(type_err)
3088                     }
3089                 }
3090             }
3091         }
3092     }
3093
3094     /// Parse prefix-forms of range notation: `..expr`, `..`, `..=expr`
3095     fn parse_prefix_range_expr(&mut self,
3096                                already_parsed_attrs: Option<ThinVec<Attribute>>)
3097                                -> PResult<'a, P<Expr>> {
3098         // Check for deprecated `...` syntax
3099         if self.token == token::DotDotDot {
3100             self.err_dotdotdot_syntax(self.span);
3101         }
3102
3103         debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token),
3104                       "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
3105                       self.token);
3106         let tok = self.token.clone();
3107         let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3108         let lo = self.span;
3109         let mut hi = self.span;
3110         self.bump();
3111         let opt_end = if self.is_at_start_of_range_notation_rhs() {
3112             // RHS must be parsed with more associativity than the dots.
3113             let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
3114             Some(self.parse_assoc_expr_with(next_prec,
3115                                             LhsExpr::NotYetParsed)
3116                 .map(|x|{
3117                     hi = x.span;
3118                     x
3119                 })?)
3120         } else {
3121             None
3122         };
3123         let limits = if tok == token::DotDot {
3124             RangeLimits::HalfOpen
3125         } else {
3126             RangeLimits::Closed
3127         };
3128
3129         let r = self.mk_range(None, opt_end, limits)?;
3130         Ok(self.mk_expr(lo.to(hi), r, attrs))
3131     }
3132
3133     fn is_at_start_of_range_notation_rhs(&self) -> bool {
3134         if self.token.can_begin_expr() {
3135             // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
3136             if self.token == token::OpenDelim(token::Brace) {
3137                 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
3138             }
3139             true
3140         } else {
3141             false
3142         }
3143     }
3144
3145     /// Parses an `if` or `if let` expression (`if` token already eaten).
3146     fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3147         if self.check_keyword(kw::Let) {
3148             return self.parse_if_let_expr(attrs);
3149         }
3150         let lo = self.prev_span;
3151         let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3152
3153         // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
3154         // verify that the last statement is either an implicit return (no `;`) or an explicit
3155         // return. This won't catch blocks with an explicit `return`, but that would be caught by
3156         // the dead code lint.
3157         if self.eat_keyword(kw::Else) || !cond.returns() {
3158             let sp = self.sess.source_map().next_point(lo);
3159             let mut err = self.diagnostic()
3160                 .struct_span_err(sp, "missing condition for `if` statemement");
3161             err.span_label(sp, "expected if condition here");
3162             return Err(err)
3163         }
3164         let not_block = self.token != token::OpenDelim(token::Brace);
3165         let thn = self.parse_block().map_err(|mut err| {
3166             if not_block {
3167                 err.span_label(lo, "this `if` statement has a condition, but no block");
3168             }
3169             err
3170         })?;
3171         let mut els: Option<P<Expr>> = None;
3172         let mut hi = thn.span;
3173         if self.eat_keyword(kw::Else) {
3174             let elexpr = self.parse_else_expr()?;
3175             hi = elexpr.span;
3176             els = Some(elexpr);
3177         }
3178         Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
3179     }
3180
3181     /// Parses an `if let` expression (`if` token already eaten).
3182     fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
3183                              -> PResult<'a, P<Expr>> {
3184         let lo = self.prev_span;
3185         self.expect_keyword(kw::Let)?;
3186         let pats = self.parse_pats()?;
3187         self.expect(&token::Eq)?;
3188         let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3189         let thn = self.parse_block()?;
3190         let (hi, els) = if self.eat_keyword(kw::Else) {
3191             let expr = self.parse_else_expr()?;
3192             (expr.span, Some(expr))
3193         } else {
3194             (thn.span, None)
3195         };
3196         Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pats, expr, thn, els), attrs))
3197     }
3198
3199     /// Parses `move |args| expr`.
3200     fn parse_lambda_expr(&mut self,
3201                              attrs: ThinVec<Attribute>)
3202                              -> PResult<'a, P<Expr>>
3203     {
3204         let lo = self.span;
3205         let movability = if self.eat_keyword(kw::Static) {
3206             Movability::Static
3207         } else {
3208             Movability::Movable
3209         };
3210         let asyncness = if self.span.rust_2018() {
3211             self.parse_asyncness()
3212         } else {
3213             IsAsync::NotAsync
3214         };
3215         let capture_clause = if self.eat_keyword(kw::Move) {
3216             CaptureBy::Value
3217         } else {
3218             CaptureBy::Ref
3219         };
3220         let decl = self.parse_fn_block_decl()?;
3221         let decl_hi = self.prev_span;
3222         let body = match decl.output {
3223             FunctionRetTy::Default(_) => {
3224                 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
3225                 self.parse_expr_res(restrictions, None)?
3226             },
3227             _ => {
3228                 // If an explicit return type is given, require a
3229                 // block to appear (RFC 968).
3230                 let body_lo = self.span;
3231                 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, ThinVec::new())?
3232             }
3233         };
3234
3235         Ok(self.mk_expr(
3236             lo.to(body.span),
3237             ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
3238             attrs))
3239     }
3240
3241     // `else` token already eaten
3242     fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3243         if self.eat_keyword(kw::If) {
3244             return self.parse_if_expr(ThinVec::new());
3245         } else {
3246             let blk = self.parse_block()?;
3247             return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None), ThinVec::new()));
3248         }
3249     }
3250
3251     /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3252     fn parse_for_expr(&mut self, opt_label: Option<Label>,
3253                           span_lo: Span,
3254                           mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3255         // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3256
3257         let pat = self.parse_top_level_pat()?;
3258         if !self.eat_keyword(kw::In) {
3259             let in_span = self.prev_span.between(self.span);
3260             let mut err = self.sess.span_diagnostic
3261                 .struct_span_err(in_span, "missing `in` in `for` loop");
3262             err.span_suggestion_short(
3263                 in_span, "try adding `in` here", " in ".into(),
3264                 // has been misleading, at least in the past (closed Issue #48492)
3265                 Applicability::MaybeIncorrect
3266             );
3267             err.emit();
3268         }
3269         let in_span = self.prev_span;
3270         self.check_for_for_in_in_typo(in_span);
3271         let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3272         let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3273         attrs.extend(iattrs);
3274
3275         let hi = self.prev_span;
3276         Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_label), attrs))
3277     }
3278
3279     /// Parses a `while` or `while let` expression (`while` token already eaten).
3280     fn parse_while_expr(&mut self, opt_label: Option<Label>,
3281                             span_lo: Span,
3282                             mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3283         if self.token.is_keyword(kw::Let) {
3284             return self.parse_while_let_expr(opt_label, span_lo, attrs);
3285         }
3286         let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3287         let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3288         attrs.extend(iattrs);
3289         let span = span_lo.to(body.span);
3290         return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_label), attrs));
3291     }
3292
3293     /// Parses a `while let` expression (`while` token already eaten).
3294     fn parse_while_let_expr(&mut self, opt_label: Option<Label>,
3295                                 span_lo: Span,
3296                                 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3297         self.expect_keyword(kw::Let)?;
3298         let pats = self.parse_pats()?;
3299         self.expect(&token::Eq)?;
3300         let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3301         let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3302         attrs.extend(iattrs);
3303         let span = span_lo.to(body.span);
3304         return Ok(self.mk_expr(span, ExprKind::WhileLet(pats, expr, body, opt_label), attrs));
3305     }
3306
3307     // parse `loop {...}`, `loop` token already eaten
3308     fn parse_loop_expr(&mut self, opt_label: Option<Label>,
3309                            span_lo: Span,
3310                            mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3311         let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3312         attrs.extend(iattrs);
3313         let span = span_lo.to(body.span);
3314         Ok(self.mk_expr(span, ExprKind::Loop(body, opt_label), attrs))
3315     }
3316
3317     /// Parses an `async move {...}` expression.
3318     pub fn parse_async_block(&mut self, mut attrs: ThinVec<Attribute>)
3319         -> PResult<'a, P<Expr>>
3320     {
3321         let span_lo = self.span;
3322         self.expect_keyword(kw::Async)?;
3323         let capture_clause = if self.eat_keyword(kw::Move) {
3324             CaptureBy::Value
3325         } else {
3326             CaptureBy::Ref
3327         };
3328         let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3329         attrs.extend(iattrs);
3330         Ok(self.mk_expr(
3331             span_lo.to(body.span),
3332             ExprKind::Async(capture_clause, ast::DUMMY_NODE_ID, body), attrs))
3333     }
3334
3335     /// Parses a `try {...}` expression (`try` token already eaten).
3336     fn parse_try_block(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
3337         -> PResult<'a, P<Expr>>
3338     {
3339         let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3340         attrs.extend(iattrs);
3341         if self.eat_keyword(kw::Catch) {
3342             let mut error = self.struct_span_err(self.prev_span,
3343                                                  "keyword `catch` cannot follow a `try` block");
3344             error.help("try using `match` on the result of the `try` block instead");
3345             error.emit();
3346             Err(error)
3347         } else {
3348             Ok(self.mk_expr(span_lo.to(body.span), ExprKind::TryBlock(body), attrs))
3349         }
3350     }
3351
3352     // `match` token already eaten
3353     fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3354         let match_span = self.prev_span;
3355         let lo = self.prev_span;
3356         let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL,
3357                                                None)?;
3358         if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
3359             if self.token == token::Token::Semi {
3360                 e.span_suggestion_short(
3361                     match_span,
3362                     "try removing this `match`",
3363                     String::new(),
3364                     Applicability::MaybeIncorrect // speculative
3365                 );
3366             }
3367             return Err(e)
3368         }
3369         attrs.extend(self.parse_inner_attributes()?);
3370
3371         let mut arms: Vec<Arm> = Vec::new();
3372         while self.token != token::CloseDelim(token::Brace) {
3373             match self.parse_arm() {
3374                 Ok(arm) => arms.push(arm),
3375                 Err(mut e) => {
3376                     // Recover by skipping to the end of the block.
3377                     e.emit();
3378                     self.recover_stmt();
3379                     let span = lo.to(self.span);
3380                     if self.token == token::CloseDelim(token::Brace) {
3381                         self.bump();
3382                     }
3383                     return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
3384                 }
3385             }
3386         }
3387         let hi = self.span;
3388         self.bump();
3389         return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
3390     }
3391
3392     crate fn parse_arm(&mut self) -> PResult<'a, Arm> {
3393         let attrs = self.parse_outer_attributes()?;
3394         let lo = self.span;
3395         let pats = self.parse_pats()?;
3396         let guard = if self.eat_keyword(kw::If) {
3397             Some(Guard::If(self.parse_expr()?))
3398         } else {
3399             None
3400         };
3401         let arrow_span = self.span;
3402         self.expect(&token::FatArrow)?;
3403         let arm_start_span = self.span;
3404
3405         let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)
3406             .map_err(|mut err| {
3407                 err.span_label(arrow_span, "while parsing the `match` arm starting here");
3408                 err
3409             })?;
3410
3411         let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
3412             && self.token != token::CloseDelim(token::Brace);
3413
3414         let hi = self.span;
3415
3416         if require_comma {
3417             let cm = self.sess.source_map();
3418             self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])
3419                 .map_err(|mut err| {
3420                     match (cm.span_to_lines(expr.span), cm.span_to_lines(arm_start_span)) {
3421                         (Ok(ref expr_lines), Ok(ref arm_start_lines))
3422                         if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
3423                             && expr_lines.lines.len() == 2
3424                             && self.token == token::FatArrow => {
3425                             // We check whether there's any trailing code in the parse span,
3426                             // if there isn't, we very likely have the following:
3427                             //
3428                             // X |     &Y => "y"
3429                             //   |        --    - missing comma
3430                             //   |        |
3431                             //   |        arrow_span
3432                             // X |     &X => "x"
3433                             //   |      - ^^ self.span
3434                             //   |      |
3435                             //   |      parsed until here as `"y" & X`
3436                             err.span_suggestion_short(
3437                                 cm.next_point(arm_start_span),
3438                                 "missing a comma here to end this `match` arm",
3439                                 ",".to_owned(),
3440                                 Applicability::MachineApplicable
3441                             );
3442                         }
3443                         _ => {
3444                             err.span_label(arrow_span,
3445                                            "while parsing the `match` arm starting here");
3446                         }
3447                     }
3448                     err
3449                 })?;
3450         } else {
3451             self.eat(&token::Comma);
3452         }
3453
3454         Ok(ast::Arm {
3455             attrs,
3456             pats,
3457             guard,
3458             body: expr,
3459             span: lo.to(hi),
3460         })
3461     }
3462
3463     /// Parses an expression.
3464     #[inline]
3465     pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3466         self.parse_expr_res(Restrictions::empty(), None)
3467     }
3468
3469     /// Evaluates the closure with restrictions in place.
3470     ///
3471     /// Afters the closure is evaluated, restrictions are reset.
3472     fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
3473         where F: FnOnce(&mut Self) -> T
3474     {
3475         let old = self.restrictions;
3476         self.restrictions = r;
3477         let r = f(self);
3478         self.restrictions = old;
3479         return r;
3480
3481     }
3482
3483     /// Parses an expression, subject to the given restrictions.
3484     #[inline]
3485     fn parse_expr_res(&mut self, r: Restrictions,
3486                           already_parsed_attrs: Option<ThinVec<Attribute>>)
3487                           -> PResult<'a, P<Expr>> {
3488         self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3489     }
3490
3491     /// Parses the RHS of a local variable declaration (e.g., '= 14;').
3492     fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
3493         if self.eat(&token::Eq) {
3494             Ok(Some(self.parse_expr()?))
3495         } else if skip_eq {
3496             Ok(Some(self.parse_expr()?))
3497         } else {
3498             Ok(None)
3499         }
3500     }
3501
3502     /// Parses patterns, separated by '|' s.
3503     fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3504         // Allow a '|' before the pats (RFC 1925 + RFC 2530)
3505         self.eat(&token::BinOp(token::Or));
3506
3507         let mut pats = Vec::new();
3508         loop {
3509             pats.push(self.parse_top_level_pat()?);
3510
3511             if self.token == token::OrOr {
3512                 let mut err = self.struct_span_err(self.span,
3513                                                    "unexpected token `||` after pattern");
3514                 err.span_suggestion(
3515                     self.span,
3516                     "use a single `|` to specify multiple patterns",
3517                     "|".to_owned(),
3518                     Applicability::MachineApplicable
3519                 );
3520                 err.emit();
3521                 self.bump();
3522             } else if self.eat(&token::BinOp(token::Or)) {
3523                 // This is a No-op. Continue the loop to parse the next
3524                 // pattern.
3525             } else {
3526                 return Ok(pats);
3527             }
3528         };
3529     }
3530
3531     // Parses a parenthesized list of patterns like
3532     // `()`, `(p)`, `(p,)`, `(p, q)`, or `(p, .., q)`. Returns:
3533     // - a vector of the patterns that were parsed
3534     // - an option indicating the index of the `..` element
3535     // - a boolean indicating whether a trailing comma was present.
3536     // Trailing commas are significant because (p) and (p,) are different patterns.
3537     fn parse_parenthesized_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
3538         self.expect(&token::OpenDelim(token::Paren))?;
3539         let result = match self.parse_pat_list() {
3540             Ok(result) => result,
3541             Err(mut err) => { // recover from parse error in tuple pattern list
3542                 err.emit();
3543                 self.consume_block(token::Paren);
3544                 return Ok((vec![], Some(0), false));
3545             }
3546         };
3547         self.expect(&token::CloseDelim(token::Paren))?;
3548         Ok(result)
3549     }
3550
3551     fn parse_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
3552         let mut fields = Vec::new();
3553         let mut ddpos = None;
3554         let mut prev_dd_sp = None;
3555         let mut trailing_comma = false;
3556         loop {
3557             if self.eat(&token::DotDot) {
3558                 if ddpos.is_none() {
3559                     ddpos = Some(fields.len());
3560                     prev_dd_sp = Some(self.prev_span);
3561                 } else {
3562                     // Emit a friendly error, ignore `..` and continue parsing
3563                     let mut err = self.struct_span_err(
3564                         self.prev_span,
3565                         "`..` can only be used once per tuple or tuple struct pattern",
3566                     );
3567                     err.span_label(self.prev_span, "can only be used once per pattern");
3568                     if let Some(sp) = prev_dd_sp {
3569                         err.span_label(sp, "previously present here");
3570                     }
3571                     err.emit();
3572                 }
3573             } else if !self.check(&token::CloseDelim(token::Paren)) {
3574                 fields.push(self.parse_pat(None)?);
3575             } else {
3576                 break
3577             }
3578
3579             trailing_comma = self.eat(&token::Comma);
3580             if !trailing_comma {
3581                 break
3582             }
3583         }
3584
3585         if ddpos == Some(fields.len()) && trailing_comma {
3586             // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
3587             let msg = "trailing comma is not permitted after `..`";
3588             self.struct_span_err(self.prev_span, msg)
3589                 .span_label(self.prev_span, msg)
3590                 .emit();
3591         }
3592
3593         Ok((fields, ddpos, trailing_comma))
3594     }
3595
3596     fn parse_pat_vec_elements(
3597         &mut self,
3598     ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3599         let mut before = Vec::new();
3600         let mut slice = None;
3601         let mut after = Vec::new();
3602         let mut first = true;
3603         let mut before_slice = true;
3604
3605         while self.token != token::CloseDelim(token::Bracket) {
3606             if first {
3607                 first = false;
3608             } else {
3609                 self.expect(&token::Comma)?;
3610
3611                 if self.token == token::CloseDelim(token::Bracket)
3612                         && (before_slice || !after.is_empty()) {
3613                     break
3614                 }
3615             }
3616
3617             if before_slice {
3618                 if self.eat(&token::DotDot) {
3619
3620                     if self.check(&token::Comma) ||
3621                             self.check(&token::CloseDelim(token::Bracket)) {
3622                         slice = Some(P(Pat {
3623                             id: ast::DUMMY_NODE_ID,
3624                             node: PatKind::Wild,
3625                             span: self.prev_span,
3626                         }));
3627                         before_slice = false;
3628                     }
3629                     continue
3630                 }
3631             }
3632
3633             let subpat = self.parse_pat(None)?;
3634             if before_slice && self.eat(&token::DotDot) {
3635                 slice = Some(subpat);
3636                 before_slice = false;
3637             } else if before_slice {
3638                 before.push(subpat);
3639             } else {
3640                 after.push(subpat);
3641             }
3642         }
3643
3644         Ok((before, slice, after))
3645     }
3646
3647     fn parse_pat_field(
3648         &mut self,
3649         lo: Span,
3650         attrs: Vec<Attribute>
3651     ) -> PResult<'a, source_map::Spanned<ast::FieldPat>> {
3652         // Check if a colon exists one ahead. This means we're parsing a fieldname.
3653         let hi;
3654         let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3655             // Parsing a pattern of the form "fieldname: pat"
3656             let fieldname = self.parse_field_name()?;
3657             self.bump();
3658             let pat = self.parse_pat(None)?;
3659             hi = pat.span;
3660             (pat, fieldname, false)
3661         } else {
3662             // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3663             let is_box = self.eat_keyword(kw::Box);
3664             let boxed_span = self.span;
3665             let is_ref = self.eat_keyword(kw::Ref);
3666             let is_mut = self.eat_keyword(kw::Mut);
3667             let fieldname = self.parse_ident()?;
3668             hi = self.prev_span;
3669
3670             let bind_type = match (is_ref, is_mut) {
3671                 (true, true) => BindingMode::ByRef(Mutability::Mutable),
3672                 (true, false) => BindingMode::ByRef(Mutability::Immutable),
3673                 (false, true) => BindingMode::ByValue(Mutability::Mutable),
3674                 (false, false) => BindingMode::ByValue(Mutability::Immutable),
3675             };
3676             let fieldpat = P(Pat {
3677                 id: ast::DUMMY_NODE_ID,
3678                 node: PatKind::Ident(bind_type, fieldname, None),
3679                 span: boxed_span.to(hi),
3680             });
3681
3682             let subpat = if is_box {
3683                 P(Pat {
3684                     id: ast::DUMMY_NODE_ID,
3685                     node: PatKind::Box(fieldpat),
3686                     span: lo.to(hi),
3687                 })
3688             } else {
3689                 fieldpat
3690             };
3691             (subpat, fieldname, true)
3692         };
3693
3694         Ok(source_map::Spanned {
3695             span: lo.to(hi),
3696             node: ast::FieldPat {
3697                 ident: fieldname,
3698                 pat: subpat,
3699                 is_shorthand,
3700                 attrs: attrs.into(),
3701            }
3702         })
3703     }
3704
3705     /// Parses the fields of a struct-like pattern.
3706     fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<source_map::Spanned<ast::FieldPat>>, bool)> {
3707         let mut fields = Vec::new();
3708         let mut etc = false;
3709         let mut ate_comma = true;
3710         let mut delayed_err: Option<DiagnosticBuilder<'a>> = None;
3711         let mut etc_span = None;
3712
3713         while self.token != token::CloseDelim(token::Brace) {
3714             let attrs = self.parse_outer_attributes()?;
3715             let lo = self.span;
3716
3717             // check that a comma comes after every field
3718             if !ate_comma {
3719                 let err = self.struct_span_err(self.prev_span, "expected `,`");
3720                 if let Some(mut delayed) = delayed_err {
3721                     delayed.emit();
3722                 }
3723                 return Err(err);
3724             }
3725             ate_comma = false;
3726
3727             if self.check(&token::DotDot) || self.token == token::DotDotDot {
3728                 etc = true;
3729                 let mut etc_sp = self.span;
3730
3731                 if self.token == token::DotDotDot { // Issue #46718
3732                     // Accept `...` as if it were `..` to avoid further errors
3733                     let mut err = self.struct_span_err(self.span,
3734                                                        "expected field pattern, found `...`");
3735                     err.span_suggestion(
3736                         self.span,
3737                         "to omit remaining fields, use one fewer `.`",
3738                         "..".to_owned(),
3739                         Applicability::MachineApplicable
3740                     );
3741                     err.emit();
3742                 }
3743                 self.bump();  // `..` || `...`
3744
3745                 if self.token == token::CloseDelim(token::Brace) {
3746                     etc_span = Some(etc_sp);
3747                     break;
3748                 }
3749                 let token_str = self.this_token_descr();
3750                 let mut err = self.fatal(&format!("expected `}}`, found {}", token_str));
3751
3752                 err.span_label(self.span, "expected `}`");
3753                 let mut comma_sp = None;
3754                 if self.token == token::Comma { // Issue #49257
3755                     etc_sp = etc_sp.to(self.sess.source_map().span_until_non_whitespace(self.span));
3756                     err.span_label(etc_sp,
3757                                    "`..` must be at the end and cannot have a trailing comma");
3758                     comma_sp = Some(self.span);
3759                     self.bump();
3760                     ate_comma = true;
3761                 }
3762
3763                 etc_span = Some(etc_sp.until(self.span));
3764                 if self.token == token::CloseDelim(token::Brace) {
3765                     // If the struct looks otherwise well formed, recover and continue.
3766                     if let Some(sp) = comma_sp {
3767                         err.span_suggestion_short(
3768                             sp,
3769                             "remove this comma",
3770                             String::new(),
3771                             Applicability::MachineApplicable,
3772                         );
3773                     }
3774                     err.emit();
3775                     break;
3776                 } else if self.token.is_ident() && ate_comma {
3777                     // Accept fields coming after `..,`.
3778                     // This way we avoid "pattern missing fields" errors afterwards.
3779                     // We delay this error until the end in order to have a span for a
3780                     // suggested fix.
3781                     if let Some(mut delayed_err) = delayed_err {
3782                         delayed_err.emit();
3783                         return Err(err);
3784                     } else {
3785                         delayed_err = Some(err);
3786                     }
3787                 } else {
3788                     if let Some(mut err) = delayed_err {
3789                         err.emit();
3790                     }
3791                     return Err(err);
3792                 }
3793             }
3794
3795             fields.push(match self.parse_pat_field(lo, attrs) {
3796                 Ok(field) => field,
3797                 Err(err) => {
3798                     if let Some(mut delayed_err) = delayed_err {
3799                         delayed_err.emit();
3800                     }
3801                     return Err(err);
3802                 }
3803             });
3804             ate_comma = self.eat(&token::Comma);
3805         }
3806
3807         if let Some(mut err) = delayed_err {
3808             if let Some(etc_span) = etc_span {
3809                 err.multipart_suggestion(
3810                     "move the `..` to the end of the field list",
3811                     vec![
3812                         (etc_span, String::new()),
3813                         (self.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
3814                     ],
3815                     Applicability::MachineApplicable,
3816                 );
3817             }
3818             err.emit();
3819         }
3820         return Ok((fields, etc));
3821     }
3822
3823     fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
3824         if self.token.is_path_start() {
3825             let lo = self.span;
3826             let (qself, path) = if self.eat_lt() {
3827                 // Parse a qualified path
3828                 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3829                 (Some(qself), path)
3830             } else {
3831                 // Parse an unqualified path
3832                 (None, self.parse_path(PathStyle::Expr)?)
3833             };
3834             let hi = self.prev_span;
3835             Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
3836         } else {
3837             self.parse_literal_maybe_minus()
3838         }
3839     }
3840
3841     // helper function to decide whether to parse as ident binding or to try to do
3842     // something more complex like range patterns
3843     fn parse_as_ident(&mut self) -> bool {
3844         self.look_ahead(1, |t| match *t {
3845             token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
3846             token::DotDotDot | token::DotDotEq | token::ModSep | token::Not => Some(false),
3847             // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
3848             // range pattern branch
3849             token::DotDot => None,
3850             _ => Some(true),
3851         }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
3852             token::Comma | token::CloseDelim(token::Bracket) => true,
3853             _ => false,
3854         }))
3855     }
3856
3857     /// A wrapper around `parse_pat` with some special error handling for the
3858     /// "top-level" patterns in a match arm, `for` loop, `let`, &c. (in contrast
3859     /// to subpatterns within such).
3860     fn parse_top_level_pat(&mut self) -> PResult<'a, P<Pat>> {
3861         let pat = self.parse_pat(None)?;
3862         if self.token == token::Comma {
3863             // An unexpected comma after a top-level pattern is a clue that the
3864             // user (perhaps more accustomed to some other language) forgot the
3865             // parentheses in what should have been a tuple pattern; return a
3866             // suggestion-enhanced error here rather than choking on the comma
3867             // later.
3868             let comma_span = self.span;
3869             self.bump();
3870             if let Err(mut err) = self.parse_pat_list() {
3871                 // We didn't expect this to work anyway; we just wanted
3872                 // to advance to the end of the comma-sequence so we know
3873                 // the span to suggest parenthesizing
3874                 err.cancel();
3875             }
3876             let seq_span = pat.span.to(self.prev_span);
3877             let mut err = self.struct_span_err(comma_span,
3878                                                "unexpected `,` in pattern");
3879             if let Ok(seq_snippet) = self.sess.source_map().span_to_snippet(seq_span) {
3880                 err.span_suggestion(
3881                     seq_span,
3882                     "try adding parentheses to match on a tuple..",
3883                     format!("({})", seq_snippet),
3884                     Applicability::MachineApplicable
3885                 ).span_suggestion(
3886                     seq_span,
3887                     "..or a vertical bar to match on multiple alternatives",
3888                     format!("{}", seq_snippet.replace(",", " |")),
3889                     Applicability::MachineApplicable
3890                 );
3891             }
3892             return Err(err);
3893         }
3894         Ok(pat)
3895     }
3896
3897     /// Parses a pattern.
3898     pub fn parse_pat(&mut self, expected: Option<&'static str>) -> PResult<'a, P<Pat>> {
3899         self.parse_pat_with_range_pat(true, expected)
3900     }
3901
3902     /// Parses a pattern, with a setting whether modern range patterns (e.g., `a..=b`, `a..b` are
3903     /// allowed).
3904     fn parse_pat_with_range_pat(
3905         &mut self,
3906         allow_range_pat: bool,
3907         expected: Option<&'static str>,
3908     ) -> PResult<'a, P<Pat>> {
3909         maybe_recover_from_interpolated_ty_qpath!(self, true);
3910         maybe_whole!(self, NtPat, |x| x);
3911
3912         let lo = self.span;
3913         let pat;
3914         match self.token {
3915             token::BinOp(token::And) | token::AndAnd => {
3916                 // Parse &pat / &mut pat
3917                 self.expect_and()?;
3918                 let mutbl = self.parse_mutability();
3919                 if let token::Lifetime(ident) = self.token {
3920                     let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern",
3921                                                       ident));
3922                     err.span_label(self.span, "unexpected lifetime");
3923                     return Err(err);
3924                 }
3925                 let subpat = self.parse_pat_with_range_pat(false, expected)?;
3926                 pat = PatKind::Ref(subpat, mutbl);
3927             }
3928             token::OpenDelim(token::Paren) => {
3929                 // Parse (pat,pat,pat,...) as tuple pattern
3930                 let (fields, ddpos, trailing_comma) = self.parse_parenthesized_pat_list()?;
3931                 pat = if fields.len() == 1 && ddpos.is_none() && !trailing_comma {
3932                     PatKind::Paren(fields.into_iter().nth(0).unwrap())
3933                 } else {
3934                     PatKind::Tuple(fields, ddpos)
3935                 };
3936             }
3937             token::OpenDelim(token::Bracket) => {
3938                 // Parse [pat,pat,...] as slice pattern
3939                 self.bump();
3940                 let (before, slice, after) = self.parse_pat_vec_elements()?;
3941                 self.expect(&token::CloseDelim(token::Bracket))?;
3942                 pat = PatKind::Slice(before, slice, after);
3943             }
3944             // At this point, token != &, &&, (, [
3945             _ => if self.eat_keyword(kw::Underscore) {
3946                 // Parse _
3947                 pat = PatKind::Wild;
3948             } else if self.eat_keyword(kw::Mut) {
3949                 // Parse mut ident @ pat / mut ref ident @ pat
3950                 let mutref_span = self.prev_span.to(self.span);
3951                 let binding_mode = if self.eat_keyword(kw::Ref) {
3952                     self.diagnostic()
3953                         .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
3954                         .span_suggestion(
3955                             mutref_span,
3956                             "try switching the order",
3957                             "ref mut".into(),
3958                             Applicability::MachineApplicable
3959                         ).emit();
3960                     BindingMode::ByRef(Mutability::Mutable)
3961                 } else {
3962                     BindingMode::ByValue(Mutability::Mutable)
3963                 };
3964                 pat = self.parse_pat_ident(binding_mode)?;
3965             } else if self.eat_keyword(kw::Ref) {
3966                 // Parse ref ident @ pat / ref mut ident @ pat
3967                 let mutbl = self.parse_mutability();
3968                 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
3969             } else if self.eat_keyword(kw::Box) {
3970                 // Parse box pat
3971                 let subpat = self.parse_pat_with_range_pat(false, None)?;
3972                 pat = PatKind::Box(subpat);
3973             } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
3974                       self.parse_as_ident() {
3975                 // Parse ident @ pat
3976                 // This can give false positives and parse nullary enums,
3977                 // they are dealt with later in resolve
3978                 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
3979                 pat = self.parse_pat_ident(binding_mode)?;
3980             } else if self.token.is_path_start() {
3981                 // Parse pattern starting with a path
3982                 let (qself, path) = if self.eat_lt() {
3983                     // Parse a qualified path
3984                     let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3985                     (Some(qself), path)
3986                 } else {
3987                     // Parse an unqualified path
3988                     (None, self.parse_path(PathStyle::Expr)?)
3989                 };
3990                 match self.token {
3991                     token::Not if qself.is_none() => {
3992                         // Parse macro invocation
3993                         self.bump();
3994                         let (delim, tts) = self.expect_delimited_token_tree()?;
3995                         let mac = respan(lo.to(self.prev_span), Mac_ { path, tts, delim });
3996                         pat = PatKind::Mac(mac);
3997                     }
3998                     token::DotDotDot | token::DotDotEq | token::DotDot => {
3999                         let end_kind = match self.token {
4000                             token::DotDot => RangeEnd::Excluded,
4001                             token::DotDotDot => RangeEnd::Included(RangeSyntax::DotDotDot),
4002                             token::DotDotEq => RangeEnd::Included(RangeSyntax::DotDotEq),
4003                             _ => panic!("can only parse `..`/`...`/`..=` for ranges \
4004                                          (checked above)"),
4005                         };
4006                         let op_span = self.span;
4007                         // Parse range
4008                         let span = lo.to(self.prev_span);
4009                         let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
4010                         self.bump();
4011                         let end = self.parse_pat_range_end()?;
4012                         let op = Spanned { span: op_span, node: end_kind };
4013                         pat = PatKind::Range(begin, end, op);
4014                     }
4015                     token::OpenDelim(token::Brace) => {
4016                         if qself.is_some() {
4017                             let msg = "unexpected `{` after qualified path";
4018                             let mut err = self.fatal(msg);
4019                             err.span_label(self.span, msg);
4020                             return Err(err);
4021                         }
4022                         // Parse struct pattern
4023                         self.bump();
4024                         let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
4025                             e.emit();
4026                             self.recover_stmt();
4027                             (vec![], true)
4028                         });
4029                         self.bump();
4030                         pat = PatKind::Struct(path, fields, etc);
4031                     }
4032                     token::OpenDelim(token::Paren) => {
4033                         if qself.is_some() {
4034                             let msg = "unexpected `(` after qualified path";
4035                             let mut err = self.fatal(msg);
4036                             err.span_label(self.span, msg);
4037                             return Err(err);
4038                         }
4039                         // Parse tuple struct or enum pattern
4040                         let (fields, ddpos, _) = self.parse_parenthesized_pat_list()?;
4041                         pat = PatKind::TupleStruct(path, fields, ddpos)
4042                     }
4043                     _ => pat = PatKind::Path(qself, path),
4044                 }
4045             } else {
4046                 // Try to parse everything else as literal with optional minus
4047                 match self.parse_literal_maybe_minus() {
4048                     Ok(begin) => {
4049                         let op_span = self.span;
4050                         if self.check(&token::DotDot) || self.check(&token::DotDotEq) ||
4051                                 self.check(&token::DotDotDot) {
4052                             let end_kind = if self.eat(&token::DotDotDot) {
4053                                 RangeEnd::Included(RangeSyntax::DotDotDot)
4054                             } else if self.eat(&token::DotDotEq) {
4055                                 RangeEnd::Included(RangeSyntax::DotDotEq)
4056                             } else if self.eat(&token::DotDot) {
4057                                 RangeEnd::Excluded
4058                             } else {
4059                                 panic!("impossible case: we already matched \
4060                                         on a range-operator token")
4061                             };
4062                             let end = self.parse_pat_range_end()?;
4063                             let op = Spanned { span: op_span, node: end_kind };
4064                             pat = PatKind::Range(begin, end, op);
4065                         } else {
4066                             pat = PatKind::Lit(begin);
4067                         }
4068                     }
4069                     Err(mut err) => {
4070                         self.cancel(&mut err);
4071                         let expected = expected.unwrap_or("pattern");
4072                         let msg = format!(
4073                             "expected {}, found {}",
4074                             expected,
4075                             self.this_token_descr(),
4076                         );
4077                         let mut err = self.fatal(&msg);
4078                         err.span_label(self.span, format!("expected {}", expected));
4079                         let sp = self.sess.source_map().start_point(self.span);
4080                         if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
4081                             self.sess.expr_parentheses_needed(&mut err, *sp, None);
4082                         }
4083                         return Err(err);
4084                     }
4085                 }
4086             }
4087         }
4088
4089         let pat = P(Pat { node: pat, span: lo.to(self.prev_span), id: ast::DUMMY_NODE_ID });
4090         let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
4091
4092         if !allow_range_pat {
4093             match pat.node {
4094                 PatKind::Range(
4095                     _, _, Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. }
4096                 ) => {},
4097                 PatKind::Range(..) => {
4098                     let mut err = self.struct_span_err(
4099                         pat.span,
4100                         "the range pattern here has ambiguous interpretation",
4101                     );
4102                     err.span_suggestion(
4103                         pat.span,
4104                         "add parentheses to clarify the precedence",
4105                         format!("({})", pprust::pat_to_string(&pat)),
4106                         // "ambiguous interpretation" implies that we have to be guessing
4107                         Applicability::MaybeIncorrect
4108                     );
4109                     return Err(err);
4110                 }
4111                 _ => {}
4112             }
4113         }
4114
4115         Ok(pat)
4116     }
4117
4118     /// Parses `ident` or `ident @ pat`.
4119     /// used by the copy foo and ref foo patterns to give a good
4120     /// error message when parsing mistakes like `ref foo(a, b)`.
4121     fn parse_pat_ident(&mut self,
4122                        binding_mode: ast::BindingMode)
4123                        -> PResult<'a, PatKind> {
4124         let ident = self.parse_ident()?;
4125         let sub = if self.eat(&token::At) {
4126             Some(self.parse_pat(Some("binding pattern"))?)
4127         } else {
4128             None
4129         };
4130
4131         // just to be friendly, if they write something like
4132         //   ref Some(i)
4133         // we end up here with ( as the current token.  This shortly
4134         // leads to a parse error.  Note that if there is no explicit
4135         // binding mode then we do not end up here, because the lookahead
4136         // will direct us over to parse_enum_variant()
4137         if self.token == token::OpenDelim(token::Paren) {
4138             return Err(self.span_fatal(
4139                 self.prev_span,
4140                 "expected identifier, found enum pattern"))
4141         }
4142
4143         Ok(PatKind::Ident(binding_mode, ident, sub))
4144     }
4145
4146     /// Parses a local variable declaration.
4147     fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
4148         let lo = self.prev_span;
4149         let pat = self.parse_top_level_pat()?;
4150
4151         let (err, ty) = if self.eat(&token::Colon) {
4152             // Save the state of the parser before parsing type normally, in case there is a `:`
4153             // instead of an `=` typo.
4154             let parser_snapshot_before_type = self.clone();
4155             let colon_sp = self.prev_span;
4156             match self.parse_ty() {
4157                 Ok(ty) => (None, Some(ty)),
4158                 Err(mut err) => {
4159                     // Rewind to before attempting to parse the type and continue parsing
4160                     let parser_snapshot_after_type = self.clone();
4161                     mem::replace(self, parser_snapshot_before_type);
4162
4163                     let snippet = self.sess.source_map().span_to_snippet(pat.span).unwrap();
4164                     err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
4165                     (Some((parser_snapshot_after_type, colon_sp, err)), None)
4166                 }
4167             }
4168         } else {
4169             (None, None)
4170         };
4171         let init = match (self.parse_initializer(err.is_some()), err) {
4172             (Ok(init), None) => {  // init parsed, ty parsed
4173                 init
4174             }
4175             (Ok(init), Some((_, colon_sp, mut err))) => {  // init parsed, ty error
4176                 // Could parse the type as if it were the initializer, it is likely there was a
4177                 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
4178                 err.span_suggestion_short(
4179                     colon_sp,
4180                     "use `=` if you meant to assign",
4181                     "=".to_string(),
4182                     Applicability::MachineApplicable
4183                 );
4184                 err.emit();
4185                 // As this was parsed successfully, continue as if the code has been fixed for the
4186                 // rest of the file. It will still fail due to the emitted error, but we avoid
4187                 // extra noise.
4188                 init
4189             }
4190             (Err(mut init_err), Some((snapshot, _, ty_err))) => {  // init error, ty error
4191                 init_err.cancel();
4192                 // Couldn't parse the type nor the initializer, only raise the type error and
4193                 // return to the parser state before parsing the type as the initializer.
4194                 // let x: <parse_error>;
4195                 mem::replace(self, snapshot);
4196                 return Err(ty_err);
4197             }
4198             (Err(err), None) => {  // init error, ty parsed
4199                 // Couldn't parse the initializer and we're not attempting to recover a failed
4200                 // parse of the type, return the error.
4201                 return Err(err);
4202             }
4203         };
4204         let hi = if self.token == token::Semi {
4205             self.span
4206         } else {
4207             self.prev_span
4208         };
4209         Ok(P(ast::Local {
4210             ty,
4211             pat,
4212             init,
4213             id: ast::DUMMY_NODE_ID,
4214             span: lo.to(hi),
4215             attrs,
4216             source: LocalSource::Normal,
4217         }))
4218     }
4219
4220     /// Parses a structure field.
4221     fn parse_name_and_ty(&mut self,
4222                          lo: Span,
4223                          vis: Visibility,
4224                          attrs: Vec<Attribute>)
4225                          -> PResult<'a, StructField> {
4226         let name = self.parse_ident()?;
4227         self.expect(&token::Colon)?;
4228         let ty = self.parse_ty()?;
4229         Ok(StructField {
4230             span: lo.to(self.prev_span),
4231             ident: Some(name),
4232             vis,
4233             id: ast::DUMMY_NODE_ID,
4234             ty,
4235             attrs,
4236         })
4237     }
4238
4239     /// Emits an expected-item-after-attributes error.
4240     fn expected_item_err(&mut self, attrs: &[Attribute]) -> PResult<'a,  ()> {
4241         let message = match attrs.last() {
4242             Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
4243             _ => "expected item after attributes",
4244         };
4245
4246         let mut err = self.diagnostic().struct_span_err(self.prev_span, message);
4247         if attrs.last().unwrap().is_sugared_doc {
4248             err.span_label(self.prev_span, "this doc comment doesn't document anything");
4249         }
4250         Err(err)
4251     }
4252
4253     /// Parse a statement. This stops just before trailing semicolons on everything but items.
4254     /// e.g., a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
4255     pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
4256         Ok(self.parse_stmt_(true))
4257     }
4258
4259     fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
4260         self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
4261             e.emit();
4262             self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4263             None
4264         })
4265     }
4266
4267     fn is_async_block(&self) -> bool {
4268         self.token.is_keyword(kw::Async) &&
4269         (
4270             ( // `async move {`
4271                 self.is_keyword_ahead(1, &[kw::Move]) &&
4272                 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
4273             ) || ( // `async {`
4274                 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
4275             )
4276         )
4277     }
4278
4279     fn is_async_fn(&self) -> bool {
4280         self.token.is_keyword(kw::Async) &&
4281             self.is_keyword_ahead(1, &[kw::Fn])
4282     }
4283
4284     fn is_do_catch_block(&self) -> bool {
4285         self.token.is_keyword(kw::Do) &&
4286         self.is_keyword_ahead(1, &[kw::Catch]) &&
4287         self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
4288         !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4289     }
4290
4291     fn is_try_block(&self) -> bool {
4292         self.token.is_keyword(kw::Try) &&
4293         self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) &&
4294         self.span.rust_2018() &&
4295         // prevent `while try {} {}`, `if try {} {} else {}`, etc.
4296         !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4297     }
4298
4299     fn is_union_item(&self) -> bool {
4300         self.token.is_keyword(kw::Union) &&
4301         self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
4302     }
4303
4304     fn is_crate_vis(&self) -> bool {
4305         self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
4306     }
4307
4308     fn is_existential_type_decl(&self) -> bool {
4309         self.token.is_keyword(kw::Existential) &&
4310         self.is_keyword_ahead(1, &[kw::Type])
4311     }
4312
4313     fn is_auto_trait_item(&self) -> bool {
4314         // auto trait
4315         (self.token.is_keyword(kw::Auto) &&
4316             self.is_keyword_ahead(1, &[kw::Trait]))
4317         || // unsafe auto trait
4318         (self.token.is_keyword(kw::Unsafe) &&
4319          self.is_keyword_ahead(1, &[kw::Auto]) &&
4320          self.is_keyword_ahead(2, &[kw::Trait]))
4321     }
4322
4323     fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility, lo: Span)
4324                      -> PResult<'a, Option<P<Item>>> {
4325         let token_lo = self.span;
4326         let (ident, def) = match self.token {
4327             token::Ident(ident, false) if ident.name == kw::Macro => {
4328                 self.bump();
4329                 let ident = self.parse_ident()?;
4330                 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
4331                     match self.parse_token_tree() {
4332                         TokenTree::Delimited(_, _, tts) => tts,
4333                         _ => unreachable!(),
4334                     }
4335                 } else if self.check(&token::OpenDelim(token::Paren)) {
4336                     let args = self.parse_token_tree();
4337                     let body = if self.check(&token::OpenDelim(token::Brace)) {
4338                         self.parse_token_tree()
4339                     } else {
4340                         self.unexpected()?;
4341                         unreachable!()
4342                     };
4343                     TokenStream::new(vec![
4344                         args.into(),
4345                         TokenTree::Token(token_lo.to(self.prev_span), token::FatArrow).into(),
4346                         body.into(),
4347                     ])
4348                 } else {
4349                     self.unexpected()?;
4350                     unreachable!()
4351                 };
4352
4353                 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
4354             }
4355             token::Ident(ident, _) if ident.name == sym::macro_rules &&
4356                                    self.look_ahead(1, |t| *t == token::Not) => {
4357                 let prev_span = self.prev_span;
4358                 self.complain_if_pub_macro(&vis.node, prev_span);
4359                 self.bump();
4360                 self.bump();
4361
4362                 let ident = self.parse_ident()?;
4363                 let (delim, tokens) = self.expect_delimited_token_tree()?;
4364                 if delim != MacDelimiter::Brace && !self.eat(&token::Semi) {
4365                     self.report_invalid_macro_expansion_item();
4366                 }
4367
4368                 (ident, ast::MacroDef { tokens: tokens, legacy: true })
4369             }
4370             _ => return Ok(None),
4371         };
4372
4373         let span = lo.to(self.prev_span);
4374         Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
4375     }
4376
4377     fn parse_stmt_without_recovery(&mut self,
4378                                    macro_legacy_warnings: bool)
4379                                    -> PResult<'a, Option<Stmt>> {
4380         maybe_whole!(self, NtStmt, |x| Some(x));
4381
4382         let attrs = self.parse_outer_attributes()?;
4383         let lo = self.span;
4384
4385         Ok(Some(if self.eat_keyword(kw::Let) {
4386             Stmt {
4387                 id: ast::DUMMY_NODE_ID,
4388                 node: StmtKind::Local(self.parse_local(attrs.into())?),
4389                 span: lo.to(self.prev_span),
4390             }
4391         } else if let Some(macro_def) = self.eat_macro_def(
4392             &attrs,
4393             &source_map::respan(lo, VisibilityKind::Inherited),
4394             lo,
4395         )? {
4396             Stmt {
4397                 id: ast::DUMMY_NODE_ID,
4398                 node: StmtKind::Item(macro_def),
4399                 span: lo.to(self.prev_span),
4400             }
4401         // Starts like a simple path, being careful to avoid contextual keywords
4402         // such as a union items, item with `crate` visibility or auto trait items.
4403         // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts
4404         // like a path (1 token), but it fact not a path.
4405         // `union::b::c` - path, `union U { ... }` - not a path.
4406         // `crate::b::c` - path, `crate struct S;` - not a path.
4407         } else if self.token.is_path_start() &&
4408                   !self.token.is_qpath_start() &&
4409                   !self.is_union_item() &&
4410                   !self.is_crate_vis() &&
4411                   !self.is_existential_type_decl() &&
4412                   !self.is_auto_trait_item() &&
4413                   !self.is_async_fn() {
4414             let pth = self.parse_path(PathStyle::Expr)?;
4415
4416             if !self.eat(&token::Not) {
4417                 let expr = if self.check(&token::OpenDelim(token::Brace)) {
4418                     self.parse_struct_expr(lo, pth, ThinVec::new())?
4419                 } else {
4420                     let hi = self.prev_span;
4421                     self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
4422                 };
4423
4424                 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
4425                     let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
4426                     this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
4427                 })?;
4428
4429                 return Ok(Some(Stmt {
4430                     id: ast::DUMMY_NODE_ID,
4431                     node: StmtKind::Expr(expr),
4432                     span: lo.to(self.prev_span),
4433                 }));
4434             }
4435
4436             // it's a macro invocation
4437             let id = match self.token {
4438                 token::OpenDelim(_) => Ident::invalid(), // no special identifier
4439                 _ => self.parse_ident()?,
4440             };
4441
4442             // check that we're pointing at delimiters (need to check
4443             // again after the `if`, because of `parse_ident`
4444             // consuming more tokens).
4445             match self.token {
4446                 token::OpenDelim(_) => {}
4447                 _ => {
4448                     // we only expect an ident if we didn't parse one
4449                     // above.
4450                     let ident_str = if id.name == kw::Invalid {
4451                         "identifier, "
4452                     } else {
4453                         ""
4454                     };
4455                     let tok_str = self.this_token_descr();
4456                     let mut err = self.fatal(&format!("expected {}`(` or `{{`, found {}",
4457                                                       ident_str,
4458                                                       tok_str));
4459                     err.span_label(self.span, format!("expected {}`(` or `{{`", ident_str));
4460                     return Err(err)
4461                 },
4462             }
4463
4464             let (delim, tts) = self.expect_delimited_token_tree()?;
4465             let hi = self.prev_span;
4466
4467             let style = if delim == MacDelimiter::Brace {
4468                 MacStmtStyle::Braces
4469             } else {
4470                 MacStmtStyle::NoBraces
4471             };
4472
4473             if id.name == kw::Invalid {
4474                 let mac = respan(lo.to(hi), Mac_ { path: pth, tts, delim });
4475                 let node = if delim == MacDelimiter::Brace ||
4476                               self.token == token::Semi || self.token == token::Eof {
4477                     StmtKind::Mac(P((mac, style, attrs.into())))
4478                 }
4479                 // We used to incorrectly stop parsing macro-expanded statements here.
4480                 // If the next token will be an error anyway but could have parsed with the
4481                 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
4482                 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
4483                     // These can continue an expression, so we can't stop parsing and warn.
4484                     token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
4485                     token::BinOp(token::Minus) | token::BinOp(token::Star) |
4486                     token::BinOp(token::And) | token::BinOp(token::Or) |
4487                     token::AndAnd | token::OrOr |
4488                     token::DotDot | token::DotDotDot | token::DotDotEq => false,
4489                     _ => true,
4490                 } {
4491                     self.warn_missing_semicolon();
4492                     StmtKind::Mac(P((mac, style, attrs.into())))
4493                 } else {
4494                     let e = self.mk_expr(mac.span, ExprKind::Mac(mac), ThinVec::new());
4495                     let e = self.maybe_recover_from_bad_qpath(e, true)?;
4496                     let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
4497                     let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
4498                     StmtKind::Expr(e)
4499                 };
4500                 Stmt {
4501                     id: ast::DUMMY_NODE_ID,
4502                     span: lo.to(hi),
4503                     node,
4504                 }
4505             } else {
4506                 // if it has a special ident, it's definitely an item
4507                 //
4508                 // Require a semicolon or braces.
4509                 if style != MacStmtStyle::Braces && !self.eat(&token::Semi) {
4510                     self.report_invalid_macro_expansion_item();
4511                 }
4512                 let span = lo.to(hi);
4513                 Stmt {
4514                     id: ast::DUMMY_NODE_ID,
4515                     span,
4516                     node: StmtKind::Item({
4517                         self.mk_item(
4518                             span, id /*id is good here*/,
4519                             ItemKind::Mac(respan(span, Mac_ { path: pth, tts, delim })),
4520                             respan(lo, VisibilityKind::Inherited),
4521                             attrs)
4522                     }),
4523                 }
4524             }
4525         } else {
4526             // FIXME: Bad copy of attrs
4527             let old_directory_ownership =
4528                 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
4529             let item = self.parse_item_(attrs.clone(), false, true)?;
4530             self.directory.ownership = old_directory_ownership;
4531
4532             match item {
4533                 Some(i) => Stmt {
4534                     id: ast::DUMMY_NODE_ID,
4535                     span: lo.to(i.span),
4536                     node: StmtKind::Item(i),
4537                 },
4538                 None => {
4539                     let unused_attrs = |attrs: &[Attribute], s: &mut Self| {
4540                         if !attrs.is_empty() {
4541                             if s.prev_token_kind == PrevTokenKind::DocComment {
4542                                 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
4543                             } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
4544                                 s.span_err(s.span, "expected statement after outer attribute");
4545                             }
4546                         }
4547                     };
4548
4549                     // Do not attempt to parse an expression if we're done here.
4550                     if self.token == token::Semi {
4551                         unused_attrs(&attrs, self);
4552                         self.bump();
4553                         return Ok(None);
4554                     }
4555
4556                     if self.token == token::CloseDelim(token::Brace) {
4557                         unused_attrs(&attrs, self);
4558                         return Ok(None);
4559                     }
4560
4561                     // Remainder are line-expr stmts.
4562                     let e = self.parse_expr_res(
4563                         Restrictions::STMT_EXPR, Some(attrs.into()))?;
4564                     Stmt {
4565                         id: ast::DUMMY_NODE_ID,
4566                         span: lo.to(e.span),
4567                         node: StmtKind::Expr(e),
4568                     }
4569                 }
4570             }
4571         }))
4572     }
4573
4574     /// Checks if this expression is a successfully parsed statement.
4575     fn expr_is_complete(&self, e: &Expr) -> bool {
4576         self.restrictions.contains(Restrictions::STMT_EXPR) &&
4577             !classify::expr_requires_semi_to_be_stmt(e)
4578     }
4579
4580     /// Parses a block. No inner attributes are allowed.
4581     pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
4582         maybe_whole!(self, NtBlock, |x| x);
4583
4584         let lo = self.span;
4585
4586         if !self.eat(&token::OpenDelim(token::Brace)) {
4587             let sp = self.span;
4588             let tok = self.this_token_descr();
4589             let mut e = self.span_fatal(sp, &format!("expected `{{`, found {}", tok));
4590             let do_not_suggest_help =
4591                 self.token.is_keyword(kw::In) || self.token == token::Colon;
4592
4593             if self.token.is_ident_named(sym::and) {
4594                 e.span_suggestion_short(
4595                     self.span,
4596                     "use `&&` instead of `and` for the boolean operator",
4597                     "&&".to_string(),
4598                     Applicability::MaybeIncorrect,
4599                 );
4600             }
4601             if self.token.is_ident_named(sym::or) {
4602                 e.span_suggestion_short(
4603                     self.span,
4604                     "use `||` instead of `or` for the boolean operator",
4605                     "||".to_string(),
4606                     Applicability::MaybeIncorrect,
4607                 );
4608             }
4609
4610             // Check to see if the user has written something like
4611             //
4612             //    if (cond)
4613             //      bar;
4614             //
4615             // Which is valid in other languages, but not Rust.
4616             match self.parse_stmt_without_recovery(false) {
4617                 Ok(Some(stmt)) => {
4618                     if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace))
4619                         || do_not_suggest_help {
4620                         // if the next token is an open brace (e.g., `if a b {`), the place-
4621                         // inside-a-block suggestion would be more likely wrong than right
4622                         e.span_label(sp, "expected `{`");
4623                         return Err(e);
4624                     }
4625                     let mut stmt_span = stmt.span;
4626                     // expand the span to include the semicolon, if it exists
4627                     if self.eat(&token::Semi) {
4628                         stmt_span = stmt_span.with_hi(self.prev_span.hi());
4629                     }
4630                     let sugg = pprust::to_string(|s| {
4631                         use crate::print::pprust::{PrintState, INDENT_UNIT};
4632                         s.ibox(INDENT_UNIT)?;
4633                         s.bopen()?;
4634                         s.print_stmt(&stmt)?;
4635                         s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
4636                     });
4637                     e.span_suggestion(
4638                         stmt_span,
4639                         "try placing this code inside a block",
4640                         sugg,
4641                         // speculative, has been misleading in the past (closed Issue #46836)
4642                         Applicability::MaybeIncorrect
4643                     );
4644                 }
4645                 Err(mut e) => {
4646                     self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4647                     self.cancel(&mut e);
4648                 }
4649                 _ => ()
4650             }
4651             e.span_label(sp, "expected `{`");
4652             return Err(e);
4653         }
4654
4655         self.parse_block_tail(lo, BlockCheckMode::Default)
4656     }
4657
4658     /// Parses a block. Inner attributes are allowed.
4659     fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
4660         maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
4661
4662         let lo = self.span;
4663         self.expect(&token::OpenDelim(token::Brace))?;
4664         Ok((self.parse_inner_attributes()?,
4665             self.parse_block_tail(lo, BlockCheckMode::Default)?))
4666     }
4667
4668     /// Parses the rest of a block expression or function body.
4669     /// Precondition: already parsed the '{'.
4670     fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
4671         let mut stmts = vec![];
4672         while !self.eat(&token::CloseDelim(token::Brace)) {
4673             let stmt = match self.parse_full_stmt(false) {
4674                 Err(mut err) => {
4675                     err.emit();
4676                     self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
4677                     Some(Stmt {
4678                         id: ast::DUMMY_NODE_ID,
4679                         node: StmtKind::Expr(DummyResult::raw_expr(self.span, true)),
4680                         span: self.span,
4681                     })
4682                 }
4683                 Ok(stmt) => stmt,
4684             };
4685             if let Some(stmt) = stmt {
4686                 stmts.push(stmt);
4687             } else if self.token == token::Eof {
4688                 break;
4689             } else {
4690                 // Found only `;` or `}`.
4691                 continue;
4692             };
4693         }
4694         Ok(P(ast::Block {
4695             stmts,
4696             id: ast::DUMMY_NODE_ID,
4697             rules: s,
4698             span: lo.to(self.prev_span),
4699         }))
4700     }
4701
4702     /// Parses a statement, including the trailing semicolon.
4703     crate fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
4704         // skip looking for a trailing semicolon when we have an interpolated statement
4705         maybe_whole!(self, NtStmt, |x| Some(x));
4706
4707         let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
4708             Some(stmt) => stmt,
4709             None => return Ok(None),
4710         };
4711
4712         match stmt.node {
4713             StmtKind::Expr(ref expr) if self.token != token::Eof => {
4714                 // expression without semicolon
4715                 if classify::expr_requires_semi_to_be_stmt(expr) {
4716                     // Just check for errors and recover; do not eat semicolon yet.
4717                     if let Err(mut e) =
4718                         self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
4719                     {
4720                         e.emit();
4721                         self.recover_stmt();
4722                     }
4723                 }
4724             }
4725             StmtKind::Local(..) => {
4726                 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
4727                 if macro_legacy_warnings && self.token != token::Semi {
4728                     self.warn_missing_semicolon();
4729                 } else {
4730                     self.expect_one_of(&[], &[token::Semi])?;
4731                 }
4732             }
4733             _ => {}
4734         }
4735
4736         if self.eat(&token::Semi) {
4737             stmt = stmt.add_trailing_semicolon();
4738         }
4739
4740         stmt.span = stmt.span.with_hi(self.prev_span.hi());
4741         Ok(Some(stmt))
4742     }
4743
4744     fn warn_missing_semicolon(&self) {
4745         self.diagnostic().struct_span_warn(self.span, {
4746             &format!("expected `;`, found {}", self.this_token_descr())
4747         }).note({
4748             "This was erroneously allowed and will become a hard error in a future release"
4749         }).emit();
4750     }
4751
4752     fn err_dotdotdot_syntax(&self, span: Span) {
4753         self.diagnostic().struct_span_err(span, {
4754             "unexpected token: `...`"
4755         }).span_suggestion(
4756             span, "use `..` for an exclusive range", "..".to_owned(),
4757             Applicability::MaybeIncorrect
4758         ).span_suggestion(
4759             span, "or `..=` for an inclusive range", "..=".to_owned(),
4760             Applicability::MaybeIncorrect
4761         ).emit();
4762     }
4763
4764     /// Parses bounds of a type parameter `BOUND + BOUND + ...`, possibly with trailing `+`.
4765     ///
4766     /// ```
4767     /// BOUND = TY_BOUND | LT_BOUND
4768     /// LT_BOUND = LIFETIME (e.g., `'a`)
4769     /// TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
4770     /// TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g., `?for<'a: 'b> m::Trait<'a>`)
4771     /// ```
4772     fn parse_generic_bounds_common(&mut self,
4773                                    allow_plus: bool,
4774                                    colon_span: Option<Span>) -> PResult<'a, GenericBounds> {
4775         let mut bounds = Vec::new();
4776         let mut negative_bounds = Vec::new();
4777         let mut last_plus_span = None;
4778         let mut was_negative = false;
4779         loop {
4780             // This needs to be synchronized with `Token::can_begin_bound`.
4781             let is_bound_start = self.check_path() || self.check_lifetime() ||
4782                                  self.check(&token::Not) || // used for error reporting only
4783                                  self.check(&token::Question) ||
4784                                  self.check_keyword(kw::For) ||
4785                                  self.check(&token::OpenDelim(token::Paren));
4786             if is_bound_start {
4787                 let lo = self.span;
4788                 let has_parens = self.eat(&token::OpenDelim(token::Paren));
4789                 let inner_lo = self.span;
4790                 let is_negative = self.eat(&token::Not);
4791                 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
4792                 if self.token.is_lifetime() {
4793                     if let Some(question_span) = question {
4794                         self.span_err(question_span,
4795                                       "`?` may only modify trait bounds, not lifetime bounds");
4796                     }
4797                     bounds.push(GenericBound::Outlives(self.expect_lifetime()));
4798                     if has_parens {
4799                         let inner_span = inner_lo.to(self.prev_span);
4800                         self.expect(&token::CloseDelim(token::Paren))?;
4801                         let mut err = self.struct_span_err(
4802                             lo.to(self.prev_span),
4803                             "parenthesized lifetime bounds are not supported"
4804                         );
4805                         if let Ok(snippet) = self.sess.source_map().span_to_snippet(inner_span) {
4806                             err.span_suggestion_short(
4807                                 lo.to(self.prev_span),
4808                                 "remove the parentheses",
4809                                 snippet.to_owned(),
4810                                 Applicability::MachineApplicable
4811                             );
4812                         }
4813                         err.emit();
4814                     }
4815                 } else {
4816                     let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4817                     let path = self.parse_path(PathStyle::Type)?;
4818                     if has_parens {
4819                         self.expect(&token::CloseDelim(token::Paren))?;
4820                     }
4821                     let poly_span = lo.to(self.prev_span);
4822                     if is_negative {
4823                         was_negative = true;
4824                         if let Some(sp) = last_plus_span.or(colon_span) {
4825                             negative_bounds.push(sp.to(poly_span));
4826                         }
4827                     } else {
4828                         let poly_trait = PolyTraitRef::new(lifetime_defs, path, poly_span);
4829                         let modifier = if question.is_some() {
4830                             TraitBoundModifier::Maybe
4831                         } else {
4832                             TraitBoundModifier::None
4833                         };
4834                         bounds.push(GenericBound::Trait(poly_trait, modifier));
4835                     }
4836                 }
4837             } else {
4838                 break
4839             }
4840
4841             if !allow_plus || !self.eat_plus() {
4842                 break
4843             } else {
4844                 last_plus_span = Some(self.prev_span);
4845             }
4846         }
4847
4848         if !negative_bounds.is_empty() || was_negative {
4849             let plural = negative_bounds.len() > 1;
4850             let last_span = negative_bounds.last().map(|sp| *sp);
4851             let mut err = self.struct_span_err(
4852                 negative_bounds,
4853                 "negative trait bounds are not supported",
4854             );
4855             if let Some(sp) = last_span {
4856                 err.span_label(sp, "negative trait bounds are not supported");
4857             }
4858             if let Some(bound_list) = colon_span {
4859                 let bound_list = bound_list.to(self.prev_span);
4860                 let mut new_bound_list = String::new();
4861                 if !bounds.is_empty() {
4862                     let mut snippets = bounds.iter().map(|bound| bound.span())
4863                         .map(|span| self.sess.source_map().span_to_snippet(span));
4864                     while let Some(Ok(snippet)) = snippets.next() {
4865                         new_bound_list.push_str(" + ");
4866                         new_bound_list.push_str(&snippet);
4867                     }
4868                     new_bound_list = new_bound_list.replacen(" +", ":", 1);
4869                 }
4870                 err.span_suggestion_hidden(
4871                     bound_list,
4872                     &format!("remove the trait bound{}", if plural { "s" } else { "" }),
4873                     new_bound_list,
4874                     Applicability::MachineApplicable,
4875                 );
4876             }
4877             err.emit();
4878         }
4879
4880         return Ok(bounds);
4881     }
4882
4883     crate fn parse_generic_bounds(&mut self,
4884                                   colon_span: Option<Span>) -> PResult<'a, GenericBounds> {
4885         self.parse_generic_bounds_common(true, colon_span)
4886     }
4887
4888     /// Parses bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4889     ///
4890     /// ```
4891     /// BOUND = LT_BOUND (e.g., `'a`)
4892     /// ```
4893     fn parse_lt_param_bounds(&mut self) -> GenericBounds {
4894         let mut lifetimes = Vec::new();
4895         while self.check_lifetime() {
4896             lifetimes.push(ast::GenericBound::Outlives(self.expect_lifetime()));
4897
4898             if !self.eat_plus() {
4899                 break
4900             }
4901         }
4902         lifetimes
4903     }
4904
4905     /// Matches `typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?`.
4906     fn parse_ty_param(&mut self,
4907                       preceding_attrs: Vec<Attribute>)
4908                       -> PResult<'a, GenericParam> {
4909         let ident = self.parse_ident()?;
4910
4911         // Parse optional colon and param bounds.
4912         let bounds = if self.eat(&token::Colon) {
4913             self.parse_generic_bounds(Some(self.prev_span))?
4914         } else {
4915             Vec::new()
4916         };
4917
4918         let default = if self.eat(&token::Eq) {
4919             Some(self.parse_ty()?)
4920         } else {
4921             None
4922         };
4923
4924         Ok(GenericParam {
4925             ident,
4926             id: ast::DUMMY_NODE_ID,
4927             attrs: preceding_attrs.into(),
4928             bounds,
4929             kind: GenericParamKind::Type {
4930                 default,
4931             }
4932         })
4933     }
4934
4935     /// Parses the following grammar:
4936     ///
4937     ///     TraitItemAssocTy = Ident ["<"...">"] [":" [GenericBounds]] ["where" ...] ["=" Ty]
4938     fn parse_trait_item_assoc_ty(&mut self)
4939         -> PResult<'a, (Ident, TraitItemKind, ast::Generics)> {
4940         let ident = self.parse_ident()?;
4941         let mut generics = self.parse_generics()?;
4942
4943         // Parse optional colon and param bounds.
4944         let bounds = if self.eat(&token::Colon) {
4945             self.parse_generic_bounds(None)?
4946         } else {
4947             Vec::new()
4948         };
4949         generics.where_clause = self.parse_where_clause()?;
4950
4951         let default = if self.eat(&token::Eq) {
4952             Some(self.parse_ty()?)
4953         } else {
4954             None
4955         };
4956         self.expect(&token::Semi)?;
4957
4958         Ok((ident, TraitItemKind::Type(bounds, default), generics))
4959     }
4960
4961     fn parse_const_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, GenericParam> {
4962         self.expect_keyword(kw::Const)?;
4963         let ident = self.parse_ident()?;
4964         self.expect(&token::Colon)?;
4965         let ty = self.parse_ty()?;
4966
4967         Ok(GenericParam {
4968             ident,
4969             id: ast::DUMMY_NODE_ID,
4970             attrs: preceding_attrs.into(),
4971             bounds: Vec::new(),
4972             kind: GenericParamKind::Const {
4973                 ty,
4974             }
4975         })
4976     }
4977
4978     /// Parses a (possibly empty) list of lifetime and type parameters, possibly including
4979     /// a trailing comma and erroneous trailing attributes.
4980     crate fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
4981         let mut params = Vec::new();
4982         loop {
4983             let attrs = self.parse_outer_attributes()?;
4984             if self.check_lifetime() {
4985                 let lifetime = self.expect_lifetime();
4986                 // Parse lifetime parameter.
4987                 let bounds = if self.eat(&token::Colon) {
4988                     self.parse_lt_param_bounds()
4989                 } else {
4990                     Vec::new()
4991                 };
4992                 params.push(ast::GenericParam {
4993                     ident: lifetime.ident,
4994                     id: lifetime.id,
4995                     attrs: attrs.into(),
4996                     bounds,
4997                     kind: ast::GenericParamKind::Lifetime,
4998                 });
4999             } else if self.check_keyword(kw::Const) {
5000                 // Parse const parameter.
5001                 params.push(self.parse_const_param(attrs)?);
5002             } else if self.check_ident() {
5003                 // Parse type parameter.
5004                 params.push(self.parse_ty_param(attrs)?);
5005             } else {
5006                 // Check for trailing attributes and stop parsing.
5007                 if !attrs.is_empty() {
5008                     if !params.is_empty() {
5009                         self.struct_span_err(
5010                             attrs[0].span,
5011                             &format!("trailing attribute after generic parameter"),
5012                         )
5013                         .span_label(attrs[0].span, "attributes must go before parameters")
5014                         .emit();
5015                     } else {
5016                         self.struct_span_err(
5017                             attrs[0].span,
5018                             &format!("attribute without generic parameters"),
5019                         )
5020                         .span_label(
5021                             attrs[0].span,
5022                             "attributes are only permitted when preceding parameters",
5023                         )
5024                         .emit();
5025                     }
5026                 }
5027                 break
5028             }
5029
5030             if !self.eat(&token::Comma) {
5031                 break
5032             }
5033         }
5034         Ok(params)
5035     }
5036
5037     /// Parses a set of optional generic type parameter declarations. Where
5038     /// clauses are not parsed here, and must be added later via
5039     /// `parse_where_clause()`.
5040     ///
5041     /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
5042     ///                  | ( < lifetimes , typaramseq ( , )? > )
5043     /// where   typaramseq = ( typaram ) | ( typaram , typaramseq )
5044     fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
5045         let span_lo = self.span;
5046         let (params, span) = if self.eat_lt() {
5047             let params = self.parse_generic_params()?;
5048             self.expect_gt()?;
5049             (params, span_lo.to(self.prev_span))
5050         } else {
5051             (vec![], self.prev_span.between(self.span))
5052         };
5053         Ok(ast::Generics {
5054             params,
5055             where_clause: WhereClause {
5056                 id: ast::DUMMY_NODE_ID,
5057                 predicates: Vec::new(),
5058                 span: DUMMY_SP,
5059             },
5060             span,
5061         })
5062     }
5063
5064     /// Parses generic args (within a path segment) with recovery for extra leading angle brackets.
5065     /// For the purposes of understanding the parsing logic of generic arguments, this function
5066     /// can be thought of being the same as just calling `self.parse_generic_args()` if the source
5067     /// had the correct amount of leading angle brackets.
5068     ///
5069     /// ```ignore (diagnostics)
5070     /// bar::<<<<T as Foo>::Output>();
5071     ///      ^^ help: remove extra angle brackets
5072     /// ```
5073     fn parse_generic_args_with_leaning_angle_bracket_recovery(
5074         &mut self,
5075         style: PathStyle,
5076         lo: Span,
5077     ) -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> {
5078         // We need to detect whether there are extra leading left angle brackets and produce an
5079         // appropriate error and suggestion. This cannot be implemented by looking ahead at
5080         // upcoming tokens for a matching `>` character - if there are unmatched `<` tokens
5081         // then there won't be matching `>` tokens to find.
5082         //
5083         // To explain how this detection works, consider the following example:
5084         //
5085         // ```ignore (diagnostics)
5086         // bar::<<<<T as Foo>::Output>();
5087         //      ^^ help: remove extra angle brackets
5088         // ```
5089         //
5090         // Parsing of the left angle brackets starts in this function. We start by parsing the
5091         // `<` token (incrementing the counter of unmatched angle brackets on `Parser` via
5092         // `eat_lt`):
5093         //
5094         // *Upcoming tokens:* `<<<<T as Foo>::Output>;`
5095         // *Unmatched count:* 1
5096         // *`parse_path_segment` calls deep:* 0
5097         //
5098         // This has the effect of recursing as this function is called if a `<` character
5099         // is found within the expected generic arguments:
5100         //
5101         // *Upcoming tokens:* `<<<T as Foo>::Output>;`
5102         // *Unmatched count:* 2
5103         // *`parse_path_segment` calls deep:* 1
5104         //
5105         // Eventually we will have recursed until having consumed all of the `<` tokens and
5106         // this will be reflected in the count:
5107         //
5108         // *Upcoming tokens:* `T as Foo>::Output>;`
5109         // *Unmatched count:* 4
5110         // `parse_path_segment` calls deep:* 3
5111         //
5112         // The parser will continue until reaching the first `>` - this will decrement the
5113         // unmatched angle bracket count and return to the parent invocation of this function
5114         // having succeeded in parsing:
5115         //
5116         // *Upcoming tokens:* `::Output>;`
5117         // *Unmatched count:* 3
5118         // *`parse_path_segment` calls deep:* 2
5119         //
5120         // This will continue until the next `>` character which will also return successfully
5121         // to the parent invocation of this function and decrement the count:
5122         //
5123         // *Upcoming tokens:* `;`
5124         // *Unmatched count:* 2
5125         // *`parse_path_segment` calls deep:* 1
5126         //
5127         // At this point, this function will expect to find another matching `>` character but
5128         // won't be able to and will return an error. This will continue all the way up the
5129         // call stack until the first invocation:
5130         //
5131         // *Upcoming tokens:* `;`
5132         // *Unmatched count:* 2
5133         // *`parse_path_segment` calls deep:* 0
5134         //
5135         // In doing this, we have managed to work out how many unmatched leading left angle
5136         // brackets there are, but we cannot recover as the unmatched angle brackets have
5137         // already been consumed. To remedy this, we keep a snapshot of the parser state
5138         // before we do the above. We can then inspect whether we ended up with a parsing error
5139         // and unmatched left angle brackets and if so, restore the parser state before we
5140         // consumed any `<` characters to emit an error and consume the erroneous tokens to
5141         // recover by attempting to parse again.
5142         //
5143         // In practice, the recursion of this function is indirect and there will be other
5144         // locations that consume some `<` characters - as long as we update the count when
5145         // this happens, it isn't an issue.
5146
5147         let is_first_invocation = style == PathStyle::Expr;
5148         // Take a snapshot before attempting to parse - we can restore this later.
5149         let snapshot = if is_first_invocation {
5150             Some(self.clone())
5151         } else {
5152             None
5153         };
5154
5155         debug!("parse_generic_args_with_leading_angle_bracket_recovery: (snapshotting)");
5156         match self.parse_generic_args() {
5157             Ok(value) => Ok(value),
5158             Err(ref mut e) if is_first_invocation && self.unmatched_angle_bracket_count > 0 => {
5159                 // Cancel error from being unable to find `>`. We know the error
5160                 // must have been this due to a non-zero unmatched angle bracket
5161                 // count.
5162                 e.cancel();
5163
5164                 // Swap `self` with our backup of the parser state before attempting to parse
5165                 // generic arguments.
5166                 let snapshot = mem::replace(self, snapshot.unwrap());
5167
5168                 debug!(
5169                     "parse_generic_args_with_leading_angle_bracket_recovery: (snapshot failure) \
5170                      snapshot.count={:?}",
5171                     snapshot.unmatched_angle_bracket_count,
5172                 );
5173
5174                 // Eat the unmatched angle brackets.
5175                 for _ in 0..snapshot.unmatched_angle_bracket_count {
5176                     self.eat_lt();
5177                 }
5178
5179                 // Make a span over ${unmatched angle bracket count} characters.
5180                 let span = lo.with_hi(
5181                     lo.lo() + BytePos(snapshot.unmatched_angle_bracket_count)
5182                 );
5183                 let plural = snapshot.unmatched_angle_bracket_count > 1;
5184                 self.diagnostic()
5185                     .struct_span_err(
5186                         span,
5187                         &format!(
5188                             "unmatched angle bracket{}",
5189                             if plural { "s" } else { "" }
5190                         ),
5191                     )
5192                     .span_suggestion(
5193                         span,
5194                         &format!(
5195                             "remove extra angle bracket{}",
5196                             if plural { "s" } else { "" }
5197                         ),
5198                         String::new(),
5199                         Applicability::MachineApplicable,
5200                     )
5201                     .emit();
5202
5203                 // Try again without unmatched angle bracket characters.
5204                 self.parse_generic_args()
5205             },
5206             Err(e) => Err(e),
5207         }
5208     }
5209
5210     /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
5211     /// possibly including trailing comma.
5212     fn parse_generic_args(&mut self) -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> {
5213         let mut args = Vec::new();
5214         let mut bindings = Vec::new();
5215         let mut misplaced_assoc_ty_bindings: Vec<Span> = Vec::new();
5216         let mut assoc_ty_bindings: Vec<Span> = Vec::new();
5217
5218         let args_lo = self.span;
5219
5220         loop {
5221             if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5222                 // Parse lifetime argument.
5223                 args.push(GenericArg::Lifetime(self.expect_lifetime()));
5224                 misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings);
5225             } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
5226                 // Parse associated type binding.
5227                 let lo = self.span;
5228                 let ident = self.parse_ident()?;
5229                 self.bump();
5230                 let ty = self.parse_ty()?;
5231                 let span = lo.to(self.prev_span);
5232                 bindings.push(TypeBinding {
5233                     id: ast::DUMMY_NODE_ID,
5234                     ident,
5235                     ty,
5236                     span,
5237                 });
5238                 assoc_ty_bindings.push(span);
5239             } else if self.check_const_arg() {
5240                 // Parse const argument.
5241                 let expr = if let token::OpenDelim(token::Brace) = self.token {
5242                     self.parse_block_expr(None, self.span, BlockCheckMode::Default, ThinVec::new())?
5243                 } else if self.token.is_ident() {
5244                     // FIXME(const_generics): to distinguish between idents for types and consts,
5245                     // we should introduce a GenericArg::Ident in the AST and distinguish when
5246                     // lowering to the HIR. For now, idents for const args are not permitted.
5247                     if self.token.is_keyword(kw::True) || self.token.is_keyword(kw::False) {
5248                         self.parse_literal_maybe_minus()?
5249                     } else {
5250                         return Err(
5251                             self.fatal("identifiers may currently not be used for const generics")
5252                         );
5253                     }
5254                 } else {
5255                     self.parse_literal_maybe_minus()?
5256                 };
5257                 let value = AnonConst {
5258                     id: ast::DUMMY_NODE_ID,
5259                     value: expr,
5260                 };
5261                 args.push(GenericArg::Const(value));
5262                 misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings);
5263             } else if self.check_type() {
5264                 // Parse type argument.
5265                 args.push(GenericArg::Type(self.parse_ty()?));
5266                 misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings);
5267             } else {
5268                 break
5269             }
5270
5271             if !self.eat(&token::Comma) {
5272                 break
5273             }
5274         }
5275
5276         // FIXME: we would like to report this in ast_validation instead, but we currently do not
5277         // preserve ordering of generic parameters with respect to associated type binding, so we
5278         // lose that information after parsing.
5279         if misplaced_assoc_ty_bindings.len() > 0 {
5280             let mut err = self.struct_span_err(
5281                 args_lo.to(self.prev_span),
5282                 "associated type bindings must be declared after generic parameters",
5283             );
5284             for span in misplaced_assoc_ty_bindings {
5285                 err.span_label(
5286                     span,
5287                     "this associated type binding should be moved after the generic parameters",
5288                 );
5289             }
5290             err.emit();
5291         }
5292
5293         Ok((args, bindings))
5294     }
5295
5296     /// Parses an optional where-clause and places it in `generics`.
5297     ///
5298     /// ```ignore (only-for-syntax-highlight)
5299     /// where T : Trait<U, V> + 'b, 'a : 'b
5300     /// ```
5301     fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
5302         let mut where_clause = WhereClause {
5303             id: ast::DUMMY_NODE_ID,
5304             predicates: Vec::new(),
5305             span: DUMMY_SP,
5306         };
5307
5308         if !self.eat_keyword(kw::Where) {
5309             return Ok(where_clause);
5310         }
5311         let lo = self.prev_span;
5312
5313         // We are considering adding generics to the `where` keyword as an alternative higher-rank
5314         // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
5315         // change we parse those generics now, but report an error.
5316         if self.choose_generics_over_qpath() {
5317             let generics = self.parse_generics()?;
5318             self.struct_span_err(
5319                 generics.span,
5320                 "generic parameters on `where` clauses are reserved for future use",
5321             )
5322                 .span_label(generics.span, "currently unsupported")
5323                 .emit();
5324         }
5325
5326         loop {
5327             let lo = self.span;
5328             if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5329                 let lifetime = self.expect_lifetime();
5330                 // Bounds starting with a colon are mandatory, but possibly empty.
5331                 self.expect(&token::Colon)?;
5332                 let bounds = self.parse_lt_param_bounds();
5333                 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
5334                     ast::WhereRegionPredicate {
5335                         span: lo.to(self.prev_span),
5336                         lifetime,
5337                         bounds,
5338                     }
5339                 ));
5340             } else if self.check_type() {
5341                 // Parse optional `for<'a, 'b>`.
5342                 // This `for` is parsed greedily and applies to the whole predicate,
5343                 // the bounded type can have its own `for` applying only to it.
5344                 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
5345                 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
5346                 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
5347                 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
5348
5349                 // Parse type with mandatory colon and (possibly empty) bounds,
5350                 // or with mandatory equality sign and the second type.
5351                 let ty = self.parse_ty()?;
5352                 if self.eat(&token::Colon) {
5353                     let bounds = self.parse_generic_bounds(Some(self.prev_span))?;
5354                     where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
5355                         ast::WhereBoundPredicate {
5356                             span: lo.to(self.prev_span),
5357                             bound_generic_params: lifetime_defs,
5358                             bounded_ty: ty,
5359                             bounds,
5360                         }
5361                     ));
5362                 // FIXME: Decide what should be used here, `=` or `==`.
5363                 // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
5364                 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
5365                     let rhs_ty = self.parse_ty()?;
5366                     where_clause.predicates.push(ast::WherePredicate::EqPredicate(
5367                         ast::WhereEqPredicate {
5368                             span: lo.to(self.prev_span),
5369                             lhs_ty: ty,
5370                             rhs_ty,
5371                             id: ast::DUMMY_NODE_ID,
5372                         }
5373                     ));
5374                 } else {
5375                     return self.unexpected();
5376                 }
5377             } else {
5378                 break
5379             }
5380
5381             if !self.eat(&token::Comma) {
5382                 break
5383             }
5384         }
5385
5386         where_clause.span = lo.to(self.prev_span);
5387         Ok(where_clause)
5388     }
5389
5390     fn parse_fn_args(&mut self, named_args: bool, allow_c_variadic: bool)
5391                      -> PResult<'a, (Vec<Arg> , bool)> {
5392         self.expect(&token::OpenDelim(token::Paren))?;
5393
5394         let sp = self.span;
5395         let mut c_variadic = false;
5396         let (args, recovered): (Vec<Option<Arg>>, bool) =
5397             self.parse_seq_to_before_end(
5398                 &token::CloseDelim(token::Paren),
5399                 SeqSep::trailing_allowed(token::Comma),
5400                 |p| {
5401                     // If the argument is a C-variadic argument we should not
5402                     // enforce named arguments.
5403                     let enforce_named_args = if p.token == token::DotDotDot {
5404                         false
5405                     } else {
5406                         named_args
5407                     };
5408                     match p.parse_arg_general(enforce_named_args, false,
5409                                               allow_c_variadic) {
5410                         Ok(arg) => {
5411                             if let TyKind::CVarArgs = arg.ty.node {
5412                                 c_variadic = true;
5413                                 if p.token != token::CloseDelim(token::Paren) {
5414                                     let span = p.span;
5415                                     p.span_err(span,
5416                                         "`...` must be the last argument of a C-variadic function");
5417                                     Ok(None)
5418                                 } else {
5419                                     Ok(Some(arg))
5420                                 }
5421                             } else {
5422                                 Ok(Some(arg))
5423                             }
5424                         },
5425                         Err(mut e) => {
5426                             e.emit();
5427                             let lo = p.prev_span;
5428                             // Skip every token until next possible arg or end.
5429                             p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
5430                             // Create a placeholder argument for proper arg count (issue #34264).
5431                             let span = lo.to(p.prev_span);
5432                             Ok(Some(dummy_arg(Ident::new(kw::Invalid, span))))
5433                         }
5434                     }
5435                 }
5436             )?;
5437
5438         if !recovered {
5439             self.eat(&token::CloseDelim(token::Paren));
5440         }
5441
5442         let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
5443
5444         if c_variadic && args.is_empty() {
5445             self.span_err(sp,
5446                           "C-variadic function must be declared with at least one named argument");
5447         }
5448
5449         Ok((args, c_variadic))
5450     }
5451
5452     /// Parses the argument list and result type of a function declaration.
5453     fn parse_fn_decl(&mut self, allow_c_variadic: bool) -> PResult<'a, P<FnDecl>> {
5454
5455         let (args, c_variadic) = self.parse_fn_args(true, allow_c_variadic)?;
5456         let ret_ty = self.parse_ret_ty(true)?;
5457
5458         Ok(P(FnDecl {
5459             inputs: args,
5460             output: ret_ty,
5461             c_variadic,
5462         }))
5463     }
5464
5465     /// Returns the parsed optional self argument and whether a self shortcut was used.
5466     fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
5467         let expect_ident = |this: &mut Self| match this.token {
5468             // Preserve hygienic context.
5469             token::Ident(ident, _) =>
5470                 { let span = this.span; this.bump(); Ident::new(ident.name, span) }
5471             _ => unreachable!()
5472         };
5473         let isolated_self = |this: &mut Self, n| {
5474             this.look_ahead(n, |t| t.is_keyword(kw::SelfLower)) &&
5475             this.look_ahead(n + 1, |t| t != &token::ModSep)
5476         };
5477
5478         // Parse optional self parameter of a method.
5479         // Only a limited set of initial token sequences is considered self parameters, anything
5480         // else is parsed as a normal function parameter list, so some lookahead is required.
5481         let eself_lo = self.span;
5482         let (eself, eself_ident, eself_hi) = match self.token {
5483             token::BinOp(token::And) => {
5484                 // &self
5485                 // &mut self
5486                 // &'lt self
5487                 // &'lt mut self
5488                 // &not_self
5489                 (if isolated_self(self, 1) {
5490                     self.bump();
5491                     SelfKind::Region(None, Mutability::Immutable)
5492                 } else if self.is_keyword_ahead(1, &[kw::Mut]) &&
5493                           isolated_self(self, 2) {
5494                     self.bump();
5495                     self.bump();
5496                     SelfKind::Region(None, Mutability::Mutable)
5497                 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5498                           isolated_self(self, 2) {
5499                     self.bump();
5500                     let lt = self.expect_lifetime();
5501                     SelfKind::Region(Some(lt), Mutability::Immutable)
5502                 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5503                           self.is_keyword_ahead(2, &[kw::Mut]) &&
5504                           isolated_self(self, 3) {
5505                     self.bump();
5506                     let lt = self.expect_lifetime();
5507                     self.bump();
5508                     SelfKind::Region(Some(lt), Mutability::Mutable)
5509                 } else {
5510                     return Ok(None);
5511                 }, expect_ident(self), self.prev_span)
5512             }
5513             token::BinOp(token::Star) => {
5514                 // *self
5515                 // *const self
5516                 // *mut self
5517                 // *not_self
5518                 // Emit special error for `self` cases.
5519                 let msg = "cannot pass `self` by raw pointer";
5520                 (if isolated_self(self, 1) {
5521                     self.bump();
5522                     self.struct_span_err(self.span, msg)
5523                         .span_label(self.span, msg)
5524                         .emit();
5525                     SelfKind::Value(Mutability::Immutable)
5526                 } else if self.look_ahead(1, |t| t.is_mutability()) &&
5527                           isolated_self(self, 2) {
5528                     self.bump();
5529                     self.bump();
5530                     self.struct_span_err(self.span, msg)
5531                         .span_label(self.span, msg)
5532                         .emit();
5533                     SelfKind::Value(Mutability::Immutable)
5534                 } else {
5535                     return Ok(None);
5536                 }, expect_ident(self), self.prev_span)
5537             }
5538             token::Ident(..) => {
5539                 if isolated_self(self, 0) {
5540                     // self
5541                     // self: TYPE
5542                     let eself_ident = expect_ident(self);
5543                     let eself_hi = self.prev_span;
5544                     (if self.eat(&token::Colon) {
5545                         let ty = self.parse_ty()?;
5546                         SelfKind::Explicit(ty, Mutability::Immutable)
5547                     } else {
5548                         SelfKind::Value(Mutability::Immutable)
5549                     }, eself_ident, eself_hi)
5550                 } else if self.token.is_keyword(kw::Mut) &&
5551                           isolated_self(self, 1) {
5552                     // mut self
5553                     // mut self: TYPE
5554                     self.bump();
5555                     let eself_ident = expect_ident(self);
5556                     let eself_hi = self.prev_span;
5557                     (if self.eat(&token::Colon) {
5558                         let ty = self.parse_ty()?;
5559                         SelfKind::Explicit(ty, Mutability::Mutable)
5560                     } else {
5561                         SelfKind::Value(Mutability::Mutable)
5562                     }, eself_ident, eself_hi)
5563                 } else {
5564                     return Ok(None);
5565                 }
5566             }
5567             _ => return Ok(None),
5568         };
5569
5570         let eself = source_map::respan(eself_lo.to(eself_hi), eself);
5571         Ok(Some(Arg::from_self(eself, eself_ident)))
5572     }
5573
5574     /// Parses the parameter list and result type of a function that may have a `self` parameter.
5575     fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
5576         where F: FnMut(&mut Parser<'a>) -> PResult<'a,  Arg>,
5577     {
5578         self.expect(&token::OpenDelim(token::Paren))?;
5579
5580         // Parse optional self argument
5581         let self_arg = self.parse_self_arg()?;
5582
5583         // Parse the rest of the function parameter list.
5584         let sep = SeqSep::trailing_allowed(token::Comma);
5585         let (mut fn_inputs, recovered) = if let Some(self_arg) = self_arg {
5586             if self.check(&token::CloseDelim(token::Paren)) {
5587                 (vec![self_arg], false)
5588             } else if self.eat(&token::Comma) {
5589                 let mut fn_inputs = vec![self_arg];
5590                 let (mut input, recovered) = self.parse_seq_to_before_end(
5591                     &token::CloseDelim(token::Paren), sep, parse_arg_fn)?;
5592                 fn_inputs.append(&mut input);
5593                 (fn_inputs, recovered)
5594             } else {
5595                 match self.expect_one_of(&[], &[]) {
5596                     Err(err) => return Err(err),
5597                     Ok(recovered) => (vec![self_arg], recovered),
5598                 }
5599             }
5600         } else {
5601             self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5602         };
5603
5604         if !recovered {
5605             // Parse closing paren and return type.
5606             self.expect(&token::CloseDelim(token::Paren))?;
5607         }
5608         // Replace duplicated recovered arguments with `_` pattern to avoid unecessary errors.
5609         self.deduplicate_recovered_arg_names(&mut fn_inputs);
5610
5611         Ok(P(FnDecl {
5612             inputs: fn_inputs,
5613             output: self.parse_ret_ty(true)?,
5614             c_variadic: false
5615         }))
5616     }
5617
5618     /// Parses the `|arg, arg|` header of a closure.
5619     fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
5620         let inputs_captures = {
5621             if self.eat(&token::OrOr) {
5622                 Vec::new()
5623             } else {
5624                 self.expect(&token::BinOp(token::Or))?;
5625                 let args = self.parse_seq_to_before_tokens(
5626                     &[&token::BinOp(token::Or), &token::OrOr],
5627                     SeqSep::trailing_allowed(token::Comma),
5628                     TokenExpectType::NoExpect,
5629                     |p| p.parse_fn_block_arg()
5630                 )?.0;
5631                 self.expect_or()?;
5632                 args
5633             }
5634         };
5635         let output = self.parse_ret_ty(true)?;
5636
5637         Ok(P(FnDecl {
5638             inputs: inputs_captures,
5639             output,
5640             c_variadic: false
5641         }))
5642     }
5643
5644     /// Parses the name and optional generic types of a function header.
5645     fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
5646         let id = self.parse_ident()?;
5647         let generics = self.parse_generics()?;
5648         Ok((id, generics))
5649     }
5650
5651     fn mk_item(&self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
5652                attrs: Vec<Attribute>) -> P<Item> {
5653         P(Item {
5654             ident,
5655             attrs,
5656             id: ast::DUMMY_NODE_ID,
5657             node,
5658             vis,
5659             span,
5660             tokens: None,
5661         })
5662     }
5663
5664     /// Parses an item-position function declaration.
5665     fn parse_item_fn(&mut self,
5666                      unsafety: Unsafety,
5667                      mut asyncness: Spanned<IsAsync>,
5668                      constness: Spanned<Constness>,
5669                      abi: Abi)
5670                      -> PResult<'a, ItemInfo> {
5671         let (ident, mut generics) = self.parse_fn_header()?;
5672         let allow_c_variadic = abi == Abi::C && unsafety == Unsafety::Unsafe;
5673         let mut decl = self.parse_fn_decl(allow_c_variadic)?;
5674         generics.where_clause = self.parse_where_clause()?;
5675         let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5676         self.construct_async_arguments(&mut asyncness, &mut decl);
5677         let header = FnHeader { unsafety, asyncness, constness, abi };
5678         Ok((ident, ItemKind::Fn(decl, header, generics, body), Some(inner_attrs)))
5679     }
5680
5681     /// Returns `true` if we are looking at `const ID`
5682     /// (returns `false` for things like `const fn`, etc.).
5683     fn is_const_item(&self) -> bool {
5684         self.token.is_keyword(kw::Const) &&
5685             !self.is_keyword_ahead(1, &[kw::Fn, kw::Unsafe])
5686     }
5687
5688     /// Parses all the "front matter" for a `fn` declaration, up to
5689     /// and including the `fn` keyword:
5690     ///
5691     /// - `const fn`
5692     /// - `unsafe fn`
5693     /// - `const unsafe fn`
5694     /// - `extern fn`
5695     /// - etc.
5696     fn parse_fn_front_matter(&mut self)
5697         -> PResult<'a, (
5698             Spanned<Constness>,
5699             Unsafety,
5700             Spanned<IsAsync>,
5701             Abi
5702         )>
5703     {
5704         let is_const_fn = self.eat_keyword(kw::Const);
5705         let const_span = self.prev_span;
5706         let unsafety = self.parse_unsafety();
5707         let asyncness = self.parse_asyncness();
5708         let asyncness = respan(self.prev_span, asyncness);
5709         let (constness, unsafety, abi) = if is_const_fn {
5710             (respan(const_span, Constness::Const), unsafety, Abi::Rust)
5711         } else {
5712             let abi = if self.eat_keyword(kw::Extern) {
5713                 self.parse_opt_abi()?.unwrap_or(Abi::C)
5714             } else {
5715                 Abi::Rust
5716             };
5717             (respan(self.prev_span, Constness::NotConst), unsafety, abi)
5718         };
5719         if !self.eat_keyword(kw::Fn) {
5720             // It is possible for `expect_one_of` to recover given the contents of
5721             // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
5722             // account for this.
5723             if !self.expect_one_of(&[], &[])? { unreachable!() }
5724         }
5725         Ok((constness, unsafety, asyncness, abi))
5726     }
5727
5728     /// Parses an impl item.
5729     pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
5730         maybe_whole!(self, NtImplItem, |x| x);
5731         let attrs = self.parse_outer_attributes()?;
5732         let mut unclosed_delims = vec![];
5733         let (mut item, tokens) = self.collect_tokens(|this| {
5734             let item = this.parse_impl_item_(at_end, attrs);
5735             unclosed_delims.append(&mut this.unclosed_delims);
5736             item
5737         })?;
5738         self.unclosed_delims.append(&mut unclosed_delims);
5739
5740         // See `parse_item` for why this clause is here.
5741         if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
5742             item.tokens = Some(tokens);
5743         }
5744         Ok(item)
5745     }
5746
5747     fn parse_impl_item_(&mut self,
5748                         at_end: &mut bool,
5749                         mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
5750         let lo = self.span;
5751         let vis = self.parse_visibility(false)?;
5752         let defaultness = self.parse_defaultness();
5753         let (name, node, generics) = if let Some(type_) = self.eat_type() {
5754             let (name, alias, generics) = type_?;
5755             let kind = match alias {
5756                 AliasKind::Weak(typ) => ast::ImplItemKind::Type(typ),
5757                 AliasKind::Existential(bounds) => ast::ImplItemKind::Existential(bounds),
5758             };
5759             (name, kind, generics)
5760         } else if self.is_const_item() {
5761             // This parses the grammar:
5762             //     ImplItemConst = "const" Ident ":" Ty "=" Expr ";"
5763             self.expect_keyword(kw::Const)?;
5764             let name = self.parse_ident()?;
5765             self.expect(&token::Colon)?;
5766             let typ = self.parse_ty()?;
5767             self.expect(&token::Eq)?;
5768             let expr = self.parse_expr()?;
5769             self.expect(&token::Semi)?;
5770             (name, ast::ImplItemKind::Const(typ, expr), ast::Generics::default())
5771         } else {
5772             let (name, inner_attrs, generics, node) = self.parse_impl_method(&vis, at_end)?;
5773             attrs.extend(inner_attrs);
5774             (name, node, generics)
5775         };
5776
5777         Ok(ImplItem {
5778             id: ast::DUMMY_NODE_ID,
5779             span: lo.to(self.prev_span),
5780             ident: name,
5781             vis,
5782             defaultness,
5783             attrs,
5784             generics,
5785             node,
5786             tokens: None,
5787         })
5788     }
5789
5790     fn complain_if_pub_macro(&self, vis: &VisibilityKind, sp: Span) {
5791         match *vis {
5792             VisibilityKind::Inherited => {}
5793             _ => {
5794                 let is_macro_rules: bool = match self.token {
5795                     token::Ident(sid, _) => sid.name == sym::macro_rules,
5796                     _ => false,
5797                 };
5798                 let mut err = if is_macro_rules {
5799                     let mut err = self.diagnostic()
5800                         .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
5801                     err.span_suggestion(
5802                         sp,
5803                         "try exporting the macro",
5804                         "#[macro_export]".to_owned(),
5805                         Applicability::MaybeIncorrect // speculative
5806                     );
5807                     err
5808                 } else {
5809                     let mut err = self.diagnostic()
5810                         .struct_span_err(sp, "can't qualify macro invocation with `pub`");
5811                     err.help("try adjusting the macro to put `pub` inside the invocation");
5812                     err
5813                 };
5814                 err.emit();
5815             }
5816         }
5817     }
5818
5819     fn missing_assoc_item_kind_err(&self, item_type: &str, prev_span: Span)
5820                                    -> DiagnosticBuilder<'a>
5821     {
5822         let expected_kinds = if item_type == "extern" {
5823             "missing `fn`, `type`, or `static`"
5824         } else {
5825             "missing `fn`, `type`, or `const`"
5826         };
5827
5828         // Given this code `path(`, it seems like this is not
5829         // setting the visibility of a macro invocation, but rather
5830         // a mistyped method declaration.
5831         // Create a diagnostic pointing out that `fn` is missing.
5832         //
5833         // x |     pub path(&self) {
5834         //   |        ^ missing `fn`, `type`, or `const`
5835         //     pub  path(
5836         //        ^^ `sp` below will point to this
5837         let sp = prev_span.between(self.prev_span);
5838         let mut err = self.diagnostic().struct_span_err(
5839             sp,
5840             &format!("{} for {}-item declaration",
5841                      expected_kinds, item_type));
5842         err.span_label(sp, expected_kinds);
5843         err
5844     }
5845
5846     /// Parse a method or a macro invocation in a trait impl.
5847     fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
5848                          -> PResult<'a, (Ident, Vec<Attribute>, ast::Generics,
5849                              ast::ImplItemKind)> {
5850         // code copied from parse_macro_use_or_failure... abstraction!
5851         if let Some(mac) = self.parse_assoc_macro_invoc("impl", Some(vis), at_end)? {
5852             // method macro
5853             Ok((Ident::invalid(), vec![], ast::Generics::default(),
5854                 ast::ImplItemKind::Macro(mac)))
5855         } else {
5856             let (constness, unsafety, mut asyncness, abi) = self.parse_fn_front_matter()?;
5857             let ident = self.parse_ident()?;
5858             let mut generics = self.parse_generics()?;
5859             let mut decl = self.parse_fn_decl_with_self(|p| {
5860                 p.parse_arg_general(true, true, false)
5861             })?;
5862             generics.where_clause = self.parse_where_clause()?;
5863             self.construct_async_arguments(&mut asyncness, &mut decl);
5864             *at_end = true;
5865             let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5866             let header = ast::FnHeader { abi, unsafety, constness, asyncness };
5867             Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method(
5868                 ast::MethodSig { header, decl },
5869                 body
5870             )))
5871         }
5872     }
5873
5874     /// Parses `trait Foo { ... }` or `trait Foo = Bar;`.
5875     fn parse_item_trait(&mut self, is_auto: IsAuto, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
5876         let ident = self.parse_ident()?;
5877         let mut tps = self.parse_generics()?;
5878
5879         // Parse optional colon and supertrait bounds.
5880         let bounds = if self.eat(&token::Colon) {
5881             self.parse_generic_bounds(Some(self.prev_span))?
5882         } else {
5883             Vec::new()
5884         };
5885
5886         if self.eat(&token::Eq) {
5887             // it's a trait alias
5888             let bounds = self.parse_generic_bounds(None)?;
5889             tps.where_clause = self.parse_where_clause()?;
5890             self.expect(&token::Semi)?;
5891             if is_auto == IsAuto::Yes {
5892                 let msg = "trait aliases cannot be `auto`";
5893                 self.struct_span_err(self.prev_span, msg)
5894                     .span_label(self.prev_span, msg)
5895                     .emit();
5896             }
5897             if unsafety != Unsafety::Normal {
5898                 let msg = "trait aliases cannot be `unsafe`";
5899                 self.struct_span_err(self.prev_span, msg)
5900                     .span_label(self.prev_span, msg)
5901                     .emit();
5902             }
5903             Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
5904         } else {
5905             // it's a normal trait
5906             tps.where_clause = self.parse_where_clause()?;
5907             self.expect(&token::OpenDelim(token::Brace))?;
5908             let mut trait_items = vec![];
5909             while !self.eat(&token::CloseDelim(token::Brace)) {
5910                 if let token::DocComment(_) = self.token {
5911                     if self.look_ahead(1,
5912                     |tok| tok == &token::Token::CloseDelim(token::Brace)) {
5913                         let mut err = self.diagnostic().struct_span_err_with_code(
5914                             self.span,
5915                             "found a documentation comment that doesn't document anything",
5916                             DiagnosticId::Error("E0584".into()),
5917                         );
5918                         err.help("doc comments must come before what they document, maybe a \
5919                             comment was intended with `//`?",
5920                         );
5921                         err.emit();
5922                         self.bump();
5923                         continue;
5924                     }
5925                 }
5926                 let mut at_end = false;
5927                 match self.parse_trait_item(&mut at_end) {
5928                     Ok(item) => trait_items.push(item),
5929                     Err(mut e) => {
5930                         e.emit();
5931                         if !at_end {
5932                             self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5933                         }
5934                     }
5935                 }
5936             }
5937             Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
5938         }
5939     }
5940
5941     fn choose_generics_over_qpath(&self) -> bool {
5942         // There's an ambiguity between generic parameters and qualified paths in impls.
5943         // If we see `<` it may start both, so we have to inspect some following tokens.
5944         // The following combinations can only start generics,
5945         // but not qualified paths (with one exception):
5946         //     `<` `>` - empty generic parameters
5947         //     `<` `#` - generic parameters with attributes
5948         //     `<` (LIFETIME|IDENT) `>` - single generic parameter
5949         //     `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
5950         //     `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
5951         //     `<` (LIFETIME|IDENT) `=` - generic parameter with a default
5952         //     `<` const                - generic const parameter
5953         // The only truly ambiguous case is
5954         //     `<` IDENT `>` `::` IDENT ...
5955         // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
5956         // because this is what almost always expected in practice, qualified paths in impls
5957         // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
5958         self.token == token::Lt &&
5959             (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) ||
5960              self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) &&
5961                 self.look_ahead(2, |t| t == &token::Gt || t == &token::Comma ||
5962                                        t == &token::Colon || t == &token::Eq) ||
5963             self.is_keyword_ahead(1, &[kw::Const]))
5964     }
5965
5966     fn parse_impl_body(&mut self) -> PResult<'a, (Vec<ImplItem>, Vec<Attribute>)> {
5967         self.expect(&token::OpenDelim(token::Brace))?;
5968         let attrs = self.parse_inner_attributes()?;
5969
5970         let mut impl_items = Vec::new();
5971         while !self.eat(&token::CloseDelim(token::Brace)) {
5972             let mut at_end = false;
5973             match self.parse_impl_item(&mut at_end) {
5974                 Ok(impl_item) => impl_items.push(impl_item),
5975                 Err(mut err) => {
5976                     err.emit();
5977                     if !at_end {
5978                         self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5979                     }
5980                 }
5981             }
5982         }
5983         Ok((impl_items, attrs))
5984     }
5985
5986     /// Parses an implementation item, `impl` keyword is already parsed.
5987     ///
5988     ///    impl<'a, T> TYPE { /* impl items */ }
5989     ///    impl<'a, T> TRAIT for TYPE { /* impl items */ }
5990     ///    impl<'a, T> !TRAIT for TYPE { /* impl items */ }
5991     ///
5992     /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
5993     ///     `impl` GENERICS `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
5994     ///     `impl` GENERICS `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
5995     fn parse_item_impl(&mut self, unsafety: Unsafety, defaultness: Defaultness)
5996                        -> PResult<'a, ItemInfo> {
5997         // First, parse generic parameters if necessary.
5998         let mut generics = if self.choose_generics_over_qpath() {
5999             self.parse_generics()?
6000         } else {
6001             ast::Generics::default()
6002         };
6003
6004         // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
6005         let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
6006             self.bump(); // `!`
6007             ast::ImplPolarity::Negative
6008         } else {
6009             ast::ImplPolarity::Positive
6010         };
6011
6012         // Parse both types and traits as a type, then reinterpret if necessary.
6013         let err_path = |span| ast::Path::from_ident(Ident::new(kw::Invalid, span));
6014         let ty_first = if self.token.is_keyword(kw::For) &&
6015                           self.look_ahead(1, |t| t != &token::Lt) {
6016             let span = self.prev_span.between(self.span);
6017             self.struct_span_err(span, "missing trait in a trait impl").emit();
6018             P(Ty { node: TyKind::Path(None, err_path(span)), span, id: ast::DUMMY_NODE_ID })
6019         } else {
6020             self.parse_ty()?
6021         };
6022
6023         // If `for` is missing we try to recover.
6024         let has_for = self.eat_keyword(kw::For);
6025         let missing_for_span = self.prev_span.between(self.span);
6026
6027         let ty_second = if self.token == token::DotDot {
6028             // We need to report this error after `cfg` expansion for compatibility reasons
6029             self.bump(); // `..`, do not add it to expected tokens
6030             Some(DummyResult::raw_ty(self.prev_span, true))
6031         } else if has_for || self.token.can_begin_type() {
6032             Some(self.parse_ty()?)
6033         } else {
6034             None
6035         };
6036
6037         generics.where_clause = self.parse_where_clause()?;
6038
6039         let (impl_items, attrs) = self.parse_impl_body()?;
6040
6041         let item_kind = match ty_second {
6042             Some(ty_second) => {
6043                 // impl Trait for Type
6044                 if !has_for {
6045                     self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
6046                         .span_suggestion_short(
6047                             missing_for_span,
6048                             "add `for` here",
6049                             " for ".to_string(),
6050                             Applicability::MachineApplicable,
6051                         ).emit();
6052                 }
6053
6054                 let ty_first = ty_first.into_inner();
6055                 let path = match ty_first.node {
6056                     // This notably includes paths passed through `ty` macro fragments (#46438).
6057                     TyKind::Path(None, path) => path,
6058                     _ => {
6059                         self.span_err(ty_first.span, "expected a trait, found type");
6060                         err_path(ty_first.span)
6061                     }
6062                 };
6063                 let trait_ref = TraitRef { path, ref_id: ty_first.id };
6064
6065                 ItemKind::Impl(unsafety, polarity, defaultness,
6066                                generics, Some(trait_ref), ty_second, impl_items)
6067             }
6068             None => {
6069                 // impl Type
6070                 ItemKind::Impl(unsafety, polarity, defaultness,
6071                                generics, None, ty_first, impl_items)
6072             }
6073         };
6074
6075         Ok((Ident::invalid(), item_kind, Some(attrs)))
6076     }
6077
6078     fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
6079         if self.eat_keyword(kw::For) {
6080             self.expect_lt()?;
6081             let params = self.parse_generic_params()?;
6082             self.expect_gt()?;
6083             // We rely on AST validation to rule out invalid cases: There must not be type
6084             // parameters, and the lifetime parameters must not have bounds.
6085             Ok(params)
6086         } else {
6087             Ok(Vec::new())
6088         }
6089     }
6090
6091     /// Parses `struct Foo { ... }`.
6092     fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
6093         let class_name = self.parse_ident()?;
6094
6095         let mut generics = self.parse_generics()?;
6096
6097         // There is a special case worth noting here, as reported in issue #17904.
6098         // If we are parsing a tuple struct it is the case that the where clause
6099         // should follow the field list. Like so:
6100         //
6101         // struct Foo<T>(T) where T: Copy;
6102         //
6103         // If we are parsing a normal record-style struct it is the case
6104         // that the where clause comes before the body, and after the generics.
6105         // So if we look ahead and see a brace or a where-clause we begin
6106         // parsing a record style struct.
6107         //
6108         // Otherwise if we look ahead and see a paren we parse a tuple-style
6109         // struct.
6110
6111         let vdata = if self.token.is_keyword(kw::Where) {
6112             generics.where_clause = self.parse_where_clause()?;
6113             if self.eat(&token::Semi) {
6114                 // If we see a: `struct Foo<T> where T: Copy;` style decl.
6115                 VariantData::Unit(ast::DUMMY_NODE_ID)
6116             } else {
6117                 // If we see: `struct Foo<T> where T: Copy { ... }`
6118                 let (fields, recovered) = self.parse_record_struct_body()?;
6119                 VariantData::Struct(fields, recovered)
6120             }
6121         // No `where` so: `struct Foo<T>;`
6122         } else if self.eat(&token::Semi) {
6123             VariantData::Unit(ast::DUMMY_NODE_ID)
6124         // Record-style struct definition
6125         } else if self.token == token::OpenDelim(token::Brace) {
6126             let (fields, recovered) = self.parse_record_struct_body()?;
6127             VariantData::Struct(fields, recovered)
6128         // Tuple-style struct definition with optional where-clause.
6129         } else if self.token == token::OpenDelim(token::Paren) {
6130             let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
6131             generics.where_clause = self.parse_where_clause()?;
6132             self.expect(&token::Semi)?;
6133             body
6134         } else {
6135             let token_str = self.this_token_descr();
6136             let mut err = self.fatal(&format!(
6137                 "expected `where`, `{{`, `(`, or `;` after struct name, found {}",
6138                 token_str
6139             ));
6140             err.span_label(self.span, "expected `where`, `{`, `(`, or `;` after struct name");
6141             return Err(err);
6142         };
6143
6144         Ok((class_name, ItemKind::Struct(vdata, generics), None))
6145     }
6146
6147     /// Parses `union Foo { ... }`.
6148     fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
6149         let class_name = self.parse_ident()?;
6150
6151         let mut generics = self.parse_generics()?;
6152
6153         let vdata = if self.token.is_keyword(kw::Where) {
6154             generics.where_clause = self.parse_where_clause()?;
6155             let (fields, recovered) = self.parse_record_struct_body()?;
6156             VariantData::Struct(fields, recovered)
6157         } else if self.token == token::OpenDelim(token::Brace) {
6158             let (fields, recovered) = self.parse_record_struct_body()?;
6159             VariantData::Struct(fields, recovered)
6160         } else {
6161             let token_str = self.this_token_descr();
6162             let mut err = self.fatal(&format!(
6163                 "expected `where` or `{{` after union name, found {}", token_str));
6164             err.span_label(self.span, "expected `where` or `{` after union name");
6165             return Err(err);
6166         };
6167
6168         Ok((class_name, ItemKind::Union(vdata, generics), None))
6169     }
6170
6171     fn parse_record_struct_body(
6172         &mut self,
6173     ) -> PResult<'a, (Vec<StructField>, /* recovered */ bool)> {
6174         let mut fields = Vec::new();
6175         let mut recovered = false;
6176         if self.eat(&token::OpenDelim(token::Brace)) {
6177             while self.token != token::CloseDelim(token::Brace) {
6178                 let field = self.parse_struct_decl_field().map_err(|e| {
6179                     self.recover_stmt();
6180                     recovered = true;
6181                     e
6182                 });
6183                 match field {
6184                     Ok(field) => fields.push(field),
6185                     Err(mut err) => {
6186                         err.emit();
6187                     }
6188                 }
6189             }
6190             self.eat(&token::CloseDelim(token::Brace));
6191         } else {
6192             let token_str = self.this_token_descr();
6193             let mut err = self.fatal(&format!(
6194                     "expected `where`, or `{{` after struct name, found {}", token_str));
6195             err.span_label(self.span, "expected `where`, or `{` after struct name");
6196             return Err(err);
6197         }
6198
6199         Ok((fields, recovered))
6200     }
6201
6202     fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
6203         // This is the case where we find `struct Foo<T>(T) where T: Copy;`
6204         // Unit like structs are handled in parse_item_struct function
6205         let fields = self.parse_unspanned_seq(
6206             &token::OpenDelim(token::Paren),
6207             &token::CloseDelim(token::Paren),
6208             SeqSep::trailing_allowed(token::Comma),
6209             |p| {
6210                 let attrs = p.parse_outer_attributes()?;
6211                 let lo = p.span;
6212                 let vis = p.parse_visibility(true)?;
6213                 let ty = p.parse_ty()?;
6214                 Ok(StructField {
6215                     span: lo.to(ty.span),
6216                     vis,
6217                     ident: None,
6218                     id: ast::DUMMY_NODE_ID,
6219                     ty,
6220                     attrs,
6221                 })
6222             })?;
6223
6224         Ok(fields)
6225     }
6226
6227     /// Parses a structure field declaration.
6228     fn parse_single_struct_field(&mut self,
6229                                      lo: Span,
6230                                      vis: Visibility,
6231                                      attrs: Vec<Attribute> )
6232                                      -> PResult<'a, StructField> {
6233         let mut seen_comma: bool = false;
6234         let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
6235         if self.token == token::Comma {
6236             seen_comma = true;
6237         }
6238         match self.token {
6239             token::Comma => {
6240                 self.bump();
6241             }
6242             token::CloseDelim(token::Brace) => {}
6243             token::DocComment(_) => {
6244                 let previous_span = self.prev_span;
6245                 let mut err = self.span_fatal_err(self.span, Error::UselessDocComment);
6246                 self.bump(); // consume the doc comment
6247                 let comma_after_doc_seen = self.eat(&token::Comma);
6248                 // `seen_comma` is always false, because we are inside doc block
6249                 // condition is here to make code more readable
6250                 if seen_comma == false && comma_after_doc_seen == true {
6251                     seen_comma = true;
6252                 }
6253                 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
6254                     err.emit();
6255                 } else {
6256                     if seen_comma == false {
6257                         let sp = self.sess.source_map().next_point(previous_span);
6258                         err.span_suggestion(
6259                             sp,
6260                             "missing comma here",
6261                             ",".into(),
6262                             Applicability::MachineApplicable
6263                         );
6264                     }
6265                     return Err(err);
6266                 }
6267             }
6268             _ => {
6269                 let sp = self.sess.source_map().next_point(self.prev_span);
6270                 let mut err = self.struct_span_err(sp, &format!("expected `,`, or `}}`, found {}",
6271                                                                 self.this_token_descr()));
6272                 if self.token.is_ident() {
6273                     // This is likely another field; emit the diagnostic and keep going
6274                     err.span_suggestion(
6275                         sp,
6276                         "try adding a comma",
6277                         ",".into(),
6278                         Applicability::MachineApplicable,
6279                     );
6280                     err.emit();
6281                 } else {
6282                     return Err(err)
6283                 }
6284             }
6285         }
6286         Ok(a_var)
6287     }
6288
6289     /// Parses an element of a struct declaration.
6290     fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
6291         let attrs = self.parse_outer_attributes()?;
6292         let lo = self.span;
6293         let vis = self.parse_visibility(false)?;
6294         self.parse_single_struct_field(lo, vis, attrs)
6295     }
6296
6297     /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
6298     /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
6299     /// If the following element can't be a tuple (i.e., it's a function definition), then
6300     /// it's not a tuple struct field), and the contents within the parentheses isn't valid,
6301     /// so emit a proper diagnostic.
6302     pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
6303         maybe_whole!(self, NtVis, |x| x);
6304
6305         self.expected_tokens.push(TokenType::Keyword(kw::Crate));
6306         if self.is_crate_vis() {
6307             self.bump(); // `crate`
6308             return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
6309         }
6310
6311         if !self.eat_keyword(kw::Pub) {
6312             // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
6313             // keyword to grab a span from for inherited visibility; an empty span at the
6314             // beginning of the current token would seem to be the "Schelling span".
6315             return Ok(respan(self.span.shrink_to_lo(), VisibilityKind::Inherited))
6316         }
6317         let lo = self.prev_span;
6318
6319         if self.check(&token::OpenDelim(token::Paren)) {
6320             // We don't `self.bump()` the `(` yet because this might be a struct definition where
6321             // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
6322             // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
6323             // by the following tokens.
6324             if self.is_keyword_ahead(1, &[kw::Crate]) &&
6325                 self.look_ahead(2, |t| t != &token::ModSep) // account for `pub(crate::foo)`
6326             {
6327                 // `pub(crate)`
6328                 self.bump(); // `(`
6329                 self.bump(); // `crate`
6330                 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6331                 let vis = respan(
6332                     lo.to(self.prev_span),
6333                     VisibilityKind::Crate(CrateSugar::PubCrate),
6334                 );
6335                 return Ok(vis)
6336             } else if self.is_keyword_ahead(1, &[kw::In]) {
6337                 // `pub(in path)`
6338                 self.bump(); // `(`
6339                 self.bump(); // `in`
6340                 let path = self.parse_path(PathStyle::Mod)?; // `path`
6341                 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6342                 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6343                     path: P(path),
6344                     id: ast::DUMMY_NODE_ID,
6345                 });
6346                 return Ok(vis)
6347             } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
6348                       self.is_keyword_ahead(1, &[kw::Super, kw::SelfLower])
6349             {
6350                 // `pub(self)` or `pub(super)`
6351                 self.bump(); // `(`
6352                 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
6353                 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6354                 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6355                     path: P(path),
6356                     id: ast::DUMMY_NODE_ID,
6357                 });
6358                 return Ok(vis)
6359             } else if !can_take_tuple {  // Provide this diagnostic if this is not a tuple struct
6360                 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
6361                 self.bump(); // `(`
6362                 let msg = "incorrect visibility restriction";
6363                 let suggestion = r##"some possible visibility restrictions are:
6364 `pub(crate)`: visible only on the current crate
6365 `pub(super)`: visible only in the current module's parent
6366 `pub(in path::to::module)`: visible only on the specified path"##;
6367                 let path = self.parse_path(PathStyle::Mod)?;
6368                 let sp = path.span;
6369                 let help_msg = format!("make this visible only to module `{}` with `in`", path);
6370                 self.expect(&token::CloseDelim(token::Paren))?;  // `)`
6371                 let mut err = struct_span_err!(self.sess.span_diagnostic, sp, E0704, "{}", msg);
6372                 err.help(suggestion);
6373                 err.span_suggestion(
6374                     sp, &help_msg, format!("in {}", path), Applicability::MachineApplicable
6375                 );
6376                 err.emit();  // emit diagnostic, but continue with public visibility
6377             }
6378         }
6379
6380         Ok(respan(lo, VisibilityKind::Public))
6381     }
6382
6383     /// Parses defaultness (i.e., `default` or nothing).
6384     fn parse_defaultness(&mut self) -> Defaultness {
6385         // `pub` is included for better error messages
6386         if self.check_keyword(kw::Default) &&
6387             self.is_keyword_ahead(1, &[
6388                 kw::Impl,
6389                 kw::Const,
6390                 kw::Fn,
6391                 kw::Unsafe,
6392                 kw::Extern,
6393                 kw::Type,
6394                 kw::Pub,
6395             ])
6396         {
6397             self.bump(); // `default`
6398             Defaultness::Default
6399         } else {
6400             Defaultness::Final
6401         }
6402     }
6403
6404     /// Given a termination token, parses all of the items in a module.
6405     fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
6406         let mut items = vec![];
6407         while let Some(item) = self.parse_item()? {
6408             items.push(item);
6409             self.maybe_consume_incorrect_semicolon(&items);
6410         }
6411
6412         if !self.eat(term) {
6413             let token_str = self.this_token_descr();
6414             if !self.maybe_consume_incorrect_semicolon(&items) {
6415                 let mut err = self.fatal(&format!("expected item, found {}", token_str));
6416                 err.span_label(self.span, "expected item");
6417                 return Err(err);
6418             }
6419         }
6420
6421         let hi = if self.span.is_dummy() {
6422             inner_lo
6423         } else {
6424             self.prev_span
6425         };
6426
6427         Ok(ast::Mod {
6428             inner: inner_lo.to(hi),
6429             items,
6430             inline: true
6431         })
6432     }
6433
6434     fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
6435         let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
6436         self.expect(&token::Colon)?;
6437         let ty = self.parse_ty()?;
6438         self.expect(&token::Eq)?;
6439         let e = self.parse_expr()?;
6440         self.expect(&token::Semi)?;
6441         let item = match m {
6442             Some(m) => ItemKind::Static(ty, m, e),
6443             None => ItemKind::Const(ty, e),
6444         };
6445         Ok((id, item, None))
6446     }
6447
6448     /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
6449     fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
6450         let (in_cfg, outer_attrs) = {
6451             let mut strip_unconfigured = crate::config::StripUnconfigured {
6452                 sess: self.sess,
6453                 features: None, // don't perform gated feature checking
6454             };
6455             let mut outer_attrs = outer_attrs.to_owned();
6456             strip_unconfigured.process_cfg_attrs(&mut outer_attrs);
6457             (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
6458         };
6459
6460         let id_span = self.span;
6461         let id = self.parse_ident()?;
6462         if self.eat(&token::Semi) {
6463             if in_cfg && self.recurse_into_file_modules {
6464                 // This mod is in an external file. Let's go get it!
6465                 let ModulePathSuccess { path, directory_ownership, warn } =
6466                     self.submod_path(id, &outer_attrs, id_span)?;
6467                 let (module, mut attrs) =
6468                     self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
6469                 // Record that we fetched the mod from an external file
6470                 if warn {
6471                     let attr = Attribute {
6472                         id: attr::mk_attr_id(),
6473                         style: ast::AttrStyle::Outer,
6474                         path: ast::Path::from_ident(
6475                             Ident::with_empty_ctxt(sym::warn_directory_ownership)),
6476                         tokens: TokenStream::empty(),
6477                         is_sugared_doc: false,
6478                         span: DUMMY_SP,
6479                     };
6480                     attr::mark_known(&attr);
6481                     attrs.push(attr);
6482                 }
6483                 Ok((id, ItemKind::Mod(module), Some(attrs)))
6484             } else {
6485                 let placeholder = ast::Mod {
6486                     inner: DUMMY_SP,
6487                     items: Vec::new(),
6488                     inline: false
6489                 };
6490                 Ok((id, ItemKind::Mod(placeholder), None))
6491             }
6492         } else {
6493             let old_directory = self.directory.clone();
6494             self.push_directory(id, &outer_attrs);
6495
6496             self.expect(&token::OpenDelim(token::Brace))?;
6497             let mod_inner_lo = self.span;
6498             let attrs = self.parse_inner_attributes()?;
6499             let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
6500
6501             self.directory = old_directory;
6502             Ok((id, ItemKind::Mod(module), Some(attrs)))
6503         }
6504     }
6505
6506     fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
6507         if let Some(path) = attr::first_attr_value_str_by_name(attrs, sym::path) {
6508             self.directory.path.to_mut().push(&path.as_str());
6509             self.directory.ownership = DirectoryOwnership::Owned { relative: None };
6510         } else {
6511             // We have to push on the current module name in the case of relative
6512             // paths in order to ensure that any additional module paths from inline
6513             // `mod x { ... }` come after the relative extension.
6514             //
6515             // For example, a `mod z { ... }` inside `x/y.rs` should set the current
6516             // directory path to `/x/y/z`, not `/x/z` with a relative offset of `y`.
6517             if let DirectoryOwnership::Owned { relative } = &mut self.directory.ownership {
6518                 if let Some(ident) = relative.take() { // remove the relative offset
6519                     self.directory.path.to_mut().push(ident.as_str());
6520                 }
6521             }
6522             self.directory.path.to_mut().push(&id.as_str());
6523         }
6524     }
6525
6526     pub fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> {
6527         if let Some(s) = attr::first_attr_value_str_by_name(attrs, sym::path) {
6528             let s = s.as_str();
6529
6530             // On windows, the base path might have the form
6531             // `\\?\foo\bar` in which case it does not tolerate
6532             // mixed `/` and `\` separators, so canonicalize
6533             // `/` to `\`.
6534             #[cfg(windows)]
6535             let s = s.replace("/", "\\");
6536             Some(dir_path.join(s))
6537         } else {
6538             None
6539         }
6540     }
6541
6542     /// Returns a path to a module.
6543     pub fn default_submod_path(
6544         id: ast::Ident,
6545         relative: Option<ast::Ident>,
6546         dir_path: &Path,
6547         source_map: &SourceMap) -> ModulePath
6548     {
6549         // If we're in a foo.rs file instead of a mod.rs file,
6550         // we need to look for submodules in
6551         // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
6552         // `./<id>.rs` and `./<id>/mod.rs`.
6553         let relative_prefix_string;
6554         let relative_prefix = if let Some(ident) = relative {
6555             relative_prefix_string = format!("{}{}", ident.as_str(), path::MAIN_SEPARATOR);
6556             &relative_prefix_string
6557         } else {
6558             ""
6559         };
6560
6561         let mod_name = id.to_string();
6562         let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
6563         let secondary_path_str = format!("{}{}{}mod.rs",
6564                                          relative_prefix, mod_name, path::MAIN_SEPARATOR);
6565         let default_path = dir_path.join(&default_path_str);
6566         let secondary_path = dir_path.join(&secondary_path_str);
6567         let default_exists = source_map.file_exists(&default_path);
6568         let secondary_exists = source_map.file_exists(&secondary_path);
6569
6570         let result = match (default_exists, secondary_exists) {
6571             (true, false) => Ok(ModulePathSuccess {
6572                 path: default_path,
6573                 directory_ownership: DirectoryOwnership::Owned {
6574                     relative: Some(id),
6575                 },
6576                 warn: false,
6577             }),
6578             (false, true) => Ok(ModulePathSuccess {
6579                 path: secondary_path,
6580                 directory_ownership: DirectoryOwnership::Owned {
6581                     relative: None,
6582                 },
6583                 warn: false,
6584             }),
6585             (false, false) => Err(Error::FileNotFoundForModule {
6586                 mod_name: mod_name.clone(),
6587                 default_path: default_path_str,
6588                 secondary_path: secondary_path_str,
6589                 dir_path: dir_path.display().to_string(),
6590             }),
6591             (true, true) => Err(Error::DuplicatePaths {
6592                 mod_name: mod_name.clone(),
6593                 default_path: default_path_str,
6594                 secondary_path: secondary_path_str,
6595             }),
6596         };
6597
6598         ModulePath {
6599             name: mod_name,
6600             path_exists: default_exists || secondary_exists,
6601             result,
6602         }
6603     }
6604
6605     fn submod_path(&mut self,
6606                    id: ast::Ident,
6607                    outer_attrs: &[Attribute],
6608                    id_sp: Span)
6609                    -> PResult<'a, ModulePathSuccess> {
6610         if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
6611             return Ok(ModulePathSuccess {
6612                 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
6613                     // All `#[path]` files are treated as though they are a `mod.rs` file.
6614                     // This means that `mod foo;` declarations inside `#[path]`-included
6615                     // files are siblings,
6616                     //
6617                     // Note that this will produce weirdness when a file named `foo.rs` is
6618                     // `#[path]` included and contains a `mod foo;` declaration.
6619                     // If you encounter this, it's your own darn fault :P
6620                     Some(_) => DirectoryOwnership::Owned { relative: None },
6621                     _ => DirectoryOwnership::UnownedViaMod(true),
6622                 },
6623                 path,
6624                 warn: false,
6625             });
6626         }
6627
6628         let relative = match self.directory.ownership {
6629             DirectoryOwnership::Owned { relative } => relative,
6630             DirectoryOwnership::UnownedViaBlock |
6631             DirectoryOwnership::UnownedViaMod(_) => None,
6632         };
6633         let paths = Parser::default_submod_path(
6634                         id, relative, &self.directory.path, self.sess.source_map());
6635
6636         match self.directory.ownership {
6637             DirectoryOwnership::Owned { .. } => {
6638                 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
6639             },
6640             DirectoryOwnership::UnownedViaBlock => {
6641                 let msg =
6642                     "Cannot declare a non-inline module inside a block \
6643                     unless it has a path attribute";
6644                 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
6645                 if paths.path_exists {
6646                     let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
6647                                       paths.name);
6648                     err.span_note(id_sp, &msg);
6649                 }
6650                 Err(err)
6651             }
6652             DirectoryOwnership::UnownedViaMod(warn) => {
6653                 if warn {
6654                     if let Ok(result) = paths.result {
6655                         return Ok(ModulePathSuccess { warn: true, ..result });
6656                     }
6657                 }
6658                 let mut err = self.diagnostic().struct_span_err(id_sp,
6659                     "cannot declare a new module at this location");
6660                 if !id_sp.is_dummy() {
6661                     let src_path = self.sess.source_map().span_to_filename(id_sp);
6662                     if let FileName::Real(src_path) = src_path {
6663                         if let Some(stem) = src_path.file_stem() {
6664                             let mut dest_path = src_path.clone();
6665                             dest_path.set_file_name(stem);
6666                             dest_path.push("mod.rs");
6667                             err.span_note(id_sp,
6668                                     &format!("maybe move this module `{}` to its own \
6669                                                 directory via `{}`", src_path.display(),
6670                                             dest_path.display()));
6671                         }
6672                     }
6673                 }
6674                 if paths.path_exists {
6675                     err.span_note(id_sp,
6676                                   &format!("... or maybe `use` the module `{}` instead \
6677                                             of possibly redeclaring it",
6678                                            paths.name));
6679                 }
6680                 Err(err)
6681             }
6682         }
6683     }
6684
6685     /// Reads a module from a source file.
6686     fn eval_src_mod(&mut self,
6687                     path: PathBuf,
6688                     directory_ownership: DirectoryOwnership,
6689                     name: String,
6690                     id_sp: Span)
6691                     -> PResult<'a, (ast::Mod, Vec<Attribute> )> {
6692         let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
6693         if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
6694             let mut err = String::from("circular modules: ");
6695             let len = included_mod_stack.len();
6696             for p in &included_mod_stack[i.. len] {
6697                 err.push_str(&p.to_string_lossy());
6698                 err.push_str(" -> ");
6699             }
6700             err.push_str(&path.to_string_lossy());
6701             return Err(self.span_fatal(id_sp, &err[..]));
6702         }
6703         included_mod_stack.push(path.clone());
6704         drop(included_mod_stack);
6705
6706         let mut p0 =
6707             new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
6708         p0.cfg_mods = self.cfg_mods;
6709         let mod_inner_lo = p0.span;
6710         let mod_attrs = p0.parse_inner_attributes()?;
6711         let mut m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
6712         m0.inline = false;
6713         self.sess.included_mod_stack.borrow_mut().pop();
6714         Ok((m0, mod_attrs))
6715     }
6716
6717     /// Parses a function declaration from a foreign module.
6718     fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6719                              -> PResult<'a, ForeignItem> {
6720         self.expect_keyword(kw::Fn)?;
6721
6722         let (ident, mut generics) = self.parse_fn_header()?;
6723         let decl = self.parse_fn_decl(true)?;
6724         generics.where_clause = self.parse_where_clause()?;
6725         let hi = self.span;
6726         self.expect(&token::Semi)?;
6727         Ok(ast::ForeignItem {
6728             ident,
6729             attrs,
6730             node: ForeignItemKind::Fn(decl, generics),
6731             id: ast::DUMMY_NODE_ID,
6732             span: lo.to(hi),
6733             vis,
6734         })
6735     }
6736
6737     /// Parses a static item from a foreign module.
6738     /// Assumes that the `static` keyword is already parsed.
6739     fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6740                                  -> PResult<'a, ForeignItem> {
6741         let mutbl = self.parse_mutability();
6742         let ident = self.parse_ident()?;
6743         self.expect(&token::Colon)?;
6744         let ty = self.parse_ty()?;
6745         let hi = self.span;
6746         self.expect(&token::Semi)?;
6747         Ok(ForeignItem {
6748             ident,
6749             attrs,
6750             node: ForeignItemKind::Static(ty, mutbl),
6751             id: ast::DUMMY_NODE_ID,
6752             span: lo.to(hi),
6753             vis,
6754         })
6755     }
6756
6757     /// Parses a type from a foreign module.
6758     fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6759                              -> PResult<'a, ForeignItem> {
6760         self.expect_keyword(kw::Type)?;
6761
6762         let ident = self.parse_ident()?;
6763         let hi = self.span;
6764         self.expect(&token::Semi)?;
6765         Ok(ast::ForeignItem {
6766             ident: ident,
6767             attrs: attrs,
6768             node: ForeignItemKind::Ty,
6769             id: ast::DUMMY_NODE_ID,
6770             span: lo.to(hi),
6771             vis: vis
6772         })
6773     }
6774
6775     fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> {
6776         let error_msg = "crate name using dashes are not valid in `extern crate` statements";
6777         let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
6778                               in the code";
6779         let mut ident = if self.token.is_keyword(kw::SelfLower) {
6780             self.parse_path_segment_ident()
6781         } else {
6782             self.parse_ident()
6783         }?;
6784         let mut idents = vec![];
6785         let mut replacement = vec![];
6786         let mut fixed_crate_name = false;
6787         // Accept `extern crate name-like-this` for better diagnostics
6788         let dash = token::Token::BinOp(token::BinOpToken::Minus);
6789         if self.token == dash {  // Do not include `-` as part of the expected tokens list
6790             while self.eat(&dash) {
6791                 fixed_crate_name = true;
6792                 replacement.push((self.prev_span, "_".to_string()));
6793                 idents.push(self.parse_ident()?);
6794             }
6795         }
6796         if fixed_crate_name {
6797             let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
6798             let mut fixed_name = format!("{}", ident.name);
6799             for part in idents {
6800                 fixed_name.push_str(&format!("_{}", part.name));
6801             }
6802             ident = Ident::from_str(&fixed_name).with_span_pos(fixed_name_sp);
6803
6804             let mut err = self.struct_span_err(fixed_name_sp, error_msg);
6805             err.span_label(fixed_name_sp, "dash-separated idents are not valid");
6806             err.multipart_suggestion(
6807                 suggestion_msg,
6808                 replacement,
6809                 Applicability::MachineApplicable,
6810             );
6811             err.emit();
6812         }
6813         Ok(ident)
6814     }
6815
6816     /// Parses `extern crate` links.
6817     ///
6818     /// # Examples
6819     ///
6820     /// ```
6821     /// extern crate foo;
6822     /// extern crate bar as foo;
6823     /// ```
6824     fn parse_item_extern_crate(&mut self,
6825                                lo: Span,
6826                                visibility: Visibility,
6827                                attrs: Vec<Attribute>)
6828                                -> PResult<'a, P<Item>> {
6829         // Accept `extern crate name-like-this` for better diagnostics
6830         let orig_name = self.parse_crate_name_with_dashes()?;
6831         let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
6832             (rename, Some(orig_name.name))
6833         } else {
6834             (orig_name, None)
6835         };
6836         self.expect(&token::Semi)?;
6837
6838         let span = lo.to(self.prev_span);
6839         Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs))
6840     }
6841
6842     /// Parses `extern` for foreign ABIs modules.
6843     ///
6844     /// `extern` is expected to have been
6845     /// consumed before calling this method.
6846     ///
6847     /// # Examples
6848     ///
6849     /// ```ignore (only-for-syntax-highlight)
6850     /// extern "C" {}
6851     /// extern {}
6852     /// ```
6853     fn parse_item_foreign_mod(&mut self,
6854                               lo: Span,
6855                               opt_abi: Option<Abi>,
6856                               visibility: Visibility,
6857                               mut attrs: Vec<Attribute>)
6858                               -> PResult<'a, P<Item>> {
6859         self.expect(&token::OpenDelim(token::Brace))?;
6860
6861         let abi = opt_abi.unwrap_or(Abi::C);
6862
6863         attrs.extend(self.parse_inner_attributes()?);
6864
6865         let mut foreign_items = vec![];
6866         while !self.eat(&token::CloseDelim(token::Brace)) {
6867             foreign_items.push(self.parse_foreign_item()?);
6868         }
6869
6870         let prev_span = self.prev_span;
6871         let m = ast::ForeignMod {
6872             abi,
6873             items: foreign_items
6874         };
6875         let invalid = Ident::invalid();
6876         Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
6877     }
6878
6879     /// Parses `type Foo = Bar;`
6880     /// or
6881     /// `existential type Foo: Bar;`
6882     /// or
6883     /// `return `None``
6884     /// without modifying the parser state.
6885     fn eat_type(&mut self) -> Option<PResult<'a, (Ident, AliasKind, ast::Generics)>> {
6886         // This parses the grammar:
6887         //     Ident ["<"...">"] ["where" ...] ("=" | ":") Ty ";"
6888         if self.check_keyword(kw::Type) ||
6889            self.check_keyword(kw::Existential) &&
6890                 self.is_keyword_ahead(1, &[kw::Type]) {
6891             let existential = self.eat_keyword(kw::Existential);
6892             assert!(self.eat_keyword(kw::Type));
6893             Some(self.parse_existential_or_alias(existential))
6894         } else {
6895             None
6896         }
6897     }
6898
6899     /// Parses a type alias or existential type.
6900     fn parse_existential_or_alias(
6901         &mut self,
6902         existential: bool,
6903     ) -> PResult<'a, (Ident, AliasKind, ast::Generics)> {
6904         let ident = self.parse_ident()?;
6905         let mut tps = self.parse_generics()?;
6906         tps.where_clause = self.parse_where_clause()?;
6907         let alias = if existential {
6908             self.expect(&token::Colon)?;
6909             let bounds = self.parse_generic_bounds(Some(self.prev_span))?;
6910             AliasKind::Existential(bounds)
6911         } else {
6912             self.expect(&token::Eq)?;
6913             let ty = self.parse_ty()?;
6914             AliasKind::Weak(ty)
6915         };
6916         self.expect(&token::Semi)?;
6917         Ok((ident, alias, tps))
6918     }
6919
6920     /// Parses the part of an enum declaration following the `{`.
6921     fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
6922         let mut variants = Vec::new();
6923         let mut any_disr = vec![];
6924         while self.token != token::CloseDelim(token::Brace) {
6925             let variant_attrs = self.parse_outer_attributes()?;
6926             let vlo = self.span;
6927
6928             let struct_def;
6929             let mut disr_expr = None;
6930             self.eat_bad_pub();
6931             let ident = self.parse_ident()?;
6932             if self.check(&token::OpenDelim(token::Brace)) {
6933                 // Parse a struct variant.
6934                 let (fields, recovered) = self.parse_record_struct_body()?;
6935                 struct_def = VariantData::Struct(fields, recovered);
6936             } else if self.check(&token::OpenDelim(token::Paren)) {
6937                 struct_def = VariantData::Tuple(
6938                     self.parse_tuple_struct_body()?,
6939                     ast::DUMMY_NODE_ID,
6940                 );
6941             } else if self.eat(&token::Eq) {
6942                 disr_expr = Some(AnonConst {
6943                     id: ast::DUMMY_NODE_ID,
6944                     value: self.parse_expr()?,
6945                 });
6946                 if let Some(sp) = disr_expr.as_ref().map(|c| c.value.span) {
6947                     any_disr.push(sp);
6948                 }
6949                 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6950             } else {
6951                 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6952             }
6953
6954             let vr = ast::Variant_ {
6955                 ident,
6956                 id: ast::DUMMY_NODE_ID,
6957                 attrs: variant_attrs,
6958                 data: struct_def,
6959                 disr_expr,
6960             };
6961             variants.push(respan(vlo.to(self.prev_span), vr));
6962
6963             if !self.eat(&token::Comma) {
6964                 if self.token.is_ident() && !self.token.is_reserved_ident() {
6965                     let sp = self.sess.source_map().next_point(self.prev_span);
6966                     let mut err = self.struct_span_err(sp, "missing comma");
6967                     err.span_suggestion_short(
6968                         sp,
6969                         "missing comma",
6970                         ",".to_owned(),
6971                         Applicability::MaybeIncorrect,
6972                     );
6973                     err.emit();
6974                 } else {
6975                     break;
6976                 }
6977             }
6978         }
6979         self.expect(&token::CloseDelim(token::Brace))?;
6980         self.maybe_report_invalid_custom_discriminants(any_disr, &variants);
6981
6982         Ok(ast::EnumDef { variants })
6983     }
6984
6985     /// Parses an enum declaration.
6986     fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
6987         let id = self.parse_ident()?;
6988         let mut generics = self.parse_generics()?;
6989         generics.where_clause = self.parse_where_clause()?;
6990         self.expect(&token::OpenDelim(token::Brace))?;
6991
6992         let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
6993             self.recover_stmt();
6994             self.eat(&token::CloseDelim(token::Brace));
6995             e
6996         })?;
6997         Ok((id, ItemKind::Enum(enum_definition, generics), None))
6998     }
6999
7000     /// Parses a string as an ABI spec on an extern type or module. Consumes
7001     /// the `extern` keyword, if one is found.
7002     fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
7003         match self.token {
7004             token::Literal(token::Lit { kind: token::Str, symbol, suffix }) |
7005             token::Literal(token::Lit { kind: token::StrRaw(..), symbol, suffix }) => {
7006                 let sp = self.span;
7007                 self.expect_no_suffix(sp, "an ABI spec", suffix);
7008                 self.bump();
7009                 match abi::lookup(&symbol.as_str()) {
7010                     Some(abi) => Ok(Some(abi)),
7011                     None => {
7012                         let prev_span = self.prev_span;
7013                         let mut err = struct_span_err!(
7014                             self.sess.span_diagnostic,
7015                             prev_span,
7016                             E0703,
7017                             "invalid ABI: found `{}`",
7018                             symbol);
7019                         err.span_label(prev_span, "invalid ABI");
7020                         err.help(&format!("valid ABIs: {}", abi::all_names().join(", ")));
7021                         err.emit();
7022                         Ok(None)
7023                     }
7024                 }
7025             }
7026
7027             _ => Ok(None),
7028         }
7029     }
7030
7031     fn is_static_global(&mut self) -> bool {
7032         if self.check_keyword(kw::Static) {
7033             // Check if this could be a closure
7034             !self.look_ahead(1, |token| {
7035                 if token.is_keyword(kw::Move) {
7036                     return true;
7037                 }
7038                 match *token {
7039                     token::BinOp(token::Or) | token::OrOr => true,
7040                     _ => false,
7041                 }
7042             })
7043         } else {
7044             false
7045         }
7046     }
7047
7048     fn parse_item_(
7049         &mut self,
7050         attrs: Vec<Attribute>,
7051         macros_allowed: bool,
7052         attributes_allowed: bool,
7053     ) -> PResult<'a, Option<P<Item>>> {
7054         let mut unclosed_delims = vec![];
7055         let (ret, tokens) = self.collect_tokens(|this| {
7056             let item = this.parse_item_implementation(attrs, macros_allowed, attributes_allowed);
7057             unclosed_delims.append(&mut this.unclosed_delims);
7058             item
7059         })?;
7060         self.unclosed_delims.append(&mut unclosed_delims);
7061
7062         // Once we've parsed an item and recorded the tokens we got while
7063         // parsing we may want to store `tokens` into the item we're about to
7064         // return. Note, though, that we specifically didn't capture tokens
7065         // related to outer attributes. The `tokens` field here may later be
7066         // used with procedural macros to convert this item back into a token
7067         // stream, but during expansion we may be removing attributes as we go
7068         // along.
7069         //
7070         // If we've got inner attributes then the `tokens` we've got above holds
7071         // these inner attributes. If an inner attribute is expanded we won't
7072         // actually remove it from the token stream, so we'll just keep yielding
7073         // it (bad!). To work around this case for now we just avoid recording
7074         // `tokens` if we detect any inner attributes. This should help keep
7075         // expansion correct, but we should fix this bug one day!
7076         Ok(ret.map(|item| {
7077             item.map(|mut i| {
7078                 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
7079                     i.tokens = Some(tokens);
7080                 }
7081                 i
7082             })
7083         }))
7084     }
7085
7086     /// Parses one of the items allowed by the flags.
7087     fn parse_item_implementation(
7088         &mut self,
7089         attrs: Vec<Attribute>,
7090         macros_allowed: bool,
7091         attributes_allowed: bool,
7092     ) -> PResult<'a, Option<P<Item>>> {
7093         maybe_whole!(self, NtItem, |item| {
7094             let mut item = item.into_inner();
7095             let mut attrs = attrs;
7096             mem::swap(&mut item.attrs, &mut attrs);
7097             item.attrs.extend(attrs);
7098             Some(P(item))
7099         });
7100
7101         let lo = self.span;
7102
7103         let visibility = self.parse_visibility(false)?;
7104
7105         if self.eat_keyword(kw::Use) {
7106             // USE ITEM
7107             let item_ = ItemKind::Use(P(self.parse_use_tree()?));
7108             self.expect(&token::Semi)?;
7109
7110             let span = lo.to(self.prev_span);
7111             let item =
7112                 self.mk_item(span, Ident::invalid(), item_, visibility, attrs);
7113             return Ok(Some(item));
7114         }
7115
7116         if self.eat_keyword(kw::Extern) {
7117             if self.eat_keyword(kw::Crate) {
7118                 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
7119             }
7120
7121             let opt_abi = self.parse_opt_abi()?;
7122
7123             if self.eat_keyword(kw::Fn) {
7124                 // EXTERN FUNCTION ITEM
7125                 let fn_span = self.prev_span;
7126                 let abi = opt_abi.unwrap_or(Abi::C);
7127                 let (ident, item_, extra_attrs) =
7128                     self.parse_item_fn(Unsafety::Normal,
7129                                        respan(fn_span, IsAsync::NotAsync),
7130                                        respan(fn_span, Constness::NotConst),
7131                                        abi)?;
7132                 let prev_span = self.prev_span;
7133                 let item = self.mk_item(lo.to(prev_span),
7134                                         ident,
7135                                         item_,
7136                                         visibility,
7137                                         maybe_append(attrs, extra_attrs));
7138                 return Ok(Some(item));
7139             } else if self.check(&token::OpenDelim(token::Brace)) {
7140                 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
7141             }
7142
7143             self.unexpected()?;
7144         }
7145
7146         if self.is_static_global() {
7147             self.bump();
7148             // STATIC ITEM
7149             let m = if self.eat_keyword(kw::Mut) {
7150                 Mutability::Mutable
7151             } else {
7152                 Mutability::Immutable
7153             };
7154             let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
7155             let prev_span = self.prev_span;
7156             let item = self.mk_item(lo.to(prev_span),
7157                                     ident,
7158                                     item_,
7159                                     visibility,
7160                                     maybe_append(attrs, extra_attrs));
7161             return Ok(Some(item));
7162         }
7163         if self.eat_keyword(kw::Const) {
7164             let const_span = self.prev_span;
7165             if self.check_keyword(kw::Fn)
7166                 || (self.check_keyword(kw::Unsafe)
7167                     && self.is_keyword_ahead(1, &[kw::Fn])) {
7168                 // CONST FUNCTION ITEM
7169                 let unsafety = self.parse_unsafety();
7170                 self.bump();
7171                 let (ident, item_, extra_attrs) =
7172                     self.parse_item_fn(unsafety,
7173                                        respan(const_span, IsAsync::NotAsync),
7174                                        respan(const_span, Constness::Const),
7175                                        Abi::Rust)?;
7176                 let prev_span = self.prev_span;
7177                 let item = self.mk_item(lo.to(prev_span),
7178                                         ident,
7179                                         item_,
7180                                         visibility,
7181                                         maybe_append(attrs, extra_attrs));
7182                 return Ok(Some(item));
7183             }
7184
7185             // CONST ITEM
7186             if self.eat_keyword(kw::Mut) {
7187                 let prev_span = self.prev_span;
7188                 let mut err = self.diagnostic()
7189                     .struct_span_err(prev_span, "const globals cannot be mutable");
7190                 err.span_label(prev_span, "cannot be mutable");
7191                 err.span_suggestion(
7192                     const_span,
7193                     "you might want to declare a static instead",
7194                     "static".to_owned(),
7195                     Applicability::MaybeIncorrect,
7196                 );
7197                 err.emit();
7198             }
7199             let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
7200             let prev_span = self.prev_span;
7201             let item = self.mk_item(lo.to(prev_span),
7202                                     ident,
7203                                     item_,
7204                                     visibility,
7205                                     maybe_append(attrs, extra_attrs));
7206             return Ok(Some(item));
7207         }
7208
7209         // Parse `async unsafe? fn`.
7210         if self.check_keyword(kw::Async) {
7211             let async_span = self.span;
7212             if self.is_keyword_ahead(1, &[kw::Fn])
7213                 || self.is_keyword_ahead(2, &[kw::Fn])
7214             {
7215                 // ASYNC FUNCTION ITEM
7216                 self.bump(); // `async`
7217                 let unsafety = self.parse_unsafety(); // `unsafe`?
7218                 self.expect_keyword(kw::Fn)?; // `fn`
7219                 let fn_span = self.prev_span;
7220                 let (ident, item_, extra_attrs) =
7221                     self.parse_item_fn(unsafety,
7222                                     respan(async_span, IsAsync::Async {
7223                                         closure_id: ast::DUMMY_NODE_ID,
7224                                         return_impl_trait_id: ast::DUMMY_NODE_ID,
7225                                         arguments: Vec::new(),
7226                                     }),
7227                                     respan(fn_span, Constness::NotConst),
7228                                     Abi::Rust)?;
7229                 let prev_span = self.prev_span;
7230                 let item = self.mk_item(lo.to(prev_span),
7231                                         ident,
7232                                         item_,
7233                                         visibility,
7234                                         maybe_append(attrs, extra_attrs));
7235                 if self.span.rust_2015() {
7236                     self.diagnostic().struct_span_err_with_code(
7237                         async_span,
7238                         "`async fn` is not permitted in the 2015 edition",
7239                         DiagnosticId::Error("E0670".into())
7240                     ).emit();
7241                 }
7242                 return Ok(Some(item));
7243             }
7244         }
7245         if self.check_keyword(kw::Unsafe) &&
7246             self.is_keyword_ahead(1, &[kw::Trait, kw::Auto])
7247         {
7248             // UNSAFE TRAIT ITEM
7249             self.bump(); // `unsafe`
7250             let is_auto = if self.eat_keyword(kw::Trait) {
7251                 IsAuto::No
7252             } else {
7253                 self.expect_keyword(kw::Auto)?;
7254                 self.expect_keyword(kw::Trait)?;
7255                 IsAuto::Yes
7256             };
7257             let (ident, item_, extra_attrs) =
7258                 self.parse_item_trait(is_auto, Unsafety::Unsafe)?;
7259             let prev_span = self.prev_span;
7260             let item = self.mk_item(lo.to(prev_span),
7261                                     ident,
7262                                     item_,
7263                                     visibility,
7264                                     maybe_append(attrs, extra_attrs));
7265             return Ok(Some(item));
7266         }
7267         if self.check_keyword(kw::Impl) ||
7268            self.check_keyword(kw::Unsafe) &&
7269                 self.is_keyword_ahead(1, &[kw::Impl]) ||
7270            self.check_keyword(kw::Default) &&
7271                 self.is_keyword_ahead(1, &[kw::Impl, kw::Unsafe]) {
7272             // IMPL ITEM
7273             let defaultness = self.parse_defaultness();
7274             let unsafety = self.parse_unsafety();
7275             self.expect_keyword(kw::Impl)?;
7276             let (ident, item, extra_attrs) = self.parse_item_impl(unsafety, defaultness)?;
7277             let span = lo.to(self.prev_span);
7278             return Ok(Some(self.mk_item(span, ident, item, visibility,
7279                                         maybe_append(attrs, extra_attrs))));
7280         }
7281         if self.check_keyword(kw::Fn) {
7282             // FUNCTION ITEM
7283             self.bump();
7284             let fn_span = self.prev_span;
7285             let (ident, item_, extra_attrs) =
7286                 self.parse_item_fn(Unsafety::Normal,
7287                                    respan(fn_span, IsAsync::NotAsync),
7288                                    respan(fn_span, Constness::NotConst),
7289                                    Abi::Rust)?;
7290             let prev_span = self.prev_span;
7291             let item = self.mk_item(lo.to(prev_span),
7292                                     ident,
7293                                     item_,
7294                                     visibility,
7295                                     maybe_append(attrs, extra_attrs));
7296             return Ok(Some(item));
7297         }
7298         if self.check_keyword(kw::Unsafe)
7299             && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
7300             // UNSAFE FUNCTION ITEM
7301             self.bump(); // `unsafe`
7302             // `{` is also expected after `unsafe`, in case of error, include it in the diagnostic
7303             self.check(&token::OpenDelim(token::Brace));
7304             let abi = if self.eat_keyword(kw::Extern) {
7305                 self.parse_opt_abi()?.unwrap_or(Abi::C)
7306             } else {
7307                 Abi::Rust
7308             };
7309             self.expect_keyword(kw::Fn)?;
7310             let fn_span = self.prev_span;
7311             let (ident, item_, extra_attrs) =
7312                 self.parse_item_fn(Unsafety::Unsafe,
7313                                    respan(fn_span, IsAsync::NotAsync),
7314                                    respan(fn_span, Constness::NotConst),
7315                                    abi)?;
7316             let prev_span = self.prev_span;
7317             let item = self.mk_item(lo.to(prev_span),
7318                                     ident,
7319                                     item_,
7320                                     visibility,
7321                                     maybe_append(attrs, extra_attrs));
7322             return Ok(Some(item));
7323         }
7324         if self.eat_keyword(kw::Mod) {
7325             // MODULE ITEM
7326             let (ident, item_, extra_attrs) =
7327                 self.parse_item_mod(&attrs[..])?;
7328             let prev_span = self.prev_span;
7329             let item = self.mk_item(lo.to(prev_span),
7330                                     ident,
7331                                     item_,
7332                                     visibility,
7333                                     maybe_append(attrs, extra_attrs));
7334             return Ok(Some(item));
7335         }
7336         if let Some(type_) = self.eat_type() {
7337             let (ident, alias, generics) = type_?;
7338             // TYPE ITEM
7339             let item_ = match alias {
7340                 AliasKind::Weak(ty) => ItemKind::Ty(ty, generics),
7341                 AliasKind::Existential(bounds) => ItemKind::Existential(bounds, generics),
7342             };
7343             let prev_span = self.prev_span;
7344             let item = self.mk_item(lo.to(prev_span),
7345                                     ident,
7346                                     item_,
7347                                     visibility,
7348                                     attrs);
7349             return Ok(Some(item));
7350         }
7351         if self.eat_keyword(kw::Enum) {
7352             // ENUM ITEM
7353             let (ident, item_, extra_attrs) = self.parse_item_enum()?;
7354             let prev_span = self.prev_span;
7355             let item = self.mk_item(lo.to(prev_span),
7356                                     ident,
7357                                     item_,
7358                                     visibility,
7359                                     maybe_append(attrs, extra_attrs));
7360             return Ok(Some(item));
7361         }
7362         if self.check_keyword(kw::Trait)
7363             || (self.check_keyword(kw::Auto)
7364                 && self.is_keyword_ahead(1, &[kw::Trait]))
7365         {
7366             let is_auto = if self.eat_keyword(kw::Trait) {
7367                 IsAuto::No
7368             } else {
7369                 self.expect_keyword(kw::Auto)?;
7370                 self.expect_keyword(kw::Trait)?;
7371                 IsAuto::Yes
7372             };
7373             // TRAIT ITEM
7374             let (ident, item_, extra_attrs) =
7375                 self.parse_item_trait(is_auto, Unsafety::Normal)?;
7376             let prev_span = self.prev_span;
7377             let item = self.mk_item(lo.to(prev_span),
7378                                     ident,
7379                                     item_,
7380                                     visibility,
7381                                     maybe_append(attrs, extra_attrs));
7382             return Ok(Some(item));
7383         }
7384         if self.eat_keyword(kw::Struct) {
7385             // STRUCT ITEM
7386             let (ident, item_, extra_attrs) = self.parse_item_struct()?;
7387             let prev_span = self.prev_span;
7388             let item = self.mk_item(lo.to(prev_span),
7389                                     ident,
7390                                     item_,
7391                                     visibility,
7392                                     maybe_append(attrs, extra_attrs));
7393             return Ok(Some(item));
7394         }
7395         if self.is_union_item() {
7396             // UNION ITEM
7397             self.bump();
7398             let (ident, item_, extra_attrs) = self.parse_item_union()?;
7399             let prev_span = self.prev_span;
7400             let item = self.mk_item(lo.to(prev_span),
7401                                     ident,
7402                                     item_,
7403                                     visibility,
7404                                     maybe_append(attrs, extra_attrs));
7405             return Ok(Some(item));
7406         }
7407         if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? {
7408             return Ok(Some(macro_def));
7409         }
7410
7411         // Verify whether we have encountered a struct or method definition where the user forgot to
7412         // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
7413         if visibility.node.is_pub() &&
7414             self.check_ident() &&
7415             self.look_ahead(1, |t| *t != token::Not)
7416         {
7417             // Space between `pub` keyword and the identifier
7418             //
7419             //     pub   S {}
7420             //        ^^^ `sp` points here
7421             let sp = self.prev_span.between(self.span);
7422             let full_sp = self.prev_span.to(self.span);
7423             let ident_sp = self.span;
7424             if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
7425                 // possible public struct definition where `struct` was forgotten
7426                 let ident = self.parse_ident().unwrap();
7427                 let msg = format!("add `struct` here to parse `{}` as a public struct",
7428                                   ident);
7429                 let mut err = self.diagnostic()
7430                     .struct_span_err(sp, "missing `struct` for struct definition");
7431                 err.span_suggestion_short(
7432                     sp, &msg, " struct ".into(), Applicability::MaybeIncorrect // speculative
7433                 );
7434                 return Err(err);
7435             } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
7436                 let ident = self.parse_ident().unwrap();
7437                 self.bump();  // `(`
7438                 let kw_name = if let Ok(Some(_)) = self.parse_self_arg() {
7439                     "method"
7440                 } else {
7441                     "function"
7442                 };
7443                 self.consume_block(token::Paren);
7444                 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) {
7445                     self.eat_to_tokens(&[&token::OpenDelim(token::Brace)]);
7446                     self.bump();  // `{`
7447                     ("fn", kw_name, false)
7448                 } else if self.check(&token::OpenDelim(token::Brace)) {
7449                     self.bump();  // `{`
7450                     ("fn", kw_name, false)
7451                 } else if self.check(&token::Colon) {
7452                     let kw = "struct";
7453                     (kw, kw, false)
7454                 } else {
7455                     ("fn` or `struct", "function or struct", true)
7456                 };
7457
7458                 let msg = format!("missing `{}` for {} definition", kw, kw_name);
7459                 let mut err = self.diagnostic().struct_span_err(sp, &msg);
7460                 if !ambiguous {
7461                     self.consume_block(token::Brace);
7462                     let suggestion = format!("add `{}` here to parse `{}` as a public {}",
7463                                              kw,
7464                                              ident,
7465                                              kw_name);
7466                     err.span_suggestion_short(
7467                         sp, &suggestion, format!(" {} ", kw), Applicability::MachineApplicable
7468                     );
7469                 } else {
7470                     if let Ok(snippet) = self.sess.source_map().span_to_snippet(ident_sp) {
7471                         err.span_suggestion(
7472                             full_sp,
7473                             "if you meant to call a macro, try",
7474                             format!("{}!", snippet),
7475                             // this is the `ambiguous` conditional branch
7476                             Applicability::MaybeIncorrect
7477                         );
7478                     } else {
7479                         err.help("if you meant to call a macro, remove the `pub` \
7480                                   and add a trailing `!` after the identifier");
7481                     }
7482                 }
7483                 return Err(err);
7484             } else if self.look_ahead(1, |t| *t == token::Lt) {
7485                 let ident = self.parse_ident().unwrap();
7486                 self.eat_to_tokens(&[&token::Gt]);
7487                 self.bump();  // `>`
7488                 let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(token::Paren)) {
7489                     if let Ok(Some(_)) = self.parse_self_arg() {
7490                         ("fn", "method", false)
7491                     } else {
7492                         ("fn", "function", false)
7493                     }
7494                 } else if self.check(&token::OpenDelim(token::Brace)) {
7495                     ("struct", "struct", false)
7496                 } else {
7497                     ("fn` or `struct", "function or struct", true)
7498                 };
7499                 let msg = format!("missing `{}` for {} definition", kw, kw_name);
7500                 let mut err = self.diagnostic().struct_span_err(sp, &msg);
7501                 if !ambiguous {
7502                     err.span_suggestion_short(
7503                         sp,
7504                         &format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name),
7505                         format!(" {} ", kw),
7506                         Applicability::MachineApplicable,
7507                     );
7508                 }
7509                 return Err(err);
7510             }
7511         }
7512         self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, visibility)
7513     }
7514
7515     /// Parses a foreign item.
7516     crate fn parse_foreign_item(&mut self) -> PResult<'a, ForeignItem> {
7517         maybe_whole!(self, NtForeignItem, |ni| ni);
7518
7519         let attrs = self.parse_outer_attributes()?;
7520         let lo = self.span;
7521         let visibility = self.parse_visibility(false)?;
7522
7523         // FOREIGN STATIC ITEM
7524         // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
7525         if self.check_keyword(kw::Static) || self.token.is_keyword(kw::Const) {
7526             if self.token.is_keyword(kw::Const) {
7527                 self.diagnostic()
7528                     .struct_span_err(self.span, "extern items cannot be `const`")
7529                     .span_suggestion(
7530                         self.span,
7531                         "try using a static value",
7532                         "static".to_owned(),
7533                         Applicability::MachineApplicable
7534                     ).emit();
7535             }
7536             self.bump(); // `static` or `const`
7537             return Ok(self.parse_item_foreign_static(visibility, lo, attrs)?);
7538         }
7539         // FOREIGN FUNCTION ITEM
7540         if self.check_keyword(kw::Fn) {
7541             return Ok(self.parse_item_foreign_fn(visibility, lo, attrs)?);
7542         }
7543         // FOREIGN TYPE ITEM
7544         if self.check_keyword(kw::Type) {
7545             return Ok(self.parse_item_foreign_type(visibility, lo, attrs)?);
7546         }
7547
7548         match self.parse_assoc_macro_invoc("extern", Some(&visibility), &mut false)? {
7549             Some(mac) => {
7550                 Ok(
7551                     ForeignItem {
7552                         ident: Ident::invalid(),
7553                         span: lo.to(self.prev_span),
7554                         id: ast::DUMMY_NODE_ID,
7555                         attrs,
7556                         vis: visibility,
7557                         node: ForeignItemKind::Macro(mac),
7558                     }
7559                 )
7560             }
7561             None => {
7562                 if !attrs.is_empty()  {
7563                     self.expected_item_err(&attrs)?;
7564                 }
7565
7566                 self.unexpected()
7567             }
7568         }
7569     }
7570
7571     /// This is the fall-through for parsing items.
7572     fn parse_macro_use_or_failure(
7573         &mut self,
7574         attrs: Vec<Attribute> ,
7575         macros_allowed: bool,
7576         attributes_allowed: bool,
7577         lo: Span,
7578         visibility: Visibility
7579     ) -> PResult<'a, Option<P<Item>>> {
7580         if macros_allowed && self.token.is_path_start() &&
7581                 !(self.is_async_fn() && self.span.rust_2015()) {
7582             // MACRO INVOCATION ITEM
7583
7584             let prev_span = self.prev_span;
7585             self.complain_if_pub_macro(&visibility.node, prev_span);
7586
7587             let mac_lo = self.span;
7588
7589             // item macro.
7590             let pth = self.parse_path(PathStyle::Mod)?;
7591             self.expect(&token::Not)?;
7592
7593             // a 'special' identifier (like what `macro_rules!` uses)
7594             // is optional. We should eventually unify invoc syntax
7595             // and remove this.
7596             let id = if self.token.is_ident() {
7597                 self.parse_ident()?
7598             } else {
7599                 Ident::invalid() // no special identifier
7600             };
7601             // eat a matched-delimiter token tree:
7602             let (delim, tts) = self.expect_delimited_token_tree()?;
7603             if delim != MacDelimiter::Brace && !self.eat(&token::Semi) {
7604                 self.report_invalid_macro_expansion_item();
7605             }
7606
7607             let hi = self.prev_span;
7608             let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts, delim });
7609             let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
7610             return Ok(Some(item));
7611         }
7612
7613         // FAILURE TO PARSE ITEM
7614         match visibility.node {
7615             VisibilityKind::Inherited => {}
7616             _ => {
7617                 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
7618             }
7619         }
7620
7621         if !attributes_allowed && !attrs.is_empty() {
7622             self.expected_item_err(&attrs)?;
7623         }
7624         Ok(None)
7625     }
7626
7627     /// Parses a macro invocation inside a `trait`, `impl` or `extern` block.
7628     fn parse_assoc_macro_invoc(&mut self, item_kind: &str, vis: Option<&Visibility>,
7629                                at_end: &mut bool) -> PResult<'a, Option<Mac>>
7630     {
7631         if self.token.is_path_start() &&
7632                 !(self.is_async_fn() && self.span.rust_2015()) {
7633             let prev_span = self.prev_span;
7634             let lo = self.span;
7635             let pth = self.parse_path(PathStyle::Mod)?;
7636
7637             if pth.segments.len() == 1 {
7638                 if !self.eat(&token::Not) {
7639                     return Err(self.missing_assoc_item_kind_err(item_kind, prev_span));
7640                 }
7641             } else {
7642                 self.expect(&token::Not)?;
7643             }
7644
7645             if let Some(vis) = vis {
7646                 self.complain_if_pub_macro(&vis.node, prev_span);
7647             }
7648
7649             *at_end = true;
7650
7651             // eat a matched-delimiter token tree:
7652             let (delim, tts) = self.expect_delimited_token_tree()?;
7653             if delim != MacDelimiter::Brace {
7654                 self.expect(&token::Semi)?;
7655             }
7656
7657             Ok(Some(respan(lo.to(self.prev_span), Mac_ { path: pth, tts, delim })))
7658         } else {
7659             Ok(None)
7660         }
7661     }
7662
7663     fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
7664         where F: FnOnce(&mut Self) -> PResult<'a, R>
7665     {
7666         // Record all tokens we parse when parsing this item.
7667         let mut tokens = Vec::new();
7668         let prev_collecting = match self.token_cursor.frame.last_token {
7669             LastToken::Collecting(ref mut list) => {
7670                 Some(mem::replace(list, Vec::new()))
7671             }
7672             LastToken::Was(ref mut last) => {
7673                 tokens.extend(last.take());
7674                 None
7675             }
7676         };
7677         self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
7678         let prev = self.token_cursor.stack.len();
7679         let ret = f(self);
7680         let last_token = if self.token_cursor.stack.len() == prev {
7681             &mut self.token_cursor.frame.last_token
7682         } else {
7683             &mut self.token_cursor.stack[prev].last_token
7684         };
7685
7686         // Pull out the tokens that we've collected from the call to `f` above.
7687         let mut collected_tokens = match *last_token {
7688             LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
7689             LastToken::Was(_) => panic!("our vector went away?"),
7690         };
7691
7692         // If we're not at EOF our current token wasn't actually consumed by
7693         // `f`, but it'll still be in our list that we pulled out. In that case
7694         // put it back.
7695         let extra_token = if self.token != token::Eof {
7696             collected_tokens.pop()
7697         } else {
7698             None
7699         };
7700
7701         // If we were previously collecting tokens, then this was a recursive
7702         // call. In that case we need to record all the tokens we collected in
7703         // our parent list as well. To do that we push a clone of our stream
7704         // onto the previous list.
7705         match prev_collecting {
7706             Some(mut list) => {
7707                 list.extend(collected_tokens.iter().cloned());
7708                 list.extend(extra_token);
7709                 *last_token = LastToken::Collecting(list);
7710             }
7711             None => {
7712                 *last_token = LastToken::Was(extra_token);
7713             }
7714         }
7715
7716         Ok((ret?, TokenStream::new(collected_tokens)))
7717     }
7718
7719     pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
7720         let attrs = self.parse_outer_attributes()?;
7721         self.parse_item_(attrs, true, false)
7722     }
7723
7724     /// `::{` or `::*`
7725     fn is_import_coupler(&mut self) -> bool {
7726         self.check(&token::ModSep) &&
7727             self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
7728                                    *t == token::BinOp(token::Star))
7729     }
7730
7731     /// Parses a `UseTree`.
7732     ///
7733     /// ```
7734     /// USE_TREE = [`::`] `*` |
7735     ///            [`::`] `{` USE_TREE_LIST `}` |
7736     ///            PATH `::` `*` |
7737     ///            PATH `::` `{` USE_TREE_LIST `}` |
7738     ///            PATH [`as` IDENT]
7739     /// ```
7740     fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
7741         let lo = self.span;
7742
7743         let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
7744         let kind = if self.check(&token::OpenDelim(token::Brace)) ||
7745                       self.check(&token::BinOp(token::Star)) ||
7746                       self.is_import_coupler() {
7747             // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
7748             let mod_sep_ctxt = self.span.ctxt();
7749             if self.eat(&token::ModSep) {
7750                 prefix.segments.push(
7751                     PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt))
7752                 );
7753             }
7754
7755             if self.eat(&token::BinOp(token::Star)) {
7756                 UseTreeKind::Glob
7757             } else {
7758                 UseTreeKind::Nested(self.parse_use_tree_list()?)
7759             }
7760         } else {
7761             // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
7762             prefix = self.parse_path(PathStyle::Mod)?;
7763
7764             if self.eat(&token::ModSep) {
7765                 if self.eat(&token::BinOp(token::Star)) {
7766                     UseTreeKind::Glob
7767                 } else {
7768                     UseTreeKind::Nested(self.parse_use_tree_list()?)
7769                 }
7770             } else {
7771                 UseTreeKind::Simple(self.parse_rename()?, ast::DUMMY_NODE_ID, ast::DUMMY_NODE_ID)
7772             }
7773         };
7774
7775         Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
7776     }
7777
7778     /// Parses a `UseTreeKind::Nested(list)`.
7779     ///
7780     /// ```
7781     /// USE_TREE_LIST = Ã˜ | (USE_TREE `,`)* USE_TREE [`,`]
7782     /// ```
7783     fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
7784         self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
7785                                  &token::CloseDelim(token::Brace),
7786                                  SeqSep::trailing_allowed(token::Comma), |this| {
7787             Ok((this.parse_use_tree()?, ast::DUMMY_NODE_ID))
7788         })
7789     }
7790
7791     fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
7792         if self.eat_keyword(kw::As) {
7793             self.parse_ident_or_underscore().map(Some)
7794         } else {
7795             Ok(None)
7796         }
7797     }
7798
7799     /// Parses a source module as a crate. This is the main entry point for the parser.
7800     pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
7801         let lo = self.span;
7802         let krate = Ok(ast::Crate {
7803             attrs: self.parse_inner_attributes()?,
7804             module: self.parse_mod_items(&token::Eof, lo)?,
7805             span: lo.to(self.span),
7806         });
7807         krate
7808     }
7809
7810     pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
7811         let ret = match self.token {
7812             token::Literal(token::Lit { kind: token::Str, symbol, suffix }) =>
7813                 (symbol, ast::StrStyle::Cooked, suffix),
7814             token::Literal(token::Lit { kind: token::StrRaw(n), symbol, suffix }) =>
7815                 (symbol, ast::StrStyle::Raw(n), suffix),
7816             _ => return None
7817         };
7818         self.bump();
7819         Some(ret)
7820     }
7821
7822     pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
7823         match self.parse_optional_str() {
7824             Some((s, style, suf)) => {
7825                 let sp = self.prev_span;
7826                 self.expect_no_suffix(sp, "a string literal", suf);
7827                 Ok((s, style))
7828             }
7829             _ => {
7830                 let msg = "expected string literal";
7831                 let mut err = self.fatal(msg);
7832                 err.span_label(self.span, msg);
7833                 Err(err)
7834             }
7835         }
7836     }
7837
7838     fn report_invalid_macro_expansion_item(&self) {
7839         self.struct_span_err(
7840             self.prev_span,
7841             "macros that expand to items must be delimited with braces or followed by a semicolon",
7842         ).multipart_suggestion(
7843             "change the delimiters to curly braces",
7844             vec![
7845                 (self.prev_span.with_hi(self.prev_span.lo() + BytePos(1)), String::from(" {")),
7846                 (self.prev_span.with_lo(self.prev_span.hi() - BytePos(1)), '}'.to_string()),
7847             ],
7848             Applicability::MaybeIncorrect,
7849         ).span_suggestion(
7850             self.sess.source_map.next_point(self.prev_span),
7851             "add a semicolon",
7852             ';'.to_string(),
7853             Applicability::MaybeIncorrect,
7854         ).emit();
7855     }
7856
7857     /// When lowering a `async fn` to the HIR, we need to move all of the arguments of the function
7858     /// into the generated closure so that they are dropped when the future is polled and not when
7859     /// it is created.
7860     ///
7861     /// The arguments of the function are replaced in HIR lowering with the arguments created by
7862     /// this function and the statements created here are inserted at the top of the closure body.
7863     fn construct_async_arguments(&mut self, asyncness: &mut Spanned<IsAsync>, decl: &mut FnDecl) {
7864         // FIXME(davidtwco): This function should really live in the HIR lowering but because
7865         // the types constructed here need to be used in parts of resolve so that the correct
7866         // locals are considered upvars, it is currently easier for it to live here in the parser,
7867         // where it can be constructed once.
7868         if let IsAsync::Async { ref mut arguments, .. } = asyncness.node {
7869             for (index, input) in decl.inputs.iter_mut().enumerate() {
7870                 let id = ast::DUMMY_NODE_ID;
7871                 let span = input.pat.span;
7872                 let desugared_span = self.sess.source_map()
7873                     .mark_span_with_reason(CompilerDesugaringKind::Async, span, None);
7874
7875                 // Construct a name for our temporary argument.
7876                 let name = format!("__arg{}", index);
7877                 let ident = Ident::from_str(&name).gensym();
7878
7879                 // Check if this is a ident pattern, if so, we can optimize and avoid adding a
7880                 // `let <pat> = __argN;` statement, instead just adding a `let <pat> = <pat>;`
7881                 // statement.
7882                 let (binding_mode, ident, is_simple_pattern) = match input.pat.node {
7883                     PatKind::Ident(binding_mode @ BindingMode::ByValue(_), ident, _) => {
7884                         // Simple patterns like this don't have a generated argument, but they are
7885                         // moved into the closure with a statement, so any `mut` bindings on the
7886                         // argument will be unused. This binding mode can't be removed, because
7887                         // this would affect the input to procedural macros, but they can have
7888                         // their span marked as being the result of a compiler desugaring so
7889                         // that they aren't linted against.
7890                         input.pat.span = desugared_span;
7891
7892                         (binding_mode, ident, true)
7893                     }
7894                     _ => (BindingMode::ByValue(Mutability::Mutable), ident, false),
7895                 };
7896
7897                 // Construct an argument representing `__argN: <ty>` to replace the argument of the
7898                 // async function if it isn't a simple pattern.
7899                 let arg = if is_simple_pattern {
7900                     None
7901                 } else {
7902                     Some(Arg {
7903                         ty: input.ty.clone(),
7904                         id,
7905                         pat: P(Pat {
7906                             id,
7907                             node: PatKind::Ident(
7908                                 BindingMode::ByValue(Mutability::Immutable), ident, None,
7909                             ),
7910                             span: desugared_span,
7911                         }),
7912                         source: ArgSource::AsyncFn(input.pat.clone()),
7913                     })
7914                 };
7915
7916                 // Construct a `let __argN = __argN;` statement to insert at the top of the
7917                 // async closure. This makes sure that the argument is captured by the closure and
7918                 // that the drop order is correct.
7919                 let move_local = Local {
7920                     pat: P(Pat {
7921                         id,
7922                         node: PatKind::Ident(binding_mode, ident, None),
7923                         span: desugared_span,
7924                     }),
7925                     // We explicitly do not specify the type for this statement. When the user's
7926                     // argument type is `impl Trait` then this would require the
7927                     // `impl_trait_in_bindings` feature to also be present for that same type to
7928                     // be valid in this binding. At the time of writing (13 Mar 19),
7929                     // `impl_trait_in_bindings` is not stable.
7930                     ty: None,
7931                     init: Some(P(Expr {
7932                         id,
7933                         node: ExprKind::Path(None, ast::Path {
7934                             span,
7935                             segments: vec![PathSegment { ident, id, args: None }],
7936                         }),
7937                         span,
7938                         attrs: ThinVec::new(),
7939                     })),
7940                     id,
7941                     span,
7942                     attrs: ThinVec::new(),
7943                     source: LocalSource::AsyncFn,
7944                 };
7945
7946                 // Construct a `let <pat> = __argN;` statement to insert at the top of the
7947                 // async closure if this isn't a simple pattern.
7948                 let pat_stmt = if is_simple_pattern {
7949                     None
7950                 } else {
7951                     Some(Stmt {
7952                         id,
7953                         node: StmtKind::Local(P(Local {
7954                             pat: input.pat.clone(),
7955                             ..move_local.clone()
7956                         })),
7957                         span,
7958                     })
7959                 };
7960
7961                 let move_stmt = Stmt { id, node: StmtKind::Local(P(move_local)), span };
7962                 arguments.push(AsyncArgument { ident, arg, pat_stmt, move_stmt });
7963             }
7964         }
7965     }
7966 }
7967
7968 pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, handler: &errors::Handler) {
7969     for unmatched in unclosed_delims.iter() {
7970         let mut err = handler.struct_span_err(unmatched.found_span, &format!(
7971             "incorrect close delimiter: `{}`",
7972             pprust::token_to_string(&token::Token::CloseDelim(unmatched.found_delim)),
7973         ));
7974         err.span_label(unmatched.found_span, "incorrect close delimiter");
7975         if let Some(sp) = unmatched.candidate_span {
7976             err.span_label(sp, "close delimiter possibly meant for this");
7977         }
7978         if let Some(sp) = unmatched.unclosed_span {
7979             err.span_label(sp, "un-closed delimiter");
7980         }
7981         err.emit();
7982     }
7983     unclosed_delims.clear();
7984 }