]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/parse/parser.rs
whitespace after colon, not before
[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::AngleBracketedParameters(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::ParenthesizedParameters(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                 segments.push(ast::PathSegment {
1763                     identifier: identifier,
1764                     parameters: ast::AngleBracketedParameters(ast::AngleBracketedParameterData {
1765                         lifetimes: lifetimes,
1766                         types: P::from_vec(types),
1767                         bindings: P::from_vec(bindings),
1768                     }),
1769                 });
1770
1771                 // Consumed `a::b::<T,U>`, check for `::` before proceeding
1772                 if !try!(self.eat(&token::ModSep) ){
1773                     return Ok(segments);
1774                 }
1775             } else {
1776                 // Consumed `a::`, go look for `b`
1777                 segments.push(ast::PathSegment {
1778                     identifier: identifier,
1779                     parameters: ast::PathParameters::none(),
1780                 });
1781             }
1782         }
1783     }
1784
1785
1786     /// Examples:
1787     /// - `a::b::c`
1788     pub fn parse_path_segments_without_types(&mut self) -> PResult<'a, Vec<ast::PathSegment>> {
1789         let mut segments = Vec::new();
1790         loop {
1791             // First, parse an identifier.
1792             let identifier = try!(self.parse_ident_or_self_type());
1793
1794             // Assemble and push the result.
1795             segments.push(ast::PathSegment {
1796                 identifier: identifier,
1797                 parameters: ast::PathParameters::none()
1798             });
1799
1800             // If we do not see a `::`, stop.
1801             if !try!(self.eat(&token::ModSep) ){
1802                 return Ok(segments);
1803             }
1804         }
1805     }
1806
1807     /// parses 0 or 1 lifetime
1808     pub fn parse_opt_lifetime(&mut self) -> PResult<'a, Option<ast::Lifetime>> {
1809         match self.token {
1810             token::Lifetime(..) => {
1811                 Ok(Some(try!(self.parse_lifetime())))
1812             }
1813             _ => {
1814                 Ok(None)
1815             }
1816         }
1817     }
1818
1819     /// Parses a single lifetime
1820     /// Matches lifetime = LIFETIME
1821     pub fn parse_lifetime(&mut self) -> PResult<'a, ast::Lifetime> {
1822         match self.token {
1823             token::Lifetime(i) => {
1824                 let span = self.span;
1825                 try!(self.bump());
1826                 return Ok(ast::Lifetime {
1827                     id: ast::DUMMY_NODE_ID,
1828                     span: span,
1829                     name: i.name
1830                 });
1831             }
1832             _ => {
1833                 return Err(self.fatal("expected a lifetime name"));
1834             }
1835         }
1836     }
1837
1838     /// Parses `lifetime_defs = [ lifetime_defs { ',' lifetime_defs } ]` where `lifetime_def  =
1839     /// lifetime [':' lifetimes]`
1840     pub fn parse_lifetime_defs(&mut self) -> PResult<'a, Vec<ast::LifetimeDef>> {
1841
1842         let mut res = Vec::new();
1843         loop {
1844             match self.token {
1845                 token::Lifetime(_) => {
1846                     let lifetime = try!(self.parse_lifetime());
1847                     let bounds =
1848                         if try!(self.eat(&token::Colon) ){
1849                             try!(self.parse_lifetimes(token::BinOp(token::Plus)))
1850                         } else {
1851                             Vec::new()
1852                         };
1853                     res.push(ast::LifetimeDef { lifetime: lifetime,
1854                                                 bounds: bounds });
1855                 }
1856
1857                 _ => {
1858                     return Ok(res);
1859                 }
1860             }
1861
1862             match self.token {
1863                 token::Comma => { try!(self.bump());}
1864                 token::Gt => { return Ok(res); }
1865                 token::BinOp(token::Shr) => { return Ok(res); }
1866                 _ => {
1867                     let this_token_str = self.this_token_to_string();
1868                     let msg = format!("expected `,` or `>` after lifetime \
1869                                       name, found `{}`",
1870                                       this_token_str);
1871                     return Err(self.fatal(&msg[..]));
1872                 }
1873             }
1874         }
1875     }
1876
1877     /// matches lifetimes = ( lifetime ) | ( lifetime , lifetimes ) actually, it matches the empty
1878     /// one too, but putting that in there messes up the grammar....
1879     ///
1880     /// Parses zero or more comma separated lifetimes. Expects each lifetime to be followed by
1881     /// either a comma or `>`.  Used when parsing type parameter lists, where we expect something
1882     /// like `<'a, 'b, T>`.
1883     pub fn parse_lifetimes(&mut self, sep: token::Token) -> PResult<'a, Vec<ast::Lifetime>> {
1884
1885         let mut res = Vec::new();
1886         loop {
1887             match self.token {
1888                 token::Lifetime(_) => {
1889                     res.push(try!(self.parse_lifetime()));
1890                 }
1891                 _ => {
1892                     return Ok(res);
1893                 }
1894             }
1895
1896             if self.token != sep {
1897                 return Ok(res);
1898             }
1899
1900             try!(self.bump());
1901         }
1902     }
1903
1904     /// Parse mutability declaration (mut/const/imm)
1905     pub fn parse_mutability(&mut self) -> PResult<'a, Mutability> {
1906         if try!(self.eat_keyword(keywords::Mut) ){
1907             Ok(MutMutable)
1908         } else {
1909             Ok(MutImmutable)
1910         }
1911     }
1912
1913     /// Parse ident COLON expr
1914     pub fn parse_field(&mut self) -> PResult<'a, Field> {
1915         let lo = self.span.lo;
1916         let i = try!(self.parse_ident());
1917         let hi = self.last_span.hi;
1918         try!(self.expect(&token::Colon));
1919         let e = try!(self.parse_expr());
1920         Ok(ast::Field {
1921             ident: spanned(lo, hi, i),
1922             span: mk_sp(lo, e.span.hi),
1923             expr: e,
1924         })
1925     }
1926
1927     pub fn mk_expr(&mut self, lo: BytePos, hi: BytePos,
1928                    node: Expr_, attrs: ThinAttributes) -> P<Expr> {
1929         P(Expr {
1930             id: ast::DUMMY_NODE_ID,
1931             node: node,
1932             span: mk_sp(lo, hi),
1933             attrs: attrs,
1934         })
1935     }
1936
1937     pub fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::Expr_ {
1938         ExprUnary(unop, expr)
1939     }
1940
1941     pub fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::Expr_ {
1942         ExprBinary(binop, lhs, rhs)
1943     }
1944
1945     pub fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::Expr_ {
1946         ExprCall(f, args)
1947     }
1948
1949     fn mk_method_call(&mut self,
1950                       ident: ast::SpannedIdent,
1951                       tps: Vec<P<Ty>>,
1952                       args: Vec<P<Expr>>)
1953                       -> ast::Expr_ {
1954         ExprMethodCall(ident, tps, args)
1955     }
1956
1957     pub fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::Expr_ {
1958         ExprIndex(expr, idx)
1959     }
1960
1961     pub fn mk_range(&mut self,
1962                     start: Option<P<Expr>>,
1963                     end: Option<P<Expr>>)
1964                     -> ast::Expr_ {
1965         ExprRange(start, end)
1966     }
1967
1968     pub fn mk_field(&mut self, expr: P<Expr>, ident: ast::SpannedIdent) -> ast::Expr_ {
1969         ExprField(expr, ident)
1970     }
1971
1972     pub fn mk_tup_field(&mut self, expr: P<Expr>, idx: codemap::Spanned<usize>) -> ast::Expr_ {
1973         ExprTupField(expr, idx)
1974     }
1975
1976     pub fn mk_assign_op(&mut self, binop: ast::BinOp,
1977                         lhs: P<Expr>, rhs: P<Expr>) -> ast::Expr_ {
1978         ExprAssignOp(binop, lhs, rhs)
1979     }
1980
1981     pub fn mk_mac_expr(&mut self, lo: BytePos, hi: BytePos,
1982                        m: Mac_, attrs: ThinAttributes) -> P<Expr> {
1983         P(Expr {
1984             id: ast::DUMMY_NODE_ID,
1985             node: ExprMac(codemap::Spanned {node: m, span: mk_sp(lo, hi)}),
1986             span: mk_sp(lo, hi),
1987             attrs: attrs,
1988         })
1989     }
1990
1991     pub fn mk_lit_u32(&mut self, i: u32, attrs: ThinAttributes) -> P<Expr> {
1992         let span = &self.span;
1993         let lv_lit = P(codemap::Spanned {
1994             node: LitInt(i as u64, ast::UnsignedIntLit(TyU32)),
1995             span: *span
1996         });
1997
1998         P(Expr {
1999             id: ast::DUMMY_NODE_ID,
2000             node: ExprLit(lv_lit),
2001             span: *span,
2002             attrs: attrs,
2003         })
2004     }
2005
2006     fn expect_open_delim(&mut self) -> PResult<'a, token::DelimToken> {
2007         self.expected_tokens.push(TokenType::Token(token::Gt));
2008         match self.token {
2009             token::OpenDelim(delim) => {
2010                 try!(self.bump());
2011                 Ok(delim)
2012             },
2013             _ => Err(self.fatal("expected open delimiter")),
2014         }
2015     }
2016
2017     /// At the bottom (top?) of the precedence hierarchy,
2018     /// parse things like parenthesized exprs,
2019     /// macros, return, etc.
2020     ///
2021     /// NB: This does not parse outer attributes,
2022     ///     and is private because it only works
2023     ///     correctly if called from parse_dot_or_call_expr().
2024     fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2025         maybe_whole_expr!(self);
2026
2027         // Outer attributes are already parsed and will be
2028         // added to the return value after the fact.
2029         //
2030         // Therefore, prevent sub-parser from parsing
2031         // attributes by giving them a empty "already parsed" list.
2032         let mut attrs = None;
2033
2034         let lo = self.span.lo;
2035         let mut hi = self.span.hi;
2036
2037         let ex: Expr_;
2038
2039         // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2040         match self.token {
2041             token::OpenDelim(token::Paren) => {
2042                 try!(self.bump());
2043
2044                 let attrs = try!(self.parse_inner_attributes())
2045                     .into_thin_attrs()
2046                     .prepend(attrs);
2047
2048                 // (e) is parenthesized e
2049                 // (e,) is a tuple with only one field, e
2050                 let mut es = vec![];
2051                 let mut trailing_comma = false;
2052                 while self.token != token::CloseDelim(token::Paren) {
2053                     es.push(try!(self.parse_expr()));
2054                     try!(self.commit_expr(&**es.last().unwrap(), &[],
2055                                      &[token::Comma, token::CloseDelim(token::Paren)]));
2056                     if self.check(&token::Comma) {
2057                         trailing_comma = true;
2058
2059                         try!(self.bump());
2060                     } else {
2061                         trailing_comma = false;
2062                         break;
2063                     }
2064                 }
2065                 try!(self.bump());
2066
2067                 hi = self.last_span.hi;
2068                 return if es.len() == 1 && !trailing_comma {
2069                     Ok(self.mk_expr(lo, hi, ExprParen(es.into_iter().nth(0).unwrap()), attrs))
2070                 } else {
2071                     Ok(self.mk_expr(lo, hi, ExprTup(es), attrs))
2072                 }
2073             },
2074             token::OpenDelim(token::Brace) => {
2075                 return self.parse_block_expr(lo, DefaultBlock, attrs);
2076             },
2077             token::BinOp(token::Or) |  token::OrOr => {
2078                 let lo = self.span.lo;
2079                 return self.parse_lambda_expr(lo, CaptureByRef, attrs);
2080             },
2081             token::Ident(id @ ast::Ident {
2082                             name: token::SELF_KEYWORD_NAME,
2083                             ctxt: _
2084                          }, token::Plain) => {
2085                 try!(self.bump());
2086                 let path = ast_util::ident_to_path(mk_sp(lo, hi), id);
2087                 ex = ExprPath(None, path);
2088                 hi = self.last_span.hi;
2089             }
2090             token::OpenDelim(token::Bracket) => {
2091                 try!(self.bump());
2092
2093                 let inner_attrs = try!(self.parse_inner_attributes())
2094                     .into_thin_attrs();
2095                 attrs.update(|attrs| attrs.append(inner_attrs));
2096
2097                 if self.check(&token::CloseDelim(token::Bracket)) {
2098                     // Empty vector.
2099                     try!(self.bump());
2100                     ex = ExprVec(Vec::new());
2101                 } else {
2102                     // Nonempty vector.
2103                     let first_expr = try!(self.parse_expr());
2104                     if self.check(&token::Semi) {
2105                         // Repeating array syntax: [ 0; 512 ]
2106                         try!(self.bump());
2107                         let count = try!(self.parse_expr());
2108                         try!(self.expect(&token::CloseDelim(token::Bracket)));
2109                         ex = ExprRepeat(first_expr, count);
2110                     } else if self.check(&token::Comma) {
2111                         // Vector with two or more elements.
2112                         try!(self.bump());
2113                         let remaining_exprs = try!(self.parse_seq_to_end(
2114                             &token::CloseDelim(token::Bracket),
2115                             seq_sep_trailing_allowed(token::Comma),
2116                             |p| Ok(try!(p.parse_expr()))
2117                                 ));
2118                         let mut exprs = vec!(first_expr);
2119                         exprs.extend(remaining_exprs);
2120                         ex = ExprVec(exprs);
2121                     } else {
2122                         // Vector with one element.
2123                         try!(self.expect(&token::CloseDelim(token::Bracket)));
2124                         ex = ExprVec(vec!(first_expr));
2125                     }
2126                 }
2127                 hi = self.last_span.hi;
2128             }
2129             _ => {
2130                 if try!(self.eat_lt()){
2131                     let (qself, path) =
2132                         try!(self.parse_qualified_path(LifetimeAndTypesWithColons));
2133                     hi = path.span.hi;
2134                     return Ok(self.mk_expr(lo, hi, ExprPath(Some(qself), path), attrs));
2135                 }
2136                 if try!(self.eat_keyword(keywords::Move) ){
2137                     let lo = self.last_span.lo;
2138                     return self.parse_lambda_expr(lo, CaptureByValue, attrs);
2139                 }
2140                 if try!(self.eat_keyword(keywords::If)) {
2141                     return self.parse_if_expr(attrs);
2142                 }
2143                 if try!(self.eat_keyword(keywords::For) ){
2144                     let lo = self.last_span.lo;
2145                     return self.parse_for_expr(None, lo, attrs);
2146                 }
2147                 if try!(self.eat_keyword(keywords::While) ){
2148                     let lo = self.last_span.lo;
2149                     return self.parse_while_expr(None, lo, attrs);
2150                 }
2151                 if self.token.is_lifetime() {
2152                     let lifetime = self.get_lifetime();
2153                     let lo = self.span.lo;
2154                     try!(self.bump());
2155                     try!(self.expect(&token::Colon));
2156                     if try!(self.eat_keyword(keywords::While) ){
2157                         return self.parse_while_expr(Some(lifetime), lo, attrs)
2158                     }
2159                     if try!(self.eat_keyword(keywords::For) ){
2160                         return self.parse_for_expr(Some(lifetime), lo, attrs)
2161                     }
2162                     if try!(self.eat_keyword(keywords::Loop) ){
2163                         return self.parse_loop_expr(Some(lifetime), lo, attrs)
2164                     }
2165                     return Err(self.fatal("expected `while`, `for`, or `loop` after a label"))
2166                 }
2167                 if try!(self.eat_keyword(keywords::Loop) ){
2168                     let lo = self.last_span.lo;
2169                     return self.parse_loop_expr(None, lo, attrs);
2170                 }
2171                 if try!(self.eat_keyword(keywords::Continue) ){
2172                     let ex = if self.token.is_lifetime() {
2173                         let ex = ExprAgain(Some(Spanned{
2174                             node: self.get_lifetime(),
2175                             span: self.span
2176                         }));
2177                         try!(self.bump());
2178                         ex
2179                     } else {
2180                         ExprAgain(None)
2181                     };
2182                     let hi = self.last_span.hi;
2183                     return Ok(self.mk_expr(lo, hi, ex, attrs));
2184                 }
2185                 if try!(self.eat_keyword(keywords::Match) ){
2186                     return self.parse_match_expr(attrs);
2187                 }
2188                 if try!(self.eat_keyword(keywords::Unsafe) ){
2189                     return self.parse_block_expr(
2190                         lo,
2191                         UnsafeBlock(ast::UserProvided),
2192                         attrs);
2193                 }
2194                 if try!(self.eat_keyword(keywords::Return) ){
2195                     if self.token.can_begin_expr() {
2196                         let e = try!(self.parse_expr());
2197                         hi = e.span.hi;
2198                         ex = ExprRet(Some(e));
2199                     } else {
2200                         ex = ExprRet(None);
2201                     }
2202                 } else if try!(self.eat_keyword(keywords::Break) ){
2203                     if self.token.is_lifetime() {
2204                         ex = ExprBreak(Some(Spanned {
2205                             node: self.get_lifetime(),
2206                             span: self.span
2207                         }));
2208                         try!(self.bump());
2209                     } else {
2210                         ex = ExprBreak(None);
2211                     }
2212                     hi = self.last_span.hi;
2213                 } else if self.check(&token::ModSep) ||
2214                         self.token.is_ident() &&
2215                         !self.check_keyword(keywords::True) &&
2216                         !self.check_keyword(keywords::False) {
2217                     let pth =
2218                         try!(self.parse_path(LifetimeAndTypesWithColons));
2219
2220                     // `!`, as an operator, is prefix, so we know this isn't that
2221                     if self.check(&token::Not) {
2222                         // MACRO INVOCATION expression
2223                         try!(self.bump());
2224
2225                         let delim = try!(self.expect_open_delim());
2226                         let tts = try!(self.parse_seq_to_end(
2227                             &token::CloseDelim(delim),
2228                             seq_sep_none(),
2229                             |p| p.parse_token_tree()));
2230                         let hi = self.last_span.hi;
2231
2232                         return Ok(self.mk_mac_expr(lo,
2233                                                    hi,
2234                                                    Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT },
2235                                                    attrs));
2236                     }
2237                     if self.check(&token::OpenDelim(token::Brace)) {
2238                         // This is a struct literal, unless we're prohibited
2239                         // from parsing struct literals here.
2240                         let prohibited = self.restrictions.contains(
2241                             Restrictions::RESTRICTION_NO_STRUCT_LITERAL
2242                         );
2243                         if !prohibited {
2244                             // It's a struct literal.
2245                             try!(self.bump());
2246                             let mut fields = Vec::new();
2247                             let mut base = None;
2248
2249                             let attrs = attrs.append(
2250                                 try!(self.parse_inner_attributes())
2251                                     .into_thin_attrs());
2252
2253                             while self.token != token::CloseDelim(token::Brace) {
2254                                 if try!(self.eat(&token::DotDot) ){
2255                                     base = Some(try!(self.parse_expr()));
2256                                     break;
2257                                 }
2258
2259                                 fields.push(try!(self.parse_field()));
2260                                 try!(self.commit_expr(&*fields.last().unwrap().expr,
2261                                                  &[token::Comma],
2262                                                  &[token::CloseDelim(token::Brace)]));
2263                             }
2264
2265                             hi = self.span.hi;
2266                             try!(self.expect(&token::CloseDelim(token::Brace)));
2267                             ex = ExprStruct(pth, fields, base);
2268                             return Ok(self.mk_expr(lo, hi, ex, attrs));
2269                         }
2270                     }
2271
2272                     hi = pth.span.hi;
2273                     ex = ExprPath(None, pth);
2274                 } else {
2275                     // other literal expression
2276                     let lit = try!(self.parse_lit());
2277                     hi = lit.span.hi;
2278                     ex = ExprLit(P(lit));
2279                 }
2280             }
2281         }
2282
2283         return Ok(self.mk_expr(lo, hi, ex, attrs));
2284     }
2285
2286     fn parse_or_use_outer_attributes(&mut self,
2287                                      already_parsed_attrs: Option<ThinAttributes>)
2288                                      -> PResult<'a, ThinAttributes> {
2289         if let Some(attrs) = already_parsed_attrs {
2290             Ok(attrs)
2291         } else {
2292             self.parse_outer_attributes().map(|a| a.into_thin_attrs())
2293         }
2294     }
2295
2296     /// Parse a block or unsafe block
2297     pub fn parse_block_expr(&mut self, lo: BytePos, blk_mode: BlockCheckMode,
2298                             attrs: ThinAttributes)
2299                             -> PResult<'a, P<Expr>> {
2300
2301         let outer_attrs = attrs;
2302         try!(self.expect(&token::OpenDelim(token::Brace)));
2303
2304         let inner_attrs = try!(self.parse_inner_attributes()).into_thin_attrs();
2305         let attrs = outer_attrs.append(inner_attrs);
2306
2307         let blk = try!(self.parse_block_tail(lo, blk_mode));
2308         return Ok(self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk), attrs));
2309     }
2310
2311     /// parse a.b or a(13) or a[4] or just a
2312     pub fn parse_dot_or_call_expr(&mut self,
2313                                   already_parsed_attrs: Option<ThinAttributes>)
2314                                   -> PResult<'a, P<Expr>> {
2315         let attrs = try!(self.parse_or_use_outer_attributes(already_parsed_attrs));
2316
2317         let b = try!(self.parse_bottom_expr());
2318         self.parse_dot_or_call_expr_with(b, attrs)
2319     }
2320
2321     pub fn parse_dot_or_call_expr_with(&mut self,
2322                                        e0: P<Expr>,
2323                                        attrs: ThinAttributes)
2324                                        -> PResult<'a, P<Expr>> {
2325         // Stitch the list of outer attributes onto the return value.
2326         // A little bit ugly, but the best way given the current code
2327         // structure
2328         self.parse_dot_or_call_expr_with_(e0)
2329         .map(|expr|
2330             expr.map(|mut expr| {
2331                 expr.attrs.update(|a| a.prepend(attrs));
2332                 match expr.node {
2333                     ExprIf(..) | ExprIfLet(..) => {
2334                         if !expr.attrs.as_attr_slice().is_empty() {
2335                             // Just point to the first attribute in there...
2336                             let span = expr.attrs.as_attr_slice()[0].span;
2337
2338                             self.span_err(span,
2339                                 "attributes are not yet allowed on `if` \
2340                                 expressions");
2341                         }
2342                     }
2343                     _ => {}
2344                 }
2345                 expr
2346             })
2347         )
2348     }
2349
2350     fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>) -> PResult<'a, P<Expr>> {
2351         let mut e = e0;
2352         let lo = e.span.lo;
2353         let mut hi;
2354         loop {
2355             // expr.f
2356             if try!(self.eat(&token::Dot) ){
2357                 match self.token {
2358                   token::Ident(i, _) => {
2359                     let dot = self.last_span.hi;
2360                     hi = self.span.hi;
2361                     try!(self.bump());
2362                     let (_, tys, bindings) = if try!(self.eat(&token::ModSep) ){
2363                         try!(self.expect_lt());
2364                         try!(self.parse_generic_values_after_lt())
2365                     } else {
2366                         (Vec::new(), Vec::new(), Vec::new())
2367                     };
2368
2369                     if !bindings.is_empty() {
2370                         let last_span = self.last_span;
2371                         self.span_err(last_span, "type bindings are only permitted on trait paths");
2372                     }
2373
2374                     // expr.f() method call
2375                     match self.token {
2376                         token::OpenDelim(token::Paren) => {
2377                             let mut es = try!(self.parse_unspanned_seq(
2378                                 &token::OpenDelim(token::Paren),
2379                                 &token::CloseDelim(token::Paren),
2380                                 seq_sep_trailing_allowed(token::Comma),
2381                                 |p| Ok(try!(p.parse_expr()))
2382                             ));
2383                             hi = self.last_span.hi;
2384
2385                             es.insert(0, e);
2386                             let id = spanned(dot, hi, i);
2387                             let nd = self.mk_method_call(id, tys, es);
2388                             e = self.mk_expr(lo, hi, nd, None);
2389                         }
2390                         _ => {
2391                             if !tys.is_empty() {
2392                                 let last_span = self.last_span;
2393                                 self.span_err(last_span,
2394                                               "field expressions may not \
2395                                                have type parameters");
2396                             }
2397
2398                             let id = spanned(dot, hi, i);
2399                             let field = self.mk_field(e, id);
2400                             e = self.mk_expr(lo, hi, field, None);
2401                         }
2402                     }
2403                   }
2404                   token::Literal(token::Integer(n), suf) => {
2405                     let sp = self.span;
2406
2407                     // A tuple index may not have a suffix
2408                     self.expect_no_suffix(sp, "tuple index", suf);
2409
2410                     let dot = self.last_span.hi;
2411                     hi = self.span.hi;
2412                     try!(self.bump());
2413
2414                     let index = n.as_str().parse::<usize>().ok();
2415                     match index {
2416                         Some(n) => {
2417                             let id = spanned(dot, hi, n);
2418                             let field = self.mk_tup_field(e, id);
2419                             e = self.mk_expr(lo, hi, field, None);
2420                         }
2421                         None => {
2422                             let last_span = self.last_span;
2423                             self.span_err(last_span, "invalid tuple or tuple struct index");
2424                         }
2425                     }
2426                   }
2427                   token::Literal(token::Float(n), _suf) => {
2428                     try!(self.bump());
2429                     let last_span = self.last_span;
2430                     let fstr = n.as_str();
2431                     let mut err = self.diagnostic().struct_span_err(last_span,
2432                         &format!("unexpected token: `{}`", n.as_str()));
2433                     if fstr.chars().all(|x| "0123456789.".contains(x)) {
2434                         let float = match fstr.parse::<f64>().ok() {
2435                             Some(f) => f,
2436                             None => continue,
2437                         };
2438                         err.fileline_help(last_span,
2439                             &format!("try parenthesizing the first index; e.g., `(foo.{}){}`",
2440                                     float.trunc() as usize,
2441                                     format!(".{}", fstr.splitn(2, ".").last().unwrap())));
2442                     }
2443                     err.emit();
2444                     self.abort_if_errors();
2445
2446                   }
2447                   _ => return Err(self.unexpected())
2448                 }
2449                 continue;
2450             }
2451             if self.expr_is_complete(&*e) { break; }
2452             match self.token {
2453               // expr(...)
2454               token::OpenDelim(token::Paren) => {
2455                 let es = try!(self.parse_unspanned_seq(
2456                     &token::OpenDelim(token::Paren),
2457                     &token::CloseDelim(token::Paren),
2458                     seq_sep_trailing_allowed(token::Comma),
2459                     |p| Ok(try!(p.parse_expr()))
2460                 ));
2461                 hi = self.last_span.hi;
2462
2463                 let nd = self.mk_call(e, es);
2464                 e = self.mk_expr(lo, hi, nd, None);
2465               }
2466
2467               // expr[...]
2468               // Could be either an index expression or a slicing expression.
2469               token::OpenDelim(token::Bracket) => {
2470                 try!(self.bump());
2471                 let ix = try!(self.parse_expr());
2472                 hi = self.span.hi;
2473                 try!(self.commit_expr_expecting(&*ix, token::CloseDelim(token::Bracket)));
2474                 let index = self.mk_index(e, ix);
2475                 e = self.mk_expr(lo, hi, index, None)
2476               }
2477               _ => return Ok(e)
2478             }
2479         }
2480         return Ok(e);
2481     }
2482
2483     // Parse unquoted tokens after a `$` in a token tree
2484     fn parse_unquoted(&mut self) -> PResult<'a, TokenTree> {
2485         let mut sp = self.span;
2486         let (name, namep) = match self.token {
2487             token::Dollar => {
2488                 try!(self.bump());
2489
2490                 if self.token == token::OpenDelim(token::Paren) {
2491                     let Spanned { node: seq, span: seq_span } = try!(self.parse_seq(
2492                         &token::OpenDelim(token::Paren),
2493                         &token::CloseDelim(token::Paren),
2494                         seq_sep_none(),
2495                         |p| p.parse_token_tree()
2496                     ));
2497                     let (sep, repeat) = try!(self.parse_sep_and_kleene_op());
2498                     let name_num = macro_parser::count_names(&seq);
2499                     return Ok(TokenTree::Sequence(mk_sp(sp.lo, seq_span.hi),
2500                                       Rc::new(SequenceRepetition {
2501                                           tts: seq,
2502                                           separator: sep,
2503                                           op: repeat,
2504                                           num_captures: name_num
2505                                       })));
2506                 } else if self.token.is_keyword_allow_following_colon(keywords::Crate) {
2507                     try!(self.bump());
2508                     return Ok(TokenTree::Token(sp, SpecialVarNt(SpecialMacroVar::CrateMacroVar)));
2509                 } else {
2510                     sp = mk_sp(sp.lo, self.span.hi);
2511                     let namep = match self.token { token::Ident(_, p) => p, _ => token::Plain };
2512                     let name = try!(self.parse_ident());
2513                     (name, namep)
2514                 }
2515             }
2516             token::SubstNt(name, namep) => {
2517                 try!(self.bump());
2518                 (name, namep)
2519             }
2520             _ => unreachable!()
2521         };
2522         // continue by trying to parse the `:ident` after `$name`
2523         if self.token == token::Colon && self.look_ahead(1, |t| t.is_ident() &&
2524                                                                 !t.is_strict_keyword() &&
2525                                                                 !t.is_reserved_keyword()) {
2526             try!(self.bump());
2527             sp = mk_sp(sp.lo, self.span.hi);
2528             let kindp = match self.token { token::Ident(_, p) => p, _ => token::Plain };
2529             let nt_kind = try!(self.parse_ident());
2530             Ok(TokenTree::Token(sp, MatchNt(name, nt_kind, namep, kindp)))
2531         } else {
2532             Ok(TokenTree::Token(sp, SubstNt(name, namep)))
2533         }
2534     }
2535
2536     pub fn check_unknown_macro_variable(&mut self) -> PResult<'a, ()> {
2537         if self.quote_depth == 0 {
2538             match self.token {
2539                 token::SubstNt(name, _) =>
2540                     return Err(self.fatal(&format!("unknown macro variable `{}`",
2541                                        name))),
2542                 _ => {}
2543             }
2544         }
2545         Ok(())
2546     }
2547
2548     /// Parse an optional separator followed by a Kleene-style
2549     /// repetition token (+ or *).
2550     pub fn parse_sep_and_kleene_op(&mut self)
2551                                    -> PResult<'a, (Option<token::Token>, ast::KleeneOp)> {
2552         fn parse_kleene_op<'a>(parser: &mut Parser<'a>) -> PResult<'a,  Option<ast::KleeneOp>> {
2553             match parser.token {
2554                 token::BinOp(token::Star) => {
2555                     try!(parser.bump());
2556                     Ok(Some(ast::ZeroOrMore))
2557                 },
2558                 token::BinOp(token::Plus) => {
2559                     try!(parser.bump());
2560                     Ok(Some(ast::OneOrMore))
2561                 },
2562                 _ => Ok(None)
2563             }
2564         };
2565
2566         match try!(parse_kleene_op(self)) {
2567             Some(kleene_op) => return Ok((None, kleene_op)),
2568             None => {}
2569         }
2570
2571         let separator = try!(self.bump_and_get());
2572         match try!(parse_kleene_op(self)) {
2573             Some(zerok) => Ok((Some(separator), zerok)),
2574             None => return Err(self.fatal("expected `*` or `+`"))
2575         }
2576     }
2577
2578     /// parse a single token tree from the input.
2579     pub fn parse_token_tree(&mut self) -> PResult<'a, TokenTree> {
2580         // FIXME #6994: currently, this is too eager. It
2581         // parses token trees but also identifies TokenType::Sequence's
2582         // and token::SubstNt's; it's too early to know yet
2583         // whether something will be a nonterminal or a seq
2584         // yet.
2585         maybe_whole!(deref self, NtTT);
2586
2587         // this is the fall-through for the 'match' below.
2588         // invariants: the current token is not a left-delimiter,
2589         // not an EOF, and not the desired right-delimiter (if
2590         // it were, parse_seq_to_before_end would have prevented
2591         // reaching this point.
2592         fn parse_non_delim_tt_tok<'b>(p: &mut Parser<'b>) -> PResult<'b,  TokenTree> {
2593             maybe_whole!(deref p, NtTT);
2594             match p.token {
2595                 token::CloseDelim(_) => {
2596                     let token_str = p.this_token_to_string();
2597                     let mut err = p.fatal(
2598                         &format!("incorrect close delimiter: `{}`", token_str));
2599                     // This is a conservative error: only report the last unclosed delimiter. The
2600                     // previous unclosed delimiters could actually be closed! The parser just hasn't
2601                     // gotten to them yet.
2602                     if let Some(&sp) = p.open_braces.last() {
2603                         err.span_note(sp, "unclosed delimiter");
2604                     };
2605                     Err(err)
2606                 },
2607                 /* we ought to allow different depths of unquotation */
2608                 token::Dollar | token::SubstNt(..) if p.quote_depth > 0 => {
2609                     p.parse_unquoted()
2610                 }
2611                 _ => {
2612                     Ok(TokenTree::Token(p.span, try!(p.bump_and_get())))
2613                 }
2614             }
2615         }
2616
2617         match self.token {
2618             token::Eof => {
2619                 let open_braces = self.open_braces.clone();
2620                 let mut err: DiagnosticBuilder<'a> =
2621                     self.fatal("this file contains an un-closed delimiter");
2622                 for sp in &open_braces {
2623                     err.span_help(*sp, "did you mean to close this delimiter?");
2624                 }
2625                 return Err(err);
2626             },
2627             token::OpenDelim(delim) => {
2628                 // The span for beginning of the delimited section
2629                 let pre_span = self.span;
2630
2631                 // Parse the open delimiter.
2632                 self.open_braces.push(self.span);
2633                 let open_span = self.span;
2634                 try!(self.bump());
2635
2636                 // Parse the token trees within the delimiters
2637                 let tts = try!(self.parse_seq_to_before_end(
2638                     &token::CloseDelim(delim),
2639                     seq_sep_none(),
2640                     |p| p.parse_token_tree()
2641                 ));
2642
2643                 // Parse the close delimiter.
2644                 let close_span = self.span;
2645                 try!(self.bump());
2646                 self.open_braces.pop().unwrap();
2647
2648                 // Expand to cover the entire delimited token tree
2649                 let span = Span { hi: close_span.hi, ..pre_span };
2650
2651                 Ok(TokenTree::Delimited(span, Rc::new(Delimited {
2652                     delim: delim,
2653                     open_span: open_span,
2654                     tts: tts,
2655                     close_span: close_span,
2656                 })))
2657             },
2658             _ => parse_non_delim_tt_tok(self),
2659         }
2660     }
2661
2662     // parse a stream of tokens into a list of TokenTree's,
2663     // up to EOF.
2664     pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2665         let mut tts = Vec::new();
2666         while self.token != token::Eof {
2667             tts.push(try!(self.parse_token_tree()));
2668         }
2669         Ok(tts)
2670     }
2671
2672     /// Parse a prefix-unary-operator expr
2673     pub fn parse_prefix_expr(&mut self,
2674                              already_parsed_attrs: Option<ThinAttributes>)
2675                              -> PResult<'a, P<Expr>> {
2676         let attrs = try!(self.parse_or_use_outer_attributes(already_parsed_attrs));
2677         let lo = self.span.lo;
2678         let hi;
2679         // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2680         let ex = match self.token {
2681             token::Not => {
2682                 try!(self.bump());
2683                 let e = try!(self.parse_prefix_expr(None));
2684                 hi = e.span.hi;
2685                 self.mk_unary(UnNot, e)
2686             }
2687             token::BinOp(token::Minus) => {
2688                 try!(self.bump());
2689                 let e = try!(self.parse_prefix_expr(None));
2690                 hi = e.span.hi;
2691                 self.mk_unary(UnNeg, e)
2692             }
2693             token::BinOp(token::Star) => {
2694                 try!(self.bump());
2695                 let e = try!(self.parse_prefix_expr(None));
2696                 hi = e.span.hi;
2697                 self.mk_unary(UnDeref, e)
2698             }
2699             token::BinOp(token::And) | token::AndAnd => {
2700                 try!(self.expect_and());
2701                 let m = try!(self.parse_mutability());
2702                 let e = try!(self.parse_prefix_expr(None));
2703                 hi = e.span.hi;
2704                 ExprAddrOf(m, e)
2705             }
2706             token::Ident(..) if self.token.is_keyword(keywords::In) => {
2707                 try!(self.bump());
2708                 let place = try!(self.parse_expr_res(
2709                     Restrictions::RESTRICTION_NO_STRUCT_LITERAL,
2710                     None,
2711                 ));
2712                 let blk = try!(self.parse_block());
2713                 let span = blk.span;
2714                 hi = span.hi;
2715                 let blk_expr = self.mk_expr(span.lo, span.hi, ExprBlock(blk),
2716                                             None);
2717                 ExprInPlace(place, blk_expr)
2718             }
2719             token::Ident(..) if self.token.is_keyword(keywords::Box) => {
2720                 try!(self.bump());
2721                 let subexpression = try!(self.parse_prefix_expr(None));
2722                 hi = subexpression.span.hi;
2723                 ExprBox(subexpression)
2724             }
2725             _ => return self.parse_dot_or_call_expr(Some(attrs))
2726         };
2727         return Ok(self.mk_expr(lo, hi, ex, attrs));
2728     }
2729
2730     /// Parse an associative expression
2731     ///
2732     /// This parses an expression accounting for associativity and precedence of the operators in
2733     /// the expression.
2734     pub fn parse_assoc_expr(&mut self,
2735                             already_parsed_attrs: Option<ThinAttributes>)
2736                             -> PResult<'a, P<Expr>> {
2737         self.parse_assoc_expr_with(0, already_parsed_attrs.into())
2738     }
2739
2740     /// Parse an associative expression with operators of at least `min_prec` precedence
2741     pub fn parse_assoc_expr_with(&mut self,
2742                                  min_prec: usize,
2743                                  lhs: LhsExpr)
2744                                  -> PResult<'a, P<Expr>> {
2745         let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
2746             expr
2747         } else {
2748             let attrs = match lhs {
2749                 LhsExpr::AttributesParsed(attrs) => Some(attrs),
2750                 _ => None,
2751             };
2752             if self.token == token::DotDot {
2753                 return self.parse_prefix_range_expr(attrs);
2754             } else {
2755                 try!(self.parse_prefix_expr(attrs))
2756             }
2757         };
2758         if self.expr_is_complete(&*lhs) {
2759             // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
2760             return Ok(lhs);
2761         }
2762         self.expected_tokens.push(TokenType::Operator);
2763         while let Some(op) = AssocOp::from_token(&self.token) {
2764             let cur_op_span = self.span;
2765             let restrictions = if op.is_assign_like() {
2766                 self.restrictions & Restrictions::RESTRICTION_NO_STRUCT_LITERAL
2767             } else {
2768                 self.restrictions
2769             };
2770             if op.precedence() < min_prec {
2771                 break;
2772             }
2773             try!(self.bump());
2774             if op.is_comparison() {
2775                 self.check_no_chained_comparison(&*lhs, &op);
2776             }
2777             // Special cases:
2778             if op == AssocOp::As {
2779                 let rhs = try!(self.parse_ty());
2780                 lhs = self.mk_expr(lhs.span.lo, rhs.span.hi,
2781                                    ExprCast(lhs, rhs), None);
2782                 continue
2783             } else if op == AssocOp::Colon {
2784                 let rhs = try!(self.parse_ty());
2785                 lhs = self.mk_expr(lhs.span.lo, rhs.span.hi,
2786                                    ExprType(lhs, rhs), None);
2787                 continue
2788             } else if op == AssocOp::DotDot {
2789                     // If we didn’t have to handle `x..`, it would be pretty easy to generalise
2790                     // it to the Fixity::None code.
2791                     //
2792                     // We have 2 alternatives here: `x..y` and `x..` The other two variants are
2793                     // handled with `parse_prefix_range_expr` call above.
2794                     let rhs = if self.is_at_start_of_range_notation_rhs() {
2795                         self.parse_assoc_expr_with(op.precedence() + 1,
2796                                                    LhsExpr::NotYetParsed).ok()
2797                     } else {
2798                         None
2799                     };
2800                     let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
2801                         x.span
2802                     } else {
2803                         cur_op_span
2804                     });
2805                     let r = self.mk_range(Some(lhs), rhs);
2806                     lhs = self.mk_expr(lhs_span.lo, rhs_span.hi, r, None);
2807                     break
2808             }
2809
2810             let rhs = try!(match op.fixity() {
2811                 Fixity::Right => self.with_res(restrictions, |this|{
2812                     this.parse_assoc_expr_with(op.precedence(), LhsExpr::NotYetParsed)
2813                 }),
2814                 Fixity::Left => self.with_res(restrictions, |this|{
2815                     this.parse_assoc_expr_with(op.precedence() + 1, LhsExpr::NotYetParsed)
2816                 }),
2817                 // We currently have no non-associative operators that are not handled above by
2818                 // the special cases. The code is here only for future convenience.
2819                 Fixity::None => self.with_res(restrictions, |this|{
2820                     this.parse_assoc_expr_with(op.precedence() + 1, LhsExpr::NotYetParsed)
2821                 }),
2822             });
2823
2824             lhs = match op {
2825                 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
2826                 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
2827                 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
2828                 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
2829                 AssocOp::Greater | AssocOp::GreaterEqual => {
2830                     let ast_op = op.to_ast_binop().unwrap();
2831                     let (lhs_span, rhs_span) = (lhs.span, rhs.span);
2832                     let binary = self.mk_binary(codemap::respan(cur_op_span, ast_op), lhs, rhs);
2833                     self.mk_expr(lhs_span.lo, rhs_span.hi, binary, None)
2834                 }
2835                 AssocOp::Assign =>
2836                     self.mk_expr(lhs.span.lo, rhs.span.hi, ExprAssign(lhs, rhs), None),
2837                 AssocOp::Inplace =>
2838                     self.mk_expr(lhs.span.lo, rhs.span.hi, ExprInPlace(lhs, rhs), None),
2839                 AssocOp::AssignOp(k) => {
2840                     let aop = match k {
2841                         token::Plus =>    BiAdd,
2842                         token::Minus =>   BiSub,
2843                         token::Star =>    BiMul,
2844                         token::Slash =>   BiDiv,
2845                         token::Percent => BiRem,
2846                         token::Caret =>   BiBitXor,
2847                         token::And =>     BiBitAnd,
2848                         token::Or =>      BiBitOr,
2849                         token::Shl =>     BiShl,
2850                         token::Shr =>     BiShr
2851                     };
2852                     let (lhs_span, rhs_span) = (lhs.span, rhs.span);
2853                     let aopexpr = self.mk_assign_op(codemap::respan(cur_op_span, aop), lhs, rhs);
2854                     self.mk_expr(lhs_span.lo, rhs_span.hi, aopexpr, None)
2855                 }
2856                 AssocOp::As | AssocOp::Colon | AssocOp::DotDot => {
2857                     self.bug("As, Colon or DotDot branch reached")
2858                 }
2859             };
2860
2861             if op.fixity() == Fixity::None { break }
2862         }
2863         Ok(lhs)
2864     }
2865
2866     /// Produce an error if comparison operators are chained (RFC #558).
2867     /// We only need to check lhs, not rhs, because all comparison ops
2868     /// have same precedence and are left-associative
2869     fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
2870         debug_assert!(outer_op.is_comparison());
2871         match lhs.node {
2872             ExprBinary(op, _, _) if op.node.is_comparison() => {
2873                 // respan to include both operators
2874                 let op_span = mk_sp(op.span.lo, self.span.hi);
2875                 let mut err = self.diagnostic().struct_span_err(op_span,
2876                     "chained comparison operators require parentheses");
2877                 if op.node == BiLt && *outer_op == AssocOp::Greater {
2878                     err.fileline_help(op_span,
2879                         "use `::<...>` instead of `<...>` if you meant to specify type arguments");
2880                 }
2881                 err.emit();
2882             }
2883             _ => {}
2884         }
2885     }
2886
2887     /// Parse prefix-forms of range notation: `..expr` and `..`
2888     fn parse_prefix_range_expr(&mut self,
2889                                already_parsed_attrs: Option<ThinAttributes>)
2890                                -> PResult<'a, P<Expr>> {
2891         debug_assert!(self.token == token::DotDot);
2892         let attrs = try!(self.parse_or_use_outer_attributes(already_parsed_attrs));
2893         let lo = self.span.lo;
2894         let mut hi = self.span.hi;
2895         try!(self.bump());
2896         let opt_end = if self.is_at_start_of_range_notation_rhs() {
2897             // RHS must be parsed with more associativity than DotDot.
2898             let next_prec = AssocOp::from_token(&token::DotDot).unwrap().precedence() + 1;
2899             Some(try!(self.parse_assoc_expr_with(next_prec,
2900                                                  LhsExpr::NotYetParsed)
2901             .map(|x|{
2902                 hi = x.span.hi;
2903                 x
2904             })))
2905          } else {
2906             None
2907         };
2908         let r = self.mk_range(None, opt_end);
2909         Ok(self.mk_expr(lo, hi, r, attrs))
2910     }
2911
2912     fn is_at_start_of_range_notation_rhs(&self) -> bool {
2913         if self.token.can_begin_expr() {
2914             // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
2915             if self.token == token::OpenDelim(token::Brace) {
2916                 return !self.restrictions.contains(Restrictions::RESTRICTION_NO_STRUCT_LITERAL);
2917             }
2918             true
2919         } else {
2920             false
2921         }
2922     }
2923
2924     /// Parse an 'if' or 'if let' expression ('if' token already eaten)
2925     pub fn parse_if_expr(&mut self, attrs: ThinAttributes) -> PResult<'a, P<Expr>> {
2926         if self.check_keyword(keywords::Let) {
2927             return self.parse_if_let_expr(attrs);
2928         }
2929         let lo = self.last_span.lo;
2930         let cond = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
2931         let thn = try!(self.parse_block());
2932         let mut els: Option<P<Expr>> = None;
2933         let mut hi = thn.span.hi;
2934         if try!(self.eat_keyword(keywords::Else) ){
2935             let elexpr = try!(self.parse_else_expr());
2936             hi = elexpr.span.hi;
2937             els = Some(elexpr);
2938         }
2939         Ok(self.mk_expr(lo, hi, ExprIf(cond, thn, els), attrs))
2940     }
2941
2942     /// Parse an 'if let' expression ('if' token already eaten)
2943     pub fn parse_if_let_expr(&mut self, attrs: ThinAttributes)
2944                              -> PResult<'a, P<Expr>> {
2945         let lo = self.last_span.lo;
2946         try!(self.expect_keyword(keywords::Let));
2947         let pat = try!(self.parse_pat());
2948         try!(self.expect(&token::Eq));
2949         let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
2950         let thn = try!(self.parse_block());
2951         let (hi, els) = if try!(self.eat_keyword(keywords::Else) ){
2952             let expr = try!(self.parse_else_expr());
2953             (expr.span.hi, Some(expr))
2954         } else {
2955             (thn.span.hi, None)
2956         };
2957         Ok(self.mk_expr(lo, hi, ExprIfLet(pat, expr, thn, els), attrs))
2958     }
2959
2960     // `|args| expr`
2961     pub fn parse_lambda_expr(&mut self, lo: BytePos,
2962                              capture_clause: CaptureClause,
2963                              attrs: ThinAttributes)
2964                              -> PResult<'a, P<Expr>>
2965     {
2966         let decl = try!(self.parse_fn_block_decl());
2967         let body = match decl.output {
2968             DefaultReturn(_) => {
2969                 // If no explicit return type is given, parse any
2970                 // expr and wrap it up in a dummy block:
2971                 let body_expr = try!(self.parse_expr());
2972                 P(ast::Block {
2973                     id: ast::DUMMY_NODE_ID,
2974                     stmts: vec![],
2975                     span: body_expr.span,
2976                     expr: Some(body_expr),
2977                     rules: DefaultBlock,
2978                 })
2979             }
2980             _ => {
2981                 // If an explicit return type is given, require a
2982                 // block to appear (RFC 968).
2983                 try!(self.parse_block())
2984             }
2985         };
2986
2987         Ok(self.mk_expr(
2988             lo,
2989             body.span.hi,
2990             ExprClosure(capture_clause, decl, body), attrs))
2991     }
2992
2993     // `else` token already eaten
2994     pub fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
2995         if try!(self.eat_keyword(keywords::If) ){
2996             return self.parse_if_expr(None);
2997         } else {
2998             let blk = try!(self.parse_block());
2999             return Ok(self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk), None));
3000         }
3001     }
3002
3003     /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3004     pub fn parse_for_expr(&mut self, opt_ident: Option<ast::Ident>,
3005                           span_lo: BytePos,
3006                           attrs: ThinAttributes) -> PResult<'a, P<Expr>> {
3007         // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3008
3009         let pat = try!(self.parse_pat());
3010         try!(self.expect_keyword(keywords::In));
3011         let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3012         let (iattrs, loop_block) = try!(self.parse_inner_attrs_and_block());
3013         let attrs = attrs.append(iattrs.into_thin_attrs());
3014
3015         let hi = self.last_span.hi;
3016
3017         Ok(self.mk_expr(span_lo, hi,
3018                         ExprForLoop(pat, expr, loop_block, opt_ident),
3019                         attrs))
3020     }
3021
3022     /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3023     pub fn parse_while_expr(&mut self, opt_ident: Option<ast::Ident>,
3024                             span_lo: BytePos,
3025                             attrs: ThinAttributes) -> PResult<'a, P<Expr>> {
3026         if self.token.is_keyword(keywords::Let) {
3027             return self.parse_while_let_expr(opt_ident, span_lo, attrs);
3028         }
3029         let cond = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3030         let (iattrs, body) = try!(self.parse_inner_attrs_and_block());
3031         let attrs = attrs.append(iattrs.into_thin_attrs());
3032         let hi = body.span.hi;
3033         return Ok(self.mk_expr(span_lo, hi, ExprWhile(cond, body, opt_ident),
3034                                attrs));
3035     }
3036
3037     /// Parse a 'while let' expression ('while' token already eaten)
3038     pub fn parse_while_let_expr(&mut self, opt_ident: Option<ast::Ident>,
3039                                 span_lo: BytePos,
3040                                 attrs: ThinAttributes) -> PResult<'a, P<Expr>> {
3041         try!(self.expect_keyword(keywords::Let));
3042         let pat = try!(self.parse_pat());
3043         try!(self.expect(&token::Eq));
3044         let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3045         let (iattrs, body) = try!(self.parse_inner_attrs_and_block());
3046         let attrs = attrs.append(iattrs.into_thin_attrs());
3047         let hi = body.span.hi;
3048         return Ok(self.mk_expr(span_lo, hi, ExprWhileLet(pat, expr, body, opt_ident), attrs));
3049     }
3050
3051     // parse `loop {...}`, `loop` token already eaten
3052     pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::Ident>,
3053                            span_lo: BytePos,
3054                            attrs: ThinAttributes) -> PResult<'a, P<Expr>> {
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         Ok(self.mk_expr(span_lo, hi, ExprLoop(body, opt_ident), attrs))
3059     }
3060
3061     // `match` token already eaten
3062     fn parse_match_expr(&mut self, attrs: ThinAttributes) -> PResult<'a, P<Expr>> {
3063         let match_span = self.last_span;
3064         let lo = self.last_span.lo;
3065         let discriminant = try!(self.parse_expr_res(
3066             Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3067         if let Err(mut e) = self.commit_expr_expecting(&*discriminant,
3068                                                        token::OpenDelim(token::Brace)) {
3069             if self.token == token::Token::Semi {
3070                 e.span_note(match_span, "did you mean to remove this `match` keyword?");
3071             }
3072             return Err(e)
3073         }
3074         let attrs = attrs.append(
3075             try!(self.parse_inner_attributes()).into_thin_attrs());
3076         let mut arms: Vec<Arm> = Vec::new();
3077         while self.token != token::CloseDelim(token::Brace) {
3078             arms.push(try!(self.parse_arm()));
3079         }
3080         let hi = self.span.hi;
3081         try!(self.bump());
3082         return Ok(self.mk_expr(lo, hi, ExprMatch(discriminant, arms), attrs));
3083     }
3084
3085     pub fn parse_arm(&mut self) -> PResult<'a, Arm> {
3086         maybe_whole!(no_clone self, NtArm);
3087
3088         let attrs = try!(self.parse_outer_attributes());
3089         let pats = try!(self.parse_pats());
3090         let mut guard = None;
3091         if try!(self.eat_keyword(keywords::If) ){
3092             guard = Some(try!(self.parse_expr()));
3093         }
3094         try!(self.expect(&token::FatArrow));
3095         let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_STMT_EXPR, None));
3096
3097         let require_comma =
3098             !classify::expr_is_simple_block(&*expr)
3099             && self.token != token::CloseDelim(token::Brace);
3100
3101         if require_comma {
3102             try!(self.commit_expr(&*expr, &[token::Comma], &[token::CloseDelim(token::Brace)]));
3103         } else {
3104             try!(self.eat(&token::Comma));
3105         }
3106
3107         Ok(ast::Arm {
3108             attrs: attrs,
3109             pats: pats,
3110             guard: guard,
3111             body: expr,
3112         })
3113     }
3114
3115     /// Parse an expression
3116     pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3117         self.parse_expr_res(Restrictions::empty(), None)
3118     }
3119
3120     /// Evaluate the closure with restrictions in place.
3121     ///
3122     /// After the closure is evaluated, restrictions are reset.
3123     pub fn with_res<F>(&mut self, r: Restrictions, f: F) -> PResult<'a, P<Expr>>
3124         where F: FnOnce(&mut Self) -> PResult<'a,  P<Expr>>
3125     {
3126         let old = self.restrictions;
3127         self.restrictions = r;
3128         let r = f(self);
3129         self.restrictions = old;
3130         return r;
3131
3132     }
3133
3134     /// Parse an expression, subject to the given restrictions
3135     pub fn parse_expr_res(&mut self, r: Restrictions,
3136                           already_parsed_attrs: Option<ThinAttributes>)
3137                           -> PResult<'a, P<Expr>> {
3138         self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3139     }
3140
3141     /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3142     fn parse_initializer(&mut self) -> PResult<'a, Option<P<Expr>>> {
3143         if self.check(&token::Eq) {
3144             try!(self.bump());
3145             Ok(Some(try!(self.parse_expr())))
3146         } else {
3147             Ok(None)
3148         }
3149     }
3150
3151     /// Parse patterns, separated by '|' s
3152     fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3153         let mut pats = Vec::new();
3154         loop {
3155             pats.push(try!(self.parse_pat()));
3156             if self.check(&token::BinOp(token::Or)) { try!(self.bump());}
3157             else { return Ok(pats); }
3158         };
3159     }
3160
3161     fn parse_pat_tuple_elements(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3162         let mut fields = vec![];
3163         if !self.check(&token::CloseDelim(token::Paren)) {
3164             fields.push(try!(self.parse_pat()));
3165             if self.look_ahead(1, |t| *t != token::CloseDelim(token::Paren)) {
3166                 while try!(self.eat(&token::Comma)) &&
3167                       !self.check(&token::CloseDelim(token::Paren)) {
3168                     fields.push(try!(self.parse_pat()));
3169                 }
3170             }
3171             if fields.len() == 1 {
3172                 try!(self.expect(&token::Comma));
3173             }
3174         }
3175         Ok(fields)
3176     }
3177
3178     fn parse_pat_vec_elements(
3179         &mut self,
3180     ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3181         let mut before = Vec::new();
3182         let mut slice = None;
3183         let mut after = Vec::new();
3184         let mut first = true;
3185         let mut before_slice = true;
3186
3187         while self.token != token::CloseDelim(token::Bracket) {
3188             if first {
3189                 first = false;
3190             } else {
3191                 try!(self.expect(&token::Comma));
3192
3193                 if self.token == token::CloseDelim(token::Bracket)
3194                         && (before_slice || !after.is_empty()) {
3195                     break
3196                 }
3197             }
3198
3199             if before_slice {
3200                 if self.check(&token::DotDot) {
3201                     try!(self.bump());
3202
3203                     if self.check(&token::Comma) ||
3204                             self.check(&token::CloseDelim(token::Bracket)) {
3205                         slice = Some(P(ast::Pat {
3206                             id: ast::DUMMY_NODE_ID,
3207                             node: PatWild,
3208                             span: self.span,
3209                         }));
3210                         before_slice = false;
3211                     }
3212                     continue
3213                 }
3214             }
3215
3216             let subpat = try!(self.parse_pat());
3217             if before_slice && self.check(&token::DotDot) {
3218                 try!(self.bump());
3219                 slice = Some(subpat);
3220                 before_slice = false;
3221             } else if before_slice {
3222                 before.push(subpat);
3223             } else {
3224                 after.push(subpat);
3225             }
3226         }
3227
3228         Ok((before, slice, after))
3229     }
3230
3231     /// Parse the fields of a struct-like pattern
3232     fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<codemap::Spanned<ast::FieldPat>> , bool)> {
3233         let mut fields = Vec::new();
3234         let mut etc = false;
3235         let mut first = true;
3236         while self.token != token::CloseDelim(token::Brace) {
3237             if first {
3238                 first = false;
3239             } else {
3240                 try!(self.expect(&token::Comma));
3241                 // accept trailing commas
3242                 if self.check(&token::CloseDelim(token::Brace)) { break }
3243             }
3244
3245             let lo = self.span.lo;
3246             let hi;
3247
3248             if self.check(&token::DotDot) {
3249                 try!(self.bump());
3250                 if self.token != token::CloseDelim(token::Brace) {
3251                     let token_str = self.this_token_to_string();
3252                     return Err(self.fatal(&format!("expected `{}`, found `{}`", "}",
3253                                        token_str)))
3254                 }
3255                 etc = true;
3256                 break;
3257             }
3258
3259             // Check if a colon exists one ahead. This means we're parsing a fieldname.
3260             let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3261                 // Parsing a pattern of the form "fieldname: pat"
3262                 let fieldname = try!(self.parse_ident());
3263                 try!(self.bump());
3264                 let pat = try!(self.parse_pat());
3265                 hi = pat.span.hi;
3266                 (pat, fieldname, false)
3267             } else {
3268                 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3269                 let is_box = try!(self.eat_keyword(keywords::Box));
3270                 let boxed_span_lo = self.span.lo;
3271                 let is_ref = try!(self.eat_keyword(keywords::Ref));
3272                 let is_mut = try!(self.eat_keyword(keywords::Mut));
3273                 let fieldname = try!(self.parse_ident());
3274                 hi = self.last_span.hi;
3275
3276                 let bind_type = match (is_ref, is_mut) {
3277                     (true, true) => BindingMode::ByRef(MutMutable),
3278                     (true, false) => BindingMode::ByRef(MutImmutable),
3279                     (false, true) => BindingMode::ByValue(MutMutable),
3280                     (false, false) => BindingMode::ByValue(MutImmutable),
3281                 };
3282                 let fieldpath = codemap::Spanned{span:self.last_span, node:fieldname};
3283                 let fieldpat = P(ast::Pat{
3284                     id: ast::DUMMY_NODE_ID,
3285                     node: PatIdent(bind_type, fieldpath, None),
3286                     span: mk_sp(boxed_span_lo, hi),
3287                 });
3288
3289                 let subpat = if is_box {
3290                     P(ast::Pat{
3291                         id: ast::DUMMY_NODE_ID,
3292                         node: PatBox(fieldpat),
3293                         span: mk_sp(lo, hi),
3294                     })
3295                 } else {
3296                     fieldpat
3297                 };
3298                 (subpat, fieldname, true)
3299             };
3300
3301             fields.push(codemap::Spanned { span: mk_sp(lo, hi),
3302                                            node: ast::FieldPat { ident: fieldname,
3303                                                                  pat: subpat,
3304                                                                  is_shorthand: is_shorthand }});
3305         }
3306         return Ok((fields, etc));
3307     }
3308
3309     fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
3310         if self.is_path_start() {
3311             let lo = self.span.lo;
3312             let (qself, path) = if try!(self.eat_lt()) {
3313                 // Parse a qualified path
3314                 let (qself, path) =
3315                     try!(self.parse_qualified_path(NoTypesAllowed));
3316                 (Some(qself), path)
3317             } else {
3318                 // Parse an unqualified path
3319                 (None, try!(self.parse_path(LifetimeAndTypesWithColons)))
3320             };
3321             let hi = self.last_span.hi;
3322             Ok(self.mk_expr(lo, hi, ExprPath(qself, path), None))
3323         } else {
3324             self.parse_pat_literal_maybe_minus()
3325         }
3326     }
3327
3328     fn is_path_start(&self) -> bool {
3329         (self.token == token::Lt || self.token == token::ModSep
3330             || self.token.is_ident() || self.token.is_path())
3331             && !self.token.is_keyword(keywords::True) && !self.token.is_keyword(keywords::False)
3332     }
3333
3334     /// Parse a pattern.
3335     pub fn parse_pat(&mut self) -> PResult<'a, P<Pat>> {
3336         maybe_whole!(self, NtPat);
3337
3338         let lo = self.span.lo;
3339         let pat;
3340         match self.token {
3341           token::Underscore => {
3342             // Parse _
3343             try!(self.bump());
3344             pat = PatWild;
3345           }
3346           token::BinOp(token::And) | token::AndAnd => {
3347             // Parse &pat / &mut pat
3348             try!(self.expect_and());
3349             let mutbl = try!(self.parse_mutability());
3350             if let token::Lifetime(ident) = self.token {
3351                 return Err(self.fatal(&format!("unexpected lifetime `{}` in pattern", ident)));
3352             }
3353
3354             let subpat = try!(self.parse_pat());
3355             pat = PatRegion(subpat, mutbl);
3356           }
3357           token::OpenDelim(token::Paren) => {
3358             // Parse (pat,pat,pat,...) as tuple pattern
3359             try!(self.bump());
3360             let fields = try!(self.parse_pat_tuple_elements());
3361             try!(self.expect(&token::CloseDelim(token::Paren)));
3362             pat = PatTup(fields);
3363           }
3364           token::OpenDelim(token::Bracket) => {
3365             // Parse [pat,pat,...] as slice pattern
3366             try!(self.bump());
3367             let (before, slice, after) = try!(self.parse_pat_vec_elements());
3368             try!(self.expect(&token::CloseDelim(token::Bracket)));
3369             pat = PatVec(before, slice, after);
3370           }
3371           _ => {
3372             // At this point, token != _, &, &&, (, [
3373             if try!(self.eat_keyword(keywords::Mut)) {
3374                 // Parse mut ident @ pat
3375                 pat = try!(self.parse_pat_ident(BindingMode::ByValue(MutMutable)));
3376             } else if try!(self.eat_keyword(keywords::Ref)) {
3377                 // Parse ref ident @ pat / ref mut ident @ pat
3378                 let mutbl = try!(self.parse_mutability());
3379                 pat = try!(self.parse_pat_ident(BindingMode::ByRef(mutbl)));
3380             } else if try!(self.eat_keyword(keywords::Box)) {
3381                 // Parse box pat
3382                 let subpat = try!(self.parse_pat());
3383                 pat = PatBox(subpat);
3384             } else if self.is_path_start() {
3385                 // Parse pattern starting with a path
3386                 if self.token.is_plain_ident() && self.look_ahead(1, |t| *t != token::DotDotDot &&
3387                         *t != token::OpenDelim(token::Brace) &&
3388                         *t != token::OpenDelim(token::Paren) &&
3389                         // Contrary to its definition, a plain ident can be followed by :: in macros
3390                         *t != token::ModSep) {
3391                     // Plain idents have some extra abilities here compared to general paths
3392                     if self.look_ahead(1, |t| *t == token::Not) {
3393                         // Parse macro invocation
3394                         let ident = try!(self.parse_ident());
3395                         let ident_span = self.last_span;
3396                         let path = ident_to_path(ident_span, ident);
3397                         try!(self.bump());
3398                         let delim = try!(self.expect_open_delim());
3399                         let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
3400                                 seq_sep_none(), |p| p.parse_token_tree()));
3401                         let mac = Mac_ { path: path, tts: tts, ctxt: EMPTY_CTXT };
3402                         pat = PatMac(codemap::Spanned {node: mac,
3403                                                        span: mk_sp(lo, self.last_span.hi)});
3404                     } else {
3405                         // Parse ident @ pat
3406                         // This can give false positives and parse nullary enums,
3407                         // they are dealt with later in resolve
3408                         pat = try!(self.parse_pat_ident(BindingMode::ByValue(MutImmutable)));
3409                     }
3410                 } else {
3411                     let (qself, path) = if try!(self.eat_lt()) {
3412                         // Parse a qualified path
3413                         let (qself, path) =
3414                             try!(self.parse_qualified_path(NoTypesAllowed));
3415                         (Some(qself), path)
3416                     } else {
3417                         // Parse an unqualified path
3418                         (None, try!(self.parse_path(LifetimeAndTypesWithColons)))
3419                     };
3420                     match self.token {
3421                       token::DotDotDot => {
3422                         // Parse range
3423                         let hi = self.last_span.hi;
3424                         let begin = self.mk_expr(lo, hi, ExprPath(qself, path), None);
3425                         try!(self.bump());
3426                         let end = try!(self.parse_pat_range_end());
3427                         pat = PatRange(begin, end);
3428                       }
3429                       token::OpenDelim(token::Brace) => {
3430                          if qself.is_some() {
3431                             return Err(self.fatal("unexpected `{` after qualified path"));
3432                         }
3433                         // Parse struct pattern
3434                         try!(self.bump());
3435                         let (fields, etc) = try!(self.parse_pat_fields());
3436                         try!(self.bump());
3437                         pat = PatStruct(path, fields, etc);
3438                       }
3439                       token::OpenDelim(token::Paren) => {
3440                         if qself.is_some() {
3441                             return Err(self.fatal("unexpected `(` after qualified path"));
3442                         }
3443                         // Parse tuple struct or enum pattern
3444                         if self.look_ahead(1, |t| *t == token::DotDot) {
3445                             // This is a "top constructor only" pat
3446                             try!(self.bump());
3447                             try!(self.bump());
3448                             try!(self.expect(&token::CloseDelim(token::Paren)));
3449                             pat = PatEnum(path, None);
3450                         } else {
3451                             let args = try!(self.parse_enum_variant_seq(
3452                                     &token::OpenDelim(token::Paren),
3453                                     &token::CloseDelim(token::Paren),
3454                                     seq_sep_trailing_allowed(token::Comma),
3455                                     |p| p.parse_pat()));
3456                             pat = PatEnum(path, Some(args));
3457                         }
3458                       }
3459                       _ => {
3460                         pat = match qself {
3461                             // Parse qualified path
3462                             Some(qself) => PatQPath(qself, path),
3463                             // Parse nullary enum
3464                             None => PatEnum(path, Some(vec![]))
3465                         };
3466                       }
3467                     }
3468                 }
3469             } else {
3470                 // Try to parse everything else as literal with optional minus
3471                 let begin = try!(self.parse_pat_literal_maybe_minus());
3472                 if try!(self.eat(&token::DotDotDot)) {
3473                     let end = try!(self.parse_pat_range_end());
3474                     pat = PatRange(begin, end);
3475                 } else {
3476                     pat = PatLit(begin);
3477                 }
3478             }
3479           }
3480         }
3481
3482         let hi = self.last_span.hi;
3483         Ok(P(ast::Pat {
3484             id: ast::DUMMY_NODE_ID,
3485             node: pat,
3486             span: mk_sp(lo, hi),
3487         }))
3488     }
3489
3490     /// Parse ident or ident @ pat
3491     /// used by the copy foo and ref foo patterns to give a good
3492     /// error message when parsing mistakes like ref foo(a,b)
3493     fn parse_pat_ident(&mut self,
3494                        binding_mode: ast::BindingMode)
3495                        -> PResult<'a, ast::Pat_> {
3496         if !self.token.is_plain_ident() {
3497             let span = self.span;
3498             let tok_str = self.this_token_to_string();
3499             return Err(self.span_fatal(span,
3500                             &format!("expected identifier, found `{}`", tok_str)))
3501         }
3502         let ident = try!(self.parse_ident());
3503         let last_span = self.last_span;
3504         let name = codemap::Spanned{span: last_span, node: ident};
3505         let sub = if try!(self.eat(&token::At) ){
3506             Some(try!(self.parse_pat()))
3507         } else {
3508             None
3509         };
3510
3511         // just to be friendly, if they write something like
3512         //   ref Some(i)
3513         // we end up here with ( as the current token.  This shortly
3514         // leads to a parse error.  Note that if there is no explicit
3515         // binding mode then we do not end up here, because the lookahead
3516         // will direct us over to parse_enum_variant()
3517         if self.token == token::OpenDelim(token::Paren) {
3518             let last_span = self.last_span;
3519             return Err(self.span_fatal(
3520                 last_span,
3521                 "expected identifier, found enum pattern"))
3522         }
3523
3524         Ok(PatIdent(binding_mode, name, sub))
3525     }
3526
3527     /// Parse a local variable declaration
3528     fn parse_local(&mut self, attrs: ThinAttributes) -> PResult<'a, P<Local>> {
3529         let lo = self.span.lo;
3530         let pat = try!(self.parse_pat());
3531
3532         let mut ty = None;
3533         if try!(self.eat(&token::Colon) ){
3534             ty = Some(try!(self.parse_ty_sum()));
3535         }
3536         let init = try!(self.parse_initializer());
3537         Ok(P(ast::Local {
3538             ty: ty,
3539             pat: pat,
3540             init: init,
3541             id: ast::DUMMY_NODE_ID,
3542             span: mk_sp(lo, self.last_span.hi),
3543             attrs: attrs,
3544         }))
3545     }
3546
3547     /// Parse a "let" stmt
3548     fn parse_let(&mut self, attrs: ThinAttributes) -> PResult<'a, P<Decl>> {
3549         let lo = self.span.lo;
3550         let local = try!(self.parse_local(attrs));
3551         Ok(P(spanned(lo, self.last_span.hi, DeclLocal(local))))
3552     }
3553
3554     /// Parse a structure field
3555     fn parse_name_and_ty(&mut self, pr: Visibility,
3556                          attrs: Vec<Attribute> ) -> PResult<'a, StructField> {
3557         let lo = match pr {
3558             Inherited => self.span.lo,
3559             Public => self.last_span.lo,
3560         };
3561         if !self.token.is_plain_ident() {
3562             return Err(self.fatal("expected ident"));
3563         }
3564         let name = try!(self.parse_ident());
3565         try!(self.expect(&token::Colon));
3566         let ty = try!(self.parse_ty_sum());
3567         Ok(spanned(lo, self.last_span.hi, ast::StructField_ {
3568             kind: NamedField(name, pr),
3569             id: ast::DUMMY_NODE_ID,
3570             ty: ty,
3571             attrs: attrs,
3572         }))
3573     }
3574
3575     /// Emit an expected item after attributes error.
3576     fn expected_item_err(&self, attrs: &[Attribute]) {
3577         let message = match attrs.last() {
3578             Some(&Attribute { node: ast::Attribute_ { is_sugared_doc: true, .. }, .. }) => {
3579                 "expected item after doc comment"
3580             }
3581             _ => "expected item after attributes",
3582         };
3583
3584         self.span_err(self.last_span, message);
3585     }
3586
3587     /// Parse a statement. may include decl.
3588     pub fn parse_stmt(&mut self) -> PResult<'a, Option<P<Stmt>>> {
3589         Ok(try!(self.parse_stmt_()).map(P))
3590     }
3591
3592     fn parse_stmt_(&mut self) -> PResult<'a, Option<Stmt>> {
3593         maybe_whole!(Some deref self, NtStmt);
3594
3595         let attrs = try!(self.parse_outer_attributes());
3596         let lo = self.span.lo;
3597
3598         Ok(Some(if self.check_keyword(keywords::Let) {
3599             try!(self.expect_keyword(keywords::Let));
3600             let decl = try!(self.parse_let(attrs.into_thin_attrs()));
3601             let hi = decl.span.hi;
3602             let stmt = StmtDecl(decl, ast::DUMMY_NODE_ID);
3603             spanned(lo, hi, stmt)
3604         } else if self.token.is_ident()
3605             && !self.token.is_any_keyword()
3606             && self.look_ahead(1, |t| *t == token::Not) {
3607             // it's a macro invocation:
3608
3609             // Potential trouble: if we allow macros with paths instead of
3610             // idents, we'd need to look ahead past the whole path here...
3611             let pth = try!(self.parse_path(NoTypesAllowed));
3612             try!(self.bump());
3613
3614             let id = match self.token {
3615                 token::OpenDelim(_) => token::special_idents::invalid, // no special identifier
3616                 _ => try!(self.parse_ident()),
3617             };
3618
3619             // check that we're pointing at delimiters (need to check
3620             // again after the `if`, because of `parse_ident`
3621             // consuming more tokens).
3622             let delim = match self.token {
3623                 token::OpenDelim(delim) => delim,
3624                 _ => {
3625                     // we only expect an ident if we didn't parse one
3626                     // above.
3627                     let ident_str = if id.name == token::special_idents::invalid.name {
3628                         "identifier, "
3629                     } else {
3630                         ""
3631                     };
3632                     let tok_str = self.this_token_to_string();
3633                     return Err(self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
3634                                        ident_str,
3635                                        tok_str)))
3636                 },
3637             };
3638
3639             let tts = try!(self.parse_unspanned_seq(
3640                 &token::OpenDelim(delim),
3641                 &token::CloseDelim(delim),
3642                 seq_sep_none(),
3643                 |p| p.parse_token_tree()
3644             ));
3645             let hi = self.last_span.hi;
3646
3647             let style = if delim == token::Brace {
3648                 MacStmtWithBraces
3649             } else {
3650                 MacStmtWithoutBraces
3651             };
3652
3653             if id.name == token::special_idents::invalid.name {
3654                 let stmt = StmtMac(P(spanned(lo,
3655                                              hi,
3656                                              Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT })),
3657                                    style,
3658                                    attrs.into_thin_attrs());
3659                 spanned(lo, hi, stmt)
3660             } else {
3661                 // if it has a special ident, it's definitely an item
3662                 //
3663                 // Require a semicolon or braces.
3664                 if style != MacStmtWithBraces {
3665                     if !try!(self.eat(&token::Semi) ){
3666                         let last_span = self.last_span;
3667                         self.span_err(last_span,
3668                                       "macros that expand to items must \
3669                                        either be surrounded with braces or \
3670                                        followed by a semicolon");
3671                     }
3672                 }
3673                 spanned(lo, hi, StmtDecl(
3674                     P(spanned(lo, hi, DeclItem(
3675                         self.mk_item(
3676                             lo, hi, id /*id is good here*/,
3677                             ItemMac(spanned(lo, hi,
3678                                             Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT })),
3679                             Inherited, attrs)))),
3680                     ast::DUMMY_NODE_ID))
3681             }
3682         } else {
3683             // FIXME: Bad copy of attrs
3684             match try!(self.parse_item_(attrs.clone(), false, true)) {
3685                 Some(i) => {
3686                     let hi = i.span.hi;
3687                     let decl = P(spanned(lo, hi, DeclItem(i)));
3688                     spanned(lo, hi, StmtDecl(decl, ast::DUMMY_NODE_ID))
3689                 }
3690                 None => {
3691                     let unused_attrs = |attrs: &[_], s: &mut Self| {
3692                         if attrs.len() > 0 {
3693                             s.span_err(s.span,
3694                                 "expected statement after outer attribute");
3695                         }
3696                     };
3697
3698                     // Do not attempt to parse an expression if we're done here.
3699                     if self.token == token::Semi {
3700                         unused_attrs(&attrs, self);
3701                         try!(self.bump());
3702                         return Ok(None);
3703                     }
3704
3705                     if self.token == token::CloseDelim(token::Brace) {
3706                         unused_attrs(&attrs, self);
3707                         return Ok(None);
3708                     }
3709
3710                     // Remainder are line-expr stmts.
3711                     let e = try!(self.parse_expr_res(
3712                         Restrictions::RESTRICTION_STMT_EXPR, Some(attrs.into_thin_attrs())));
3713                     let hi = e.span.hi;
3714                     let stmt = StmtExpr(e, ast::DUMMY_NODE_ID);
3715                     spanned(lo, hi, stmt)
3716                 }
3717             }
3718         }))
3719     }
3720
3721     /// Is this expression a successfully-parsed statement?
3722     fn expr_is_complete(&mut self, e: &Expr) -> bool {
3723         self.restrictions.contains(Restrictions::RESTRICTION_STMT_EXPR) &&
3724             !classify::expr_requires_semi_to_be_stmt(e)
3725     }
3726
3727     /// Parse a block. No inner attrs are allowed.
3728     pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
3729         maybe_whole!(no_clone self, NtBlock);
3730
3731         let lo = self.span.lo;
3732
3733         if !try!(self.eat(&token::OpenDelim(token::Brace)) ){
3734             let sp = self.span;
3735             let tok = self.this_token_to_string();
3736             return Err(self.span_fatal_help(sp,
3737                                  &format!("expected `{{`, found `{}`", tok),
3738                                  "place this code inside a block"));
3739         }
3740
3741         self.parse_block_tail(lo, DefaultBlock)
3742     }
3743
3744     /// Parse a block. Inner attrs are allowed.
3745     fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
3746         maybe_whole!(pair_empty self, NtBlock);
3747
3748         let lo = self.span.lo;
3749         try!(self.expect(&token::OpenDelim(token::Brace)));
3750         Ok((try!(self.parse_inner_attributes()),
3751          try!(self.parse_block_tail(lo, DefaultBlock))))
3752     }
3753
3754     /// Parse the rest of a block expression or function body
3755     /// Precondition: already parsed the '{'.
3756     fn parse_block_tail(&mut self, lo: BytePos, s: BlockCheckMode) -> PResult<'a, P<Block>> {
3757         let mut stmts = vec![];
3758         let mut expr = None;
3759
3760         while !try!(self.eat(&token::CloseDelim(token::Brace))) {
3761             let Spanned {node, span} = if let Some(s) = try!(self.parse_stmt_()) {
3762                 s
3763             } else {
3764                 // Found only `;` or `}`.
3765                 continue;
3766             };
3767             match node {
3768                 StmtExpr(e, _) => {
3769                     try!(self.handle_expression_like_statement(e, span, &mut stmts, &mut expr));
3770                 }
3771                 StmtMac(mac, MacStmtWithoutBraces, attrs) => {
3772                     // statement macro without braces; might be an
3773                     // expr depending on whether a semicolon follows
3774                     match self.token {
3775                         token::Semi => {
3776                             stmts.push(P(Spanned {
3777                                 node: StmtMac(mac, MacStmtWithSemicolon, attrs),
3778                                 span: mk_sp(span.lo, self.span.hi),
3779                             }));
3780                             try!(self.bump());
3781                         }
3782                         _ => {
3783                             let e = self.mk_mac_expr(span.lo, span.hi,
3784                                                      mac.and_then(|m| m.node),
3785                                                      None);
3786                             let e = try!(self.parse_dot_or_call_expr_with(e, attrs));
3787                             let e = try!(self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e)));
3788                             try!(self.handle_expression_like_statement(
3789                                 e,
3790                                 span,
3791                                 &mut stmts,
3792                                 &mut expr));
3793                         }
3794                     }
3795                 }
3796                 StmtMac(m, style, attrs) => {
3797                     // statement macro; might be an expr
3798                     match self.token {
3799                         token::Semi => {
3800                             stmts.push(P(Spanned {
3801                                 node: StmtMac(m, MacStmtWithSemicolon, attrs),
3802                                 span: mk_sp(span.lo, self.span.hi),
3803                             }));
3804                             try!(self.bump());
3805                         }
3806                         token::CloseDelim(token::Brace) => {
3807                             // if a block ends in `m!(arg)` without
3808                             // a `;`, it must be an expr
3809                             expr = Some(self.mk_mac_expr(span.lo, span.hi,
3810                                                          m.and_then(|x| x.node),
3811                                                          attrs));
3812                         }
3813                         _ => {
3814                             stmts.push(P(Spanned {
3815                                 node: StmtMac(m, style, attrs),
3816                                 span: span
3817                             }));
3818                         }
3819                     }
3820                 }
3821                 _ => { // all other kinds of statements:
3822                     let mut hi = span.hi;
3823                     if classify::stmt_ends_with_semi(&node) {
3824                         try!(self.commit_stmt_expecting(token::Semi));
3825                         hi = self.last_span.hi;
3826                     }
3827
3828                     stmts.push(P(Spanned {
3829                         node: node,
3830                         span: mk_sp(span.lo, hi)
3831                     }));
3832                 }
3833             }
3834         }
3835
3836         Ok(P(ast::Block {
3837             stmts: stmts,
3838             expr: expr,
3839             id: ast::DUMMY_NODE_ID,
3840             rules: s,
3841             span: mk_sp(lo, self.last_span.hi),
3842         }))
3843     }
3844
3845     fn handle_expression_like_statement(
3846             &mut self,
3847             e: P<Expr>,
3848             span: Span,
3849             stmts: &mut Vec<P<Stmt>>,
3850             last_block_expr: &mut Option<P<Expr>>) -> PResult<'a, ()> {
3851         // expression without semicolon
3852         if classify::expr_requires_semi_to_be_stmt(&*e) {
3853             // Just check for errors and recover; do not eat semicolon yet.
3854             try!(self.commit_stmt(&[],
3855                              &[token::Semi, token::CloseDelim(token::Brace)]));
3856         }
3857
3858         match self.token {
3859             token::Semi => {
3860                 try!(self.bump());
3861                 let span_with_semi = Span {
3862                     lo: span.lo,
3863                     hi: self.last_span.hi,
3864                     expn_id: span.expn_id,
3865                 };
3866                 stmts.push(P(Spanned {
3867                     node: StmtSemi(e, ast::DUMMY_NODE_ID),
3868                     span: span_with_semi,
3869                 }));
3870             }
3871             token::CloseDelim(token::Brace) => *last_block_expr = Some(e),
3872             _ => {
3873                 stmts.push(P(Spanned {
3874                     node: StmtExpr(e, ast::DUMMY_NODE_ID),
3875                     span: span
3876                 }));
3877             }
3878         }
3879         Ok(())
3880     }
3881
3882     // Parses a sequence of bounds if a `:` is found,
3883     // otherwise returns empty list.
3884     fn parse_colon_then_ty_param_bounds(&mut self,
3885                                         mode: BoundParsingMode)
3886                                         -> PResult<'a, TyParamBounds>
3887     {
3888         if !try!(self.eat(&token::Colon) ){
3889             Ok(P::empty())
3890         } else {
3891             self.parse_ty_param_bounds(mode)
3892         }
3893     }
3894
3895     // matches bounds    = ( boundseq )?
3896     // where   boundseq  = ( polybound + boundseq ) | polybound
3897     // and     polybound = ( 'for' '<' 'region '>' )? bound
3898     // and     bound     = 'region | trait_ref
3899     fn parse_ty_param_bounds(&mut self,
3900                              mode: BoundParsingMode)
3901                              -> PResult<'a, TyParamBounds>
3902     {
3903         let mut result = vec!();
3904         loop {
3905             let question_span = self.span;
3906             let ate_question = try!(self.eat(&token::Question));
3907             match self.token {
3908                 token::Lifetime(lifetime) => {
3909                     if ate_question {
3910                         self.span_err(question_span,
3911                                       "`?` may only modify trait bounds, not lifetime bounds");
3912                     }
3913                     result.push(RegionTyParamBound(ast::Lifetime {
3914                         id: ast::DUMMY_NODE_ID,
3915                         span: self.span,
3916                         name: lifetime.name
3917                     }));
3918                     try!(self.bump());
3919                 }
3920                 token::ModSep | token::Ident(..) => {
3921                     let poly_trait_ref = try!(self.parse_poly_trait_ref());
3922                     let modifier = if ate_question {
3923                         if mode == BoundParsingMode::Modified {
3924                             TraitBoundModifier::Maybe
3925                         } else {
3926                             self.span_err(question_span,
3927                                           "unexpected `?`");
3928                             TraitBoundModifier::None
3929                         }
3930                     } else {
3931                         TraitBoundModifier::None
3932                     };
3933                     result.push(TraitTyParamBound(poly_trait_ref, modifier))
3934                 }
3935                 _ => break,
3936             }
3937
3938             if !try!(self.eat(&token::BinOp(token::Plus)) ){
3939                 break;
3940             }
3941         }
3942
3943         return Ok(P::from_vec(result));
3944     }
3945
3946     /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
3947     fn parse_ty_param(&mut self) -> PResult<'a, TyParam> {
3948         let span = self.span;
3949         let ident = try!(self.parse_ident());
3950
3951         let bounds = try!(self.parse_colon_then_ty_param_bounds(BoundParsingMode::Modified));
3952
3953         let default = if self.check(&token::Eq) {
3954             try!(self.bump());
3955             Some(try!(self.parse_ty_sum()))
3956         } else {
3957             None
3958         };
3959
3960         Ok(TyParam {
3961             ident: ident,
3962             id: ast::DUMMY_NODE_ID,
3963             bounds: bounds,
3964             default: default,
3965             span: span,
3966         })
3967     }
3968
3969     /// Parse a set of optional generic type parameter declarations. Where
3970     /// clauses are not parsed here, and must be added later via
3971     /// `parse_where_clause()`.
3972     ///
3973     /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
3974     ///                  | ( < lifetimes , typaramseq ( , )? > )
3975     /// where   typaramseq = ( typaram ) | ( typaram , typaramseq )
3976     pub fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
3977         maybe_whole!(self, NtGenerics);
3978
3979         if try!(self.eat(&token::Lt) ){
3980             let lifetime_defs = try!(self.parse_lifetime_defs());
3981             let mut seen_default = false;
3982             let ty_params = try!(self.parse_seq_to_gt(Some(token::Comma), |p| {
3983                 try!(p.forbid_lifetime());
3984                 let ty_param = try!(p.parse_ty_param());
3985                 if ty_param.default.is_some() {
3986                     seen_default = true;
3987                 } else if seen_default {
3988                     let last_span = p.last_span;
3989                     p.span_err(last_span,
3990                                "type parameters with a default must be trailing");
3991                 }
3992                 Ok(ty_param)
3993             }));
3994             Ok(ast::Generics {
3995                 lifetimes: lifetime_defs,
3996                 ty_params: ty_params,
3997                 where_clause: WhereClause {
3998                     id: ast::DUMMY_NODE_ID,
3999                     predicates: Vec::new(),
4000                 }
4001             })
4002         } else {
4003             Ok(ast::Generics::default())
4004         }
4005     }
4006
4007     fn parse_generic_values_after_lt(&mut self) -> PResult<'a, (Vec<ast::Lifetime>,
4008                                                             Vec<P<Ty>>,
4009                                                             Vec<P<TypeBinding>>)> {
4010         let span_lo = self.span.lo;
4011         let lifetimes = try!(self.parse_lifetimes(token::Comma));
4012
4013         let missing_comma = !lifetimes.is_empty() &&
4014                             !self.token.is_like_gt() &&
4015                             self.last_token
4016                                 .as_ref().map_or(true,
4017                                                  |x| &**x != &token::Comma);
4018
4019         if missing_comma {
4020
4021             let msg = format!("expected `,` or `>` after lifetime \
4022                               name, found `{}`",
4023                               self.this_token_to_string());
4024             let mut err = self.diagnostic().struct_span_err(self.span, &msg);
4025
4026             let span_hi = self.span.hi;
4027             let span_hi = if self.parse_ty().is_ok() {
4028                 self.span.hi
4029             } else {
4030                 span_hi
4031             };
4032
4033             let msg = format!("did you mean a single argument type &'a Type, \
4034                               or did you mean the comma-separated arguments \
4035                               'a, Type?");
4036             err.span_note(mk_sp(span_lo, span_hi), &msg);
4037             err.emit();
4038
4039             self.abort_if_errors()
4040         }
4041
4042         // First parse types.
4043         let (types, returned) = try!(self.parse_seq_to_gt_or_return(
4044             Some(token::Comma),
4045             |p| {
4046                 try!(p.forbid_lifetime());
4047                 if p.look_ahead(1, |t| t == &token::Eq) {
4048                     Ok(None)
4049                 } else {
4050                     Ok(Some(try!(p.parse_ty_sum())))
4051                 }
4052             }
4053         ));
4054
4055         // If we found the `>`, don't continue.
4056         if !returned {
4057             return Ok((lifetimes, types.into_vec(), Vec::new()));
4058         }
4059
4060         // Then parse type bindings.
4061         let bindings = try!(self.parse_seq_to_gt(
4062             Some(token::Comma),
4063             |p| {
4064                 try!(p.forbid_lifetime());
4065                 let lo = p.span.lo;
4066                 let ident = try!(p.parse_ident());
4067                 let found_eq = try!(p.eat(&token::Eq));
4068                 if !found_eq {
4069                     let span = p.span;
4070                     p.span_warn(span, "whoops, no =?");
4071                 }
4072                 let ty = try!(p.parse_ty());
4073                 let hi = ty.span.hi;
4074                 let span = mk_sp(lo, hi);
4075                 return Ok(P(TypeBinding{id: ast::DUMMY_NODE_ID,
4076                     ident: ident,
4077                     ty: ty,
4078                     span: span,
4079                 }));
4080             }
4081         ));
4082         Ok((lifetimes, types.into_vec(), bindings.into_vec()))
4083     }
4084
4085     fn forbid_lifetime(&mut self) -> PResult<'a, ()> {
4086         if self.token.is_lifetime() {
4087             let span = self.span;
4088             return Err(self.span_fatal(span, "lifetime parameters must be declared \
4089                                         prior to type parameters"))
4090         }
4091         Ok(())
4092     }
4093
4094     /// Parses an optional `where` clause and places it in `generics`.
4095     ///
4096     /// ```ignore
4097     /// where T : Trait<U, V> + 'b, 'a : 'b
4098     /// ```
4099     pub fn parse_where_clause(&mut self) -> PResult<'a, ast::WhereClause> {
4100         maybe_whole!(self, NtWhereClause);
4101
4102         let mut where_clause = WhereClause {
4103             id: ast::DUMMY_NODE_ID,
4104             predicates: Vec::new(),
4105         };
4106
4107         if !try!(self.eat_keyword(keywords::Where)) {
4108             return Ok(where_clause);
4109         }
4110
4111         let mut parsed_something = false;
4112         loop {
4113             let lo = self.span.lo;
4114             match self.token {
4115                 token::OpenDelim(token::Brace) => {
4116                     break
4117                 }
4118
4119                 token::Lifetime(..) => {
4120                     let bounded_lifetime =
4121                         try!(self.parse_lifetime());
4122
4123                     try!(self.eat(&token::Colon));
4124
4125                     let bounds =
4126                         try!(self.parse_lifetimes(token::BinOp(token::Plus)));
4127
4128                     let hi = self.last_span.hi;
4129                     let span = mk_sp(lo, hi);
4130
4131                     where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
4132                         ast::WhereRegionPredicate {
4133                             span: span,
4134                             lifetime: bounded_lifetime,
4135                             bounds: bounds
4136                         }
4137                     ));
4138
4139                     parsed_something = true;
4140                 }
4141
4142                 _ => {
4143                     let bound_lifetimes = if try!(self.eat_keyword(keywords::For) ){
4144                         // Higher ranked constraint.
4145                         try!(self.expect(&token::Lt));
4146                         let lifetime_defs = try!(self.parse_lifetime_defs());
4147                         try!(self.expect_gt());
4148                         lifetime_defs
4149                     } else {
4150                         vec![]
4151                     };
4152
4153                     let bounded_ty = try!(self.parse_ty());
4154
4155                     if try!(self.eat(&token::Colon) ){
4156                         let bounds = try!(self.parse_ty_param_bounds(BoundParsingMode::Bare));
4157                         let hi = self.last_span.hi;
4158                         let span = mk_sp(lo, hi);
4159
4160                         if bounds.is_empty() {
4161                             self.span_err(span,
4162                                           "each predicate in a `where` clause must have \
4163                                            at least one bound in it");
4164                         }
4165
4166                         where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
4167                                 ast::WhereBoundPredicate {
4168                                     span: span,
4169                                     bound_lifetimes: bound_lifetimes,
4170                                     bounded_ty: bounded_ty,
4171                                     bounds: bounds,
4172                         }));
4173
4174                         parsed_something = true;
4175                     } else if try!(self.eat(&token::Eq) ){
4176                         // let ty = try!(self.parse_ty());
4177                         let hi = self.last_span.hi;
4178                         let span = mk_sp(lo, hi);
4179                         // where_clause.predicates.push(
4180                         //     ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
4181                         //         id: ast::DUMMY_NODE_ID,
4182                         //         span: span,
4183                         //         path: panic!("NYI"), //bounded_ty,
4184                         //         ty: ty,
4185                         // }));
4186                         // parsed_something = true;
4187                         // // FIXME(#18433)
4188                         self.span_err(span,
4189                                      "equality constraints are not yet supported \
4190                                      in where clauses (#20041)");
4191                     } else {
4192                         let last_span = self.last_span;
4193                         self.span_err(last_span,
4194                               "unexpected token in `where` clause");
4195                     }
4196                 }
4197             };
4198
4199             if !try!(self.eat(&token::Comma) ){
4200                 break
4201             }
4202         }
4203
4204         if !parsed_something {
4205             let last_span = self.last_span;
4206             self.span_err(last_span,
4207                           "a `where` clause must have at least one predicate \
4208                            in it");
4209         }
4210
4211         Ok(where_clause)
4212     }
4213
4214     fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
4215                      -> PResult<'a, (Vec<Arg> , bool)> {
4216         let sp = self.span;
4217         let mut args: Vec<Option<Arg>> =
4218             try!(self.parse_unspanned_seq(
4219                 &token::OpenDelim(token::Paren),
4220                 &token::CloseDelim(token::Paren),
4221                 seq_sep_trailing_allowed(token::Comma),
4222                 |p| {
4223                     if p.token == token::DotDotDot {
4224                         try!(p.bump());
4225                         if allow_variadic {
4226                             if p.token != token::CloseDelim(token::Paren) {
4227                                 let span = p.span;
4228                                 return Err(p.span_fatal(span,
4229                                     "`...` must be last in argument list for variadic function"))
4230                             }
4231                         } else {
4232                             let span = p.span;
4233                             return Err(p.span_fatal(span,
4234                                          "only foreign functions are allowed to be variadic"))
4235                         }
4236                         Ok(None)
4237                     } else {
4238                         Ok(Some(try!(p.parse_arg_general(named_args))))
4239                     }
4240                 }
4241             ));
4242
4243         let variadic = match args.pop() {
4244             Some(None) => true,
4245             Some(x) => {
4246                 // Need to put back that last arg
4247                 args.push(x);
4248                 false
4249             }
4250             None => false
4251         };
4252
4253         if variadic && args.is_empty() {
4254             self.span_err(sp,
4255                           "variadic function must be declared with at least one named argument");
4256         }
4257
4258         let args = args.into_iter().map(|x| x.unwrap()).collect();
4259
4260         Ok((args, variadic))
4261     }
4262
4263     /// Parse the argument list and result type of a function declaration
4264     pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> {
4265
4266         let (args, variadic) = try!(self.parse_fn_args(true, allow_variadic));
4267         let ret_ty = try!(self.parse_ret_ty());
4268
4269         Ok(P(FnDecl {
4270             inputs: args,
4271             output: ret_ty,
4272             variadic: variadic
4273         }))
4274     }
4275
4276     fn is_self_ident(&mut self) -> bool {
4277         match self.token {
4278           token::Ident(id, token::Plain) => id.name == special_idents::self_.name,
4279           _ => false
4280         }
4281     }
4282
4283     fn expect_self_ident(&mut self) -> PResult<'a, ast::Ident> {
4284         match self.token {
4285             token::Ident(id, token::Plain) if id.name == special_idents::self_.name => {
4286                 try!(self.bump());
4287                 Ok(id)
4288             },
4289             _ => {
4290                 let token_str = self.this_token_to_string();
4291                 return Err(self.fatal(&format!("expected `self`, found `{}`",
4292                                    token_str)))
4293             }
4294         }
4295     }
4296
4297     fn is_self_type_ident(&mut self) -> bool {
4298         match self.token {
4299           token::Ident(id, token::Plain) => id.name == special_idents::type_self.name,
4300           _ => false
4301         }
4302     }
4303
4304     fn expect_self_type_ident(&mut self) -> PResult<'a, ast::Ident> {
4305         match self.token {
4306             token::Ident(id, token::Plain) if id.name == special_idents::type_self.name => {
4307                 try!(self.bump());
4308                 Ok(id)
4309             },
4310             _ => {
4311                 let token_str = self.this_token_to_string();
4312                 Err(self.fatal(&format!("expected `Self`, found `{}`",
4313                                    token_str)))
4314             }
4315         }
4316     }
4317
4318     /// Parse the argument list and result type of a function
4319     /// that may have a self type.
4320     fn parse_fn_decl_with_self<F>(&mut self,
4321                                   parse_arg_fn: F) -> PResult<'a, (ExplicitSelf, P<FnDecl>)> where
4322         F: FnMut(&mut Parser<'a>) -> PResult<'a,  Arg>,
4323     {
4324         fn maybe_parse_borrowed_explicit_self<'b>(this: &mut Parser<'b>)
4325                                                   -> PResult<'b,  ast::ExplicitSelf_> {
4326             // The following things are possible to see here:
4327             //
4328             //     fn(&mut self)
4329             //     fn(&mut self)
4330             //     fn(&'lt self)
4331             //     fn(&'lt mut self)
4332             //
4333             // We already know that the current token is `&`.
4334
4335             if this.look_ahead(1, |t| t.is_keyword(keywords::SelfValue)) {
4336                 try!(this.bump());
4337                 Ok(SelfRegion(None, MutImmutable, try!(this.expect_self_ident())))
4338             } else if this.look_ahead(1, |t| t.is_mutability()) &&
4339                       this.look_ahead(2, |t| t.is_keyword(keywords::SelfValue)) {
4340                 try!(this.bump());
4341                 let mutability = try!(this.parse_mutability());
4342                 Ok(SelfRegion(None, mutability, try!(this.expect_self_ident())))
4343             } else if this.look_ahead(1, |t| t.is_lifetime()) &&
4344                       this.look_ahead(2, |t| t.is_keyword(keywords::SelfValue)) {
4345                 try!(this.bump());
4346                 let lifetime = try!(this.parse_lifetime());
4347                 Ok(SelfRegion(Some(lifetime), MutImmutable, try!(this.expect_self_ident())))
4348             } else if this.look_ahead(1, |t| t.is_lifetime()) &&
4349                       this.look_ahead(2, |t| t.is_mutability()) &&
4350                       this.look_ahead(3, |t| t.is_keyword(keywords::SelfValue)) {
4351                 try!(this.bump());
4352                 let lifetime = try!(this.parse_lifetime());
4353                 let mutability = try!(this.parse_mutability());
4354                 Ok(SelfRegion(Some(lifetime), mutability, try!(this.expect_self_ident())))
4355             } else {
4356                 Ok(SelfStatic)
4357             }
4358         }
4359
4360         try!(self.expect(&token::OpenDelim(token::Paren)));
4361
4362         // A bit of complexity and lookahead is needed here in order to be
4363         // backwards compatible.
4364         let lo = self.span.lo;
4365         let mut self_ident_lo = self.span.lo;
4366         let mut self_ident_hi = self.span.hi;
4367
4368         let mut mutbl_self = MutImmutable;
4369         let explicit_self = match self.token {
4370             token::BinOp(token::And) => {
4371                 let eself = try!(maybe_parse_borrowed_explicit_self(self));
4372                 self_ident_lo = self.last_span.lo;
4373                 self_ident_hi = self.last_span.hi;
4374                 eself
4375             }
4376             token::BinOp(token::Star) => {
4377                 // Possibly "*self" or "*mut self" -- not supported. Try to avoid
4378                 // emitting cryptic "unexpected token" errors.
4379                 try!(self.bump());
4380                 let _mutability = if self.token.is_mutability() {
4381                     try!(self.parse_mutability())
4382                 } else {
4383                     MutImmutable
4384                 };
4385                 if self.is_self_ident() {
4386                     let span = self.span;
4387                     self.span_err(span, "cannot pass self by raw pointer");
4388                     try!(self.bump());
4389                 }
4390                 // error case, making bogus self ident:
4391                 SelfValue(special_idents::self_)
4392             }
4393             token::Ident(..) => {
4394                 if self.is_self_ident() {
4395                     let self_ident = try!(self.expect_self_ident());
4396
4397                     // Determine whether this is the fully explicit form, `self:
4398                     // TYPE`.
4399                     if try!(self.eat(&token::Colon) ){
4400                         SelfExplicit(try!(self.parse_ty_sum()), self_ident)
4401                     } else {
4402                         SelfValue(self_ident)
4403                     }
4404                 } else if self.token.is_mutability() &&
4405                         self.look_ahead(1, |t| t.is_keyword(keywords::SelfValue)) {
4406                     mutbl_self = try!(self.parse_mutability());
4407                     let self_ident = try!(self.expect_self_ident());
4408
4409                     // Determine whether this is the fully explicit form,
4410                     // `self: TYPE`.
4411                     if try!(self.eat(&token::Colon) ){
4412                         SelfExplicit(try!(self.parse_ty_sum()), self_ident)
4413                     } else {
4414                         SelfValue(self_ident)
4415                     }
4416                 } else {
4417                     SelfStatic
4418                 }
4419             }
4420             _ => SelfStatic,
4421         };
4422
4423         let explicit_self_sp = mk_sp(self_ident_lo, self_ident_hi);
4424
4425         // shared fall-through for the three cases below. borrowing prevents simply
4426         // writing this as a closure
4427         macro_rules! parse_remaining_arguments {
4428             ($self_id:ident) =>
4429             {
4430             // If we parsed a self type, expect a comma before the argument list.
4431             match self.token {
4432                 token::Comma => {
4433                     try!(self.bump());
4434                     let sep = seq_sep_trailing_allowed(token::Comma);
4435                     let mut fn_inputs = try!(self.parse_seq_to_before_end(
4436                         &token::CloseDelim(token::Paren),
4437                         sep,
4438                         parse_arg_fn
4439                     ));
4440                     fn_inputs.insert(0, Arg::new_self(explicit_self_sp, mutbl_self, $self_id));
4441                     fn_inputs
4442                 }
4443                 token::CloseDelim(token::Paren) => {
4444                     vec!(Arg::new_self(explicit_self_sp, mutbl_self, $self_id))
4445                 }
4446                 _ => {
4447                     let token_str = self.this_token_to_string();
4448                     return Err(self.fatal(&format!("expected `,` or `)`, found `{}`",
4449                                        token_str)))
4450                 }
4451             }
4452             }
4453         }
4454
4455         let fn_inputs = match explicit_self {
4456             SelfStatic =>  {
4457                 let sep = seq_sep_trailing_allowed(token::Comma);
4458                 try!(self.parse_seq_to_before_end(&token::CloseDelim(token::Paren),
4459                                                   sep, parse_arg_fn))
4460             }
4461             SelfValue(id) => parse_remaining_arguments!(id),
4462             SelfRegion(_,_,id) => parse_remaining_arguments!(id),
4463             SelfExplicit(_,id) => parse_remaining_arguments!(id),
4464         };
4465
4466
4467         try!(self.expect(&token::CloseDelim(token::Paren)));
4468
4469         let hi = self.span.hi;
4470
4471         let ret_ty = try!(self.parse_ret_ty());
4472
4473         let fn_decl = P(FnDecl {
4474             inputs: fn_inputs,
4475             output: ret_ty,
4476             variadic: false
4477         });
4478
4479         Ok((spanned(lo, hi, explicit_self), fn_decl))
4480     }
4481
4482     // parse the |arg, arg| header on a lambda
4483     fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
4484         let inputs_captures = {
4485             if try!(self.eat(&token::OrOr) ){
4486                 Vec::new()
4487             } else {
4488                 try!(self.expect(&token::BinOp(token::Or)));
4489                 try!(self.parse_obsolete_closure_kind());
4490                 let args = try!(self.parse_seq_to_before_end(
4491                     &token::BinOp(token::Or),
4492                     seq_sep_trailing_allowed(token::Comma),
4493                     |p| p.parse_fn_block_arg()
4494                 ));
4495                 try!(self.bump());
4496                 args
4497             }
4498         };
4499         let output = try!(self.parse_ret_ty());
4500
4501         Ok(P(FnDecl {
4502             inputs: inputs_captures,
4503             output: output,
4504             variadic: false
4505         }))
4506     }
4507
4508     /// Parse the name and optional generic types of a function header.
4509     fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
4510         let id = try!(self.parse_ident());
4511         let generics = try!(self.parse_generics());
4512         Ok((id, generics))
4513     }
4514
4515     fn mk_item(&mut self, lo: BytePos, hi: BytePos, ident: Ident,
4516                node: Item_, vis: Visibility,
4517                attrs: Vec<Attribute>) -> P<Item> {
4518         P(Item {
4519             ident: ident,
4520             attrs: attrs,
4521             id: ast::DUMMY_NODE_ID,
4522             node: node,
4523             vis: vis,
4524             span: mk_sp(lo, hi)
4525         })
4526     }
4527
4528     /// Parse an item-position function declaration.
4529     fn parse_item_fn(&mut self,
4530                      unsafety: Unsafety,
4531                      constness: Constness,
4532                      abi: abi::Abi)
4533                      -> PResult<'a, ItemInfo> {
4534         let (ident, mut generics) = try!(self.parse_fn_header());
4535         let decl = try!(self.parse_fn_decl(false));
4536         generics.where_clause = try!(self.parse_where_clause());
4537         let (inner_attrs, body) = try!(self.parse_inner_attrs_and_block());
4538         Ok((ident, ItemFn(decl, unsafety, constness, abi, generics, body), Some(inner_attrs)))
4539     }
4540
4541     /// true if we are looking at `const ID`, false for things like `const fn` etc
4542     pub fn is_const_item(&mut self) -> bool {
4543         self.token.is_keyword(keywords::Const) &&
4544             !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
4545             !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
4546     }
4547
4548     /// parses all the "front matter" for a `fn` declaration, up to
4549     /// and including the `fn` keyword:
4550     ///
4551     /// - `const fn`
4552     /// - `unsafe fn`
4553     /// - `const unsafe fn`
4554     /// - `extern fn`
4555     /// - etc
4556     pub fn parse_fn_front_matter(&mut self)
4557                                  -> PResult<'a, (ast::Constness, ast::Unsafety, abi::Abi)> {
4558         let is_const_fn = try!(self.eat_keyword(keywords::Const));
4559         let unsafety = try!(self.parse_unsafety());
4560         let (constness, unsafety, abi) = if is_const_fn {
4561             (Constness::Const, unsafety, abi::Rust)
4562         } else {
4563             let abi = if try!(self.eat_keyword(keywords::Extern)) {
4564                 try!(self.parse_opt_abi()).unwrap_or(abi::C)
4565             } else {
4566                 abi::Rust
4567             };
4568             (Constness::NotConst, unsafety, abi)
4569         };
4570         try!(self.expect_keyword(keywords::Fn));
4571         Ok((constness, unsafety, abi))
4572     }
4573
4574     /// Parse an impl item.
4575     pub fn parse_impl_item(&mut self) -> PResult<'a, P<ImplItem>> {
4576         maybe_whole!(no_clone self, NtImplItem);
4577
4578         let mut attrs = try!(self.parse_outer_attributes());
4579         let lo = self.span.lo;
4580         let vis = try!(self.parse_visibility());
4581         let (name, node) = if try!(self.eat_keyword(keywords::Type)) {
4582             let name = try!(self.parse_ident());
4583             try!(self.expect(&token::Eq));
4584             let typ = try!(self.parse_ty_sum());
4585             try!(self.expect(&token::Semi));
4586             (name, ast::ImplItemKind::Type(typ))
4587         } else if self.is_const_item() {
4588             try!(self.expect_keyword(keywords::Const));
4589             let name = try!(self.parse_ident());
4590             try!(self.expect(&token::Colon));
4591             let typ = try!(self.parse_ty_sum());
4592             try!(self.expect(&token::Eq));
4593             let expr = try!(self.parse_expr());
4594             try!(self.commit_expr_expecting(&expr, token::Semi));
4595             (name, ast::ImplItemKind::Const(typ, expr))
4596         } else {
4597             let (name, inner_attrs, node) = try!(self.parse_impl_method(vis));
4598             attrs.extend(inner_attrs);
4599             (name, node)
4600         };
4601
4602         Ok(P(ImplItem {
4603             id: ast::DUMMY_NODE_ID,
4604             span: mk_sp(lo, self.last_span.hi),
4605             ident: name,
4606             vis: vis,
4607             attrs: attrs,
4608             node: node
4609         }))
4610     }
4611
4612     fn complain_if_pub_macro(&mut self, visa: Visibility, span: Span) {
4613         match visa {
4614             Public => {
4615                 let is_macro_rules: bool = match self.token {
4616                     token::Ident(sid, _) => sid.name == intern("macro_rules"),
4617                     _ => false,
4618                 };
4619                 if is_macro_rules {
4620                     self.diagnostic().struct_span_err(span, "can't qualify macro_rules invocation with `pub`")
4621                                      .fileline_help(span, "did you mean #[macro_export]?")
4622                                      .emit();
4623                 } else {
4624                     self.diagnostic().struct_span_err(span, "can't qualify macro invocation with `pub`")
4625                                      .fileline_help(span, "try adjusting the macro to put `pub` \
4626                                                            inside the invocation")
4627                                      .emit();
4628                 }
4629             }
4630             Inherited => (),
4631         }
4632     }
4633
4634     /// Parse a method or a macro invocation in a trait impl.
4635     fn parse_impl_method(&mut self, vis: Visibility)
4636                          -> PResult<'a, (Ident, Vec<ast::Attribute>, ast::ImplItemKind)> {
4637         // code copied from parse_macro_use_or_failure... abstraction!
4638         if !self.token.is_any_keyword()
4639             && self.look_ahead(1, |t| *t == token::Not)
4640             && (self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren))
4641                 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) {
4642             // method macro.
4643
4644             let last_span = self.last_span;
4645             self.complain_if_pub_macro(vis, last_span);
4646
4647             let lo = self.span.lo;
4648             let pth = try!(self.parse_path(NoTypesAllowed));
4649             try!(self.expect(&token::Not));
4650
4651             // eat a matched-delimiter token tree:
4652             let delim = try!(self.expect_open_delim());
4653             let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
4654                                             seq_sep_none(),
4655                                             |p| p.parse_token_tree()));
4656             let m_ = Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT };
4657             let m: ast::Mac = codemap::Spanned { node: m_,
4658                                                 span: mk_sp(lo,
4659                                                             self.last_span.hi) };
4660             if delim != token::Brace {
4661                 try!(self.expect(&token::Semi))
4662             }
4663             Ok((token::special_idents::invalid, vec![], ast::ImplItemKind::Macro(m)))
4664         } else {
4665             let (constness, unsafety, abi) = try!(self.parse_fn_front_matter());
4666             let ident = try!(self.parse_ident());
4667             let mut generics = try!(self.parse_generics());
4668             let (explicit_self, decl) = try!(self.parse_fn_decl_with_self(|p| {
4669                     p.parse_arg()
4670                 }));
4671             generics.where_clause = try!(self.parse_where_clause());
4672             let (inner_attrs, body) = try!(self.parse_inner_attrs_and_block());
4673             Ok((ident, inner_attrs, ast::ImplItemKind::Method(ast::MethodSig {
4674                 generics: generics,
4675                 abi: abi,
4676                 explicit_self: explicit_self,
4677                 unsafety: unsafety,
4678                 constness: constness,
4679                 decl: decl
4680              }, body)))
4681         }
4682     }
4683
4684     /// Parse trait Foo { ... }
4685     fn parse_item_trait(&mut self, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
4686
4687         let ident = try!(self.parse_ident());
4688         let mut tps = try!(self.parse_generics());
4689
4690         // Parse supertrait bounds.
4691         let bounds = try!(self.parse_colon_then_ty_param_bounds(BoundParsingMode::Bare));
4692
4693         tps.where_clause = try!(self.parse_where_clause());
4694
4695         let meths = try!(self.parse_trait_items());
4696         Ok((ident, ItemTrait(unsafety, tps, bounds, meths), None))
4697     }
4698
4699     /// Parses items implementations variants
4700     ///    impl<T> Foo { ... }
4701     ///    impl<T> ToString for &'static T { ... }
4702     ///    impl Send for .. {}
4703     fn parse_item_impl(&mut self, unsafety: ast::Unsafety) -> PResult<'a, ItemInfo> {
4704         let impl_span = self.span;
4705
4706         // First, parse type parameters if necessary.
4707         let mut generics = try!(self.parse_generics());
4708
4709         // Special case: if the next identifier that follows is '(', don't
4710         // allow this to be parsed as a trait.
4711         let could_be_trait = self.token != token::OpenDelim(token::Paren);
4712
4713         let neg_span = self.span;
4714         let polarity = if try!(self.eat(&token::Not) ){
4715             ast::ImplPolarity::Negative
4716         } else {
4717             ast::ImplPolarity::Positive
4718         };
4719
4720         // Parse the trait.
4721         let mut ty = try!(self.parse_ty_sum());
4722
4723         // Parse traits, if necessary.
4724         let opt_trait = if could_be_trait && try!(self.eat_keyword(keywords::For) ){
4725             // New-style trait. Reinterpret the type as a trait.
4726             match ty.node {
4727                 TyPath(None, ref path) => {
4728                     Some(TraitRef {
4729                         path: (*path).clone(),
4730                         ref_id: ty.id,
4731                     })
4732                 }
4733                 _ => {
4734                     self.span_err(ty.span, "not a trait");
4735                     None
4736                 }
4737             }
4738         } else {
4739             match polarity {
4740                 ast::ImplPolarity::Negative => {
4741                     // This is a negated type implementation
4742                     // `impl !MyType {}`, which is not allowed.
4743                     self.span_err(neg_span, "inherent implementation can't be negated");
4744                 },
4745                 _ => {}
4746             }
4747             None
4748         };
4749
4750         if opt_trait.is_some() && try!(self.eat(&token::DotDot) ){
4751             if generics.is_parameterized() {
4752                 self.span_err(impl_span, "default trait implementations are not \
4753                                           allowed to have generics");
4754             }
4755
4756             try!(self.expect(&token::OpenDelim(token::Brace)));
4757             try!(self.expect(&token::CloseDelim(token::Brace)));
4758             Ok((ast_util::impl_pretty_name(&opt_trait, None),
4759              ItemDefaultImpl(unsafety, opt_trait.unwrap()), None))
4760         } else {
4761             if opt_trait.is_some() {
4762                 ty = try!(self.parse_ty_sum());
4763             }
4764             generics.where_clause = try!(self.parse_where_clause());
4765
4766             try!(self.expect(&token::OpenDelim(token::Brace)));
4767             let attrs = try!(self.parse_inner_attributes());
4768
4769             let mut impl_items = vec![];
4770             while !try!(self.eat(&token::CloseDelim(token::Brace))) {
4771                 impl_items.push(try!(self.parse_impl_item()));
4772             }
4773
4774             Ok((ast_util::impl_pretty_name(&opt_trait, Some(&*ty)),
4775              ItemImpl(unsafety, polarity, generics, opt_trait, ty, impl_items),
4776              Some(attrs)))
4777         }
4778     }
4779
4780     /// Parse a::B<String,i32>
4781     fn parse_trait_ref(&mut self) -> PResult<'a, TraitRef> {
4782         Ok(ast::TraitRef {
4783             path: try!(self.parse_path(LifetimeAndTypesWithoutColons)),
4784             ref_id: ast::DUMMY_NODE_ID,
4785         })
4786     }
4787
4788     fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<ast::LifetimeDef>> {
4789         if try!(self.eat_keyword(keywords::For) ){
4790             try!(self.expect(&token::Lt));
4791             let lifetime_defs = try!(self.parse_lifetime_defs());
4792             try!(self.expect_gt());
4793             Ok(lifetime_defs)
4794         } else {
4795             Ok(Vec::new())
4796         }
4797     }
4798
4799     /// Parse for<'l> a::B<String,i32>
4800     fn parse_poly_trait_ref(&mut self) -> PResult<'a, PolyTraitRef> {
4801         let lo = self.span.lo;
4802         let lifetime_defs = try!(self.parse_late_bound_lifetime_defs());
4803
4804         Ok(ast::PolyTraitRef {
4805             bound_lifetimes: lifetime_defs,
4806             trait_ref: try!(self.parse_trait_ref()),
4807             span: mk_sp(lo, self.last_span.hi),
4808         })
4809     }
4810
4811     /// Parse struct Foo { ... }
4812     fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
4813         let class_name = try!(self.parse_ident());
4814         let mut generics = try!(self.parse_generics());
4815
4816         // There is a special case worth noting here, as reported in issue #17904.
4817         // If we are parsing a tuple struct it is the case that the where clause
4818         // should follow the field list. Like so:
4819         //
4820         // struct Foo<T>(T) where T: Copy;
4821         //
4822         // If we are parsing a normal record-style struct it is the case
4823         // that the where clause comes before the body, and after the generics.
4824         // So if we look ahead and see a brace or a where-clause we begin
4825         // parsing a record style struct.
4826         //
4827         // Otherwise if we look ahead and see a paren we parse a tuple-style
4828         // struct.
4829
4830         let vdata = if self.token.is_keyword(keywords::Where) {
4831             generics.where_clause = try!(self.parse_where_clause());
4832             if try!(self.eat(&token::Semi)) {
4833                 // If we see a: `struct Foo<T> where T: Copy;` style decl.
4834                 VariantData::Unit(ast::DUMMY_NODE_ID)
4835             } else {
4836                 // If we see: `struct Foo<T> where T: Copy { ... }`
4837                 VariantData::Struct(try!(self.parse_record_struct_body(ParsePub::Yes)),
4838                                     ast::DUMMY_NODE_ID)
4839             }
4840         // No `where` so: `struct Foo<T>;`
4841         } else if try!(self.eat(&token::Semi) ){
4842             VariantData::Unit(ast::DUMMY_NODE_ID)
4843         // Record-style struct definition
4844         } else if self.token == token::OpenDelim(token::Brace) {
4845             VariantData::Struct(try!(self.parse_record_struct_body(ParsePub::Yes)),
4846                                 ast::DUMMY_NODE_ID)
4847         // Tuple-style struct definition with optional where-clause.
4848         } else if self.token == token::OpenDelim(token::Paren) {
4849             let body = VariantData::Tuple(try!(self.parse_tuple_struct_body(ParsePub::Yes)),
4850                                           ast::DUMMY_NODE_ID);
4851             generics.where_clause = try!(self.parse_where_clause());
4852             try!(self.expect(&token::Semi));
4853             body
4854         } else {
4855             let token_str = self.this_token_to_string();
4856             return Err(self.fatal(&format!("expected `where`, `{{`, `(`, or `;` after struct \
4857                                             name, found `{}`", token_str)))
4858         };
4859
4860         Ok((class_name, ItemStruct(vdata, generics), None))
4861     }
4862
4863     pub fn parse_record_struct_body(&mut self,
4864                                     parse_pub: ParsePub)
4865                                     -> PResult<'a, Vec<StructField>> {
4866         let mut fields = Vec::new();
4867         if try!(self.eat(&token::OpenDelim(token::Brace)) ){
4868             while self.token != token::CloseDelim(token::Brace) {
4869                 fields.push(try!(self.parse_struct_decl_field(parse_pub)));
4870             }
4871
4872             try!(self.bump());
4873         } else {
4874             let token_str = self.this_token_to_string();
4875             return Err(self.fatal(&format!("expected `where`, or `{{` after struct \
4876                                 name, found `{}`",
4877                                 token_str)));
4878         }
4879
4880         Ok(fields)
4881     }
4882
4883     pub fn parse_tuple_struct_body(&mut self,
4884                                    parse_pub: ParsePub)
4885                                    -> PResult<'a, Vec<StructField>> {
4886         // This is the case where we find `struct Foo<T>(T) where T: Copy;`
4887         // Unit like structs are handled in parse_item_struct function
4888         let fields = try!(self.parse_unspanned_seq(
4889             &token::OpenDelim(token::Paren),
4890             &token::CloseDelim(token::Paren),
4891             seq_sep_trailing_allowed(token::Comma),
4892             |p| {
4893                 let attrs = try!(p.parse_outer_attributes());
4894                 let lo = p.span.lo;
4895                 let struct_field_ = ast::StructField_ {
4896                     kind: UnnamedField (
4897                         if parse_pub == ParsePub::Yes {
4898                             try!(p.parse_visibility())
4899                         } else {
4900                             Inherited
4901                         }
4902                     ),
4903                     id: ast::DUMMY_NODE_ID,
4904                     ty: try!(p.parse_ty_sum()),
4905                     attrs: attrs,
4906                 };
4907                 Ok(spanned(lo, p.span.hi, struct_field_))
4908             }));
4909
4910         Ok(fields)
4911     }
4912
4913     /// Parse a structure field declaration
4914     pub fn parse_single_struct_field(&mut self,
4915                                      vis: Visibility,
4916                                      attrs: Vec<Attribute> )
4917                                      -> PResult<'a, StructField> {
4918         let a_var = try!(self.parse_name_and_ty(vis, attrs));
4919         match self.token {
4920             token::Comma => {
4921                 try!(self.bump());
4922             }
4923             token::CloseDelim(token::Brace) => {}
4924             _ => {
4925                 let span = self.span;
4926                 let token_str = self.this_token_to_string();
4927                 return Err(self.span_fatal_help(span,
4928                                      &format!("expected `,`, or `}}`, found `{}`",
4929                                              token_str),
4930                                      "struct fields should be separated by commas"))
4931             }
4932         }
4933         Ok(a_var)
4934     }
4935
4936     /// Parse an element of a struct definition
4937     fn parse_struct_decl_field(&mut self, parse_pub: ParsePub) -> PResult<'a, StructField> {
4938
4939         let attrs = try!(self.parse_outer_attributes());
4940
4941         if try!(self.eat_keyword(keywords::Pub) ){
4942             if parse_pub == ParsePub::No {
4943                 let span = self.last_span;
4944                 self.span_err(span, "`pub` is not allowed here");
4945             }
4946             return self.parse_single_struct_field(Public, attrs);
4947         }
4948
4949         return self.parse_single_struct_field(Inherited, attrs);
4950     }
4951
4952     /// Parse visibility: PUB or nothing
4953     fn parse_visibility(&mut self) -> PResult<'a, Visibility> {
4954         if try!(self.eat_keyword(keywords::Pub)) { Ok(Public) }
4955         else { Ok(Inherited) }
4956     }
4957
4958     /// Given a termination token, parse all of the items in a module
4959     fn parse_mod_items(&mut self, term: &token::Token, inner_lo: BytePos) -> PResult<'a, Mod> {
4960         let mut items = vec![];
4961         while let Some(item) = try!(self.parse_item()) {
4962             items.push(item);
4963         }
4964
4965         if !try!(self.eat(term)) {
4966             let token_str = self.this_token_to_string();
4967             return Err(self.fatal(&format!("expected item, found `{}`", token_str)));
4968         }
4969
4970         let hi = if self.span == codemap::DUMMY_SP {
4971             inner_lo
4972         } else {
4973             self.last_span.hi
4974         };
4975
4976         Ok(ast::Mod {
4977             inner: mk_sp(inner_lo, hi),
4978             items: items
4979         })
4980     }
4981
4982     fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
4983         let id = try!(self.parse_ident());
4984         try!(self.expect(&token::Colon));
4985         let ty = try!(self.parse_ty_sum());
4986         try!(self.expect(&token::Eq));
4987         let e = try!(self.parse_expr());
4988         try!(self.commit_expr_expecting(&*e, token::Semi));
4989         let item = match m {
4990             Some(m) => ItemStatic(ty, m, e),
4991             None => ItemConst(ty, e),
4992         };
4993         Ok((id, item, None))
4994     }
4995
4996     /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
4997     fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
4998         let id_span = self.span;
4999         let id = try!(self.parse_ident());
5000         if self.check(&token::Semi) {
5001             try!(self.bump());
5002             // This mod is in an external file. Let's go get it!
5003             let (m, attrs) = try!(self.eval_src_mod(id, outer_attrs, id_span));
5004             Ok((id, m, Some(attrs)))
5005         } else {
5006             self.push_mod_path(id, outer_attrs);
5007             try!(self.expect(&token::OpenDelim(token::Brace)));
5008             let mod_inner_lo = self.span.lo;
5009             let old_owns_directory = self.owns_directory;
5010             self.owns_directory = true;
5011             let attrs = try!(self.parse_inner_attributes());
5012             let m = try!(self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo));
5013             self.owns_directory = old_owns_directory;
5014             self.pop_mod_path();
5015             Ok((id, ItemMod(m), Some(attrs)))
5016         }
5017     }
5018
5019     fn push_mod_path(&mut self, id: Ident, attrs: &[Attribute]) {
5020         let default_path = self.id_to_interned_str(id);
5021         let file_path = match ::attr::first_attr_value_str_by_name(attrs, "path") {
5022             Some(d) => d,
5023             None => default_path,
5024         };
5025         self.mod_path_stack.push(file_path)
5026     }
5027
5028     fn pop_mod_path(&mut self) {
5029         self.mod_path_stack.pop().unwrap();
5030     }
5031
5032     pub fn submod_path_from_attr(attrs: &[ast::Attribute], dir_path: &Path) -> Option<PathBuf> {
5033         ::attr::first_attr_value_str_by_name(attrs, "path").map(|d| dir_path.join(&*d))
5034     }
5035
5036     /// Returns either a path to a module, or .
5037     pub fn default_submod_path(id: ast::Ident, dir_path: &Path, codemap: &CodeMap) -> ModulePath
5038     {
5039         let mod_name = id.to_string();
5040         let default_path_str = format!("{}.rs", mod_name);
5041         let secondary_path_str = format!("{}/mod.rs", mod_name);
5042         let default_path = dir_path.join(&default_path_str);
5043         let secondary_path = dir_path.join(&secondary_path_str);
5044         let default_exists = codemap.file_exists(&default_path);
5045         let secondary_exists = codemap.file_exists(&secondary_path);
5046
5047         let result = match (default_exists, secondary_exists) {
5048             (true, false) => Ok(ModulePathSuccess { path: default_path, owns_directory: false }),
5049             (false, true) => Ok(ModulePathSuccess { path: secondary_path, owns_directory: true }),
5050             (false, false) => Err(ModulePathError {
5051                 err_msg: format!("file not found for module `{}`", mod_name),
5052                 help_msg: format!("name the file either {} or {} inside the directory {:?}",
5053                                   default_path_str,
5054                                   secondary_path_str,
5055                                   dir_path.display()),
5056             }),
5057             (true, true) => Err(ModulePathError {
5058                 err_msg: format!("file for module `{}` found at both {} and {}",
5059                                  mod_name,
5060                                  default_path_str,
5061                                  secondary_path_str),
5062                 help_msg: "delete or rename one of them to remove the ambiguity".to_owned(),
5063             }),
5064         };
5065
5066         ModulePath {
5067             name: mod_name,
5068             path_exists: default_exists || secondary_exists,
5069             result: result,
5070         }
5071     }
5072
5073     fn submod_path(&mut self,
5074                    id: ast::Ident,
5075                    outer_attrs: &[ast::Attribute],
5076                    id_sp: Span) -> PResult<'a, ModulePathSuccess> {
5077         let mut prefix = PathBuf::from(&self.sess.codemap().span_to_filename(self.span));
5078         prefix.pop();
5079         let mut dir_path = prefix;
5080         for part in &self.mod_path_stack {
5081             dir_path.push(&**part);
5082         }
5083
5084         if let Some(p) = Parser::submod_path_from_attr(outer_attrs, &dir_path) {
5085             return Ok(ModulePathSuccess { path: p, owns_directory: true });
5086         }
5087
5088         let paths = Parser::default_submod_path(id, &dir_path, self.sess.codemap());
5089
5090         if !self.owns_directory {
5091             let mut err = self.diagnostic().struct_span_err(id_sp,
5092                 "cannot declare a new module at this location");
5093             let this_module = match self.mod_path_stack.last() {
5094                 Some(name) => name.to_string(),
5095                 None => self.root_module_name.as_ref().unwrap().clone(),
5096             };
5097             err.span_note(id_sp,
5098                           &format!("maybe move this module `{0}` to its own directory \
5099                                      via `{0}/mod.rs`",
5100                                     this_module));
5101             if paths.path_exists {
5102                 err.span_note(id_sp,
5103                               &format!("... or maybe `use` the module `{}` instead \
5104                                         of possibly redeclaring it",
5105                                        paths.name));
5106             }
5107             err.emit();
5108             self.abort_if_errors();
5109         }
5110
5111         match paths.result {
5112             Ok(succ) => Ok(succ),
5113             Err(err) => Err(self.span_fatal_help(id_sp, &err.err_msg, &err.help_msg)),
5114         }
5115     }
5116
5117     /// Read a module from a source file.
5118     fn eval_src_mod(&mut self,
5119                     id: ast::Ident,
5120                     outer_attrs: &[ast::Attribute],
5121                     id_sp: Span)
5122                     -> PResult<'a, (ast::Item_, Vec<ast::Attribute> )> {
5123         let ModulePathSuccess { path, owns_directory } = try!(self.submod_path(id,
5124                                                                                outer_attrs,
5125                                                                                id_sp));
5126
5127         self.eval_src_mod_from_path(path,
5128                                     owns_directory,
5129                                     id.to_string(),
5130                                     id_sp)
5131     }
5132
5133     fn eval_src_mod_from_path(&mut self,
5134                               path: PathBuf,
5135                               owns_directory: bool,
5136                               name: String,
5137                               id_sp: Span) -> PResult<'a, (ast::Item_, Vec<ast::Attribute> )> {
5138         let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
5139         match included_mod_stack.iter().position(|p| *p == path) {
5140             Some(i) => {
5141                 let mut err = String::from("circular modules: ");
5142                 let len = included_mod_stack.len();
5143                 for p in &included_mod_stack[i.. len] {
5144                     err.push_str(&p.to_string_lossy());
5145                     err.push_str(" -> ");
5146                 }
5147                 err.push_str(&path.to_string_lossy());
5148                 return Err(self.span_fatal(id_sp, &err[..]));
5149             }
5150             None => ()
5151         }
5152         included_mod_stack.push(path.clone());
5153         drop(included_mod_stack);
5154
5155         let mut p0 = new_sub_parser_from_file(self.sess,
5156                                               self.cfg.clone(),
5157                                               &path,
5158                                               owns_directory,
5159                                               Some(name),
5160                                               id_sp);
5161         let mod_inner_lo = p0.span.lo;
5162         let mod_attrs = try!(p0.parse_inner_attributes());
5163         let m0 = try!(p0.parse_mod_items(&token::Eof, mod_inner_lo));
5164         self.sess.included_mod_stack.borrow_mut().pop();
5165         Ok((ast::ItemMod(m0), mod_attrs))
5166     }
5167
5168     /// Parse a function declaration from a foreign module
5169     fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: BytePos,
5170                              attrs: Vec<Attribute>) -> PResult<'a, P<ForeignItem>> {
5171         try!(self.expect_keyword(keywords::Fn));
5172
5173         let (ident, mut generics) = try!(self.parse_fn_header());
5174         let decl = try!(self.parse_fn_decl(true));
5175         generics.where_clause = try!(self.parse_where_clause());
5176         let hi = self.span.hi;
5177         try!(self.expect(&token::Semi));
5178         Ok(P(ast::ForeignItem {
5179             ident: ident,
5180             attrs: attrs,
5181             node: ForeignItemFn(decl, generics),
5182             id: ast::DUMMY_NODE_ID,
5183             span: mk_sp(lo, hi),
5184             vis: vis
5185         }))
5186     }
5187
5188     /// Parse a static item from a foreign module
5189     fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: BytePos,
5190                                  attrs: Vec<Attribute>) -> PResult<'a, P<ForeignItem>> {
5191         try!(self.expect_keyword(keywords::Static));
5192         let mutbl = try!(self.eat_keyword(keywords::Mut));
5193
5194         let ident = try!(self.parse_ident());
5195         try!(self.expect(&token::Colon));
5196         let ty = try!(self.parse_ty_sum());
5197         let hi = self.span.hi;
5198         try!(self.expect(&token::Semi));
5199         Ok(P(ForeignItem {
5200             ident: ident,
5201             attrs: attrs,
5202             node: ForeignItemStatic(ty, mutbl),
5203             id: ast::DUMMY_NODE_ID,
5204             span: mk_sp(lo, hi),
5205             vis: vis
5206         }))
5207     }
5208
5209     /// Parse extern crate links
5210     ///
5211     /// # Examples
5212     ///
5213     /// extern crate foo;
5214     /// extern crate bar as foo;
5215     fn parse_item_extern_crate(&mut self,
5216                                lo: BytePos,
5217                                visibility: Visibility,
5218                                attrs: Vec<Attribute>)
5219                                 -> PResult<'a, P<Item>> {
5220
5221         let crate_name = try!(self.parse_ident());
5222         let (maybe_path, ident) = if let Some(ident) = try!(self.parse_rename()) {
5223             (Some(crate_name.name), ident)
5224         } else {
5225             (None, crate_name)
5226         };
5227         try!(self.expect(&token::Semi));
5228
5229         let last_span = self.last_span;
5230
5231         if visibility == ast::Public {
5232             self.span_warn(mk_sp(lo, last_span.hi),
5233                            "`pub extern crate` does not work as expected and should not be used. \
5234                             Likely to become an error. Prefer `extern crate` and `pub use`.");
5235         }
5236
5237         Ok(self.mk_item(lo,
5238                         last_span.hi,
5239                         ident,
5240                         ItemExternCrate(maybe_path),
5241                         visibility,
5242                         attrs))
5243     }
5244
5245     /// Parse `extern` for foreign ABIs
5246     /// modules.
5247     ///
5248     /// `extern` is expected to have been
5249     /// consumed before calling this method
5250     ///
5251     /// # Examples:
5252     ///
5253     /// extern "C" {}
5254     /// extern {}
5255     fn parse_item_foreign_mod(&mut self,
5256                               lo: BytePos,
5257                               opt_abi: Option<abi::Abi>,
5258                               visibility: Visibility,
5259                               mut attrs: Vec<Attribute>)
5260                               -> PResult<'a, P<Item>> {
5261         try!(self.expect(&token::OpenDelim(token::Brace)));
5262
5263         let abi = opt_abi.unwrap_or(abi::C);
5264
5265         attrs.extend(try!(self.parse_inner_attributes()));
5266
5267         let mut foreign_items = vec![];
5268         while let Some(item) = try!(self.parse_foreign_item()) {
5269             foreign_items.push(item);
5270         }
5271         try!(self.expect(&token::CloseDelim(token::Brace)));
5272
5273         let last_span = self.last_span;
5274         let m = ast::ForeignMod {
5275             abi: abi,
5276             items: foreign_items
5277         };
5278         Ok(self.mk_item(lo,
5279                      last_span.hi,
5280                      special_idents::invalid,
5281                      ItemForeignMod(m),
5282                      visibility,
5283                      attrs))
5284     }
5285
5286     /// Parse type Foo = Bar;
5287     fn parse_item_type(&mut self) -> PResult<'a, ItemInfo> {
5288         let ident = try!(self.parse_ident());
5289         let mut tps = try!(self.parse_generics());
5290         tps.where_clause = try!(self.parse_where_clause());
5291         try!(self.expect(&token::Eq));
5292         let ty = try!(self.parse_ty_sum());
5293         try!(self.expect(&token::Semi));
5294         Ok((ident, ItemTy(ty, tps), None))
5295     }
5296
5297     /// Parse the part of an "enum" decl following the '{'
5298     fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
5299         let mut variants = Vec::new();
5300         let mut all_nullary = true;
5301         let mut any_disr = None;
5302         while self.token != token::CloseDelim(token::Brace) {
5303             let variant_attrs = try!(self.parse_outer_attributes());
5304             let vlo = self.span.lo;
5305
5306             let struct_def;
5307             let mut disr_expr = None;
5308             let ident = try!(self.parse_ident());
5309             if self.check(&token::OpenDelim(token::Brace)) {
5310                 // Parse a struct variant.
5311                 all_nullary = false;
5312                 struct_def = VariantData::Struct(try!(self.parse_record_struct_body(ParsePub::No)),
5313                                                  ast::DUMMY_NODE_ID);
5314             } else if self.check(&token::OpenDelim(token::Paren)) {
5315                 all_nullary = false;
5316                 struct_def = VariantData::Tuple(try!(self.parse_tuple_struct_body(ParsePub::No)),
5317                                                 ast::DUMMY_NODE_ID);
5318             } else if try!(self.eat(&token::Eq) ){
5319                 disr_expr = Some(try!(self.parse_expr()));
5320                 any_disr = disr_expr.as_ref().map(|expr| expr.span);
5321                 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5322             } else {
5323                 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5324             }
5325
5326             let vr = ast::Variant_ {
5327                 name: ident,
5328                 attrs: variant_attrs,
5329                 data: struct_def,
5330                 disr_expr: disr_expr,
5331             };
5332             variants.push(P(spanned(vlo, self.last_span.hi, vr)));
5333
5334             if !try!(self.eat(&token::Comma)) { break; }
5335         }
5336         try!(self.expect(&token::CloseDelim(token::Brace)));
5337         match any_disr {
5338             Some(disr_span) if !all_nullary =>
5339                 self.span_err(disr_span,
5340                     "discriminator values can only be used with a c-like enum"),
5341             _ => ()
5342         }
5343
5344         Ok(ast::EnumDef { variants: variants })
5345     }
5346
5347     /// Parse an "enum" declaration
5348     fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
5349         let id = try!(self.parse_ident());
5350         let mut generics = try!(self.parse_generics());
5351         generics.where_clause = try!(self.parse_where_clause());
5352         try!(self.expect(&token::OpenDelim(token::Brace)));
5353
5354         let enum_definition = try!(self.parse_enum_def(&generics));
5355         Ok((id, ItemEnum(enum_definition, generics), None))
5356     }
5357
5358     /// Parses a string as an ABI spec on an extern type or module. Consumes
5359     /// the `extern` keyword, if one is found.
5360     fn parse_opt_abi(&mut self) -> PResult<'a, Option<abi::Abi>> {
5361         match self.token {
5362             token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
5363                 let sp = self.span;
5364                 self.expect_no_suffix(sp, "ABI spec", suf);
5365                 try!(self.bump());
5366                 match abi::lookup(&s.as_str()) {
5367                     Some(abi) => Ok(Some(abi)),
5368                     None => {
5369                         let last_span = self.last_span;
5370                         self.span_err(
5371                             last_span,
5372                             &format!("invalid ABI: expected one of [{}], \
5373                                      found `{}`",
5374                                     abi::all_names().join(", "),
5375                                     s));
5376                         Ok(None)
5377                     }
5378                 }
5379             }
5380
5381             _ => Ok(None),
5382         }
5383     }
5384
5385     /// Parse one of the items allowed by the flags.
5386     /// NB: this function no longer parses the items inside an
5387     /// extern crate.
5388     fn parse_item_(&mut self, attrs: Vec<Attribute>,
5389                    macros_allowed: bool, attributes_allowed: bool) -> PResult<'a, Option<P<Item>>> {
5390         let nt_item = match self.token {
5391             token::Interpolated(token::NtItem(ref item)) => {
5392                 Some((**item).clone())
5393             }
5394             _ => None
5395         };
5396         match nt_item {
5397             Some(mut item) => {
5398                 try!(self.bump());
5399                 let mut attrs = attrs;
5400                 mem::swap(&mut item.attrs, &mut attrs);
5401                 item.attrs.extend(attrs);
5402                 return Ok(Some(P(item)));
5403             }
5404             None => {}
5405         }
5406
5407         let lo = self.span.lo;
5408
5409         let visibility = try!(self.parse_visibility());
5410
5411         if try!(self.eat_keyword(keywords::Use) ){
5412             // USE ITEM
5413             let item_ = ItemUse(try!(self.parse_view_path()));
5414             try!(self.expect(&token::Semi));
5415
5416             let last_span = self.last_span;
5417             let item = self.mk_item(lo,
5418                                     last_span.hi,
5419                                     token::special_idents::invalid,
5420                                     item_,
5421                                     visibility,
5422                                     attrs);
5423             return Ok(Some(item));
5424         }
5425
5426         if try!(self.eat_keyword(keywords::Extern)) {
5427             if try!(self.eat_keyword(keywords::Crate)) {
5428                 return Ok(Some(try!(self.parse_item_extern_crate(lo, visibility, attrs))));
5429             }
5430
5431             let opt_abi = try!(self.parse_opt_abi());
5432
5433             if try!(self.eat_keyword(keywords::Fn) ){
5434                 // EXTERN FUNCTION ITEM
5435                 let abi = opt_abi.unwrap_or(abi::C);
5436                 let (ident, item_, extra_attrs) =
5437                     try!(self.parse_item_fn(Unsafety::Normal, Constness::NotConst, abi));
5438                 let last_span = self.last_span;
5439                 let item = self.mk_item(lo,
5440                                         last_span.hi,
5441                                         ident,
5442                                         item_,
5443                                         visibility,
5444                                         maybe_append(attrs, extra_attrs));
5445                 return Ok(Some(item));
5446             } else if self.check(&token::OpenDelim(token::Brace)) {
5447                 return Ok(Some(try!(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs))));
5448             }
5449
5450             try!(self.expect_one_of(&[], &[]));
5451         }
5452
5453         if try!(self.eat_keyword(keywords::Static) ){
5454             // STATIC ITEM
5455             let m = if try!(self.eat_keyword(keywords::Mut)) {MutMutable} else {MutImmutable};
5456             let (ident, item_, extra_attrs) = try!(self.parse_item_const(Some(m)));
5457             let last_span = self.last_span;
5458             let item = self.mk_item(lo,
5459                                     last_span.hi,
5460                                     ident,
5461                                     item_,
5462                                     visibility,
5463                                     maybe_append(attrs, extra_attrs));
5464             return Ok(Some(item));
5465         }
5466         if try!(self.eat_keyword(keywords::Const) ){
5467             if self.check_keyword(keywords::Fn)
5468                 || (self.check_keyword(keywords::Unsafe)
5469                     && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
5470                 // CONST FUNCTION ITEM
5471                 let unsafety = if try!(self.eat_keyword(keywords::Unsafe) ){
5472                     Unsafety::Unsafe
5473                 } else {
5474                     Unsafety::Normal
5475                 };
5476                 try!(self.bump());
5477                 let (ident, item_, extra_attrs) =
5478                     try!(self.parse_item_fn(unsafety, Constness::Const, abi::Rust));
5479                 let last_span = self.last_span;
5480                 let item = self.mk_item(lo,
5481                                         last_span.hi,
5482                                         ident,
5483                                         item_,
5484                                         visibility,
5485                                         maybe_append(attrs, extra_attrs));
5486                 return Ok(Some(item));
5487             }
5488
5489             // CONST ITEM
5490             if try!(self.eat_keyword(keywords::Mut) ){
5491                 let last_span = self.last_span;
5492                 self.diagnostic().struct_span_err(last_span, "const globals cannot be mutable")
5493                                  .fileline_help(last_span, "did you mean to declare a static?")
5494                                  .emit();
5495             }
5496             let (ident, item_, extra_attrs) = try!(self.parse_item_const(None));
5497             let last_span = self.last_span;
5498             let item = self.mk_item(lo,
5499                                     last_span.hi,
5500                                     ident,
5501                                     item_,
5502                                     visibility,
5503                                     maybe_append(attrs, extra_attrs));
5504             return Ok(Some(item));
5505         }
5506         if self.check_keyword(keywords::Unsafe) &&
5507             self.look_ahead(1, |t| t.is_keyword(keywords::Trait))
5508         {
5509             // UNSAFE TRAIT ITEM
5510             try!(self.expect_keyword(keywords::Unsafe));
5511             try!(self.expect_keyword(keywords::Trait));
5512             let (ident, item_, extra_attrs) =
5513                 try!(self.parse_item_trait(ast::Unsafety::Unsafe));
5514             let last_span = self.last_span;
5515             let item = self.mk_item(lo,
5516                                     last_span.hi,
5517                                     ident,
5518                                     item_,
5519                                     visibility,
5520                                     maybe_append(attrs, extra_attrs));
5521             return Ok(Some(item));
5522         }
5523         if self.check_keyword(keywords::Unsafe) &&
5524             self.look_ahead(1, |t| t.is_keyword(keywords::Impl))
5525         {
5526             // IMPL ITEM
5527             try!(self.expect_keyword(keywords::Unsafe));
5528             try!(self.expect_keyword(keywords::Impl));
5529             let (ident, item_, extra_attrs) = try!(self.parse_item_impl(ast::Unsafety::Unsafe));
5530             let last_span = self.last_span;
5531             let item = self.mk_item(lo,
5532                                     last_span.hi,
5533                                     ident,
5534                                     item_,
5535                                     visibility,
5536                                     maybe_append(attrs, extra_attrs));
5537             return Ok(Some(item));
5538         }
5539         if self.check_keyword(keywords::Fn) {
5540             // FUNCTION ITEM
5541             try!(self.bump());
5542             let (ident, item_, extra_attrs) =
5543                 try!(self.parse_item_fn(Unsafety::Normal, Constness::NotConst, abi::Rust));
5544             let last_span = self.last_span;
5545             let item = self.mk_item(lo,
5546                                     last_span.hi,
5547                                     ident,
5548                                     item_,
5549                                     visibility,
5550                                     maybe_append(attrs, extra_attrs));
5551             return Ok(Some(item));
5552         }
5553         if self.check_keyword(keywords::Unsafe)
5554             && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
5555             // UNSAFE FUNCTION ITEM
5556             try!(self.bump());
5557             let abi = if try!(self.eat_keyword(keywords::Extern) ){
5558                 try!(self.parse_opt_abi()).unwrap_or(abi::C)
5559             } else {
5560                 abi::Rust
5561             };
5562             try!(self.expect_keyword(keywords::Fn));
5563             let (ident, item_, extra_attrs) =
5564                 try!(self.parse_item_fn(Unsafety::Unsafe, Constness::NotConst, abi));
5565             let last_span = self.last_span;
5566             let item = self.mk_item(lo,
5567                                     last_span.hi,
5568                                     ident,
5569                                     item_,
5570                                     visibility,
5571                                     maybe_append(attrs, extra_attrs));
5572             return Ok(Some(item));
5573         }
5574         if try!(self.eat_keyword(keywords::Mod) ){
5575             // MODULE ITEM
5576             let (ident, item_, extra_attrs) =
5577                 try!(self.parse_item_mod(&attrs[..]));
5578             let last_span = self.last_span;
5579             let item = self.mk_item(lo,
5580                                     last_span.hi,
5581                                     ident,
5582                                     item_,
5583                                     visibility,
5584                                     maybe_append(attrs, extra_attrs));
5585             return Ok(Some(item));
5586         }
5587         if try!(self.eat_keyword(keywords::Type) ){
5588             // TYPE ITEM
5589             let (ident, item_, extra_attrs) = try!(self.parse_item_type());
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::Enum) ){
5600             // ENUM ITEM
5601             let (ident, item_, extra_attrs) = try!(self.parse_item_enum());
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::Trait) ){
5612             // TRAIT ITEM
5613             let (ident, item_, extra_attrs) =
5614                 try!(self.parse_item_trait(ast::Unsafety::Normal));
5615             let last_span = self.last_span;
5616             let item = self.mk_item(lo,
5617                                     last_span.hi,
5618                                     ident,
5619                                     item_,
5620                                     visibility,
5621                                     maybe_append(attrs, extra_attrs));
5622             return Ok(Some(item));
5623         }
5624         if try!(self.eat_keyword(keywords::Impl) ){
5625             // IMPL ITEM
5626             let (ident, item_, extra_attrs) = try!(self.parse_item_impl(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::Struct) ){
5637             // STRUCT ITEM
5638             let (ident, item_, extra_attrs) = try!(self.parse_item_struct());
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         self.parse_macro_use_or_failure(attrs,macros_allowed,attributes_allowed,lo,visibility)
5649     }
5650
5651     /// Parse a foreign item.
5652     fn parse_foreign_item(&mut self) -> PResult<'a, Option<P<ForeignItem>>> {
5653         let attrs = try!(self.parse_outer_attributes());
5654         let lo = self.span.lo;
5655         let visibility = try!(self.parse_visibility());
5656
5657         if self.check_keyword(keywords::Static) {
5658             // FOREIGN STATIC ITEM
5659             return Ok(Some(try!(self.parse_item_foreign_static(visibility, lo, attrs))));
5660         }
5661         if self.check_keyword(keywords::Fn) || self.check_keyword(keywords::Unsafe) {
5662             // FOREIGN FUNCTION ITEM
5663             return Ok(Some(try!(self.parse_item_foreign_fn(visibility, lo, attrs))));
5664         }
5665
5666         // FIXME #5668: this will occur for a macro invocation:
5667         match try!(self.parse_macro_use_or_failure(attrs, true, false, lo, visibility)) {
5668             Some(item) => {
5669                 return Err(self.span_fatal(item.span, "macros cannot expand to foreign items"));
5670             }
5671             None => Ok(None)
5672         }
5673     }
5674
5675     /// This is the fall-through for parsing items.
5676     fn parse_macro_use_or_failure(
5677         &mut self,
5678         attrs: Vec<Attribute> ,
5679         macros_allowed: bool,
5680         attributes_allowed: bool,
5681         lo: BytePos,
5682         visibility: Visibility
5683     ) -> PResult<'a, Option<P<Item>>> {
5684         if macros_allowed && !self.token.is_any_keyword()
5685                 && self.look_ahead(1, |t| *t == token::Not)
5686                 && (self.look_ahead(2, |t| t.is_plain_ident())
5687                     || self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren))
5688                     || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) {
5689             // MACRO INVOCATION ITEM
5690
5691             let last_span = self.last_span;
5692             self.complain_if_pub_macro(visibility, last_span);
5693
5694             let mac_lo = self.span.lo;
5695
5696             // item macro.
5697             let pth = try!(self.parse_path(NoTypesAllowed));
5698             try!(self.expect(&token::Not));
5699
5700             // a 'special' identifier (like what `macro_rules!` uses)
5701             // is optional. We should eventually unify invoc syntax
5702             // and remove this.
5703             let id = if self.token.is_plain_ident() {
5704                 try!(self.parse_ident())
5705             } else {
5706                 token::special_idents::invalid // no special identifier
5707             };
5708             // eat a matched-delimiter token tree:
5709             let delim = try!(self.expect_open_delim());
5710             let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
5711                                             seq_sep_none(),
5712                                             |p| p.parse_token_tree()));
5713             // single-variant-enum... :
5714             let m = Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT };
5715             let m: ast::Mac = codemap::Spanned { node: m,
5716                                              span: mk_sp(mac_lo,
5717                                                          self.last_span.hi) };
5718
5719             if delim != token::Brace {
5720                 if !try!(self.eat(&token::Semi) ){
5721                     let last_span = self.last_span;
5722                     self.span_err(last_span,
5723                                   "macros that expand to items must either \
5724                                    be surrounded with braces or followed by \
5725                                    a semicolon");
5726                 }
5727             }
5728
5729             let item_ = ItemMac(m);
5730             let last_span = self.last_span;
5731             let item = self.mk_item(lo,
5732                                     last_span.hi,
5733                                     id,
5734                                     item_,
5735                                     visibility,
5736                                     attrs);
5737             return Ok(Some(item));
5738         }
5739
5740         // FAILURE TO PARSE ITEM
5741         match visibility {
5742             Inherited => {}
5743             Public => {
5744                 let last_span = self.last_span;
5745                 return Err(self.span_fatal(last_span, "unmatched visibility `pub`"));
5746             }
5747         }
5748
5749         if !attributes_allowed && !attrs.is_empty() {
5750             self.expected_item_err(&attrs);
5751         }
5752         Ok(None)
5753     }
5754
5755     pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
5756         let attrs = try!(self.parse_outer_attributes());
5757         self.parse_item_(attrs, true, false)
5758     }
5759
5760
5761     /// Matches view_path : MOD? non_global_path as IDENT
5762     /// | MOD? non_global_path MOD_SEP LBRACE RBRACE
5763     /// | MOD? non_global_path MOD_SEP LBRACE ident_seq RBRACE
5764     /// | MOD? non_global_path MOD_SEP STAR
5765     /// | MOD? non_global_path
5766     fn parse_view_path(&mut self) -> PResult<'a, P<ViewPath>> {
5767         let lo = self.span.lo;
5768
5769         // Allow a leading :: because the paths are absolute either way.
5770         // This occurs with "use $crate::..." in macros.
5771         try!(self.eat(&token::ModSep));
5772
5773         if self.check(&token::OpenDelim(token::Brace)) {
5774             // use {foo,bar}
5775             let idents = try!(self.parse_unspanned_seq(
5776                 &token::OpenDelim(token::Brace),
5777                 &token::CloseDelim(token::Brace),
5778                 seq_sep_trailing_allowed(token::Comma),
5779                 |p| p.parse_path_list_item()));
5780             let path = ast::Path {
5781                 span: mk_sp(lo, self.span.hi),
5782                 global: false,
5783                 segments: Vec::new()
5784             };
5785             return Ok(P(spanned(lo, self.span.hi, ViewPathList(path, idents))));
5786         }
5787
5788         let first_ident = try!(self.parse_ident());
5789         let mut path = vec!(first_ident);
5790         if let token::ModSep = self.token {
5791             // foo::bar or foo::{a,b,c} or foo::*
5792             while self.check(&token::ModSep) {
5793                 try!(self.bump());
5794
5795                 match self.token {
5796                   token::Ident(..) => {
5797                     let ident = try!(self.parse_ident());
5798                     path.push(ident);
5799                   }
5800
5801                   // foo::bar::{a,b,c}
5802                   token::OpenDelim(token::Brace) => {
5803                     let idents = try!(self.parse_unspanned_seq(
5804                         &token::OpenDelim(token::Brace),
5805                         &token::CloseDelim(token::Brace),
5806                         seq_sep_trailing_allowed(token::Comma),
5807                         |p| p.parse_path_list_item()
5808                     ));
5809                     let path = ast::Path {
5810                         span: mk_sp(lo, self.span.hi),
5811                         global: false,
5812                         segments: path.into_iter().map(|identifier| {
5813                             ast::PathSegment {
5814                                 identifier: identifier,
5815                                 parameters: ast::PathParameters::none(),
5816                             }
5817                         }).collect()
5818                     };
5819                     return Ok(P(spanned(lo, self.span.hi, ViewPathList(path, idents))));
5820                   }
5821
5822                   // foo::bar::*
5823                   token::BinOp(token::Star) => {
5824                     try!(self.bump());
5825                     let path = ast::Path {
5826                         span: mk_sp(lo, self.span.hi),
5827                         global: false,
5828                         segments: path.into_iter().map(|identifier| {
5829                             ast::PathSegment {
5830                                 identifier: identifier,
5831                                 parameters: ast::PathParameters::none(),
5832                             }
5833                         }).collect()
5834                     };
5835                     return Ok(P(spanned(lo, self.span.hi, ViewPathGlob(path))));
5836                   }
5837
5838                   // fall-through for case foo::bar::;
5839                   token::Semi => {
5840                     self.span_err(self.span, "expected identifier or `{` or `*`, found `;`");
5841                   }
5842
5843                   _ => break
5844                 }
5845             }
5846         }
5847         let mut rename_to = path[path.len() - 1];
5848         let path = ast::Path {
5849             span: mk_sp(lo, self.last_span.hi),
5850             global: false,
5851             segments: path.into_iter().map(|identifier| {
5852                 ast::PathSegment {
5853                     identifier: identifier,
5854                     parameters: ast::PathParameters::none(),
5855                 }
5856             }).collect()
5857         };
5858         rename_to = try!(self.parse_rename()).unwrap_or(rename_to);
5859         Ok(P(spanned(lo, self.last_span.hi, ViewPathSimple(rename_to, path))))
5860     }
5861
5862     fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
5863         if try!(self.eat_keyword(keywords::As)) {
5864             self.parse_ident().map(Some)
5865         } else {
5866             Ok(None)
5867         }
5868     }
5869
5870     /// Parses a source module as a crate. This is the main
5871     /// entry point for the parser.
5872     pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
5873         let lo = self.span.lo;
5874         Ok(ast::Crate {
5875             attrs: try!(self.parse_inner_attributes()),
5876             module: try!(self.parse_mod_items(&token::Eof, lo)),
5877             config: self.cfg.clone(),
5878             span: mk_sp(lo, self.span.lo),
5879             exported_macros: Vec::new(),
5880         })
5881     }
5882
5883     pub fn parse_optional_str(&mut self)
5884                               -> PResult<'a, Option<(InternedString,
5885                                                  ast::StrStyle,
5886                                                  Option<ast::Name>)>> {
5887         let ret = match self.token {
5888             token::Literal(token::Str_(s), suf) => {
5889                 (self.id_to_interned_str(ast::Ident::with_empty_ctxt(s)), ast::CookedStr, suf)
5890             }
5891             token::Literal(token::StrRaw(s, n), suf) => {
5892                 (self.id_to_interned_str(ast::Ident::with_empty_ctxt(s)), ast::RawStr(n), suf)
5893             }
5894             _ => return Ok(None)
5895         };
5896         try!(self.bump());
5897         Ok(Some(ret))
5898     }
5899
5900     pub fn parse_str(&mut self) -> PResult<'a, (InternedString, StrStyle)> {
5901         match try!(self.parse_optional_str()) {
5902             Some((s, style, suf)) => {
5903                 let sp = self.last_span;
5904                 self.expect_no_suffix(sp, "string literal", suf);
5905                 Ok((s, style))
5906             }
5907             _ =>  Err(self.fatal("expected string literal"))
5908         }
5909     }
5910 }