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