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