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