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