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