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