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