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