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