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