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