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