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