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