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