]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/parse/parser.rs
rollup merge of #16839 : treeman/issue-15358
[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, 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(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(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(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 span = self.last_span;
1420             match self.token {
1421                 token::IDENT(ref ident, _)
1422                         if "str" == token::get_ident(*ident).get() => {
1423                     // This is OK (for now).
1424                 }
1425                 token::LBRACKET => {}   // Also OK.
1426                 _ => self.obsolete(span, ObsoleteOwnedType)
1427             }
1428             TyUniq(self.parse_ty(false))
1429         } else if self.token == token::BINOP(token::STAR) {
1430             // STAR POINTER (bare pointer?)
1431             self.bump();
1432             TyPtr(self.parse_ptr())
1433         } else if self.token == token::LBRACKET {
1434             // VECTOR
1435             self.expect(&token::LBRACKET);
1436             let t = self.parse_ty(true);
1437
1438             // Parse the `, ..e` in `[ int, ..e ]`
1439             // where `e` is a const expression
1440             let t = match self.maybe_parse_fixed_vstore() {
1441                 None => TyVec(t),
1442                 Some(suffix) => TyFixedLengthVec(t, suffix)
1443             };
1444             self.expect(&token::RBRACKET);
1445             t
1446         } else if self.token == token::BINOP(token::AND) ||
1447                 self.token == token::ANDAND {
1448             // BORROWED POINTER
1449             self.expect_and();
1450             self.parse_borrowed_pointee()
1451         } else if self.is_keyword(keywords::Extern) ||
1452                   self.is_keyword(keywords::Unsafe) ||
1453                 self.token_is_bare_fn_keyword() {
1454             // BARE FUNCTION
1455             self.parse_ty_bare_fn()
1456         } else if self.token_is_closure_keyword() ||
1457                 self.token == token::BINOP(token::OR) ||
1458                 self.token == token::OROR ||
1459                 self.token == token::LT {
1460             // CLOSURE
1461             //
1462             // FIXME(pcwalton): Eventually `token::LT` will not unambiguously
1463             // introduce a closure, once procs can have lifetime bounds. We
1464             // will need to refactor the grammar a little bit at that point.
1465
1466             self.parse_ty_closure()
1467         } else if self.eat_keyword(keywords::Typeof) {
1468             // TYPEOF
1469             // In order to not be ambiguous, the type must be surrounded by parens.
1470             self.expect(&token::LPAREN);
1471             let e = self.parse_expr();
1472             self.expect(&token::RPAREN);
1473             TyTypeof(e)
1474         } else if self.eat_keyword(keywords::Proc) {
1475             self.parse_proc_type()
1476         } else if self.token == token::MOD_SEP
1477             || is_ident_or_path(&self.token) {
1478             // NAMED TYPE
1479             let mode = if plus_allowed {
1480                 LifetimeAndTypesAndBounds
1481             } else {
1482                 LifetimeAndTypesWithoutColons
1483             };
1484             let PathAndBounds {
1485                 path,
1486                 bounds
1487             } = self.parse_path(mode);
1488             TyPath(path, bounds, ast::DUMMY_NODE_ID)
1489         } else if self.eat(&token::UNDERSCORE) {
1490             // TYPE TO BE INFERRED
1491             TyInfer
1492         } else {
1493             let msg = format!("expected type, found token {:?}", self.token);
1494             self.fatal(msg.as_slice());
1495         };
1496
1497         let sp = mk_sp(lo, self.last_span.hi);
1498         P(Ty {id: ast::DUMMY_NODE_ID, node: t, span: sp})
1499     }
1500
1501     pub fn parse_borrowed_pointee(&mut self) -> Ty_ {
1502         // look for `&'lt` or `&'foo ` and interpret `foo` as the region name:
1503         let opt_lifetime = self.parse_opt_lifetime();
1504
1505         let mt = self.parse_mt();
1506         return TyRptr(opt_lifetime, mt);
1507     }
1508
1509     pub fn parse_ptr(&mut self) -> MutTy {
1510         let mutbl = if self.eat_keyword(keywords::Mut) {
1511             MutMutable
1512         } else if self.eat_keyword(keywords::Const) {
1513             MutImmutable
1514         } else {
1515             let span = self.last_span;
1516             self.span_err(span,
1517                           "bare raw pointers are no longer allowed, you should \
1518                            likely use `*mut T`, but otherwise `*T` is now \
1519                            known as `*const T`");
1520             MutImmutable
1521         };
1522         let t = self.parse_ty(true);
1523         MutTy { ty: t, mutbl: mutbl }
1524     }
1525
1526     pub fn is_named_argument(&mut self) -> bool {
1527         let offset = match self.token {
1528             token::BINOP(token::AND) => 1,
1529             token::ANDAND => 1,
1530             _ if token::is_keyword(keywords::Mut, &self.token) => 1,
1531             _ => 0
1532         };
1533
1534         debug!("parser is_named_argument offset:{}", offset);
1535
1536         if offset == 0 {
1537             is_plain_ident_or_underscore(&self.token)
1538                 && self.look_ahead(1, |t| *t == token::COLON)
1539         } else {
1540             self.look_ahead(offset, |t| is_plain_ident_or_underscore(t))
1541                 && self.look_ahead(offset + 1, |t| *t == token::COLON)
1542         }
1543     }
1544
1545     /// This version of parse arg doesn't necessarily require
1546     /// identifier names.
1547     pub fn parse_arg_general(&mut self, require_name: bool) -> Arg {
1548         let pat = if require_name || self.is_named_argument() {
1549             debug!("parse_arg_general parse_pat (require_name:{:?})",
1550                    require_name);
1551             let pat = self.parse_pat();
1552
1553             self.expect(&token::COLON);
1554             pat
1555         } else {
1556             debug!("parse_arg_general ident_to_pat");
1557             ast_util::ident_to_pat(ast::DUMMY_NODE_ID,
1558                                    self.last_span,
1559                                    special_idents::invalid)
1560         };
1561
1562         let t = self.parse_ty(true);
1563
1564         Arg {
1565             ty: t,
1566             pat: pat,
1567             id: ast::DUMMY_NODE_ID,
1568         }
1569     }
1570
1571     /// Parse a single function argument
1572     pub fn parse_arg(&mut self) -> Arg {
1573         self.parse_arg_general(true)
1574     }
1575
1576     /// Parse an argument in a lambda header e.g. |arg, arg|
1577     pub fn parse_fn_block_arg(&mut self) -> Arg {
1578         let pat = self.parse_pat();
1579         let t = if self.eat(&token::COLON) {
1580             self.parse_ty(true)
1581         } else {
1582             P(Ty {
1583                 id: ast::DUMMY_NODE_ID,
1584                 node: TyInfer,
1585                 span: mk_sp(self.span.lo, self.span.hi),
1586             })
1587         };
1588         Arg {
1589             ty: t,
1590             pat: pat,
1591             id: ast::DUMMY_NODE_ID
1592         }
1593     }
1594
1595     pub fn maybe_parse_fixed_vstore(&mut self) -> Option<Gc<ast::Expr>> {
1596         if self.token == token::COMMA &&
1597                 self.look_ahead(1, |t| *t == token::DOTDOT) {
1598             self.bump();
1599             self.bump();
1600             Some(self.parse_expr())
1601         } else {
1602             None
1603         }
1604     }
1605
1606     /// Matches token_lit = LIT_INTEGER | ...
1607     pub fn lit_from_token(&mut self, tok: &token::Token) -> Lit_ {
1608         match *tok {
1609             token::LIT_BYTE(i) => LitByte(parse::byte_lit(i.as_str()).val0()),
1610             token::LIT_CHAR(i) => LitChar(parse::char_lit(i.as_str()).val0()),
1611             token::LIT_INTEGER(s) => parse::integer_lit(s.as_str(),
1612                                                         &self.sess.span_diagnostic, self.span),
1613             token::LIT_FLOAT(s) => parse::float_lit(s.as_str()),
1614             token::LIT_STR(s) => {
1615                 LitStr(token::intern_and_get_ident(parse::str_lit(s.as_str()).as_slice()),
1616                        ast::CookedStr)
1617             }
1618             token::LIT_STR_RAW(s, n) => {
1619                 LitStr(token::intern_and_get_ident(parse::raw_str_lit(s.as_str()).as_slice()),
1620                        ast::RawStr(n))
1621             }
1622             token::LIT_BINARY(i) =>
1623                 LitBinary(parse::binary_lit(i.as_str())),
1624             token::LIT_BINARY_RAW(i, _) =>
1625                 LitBinary(Rc::new(i.as_str().as_bytes().iter().map(|&x| x).collect())),
1626             token::LPAREN => { self.expect(&token::RPAREN); LitNil },
1627             _ => { self.unexpected_last(tok); }
1628         }
1629     }
1630
1631     /// Matches lit = true | false | token_lit
1632     pub fn parse_lit(&mut self) -> Lit {
1633         let lo = self.span.lo;
1634         let lit = if self.eat_keyword(keywords::True) {
1635             LitBool(true)
1636         } else if self.eat_keyword(keywords::False) {
1637             LitBool(false)
1638         } else {
1639             let token = self.bump_and_get();
1640             let lit = self.lit_from_token(&token);
1641             lit
1642         };
1643         codemap::Spanned { node: lit, span: mk_sp(lo, self.last_span.hi) }
1644     }
1645
1646     /// matches '-' lit | lit
1647     pub fn parse_literal_maybe_minus(&mut self) -> Gc<Expr> {
1648         let minus_lo = self.span.lo;
1649         let minus_present = self.eat(&token::BINOP(token::MINUS));
1650
1651         let lo = self.span.lo;
1652         let literal = box(GC) self.parse_lit();
1653         let hi = self.span.hi;
1654         let expr = self.mk_expr(lo, hi, ExprLit(literal));
1655
1656         if minus_present {
1657             let minus_hi = self.span.hi;
1658             let unary = self.mk_unary(UnNeg, expr);
1659             self.mk_expr(minus_lo, minus_hi, unary)
1660         } else {
1661             expr
1662         }
1663     }
1664
1665     /// Parses a path and optional type parameter bounds, depending on the
1666     /// mode. The `mode` parameter determines whether lifetimes, types, and/or
1667     /// bounds are permitted and whether `::` must precede type parameter
1668     /// groups.
1669     pub fn parse_path(&mut self, mode: PathParsingMode) -> PathAndBounds {
1670         // Check for a whole path...
1671         let found = match self.token {
1672             INTERPOLATED(token::NtPath(_)) => Some(self.bump_and_get()),
1673             _ => None,
1674         };
1675         match found {
1676             Some(INTERPOLATED(token::NtPath(box path))) => {
1677                 return PathAndBounds {
1678                     path: path,
1679                     bounds: None
1680                 }
1681             }
1682             _ => {}
1683         }
1684
1685         let lo = self.span.lo;
1686         let is_global = self.eat(&token::MOD_SEP);
1687
1688         // Parse any number of segments and bound sets. A segment is an
1689         // identifier followed by an optional lifetime and a set of types.
1690         // A bound set is a set of type parameter bounds.
1691         let mut segments = Vec::new();
1692         loop {
1693             // First, parse an identifier.
1694             let identifier = self.parse_ident();
1695
1696             // Parse the '::' before type parameters if it's required. If
1697             // it is required and wasn't present, then we're done.
1698             if mode == LifetimeAndTypesWithColons &&
1699                     !self.eat(&token::MOD_SEP) {
1700                 segments.push(ast::PathSegment {
1701                     identifier: identifier,
1702                     lifetimes: Vec::new(),
1703                     types: OwnedSlice::empty(),
1704                 });
1705                 break
1706             }
1707
1708             // Parse the `<` before the lifetime and types, if applicable.
1709             let (any_lifetime_or_types, lifetimes, types) = {
1710                 if mode != NoTypesAllowed && self.eat_lt(false) {
1711                     let (lifetimes, types) =
1712                         self.parse_generic_values_after_lt();
1713                     (true, lifetimes, OwnedSlice::from_vec(types))
1714                 } else {
1715                     (false, Vec::new(), OwnedSlice::empty())
1716                 }
1717             };
1718
1719             // Assemble and push the result.
1720             segments.push(ast::PathSegment {
1721                 identifier: identifier,
1722                 lifetimes: lifetimes,
1723                 types: types,
1724             });
1725
1726             // We're done if we don't see a '::', unless the mode required
1727             // a double colon to get here in the first place.
1728             if !(mode == LifetimeAndTypesWithColons &&
1729                     !any_lifetime_or_types) {
1730                 if !self.eat(&token::MOD_SEP) {
1731                     break
1732                 }
1733             }
1734         }
1735
1736         // Next, parse a plus and bounded type parameters, if
1737         // applicable. We need to remember whether the separate was
1738         // present for later, because in some contexts it's a parse
1739         // error.
1740         let opt_bounds = {
1741             if mode == LifetimeAndTypesAndBounds &&
1742                 self.eat(&token::BINOP(token::PLUS))
1743             {
1744                 let bounds = self.parse_ty_param_bounds();
1745
1746                 // For some reason that I do not fully understand, we
1747                 // do not permit an empty list in the case where it is
1748                 // introduced by a `+`, but we do for `:` and other
1749                 // separators. -nmatsakis
1750                 if bounds.len() == 0 {
1751                     let last_span = self.last_span;
1752                     self.span_err(last_span,
1753                                   "at least one type parameter bound \
1754                                    must be specified");
1755                 }
1756
1757                 Some(bounds)
1758             } else {
1759                 None
1760             }
1761         };
1762
1763         // Assemble the span.
1764         let span = mk_sp(lo, self.last_span.hi);
1765
1766         // Assemble the result.
1767         PathAndBounds {
1768             path: ast::Path {
1769                 span: span,
1770                 global: is_global,
1771                 segments: segments,
1772             },
1773             bounds: opt_bounds,
1774         }
1775     }
1776
1777     /// parses 0 or 1 lifetime
1778     pub fn parse_opt_lifetime(&mut self) -> Option<ast::Lifetime> {
1779         match self.token {
1780             token::LIFETIME(..) => {
1781                 Some(self.parse_lifetime())
1782             }
1783             _ => {
1784                 None
1785             }
1786         }
1787     }
1788
1789     /// Parses a single lifetime
1790     /// Matches lifetime = LIFETIME
1791     pub fn parse_lifetime(&mut self) -> ast::Lifetime {
1792         match self.token {
1793             token::LIFETIME(i) => {
1794                 let span = self.span;
1795                 self.bump();
1796                 return ast::Lifetime {
1797                     id: ast::DUMMY_NODE_ID,
1798                     span: span,
1799                     name: i.name
1800                 };
1801             }
1802             _ => {
1803                 self.fatal(format!("expected a lifetime name").as_slice());
1804             }
1805         }
1806     }
1807
1808     pub fn parse_lifetime_defs(&mut self) -> Vec<ast::LifetimeDef> {
1809         /*!
1810          * Parses `lifetime_defs = [ lifetime_defs { ',' lifetime_defs } ]`
1811          * where `lifetime_def  = lifetime [':' lifetimes]`
1812          */
1813
1814         let mut res = Vec::new();
1815         loop {
1816             match self.token {
1817                 token::LIFETIME(_) => {
1818                     let lifetime = self.parse_lifetime();
1819                     let bounds =
1820                         if self.eat(&token::COLON) {
1821                             self.parse_lifetimes(token::BINOP(token::PLUS))
1822                         } else {
1823                             Vec::new()
1824                         };
1825                     res.push(ast::LifetimeDef { lifetime: lifetime,
1826                                                 bounds: bounds });
1827                 }
1828
1829                 _ => {
1830                     return res;
1831                 }
1832             }
1833
1834             match self.token {
1835                 token::COMMA => { self.bump(); }
1836                 token::GT => { return res; }
1837                 token::BINOP(token::SHR) => { return res; }
1838                 _ => {
1839                     let msg = format!("expected `,` or `>` after lifetime \
1840                                       name, got: {:?}",
1841                                       self.token);
1842                     self.fatal(msg.as_slice());
1843                 }
1844             }
1845         }
1846     }
1847
1848     // matches lifetimes = ( lifetime ) | ( lifetime , lifetimes )
1849     // actually, it matches the empty one too, but putting that in there
1850     // messes up the grammar....
1851     pub fn parse_lifetimes(&mut self, sep: token::Token) -> Vec<ast::Lifetime> {
1852         /*!
1853          * Parses zero or more comma separated lifetimes.
1854          * Expects each lifetime to be followed by either
1855          * a comma or `>`.  Used when parsing type parameter
1856          * lists, where we expect something like `<'a, 'b, T>`.
1857          */
1858
1859         let mut res = Vec::new();
1860         loop {
1861             match self.token {
1862                 token::LIFETIME(_) => {
1863                     res.push(self.parse_lifetime());
1864                 }
1865                 _ => {
1866                     return res;
1867                 }
1868             }
1869
1870             if self.token != sep {
1871                 return res;
1872             }
1873
1874             self.bump();
1875         }
1876     }
1877
1878     pub fn token_is_mutability(tok: &token::Token) -> bool {
1879         token::is_keyword(keywords::Mut, tok) ||
1880         token::is_keyword(keywords::Const, tok)
1881     }
1882
1883     /// Parse mutability declaration (mut/const/imm)
1884     pub fn parse_mutability(&mut self) -> Mutability {
1885         if self.eat_keyword(keywords::Mut) {
1886             MutMutable
1887         } else {
1888             MutImmutable
1889         }
1890     }
1891
1892     /// Parse ident COLON expr
1893     pub fn parse_field(&mut self) -> Field {
1894         let lo = self.span.lo;
1895         let i = self.parse_ident();
1896         let hi = self.last_span.hi;
1897         self.expect(&token::COLON);
1898         let e = self.parse_expr();
1899         ast::Field {
1900             ident: spanned(lo, hi, i),
1901             expr: e,
1902             span: mk_sp(lo, e.span.hi),
1903         }
1904     }
1905
1906     pub fn mk_expr(&mut self, lo: BytePos, hi: BytePos, node: Expr_) -> Gc<Expr> {
1907         box(GC) Expr {
1908             id: ast::DUMMY_NODE_ID,
1909             node: node,
1910             span: mk_sp(lo, hi),
1911         }
1912     }
1913
1914     pub fn mk_unary(&mut self, unop: ast::UnOp, expr: Gc<Expr>) -> ast::Expr_ {
1915         ExprUnary(unop, expr)
1916     }
1917
1918     pub fn mk_binary(&mut self, binop: ast::BinOp,
1919                      lhs: Gc<Expr>, rhs: Gc<Expr>) -> ast::Expr_ {
1920         ExprBinary(binop, lhs, rhs)
1921     }
1922
1923     pub fn mk_call(&mut self, f: Gc<Expr>, args: Vec<Gc<Expr>>) -> ast::Expr_ {
1924         ExprCall(f, args)
1925     }
1926
1927     fn mk_method_call(&mut self,
1928                       ident: ast::SpannedIdent,
1929                       tps: Vec<P<Ty>>,
1930                       args: Vec<Gc<Expr>>)
1931                       -> ast::Expr_ {
1932         ExprMethodCall(ident, tps, args)
1933     }
1934
1935     pub fn mk_index(&mut self, expr: Gc<Expr>, idx: Gc<Expr>) -> ast::Expr_ {
1936         ExprIndex(expr, idx)
1937     }
1938
1939     pub fn mk_field(&mut self, expr: Gc<Expr>, ident: ast::SpannedIdent,
1940                     tys: Vec<P<Ty>>) -> ast::Expr_ {
1941         ExprField(expr, ident, tys)
1942     }
1943
1944     pub fn mk_assign_op(&mut self, binop: ast::BinOp,
1945                         lhs: Gc<Expr>, rhs: Gc<Expr>) -> ast::Expr_ {
1946         ExprAssignOp(binop, lhs, rhs)
1947     }
1948
1949     pub fn mk_mac_expr(&mut self, lo: BytePos, hi: BytePos, m: Mac_) -> Gc<Expr> {
1950         box(GC) Expr {
1951             id: ast::DUMMY_NODE_ID,
1952             node: ExprMac(codemap::Spanned {node: m, span: mk_sp(lo, hi)}),
1953             span: mk_sp(lo, hi),
1954         }
1955     }
1956
1957     pub fn mk_lit_u32(&mut self, i: u32) -> Gc<Expr> {
1958         let span = &self.span;
1959         let lv_lit = box(GC) codemap::Spanned {
1960             node: LitInt(i as u64, ast::UnsignedIntLit(TyU32)),
1961             span: *span
1962         };
1963
1964         box(GC) Expr {
1965             id: ast::DUMMY_NODE_ID,
1966             node: ExprLit(lv_lit),
1967             span: *span,
1968         }
1969     }
1970
1971     /// At the bottom (top?) of the precedence hierarchy,
1972     /// parse things like parenthesized exprs,
1973     /// macros, return, etc.
1974     pub fn parse_bottom_expr(&mut self) -> Gc<Expr> {
1975         maybe_whole_expr!(self);
1976
1977         let lo = self.span.lo;
1978         let mut hi = self.span.hi;
1979
1980         let ex: Expr_;
1981
1982         match self.token {
1983             token::LPAREN => {
1984                 self.bump();
1985                 // (e) is parenthesized e
1986                 // (e,) is a tuple with only one field, e
1987                 let mut trailing_comma = false;
1988                 if self.token == token::RPAREN {
1989                     hi = self.span.hi;
1990                     self.bump();
1991                     let lit = box(GC) spanned(lo, hi, LitNil);
1992                     return self.mk_expr(lo, hi, ExprLit(lit));
1993                 }
1994                 let mut es = vec!(self.parse_expr());
1995                 self.commit_expr(*es.last().unwrap(), &[], &[token::COMMA, token::RPAREN]);
1996                 while self.token == token::COMMA {
1997                     self.bump();
1998                     if self.token != token::RPAREN {
1999                         es.push(self.parse_expr());
2000                         self.commit_expr(*es.last().unwrap(), &[], &[token::COMMA, token::RPAREN]);
2001                     }
2002                         else {
2003                         trailing_comma = true;
2004                     }
2005                 }
2006                 hi = self.span.hi;
2007                 self.commit_expr_expecting(*es.last().unwrap(), token::RPAREN);
2008
2009                 return if es.len() == 1 && !trailing_comma {
2010                     self.mk_expr(lo, hi, ExprParen(*es.get(0)))
2011                 }
2012                     else {
2013                     self.mk_expr(lo, hi, ExprTup(es))
2014                 }
2015             },
2016             token::LBRACE => {
2017                 self.bump();
2018                 let blk = self.parse_block_tail(lo, DefaultBlock);
2019                 return self.mk_expr(blk.span.lo, blk.span.hi,
2020                                     ExprBlock(blk));
2021             },
2022             token::BINOP(token::OR) |  token::OROR => {
2023                 return self.parse_lambda_expr(CaptureByValue);
2024             },
2025             // FIXME #13626: Should be able to stick in
2026             // token::SELF_KEYWORD_NAME
2027             token::IDENT(id @ ast::Ident{
2028                         name: ast::Name(token::SELF_KEYWORD_NAME_NUM),
2029                         ctxt: _
2030                     } ,false) => {
2031                 self.bump();
2032                 let path = ast_util::ident_to_path(mk_sp(lo, hi), id);
2033                 ex = ExprPath(path);
2034                 hi = self.last_span.hi;
2035             }
2036             token::LBRACKET => {
2037                 self.bump();
2038
2039                 if self.token == token::RBRACKET {
2040                     // Empty vector.
2041                     self.bump();
2042                     ex = ExprVec(Vec::new());
2043                 } else {
2044                     // Nonempty vector.
2045                     let first_expr = self.parse_expr();
2046                     if self.token == token::COMMA &&
2047                         self.look_ahead(1, |t| *t == token::DOTDOT) {
2048                         // Repeating vector syntax: [ 0, ..512 ]
2049                         self.bump();
2050                         self.bump();
2051                         let count = self.parse_expr();
2052                         self.expect(&token::RBRACKET);
2053                         ex = ExprRepeat(first_expr, count);
2054                     } else if self.token == token::COMMA {
2055                         // Vector with two or more elements.
2056                         self.bump();
2057                         let remaining_exprs = self.parse_seq_to_end(
2058                             &token::RBRACKET,
2059                             seq_sep_trailing_allowed(token::COMMA),
2060                             |p| p.parse_expr()
2061                                 );
2062                         let mut exprs = vec!(first_expr);
2063                         exprs.push_all_move(remaining_exprs);
2064                         ex = ExprVec(exprs);
2065                     } else {
2066                         // Vector with one element.
2067                         self.expect(&token::RBRACKET);
2068                         ex = ExprVec(vec!(first_expr));
2069                     }
2070                 }
2071                 hi = self.last_span.hi;
2072             },
2073             _ => {
2074                 if self.eat_keyword(keywords::Ref) {
2075                     return self.parse_lambda_expr(CaptureByRef);
2076                 }
2077                 if self.eat_keyword(keywords::Proc) {
2078                     let decl = self.parse_proc_decl();
2079                     let body = self.parse_expr();
2080                     let fakeblock = P(ast::Block {
2081                             view_items: Vec::new(),
2082                             stmts: Vec::new(),
2083                             expr: Some(body),
2084                             id: ast::DUMMY_NODE_ID,
2085                             rules: DefaultBlock,
2086                             span: body.span,
2087                         });
2088                     return self.mk_expr(lo, body.span.hi, ExprProc(decl, fakeblock));
2089                 }
2090                 if self.eat_keyword(keywords::If) {
2091                     return self.parse_if_expr();
2092                 }
2093                 if self.eat_keyword(keywords::For) {
2094                     return self.parse_for_expr(None);
2095                 }
2096                 if self.eat_keyword(keywords::While) {
2097                     return self.parse_while_expr(None);
2098                 }
2099                 if Parser::token_is_lifetime(&self.token) {
2100                     let lifetime = self.get_lifetime();
2101                     self.bump();
2102                     self.expect(&token::COLON);
2103                     if self.eat_keyword(keywords::While) {
2104                         return self.parse_while_expr(Some(lifetime))
2105                     }
2106                     if self.eat_keyword(keywords::For) {
2107                         return self.parse_for_expr(Some(lifetime))
2108                     }
2109                     if self.eat_keyword(keywords::Loop) {
2110                         return self.parse_loop_expr(Some(lifetime))
2111                     }
2112                     self.fatal("expected `while`, `for`, or `loop` after a label")
2113                 }
2114                 if self.eat_keyword(keywords::Loop) {
2115                     return self.parse_loop_expr(None);
2116                 }
2117                 if self.eat_keyword(keywords::Continue) {
2118                     let lo = self.span.lo;
2119                     let ex = if Parser::token_is_lifetime(&self.token) {
2120                         let lifetime = self.get_lifetime();
2121                         self.bump();
2122                         ExprAgain(Some(lifetime))
2123                     } else {
2124                         ExprAgain(None)
2125                     };
2126                     let hi = self.span.hi;
2127                     return self.mk_expr(lo, hi, ex);
2128                 }
2129                 if self.eat_keyword(keywords::Match) {
2130                     return self.parse_match_expr();
2131                 }
2132                 if self.eat_keyword(keywords::Unsafe) {
2133                     return self.parse_block_expr(
2134                         lo,
2135                         UnsafeBlock(ast::UserProvided));
2136                 }
2137                 if self.eat_keyword(keywords::Return) {
2138                     // RETURN expression
2139                     if can_begin_expr(&self.token) {
2140                         let e = self.parse_expr();
2141                         hi = e.span.hi;
2142                         ex = ExprRet(Some(e));
2143                     } else {
2144                         ex = ExprRet(None);
2145                     }
2146                 } else if self.eat_keyword(keywords::Break) {
2147                     // BREAK expression
2148                     if Parser::token_is_lifetime(&self.token) {
2149                         let lifetime = self.get_lifetime();
2150                         self.bump();
2151                         ex = ExprBreak(Some(lifetime));
2152                     } else {
2153                         ex = ExprBreak(None);
2154                     }
2155                     hi = self.span.hi;
2156                 } else if self.token == token::MOD_SEP ||
2157                         is_ident(&self.token) &&
2158                         !self.is_keyword(keywords::True) &&
2159                         !self.is_keyword(keywords::False) {
2160                     let pth =
2161                         self.parse_path(LifetimeAndTypesWithColons).path;
2162
2163                     // `!`, as an operator, is prefix, so we know this isn't that
2164                     if self.token == token::NOT {
2165                         // MACRO INVOCATION expression
2166                         self.bump();
2167
2168                         let ket = token::close_delimiter_for(&self.token)
2169                             .unwrap_or_else(|| {
2170                                 self.fatal("expected open delimiter")
2171                             });
2172                         self.bump();
2173
2174                         let tts = self.parse_seq_to_end(
2175                             &ket,
2176                             seq_sep_none(),
2177                             |p| p.parse_token_tree());
2178                         let hi = self.span.hi;
2179
2180                         return self.mk_mac_expr(lo,
2181                                                 hi,
2182                                                 MacInvocTT(pth,
2183                                                            tts,
2184                                                            EMPTY_CTXT));
2185                     }
2186                     if self.token == token::LBRACE {
2187                         // This is a struct literal, unless we're prohibited
2188                         // from parsing struct literals here.
2189                         if self.restriction != RESTRICT_NO_STRUCT_LITERAL {
2190                             // It's a struct literal.
2191                             self.bump();
2192                             let mut fields = Vec::new();
2193                             let mut base = None;
2194
2195                             while self.token != token::RBRACE {
2196                                 if self.eat(&token::DOTDOT) {
2197                                     base = Some(self.parse_expr());
2198                                     break;
2199                                 }
2200
2201                                 fields.push(self.parse_field());
2202                                 self.commit_expr(fields.last().unwrap().expr,
2203                                                  &[token::COMMA],
2204                                                  &[token::RBRACE]);
2205                             }
2206
2207                             if fields.len() == 0 && base.is_none() {
2208                                 let last_span = self.last_span;
2209                                 self.span_err(last_span,
2210                                               "structure literal must either \
2211                                               have at least one field or use \
2212                                               functional structure update \
2213                                               syntax");
2214                             }
2215
2216                             hi = self.span.hi;
2217                             self.expect(&token::RBRACE);
2218                             ex = ExprStruct(pth, fields, base);
2219                             return self.mk_expr(lo, hi, ex);
2220                         }
2221                     }
2222
2223                     hi = pth.span.hi;
2224                     ex = ExprPath(pth);
2225                 } else {
2226                     // other literal expression
2227                     let lit = self.parse_lit();
2228                     hi = lit.span.hi;
2229                     ex = ExprLit(box(GC) lit);
2230                 }
2231             }
2232         }
2233
2234         return self.mk_expr(lo, hi, ex);
2235     }
2236
2237     /// Parse a block or unsafe block
2238     pub fn parse_block_expr(&mut self, lo: BytePos, blk_mode: BlockCheckMode)
2239                             -> Gc<Expr> {
2240         self.expect(&token::LBRACE);
2241         let blk = self.parse_block_tail(lo, blk_mode);
2242         return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk));
2243     }
2244
2245     /// parse a.b or a(13) or a[4] or just a
2246     pub fn parse_dot_or_call_expr(&mut self) -> Gc<Expr> {
2247         let b = self.parse_bottom_expr();
2248         self.parse_dot_or_call_expr_with(b)
2249     }
2250
2251     pub fn parse_dot_or_call_expr_with(&mut self, e0: Gc<Expr>) -> Gc<Expr> {
2252         let mut e = e0;
2253         let lo = e.span.lo;
2254         let mut hi;
2255         loop {
2256             // expr.f
2257             if self.eat(&token::DOT) {
2258                 match self.token {
2259                   token::IDENT(i, _) => {
2260                     let dot = self.last_span.hi;
2261                     hi = self.span.hi;
2262                     self.bump();
2263                     let (_, tys) = if self.eat(&token::MOD_SEP) {
2264                         self.expect_lt();
2265                         self.parse_generic_values_after_lt()
2266                     } else {
2267                         (Vec::new(), Vec::new())
2268                     };
2269
2270                     // expr.f() method call
2271                     match self.token {
2272                         token::LPAREN => {
2273                             let mut es = self.parse_unspanned_seq(
2274                                 &token::LPAREN,
2275                                 &token::RPAREN,
2276                                 seq_sep_trailing_allowed(token::COMMA),
2277                                 |p| p.parse_expr()
2278                             );
2279                             hi = self.last_span.hi;
2280
2281                             es.unshift(e);
2282                             let id = spanned(dot, hi, i);
2283                             let nd = self.mk_method_call(id, tys, es);
2284                             e = self.mk_expr(lo, hi, nd);
2285                         }
2286                         _ => {
2287                             let id = spanned(dot, hi, i);
2288                             let field = self.mk_field(e, id, tys);
2289                             e = self.mk_expr(lo, hi, field)
2290                         }
2291                     }
2292                   }
2293                   _ => self.unexpected()
2294                 }
2295                 continue;
2296             }
2297             if self.expr_is_complete(e) { break; }
2298             match self.token {
2299               // expr(...)
2300               token::LPAREN => {
2301                 let es = self.parse_unspanned_seq(
2302                     &token::LPAREN,
2303                     &token::RPAREN,
2304                     seq_sep_trailing_allowed(token::COMMA),
2305                     |p| p.parse_expr()
2306                 );
2307                 hi = self.last_span.hi;
2308
2309                 let nd = self.mk_call(e, es);
2310                 e = self.mk_expr(lo, hi, nd);
2311               }
2312
2313               // expr[...]
2314               token::LBRACKET => {
2315                 self.bump();
2316                 let ix = self.parse_expr();
2317                 hi = self.span.hi;
2318                 self.commit_expr_expecting(ix, token::RBRACKET);
2319                 let index = self.mk_index(e, ix);
2320                 e = self.mk_expr(lo, hi, index)
2321               }
2322
2323               _ => return e
2324             }
2325         }
2326         return e;
2327     }
2328
2329     /// Parse an optional separator followed by a kleene-style
2330     /// repetition token (+ or *).
2331     pub fn parse_sep_and_zerok(&mut self) -> (Option<token::Token>, bool) {
2332         fn parse_zerok(parser: &mut Parser) -> Option<bool> {
2333             match parser.token {
2334                 token::BINOP(token::STAR) | token::BINOP(token::PLUS) => {
2335                     let zerok = parser.token == token::BINOP(token::STAR);
2336                     parser.bump();
2337                     Some(zerok)
2338                 },
2339                 _ => None
2340             }
2341         };
2342
2343         match parse_zerok(self) {
2344             Some(zerok) => return (None, zerok),
2345             None => {}
2346         }
2347
2348         let separator = self.bump_and_get();
2349         match parse_zerok(self) {
2350             Some(zerok) => (Some(separator), zerok),
2351             None => self.fatal("expected `*` or `+`")
2352         }
2353     }
2354
2355     /// parse a single token tree from the input.
2356     pub fn parse_token_tree(&mut self) -> TokenTree {
2357         // FIXME #6994: currently, this is too eager. It
2358         // parses token trees but also identifies TTSeq's
2359         // and TTNonterminal's; it's too early to know yet
2360         // whether something will be a nonterminal or a seq
2361         // yet.
2362         maybe_whole!(deref self, NtTT);
2363
2364         // this is the fall-through for the 'match' below.
2365         // invariants: the current token is not a left-delimiter,
2366         // not an EOF, and not the desired right-delimiter (if
2367         // it were, parse_seq_to_before_end would have prevented
2368         // reaching this point.
2369         fn parse_non_delim_tt_tok(p: &mut Parser) -> TokenTree {
2370             maybe_whole!(deref p, NtTT);
2371             match p.token {
2372               token::RPAREN | token::RBRACE | token::RBRACKET => {
2373                   // This is a conservative error: only report the last unclosed delimiter. The
2374                   // previous unclosed delimiters could actually be closed! The parser just hasn't
2375                   // gotten to them yet.
2376                   match p.open_braces.last() {
2377                       None => {}
2378                       Some(&sp) => p.span_note(sp, "unclosed delimiter"),
2379                   };
2380                   let token_str = p.this_token_to_string();
2381                   p.fatal(format!("incorrect close delimiter: `{}`",
2382                                   token_str).as_slice())
2383               },
2384               /* we ought to allow different depths of unquotation */
2385               token::DOLLAR if p.quote_depth > 0u => {
2386                 p.bump();
2387                 let sp = p.span;
2388
2389                 if p.token == token::LPAREN {
2390                     let seq = p.parse_seq(
2391                         &token::LPAREN,
2392                         &token::RPAREN,
2393                         seq_sep_none(),
2394                         |p| p.parse_token_tree()
2395                     );
2396                     let (s, z) = p.parse_sep_and_zerok();
2397                     let seq = match seq {
2398                         Spanned { node, .. } => node,
2399                     };
2400                     TTSeq(mk_sp(sp.lo, p.span.hi), Rc::new(seq), s, z)
2401                 } else {
2402                     TTNonterminal(sp, p.parse_ident())
2403                 }
2404               }
2405               _ => {
2406                   parse_any_tt_tok(p)
2407               }
2408             }
2409         }
2410
2411         // turn the next token into a TTTok:
2412         fn parse_any_tt_tok(p: &mut Parser) -> TokenTree {
2413             TTTok(p.span, p.bump_and_get())
2414         }
2415
2416         match (&self.token, token::close_delimiter_for(&self.token)) {
2417             (&token::EOF, _) => {
2418                 let open_braces = self.open_braces.clone();
2419                 for sp in open_braces.iter() {
2420                     self.span_note(*sp, "Did you mean to close this delimiter?");
2421                 }
2422                 // There shouldn't really be a span, but it's easier for the test runner
2423                 // if we give it one
2424                 self.fatal("this file contains an un-closed delimiter ");
2425             }
2426             (_, Some(close_delim)) => {
2427                 // Parse the open delimiter.
2428                 self.open_braces.push(self.span);
2429                 let mut result = vec!(parse_any_tt_tok(self));
2430
2431                 let trees =
2432                     self.parse_seq_to_before_end(&close_delim,
2433                                                  seq_sep_none(),
2434                                                  |p| p.parse_token_tree());
2435                 result.push_all_move(trees);
2436
2437                 // Parse the close delimiter.
2438                 result.push(parse_any_tt_tok(self));
2439                 self.open_braces.pop().unwrap();
2440
2441                 TTDelim(Rc::new(result))
2442             }
2443             _ => parse_non_delim_tt_tok(self)
2444         }
2445     }
2446
2447     // parse a stream of tokens into a list of TokenTree's,
2448     // up to EOF.
2449     pub fn parse_all_token_trees(&mut self) -> Vec<TokenTree> {
2450         let mut tts = Vec::new();
2451         while self.token != token::EOF {
2452             tts.push(self.parse_token_tree());
2453         }
2454         tts
2455     }
2456
2457     pub fn parse_matchers(&mut self) -> Vec<Matcher> {
2458         // unification of Matcher's and TokenTree's would vastly improve
2459         // the interpolation of Matcher's
2460         maybe_whole!(self, NtMatchers);
2461         let mut name_idx = 0u;
2462         match token::close_delimiter_for(&self.token) {
2463             Some(other_delimiter) => {
2464                 self.bump();
2465                 self.parse_matcher_subseq_upto(&mut name_idx, &other_delimiter)
2466             }
2467             None => self.fatal("expected open delimiter")
2468         }
2469     }
2470
2471     /// This goofy function is necessary to correctly match parens in Matcher's.
2472     /// Otherwise, `$( ( )` would be a valid Matcher, and `$( () )` would be
2473     /// invalid. It's similar to common::parse_seq.
2474     pub fn parse_matcher_subseq_upto(&mut self,
2475                                      name_idx: &mut uint,
2476                                      ket: &token::Token)
2477                                      -> Vec<Matcher> {
2478         let mut ret_val = Vec::new();
2479         let mut lparens = 0u;
2480
2481         while self.token != *ket || lparens > 0u {
2482             if self.token == token::LPAREN { lparens += 1u; }
2483             if self.token == token::RPAREN { lparens -= 1u; }
2484             ret_val.push(self.parse_matcher(name_idx));
2485         }
2486
2487         self.bump();
2488
2489         return ret_val;
2490     }
2491
2492     pub fn parse_matcher(&mut self, name_idx: &mut uint) -> Matcher {
2493         let lo = self.span.lo;
2494
2495         let m = if self.token == token::DOLLAR {
2496             self.bump();
2497             if self.token == token::LPAREN {
2498                 let name_idx_lo = *name_idx;
2499                 self.bump();
2500                 let ms = self.parse_matcher_subseq_upto(name_idx,
2501                                                         &token::RPAREN);
2502                 if ms.len() == 0u {
2503                     self.fatal("repetition body must be nonempty");
2504                 }
2505                 let (sep, zerok) = self.parse_sep_and_zerok();
2506                 MatchSeq(ms, sep, zerok, name_idx_lo, *name_idx)
2507             } else {
2508                 let bound_to = self.parse_ident();
2509                 self.expect(&token::COLON);
2510                 let nt_name = self.parse_ident();
2511                 let m = MatchNonterminal(bound_to, nt_name, *name_idx);
2512                 *name_idx += 1;
2513                 m
2514             }
2515         } else {
2516             MatchTok(self.bump_and_get())
2517         };
2518
2519         return spanned(lo, self.span.hi, m);
2520     }
2521
2522     /// Parse a prefix-operator expr
2523     pub fn parse_prefix_expr(&mut self) -> Gc<Expr> {
2524         let lo = self.span.lo;
2525         let hi;
2526
2527         let ex;
2528         match self.token {
2529           token::NOT => {
2530             self.bump();
2531             let e = self.parse_prefix_expr();
2532             hi = e.span.hi;
2533             ex = self.mk_unary(UnNot, e);
2534           }
2535           token::BINOP(token::MINUS) => {
2536             self.bump();
2537             let e = self.parse_prefix_expr();
2538             hi = e.span.hi;
2539             ex = self.mk_unary(UnNeg, e);
2540           }
2541           token::BINOP(token::STAR) => {
2542             self.bump();
2543             let e = self.parse_prefix_expr();
2544             hi = e.span.hi;
2545             ex = self.mk_unary(UnDeref, e);
2546           }
2547           token::BINOP(token::AND) | token::ANDAND => {
2548             self.expect_and();
2549             let m = self.parse_mutability();
2550             let e = self.parse_prefix_expr();
2551             hi = e.span.hi;
2552             ex = ExprAddrOf(m, e);
2553           }
2554           token::AT => {
2555             self.bump();
2556             let span = self.last_span;
2557             self.obsolete(span, ObsoleteManagedExpr);
2558             let e = self.parse_prefix_expr();
2559             hi = e.span.hi;
2560             ex = self.mk_unary(UnBox, e);
2561           }
2562           token::TILDE => {
2563             self.bump();
2564             let span = self.last_span;
2565             match self.token {
2566                 token::LIT_STR(_) => {
2567                     // This is OK (for now).
2568                 }
2569                 token::LBRACKET => {}   // Also OK.
2570                 _ => self.obsolete(span, ObsoleteOwnedExpr)
2571             }
2572
2573             let e = self.parse_prefix_expr();
2574             hi = e.span.hi;
2575             ex = self.mk_unary(UnUniq, e);
2576           }
2577           token::IDENT(_, _) => {
2578             if !self.is_keyword(keywords::Box) {
2579                 return self.parse_dot_or_call_expr();
2580             }
2581
2582             self.bump();
2583
2584             // Check for a place: `box(PLACE) EXPR`.
2585             if self.eat(&token::LPAREN) {
2586                 // Support `box() EXPR` as the default.
2587                 if !self.eat(&token::RPAREN) {
2588                     let place = self.parse_expr();
2589                     self.expect(&token::RPAREN);
2590                     let subexpression = self.parse_prefix_expr();
2591                     hi = subexpression.span.hi;
2592                     ex = ExprBox(place, subexpression);
2593                     return self.mk_expr(lo, hi, ex);
2594                 }
2595             }
2596
2597             // Otherwise, we use the unique pointer default.
2598             let subexpression = self.parse_prefix_expr();
2599             hi = subexpression.span.hi;
2600             ex = self.mk_unary(UnUniq, subexpression);
2601           }
2602           _ => return self.parse_dot_or_call_expr()
2603         }
2604         return self.mk_expr(lo, hi, ex);
2605     }
2606
2607     /// Parse an expression of binops
2608     pub fn parse_binops(&mut self) -> Gc<Expr> {
2609         let prefix_expr = self.parse_prefix_expr();
2610         self.parse_more_binops(prefix_expr, 0)
2611     }
2612
2613     /// Parse an expression of binops of at least min_prec precedence
2614     pub fn parse_more_binops(&mut self, lhs: Gc<Expr>,
2615                              min_prec: uint) -> Gc<Expr> {
2616         if self.expr_is_complete(lhs) { return lhs; }
2617
2618         // Prevent dynamic borrow errors later on by limiting the
2619         // scope of the borrows.
2620         {
2621             let token: &token::Token = &self.token;
2622             let restriction: &restriction = &self.restriction;
2623             match (token, restriction) {
2624                 (&token::BINOP(token::OR), &RESTRICT_NO_BAR_OP) => return lhs,
2625                 (&token::BINOP(token::OR),
2626                  &RESTRICT_NO_BAR_OR_DOUBLEBAR_OP) => return lhs,
2627                 (&token::OROR, &RESTRICT_NO_BAR_OR_DOUBLEBAR_OP) => return lhs,
2628                 _ => { }
2629             }
2630         }
2631
2632         let cur_opt = token_to_binop(&self.token);
2633         match cur_opt {
2634             Some(cur_op) => {
2635                 let cur_prec = operator_prec(cur_op);
2636                 if cur_prec > min_prec {
2637                     self.bump();
2638                     let expr = self.parse_prefix_expr();
2639                     let rhs = self.parse_more_binops(expr, cur_prec);
2640                     let binary = self.mk_binary(cur_op, lhs, rhs);
2641                     let bin = self.mk_expr(lhs.span.lo, rhs.span.hi, binary);
2642                     self.parse_more_binops(bin, min_prec)
2643                 } else {
2644                     lhs
2645                 }
2646             }
2647             None => {
2648                 if as_prec > min_prec && self.eat_keyword(keywords::As) {
2649                     let rhs = self.parse_ty(false);
2650                     let _as = self.mk_expr(lhs.span.lo,
2651                                            rhs.span.hi,
2652                                            ExprCast(lhs, rhs));
2653                     self.parse_more_binops(_as, min_prec)
2654                 } else {
2655                     lhs
2656                 }
2657             }
2658         }
2659     }
2660
2661     /// Parse an assignment expression....
2662     /// actually, this seems to be the main entry point for
2663     /// parsing an arbitrary expression.
2664     pub fn parse_assign_expr(&mut self) -> Gc<Expr> {
2665         let lo = self.span.lo;
2666         let lhs = self.parse_binops();
2667         match self.token {
2668           token::EQ => {
2669               self.bump();
2670               let rhs = self.parse_expr();
2671               self.mk_expr(lo, rhs.span.hi, ExprAssign(lhs, rhs))
2672           }
2673           token::BINOPEQ(op) => {
2674               self.bump();
2675               let rhs = self.parse_expr();
2676               let aop = match op {
2677                   token::PLUS =>    BiAdd,
2678                   token::MINUS =>   BiSub,
2679                   token::STAR =>    BiMul,
2680                   token::SLASH =>   BiDiv,
2681                   token::PERCENT => BiRem,
2682                   token::CARET =>   BiBitXor,
2683                   token::AND =>     BiBitAnd,
2684                   token::OR =>      BiBitOr,
2685                   token::SHL =>     BiShl,
2686                   token::SHR =>     BiShr
2687               };
2688               let assign_op = self.mk_assign_op(aop, lhs, rhs);
2689               self.mk_expr(lo, rhs.span.hi, assign_op)
2690           }
2691           _ => {
2692               lhs
2693           }
2694         }
2695     }
2696
2697     /// Parse an 'if' expression ('if' token already eaten)
2698     pub fn parse_if_expr(&mut self) -> Gc<Expr> {
2699         let lo = self.last_span.lo;
2700         let cond = self.parse_expr_res(RESTRICT_NO_STRUCT_LITERAL);
2701         let thn = self.parse_block();
2702         let mut els: Option<Gc<Expr>> = None;
2703         let mut hi = thn.span.hi;
2704         if self.eat_keyword(keywords::Else) {
2705             let elexpr = self.parse_else_expr();
2706             els = Some(elexpr);
2707             hi = elexpr.span.hi;
2708         }
2709         self.mk_expr(lo, hi, ExprIf(cond, thn, els))
2710     }
2711
2712     // `|args| expr`
2713     pub fn parse_lambda_expr(&mut self, capture_clause: CaptureClause)
2714                              -> Gc<Expr> {
2715         let lo = self.span.lo;
2716         let (decl, optional_unboxed_closure_kind) =
2717             self.parse_fn_block_decl();
2718         let body = self.parse_expr();
2719         let fakeblock = P(ast::Block {
2720             view_items: Vec::new(),
2721             stmts: Vec::new(),
2722             expr: Some(body),
2723             id: ast::DUMMY_NODE_ID,
2724             rules: DefaultBlock,
2725             span: body.span,
2726         });
2727
2728         match optional_unboxed_closure_kind {
2729             Some(unboxed_closure_kind) => {
2730                 self.mk_expr(lo,
2731                              body.span.hi,
2732                              ExprUnboxedFn(capture_clause,
2733                                            unboxed_closure_kind,
2734                                            decl,
2735                                            fakeblock))
2736             }
2737             None => {
2738                 self.mk_expr(lo,
2739                              body.span.hi,
2740                              ExprFnBlock(capture_clause, decl, fakeblock))
2741             }
2742         }
2743     }
2744
2745     pub fn parse_else_expr(&mut self) -> Gc<Expr> {
2746         if self.eat_keyword(keywords::If) {
2747             return self.parse_if_expr();
2748         } else {
2749             let blk = self.parse_block();
2750             return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk));
2751         }
2752     }
2753
2754     /// Parse a 'for' .. 'in' expression ('for' token already eaten)
2755     pub fn parse_for_expr(&mut self, opt_ident: Option<ast::Ident>) -> Gc<Expr> {
2756         // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
2757
2758         let lo = self.last_span.lo;
2759         let pat = self.parse_pat();
2760         self.expect_keyword(keywords::In);
2761         let expr = self.parse_expr_res(RESTRICT_NO_STRUCT_LITERAL);
2762         let loop_block = self.parse_block();
2763         let hi = self.span.hi;
2764
2765         self.mk_expr(lo, hi, ExprForLoop(pat, expr, loop_block, opt_ident))
2766     }
2767
2768     pub fn parse_while_expr(&mut self, opt_ident: Option<ast::Ident>) -> Gc<Expr> {
2769         let lo = self.last_span.lo;
2770         let cond = self.parse_expr_res(RESTRICT_NO_STRUCT_LITERAL);
2771         let body = self.parse_block();
2772         let hi = body.span.hi;
2773         return self.mk_expr(lo, hi, ExprWhile(cond, body, opt_ident));
2774     }
2775
2776     pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::Ident>) -> Gc<Expr> {
2777         let lo = self.last_span.lo;
2778         let body = self.parse_block();
2779         let hi = body.span.hi;
2780         self.mk_expr(lo, hi, ExprLoop(body, opt_ident))
2781     }
2782
2783     fn parse_match_expr(&mut self) -> Gc<Expr> {
2784         let lo = self.last_span.lo;
2785         let discriminant = self.parse_expr_res(RESTRICT_NO_STRUCT_LITERAL);
2786         self.commit_expr_expecting(discriminant, token::LBRACE);
2787         let mut arms: Vec<Arm> = Vec::new();
2788         while self.token != token::RBRACE {
2789             arms.push(self.parse_arm());
2790         }
2791         let hi = self.span.hi;
2792         self.bump();
2793         return self.mk_expr(lo, hi, ExprMatch(discriminant, arms));
2794     }
2795
2796     pub fn parse_arm(&mut self) -> Arm {
2797         let attrs = self.parse_outer_attributes();
2798         let pats = self.parse_pats();
2799         let mut guard = None;
2800         if self.eat_keyword(keywords::If) {
2801             guard = Some(self.parse_expr());
2802         }
2803         self.expect(&token::FAT_ARROW);
2804         let expr = self.parse_expr_res(RESTRICT_STMT_EXPR);
2805
2806         let require_comma =
2807             !classify::expr_is_simple_block(expr)
2808             && self.token != token::RBRACE;
2809
2810         if require_comma {
2811             self.commit_expr(expr, &[token::COMMA], &[token::RBRACE]);
2812         } else {
2813             self.eat(&token::COMMA);
2814         }
2815
2816         ast::Arm {
2817             attrs: attrs,
2818             pats: pats,
2819             guard: guard,
2820             body: expr,
2821         }
2822     }
2823
2824     /// Parse an expression
2825     pub fn parse_expr(&mut self) -> Gc<Expr> {
2826         return self.parse_expr_res(UNRESTRICTED);
2827     }
2828
2829     /// Parse an expression, subject to the given restriction
2830     pub fn parse_expr_res(&mut self, r: restriction) -> Gc<Expr> {
2831         let old = self.restriction;
2832         self.restriction = r;
2833         let e = self.parse_assign_expr();
2834         self.restriction = old;
2835         return e;
2836     }
2837
2838     /// Parse the RHS of a local variable declaration (e.g. '= 14;')
2839     fn parse_initializer(&mut self) -> Option<Gc<Expr>> {
2840         if self.token == token::EQ {
2841             self.bump();
2842             Some(self.parse_expr())
2843         } else {
2844             None
2845         }
2846     }
2847
2848     /// Parse patterns, separated by '|' s
2849     fn parse_pats(&mut self) -> Vec<Gc<Pat>> {
2850         let mut pats = Vec::new();
2851         loop {
2852             pats.push(self.parse_pat());
2853             if self.token == token::BINOP(token::OR) { self.bump(); }
2854             else { return pats; }
2855         };
2856     }
2857
2858     fn parse_pat_vec_elements(
2859         &mut self,
2860     ) -> (Vec<Gc<Pat>> , Option<Gc<Pat>>, Vec<Gc<Pat>> ) {
2861         let mut before = Vec::new();
2862         let mut slice = None;
2863         let mut after = Vec::new();
2864         let mut first = true;
2865         let mut before_slice = true;
2866
2867         while self.token != token::RBRACKET {
2868             if first { first = false; }
2869             else { self.expect(&token::COMMA); }
2870
2871             let mut is_slice = false;
2872             if before_slice {
2873                 if self.token == token::DOTDOT {
2874                     self.bump();
2875                     is_slice = true;
2876                     before_slice = false;
2877                 }
2878             }
2879
2880             if is_slice {
2881                 if self.token == token::COMMA || self.token == token::RBRACKET {
2882                     slice = Some(box(GC) ast::Pat {
2883                         id: ast::DUMMY_NODE_ID,
2884                         node: PatWild(PatWildMulti),
2885                         span: self.span,
2886                     })
2887                 } else {
2888                     let subpat = self.parse_pat();
2889                     match *subpat {
2890                         ast::Pat { node: PatIdent(_, _, _), .. } => {
2891                             slice = Some(subpat);
2892                         }
2893                         ast::Pat { span, .. } => self.span_fatal(
2894                             span, "expected an identifier or nothing"
2895                         )
2896                     }
2897                 }
2898             } else {
2899                 let subpat = self.parse_pat();
2900                 if before_slice {
2901                     before.push(subpat);
2902                 } else {
2903                     after.push(subpat);
2904                 }
2905             }
2906         }
2907
2908         (before, slice, after)
2909     }
2910
2911     /// Parse the fields of a struct-like pattern
2912     fn parse_pat_fields(&mut self) -> (Vec<ast::FieldPat> , bool) {
2913         let mut fields = Vec::new();
2914         let mut etc = false;
2915         let mut first = true;
2916         while self.token != token::RBRACE {
2917             if first {
2918                 first = false;
2919             } else {
2920                 self.expect(&token::COMMA);
2921                 // accept trailing commas
2922                 if self.token == token::RBRACE { break }
2923             }
2924
2925             if self.token == token::DOTDOT {
2926                 self.bump();
2927                 if self.token != token::RBRACE {
2928                     let token_str = self.this_token_to_string();
2929                     self.fatal(format!("expected `{}`, found `{}`", "}",
2930                                        token_str).as_slice())
2931                 }
2932                 etc = true;
2933                 break;
2934             }
2935
2936             let bind_type = if self.eat_keyword(keywords::Mut) {
2937                 BindByValue(MutMutable)
2938             } else if self.eat_keyword(keywords::Ref) {
2939                 BindByRef(self.parse_mutability())
2940             } else {
2941                 BindByValue(MutImmutable)
2942             };
2943
2944             let fieldname = self.parse_ident();
2945
2946             let subpat = if self.token == token::COLON {
2947                 match bind_type {
2948                     BindByRef(..) | BindByValue(MutMutable) => {
2949                         let token_str = self.this_token_to_string();
2950                         self.fatal(format!("unexpected `{}`",
2951                                            token_str).as_slice())
2952                     }
2953                     _ => {}
2954                 }
2955
2956                 self.bump();
2957                 self.parse_pat()
2958             } else {
2959                 let fieldpath = codemap::Spanned{span:self.last_span, node: fieldname};
2960                 box(GC) ast::Pat {
2961                     id: ast::DUMMY_NODE_ID,
2962                     node: PatIdent(bind_type, fieldpath, None),
2963                     span: self.last_span
2964                 }
2965             };
2966             fields.push(ast::FieldPat { ident: fieldname, pat: subpat });
2967         }
2968         return (fields, etc);
2969     }
2970
2971     /// Parse a pattern.
2972     pub fn parse_pat(&mut self) -> Gc<Pat> {
2973         maybe_whole!(self, NtPat);
2974
2975         let lo = self.span.lo;
2976         let mut hi;
2977         let pat;
2978         match self.token {
2979             // parse _
2980           token::UNDERSCORE => {
2981             self.bump();
2982             pat = PatWild(PatWildSingle);
2983             hi = self.last_span.hi;
2984             return box(GC) ast::Pat {
2985                 id: ast::DUMMY_NODE_ID,
2986                 node: pat,
2987                 span: mk_sp(lo, hi)
2988             }
2989           }
2990           token::TILDE => {
2991             // parse ~pat
2992             self.bump();
2993             let sub = self.parse_pat();
2994             pat = PatBox(sub);
2995             let last_span = self.last_span;
2996             hi = last_span.hi;
2997             self.obsolete(last_span, ObsoleteOwnedPattern);
2998             return box(GC) ast::Pat {
2999                 id: ast::DUMMY_NODE_ID,
3000                 node: pat,
3001                 span: mk_sp(lo, hi)
3002             }
3003           }
3004           token::BINOP(token::AND) | token::ANDAND => {
3005             // parse &pat
3006             let lo = self.span.lo;
3007             self.expect_and();
3008             let sub = self.parse_pat();
3009             pat = PatRegion(sub);
3010             hi = self.last_span.hi;
3011             return box(GC) ast::Pat {
3012                 id: ast::DUMMY_NODE_ID,
3013                 node: pat,
3014                 span: mk_sp(lo, hi)
3015             }
3016           }
3017           token::LPAREN => {
3018             // parse (pat,pat,pat,...) as tuple
3019             self.bump();
3020             if self.token == token::RPAREN {
3021                 hi = self.span.hi;
3022                 self.bump();
3023                 let lit = box(GC) codemap::Spanned {
3024                     node: LitNil,
3025                     span: mk_sp(lo, hi)};
3026                 let expr = self.mk_expr(lo, hi, ExprLit(lit));
3027                 pat = PatLit(expr);
3028             } else {
3029                 let mut fields = vec!(self.parse_pat());
3030                 if self.look_ahead(1, |t| *t != token::RPAREN) {
3031                     while self.token == token::COMMA {
3032                         self.bump();
3033                         if self.token == token::RPAREN { break; }
3034                         fields.push(self.parse_pat());
3035                     }
3036                 }
3037                 if fields.len() == 1 { self.expect(&token::COMMA); }
3038                 self.expect(&token::RPAREN);
3039                 pat = PatTup(fields);
3040             }
3041             hi = self.last_span.hi;
3042             return box(GC) ast::Pat {
3043                 id: ast::DUMMY_NODE_ID,
3044                 node: pat,
3045                 span: mk_sp(lo, hi)
3046             }
3047           }
3048           token::LBRACKET => {
3049             // parse [pat,pat,...] as vector pattern
3050             self.bump();
3051             let (before, slice, after) =
3052                 self.parse_pat_vec_elements();
3053
3054             self.expect(&token::RBRACKET);
3055             pat = ast::PatVec(before, slice, after);
3056             hi = self.last_span.hi;
3057             return box(GC) ast::Pat {
3058                 id: ast::DUMMY_NODE_ID,
3059                 node: pat,
3060                 span: mk_sp(lo, hi)
3061             }
3062           }
3063           _ => {}
3064         }
3065         // at this point, token != _, ~, &, &&, (, [
3066
3067         if (!is_ident_or_path(&self.token) && self.token != token::MOD_SEP)
3068                 || self.is_keyword(keywords::True)
3069                 || self.is_keyword(keywords::False) {
3070             // Parse an expression pattern or exp .. exp.
3071             //
3072             // These expressions are limited to literals (possibly
3073             // preceded by unary-minus) or identifiers.
3074             let val = self.parse_literal_maybe_minus();
3075             if self.eat(&token::DOTDOT) {
3076                 let end = if is_ident_or_path(&self.token) {
3077                     let path = self.parse_path(LifetimeAndTypesWithColons)
3078                                    .path;
3079                     let hi = self.span.hi;
3080                     self.mk_expr(lo, hi, ExprPath(path))
3081                 } else {
3082                     self.parse_literal_maybe_minus()
3083                 };
3084                 pat = PatRange(val, end);
3085             } else {
3086                 pat = PatLit(val);
3087             }
3088         } else if self.eat_keyword(keywords::Mut) {
3089             pat = self.parse_pat_ident(BindByValue(MutMutable));
3090         } else if self.eat_keyword(keywords::Ref) {
3091             // parse ref pat
3092             let mutbl = self.parse_mutability();
3093             pat = self.parse_pat_ident(BindByRef(mutbl));
3094         } else if self.eat_keyword(keywords::Box) {
3095             // `box PAT`
3096             //
3097             // FIXME(#13910): Rename to `PatBox` and extend to full DST
3098             // support.
3099             let sub = self.parse_pat();
3100             pat = PatBox(sub);
3101             hi = self.last_span.hi;
3102             return box(GC) ast::Pat {
3103                 id: ast::DUMMY_NODE_ID,
3104                 node: pat,
3105                 span: mk_sp(lo, hi)
3106             }
3107         } else {
3108             let can_be_enum_or_struct = self.look_ahead(1, |t| {
3109                 match *t {
3110                     token::LPAREN | token::LBRACKET | token::LT |
3111                     token::LBRACE | token::MOD_SEP => true,
3112                     _ => false,
3113                 }
3114             });
3115
3116             if self.look_ahead(1, |t| *t == token::DOTDOT) {
3117                 let start = self.parse_expr_res(RESTRICT_NO_BAR_OP);
3118                 self.eat(&token::DOTDOT);
3119                 let end = self.parse_expr_res(RESTRICT_NO_BAR_OP);
3120                 pat = PatRange(start, end);
3121             } else if is_plain_ident(&self.token) && !can_be_enum_or_struct {
3122                 let id = self.parse_ident();
3123                 let id_span = self.last_span;
3124                 let pth1 = codemap::Spanned{span:id_span, node: id};
3125                 if self.eat(&token::NOT) {
3126                     // macro invocation
3127                     let ket = token::close_delimiter_for(&self.token)
3128                                     .unwrap_or_else(|| self.fatal("expected open delimiter"));
3129                     self.bump();
3130
3131                     let tts = self.parse_seq_to_end(&ket,
3132                                                     seq_sep_none(),
3133                                                     |p| p.parse_token_tree());
3134
3135                     let mac = MacInvocTT(ident_to_path(id_span,id), tts, EMPTY_CTXT);
3136                     pat = ast::PatMac(codemap::Spanned {node: mac, span: self.span});
3137                 } else {
3138                     let sub = if self.eat(&token::AT) {
3139                         // parse foo @ pat
3140                         Some(self.parse_pat())
3141                     } else {
3142                         // or just foo
3143                         None
3144                     };
3145                     pat = PatIdent(BindByValue(MutImmutable), pth1, sub);
3146                 }
3147             } else {
3148                 // parse an enum pat
3149                 let enum_path = self.parse_path(LifetimeAndTypesWithColons)
3150                                     .path;
3151                 match self.token {
3152                     token::LBRACE => {
3153                         self.bump();
3154                         let (fields, etc) =
3155                             self.parse_pat_fields();
3156                         self.bump();
3157                         pat = PatStruct(enum_path, fields, etc);
3158                     }
3159                     _ => {
3160                         let mut args: Vec<Gc<Pat>> = Vec::new();
3161                         match self.token {
3162                           token::LPAREN => {
3163                             let is_dotdot = self.look_ahead(1, |t| {
3164                                 match *t {
3165                                     token::DOTDOT => true,
3166                                     _ => false,
3167                                 }
3168                             });
3169                             if is_dotdot {
3170                                 // This is a "top constructor only" pat
3171                                 self.bump();
3172                                 self.bump();
3173                                 self.expect(&token::RPAREN);
3174                                 pat = PatEnum(enum_path, None);
3175                             } else {
3176                                 args = self.parse_enum_variant_seq(
3177                                     &token::LPAREN,
3178                                     &token::RPAREN,
3179                                     seq_sep_trailing_allowed(token::COMMA),
3180                                     |p| p.parse_pat()
3181                                 );
3182                                 pat = PatEnum(enum_path, Some(args));
3183                             }
3184                           },
3185                           _ => {
3186                               if !enum_path.global &&
3187                                     enum_path.segments.len() == 1 &&
3188                                     enum_path.segments
3189                                              .get(0)
3190                                              .lifetimes
3191                                              .len() == 0 &&
3192                                     enum_path.segments
3193                                              .get(0)
3194                                              .types
3195                                              .len() == 0 {
3196                                   // it could still be either an enum
3197                                   // or an identifier pattern, resolve
3198                                   // will sort it out:
3199                                   pat = PatIdent(BindByValue(MutImmutable),
3200                                                  codemap::Spanned{
3201                                                     span: enum_path.span,
3202                                                     node: enum_path.segments.get(0)
3203                                                            .identifier},
3204                                                  None);
3205                               } else {
3206                                   pat = PatEnum(enum_path, Some(args));
3207                               }
3208                           }
3209                         }
3210                     }
3211                 }
3212             }
3213         }
3214         hi = self.last_span.hi;
3215         box(GC) ast::Pat {
3216             id: ast::DUMMY_NODE_ID,
3217             node: pat,
3218             span: mk_sp(lo, hi),
3219         }
3220     }
3221
3222     /// Parse ident or ident @ pat
3223     /// used by the copy foo and ref foo patterns to give a good
3224     /// error message when parsing mistakes like ref foo(a,b)
3225     fn parse_pat_ident(&mut self,
3226                        binding_mode: ast::BindingMode)
3227                        -> ast::Pat_ {
3228         if !is_plain_ident(&self.token) {
3229             let last_span = self.last_span;
3230             self.span_fatal(last_span,
3231                             "expected identifier, found path");
3232         }
3233         let ident = self.parse_ident();
3234         let last_span = self.last_span;
3235         let name = codemap::Spanned{span: last_span, node: ident};
3236         let sub = if self.eat(&token::AT) {
3237             Some(self.parse_pat())
3238         } else {
3239             None
3240         };
3241
3242         // just to be friendly, if they write something like
3243         //   ref Some(i)
3244         // we end up here with ( as the current token.  This shortly
3245         // leads to a parse error.  Note that if there is no explicit
3246         // binding mode then we do not end up here, because the lookahead
3247         // will direct us over to parse_enum_variant()
3248         if self.token == token::LPAREN {
3249             let last_span = self.last_span;
3250             self.span_fatal(
3251                 last_span,
3252                 "expected identifier, found enum pattern");
3253         }
3254
3255         PatIdent(binding_mode, name, sub)
3256     }
3257
3258     /// Parse a local variable declaration
3259     fn parse_local(&mut self) -> Gc<Local> {
3260         let lo = self.span.lo;
3261         let pat = self.parse_pat();
3262
3263         let mut ty = P(Ty {
3264             id: ast::DUMMY_NODE_ID,
3265             node: TyInfer,
3266             span: mk_sp(lo, lo),
3267         });
3268         if self.eat(&token::COLON) {
3269             ty = self.parse_ty(true);
3270         }
3271         let init = self.parse_initializer();
3272         box(GC) ast::Local {
3273             ty: ty,
3274             pat: pat,
3275             init: init,
3276             id: ast::DUMMY_NODE_ID,
3277             span: mk_sp(lo, self.last_span.hi),
3278             source: LocalLet,
3279         }
3280     }
3281
3282     /// Parse a "let" stmt
3283     fn parse_let(&mut self) -> Gc<Decl> {
3284         let lo = self.span.lo;
3285         let local = self.parse_local();
3286         box(GC) spanned(lo, self.last_span.hi, DeclLocal(local))
3287     }
3288
3289     /// Parse a structure field
3290     fn parse_name_and_ty(&mut self, pr: Visibility,
3291                          attrs: Vec<Attribute> ) -> StructField {
3292         let lo = self.span.lo;
3293         if !is_plain_ident(&self.token) {
3294             self.fatal("expected ident");
3295         }
3296         let name = self.parse_ident();
3297         self.expect(&token::COLON);
3298         let ty = self.parse_ty(true);
3299         spanned(lo, self.last_span.hi, ast::StructField_ {
3300             kind: NamedField(name, pr),
3301             id: ast::DUMMY_NODE_ID,
3302             ty: ty,
3303             attrs: attrs,
3304         })
3305     }
3306
3307     /// Parse a statement. may include decl.
3308     /// Precondition: any attributes are parsed already
3309     pub fn parse_stmt(&mut self, item_attrs: Vec<Attribute>) -> Gc<Stmt> {
3310         maybe_whole!(self, NtStmt);
3311
3312         fn check_expected_item(p: &mut Parser, found_attrs: bool) {
3313             // If we have attributes then we should have an item
3314             if found_attrs {
3315                 let last_span = p.last_span;
3316                 p.span_err(last_span, "expected item after attributes");
3317             }
3318         }
3319
3320         let lo = self.span.lo;
3321         if self.is_keyword(keywords::Let) {
3322             check_expected_item(self, !item_attrs.is_empty());
3323             self.expect_keyword(keywords::Let);
3324             let decl = self.parse_let();
3325             return box(GC) spanned(lo, decl.span.hi, StmtDecl(decl, ast::DUMMY_NODE_ID));
3326         } else if is_ident(&self.token)
3327             && !token::is_any_keyword(&self.token)
3328             && self.look_ahead(1, |t| *t == token::NOT) {
3329             // it's a macro invocation:
3330
3331             check_expected_item(self, !item_attrs.is_empty());
3332
3333             // Potential trouble: if we allow macros with paths instead of
3334             // idents, we'd need to look ahead past the whole path here...
3335             let pth = self.parse_path(NoTypesAllowed).path;
3336             self.bump();
3337
3338             let id = if token::close_delimiter_for(&self.token).is_some() {
3339                 token::special_idents::invalid // no special identifier
3340             } else {
3341                 self.parse_ident()
3342             };
3343
3344             // check that we're pointing at delimiters (need to check
3345             // again after the `if`, because of `parse_ident`
3346             // consuming more tokens).
3347             let (bra, ket) = match token::close_delimiter_for(&self.token) {
3348                 Some(ket) => (self.token.clone(), ket),
3349                 None      => {
3350                     // we only expect an ident if we didn't parse one
3351                     // above.
3352                     let ident_str = if id.name == token::special_idents::invalid.name {
3353                         "identifier, "
3354                     } else {
3355                         ""
3356                     };
3357                     let tok_str = self.this_token_to_string();
3358                     self.fatal(format!("expected {}`(` or `{{`, found `{}`",
3359                                        ident_str,
3360                                        tok_str).as_slice())
3361                 }
3362             };
3363
3364             let tts = self.parse_unspanned_seq(
3365                 &bra,
3366                 &ket,
3367                 seq_sep_none(),
3368                 |p| p.parse_token_tree()
3369             );
3370             let hi = self.span.hi;
3371
3372             if id.name == token::special_idents::invalid.name {
3373                 return box(GC) spanned(lo, hi, StmtMac(
3374                     spanned(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT)), false));
3375             } else {
3376                 // if it has a special ident, it's definitely an item
3377                 return box(GC) spanned(lo, hi, StmtDecl(
3378                     box(GC) spanned(lo, hi, DeclItem(
3379                         self.mk_item(
3380                             lo, hi, id /*id is good here*/,
3381                             ItemMac(spanned(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT))),
3382                             Inherited, Vec::new(/*no attrs*/)))),
3383                     ast::DUMMY_NODE_ID));
3384             }
3385
3386         } else {
3387             let found_attrs = !item_attrs.is_empty();
3388             match self.parse_item_or_view_item(item_attrs, false) {
3389                 IoviItem(i) => {
3390                     let hi = i.span.hi;
3391                     let decl = box(GC) spanned(lo, hi, DeclItem(i));
3392                     return box(GC) spanned(lo, hi, StmtDecl(decl, ast::DUMMY_NODE_ID));
3393                 }
3394                 IoviViewItem(vi) => {
3395                     self.span_fatal(vi.span,
3396                                     "view items must be declared at the top of the block");
3397                 }
3398                 IoviForeignItem(_) => {
3399                     self.fatal("foreign items are not allowed here");
3400                 }
3401                 IoviNone(_) => { /* fallthrough */ }
3402             }
3403
3404             check_expected_item(self, found_attrs);
3405
3406             // Remainder are line-expr stmts.
3407             let e = self.parse_expr_res(RESTRICT_STMT_EXPR);
3408             return box(GC) spanned(lo, e.span.hi, StmtExpr(e, ast::DUMMY_NODE_ID));
3409         }
3410     }
3411
3412     /// Is this expression a successfully-parsed statement?
3413     fn expr_is_complete(&mut self, e: Gc<Expr>) -> bool {
3414         return self.restriction == RESTRICT_STMT_EXPR &&
3415             !classify::expr_requires_semi_to_be_stmt(e);
3416     }
3417
3418     /// Parse a block. No inner attrs are allowed.
3419     pub fn parse_block(&mut self) -> P<Block> {
3420         maybe_whole!(no_clone self, NtBlock);
3421
3422         let lo = self.span.lo;
3423         self.expect(&token::LBRACE);
3424
3425         return self.parse_block_tail_(lo, DefaultBlock, Vec::new());
3426     }
3427
3428     /// Parse a block. Inner attrs are allowed.
3429     fn parse_inner_attrs_and_block(&mut self)
3430         -> (Vec<Attribute> , P<Block>) {
3431
3432         maybe_whole!(pair_empty self, NtBlock);
3433
3434         let lo = self.span.lo;
3435         self.expect(&token::LBRACE);
3436         let (inner, next) = self.parse_inner_attrs_and_next();
3437
3438         (inner, self.parse_block_tail_(lo, DefaultBlock, next))
3439     }
3440
3441     /// Precondition: already parsed the '{' or '#{'
3442     /// I guess that also means "already parsed the 'impure'" if
3443     /// necessary, and this should take a qualifier.
3444     /// Some blocks start with "#{"...
3445     fn parse_block_tail(&mut self, lo: BytePos, s: BlockCheckMode) -> P<Block> {
3446         self.parse_block_tail_(lo, s, Vec::new())
3447     }
3448
3449     /// Parse the rest of a block expression or function body
3450     fn parse_block_tail_(&mut self, lo: BytePos, s: BlockCheckMode,
3451                          first_item_attrs: Vec<Attribute> ) -> P<Block> {
3452         let mut stmts = Vec::new();
3453         let mut expr = None;
3454
3455         // wouldn't it be more uniform to parse view items only, here?
3456         let ParsedItemsAndViewItems {
3457             attrs_remaining: attrs_remaining,
3458             view_items: view_items,
3459             items: items,
3460             ..
3461         } = self.parse_items_and_view_items(first_item_attrs,
3462                                             false, false);
3463
3464         for item in items.iter() {
3465             let decl = box(GC) spanned(item.span.lo, item.span.hi, DeclItem(*item));
3466             stmts.push(box(GC) spanned(item.span.lo, item.span.hi,
3467                                 StmtDecl(decl, ast::DUMMY_NODE_ID)));
3468         }
3469
3470         let mut attributes_box = attrs_remaining;
3471
3472         while self.token != token::RBRACE {
3473             // parsing items even when they're not allowed lets us give
3474             // better error messages and recover more gracefully.
3475             attributes_box.push_all(self.parse_outer_attributes().as_slice());
3476             match self.token {
3477                 token::SEMI => {
3478                     if !attributes_box.is_empty() {
3479                         let last_span = self.last_span;
3480                         self.span_err(last_span, "expected item after attributes");
3481                         attributes_box = Vec::new();
3482                     }
3483                     self.bump(); // empty
3484                 }
3485                 token::RBRACE => {
3486                     // fall through and out.
3487                 }
3488                 _ => {
3489                     let stmt = self.parse_stmt(attributes_box);
3490                     attributes_box = Vec::new();
3491                     match stmt.node {
3492                         StmtExpr(e, stmt_id) => {
3493                             // expression without semicolon
3494                             if classify::stmt_ends_with_semi(&*stmt) {
3495                                 // Just check for errors and recover; do not eat semicolon yet.
3496                                 self.commit_stmt(stmt, &[], &[token::SEMI, token::RBRACE]);
3497                             }
3498
3499                             match self.token {
3500                                 token::SEMI => {
3501                                     self.bump();
3502                                     let span_with_semi = Span {
3503                                         lo: stmt.span.lo,
3504                                         hi: self.last_span.hi,
3505                                         expn_info: stmt.span.expn_info,
3506                                     };
3507                                     stmts.push(box(GC) codemap::Spanned {
3508                                         node: StmtSemi(e, stmt_id),
3509                                         span: span_with_semi,
3510                                     });
3511                                 }
3512                                 token::RBRACE => {
3513                                     expr = Some(e);
3514                                 }
3515                                 _ => {
3516                                     stmts.push(stmt);
3517                                 }
3518                             }
3519                         }
3520                         StmtMac(ref m, _) => {
3521                             // statement macro; might be an expr
3522                             match self.token {
3523                                 token::SEMI => {
3524                                     self.bump();
3525                                     stmts.push(box(GC) codemap::Spanned {
3526                                         node: StmtMac((*m).clone(), true),
3527                                         span: stmt.span,
3528                                     });
3529                                 }
3530                                 token::RBRACE => {
3531                                     // if a block ends in `m!(arg)` without
3532                                     // a `;`, it must be an expr
3533                                     expr = Some(
3534                                         self.mk_mac_expr(stmt.span.lo,
3535                                                          stmt.span.hi,
3536                                                          m.node.clone()));
3537                                 }
3538                                 _ => {
3539                                     stmts.push(stmt);
3540                                 }
3541                             }
3542                         }
3543                         _ => { // all other kinds of statements:
3544                             stmts.push(stmt.clone());
3545
3546                             if classify::stmt_ends_with_semi(&*stmt) {
3547                                 self.commit_stmt_expecting(stmt, token::SEMI);
3548                             }
3549                         }
3550                     }
3551                 }
3552             }
3553         }
3554
3555         if !attributes_box.is_empty() {
3556             let last_span = self.last_span;
3557             self.span_err(last_span, "expected item after attributes");
3558         }
3559
3560         let hi = self.span.hi;
3561         self.bump();
3562         P(ast::Block {
3563             view_items: view_items,
3564             stmts: stmts,
3565             expr: expr,
3566             id: ast::DUMMY_NODE_ID,
3567             rules: s,
3568             span: mk_sp(lo, hi),
3569         })
3570     }
3571
3572     fn parse_unboxed_function_type(&mut self) -> UnboxedFnTy {
3573         let (optional_unboxed_closure_kind, inputs) =
3574             if self.eat(&token::OROR) {
3575                 (None, Vec::new())
3576             } else {
3577                 self.expect_or();
3578
3579                 let optional_unboxed_closure_kind =
3580                     self.parse_optional_unboxed_closure_kind();
3581
3582                 let inputs = self.parse_seq_to_before_or(&token::COMMA,
3583                                                          |p| {
3584                     p.parse_arg_general(false)
3585                 });
3586                 self.expect_or();
3587                 (optional_unboxed_closure_kind, inputs)
3588             };
3589
3590         let (return_style, output) = self.parse_ret_ty();
3591         UnboxedFnTy {
3592             decl: P(FnDecl {
3593                 inputs: inputs,
3594                 output: output,
3595                 cf: return_style,
3596                 variadic: false,
3597             }),
3598             kind: match optional_unboxed_closure_kind {
3599                 Some(kind) => kind,
3600                 None => FnMutUnboxedClosureKind,
3601             },
3602         }
3603     }
3604
3605     // Parses a sequence of bounds if a `:` is found,
3606     // otherwise returns empty list.
3607     fn parse_colon_then_ty_param_bounds(&mut self)
3608                                         -> OwnedSlice<TyParamBound>
3609     {
3610         if !self.eat(&token::COLON) {
3611             OwnedSlice::empty()
3612         } else {
3613             self.parse_ty_param_bounds()
3614         }
3615     }
3616
3617     // matches bounds    = ( boundseq )?
3618     // where   boundseq  = ( bound + boundseq ) | bound
3619     // and     bound     = 'region | ty
3620     // NB: The None/Some distinction is important for issue #7264.
3621     fn parse_ty_param_bounds(&mut self)
3622                              -> OwnedSlice<TyParamBound>
3623     {
3624         let mut result = vec!();
3625         loop {
3626             match self.token {
3627                 token::LIFETIME(lifetime) => {
3628                     result.push(RegionTyParamBound(ast::Lifetime {
3629                         id: ast::DUMMY_NODE_ID,
3630                         span: self.span,
3631                         name: lifetime.name
3632                     }));
3633                     self.bump();
3634                 }
3635                 token::MOD_SEP | token::IDENT(..) => {
3636                     let tref = self.parse_trait_ref();
3637                     result.push(TraitTyParamBound(tref));
3638                 }
3639                 token::BINOP(token::OR) | token::OROR => {
3640                     let unboxed_function_type =
3641                         self.parse_unboxed_function_type();
3642                     result.push(UnboxedFnTyParamBound(unboxed_function_type));
3643                 }
3644                 _ => break,
3645             }
3646
3647             if !self.eat(&token::BINOP(token::PLUS)) {
3648                 break;
3649             }
3650         }
3651
3652         return OwnedSlice::from_vec(result);
3653     }
3654
3655     fn trait_ref_from_ident(ident: Ident, span: Span) -> ast::TraitRef {
3656         let segment = ast::PathSegment {
3657             identifier: ident,
3658             lifetimes: Vec::new(),
3659             types: OwnedSlice::empty(),
3660         };
3661         let path = ast::Path {
3662             span: span,
3663             global: false,
3664             segments: vec![segment],
3665         };
3666         ast::TraitRef {
3667             path: path,
3668             ref_id: ast::DUMMY_NODE_ID,
3669         }
3670     }
3671
3672     /// Matches typaram = (unbound`?`)? IDENT optbounds ( EQ ty )?
3673     fn parse_ty_param(&mut self) -> TyParam {
3674         // This is a bit hacky. Currently we are only interested in a single
3675         // unbound, and it may only be `Sized`. To avoid backtracking and other
3676         // complications, we parse an ident, then check for `?`. If we find it,
3677         // we use the ident as the unbound, otherwise, we use it as the name of
3678         // type param.
3679         let mut span = self.span;
3680         let mut ident = self.parse_ident();
3681         let mut unbound = None;
3682         if self.eat(&token::QUESTION) {
3683             let tref = Parser::trait_ref_from_ident(ident, span);
3684             unbound = Some(TraitTyParamBound(tref));
3685             span = self.span;
3686             ident = self.parse_ident();
3687         }
3688
3689         let bounds = self.parse_colon_then_ty_param_bounds();
3690
3691         let default = if self.token == token::EQ {
3692             self.bump();
3693             Some(self.parse_ty(true))
3694         }
3695         else { None };
3696
3697         TyParam {
3698             ident: ident,
3699             id: ast::DUMMY_NODE_ID,
3700             bounds: bounds,
3701             unbound: unbound,
3702             default: default,
3703             span: span,
3704         }
3705     }
3706
3707     /// Parse a set of optional generic type parameter declarations. Where
3708     /// clauses are not parsed here, and must be added later via
3709     /// `parse_where_clause()`.
3710     ///
3711     /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
3712     ///                  | ( < lifetimes , typaramseq ( , )? > )
3713     /// where   typaramseq = ( typaram ) | ( typaram , typaramseq )
3714     pub fn parse_generics(&mut self) -> ast::Generics {
3715         if self.eat(&token::LT) {
3716             let lifetime_defs = self.parse_lifetime_defs();
3717             let mut seen_default = false;
3718             let ty_params = self.parse_seq_to_gt(Some(token::COMMA), |p| {
3719                 p.forbid_lifetime();
3720                 let ty_param = p.parse_ty_param();
3721                 if ty_param.default.is_some() {
3722                     seen_default = true;
3723                 } else if seen_default {
3724                     let last_span = p.last_span;
3725                     p.span_err(last_span,
3726                                "type parameters with a default must be trailing");
3727                 }
3728                 ty_param
3729             });
3730             ast::Generics {
3731                 lifetimes: lifetime_defs,
3732                 ty_params: ty_params,
3733                 where_clause: WhereClause {
3734                     id: ast::DUMMY_NODE_ID,
3735                     predicates: Vec::new(),
3736                 }
3737             }
3738         } else {
3739             ast_util::empty_generics()
3740         }
3741     }
3742
3743     fn parse_generic_values_after_lt(&mut self) -> (Vec<ast::Lifetime>, Vec<P<Ty>> ) {
3744         let lifetimes = self.parse_lifetimes(token::COMMA);
3745         let result = self.parse_seq_to_gt(
3746             Some(token::COMMA),
3747             |p| {
3748                 p.forbid_lifetime();
3749                 p.parse_ty(true)
3750             }
3751         );
3752         (lifetimes, result.into_vec())
3753     }
3754
3755     fn forbid_lifetime(&mut self) {
3756         if Parser::token_is_lifetime(&self.token) {
3757             let span = self.span;
3758             self.span_fatal(span, "lifetime parameters must be declared \
3759                                         prior to type parameters");
3760         }
3761     }
3762
3763     /// Parses an optional `where` clause and places it in `generics`.
3764     fn parse_where_clause(&mut self, generics: &mut ast::Generics) {
3765         if !self.eat_keyword(keywords::Where) {
3766             return
3767         }
3768
3769         let mut parsed_something = false;
3770         loop {
3771             let lo = self.span.lo;
3772             let ident = match self.token {
3773                 token::IDENT(..) => self.parse_ident(),
3774                 _ => break,
3775             };
3776             self.expect(&token::COLON);
3777
3778             let bounds = self.parse_ty_param_bounds();
3779             let hi = self.span.hi;
3780             let span = mk_sp(lo, hi);
3781
3782             if bounds.len() == 0 {
3783                 self.span_err(span,
3784                               "each predicate in a `where` clause must have \
3785                                at least one bound in it");
3786             }
3787
3788             generics.where_clause.predicates.push(ast::WherePredicate {
3789                 id: ast::DUMMY_NODE_ID,
3790                 span: span,
3791                 ident: ident,
3792                 bounds: bounds,
3793             });
3794             parsed_something = true;
3795
3796             if !self.eat(&token::COMMA) {
3797                 break
3798             }
3799         }
3800
3801         if !parsed_something {
3802             let last_span = self.last_span;
3803             self.span_err(last_span,
3804                           "a `where` clause must have at least one predicate \
3805                            in it");
3806         }
3807     }
3808
3809     fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
3810                      -> (Vec<Arg> , bool) {
3811         let sp = self.span;
3812         let mut args: Vec<Option<Arg>> =
3813             self.parse_unspanned_seq(
3814                 &token::LPAREN,
3815                 &token::RPAREN,
3816                 seq_sep_trailing_allowed(token::COMMA),
3817                 |p| {
3818                     if p.token == token::DOTDOTDOT {
3819                         p.bump();
3820                         if allow_variadic {
3821                             if p.token != token::RPAREN {
3822                                 let span = p.span;
3823                                 p.span_fatal(span,
3824                                     "`...` must be last in argument list for variadic function");
3825                             }
3826                         } else {
3827                             let span = p.span;
3828                             p.span_fatal(span,
3829                                          "only foreign functions are allowed to be variadic");
3830                         }
3831                         None
3832                     } else {
3833                         Some(p.parse_arg_general(named_args))
3834                     }
3835                 }
3836             );
3837
3838         let variadic = match args.pop() {
3839             Some(None) => true,
3840             Some(x) => {
3841                 // Need to put back that last arg
3842                 args.push(x);
3843                 false
3844             }
3845             None => false
3846         };
3847
3848         if variadic && args.is_empty() {
3849             self.span_err(sp,
3850                           "variadic function must be declared with at least one named argument");
3851         }
3852
3853         let args = args.move_iter().map(|x| x.unwrap()).collect();
3854
3855         (args, variadic)
3856     }
3857
3858     /// Parse the argument list and result type of a function declaration
3859     pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> P<FnDecl> {
3860
3861         let (args, variadic) = self.parse_fn_args(true, allow_variadic);
3862         let (ret_style, ret_ty) = self.parse_ret_ty();
3863
3864         P(FnDecl {
3865             inputs: args,
3866             output: ret_ty,
3867             cf: ret_style,
3868             variadic: variadic
3869         })
3870     }
3871
3872     fn is_self_ident(&mut self) -> bool {
3873         match self.token {
3874           token::IDENT(id, false) => id.name == special_idents::self_.name,
3875           _ => false
3876         }
3877     }
3878
3879     fn expect_self_ident(&mut self) -> ast::Ident {
3880         match self.token {
3881             token::IDENT(id, false) if id.name == special_idents::self_.name => {
3882                 self.bump();
3883                 id
3884             },
3885             _ => {
3886                 let token_str = self.this_token_to_string();
3887                 self.fatal(format!("expected `self`, found `{}`",
3888                                    token_str).as_slice())
3889             }
3890         }
3891     }
3892
3893     /// Parse the argument list and result type of a function
3894     /// that may have a self type.
3895     fn parse_fn_decl_with_self(&mut self, parse_arg_fn: |&mut Parser| -> Arg)
3896                                -> (ExplicitSelf, P<FnDecl>) {
3897         fn maybe_parse_borrowed_explicit_self(this: &mut Parser)
3898                                               -> ast::ExplicitSelf_ {
3899             // The following things are possible to see here:
3900             //
3901             //     fn(&mut self)
3902             //     fn(&mut self)
3903             //     fn(&'lt self)
3904             //     fn(&'lt mut self)
3905             //
3906             // We already know that the current token is `&`.
3907
3908             if this.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) {
3909                 this.bump();
3910                 SelfRegion(None, MutImmutable, this.expect_self_ident())
3911             } else if this.look_ahead(1, |t| Parser::token_is_mutability(t)) &&
3912                     this.look_ahead(2,
3913                                     |t| token::is_keyword(keywords::Self,
3914                                                           t)) {
3915                 this.bump();
3916                 let mutability = this.parse_mutability();
3917                 SelfRegion(None, mutability, this.expect_self_ident())
3918             } else if this.look_ahead(1, |t| Parser::token_is_lifetime(t)) &&
3919                        this.look_ahead(2,
3920                                        |t| token::is_keyword(keywords::Self,
3921                                                              t)) {
3922                 this.bump();
3923                 let lifetime = this.parse_lifetime();
3924                 SelfRegion(Some(lifetime), MutImmutable, this.expect_self_ident())
3925             } else if this.look_ahead(1, |t| Parser::token_is_lifetime(t)) &&
3926                       this.look_ahead(2, |t| {
3927                           Parser::token_is_mutability(t)
3928                       }) &&
3929                       this.look_ahead(3, |t| token::is_keyword(keywords::Self,
3930                                                                t)) {
3931                 this.bump();
3932                 let lifetime = this.parse_lifetime();
3933                 let mutability = this.parse_mutability();
3934                 SelfRegion(Some(lifetime), mutability, this.expect_self_ident())
3935             } else {
3936                 SelfStatic
3937             }
3938         }
3939
3940         self.expect(&token::LPAREN);
3941
3942         // A bit of complexity and lookahead is needed here in order to be
3943         // backwards compatible.
3944         let lo = self.span.lo;
3945         let mut mutbl_self = MutImmutable;
3946         let explicit_self = match self.token {
3947             token::BINOP(token::AND) => {
3948                 maybe_parse_borrowed_explicit_self(self)
3949             }
3950             token::TILDE => {
3951                 // We need to make sure it isn't a type
3952                 if self.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) {
3953                     self.bump();
3954                     drop(self.expect_self_ident());
3955                     let last_span = self.last_span;
3956                     self.obsolete(last_span, ObsoleteOwnedSelf)
3957                 }
3958                 SelfStatic
3959             }
3960             token::BINOP(token::STAR) => {
3961                 // Possibly "*self" or "*mut self" -- not supported. Try to avoid
3962                 // emitting cryptic "unexpected token" errors.
3963                 self.bump();
3964                 let _mutability = if Parser::token_is_mutability(&self.token) {
3965                     self.parse_mutability()
3966                 } else {
3967                     MutImmutable
3968                 };
3969                 if self.is_self_ident() {
3970                     let span = self.span;
3971                     self.span_err(span, "cannot pass self by unsafe pointer");
3972                     self.bump();
3973                 }
3974                 // error case, making bogus self ident:
3975                 SelfValue(special_idents::self_)
3976             }
3977             token::IDENT(..) => {
3978                 if self.is_self_ident() {
3979                     let self_ident = self.expect_self_ident();
3980
3981                     // Determine whether this is the fully explicit form, `self:
3982                     // TYPE`.
3983                     if self.eat(&token::COLON) {
3984                         SelfExplicit(self.parse_ty(false), self_ident)
3985                     } else {
3986                         SelfValue(self_ident)
3987                     }
3988                 } else if Parser::token_is_mutability(&self.token) &&
3989                         self.look_ahead(1, |t| {
3990                             token::is_keyword(keywords::Self, t)
3991                         }) {
3992                     mutbl_self = self.parse_mutability();
3993                     let self_ident = self.expect_self_ident();
3994
3995                     // Determine whether this is the fully explicit form,
3996                     // `self: TYPE`.
3997                     if self.eat(&token::COLON) {
3998                         SelfExplicit(self.parse_ty(false), self_ident)
3999                     } else {
4000                         SelfValue(self_ident)
4001                     }
4002                 } else if Parser::token_is_mutability(&self.token) &&
4003                         self.look_ahead(1, |t| *t == token::TILDE) &&
4004                         self.look_ahead(2, |t| {
4005                             token::is_keyword(keywords::Self, t)
4006                         }) {
4007                     mutbl_self = self.parse_mutability();
4008                     self.bump();
4009                     drop(self.expect_self_ident());
4010                     let last_span = self.last_span;
4011                     self.obsolete(last_span, ObsoleteOwnedSelf);
4012                     SelfStatic
4013                 } else {
4014                     SelfStatic
4015                 }
4016             }
4017             _ => SelfStatic,
4018         };
4019
4020         let explicit_self_sp = mk_sp(lo, self.span.hi);
4021
4022         // shared fall-through for the three cases below. borrowing prevents simply
4023         // writing this as a closure
4024         macro_rules! parse_remaining_arguments {
4025             ($self_id:ident) =>
4026             {
4027             // If we parsed a self type, expect a comma before the argument list.
4028             match self.token {
4029                 token::COMMA => {
4030                     self.bump();
4031                     let sep = seq_sep_trailing_allowed(token::COMMA);
4032                     let mut fn_inputs = self.parse_seq_to_before_end(
4033                         &token::RPAREN,
4034                         sep,
4035                         parse_arg_fn
4036                     );
4037                     fn_inputs.unshift(Arg::new_self(explicit_self_sp, mutbl_self, $self_id));
4038                     fn_inputs
4039                 }
4040                 token::RPAREN => {
4041                     vec!(Arg::new_self(explicit_self_sp, mutbl_self, $self_id))
4042                 }
4043                 _ => {
4044                     let token_str = self.this_token_to_string();
4045                     self.fatal(format!("expected `,` or `)`, found `{}`",
4046                                        token_str).as_slice())
4047                 }
4048             }
4049             }
4050         }
4051
4052         let fn_inputs = match explicit_self {
4053             SelfStatic =>  {
4054                 let sep = seq_sep_trailing_allowed(token::COMMA);
4055                 self.parse_seq_to_before_end(&token::RPAREN, sep, parse_arg_fn)
4056             }
4057             SelfValue(id) => parse_remaining_arguments!(id),
4058             SelfRegion(_,_,id) => parse_remaining_arguments!(id),
4059             SelfExplicit(_,id) => parse_remaining_arguments!(id),
4060         };
4061
4062
4063         self.expect(&token::RPAREN);
4064
4065         let hi = self.span.hi;
4066
4067         let (ret_style, ret_ty) = self.parse_ret_ty();
4068
4069         let fn_decl = P(FnDecl {
4070             inputs: fn_inputs,
4071             output: ret_ty,
4072             cf: ret_style,
4073             variadic: false
4074         });
4075
4076         (spanned(lo, hi, explicit_self), fn_decl)
4077     }
4078
4079     // parse the |arg, arg| header on a lambda
4080     fn parse_fn_block_decl(&mut self)
4081                            -> (P<FnDecl>, Option<UnboxedClosureKind>) {
4082         let (optional_unboxed_closure_kind, inputs_captures) = {
4083             if self.eat(&token::OROR) {
4084                 (None, Vec::new())
4085             } else {
4086                 self.expect(&token::BINOP(token::OR));
4087                 let optional_unboxed_closure_kind =
4088                     self.parse_optional_unboxed_closure_kind();
4089                 let args = self.parse_seq_to_before_end(
4090                     &token::BINOP(token::OR),
4091                     seq_sep_trailing_allowed(token::COMMA),
4092                     |p| p.parse_fn_block_arg()
4093                 );
4094                 self.bump();
4095                 (optional_unboxed_closure_kind, args)
4096             }
4097         };
4098         let output = if self.eat(&token::RARROW) {
4099             self.parse_ty(true)
4100         } else {
4101             P(Ty {
4102                 id: ast::DUMMY_NODE_ID,
4103                 node: TyInfer,
4104                 span: self.span,
4105             })
4106         };
4107
4108         (P(FnDecl {
4109             inputs: inputs_captures,
4110             output: output,
4111             cf: Return,
4112             variadic: false
4113         }), optional_unboxed_closure_kind)
4114     }
4115
4116     /// Parses the `(arg, arg) -> return_type` header on a procedure.
4117     fn parse_proc_decl(&mut self) -> P<FnDecl> {
4118         let inputs =
4119             self.parse_unspanned_seq(&token::LPAREN,
4120                                      &token::RPAREN,
4121                                      seq_sep_trailing_allowed(token::COMMA),
4122                                      |p| p.parse_fn_block_arg());
4123
4124         let output = if self.eat(&token::RARROW) {
4125             self.parse_ty(true)
4126         } else {
4127             P(Ty {
4128                 id: ast::DUMMY_NODE_ID,
4129                 node: TyInfer,
4130                 span: self.span,
4131             })
4132         };
4133
4134         P(FnDecl {
4135             inputs: inputs,
4136             output: output,
4137             cf: Return,
4138             variadic: false
4139         })
4140     }
4141
4142     /// Parse the name and optional generic types of a function header.
4143     fn parse_fn_header(&mut self) -> (Ident, ast::Generics) {
4144         let id = self.parse_ident();
4145         let generics = self.parse_generics();
4146         (id, generics)
4147     }
4148
4149     fn mk_item(&mut self, lo: BytePos, hi: BytePos, ident: Ident,
4150                node: Item_, vis: Visibility,
4151                attrs: Vec<Attribute>) -> Gc<Item> {
4152         box(GC) Item {
4153             ident: ident,
4154             attrs: attrs,
4155             id: ast::DUMMY_NODE_ID,
4156             node: node,
4157             vis: vis,
4158             span: mk_sp(lo, hi)
4159         }
4160     }
4161
4162     /// Parse an item-position function declaration.
4163     fn parse_item_fn(&mut self, fn_style: FnStyle, abi: abi::Abi) -> ItemInfo {
4164         let (ident, mut generics) = self.parse_fn_header();
4165         let decl = self.parse_fn_decl(false);
4166         self.parse_where_clause(&mut generics);
4167         let (inner_attrs, body) = self.parse_inner_attrs_and_block();
4168         (ident, ItemFn(decl, fn_style, abi, generics, body), Some(inner_attrs))
4169     }
4170
4171     /// Parse a method in a trait impl, starting with `attrs` attributes.
4172     pub fn parse_method(&mut self,
4173                         already_parsed_attrs: Option<Vec<Attribute>>)
4174                         -> Gc<Method> {
4175         let next_attrs = self.parse_outer_attributes();
4176         let attrs = match already_parsed_attrs {
4177             Some(mut a) => { a.push_all_move(next_attrs); a }
4178             None => next_attrs
4179         };
4180
4181         let lo = self.span.lo;
4182
4183         // code copied from parse_macro_use_or_failure... abstraction!
4184         let (method_, hi, new_attrs) = {
4185             if !token::is_any_keyword(&self.token)
4186                 && self.look_ahead(1, |t| *t == token::NOT)
4187                 && (self.look_ahead(2, |t| *t == token::LPAREN)
4188                     || self.look_ahead(2, |t| *t == token::LBRACE)) {
4189                 // method macro.
4190                 let pth = self.parse_path(NoTypesAllowed).path;
4191                 self.expect(&token::NOT);
4192
4193                 // eat a matched-delimiter token tree:
4194                 let tts = match token::close_delimiter_for(&self.token) {
4195                     Some(ket) => {
4196                         self.bump();
4197                         self.parse_seq_to_end(&ket,
4198                                               seq_sep_none(),
4199                                               |p| p.parse_token_tree())
4200                     }
4201                     None => self.fatal("expected open delimiter")
4202                 };
4203                 let m_ = ast::MacInvocTT(pth, tts, EMPTY_CTXT);
4204                 let m: ast::Mac = codemap::Spanned { node: m_,
4205                                                  span: mk_sp(self.span.lo,
4206                                                              self.span.hi) };
4207                 (ast::MethMac(m), self.span.hi, attrs)
4208             } else {
4209                 let visa = self.parse_visibility();
4210                 let abi = if self.eat_keyword(keywords::Extern) {
4211                     self.parse_opt_abi().unwrap_or(abi::C)
4212                 } else if attr::contains_name(attrs.as_slice(),
4213                                               "rust_call_abi_hack") {
4214                     // FIXME(stage0, pcwalton): Remove this awful hack after a
4215                     // snapshot, and change to `extern "rust-call" fn`.
4216                     abi::RustCall
4217                 } else {
4218                     abi::Rust
4219                 };
4220                 let fn_style = self.parse_fn_style();
4221                 let ident = self.parse_ident();
4222                 let mut generics = self.parse_generics();
4223                 let (explicit_self, decl) = self.parse_fn_decl_with_self(|p| {
4224                         p.parse_arg()
4225                     });
4226                 self.parse_where_clause(&mut generics);
4227                 let (inner_attrs, body) = self.parse_inner_attrs_and_block();
4228                 let new_attrs = attrs.append(inner_attrs.as_slice());
4229                 (ast::MethDecl(ident,
4230                                generics,
4231                                abi,
4232                                explicit_self,
4233                                fn_style,
4234                                decl,
4235                                body,
4236                                visa),
4237                  body.span.hi, new_attrs)
4238             }
4239         };
4240         box(GC) ast::Method {
4241             attrs: new_attrs,
4242             id: ast::DUMMY_NODE_ID,
4243             span: mk_sp(lo, hi),
4244             node: method_,
4245         }
4246     }
4247
4248     /// Parse trait Foo { ... }
4249     fn parse_item_trait(&mut self) -> ItemInfo {
4250         let ident = self.parse_ident();
4251         let mut tps = self.parse_generics();
4252         let sized = self.parse_for_sized();
4253
4254         // Parse supertrait bounds.
4255         let bounds = self.parse_colon_then_ty_param_bounds();
4256
4257         self.parse_where_clause(&mut tps);
4258
4259         let meths = self.parse_trait_methods();
4260         (ident, ItemTrait(tps, sized, bounds, meths), None)
4261     }
4262
4263     fn parse_impl_items(&mut self) -> (Vec<ImplItem>, Vec<Attribute>) {
4264         let mut impl_items = Vec::new();
4265         self.expect(&token::LBRACE);
4266         let (inner_attrs, next) = self.parse_inner_attrs_and_next();
4267         let mut method_attrs = Some(next);
4268         while !self.eat(&token::RBRACE) {
4269             impl_items.push(MethodImplItem(self.parse_method(method_attrs)));
4270             method_attrs = None;
4271         }
4272         (impl_items, inner_attrs)
4273     }
4274
4275     /// Parses two variants (with the region/type params always optional):
4276     ///    impl<T> Foo { ... }
4277     ///    impl<T> ToString for ~[T] { ... }
4278     fn parse_item_impl(&mut self) -> ItemInfo {
4279         // First, parse type parameters if necessary.
4280         let mut generics = self.parse_generics();
4281
4282         // Special case: if the next identifier that follows is '(', don't
4283         // allow this to be parsed as a trait.
4284         let could_be_trait = self.token != token::LPAREN;
4285
4286         // Parse the trait.
4287         let mut ty = self.parse_ty(true);
4288
4289         // Parse traits, if necessary.
4290         let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) {
4291             // New-style trait. Reinterpret the type as a trait.
4292             let opt_trait_ref = match ty.node {
4293                 TyPath(ref path, None, node_id) => {
4294                     Some(TraitRef { path: (*path).clone(),
4295                                     ref_id: node_id })
4296                 }
4297                 TyPath(_, Some(_), _) => {
4298                     self.span_err(ty.span,
4299                                   "bounded traits are only valid in type position");
4300                     None
4301                 }
4302                 _ => {
4303                     self.span_err(ty.span, "not a trait");
4304                     None
4305                 }
4306             };
4307
4308             ty = self.parse_ty(true);
4309             opt_trait_ref
4310         } else {
4311             None
4312         };
4313
4314         self.parse_where_clause(&mut generics);
4315         let (impl_items, attrs) = self.parse_impl_items();
4316
4317         let ident = ast_util::impl_pretty_name(&opt_trait, &*ty);
4318
4319         (ident,
4320          ItemImpl(generics, opt_trait, ty, impl_items),
4321          Some(attrs))
4322     }
4323
4324     /// Parse a::B<String,int>
4325     fn parse_trait_ref(&mut self) -> TraitRef {
4326         ast::TraitRef {
4327             path: self.parse_path(LifetimeAndTypesWithoutColons).path,
4328             ref_id: ast::DUMMY_NODE_ID,
4329         }
4330     }
4331
4332     /// Parse struct Foo { ... }
4333     fn parse_item_struct(&mut self, is_virtual: bool) -> ItemInfo {
4334         let class_name = self.parse_ident();
4335         let mut generics = self.parse_generics();
4336
4337         let super_struct = if self.eat(&token::COLON) {
4338             let ty = self.parse_ty(true);
4339             match ty.node {
4340                 TyPath(_, None, _) => {
4341                     Some(ty)
4342                 }
4343                 _ => {
4344                     self.span_err(ty.span, "not a struct");
4345                     None
4346                 }
4347             }
4348         } else {
4349             None
4350         };
4351
4352         self.parse_where_clause(&mut generics);
4353
4354         let mut fields: Vec<StructField>;
4355         let is_tuple_like;
4356
4357         if self.eat(&token::LBRACE) {
4358             // It's a record-like struct.
4359             is_tuple_like = false;
4360             fields = Vec::new();
4361             while self.token != token::RBRACE {
4362                 fields.push(self.parse_struct_decl_field());
4363             }
4364             if fields.len() == 0 {
4365                 self.fatal(format!("unit-like struct definition should be \
4366                                     written as `struct {};`",
4367                                    token::get_ident(class_name)).as_slice());
4368             }
4369             self.bump();
4370         } else if self.token == token::LPAREN {
4371             // It's a tuple-like struct.
4372             is_tuple_like = true;
4373             fields = self.parse_unspanned_seq(
4374                 &token::LPAREN,
4375                 &token::RPAREN,
4376                 seq_sep_trailing_allowed(token::COMMA),
4377                 |p| {
4378                 let attrs = p.parse_outer_attributes();
4379                 let lo = p.span.lo;
4380                 let struct_field_ = ast::StructField_ {
4381                     kind: UnnamedField(p.parse_visibility()),
4382                     id: ast::DUMMY_NODE_ID,
4383                     ty: p.parse_ty(true),
4384                     attrs: attrs,
4385                 };
4386                 spanned(lo, p.span.hi, struct_field_)
4387             });
4388             if fields.len() == 0 {
4389                 self.fatal(format!("unit-like struct definition should be \
4390                                     written as `struct {};`",
4391                                    token::get_ident(class_name)).as_slice());
4392             }
4393             self.expect(&token::SEMI);
4394         } else if self.eat(&token::SEMI) {
4395             // It's a unit-like struct.
4396             is_tuple_like = true;
4397             fields = Vec::new();
4398         } else {
4399             let token_str = self.this_token_to_string();
4400             self.fatal(format!("expected `{}`, `(`, or `;` after struct \
4401                                 name, found `{}`", "{",
4402                                token_str).as_slice())
4403         }
4404
4405         let _ = ast::DUMMY_NODE_ID;  // FIXME: Workaround for crazy bug.
4406         let new_id = ast::DUMMY_NODE_ID;
4407         (class_name,
4408          ItemStruct(box(GC) ast::StructDef {
4409              fields: fields,
4410              ctor_id: if is_tuple_like { Some(new_id) } else { None },
4411              super_struct: super_struct,
4412              is_virtual: is_virtual,
4413          }, generics),
4414          None)
4415     }
4416
4417     /// Parse a structure field declaration
4418     pub fn parse_single_struct_field(&mut self,
4419                                      vis: Visibility,
4420                                      attrs: Vec<Attribute> )
4421                                      -> StructField {
4422         let a_var = self.parse_name_and_ty(vis, attrs);
4423         match self.token {
4424             token::COMMA => {
4425                 self.bump();
4426             }
4427             token::RBRACE => {}
4428             _ => {
4429                 let span = self.span;
4430                 let token_str = self.this_token_to_string();
4431                 self.span_fatal(span,
4432                                 format!("expected `,`, or `}}`, found `{}`",
4433                                         token_str).as_slice())
4434             }
4435         }
4436         a_var
4437     }
4438
4439     /// Parse an element of a struct definition
4440     fn parse_struct_decl_field(&mut self) -> StructField {
4441
4442         let attrs = self.parse_outer_attributes();
4443
4444         if self.eat_keyword(keywords::Pub) {
4445            return self.parse_single_struct_field(Public, attrs);
4446         }
4447
4448         return self.parse_single_struct_field(Inherited, attrs);
4449     }
4450
4451     /// Parse visibility: PUB, PRIV, or nothing
4452     fn parse_visibility(&mut self) -> Visibility {
4453         if self.eat_keyword(keywords::Pub) { Public }
4454         else { Inherited }
4455     }
4456
4457     fn parse_for_sized(&mut self) -> Option<ast::TyParamBound> {
4458         if self.eat_keyword(keywords::For) {
4459             let span = self.span;
4460             let ident = self.parse_ident();
4461             if !self.eat(&token::QUESTION) {
4462                 self.span_err(span,
4463                     "expected 'Sized?' after `for` in trait item");
4464                 return None;
4465             }
4466             let tref = Parser::trait_ref_from_ident(ident, span);
4467             Some(TraitTyParamBound(tref))
4468         } else {
4469             None
4470         }
4471     }
4472
4473     /// Given a termination token and a vector of already-parsed
4474     /// attributes (of length 0 or 1), parse all of the items in a module
4475     fn parse_mod_items(&mut self,
4476                        term: token::Token,
4477                        first_item_attrs: Vec<Attribute>,
4478                        inner_lo: BytePos)
4479                        -> Mod {
4480         // parse all of the items up to closing or an attribute.
4481         // view items are legal here.
4482         let ParsedItemsAndViewItems {
4483             attrs_remaining: attrs_remaining,
4484             view_items: view_items,
4485             items: starting_items,
4486             ..
4487         } = self.parse_items_and_view_items(first_item_attrs, true, true);
4488         let mut items: Vec<Gc<Item>> = starting_items;
4489         let attrs_remaining_len = attrs_remaining.len();
4490
4491         // don't think this other loop is even necessary....
4492
4493         let mut first = true;
4494         while self.token != term {
4495             let mut attrs = self.parse_outer_attributes();
4496             if first {
4497                 attrs = attrs_remaining.clone().append(attrs.as_slice());
4498                 first = false;
4499             }
4500             debug!("parse_mod_items: parse_item_or_view_item(attrs={:?})",
4501                    attrs);
4502             match self.parse_item_or_view_item(attrs,
4503                                                true /* macros allowed */) {
4504               IoviItem(item) => items.push(item),
4505               IoviViewItem(view_item) => {
4506                 self.span_fatal(view_item.span,
4507                                 "view items must be declared at the top of \
4508                                  the module");
4509               }
4510               _ => {
4511                   let token_str = self.this_token_to_string();
4512                   self.fatal(format!("expected item, found `{}`",
4513                                      token_str).as_slice())
4514               }
4515             }
4516         }
4517
4518         if first && attrs_remaining_len > 0u {
4519             // We parsed attributes for the first item but didn't find it
4520             let last_span = self.last_span;
4521             self.span_err(last_span, "expected item after attributes");
4522         }
4523
4524         ast::Mod {
4525             inner: mk_sp(inner_lo, self.span.lo),
4526             view_items: view_items,
4527             items: items
4528         }
4529     }
4530
4531     fn parse_item_const(&mut self) -> ItemInfo {
4532         let m = if self.eat_keyword(keywords::Mut) {MutMutable} else {MutImmutable};
4533         let id = self.parse_ident();
4534         self.expect(&token::COLON);
4535         let ty = self.parse_ty(true);
4536         self.expect(&token::EQ);
4537         let e = self.parse_expr();
4538         self.commit_expr_expecting(e, token::SEMI);
4539         (id, ItemStatic(ty, m, e), None)
4540     }
4541
4542     /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
4543     fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> ItemInfo {
4544         let id_span = self.span;
4545         let id = self.parse_ident();
4546         if self.token == token::SEMI {
4547             self.bump();
4548             // This mod is in an external file. Let's go get it!
4549             let (m, attrs) = self.eval_src_mod(id, outer_attrs, id_span);
4550             (id, m, Some(attrs))
4551         } else {
4552             self.push_mod_path(id, outer_attrs);
4553             self.expect(&token::LBRACE);
4554             let mod_inner_lo = self.span.lo;
4555             let old_owns_directory = self.owns_directory;
4556             self.owns_directory = true;
4557             let (inner, next) = self.parse_inner_attrs_and_next();
4558             let m = self.parse_mod_items(token::RBRACE, next, mod_inner_lo);
4559             self.expect(&token::RBRACE);
4560             self.owns_directory = old_owns_directory;
4561             self.pop_mod_path();
4562             (id, ItemMod(m), Some(inner))
4563         }
4564     }
4565
4566     fn push_mod_path(&mut self, id: Ident, attrs: &[Attribute]) {
4567         let default_path = self.id_to_interned_str(id);
4568         let file_path = match ::attr::first_attr_value_str_by_name(attrs,
4569                                                                    "path") {
4570             Some(d) => d,
4571             None => default_path,
4572         };
4573         self.mod_path_stack.push(file_path)
4574     }
4575
4576     fn pop_mod_path(&mut self) {
4577         self.mod_path_stack.pop().unwrap();
4578     }
4579
4580     /// Read a module from a source file.
4581     fn eval_src_mod(&mut self,
4582                     id: ast::Ident,
4583                     outer_attrs: &[ast::Attribute],
4584                     id_sp: Span)
4585                     -> (ast::Item_, Vec<ast::Attribute> ) {
4586         let mut prefix = Path::new(self.sess.span_diagnostic.cm.span_to_filename(self.span));
4587         prefix.pop();
4588         let mod_path = Path::new(".").join_many(self.mod_path_stack.as_slice());
4589         let dir_path = prefix.join(&mod_path);
4590         let mod_string = token::get_ident(id);
4591         let (file_path, owns_directory) = match ::attr::first_attr_value_str_by_name(
4592                 outer_attrs, "path") {
4593             Some(d) => (dir_path.join(d), true),
4594             None => {
4595                 let mod_name = mod_string.get().to_string();
4596                 let default_path_str = format!("{}.rs", mod_name);
4597                 let secondary_path_str = format!("{}/mod.rs", mod_name);
4598                 let default_path = dir_path.join(default_path_str.as_slice());
4599                 let secondary_path = dir_path.join(secondary_path_str.as_slice());
4600                 let default_exists = default_path.exists();
4601                 let secondary_exists = secondary_path.exists();
4602
4603                 if !self.owns_directory {
4604                     self.span_err(id_sp,
4605                                   "cannot declare a new module at this location");
4606                     let this_module = match self.mod_path_stack.last() {
4607                         Some(name) => name.get().to_string(),
4608                         None => self.root_module_name.get_ref().clone(),
4609                     };
4610                     self.span_note(id_sp,
4611                                    format!("maybe move this module `{0}` \
4612                                             to its own directory via \
4613                                             `{0}/mod.rs`",
4614                                            this_module).as_slice());
4615                     if default_exists || secondary_exists {
4616                         self.span_note(id_sp,
4617                                        format!("... or maybe `use` the module \
4618                                                 `{}` instead of possibly \
4619                                                 redeclaring it",
4620                                                mod_name).as_slice());
4621                     }
4622                     self.abort_if_errors();
4623                 }
4624
4625                 match (default_exists, secondary_exists) {
4626                     (true, false) => (default_path, false),
4627                     (false, true) => (secondary_path, true),
4628                     (false, false) => {
4629                         self.span_fatal(id_sp,
4630                                         format!("file not found for module \
4631                                                  `{}`",
4632                                                  mod_name).as_slice());
4633                     }
4634                     (true, true) => {
4635                         self.span_fatal(
4636                             id_sp,
4637                             format!("file for module `{}` found at both {} \
4638                                      and {}",
4639                                     mod_name,
4640                                     default_path_str,
4641                                     secondary_path_str).as_slice());
4642                     }
4643                 }
4644             }
4645         };
4646
4647         self.eval_src_mod_from_path(file_path, owns_directory,
4648                                     mod_string.get().to_string(), id_sp)
4649     }
4650
4651     fn eval_src_mod_from_path(&mut self,
4652                               path: Path,
4653                               owns_directory: bool,
4654                               name: String,
4655                               id_sp: Span) -> (ast::Item_, Vec<ast::Attribute> ) {
4656         let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
4657         match included_mod_stack.iter().position(|p| *p == path) {
4658             Some(i) => {
4659                 let mut err = String::from_str("circular modules: ");
4660                 let len = included_mod_stack.len();
4661                 for p in included_mod_stack.slice(i, len).iter() {
4662                     err.push_str(p.display().as_maybe_owned().as_slice());
4663                     err.push_str(" -> ");
4664                 }
4665                 err.push_str(path.display().as_maybe_owned().as_slice());
4666                 self.span_fatal(id_sp, err.as_slice());
4667             }
4668             None => ()
4669         }
4670         included_mod_stack.push(path.clone());
4671         drop(included_mod_stack);
4672
4673         let mut p0 =
4674             new_sub_parser_from_file(self.sess,
4675                                      self.cfg.clone(),
4676                                      &path,
4677                                      owns_directory,
4678                                      Some(name),
4679                                      id_sp);
4680         let mod_inner_lo = p0.span.lo;
4681         let (mod_attrs, next) = p0.parse_inner_attrs_and_next();
4682         let first_item_outer_attrs = next;
4683         let m0 = p0.parse_mod_items(token::EOF, first_item_outer_attrs, mod_inner_lo);
4684         self.sess.included_mod_stack.borrow_mut().pop();
4685         return (ast::ItemMod(m0), mod_attrs);
4686     }
4687
4688     /// Parse a function declaration from a foreign module
4689     fn parse_item_foreign_fn(&mut self, vis: ast::Visibility,
4690                              attrs: Vec<Attribute>) -> Gc<ForeignItem> {
4691         let lo = self.span.lo;
4692         self.expect_keyword(keywords::Fn);
4693
4694         let (ident, mut generics) = self.parse_fn_header();
4695         let decl = self.parse_fn_decl(true);
4696         self.parse_where_clause(&mut generics);
4697         let hi = self.span.hi;
4698         self.expect(&token::SEMI);
4699         box(GC) ast::ForeignItem { ident: ident,
4700                                    attrs: attrs,
4701                                    node: ForeignItemFn(decl, generics),
4702                                    id: ast::DUMMY_NODE_ID,
4703                                    span: mk_sp(lo, hi),
4704                                    vis: vis }
4705     }
4706
4707     /// Parse a static item from a foreign module
4708     fn parse_item_foreign_static(&mut self, vis: ast::Visibility,
4709                                  attrs: Vec<Attribute> ) -> Gc<ForeignItem> {
4710         let lo = self.span.lo;
4711
4712         self.expect_keyword(keywords::Static);
4713         let mutbl = self.eat_keyword(keywords::Mut);
4714
4715         let ident = self.parse_ident();
4716         self.expect(&token::COLON);
4717         let ty = self.parse_ty(true);
4718         let hi = self.span.hi;
4719         self.expect(&token::SEMI);
4720         box(GC) ast::ForeignItem {
4721             ident: ident,
4722             attrs: attrs,
4723             node: ForeignItemStatic(ty, mutbl),
4724             id: ast::DUMMY_NODE_ID,
4725             span: mk_sp(lo, hi),
4726             vis: vis,
4727         }
4728     }
4729
4730     /// Parse safe/unsafe and fn
4731     fn parse_fn_style(&mut self) -> FnStyle {
4732         if self.eat_keyword(keywords::Fn) { NormalFn }
4733         else if self.eat_keyword(keywords::Unsafe) {
4734             self.expect_keyword(keywords::Fn);
4735             UnsafeFn
4736         }
4737         else { self.unexpected(); }
4738     }
4739
4740
4741     /// At this point, this is essentially a wrapper for
4742     /// parse_foreign_items.
4743     fn parse_foreign_mod_items(&mut self,
4744                                abi: abi::Abi,
4745                                first_item_attrs: Vec<Attribute> )
4746                                -> ForeignMod {
4747         let ParsedItemsAndViewItems {
4748             attrs_remaining: attrs_remaining,
4749             view_items: view_items,
4750             items: _,
4751             foreign_items: foreign_items
4752         } = self.parse_foreign_items(first_item_attrs, true);
4753         if ! attrs_remaining.is_empty() {
4754             let last_span = self.last_span;
4755             self.span_err(last_span,
4756                           "expected item after attributes");
4757         }
4758         assert!(self.token == token::RBRACE);
4759         ast::ForeignMod {
4760             abi: abi,
4761             view_items: view_items,
4762             items: foreign_items
4763         }
4764     }
4765
4766     /// Parse extern crate links
4767     ///
4768     /// # Example
4769     ///
4770     /// extern crate url;
4771     /// extern crate foo = "bar"; //deprecated
4772     /// extern crate "bar" as foo;
4773     fn parse_item_extern_crate(&mut self,
4774                                 lo: BytePos,
4775                                 visibility: Visibility,
4776                                 attrs: Vec<Attribute> )
4777                                 -> ItemOrViewItem {
4778
4779         let (maybe_path, ident) = match self.token {
4780             token::IDENT(..) => {
4781                 let the_ident = self.parse_ident();
4782                 self.expect_one_of(&[], &[token::EQ, token::SEMI]);
4783                 // NOTE - #16689 change this to a warning once
4784                 //        the 'as' support is in stage0
4785                 let path = if self.token == token::EQ {
4786                     self.bump();
4787                     Some(self.parse_str())
4788                 } else {None};
4789
4790                 self.expect(&token::SEMI);
4791                 (path, the_ident)
4792             },
4793             token::LIT_STR(..) | token::LIT_STR_RAW(..) => {
4794                 let path = self.parse_str();
4795                 self.expect_keyword(keywords::As);
4796                 let the_ident = self.parse_ident();
4797                 self.expect(&token::SEMI);
4798                 (Some(path), the_ident)
4799             },
4800             _ => {
4801                 let span = self.span;
4802                 let token_str = self.this_token_to_string();
4803                 self.span_fatal(span,
4804                                 format!("expected extern crate name but \
4805                                          found `{}`",
4806                                         token_str).as_slice());
4807             }
4808         };
4809
4810         IoviViewItem(ast::ViewItem {
4811                 node: ViewItemExternCrate(ident, maybe_path, ast::DUMMY_NODE_ID),
4812                 attrs: attrs,
4813                 vis: visibility,
4814                 span: mk_sp(lo, self.last_span.hi)
4815             })
4816     }
4817
4818     /// Parse `extern` for foreign ABIs
4819     /// modules.
4820     ///
4821     /// `extern` is expected to have been
4822     /// consumed before calling this method
4823     ///
4824     /// # Examples:
4825     ///
4826     /// extern "C" {}
4827     /// extern {}
4828     fn parse_item_foreign_mod(&mut self,
4829                               lo: BytePos,
4830                               opt_abi: Option<abi::Abi>,
4831                               visibility: Visibility,
4832                               attrs: Vec<Attribute> )
4833                               -> ItemOrViewItem {
4834
4835         self.expect(&token::LBRACE);
4836
4837         let abi = opt_abi.unwrap_or(abi::C);
4838
4839         let (inner, next) = self.parse_inner_attrs_and_next();
4840         let m = self.parse_foreign_mod_items(abi, next);
4841         self.expect(&token::RBRACE);
4842
4843         let last_span = self.last_span;
4844         let item = self.mk_item(lo,
4845                                 last_span.hi,
4846                                 special_idents::invalid,
4847                                 ItemForeignMod(m),
4848                                 visibility,
4849                                 maybe_append(attrs, Some(inner)));
4850         return IoviItem(item);
4851     }
4852
4853     /// Parse type Foo = Bar;
4854     fn parse_item_type(&mut self) -> ItemInfo {
4855         let ident = self.parse_ident();
4856         let mut tps = self.parse_generics();
4857         self.parse_where_clause(&mut tps);
4858         self.expect(&token::EQ);
4859         let ty = self.parse_ty(true);
4860         self.expect(&token::SEMI);
4861         (ident, ItemTy(ty, tps), None)
4862     }
4863
4864     /// Parse a structure-like enum variant definition
4865     /// this should probably be renamed or refactored...
4866     fn parse_struct_def(&mut self) -> Gc<StructDef> {
4867         let mut fields: Vec<StructField> = Vec::new();
4868         while self.token != token::RBRACE {
4869             fields.push(self.parse_struct_decl_field());
4870         }
4871         self.bump();
4872
4873         return box(GC) ast::StructDef {
4874             fields: fields,
4875             ctor_id: None,
4876             super_struct: None,
4877             is_virtual: false,
4878         };
4879     }
4880
4881     /// Parse the part of an "enum" decl following the '{'
4882     fn parse_enum_def(&mut self, _generics: &ast::Generics) -> EnumDef {
4883         let mut variants = Vec::new();
4884         let mut all_nullary = true;
4885         let mut have_disr = false;
4886         while self.token != token::RBRACE {
4887             let variant_attrs = self.parse_outer_attributes();
4888             let vlo = self.span.lo;
4889
4890             let vis = self.parse_visibility();
4891
4892             let ident;
4893             let kind;
4894             let mut args = Vec::new();
4895             let mut disr_expr = None;
4896             ident = self.parse_ident();
4897             if self.eat(&token::LBRACE) {
4898                 // Parse a struct variant.
4899                 all_nullary = false;
4900                 kind = StructVariantKind(self.parse_struct_def());
4901             } else if self.token == token::LPAREN {
4902                 all_nullary = false;
4903                 let arg_tys = self.parse_enum_variant_seq(
4904                     &token::LPAREN,
4905                     &token::RPAREN,
4906                     seq_sep_trailing_allowed(token::COMMA),
4907                     |p| p.parse_ty(true)
4908                 );
4909                 for ty in arg_tys.move_iter() {
4910                     args.push(ast::VariantArg {
4911                         ty: ty,
4912                         id: ast::DUMMY_NODE_ID,
4913                     });
4914                 }
4915                 kind = TupleVariantKind(args);
4916             } else if self.eat(&token::EQ) {
4917                 have_disr = true;
4918                 disr_expr = Some(self.parse_expr());
4919                 kind = TupleVariantKind(args);
4920             } else {
4921                 kind = TupleVariantKind(Vec::new());
4922             }
4923
4924             let vr = ast::Variant_ {
4925                 name: ident,
4926                 attrs: variant_attrs,
4927                 kind: kind,
4928                 id: ast::DUMMY_NODE_ID,
4929                 disr_expr: disr_expr,
4930                 vis: vis,
4931             };
4932             variants.push(P(spanned(vlo, self.last_span.hi, vr)));
4933
4934             if !self.eat(&token::COMMA) { break; }
4935         }
4936         self.expect(&token::RBRACE);
4937         if have_disr && !all_nullary {
4938             self.fatal("discriminator values can only be used with a c-like \
4939                         enum");
4940         }
4941
4942         ast::EnumDef { variants: variants }
4943     }
4944
4945     /// Parse an "enum" declaration
4946     fn parse_item_enum(&mut self) -> ItemInfo {
4947         let id = self.parse_ident();
4948         let mut generics = self.parse_generics();
4949         self.parse_where_clause(&mut generics);
4950         self.expect(&token::LBRACE);
4951
4952         let enum_definition = self.parse_enum_def(&generics);
4953         (id, ItemEnum(enum_definition, generics), None)
4954     }
4955
4956     fn fn_expr_lookahead(tok: &token::Token) -> bool {
4957         match *tok {
4958           token::LPAREN | token::AT | token::TILDE | token::BINOP(_) => true,
4959           _ => false
4960         }
4961     }
4962
4963     /// Parses a string as an ABI spec on an extern type or module. Consumes
4964     /// the `extern` keyword, if one is found.
4965     fn parse_opt_abi(&mut self) -> Option<abi::Abi> {
4966         match self.token {
4967             token::LIT_STR(s) | token::LIT_STR_RAW(s, _) => {
4968                 self.bump();
4969                 let the_string = s.as_str();
4970                 match abi::lookup(the_string) {
4971                     Some(abi) => Some(abi),
4972                     None => {
4973                         let last_span = self.last_span;
4974                         self.span_err(
4975                             last_span,
4976                             format!("illegal ABI: expected one of [{}], \
4977                                      found `{}`",
4978                                     abi::all_names().connect(", "),
4979                                     the_string).as_slice());
4980                         None
4981                     }
4982                 }
4983             }
4984
4985             _ => None,
4986         }
4987     }
4988
4989     /// Parse one of the items or view items allowed by the
4990     /// flags; on failure, return IoviNone.
4991     /// NB: this function no longer parses the items inside an
4992     /// extern crate.
4993     fn parse_item_or_view_item(&mut self,
4994                                attrs: Vec<Attribute> ,
4995                                macros_allowed: bool)
4996                                -> ItemOrViewItem {
4997         match self.token {
4998             INTERPOLATED(token::NtItem(item)) => {
4999                 self.bump();
5000                 let new_attrs = attrs.append(item.attrs.as_slice());
5001                 return IoviItem(box(GC) Item {
5002                     attrs: new_attrs,
5003                     ..(*item).clone()
5004                 });
5005             }
5006             _ => {}
5007         }
5008
5009         let lo = self.span.lo;
5010
5011         let visibility = self.parse_visibility();
5012
5013         // must be a view item:
5014         if self.eat_keyword(keywords::Use) {
5015             // USE ITEM (IoviViewItem)
5016             let view_item = self.parse_use();
5017             self.expect(&token::SEMI);
5018             return IoviViewItem(ast::ViewItem {
5019                 node: view_item,
5020                 attrs: attrs,
5021                 vis: visibility,
5022                 span: mk_sp(lo, self.last_span.hi)
5023             });
5024         }
5025         // either a view item or an item:
5026         if self.eat_keyword(keywords::Extern) {
5027             let next_is_mod = self.eat_keyword(keywords::Mod);
5028
5029             if next_is_mod || self.eat_keyword(keywords::Crate) {
5030                 if next_is_mod {
5031                     let last_span = self.last_span;
5032                     self.span_err(mk_sp(lo, last_span.hi),
5033                                  format!("`extern mod` is obsolete, use \
5034                                           `extern crate` instead \
5035                                           to refer to external \
5036                                           crates.").as_slice())
5037                 }
5038                 return self.parse_item_extern_crate(lo, visibility, attrs);
5039             }
5040
5041             let opt_abi = self.parse_opt_abi();
5042
5043             if self.eat_keyword(keywords::Fn) {
5044                 // EXTERN FUNCTION ITEM
5045                 let abi = opt_abi.unwrap_or(abi::C);
5046                 let (ident, item_, extra_attrs) =
5047                     self.parse_item_fn(NormalFn, abi);
5048                 let last_span = self.last_span;
5049                 let item = self.mk_item(lo,
5050                                         last_span.hi,
5051                                         ident,
5052                                         item_,
5053                                         visibility,
5054                                         maybe_append(attrs, extra_attrs));
5055                 return IoviItem(item);
5056             } else if self.token == token::LBRACE {
5057                 return self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs);
5058             }
5059
5060             let span = self.span;
5061             let token_str = self.this_token_to_string();
5062             self.span_fatal(span,
5063                             format!("expected `{}` or `fn`, found `{}`", "{",
5064                                     token_str).as_slice());
5065         }
5066
5067         let is_virtual = self.eat_keyword(keywords::Virtual);
5068         if is_virtual && !self.is_keyword(keywords::Struct) {
5069             let span = self.span;
5070             self.span_err(span,
5071                           "`virtual` keyword may only be used with `struct`");
5072         }
5073
5074         // the rest are all guaranteed to be items:
5075         if self.is_keyword(keywords::Static) {
5076             // STATIC ITEM
5077             self.bump();
5078             let (ident, item_, extra_attrs) = self.parse_item_const();
5079             let last_span = self.last_span;
5080             let item = self.mk_item(lo,
5081                                     last_span.hi,
5082                                     ident,
5083                                     item_,
5084                                     visibility,
5085                                     maybe_append(attrs, extra_attrs));
5086             return IoviItem(item);
5087         }
5088         if self.is_keyword(keywords::Fn) &&
5089                 self.look_ahead(1, |f| !Parser::fn_expr_lookahead(f)) {
5090             // FUNCTION ITEM
5091             self.bump();
5092             let (ident, item_, extra_attrs) =
5093                 self.parse_item_fn(NormalFn, abi::Rust);
5094             let last_span = self.last_span;
5095             let item = self.mk_item(lo,
5096                                     last_span.hi,
5097                                     ident,
5098                                     item_,
5099                                     visibility,
5100                                     maybe_append(attrs, extra_attrs));
5101             return IoviItem(item);
5102         }
5103         if self.is_keyword(keywords::Unsafe)
5104             && self.look_ahead(1u, |t| *t != token::LBRACE) {
5105             // UNSAFE FUNCTION ITEM
5106             self.bump();
5107             let abi = if self.eat_keyword(keywords::Extern) {
5108                 self.parse_opt_abi().unwrap_or(abi::C)
5109             } else {
5110                 abi::Rust
5111             };
5112             self.expect_keyword(keywords::Fn);
5113             let (ident, item_, extra_attrs) =
5114                 self.parse_item_fn(UnsafeFn, abi);
5115             let last_span = self.last_span;
5116             let item = self.mk_item(lo,
5117                                     last_span.hi,
5118                                     ident,
5119                                     item_,
5120                                     visibility,
5121                                     maybe_append(attrs, extra_attrs));
5122             return IoviItem(item);
5123         }
5124         if self.eat_keyword(keywords::Mod) {
5125             // MODULE ITEM
5126             let (ident, item_, extra_attrs) =
5127                 self.parse_item_mod(attrs.as_slice());
5128             let last_span = self.last_span;
5129             let item = self.mk_item(lo,
5130                                     last_span.hi,
5131                                     ident,
5132                                     item_,
5133                                     visibility,
5134                                     maybe_append(attrs, extra_attrs));
5135             return IoviItem(item);
5136         }
5137         if self.eat_keyword(keywords::Type) {
5138             // TYPE ITEM
5139             let (ident, item_, extra_attrs) = self.parse_item_type();
5140             let last_span = self.last_span;
5141             let item = self.mk_item(lo,
5142                                     last_span.hi,
5143                                     ident,
5144                                     item_,
5145                                     visibility,
5146                                     maybe_append(attrs, extra_attrs));
5147             return IoviItem(item);
5148         }
5149         if self.eat_keyword(keywords::Enum) {
5150             // ENUM ITEM
5151             let (ident, item_, extra_attrs) = self.parse_item_enum();
5152             let last_span = self.last_span;
5153             let item = self.mk_item(lo,
5154                                     last_span.hi,
5155                                     ident,
5156                                     item_,
5157                                     visibility,
5158                                     maybe_append(attrs, extra_attrs));
5159             return IoviItem(item);
5160         }
5161         if self.eat_keyword(keywords::Trait) {
5162             // TRAIT ITEM
5163             let (ident, item_, extra_attrs) = self.parse_item_trait();
5164             let last_span = self.last_span;
5165             let item = self.mk_item(lo,
5166                                     last_span.hi,
5167                                     ident,
5168                                     item_,
5169                                     visibility,
5170                                     maybe_append(attrs, extra_attrs));
5171             return IoviItem(item);
5172         }
5173         if self.eat_keyword(keywords::Impl) {
5174             // IMPL ITEM
5175             let (ident, item_, extra_attrs) = self.parse_item_impl();
5176             let last_span = self.last_span;
5177             let item = self.mk_item(lo,
5178                                     last_span.hi,
5179                                     ident,
5180                                     item_,
5181                                     visibility,
5182                                     maybe_append(attrs, extra_attrs));
5183             return IoviItem(item);
5184         }
5185         if self.eat_keyword(keywords::Struct) {
5186             // STRUCT ITEM
5187             let (ident, item_, extra_attrs) = self.parse_item_struct(is_virtual);
5188             let last_span = self.last_span;
5189             let item = self.mk_item(lo,
5190                                     last_span.hi,
5191                                     ident,
5192                                     item_,
5193                                     visibility,
5194                                     maybe_append(attrs, extra_attrs));
5195             return IoviItem(item);
5196         }
5197         self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility)
5198     }
5199
5200     /// Parse a foreign item; on failure, return IoviNone.
5201     fn parse_foreign_item(&mut self,
5202                           attrs: Vec<Attribute> ,
5203                           macros_allowed: bool)
5204                           -> ItemOrViewItem {
5205         maybe_whole!(iovi self, NtItem);
5206         let lo = self.span.lo;
5207
5208         let visibility = self.parse_visibility();
5209
5210         if self.is_keyword(keywords::Static) {
5211             // FOREIGN STATIC ITEM
5212             let item = self.parse_item_foreign_static(visibility, attrs);
5213             return IoviForeignItem(item);
5214         }
5215         if self.is_keyword(keywords::Fn) || self.is_keyword(keywords::Unsafe) {
5216             // FOREIGN FUNCTION ITEM
5217             let item = self.parse_item_foreign_fn(visibility, attrs);
5218             return IoviForeignItem(item);
5219         }
5220         self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility)
5221     }
5222
5223     /// This is the fall-through for parsing items.
5224     fn parse_macro_use_or_failure(
5225         &mut self,
5226         attrs: Vec<Attribute> ,
5227         macros_allowed: bool,
5228         lo: BytePos,
5229         visibility: Visibility
5230     ) -> ItemOrViewItem {
5231         if macros_allowed && !token::is_any_keyword(&self.token)
5232                 && self.look_ahead(1, |t| *t == token::NOT)
5233                 && (self.look_ahead(2, |t| is_plain_ident(t))
5234                     || self.look_ahead(2, |t| *t == token::LPAREN)
5235                     || self.look_ahead(2, |t| *t == token::LBRACE)) {
5236             // MACRO INVOCATION ITEM
5237
5238             // item macro.
5239             let pth = self.parse_path(NoTypesAllowed).path;
5240             self.expect(&token::NOT);
5241
5242             // a 'special' identifier (like what `macro_rules!` uses)
5243             // is optional. We should eventually unify invoc syntax
5244             // and remove this.
5245             let id = if is_plain_ident(&self.token) {
5246                 self.parse_ident()
5247             } else {
5248                 token::special_idents::invalid // no special identifier
5249             };
5250             // eat a matched-delimiter token tree:
5251             let tts = match token::close_delimiter_for(&self.token) {
5252                 Some(ket) => {
5253                     self.bump();
5254                     self.parse_seq_to_end(&ket,
5255                                           seq_sep_none(),
5256                                           |p| p.parse_token_tree())
5257                 }
5258                 None => self.fatal("expected open delimiter")
5259             };
5260             // single-variant-enum... :
5261             let m = ast::MacInvocTT(pth, tts, EMPTY_CTXT);
5262             let m: ast::Mac = codemap::Spanned { node: m,
5263                                              span: mk_sp(self.span.lo,
5264                                                          self.span.hi) };
5265             let item_ = ItemMac(m);
5266             let last_span = self.last_span;
5267             let item = self.mk_item(lo,
5268                                     last_span.hi,
5269                                     id,
5270                                     item_,
5271                                     visibility,
5272                                     attrs);
5273             return IoviItem(item);
5274         }
5275
5276         // FAILURE TO PARSE ITEM
5277         if visibility != Inherited {
5278             let mut s = String::from_str("unmatched visibility `");
5279             if visibility == Public {
5280                 s.push_str("pub")
5281             } else {
5282                 s.push_str("priv")
5283             }
5284             s.push_char('`');
5285             let last_span = self.last_span;
5286             self.span_fatal(last_span, s.as_slice());
5287         }
5288         return IoviNone(attrs);
5289     }
5290
5291     pub fn parse_item_with_outer_attributes(&mut self) -> Option<Gc<Item>> {
5292         let attrs = self.parse_outer_attributes();
5293         self.parse_item(attrs)
5294     }
5295
5296     pub fn parse_item(&mut self, attrs: Vec<Attribute> ) -> Option<Gc<Item>> {
5297         match self.parse_item_or_view_item(attrs, true) {
5298             IoviNone(_) => None,
5299             IoviViewItem(_) =>
5300                 self.fatal("view items are not allowed here"),
5301             IoviForeignItem(_) =>
5302                 self.fatal("foreign items are not allowed here"),
5303             IoviItem(item) => Some(item)
5304         }
5305     }
5306
5307     /// Parse, e.g., "use a::b::{z,y}"
5308     fn parse_use(&mut self) -> ViewItem_ {
5309         return ViewItemUse(self.parse_view_path());
5310     }
5311
5312
5313     /// Matches view_path : MOD? IDENT EQ non_global_path
5314     /// | MOD? non_global_path MOD_SEP LBRACE RBRACE
5315     /// | MOD? non_global_path MOD_SEP LBRACE ident_seq RBRACE
5316     /// | MOD? non_global_path MOD_SEP STAR
5317     /// | MOD? non_global_path
5318     fn parse_view_path(&mut self) -> Gc<ViewPath> {
5319         let lo = self.span.lo;
5320
5321         if self.token == token::LBRACE {
5322             // use {foo,bar}
5323             let idents = self.parse_unspanned_seq(
5324                 &token::LBRACE, &token::RBRACE,
5325                 seq_sep_trailing_allowed(token::COMMA),
5326                 |p| p.parse_path_list_item());
5327             let path = ast::Path {
5328                 span: mk_sp(lo, self.span.hi),
5329                 global: false,
5330                 segments: Vec::new()
5331             };
5332             return box(GC) spanned(lo, self.span.hi,
5333                             ViewPathList(path, idents, ast::DUMMY_NODE_ID));
5334         }
5335
5336         let first_ident = self.parse_ident();
5337         let mut path = vec!(first_ident);
5338         match self.token {
5339           token::EQ => {
5340             // x = foo::bar
5341             self.bump();
5342             let path_lo = self.span.lo;
5343             path = vec!(self.parse_ident());
5344             while self.token == token::MOD_SEP {
5345                 self.bump();
5346                 let id = self.parse_ident();
5347                 path.push(id);
5348             }
5349             let span = mk_sp(path_lo, self.span.hi);
5350             self.obsolete(span, ObsoleteImportRenaming);
5351             let path = ast::Path {
5352                 span: span,
5353                 global: false,
5354                 segments: path.move_iter().map(|identifier| {
5355                     ast::PathSegment {
5356                         identifier: identifier,
5357                         lifetimes: Vec::new(),
5358                         types: OwnedSlice::empty(),
5359                     }
5360                 }).collect()
5361             };
5362             return box(GC) spanned(lo, self.span.hi,
5363                             ViewPathSimple(first_ident, path,
5364                                            ast::DUMMY_NODE_ID));
5365           }
5366
5367           token::MOD_SEP => {
5368             // foo::bar or foo::{a,b,c} or foo::*
5369             while self.token == token::MOD_SEP {
5370                 self.bump();
5371
5372                 match self.token {
5373                   token::IDENT(i, _) => {
5374                     self.bump();
5375                     path.push(i);
5376                   }
5377
5378                   // foo::bar::{a,b,c}
5379                   token::LBRACE => {
5380                     let idents = self.parse_unspanned_seq(
5381                         &token::LBRACE,
5382                         &token::RBRACE,
5383                         seq_sep_trailing_allowed(token::COMMA),
5384                         |p| p.parse_path_list_item()
5385                     );
5386                     let path = ast::Path {
5387                         span: mk_sp(lo, self.span.hi),
5388                         global: false,
5389                         segments: path.move_iter().map(|identifier| {
5390                             ast::PathSegment {
5391                                 identifier: identifier,
5392                                 lifetimes: Vec::new(),
5393                                 types: OwnedSlice::empty(),
5394                             }
5395                         }).collect()
5396                     };
5397                     return box(GC) spanned(lo, self.span.hi,
5398                                     ViewPathList(path, idents, ast::DUMMY_NODE_ID));
5399                   }
5400
5401                   // foo::bar::*
5402                   token::BINOP(token::STAR) => {
5403                     self.bump();
5404                     let path = ast::Path {
5405                         span: mk_sp(lo, self.span.hi),
5406                         global: false,
5407                         segments: path.move_iter().map(|identifier| {
5408                             ast::PathSegment {
5409                                 identifier: identifier,
5410                                 lifetimes: Vec::new(),
5411                                 types: OwnedSlice::empty(),
5412                             }
5413                         }).collect()
5414                     };
5415                     return box(GC) spanned(lo, self.span.hi,
5416                                     ViewPathGlob(path, ast::DUMMY_NODE_ID));
5417                   }
5418
5419                   _ => break
5420                 }
5421             }
5422           }
5423           _ => ()
5424         }
5425         let mut rename_to = *path.get(path.len() - 1u);
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         if self.eat_keyword(keywords::As) {
5438             rename_to = self.parse_ident()
5439         }
5440         return box(GC) spanned(lo,
5441                         self.last_span.hi,
5442                         ViewPathSimple(rename_to, path, ast::DUMMY_NODE_ID));
5443     }
5444
5445     /// Parses a sequence of items. Stops when it finds program
5446     /// text that can't be parsed as an item
5447     /// - mod_items uses extern_mod_allowed = true
5448     /// - block_tail_ uses extern_mod_allowed = false
5449     fn parse_items_and_view_items(&mut self,
5450                                   first_item_attrs: Vec<Attribute> ,
5451                                   mut extern_mod_allowed: bool,
5452                                   macros_allowed: bool)
5453                                   -> ParsedItemsAndViewItems {
5454         let mut attrs = first_item_attrs.append(self.parse_outer_attributes().as_slice());
5455         // First, parse view items.
5456         let mut view_items : Vec<ast::ViewItem> = Vec::new();
5457         let mut items = Vec::new();
5458
5459         // I think this code would probably read better as a single
5460         // loop with a mutable three-state-variable (for extern crates,
5461         // view items, and regular items) ... except that because
5462         // of macros, I'd like to delay that entire check until later.
5463         loop {
5464             match self.parse_item_or_view_item(attrs, macros_allowed) {
5465                 IoviNone(attrs) => {
5466                     return ParsedItemsAndViewItems {
5467                         attrs_remaining: attrs,
5468                         view_items: view_items,
5469                         items: items,
5470                         foreign_items: Vec::new()
5471                     }
5472                 }
5473                 IoviViewItem(view_item) => {
5474                     match view_item.node {
5475                         ViewItemUse(..) => {
5476                             // `extern crate` must precede `use`.
5477                             extern_mod_allowed = false;
5478                         }
5479                         ViewItemExternCrate(..) if !extern_mod_allowed => {
5480                             self.span_err(view_item.span,
5481                                           "\"extern crate\" declarations are \
5482                                            not allowed here");
5483                         }
5484                         ViewItemExternCrate(..) => {}
5485                     }
5486                     view_items.push(view_item);
5487                 }
5488                 IoviItem(item) => {
5489                     items.push(item);
5490                     attrs = self.parse_outer_attributes();
5491                     break;
5492                 }
5493                 IoviForeignItem(_) => {
5494                     fail!();
5495                 }
5496             }
5497             attrs = self.parse_outer_attributes();
5498         }
5499
5500         // Next, parse items.
5501         loop {
5502             match self.parse_item_or_view_item(attrs, macros_allowed) {
5503                 IoviNone(returned_attrs) => {
5504                     attrs = returned_attrs;
5505                     break
5506                 }
5507                 IoviViewItem(view_item) => {
5508                     attrs = self.parse_outer_attributes();
5509                     self.span_err(view_item.span,
5510                                   "`use` and `extern crate` declarations must precede items");
5511                 }
5512                 IoviItem(item) => {
5513                     attrs = self.parse_outer_attributes();
5514                     items.push(item)
5515                 }
5516                 IoviForeignItem(_) => {
5517                     fail!();
5518                 }
5519             }
5520         }
5521
5522         ParsedItemsAndViewItems {
5523             attrs_remaining: attrs,
5524             view_items: view_items,
5525             items: items,
5526             foreign_items: Vec::new()
5527         }
5528     }
5529
5530     /// Parses a sequence of foreign items. Stops when it finds program
5531     /// text that can't be parsed as an item
5532     fn parse_foreign_items(&mut self, first_item_attrs: Vec<Attribute> ,
5533                            macros_allowed: bool)
5534         -> ParsedItemsAndViewItems {
5535         let mut attrs = first_item_attrs.append(self.parse_outer_attributes().as_slice());
5536         let mut foreign_items = Vec::new();
5537         loop {
5538             match self.parse_foreign_item(attrs, macros_allowed) {
5539                 IoviNone(returned_attrs) => {
5540                     if self.token == token::RBRACE {
5541                         attrs = returned_attrs;
5542                         break
5543                     }
5544                     self.unexpected();
5545                 },
5546                 IoviViewItem(view_item) => {
5547                     // I think this can't occur:
5548                     self.span_err(view_item.span,
5549                                   "`use` and `extern crate` declarations must precede items");
5550                 }
5551                 IoviItem(item) => {
5552                     // FIXME #5668: this will occur for a macro invocation:
5553                     self.span_fatal(item.span, "macros cannot expand to foreign items");
5554                 }
5555                 IoviForeignItem(foreign_item) => {
5556                     foreign_items.push(foreign_item);
5557                 }
5558             }
5559             attrs = self.parse_outer_attributes();
5560         }
5561
5562         ParsedItemsAndViewItems {
5563             attrs_remaining: attrs,
5564             view_items: Vec::new(),
5565             items: Vec::new(),
5566             foreign_items: foreign_items
5567         }
5568     }
5569
5570     /// Parses a source module as a crate. This is the main
5571     /// entry point for the parser.
5572     pub fn parse_crate_mod(&mut self) -> Crate {
5573         let lo = self.span.lo;
5574         // parse the crate's inner attrs, maybe (oops) one
5575         // of the attrs of an item:
5576         let (inner, next) = self.parse_inner_attrs_and_next();
5577         let first_item_outer_attrs = next;
5578         // parse the items inside the crate:
5579         let m = self.parse_mod_items(token::EOF, first_item_outer_attrs, lo);
5580
5581         ast::Crate {
5582             module: m,
5583             attrs: inner,
5584             config: self.cfg.clone(),
5585             span: mk_sp(lo, self.span.lo),
5586             exported_macros: Vec::new(),
5587         }
5588     }
5589
5590     pub fn parse_optional_str(&mut self)
5591                               -> Option<(InternedString, ast::StrStyle)> {
5592         let (s, style) = match self.token {
5593             token::LIT_STR(s) => (self.id_to_interned_str(s.ident()), ast::CookedStr),
5594             token::LIT_STR_RAW(s, n) => {
5595                 (self.id_to_interned_str(s.ident()), ast::RawStr(n))
5596             }
5597             _ => return None
5598         };
5599         self.bump();
5600         Some((s, style))
5601     }
5602
5603     pub fn parse_str(&mut self) -> (InternedString, StrStyle) {
5604         match self.parse_optional_str() {
5605             Some(s) => { s }
5606             _ =>  self.fatal("expected string literal")
5607         }
5608     }
5609 }
5610