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