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