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