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