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