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