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