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