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