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