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