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