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