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