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