]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/parse/parser.rs
Do not use entropy during gen_weighted_bool(1)
[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 pub use self::PathParsingMode::*;
14 use self::ItemOrViewItem::*;
15
16 use abi;
17 use ast::{AssociatedType, BareFnTy, ClosureTy};
18 use ast::{RegionTyParamBound, TraitTyParamBound, TraitBoundModifier};
19 use ast::{ProvidedMethod, Public, Unsafety};
20 use ast::{Mod, BiAdd, Arg, Arm, Attribute, BindByRef, BindByValue};
21 use ast::{BiBitAnd, BiBitOr, BiBitXor, BiRem, Block};
22 use ast::{BlockCheckMode, CaptureByRef, CaptureByValue, CaptureClause};
23 use ast::{Crate, CrateConfig, Decl, DeclItem};
24 use ast::{DeclLocal, DefaultBlock, UnDeref, BiDiv, EMPTY_CTXT, EnumDef, ExplicitSelf};
25 use ast::{Expr, Expr_, ExprAddrOf, ExprMatch, ExprAgain};
26 use ast::{ExprAssign, ExprAssignOp, ExprBinary, ExprBlock, ExprBox};
27 use ast::{ExprBreak, ExprCall, ExprCast};
28 use ast::{ExprField, ExprTupField, ExprClosure, ExprIf, ExprIfLet, ExprIndex};
29 use ast::{ExprLit, ExprLoop, ExprMac, ExprRange};
30 use ast::{ExprMethodCall, ExprParen, ExprPath};
31 use ast::{ExprRepeat, ExprRet, ExprStruct, ExprTup, ExprUnary};
32 use ast::{ExprVec, ExprWhile, ExprWhileLet, ExprForLoop, Field, FnDecl};
33 use ast::{Many};
34 use ast::{FnUnboxedClosureKind, FnMutUnboxedClosureKind};
35 use ast::{FnOnceUnboxedClosureKind};
36 use ast::{ForeignItem, ForeignItemStatic, ForeignItemFn, ForeignMod, FunctionRetTy};
37 use ast::{Ident, Inherited, ImplItem, Item, Item_, ItemStatic};
38 use ast::{ItemEnum, ItemFn, ItemForeignMod, ItemImpl, ItemConst};
39 use ast::{ItemMac, ItemMod, ItemStruct, ItemTrait, ItemTy};
40 use ast::{LifetimeDef, Lit, Lit_};
41 use ast::{LitBool, LitChar, LitByte, LitBinary};
42 use ast::{LitStr, LitInt, Local, LocalLet};
43 use ast::{MacStmtWithBraces, MacStmtWithSemicolon, MacStmtWithoutBraces};
44 use ast::{MutImmutable, MutMutable, Mac_, MacInvocTT, MatchSource};
45 use ast::{Method, MutTy, BiMul, Mutability};
46 use ast::{MethodImplItem, NamedField, UnNeg, NoReturn, NodeId, UnNot};
47 use ast::{Pat, PatEnum, PatIdent, PatLit, PatRange, PatRegion, PatStruct};
48 use ast::{PatTup, PatBox, PatWild, PatWildMulti, PatWildSingle};
49 use ast::{PolyTraitRef};
50 use ast::{QPath, RequiredMethod};
51 use ast::{Return, BiShl, BiShr, Stmt, StmtDecl};
52 use ast::{StmtExpr, StmtSemi, StmtMac, StructDef, StructField};
53 use ast::{StructVariantKind, BiSub, StrStyle};
54 use ast::{SelfExplicit, SelfRegion, SelfStatic, SelfValue};
55 use ast::{Delimited, SequenceRepetition, TokenTree, TraitItem, TraitRef};
56 use ast::{TtDelimited, TtSequence, TtToken};
57 use ast::{TupleVariantKind, Ty, Ty_, TypeBinding};
58 use ast::{TypeField, TyFixedLengthVec, TyClosure, TyBareFn};
59 use ast::{TyTypeof, TyInfer, TypeMethod};
60 use ast::{TyParam, TyParamBound, TyParen, TyPath, TyPolyTraitRef, TyPtr, TyQPath};
61 use ast::{TyRptr, TyTup, TyU32, TyVec, UnUniq};
62 use ast::{TypeImplItem, TypeTraitItem, Typedef, UnboxedClosureKind};
63 use ast::{UnnamedField, UnsafeBlock};
64 use ast::{ViewItem, ViewItem_, ViewItemExternCrate, ViewItemUse};
65 use ast::{ViewPath, ViewPathGlob, ViewPathList, ViewPathSimple};
66 use ast::{Visibility, WhereClause};
67 use ast;
68 use ast_util::{self, as_prec, ident_to_path, operator_prec};
69 use codemap::{self, Span, BytePos, Spanned, spanned, mk_sp, DUMMY_SP};
70 use diagnostic;
71 use ext::tt::macro_parser;
72 use parse;
73 use parse::attr::ParserAttr;
74 use parse::classify;
75 use parse::common::{SeqSep, seq_sep_none, seq_sep_trailing_allowed};
76 use parse::lexer::{Reader, TokenAndSpan};
77 use parse::obsolete::*;
78 use parse::token::{self, MatchNt, SubstNt, InternedString};
79 use parse::token::{keywords, special_idents};
80 use parse::{new_sub_parser_from_file, ParseSess};
81 use print::pprust;
82 use ptr::P;
83 use owned_slice::OwnedSlice;
84
85 use std::collections::HashSet;
86 use std::io::fs::PathExtensions;
87 use std::iter;
88 use std::mem;
89 use std::num::Float;
90 use std::rc::Rc;
91 use std::slice;
92
93 bitflags! {
94     flags Restrictions: u8 {
95         const UNRESTRICTED                  = 0b0000,
96         const RESTRICTION_STMT_EXPR         = 0b0001,
97         const RESTRICTION_NO_BAR_OP         = 0b0010,
98         const RESTRICTION_NO_STRUCT_LITERAL = 0b0100,
99         const RESTRICTION_NO_DOTS           = 0b1000,
100     }
101 }
102
103
104 type ItemInfo = (Ident, Item_, Option<Vec<Attribute> >);
105
106 /// How to parse a path. There are four different kinds of paths, all of which
107 /// are parsed somewhat differently.
108 #[derive(Copy, PartialEq)]
109 pub enum PathParsingMode {
110     /// A path with no type parameters; e.g. `foo::bar::Baz`
111     NoTypesAllowed,
112     /// A path with a lifetime and type parameters, with no double colons
113     /// before the type parameters; e.g. `foo::bar<'a>::Baz<T>`
114     LifetimeAndTypesWithoutColons,
115     /// A path with a lifetime and type parameters with double colons before
116     /// the type parameters; e.g. `foo::bar::<'a>::Baz::<T>`
117     LifetimeAndTypesWithColons,
118 }
119
120 /// How to parse a bound, whether to allow bound modifiers such as `?`.
121 #[derive(Copy, PartialEq)]
122 pub enum BoundParsingMode {
123     Bare,
124     Modified,
125 }
126
127 enum ItemOrViewItem {
128     /// Indicates a failure to parse any kind of item. The attributes are
129     /// returned.
130     IoviNone(Vec<Attribute>),
131     IoviItem(P<Item>),
132     IoviForeignItem(P<ForeignItem>),
133     IoviViewItem(ViewItem)
134 }
135
136
137 /// Possibly accept an `token::Interpolated` expression (a pre-parsed expression
138 /// dropped into the token stream, which happens while parsing the result of
139 /// macro expansion). Placement of these is not as complex as I feared it would
140 /// be. The important thing is to make sure that lookahead doesn't balk at
141 /// `token::Interpolated` tokens.
142 macro_rules! maybe_whole_expr {
143     ($p:expr) => (
144         {
145             let found = match $p.token {
146                 token::Interpolated(token::NtExpr(ref e)) => {
147                     Some((*e).clone())
148                 }
149                 token::Interpolated(token::NtPath(_)) => {
150                     // FIXME: The following avoids an issue with lexical borrowck scopes,
151                     // but the clone is unfortunate.
152                     let pt = match $p.token {
153                         token::Interpolated(token::NtPath(ref pt)) => (**pt).clone(),
154                         _ => unreachable!()
155                     };
156                     let span = $p.span;
157                     Some($p.mk_expr(span.lo, span.hi, ExprPath(pt)))
158                 }
159                 token::Interpolated(token::NtBlock(_)) => {
160                     // FIXME: The following avoids an issue with lexical borrowck scopes,
161                     // but the clone is unfortunate.
162                     let b = match $p.token {
163                         token::Interpolated(token::NtBlock(ref b)) => (*b).clone(),
164                         _ => unreachable!()
165                     };
166                     let span = $p.span;
167                     Some($p.mk_expr(span.lo, span.hi, ExprBlock(b)))
168                 }
169                 _ => None
170             };
171             match found {
172                 Some(e) => {
173                     $p.bump();
174                     return e;
175                 }
176                 None => ()
177             }
178         }
179     )
180 }
181
182 /// As maybe_whole_expr, but for things other than expressions
183 macro_rules! maybe_whole {
184     ($p:expr, $constructor:ident) => (
185         {
186             let found = match ($p).token {
187                 token::Interpolated(token::$constructor(_)) => {
188                     Some(($p).bump_and_get())
189                 }
190                 _ => None
191             };
192             if let Some(token::Interpolated(token::$constructor(x))) = found {
193                 return x.clone();
194             }
195         }
196     );
197     (no_clone $p:expr, $constructor:ident) => (
198         {
199             let found = match ($p).token {
200                 token::Interpolated(token::$constructor(_)) => {
201                     Some(($p).bump_and_get())
202                 }
203                 _ => None
204             };
205             if let Some(token::Interpolated(token::$constructor(x))) = found {
206                 return x;
207             }
208         }
209     );
210     (deref $p:expr, $constructor:ident) => (
211         {
212             let found = match ($p).token {
213                 token::Interpolated(token::$constructor(_)) => {
214                     Some(($p).bump_and_get())
215                 }
216                 _ => None
217             };
218             if let Some(token::Interpolated(token::$constructor(x))) = found {
219                 return (*x).clone();
220             }
221         }
222     );
223     (Some $p:expr, $constructor:ident) => (
224         {
225             let found = match ($p).token {
226                 token::Interpolated(token::$constructor(_)) => {
227                     Some(($p).bump_and_get())
228                 }
229                 _ => None
230             };
231             if let Some(token::Interpolated(token::$constructor(x))) = found {
232                 return Some(x.clone());
233             }
234         }
235     );
236     (iovi $p:expr, $constructor:ident) => (
237         {
238             let found = match ($p).token {
239                 token::Interpolated(token::$constructor(_)) => {
240                     Some(($p).bump_and_get())
241                 }
242                 _ => None
243             };
244             if let Some(token::Interpolated(token::$constructor(x))) = found {
245                 return IoviItem(x.clone());
246             }
247         }
248     );
249     (pair_empty $p:expr, $constructor:ident) => (
250         {
251             let found = match ($p).token {
252                 token::Interpolated(token::$constructor(_)) => {
253                     Some(($p).bump_and_get())
254                 }
255                 _ => None
256             };
257             if let Some(token::Interpolated(token::$constructor(x))) = found {
258                 return (Vec::new(), x);
259             }
260         }
261     )
262 }
263
264
265 fn maybe_append(mut lhs: Vec<Attribute>, rhs: Option<Vec<Attribute>>)
266                 -> Vec<Attribute> {
267     match rhs {
268         Some(ref attrs) => lhs.extend(attrs.iter().map(|a| a.clone())),
269         None => {}
270     }
271     lhs
272 }
273
274
275 struct ParsedItemsAndViewItems {
276     attrs_remaining: Vec<Attribute>,
277     view_items: Vec<ViewItem>,
278     items: Vec<P<Item>> ,
279     foreign_items: Vec<P<ForeignItem>>
280 }
281
282 /* ident is handled by common.rs */
283
284 pub struct Parser<'a> {
285     pub sess: &'a ParseSess,
286     /// the current token:
287     pub token: token::Token,
288     /// the span of the current token:
289     pub span: Span,
290     /// the span of the prior token:
291     pub last_span: Span,
292     pub cfg: CrateConfig,
293     /// the previous token or None (only stashed sometimes).
294     pub last_token: Option<Box<token::Token>>,
295     pub buffer: [TokenAndSpan; 4],
296     pub buffer_start: int,
297     pub buffer_end: int,
298     pub tokens_consumed: uint,
299     pub restrictions: Restrictions,
300     pub quote_depth: uint, // not (yet) related to the quasiquoter
301     pub reader: Box<Reader+'a>,
302     pub interner: Rc<token::IdentInterner>,
303     /// The set of seen errors about obsolete syntax. Used to suppress
304     /// extra detail when the same error is seen twice
305     pub obsolete_set: HashSet<ObsoleteSyntax>,
306     /// Used to determine the path to externally loaded source files
307     pub mod_path_stack: Vec<InternedString>,
308     /// Stack of spans of open delimiters. Used for error message.
309     pub open_braces: Vec<Span>,
310     /// Flag if this parser "owns" the directory that it is currently parsing
311     /// in. This will affect how nested files are looked up.
312     pub owns_directory: bool,
313     /// Name of the root module this parser originated from. If `None`, then the
314     /// name is not known. This does not change while the parser is descending
315     /// into modules, and sub-parsers have new values for this name.
316     pub root_module_name: Option<String>,
317     pub expected_tokens: Vec<TokenType>,
318 }
319
320 #[derive(PartialEq, Eq, Clone)]
321 pub enum TokenType {
322     Token(token::Token),
323     Operator,
324 }
325
326 impl TokenType {
327     fn to_string(&self) -> String {
328         match *self {
329             TokenType::Token(ref t) => format!("`{}`", Parser::token_to_string(t)),
330             TokenType::Operator => "an operator".to_string(),
331         }
332     }
333 }
334
335 fn is_plain_ident_or_underscore(t: &token::Token) -> bool {
336     t.is_plain_ident() || *t == token::Underscore
337 }
338
339 impl<'a> Parser<'a> {
340     pub fn new(sess: &'a ParseSess,
341                cfg: ast::CrateConfig,
342                mut rdr: Box<Reader+'a>)
343                -> Parser<'a>
344     {
345         let tok0 = rdr.real_token();
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             restrictions: 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             expected_tokens: Vec::new(),
378         }
379     }
380
381     /// Convert a token to a string using self's reader
382     pub fn token_to_string(token: &token::Token) -> String {
383         pprust::token_to_string(token)
384     }
385
386     /// Convert the current token to a string using self's reader
387     pub fn this_token_to_string(&mut self) -> String {
388         Parser::token_to_string(&self.token)
389     }
390
391     pub fn unexpected_last(&mut self, t: &token::Token) -> ! {
392         let token_str = Parser::token_to_string(t);
393         let last_span = self.last_span;
394         self.span_fatal(last_span, format!("unexpected token: `{}`",
395                                                 token_str)[]);
396     }
397
398     pub fn unexpected(&mut self) -> ! {
399         let this_token = self.this_token_to_string();
400         self.fatal(format!("unexpected token: `{}`", this_token)[]);
401     }
402
403     /// Expect and consume the token t. Signal an error if
404     /// the next token is not t.
405     pub fn expect(&mut self, t: &token::Token) {
406         if self.expected_tokens.is_empty() {
407             if self.token == *t {
408                 self.bump();
409             } else {
410                 let token_str = Parser::token_to_string(t);
411                 let this_token_str = self.this_token_to_string();
412                 self.fatal(format!("expected `{}`, found `{}`",
413                                    token_str,
414                                    this_token_str)[])
415             }
416         } else {
417             self.expect_one_of(slice::ref_slice(t), &[]);
418         }
419     }
420
421     /// Expect next token to be edible or inedible token.  If edible,
422     /// then consume it; if inedible, then return without consuming
423     /// anything.  Signal a fatal error if next token is unexpected.
424     pub fn expect_one_of(&mut self,
425                          edible: &[token::Token],
426                          inedible: &[token::Token]) {
427         fn tokens_to_string(tokens: &[TokenType]) -> String {
428             let mut i = tokens.iter();
429             // This might be a sign we need a connect method on Iterator.
430             let b = i.next()
431                      .map_or("".to_string(), |t| t.to_string());
432             i.enumerate().fold(b, |mut b, (i, ref a)| {
433                 if tokens.len() > 2 && i == tokens.len() - 2 {
434                     b.push_str(", or ");
435                 } else if tokens.len() == 2 && i == tokens.len() - 2 {
436                     b.push_str(" or ");
437                 } else {
438                     b.push_str(", ");
439                 }
440                 b.push_str(&*a.to_string());
441                 b
442             })
443         }
444         if edible.contains(&self.token) {
445             self.bump();
446         } else if inedible.contains(&self.token) {
447             // leave it in the input
448         } else {
449             let mut expected = edible.iter().map(|x| TokenType::Token(x.clone()))
450                                             .collect::<Vec<_>>();
451             expected.extend(inedible.iter().map(|x| TokenType::Token(x.clone())));
452             expected.push_all(&*self.expected_tokens);
453             expected.sort_by(|a, b| a.to_string().cmp(&b.to_string()));
454             expected.dedup();
455             let expect = tokens_to_string(expected[]);
456             let actual = self.this_token_to_string();
457             self.fatal(
458                 (if expected.len() != 1 {
459                     (format!("expected one of {}, found `{}`",
460                              expect,
461                              actual))
462                 } else {
463                     (format!("expected {}, found `{}`",
464                              expect,
465                              actual))
466                 })[]
467             )
468         }
469     }
470
471     /// Check for erroneous `ident { }`; if matches, signal error and
472     /// recover (without consuming any expected input token).  Returns
473     /// true if and only if input was consumed for recovery.
474     pub fn check_for_erroneous_unit_struct_expecting(&mut self, expected: &[token::Token]) -> bool {
475         if self.token == token::OpenDelim(token::Brace)
476             && expected.iter().all(|t| *t != token::OpenDelim(token::Brace))
477             && self.look_ahead(1, |t| *t == token::CloseDelim(token::Brace)) {
478             // matched; signal non-fatal error and recover.
479             let span = self.span;
480             self.span_err(span,
481                           "unit-like struct construction is written with no trailing `{ }`");
482             self.eat(&token::OpenDelim(token::Brace));
483             self.eat(&token::CloseDelim(token::Brace));
484             true
485         } else {
486             false
487         }
488     }
489
490     /// Commit to parsing a complete expression `e` expected to be
491     /// followed by some token from the set edible + inedible.  Recover
492     /// from anticipated input errors, discarding erroneous characters.
493     pub fn commit_expr(&mut self, e: &Expr, edible: &[token::Token], inedible: &[token::Token]) {
494         debug!("commit_expr {}", e);
495         if let ExprPath(..) = e.node {
496             // might be unit-struct construction; check for recoverableinput error.
497             let mut expected = edible.iter().map(|x| x.clone()).collect::<Vec<_>>();
498             expected.push_all(inedible);
499             self.check_for_erroneous_unit_struct_expecting(expected[]);
500         }
501         self.expect_one_of(edible, inedible)
502     }
503
504     pub fn commit_expr_expecting(&mut self, e: &Expr, edible: token::Token) {
505         self.commit_expr(e, &[edible], &[])
506     }
507
508     /// Commit to parsing a complete statement `s`, which expects to be
509     /// followed by some token from the set edible + inedible.  Check
510     /// for recoverable input errors, discarding erroneous characters.
511     pub fn commit_stmt(&mut self, edible: &[token::Token], inedible: &[token::Token]) {
512         if self.last_token
513                .as_ref()
514                .map_or(false, |t| t.is_ident() || t.is_path()) {
515             let mut expected = edible.iter().map(|x| x.clone()).collect::<Vec<_>>();
516             expected.push_all(inedible[]);
517             self.check_for_erroneous_unit_struct_expecting(
518                 expected[]);
519         }
520         self.expect_one_of(edible, inedible)
521     }
522
523     pub fn commit_stmt_expecting(&mut self, edible: token::Token) {
524         self.commit_stmt(&[edible], &[])
525     }
526
527     pub fn parse_ident(&mut self) -> ast::Ident {
528         self.check_strict_keywords();
529         self.check_reserved_keywords();
530         match self.token {
531             token::Ident(i, _) => {
532                 self.bump();
533                 i
534             }
535             token::Interpolated(token::NtIdent(..)) => {
536                 self.bug("ident interpolation not converted to real token");
537             }
538             _ => {
539                 let token_str = self.this_token_to_string();
540                 self.fatal((format!("expected ident, found `{}`",
541                                     token_str))[])
542             }
543         }
544     }
545
546     pub fn parse_path_list_item(&mut self) -> ast::PathListItem {
547         let lo = self.span.lo;
548         let node = if self.eat_keyword(keywords::Mod) {
549             let span = self.last_span;
550             self.span_warn(span, "deprecated syntax; use the `self` keyword now");
551             ast::PathListMod { id: ast::DUMMY_NODE_ID }
552         } else if self.eat_keyword(keywords::Self) {
553             ast::PathListMod { id: ast::DUMMY_NODE_ID }
554         } else {
555             let ident = self.parse_ident();
556             ast::PathListIdent { name: ident, id: ast::DUMMY_NODE_ID }
557         };
558         let hi = self.last_span.hi;
559         spanned(lo, hi, node)
560     }
561
562     /// Check if the next token is `tok`, and return `true` if so.
563     ///
564     /// This method is will automatically add `tok` to `expected_tokens` if `tok` is not
565     /// encountered.
566     pub fn check(&mut self, tok: &token::Token) -> bool {
567         let is_present = self.token == *tok;
568         if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
569         is_present
570     }
571
572     /// Consume token 'tok' if it exists. Returns true if the given
573     /// token was present, false otherwise.
574     pub fn eat(&mut self, tok: &token::Token) -> bool {
575         let is_present = self.check(tok);
576         if is_present { self.bump() }
577         is_present
578     }
579
580     /// If the next token is the given keyword, eat it and return
581     /// true. Otherwise, return false.
582     pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
583         if self.token.is_keyword(kw) {
584             self.bump();
585             true
586         } else {
587             false
588         }
589     }
590
591     /// If the given word is not a keyword, signal an error.
592     /// If the next token is not the given word, signal an error.
593     /// Otherwise, eat it.
594     pub fn expect_keyword(&mut self, kw: keywords::Keyword) {
595         if !self.eat_keyword(kw) {
596             let id_interned_str = token::get_name(kw.to_name());
597             let token_str = self.this_token_to_string();
598             self.fatal(format!("expected `{}`, found `{}`",
599                                id_interned_str, token_str)[])
600         }
601     }
602
603     /// Signal an error if the given string is a strict keyword
604     pub fn check_strict_keywords(&mut self) {
605         if self.token.is_strict_keyword() {
606             let token_str = self.this_token_to_string();
607             let span = self.span;
608             self.span_err(span,
609                           format!("expected identifier, found keyword `{}`",
610                                   token_str)[]);
611         }
612     }
613
614     /// Signal an error if the current token is a reserved keyword
615     pub fn check_reserved_keywords(&mut self) {
616         if self.token.is_reserved_keyword() {
617             let token_str = self.this_token_to_string();
618             self.fatal(format!("`{}` is a reserved keyword",
619                                token_str)[])
620         }
621     }
622
623     /// Expect and consume an `&`. If `&&` is seen, replace it with a single
624     /// `&` and continue. If an `&` is not seen, signal an error.
625     fn expect_and(&mut self) {
626         match self.token {
627             token::BinOp(token::And) => self.bump(),
628             token::AndAnd => {
629                 let span = self.span;
630                 let lo = span.lo + BytePos(1);
631                 self.replace_token(token::BinOp(token::And), lo, span.hi)
632             }
633             _ => {
634                 let token_str = self.this_token_to_string();
635                 let found_token =
636                     Parser::token_to_string(&token::BinOp(token::And));
637                 self.fatal(format!("expected `{}`, found `{}`",
638                                    found_token,
639                                    token_str)[])
640             }
641         }
642     }
643
644     /// Expect and consume a `|`. If `||` is seen, replace it with a single
645     /// `|` and continue. If a `|` is not seen, signal an error.
646     fn expect_or(&mut self) {
647         match self.token {
648             token::BinOp(token::Or) => self.bump(),
649             token::OrOr => {
650                 let span = self.span;
651                 let lo = span.lo + BytePos(1);
652                 self.replace_token(token::BinOp(token::Or), lo, span.hi)
653             }
654             _ => {
655                 let found_token = self.this_token_to_string();
656                 let token_str =
657                     Parser::token_to_string(&token::BinOp(token::Or));
658                 self.fatal(format!("expected `{}`, found `{}`",
659                                    token_str,
660                                    found_token)[])
661             }
662         }
663     }
664
665     pub fn expect_no_suffix(&mut self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
666         match suffix {
667             None => {/* everything ok */}
668             Some(suf) => {
669                 let text = suf.as_str();
670                 if text.is_empty() {
671                     self.span_bug(sp, "found empty literal suffix in Some")
672                 }
673                 self.span_err(sp, &*format!("{} with a suffix is illegal", kind));
674             }
675         }
676     }
677
678
679     /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
680     /// `<` and continue. If a `<` is not seen, return false.
681     ///
682     /// This is meant to be used when parsing generics on a path to get the
683     /// starting token.
684     fn eat_lt(&mut self) -> bool {
685         match self.token {
686             token::Lt => { self.bump(); true }
687             token::BinOp(token::Shl) => {
688                 let span = self.span;
689                 let lo = span.lo + BytePos(1);
690                 self.replace_token(token::Lt, lo, span.hi);
691                 true
692             }
693             _ => false,
694         }
695     }
696
697     fn expect_lt(&mut self) {
698         if !self.eat_lt() {
699             let found_token = self.this_token_to_string();
700             let token_str = Parser::token_to_string(&token::Lt);
701             self.fatal(format!("expected `{}`, found `{}`",
702                                token_str,
703                                found_token)[])
704         }
705     }
706
707     /// Parse a sequence bracketed by `|` and `|`, stopping before the `|`.
708     fn parse_seq_to_before_or<T, F>(&mut self,
709                                     sep: &token::Token,
710                                     mut f: F)
711                                     -> Vec<T> where
712         F: FnMut(&mut Parser) -> T,
713     {
714         let mut first = true;
715         let mut vector = Vec::new();
716         while self.token != token::BinOp(token::Or) &&
717                 self.token != token::OrOr {
718             if first {
719                 first = false
720             } else {
721                 self.expect(sep)
722             }
723
724             vector.push(f(self))
725         }
726         vector
727     }
728
729     /// Expect and consume a GT. if a >> is seen, replace it
730     /// with a single > and continue. If a GT is not seen,
731     /// signal an error.
732     pub fn expect_gt(&mut self) {
733         match self.token {
734             token::Gt => self.bump(),
735             token::BinOp(token::Shr) => {
736                 let span = self.span;
737                 let lo = span.lo + BytePos(1);
738                 self.replace_token(token::Gt, lo, span.hi)
739             }
740             token::BinOpEq(token::Shr) => {
741                 let span = self.span;
742                 let lo = span.lo + BytePos(1);
743                 self.replace_token(token::Ge, lo, span.hi)
744             }
745             token::Ge => {
746                 let span = self.span;
747                 let lo = span.lo + BytePos(1);
748                 self.replace_token(token::Eq, lo, span.hi)
749             }
750             _ => {
751                 let gt_str = Parser::token_to_string(&token::Gt);
752                 let this_token_str = self.this_token_to_string();
753                 self.fatal(format!("expected `{}`, found `{}`",
754                                    gt_str,
755                                    this_token_str)[])
756             }
757         }
758     }
759
760     pub fn parse_seq_to_before_gt_or_return<T, F>(&mut self,
761                                                   sep: Option<token::Token>,
762                                                   mut f: F)
763                                                   -> (OwnedSlice<T>, bool) where
764         F: FnMut(&mut Parser) -> Option<T>,
765     {
766         let mut v = Vec::new();
767         // This loop works by alternating back and forth between parsing types
768         // and commas.  For example, given a string `A, B,>`, the parser would
769         // first parse `A`, then a comma, then `B`, then a comma. After that it
770         // would encounter a `>` and stop. This lets the parser handle trailing
771         // commas in generic parameters, because it can stop either after
772         // parsing a type or after parsing a comma.
773         for i in iter::count(0u, 1) {
774             if self.check(&token::Gt)
775                 || self.token == token::BinOp(token::Shr)
776                 || self.token == token::Ge
777                 || self.token == token::BinOpEq(token::Shr) {
778                 break;
779             }
780
781             if i % 2 == 0 {
782                 match f(self) {
783                     Some(result) => v.push(result),
784                     None => return (OwnedSlice::from_vec(v), true)
785                 }
786             } else {
787                 sep.as_ref().map(|t| self.expect(t));
788             }
789         }
790         return (OwnedSlice::from_vec(v), false);
791     }
792
793     /// Parse a sequence bracketed by '<' and '>', stopping
794     /// before the '>'.
795     pub fn parse_seq_to_before_gt<T, F>(&mut self,
796                                         sep: Option<token::Token>,
797                                         mut f: F)
798                                         -> OwnedSlice<T> where
799         F: FnMut(&mut Parser) -> T,
800     {
801         let (result, returned) = self.parse_seq_to_before_gt_or_return(sep, |p| Some(f(p)));
802         assert!(!returned);
803         return result;
804     }
805
806     pub fn parse_seq_to_gt<T, F>(&mut self,
807                                  sep: Option<token::Token>,
808                                  f: F)
809                                  -> OwnedSlice<T> where
810         F: FnMut(&mut Parser) -> T,
811     {
812         let v = self.parse_seq_to_before_gt(sep, f);
813         self.expect_gt();
814         return v;
815     }
816
817     pub fn parse_seq_to_gt_or_return<T, F>(&mut self,
818                                            sep: Option<token::Token>,
819                                            f: F)
820                                            -> (OwnedSlice<T>, bool) where
821         F: FnMut(&mut Parser) -> Option<T>,
822     {
823         let (v, returned) = self.parse_seq_to_before_gt_or_return(sep, f);
824         if !returned {
825             self.expect_gt();
826         }
827         return (v, returned);
828     }
829
830     /// Parse a sequence, including the closing delimiter. The function
831     /// f must consume tokens until reaching the next separator or
832     /// closing bracket.
833     pub fn parse_seq_to_end<T, F>(&mut self,
834                                   ket: &token::Token,
835                                   sep: SeqSep,
836                                   f: F)
837                                   -> Vec<T> where
838         F: FnMut(&mut Parser) -> T,
839     {
840         let val = self.parse_seq_to_before_end(ket, sep, f);
841         self.bump();
842         val
843     }
844
845     /// Parse a sequence, not including the closing delimiter. The function
846     /// f must consume tokens until reaching the next separator or
847     /// closing bracket.
848     pub fn parse_seq_to_before_end<T, F>(&mut self,
849                                          ket: &token::Token,
850                                          sep: SeqSep,
851                                          mut f: F)
852                                          -> Vec<T> where
853         F: FnMut(&mut Parser) -> T,
854     {
855         let mut first: bool = true;
856         let mut v = vec!();
857         while self.token != *ket {
858             match sep.sep {
859               Some(ref t) => {
860                 if first { first = false; }
861                 else { self.expect(t); }
862               }
863               _ => ()
864             }
865             if sep.trailing_sep_allowed && self.check(ket) { break; }
866             v.push(f(self));
867         }
868         return v;
869     }
870
871     /// Parse a sequence, including the closing delimiter. The function
872     /// f must consume tokens until reaching the next separator or
873     /// closing bracket.
874     pub fn parse_unspanned_seq<T, F>(&mut self,
875                                      bra: &token::Token,
876                                      ket: &token::Token,
877                                      sep: SeqSep,
878                                      f: F)
879                                      -> Vec<T> where
880         F: FnMut(&mut Parser) -> T,
881     {
882         self.expect(bra);
883         let result = self.parse_seq_to_before_end(ket, sep, f);
884         self.bump();
885         result
886     }
887
888     /// Parse a sequence parameter of enum variant. For consistency purposes,
889     /// these should not be empty.
890     pub fn parse_enum_variant_seq<T, F>(&mut self,
891                                         bra: &token::Token,
892                                         ket: &token::Token,
893                                         sep: SeqSep,
894                                         f: F)
895                                         -> Vec<T> where
896         F: FnMut(&mut Parser) -> T,
897     {
898         let result = self.parse_unspanned_seq(bra, ket, sep, f);
899         if result.is_empty() {
900             let last_span = self.last_span;
901             self.span_err(last_span,
902             "nullary enum variants are written with no trailing `( )`");
903         }
904         result
905     }
906
907     // NB: Do not use this function unless you actually plan to place the
908     // spanned list in the AST.
909     pub fn parse_seq<T, F>(&mut self,
910                            bra: &token::Token,
911                            ket: &token::Token,
912                            sep: SeqSep,
913                            f: F)
914                            -> Spanned<Vec<T>> where
915         F: FnMut(&mut Parser) -> T,
916     {
917         let lo = self.span.lo;
918         self.expect(bra);
919         let result = self.parse_seq_to_before_end(ket, sep, f);
920         let hi = self.span.hi;
921         self.bump();
922         spanned(lo, hi, result)
923     }
924
925     /// Advance the parser by one token
926     pub fn bump(&mut self) {
927         self.last_span = self.span;
928         // Stash token for error recovery (sometimes; clone is not necessarily cheap).
929         self.last_token = if self.token.is_ident() || self.token.is_path() {
930             Some(box self.token.clone())
931         } else {
932             None
933         };
934         let next = if self.buffer_start == self.buffer_end {
935             self.reader.real_token()
936         } else {
937             // Avoid token copies with `replace`.
938             let buffer_start = self.buffer_start as uint;
939             let next_index = (buffer_start + 1) & 3 as uint;
940             self.buffer_start = next_index as int;
941
942             let placeholder = TokenAndSpan {
943                 tok: token::Underscore,
944                 sp: self.span,
945             };
946             mem::replace(&mut self.buffer[buffer_start], placeholder)
947         };
948         self.span = next.sp;
949         self.token = next.tok;
950         self.tokens_consumed += 1u;
951         self.expected_tokens.clear();
952     }
953
954     /// Advance the parser by one token and return the bumped token.
955     pub fn bump_and_get(&mut self) -> token::Token {
956         let old_token = mem::replace(&mut self.token, token::Underscore);
957         self.bump();
958         old_token
959     }
960
961     /// EFFECT: replace the current token and span with the given one
962     pub fn replace_token(&mut self,
963                          next: token::Token,
964                          lo: BytePos,
965                          hi: BytePos) {
966         self.last_span = mk_sp(self.span.lo, lo);
967         self.token = next;
968         self.span = mk_sp(lo, hi);
969     }
970     pub fn buffer_length(&mut self) -> int {
971         if self.buffer_start <= self.buffer_end {
972             return self.buffer_end - self.buffer_start;
973         }
974         return (4 - self.buffer_start) + self.buffer_end;
975     }
976     pub fn look_ahead<R, F>(&mut self, distance: uint, f: F) -> R where
977         F: FnOnce(&token::Token) -> R,
978     {
979         let dist = distance as int;
980         while self.buffer_length() < dist {
981             self.buffer[self.buffer_end as uint] = self.reader.real_token();
982             self.buffer_end = (self.buffer_end + 1) & 3;
983         }
984         f(&self.buffer[((self.buffer_start + dist - 1) & 3) as uint].tok)
985     }
986     pub fn fatal(&mut self, m: &str) -> ! {
987         self.sess.span_diagnostic.span_fatal(self.span, m)
988     }
989     pub fn span_fatal(&mut self, sp: Span, m: &str) -> ! {
990         self.sess.span_diagnostic.span_fatal(sp, m)
991     }
992     pub fn span_fatal_help(&mut self, sp: Span, m: &str, help: &str) -> ! {
993         self.span_err(sp, m);
994         self.span_help(sp, help);
995         panic!(diagnostic::FatalError);
996     }
997     pub fn span_note(&mut self, sp: Span, m: &str) {
998         self.sess.span_diagnostic.span_note(sp, m)
999     }
1000     pub fn span_help(&mut self, sp: Span, m: &str) {
1001         self.sess.span_diagnostic.span_help(sp, m)
1002     }
1003     pub fn bug(&mut self, m: &str) -> ! {
1004         self.sess.span_diagnostic.span_bug(self.span, m)
1005     }
1006     pub fn warn(&mut self, m: &str) {
1007         self.sess.span_diagnostic.span_warn(self.span, m)
1008     }
1009     pub fn span_warn(&mut self, sp: Span, m: &str) {
1010         self.sess.span_diagnostic.span_warn(sp, m)
1011     }
1012     pub fn span_err(&mut self, sp: Span, m: &str) {
1013         self.sess.span_diagnostic.span_err(sp, m)
1014     }
1015     pub fn span_bug(&mut self, sp: Span, m: &str) -> ! {
1016         self.sess.span_diagnostic.span_bug(sp, m)
1017     }
1018     pub fn abort_if_errors(&mut self) {
1019         self.sess.span_diagnostic.handler().abort_if_errors();
1020     }
1021
1022     pub fn id_to_interned_str(&mut self, id: Ident) -> InternedString {
1023         token::get_ident(id)
1024     }
1025
1026     /// Is the current token one of the keywords that signals a bare function
1027     /// type?
1028     pub fn token_is_bare_fn_keyword(&mut self) -> bool {
1029         self.token.is_keyword(keywords::Fn) ||
1030             self.token.is_keyword(keywords::Unsafe) ||
1031             self.token.is_keyword(keywords::Extern)
1032     }
1033
1034     /// Is the current token one of the keywords that signals a closure type?
1035     pub fn token_is_closure_keyword(&mut self) -> bool {
1036         self.token.is_keyword(keywords::Unsafe)
1037     }
1038
1039     pub fn get_lifetime(&mut self) -> ast::Ident {
1040         match self.token {
1041             token::Lifetime(ref ident) => *ident,
1042             _ => self.bug("not a lifetime"),
1043         }
1044     }
1045
1046     pub fn parse_for_in_type(&mut self) -> Ty_ {
1047         /*
1048         Parses whatever can come after a `for` keyword in a type.
1049         The `for` has already been consumed.
1050
1051         Deprecated:
1052
1053         - for <'lt> |S| -> T
1054
1055         Eventually:
1056
1057         - for <'lt> [unsafe] [extern "ABI"] fn (S) -> T
1058         - for <'lt> path::foo(a, b)
1059
1060         */
1061
1062         // parse <'lt>
1063         let lifetime_defs = self.parse_late_bound_lifetime_defs();
1064
1065         // examine next token to decide to do
1066         if self.eat_keyword(keywords::Proc) {
1067             self.parse_proc_type(lifetime_defs)
1068         } else if self.token_is_bare_fn_keyword() || self.token_is_closure_keyword() {
1069             self.parse_ty_bare_fn_or_ty_closure(lifetime_defs)
1070         } else if self.check(&token::ModSep) ||
1071                   self.token.is_ident() ||
1072                   self.token.is_path()
1073         {
1074             let trait_ref = self.parse_trait_ref();
1075             let poly_trait_ref = ast::PolyTraitRef { bound_lifetimes: lifetime_defs,
1076                                                      trait_ref: trait_ref };
1077             let other_bounds = if self.eat(&token::BinOp(token::Plus)) {
1078                 self.parse_ty_param_bounds(BoundParsingMode::Bare)
1079             } else {
1080                 OwnedSlice::empty()
1081             };
1082             let all_bounds =
1083                 Some(TraitTyParamBound(poly_trait_ref, TraitBoundModifier::None)).into_iter()
1084                 .chain(other_bounds.into_vec().into_iter())
1085                 .collect();
1086             ast::TyPolyTraitRef(all_bounds)
1087         } else {
1088             self.parse_ty_closure(lifetime_defs)
1089         }
1090     }
1091
1092     pub fn parse_ty_path(&mut self) -> Ty_ {
1093         let path = self.parse_path(LifetimeAndTypesWithoutColons);
1094         TyPath(path, ast::DUMMY_NODE_ID)
1095     }
1096
1097     /// parse a TyBareFn type:
1098     pub fn parse_ty_bare_fn(&mut self, lifetime_defs: Vec<ast::LifetimeDef>) -> Ty_ {
1099         /*
1100
1101         [unsafe] [extern "ABI"] fn <'lt> (S) -> T
1102          ^~~~^           ^~~~^     ^~~~^ ^~^    ^
1103            |               |         |    |     |
1104            |               |         |    |   Return type
1105            |               |         |  Argument types
1106            |               |     Lifetimes
1107            |              ABI
1108         Function Style
1109         */
1110
1111         let unsafety = self.parse_unsafety();
1112         let abi = if self.eat_keyword(keywords::Extern) {
1113             self.parse_opt_abi().unwrap_or(abi::C)
1114         } else {
1115             abi::Rust
1116         };
1117
1118         self.expect_keyword(keywords::Fn);
1119         let lifetime_defs = self.parse_legacy_lifetime_defs(lifetime_defs);
1120         let (inputs, variadic) = self.parse_fn_args(false, true);
1121         let ret_ty = self.parse_ret_ty();
1122         let decl = P(FnDecl {
1123             inputs: inputs,
1124             output: ret_ty,
1125             variadic: variadic
1126         });
1127         TyBareFn(P(BareFnTy {
1128             abi: abi,
1129             unsafety: unsafety,
1130             lifetimes: lifetime_defs,
1131             decl: decl
1132         }))
1133     }
1134
1135     /// Parses a procedure type (`proc`). The initial `proc` keyword must
1136     /// already have been parsed.
1137     pub fn parse_proc_type(&mut self, lifetime_defs: Vec<ast::LifetimeDef>) -> Ty_ {
1138         /*
1139
1140         proc <'lt> (S) [:Bounds] -> T
1141         ^~~^ ^~~~^  ^  ^~~~~~~~^    ^
1142          |     |    |      |        |
1143          |     |    |      |      Return type
1144          |     |    |    Bounds
1145          |     |  Argument types
1146          |   Legacy lifetimes
1147         the `proc` keyword (already consumed)
1148
1149         */
1150
1151         let proc_span = self.last_span;
1152
1153         // To be helpful, parse the proc as ever
1154         let _ = self.parse_legacy_lifetime_defs(lifetime_defs);
1155         let _ = self.parse_fn_args(false, false);
1156         let _ = self.parse_colon_then_ty_param_bounds(BoundParsingMode::Bare);
1157         let _ = self.parse_ret_ty();
1158
1159         self.obsolete(proc_span, ObsoleteProcType);
1160
1161         TyInfer
1162     }
1163
1164     /// Parses an optional unboxed closure kind (`&:`, `&mut:`, or `:`).
1165     pub fn parse_optional_unboxed_closure_kind(&mut self)
1166                                                -> Option<UnboxedClosureKind> {
1167         if self.check(&token::BinOp(token::And)) &&
1168                 self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
1169                 self.look_ahead(2, |t| *t == token::Colon) {
1170             self.bump();
1171             self.bump();
1172             self.bump();
1173             return Some(FnMutUnboxedClosureKind)
1174         }
1175
1176         if self.token == token::BinOp(token::And) &&
1177                     self.look_ahead(1, |t| *t == token::Colon) {
1178             self.bump();
1179             self.bump();
1180             return Some(FnUnboxedClosureKind)
1181         }
1182
1183         if self.eat(&token::Colon) {
1184             return Some(FnOnceUnboxedClosureKind)
1185         }
1186
1187         return None
1188     }
1189
1190     pub fn parse_ty_bare_fn_or_ty_closure(&mut self, lifetime_defs: Vec<LifetimeDef>) -> Ty_ {
1191         // Both bare fns and closures can begin with stuff like unsafe
1192         // and extern. So we just scan ahead a few tokens to see if we see
1193         // a `fn`.
1194         //
1195         // Closure:  [unsafe] <'lt> |S| [:Bounds] -> T
1196         // Fn:       [unsafe] [extern "ABI"] fn <'lt> (S) -> T
1197
1198         if self.token.is_keyword(keywords::Fn) {
1199             self.parse_ty_bare_fn(lifetime_defs)
1200         } else if self.token.is_keyword(keywords::Extern) {
1201             self.parse_ty_bare_fn(lifetime_defs)
1202         } else if self.token.is_keyword(keywords::Unsafe) {
1203             if self.look_ahead(1, |t| t.is_keyword(keywords::Fn) ||
1204                                       t.is_keyword(keywords::Extern)) {
1205                 self.parse_ty_bare_fn(lifetime_defs)
1206             } else {
1207                 self.parse_ty_closure(lifetime_defs)
1208             }
1209         } else {
1210             self.parse_ty_closure(lifetime_defs)
1211         }
1212     }
1213
1214     /// Parse a TyClosure type
1215     pub fn parse_ty_closure(&mut self, lifetime_defs: Vec<ast::LifetimeDef>) -> Ty_ {
1216         /*
1217
1218         [unsafe] <'lt> |S| [:Bounds] -> T
1219         ^~~~~~~^ ^~~~^  ^  ^~~~~~~~^    ^
1220           |        |       |      |        |
1221           |        |       |      |      Return type
1222           |        |       |  Closure bounds
1223           |        |     Argument types
1224           |      Deprecated lifetime defs
1225           |
1226         Function Style
1227
1228         */
1229
1230         let unsafety = self.parse_unsafety();
1231
1232         let lifetime_defs = self.parse_legacy_lifetime_defs(lifetime_defs);
1233
1234         let inputs = if self.eat(&token::OrOr) {
1235             Vec::new()
1236         } else {
1237             self.expect_or();
1238
1239             let inputs = self.parse_seq_to_before_or(
1240                 &token::Comma,
1241                 |p| p.parse_arg_general(false));
1242             self.expect_or();
1243             inputs
1244         };
1245
1246         let bounds = self.parse_colon_then_ty_param_bounds(BoundParsingMode::Bare);
1247
1248         let output = self.parse_ret_ty();
1249         let decl = P(FnDecl {
1250             inputs: inputs,
1251             output: output,
1252             variadic: false
1253         });
1254
1255         TyClosure(P(ClosureTy {
1256             unsafety: unsafety,
1257             onceness: Many,
1258             bounds: bounds,
1259             decl: decl,
1260             lifetimes: lifetime_defs,
1261         }))
1262     }
1263
1264     pub fn parse_unsafety(&mut self) -> Unsafety {
1265         if self.eat_keyword(keywords::Unsafe) {
1266             return Unsafety::Unsafe;
1267         } else {
1268             return Unsafety::Normal;
1269         }
1270     }
1271
1272     /// Parses `[ 'for' '<' lifetime_defs '>' ]'
1273     fn parse_legacy_lifetime_defs(&mut self,
1274                                   lifetime_defs: Vec<ast::LifetimeDef>)
1275                                   -> Vec<ast::LifetimeDef>
1276     {
1277         if self.token == token::Lt {
1278             self.bump();
1279             if lifetime_defs.is_empty() {
1280                 self.warn("deprecated syntax; use the `for` keyword now \
1281                             (e.g. change `fn<'a>` to `for<'a> fn`)");
1282                 let lifetime_defs = self.parse_lifetime_defs();
1283                 self.expect_gt();
1284                 lifetime_defs
1285             } else {
1286                 self.fatal("cannot use new `for` keyword and older syntax together");
1287             }
1288         } else {
1289             lifetime_defs
1290         }
1291     }
1292
1293     /// Parses `type Foo;` in a trait declaration only. The `type` keyword has
1294     /// already been parsed.
1295     fn parse_associated_type(&mut self, attrs: Vec<Attribute>)
1296                              -> AssociatedType
1297     {
1298         let ty_param = self.parse_ty_param();
1299         self.expect(&token::Semi);
1300         AssociatedType {
1301             attrs: attrs,
1302             ty_param: ty_param,
1303         }
1304     }
1305
1306     /// Parses `type Foo = TYPE;` in an implementation declaration only. The
1307     /// `type` keyword has already been parsed.
1308     fn parse_typedef(&mut self, attrs: Vec<Attribute>, vis: Visibility)
1309                      -> Typedef {
1310         let lo = self.span.lo;
1311         let ident = self.parse_ident();
1312         self.expect(&token::Eq);
1313         let typ = self.parse_ty_sum();
1314         let hi = self.span.hi;
1315         self.expect(&token::Semi);
1316         Typedef {
1317             id: ast::DUMMY_NODE_ID,
1318             span: mk_sp(lo, hi),
1319             ident: ident,
1320             vis: vis,
1321             attrs: attrs,
1322             typ: typ,
1323         }
1324     }
1325
1326     /// Parse the items in a trait declaration
1327     pub fn parse_trait_items(&mut self) -> Vec<TraitItem> {
1328         self.parse_unspanned_seq(
1329             &token::OpenDelim(token::Brace),
1330             &token::CloseDelim(token::Brace),
1331             seq_sep_none(),
1332             |p| {
1333             let attrs = p.parse_outer_attributes();
1334
1335             if p.eat_keyword(keywords::Type) {
1336                 TypeTraitItem(P(p.parse_associated_type(attrs)))
1337             } else {
1338                 let lo = p.span.lo;
1339
1340                 let vis = p.parse_visibility();
1341                 let style = p.parse_unsafety();
1342                 let abi = if p.eat_keyword(keywords::Extern) {
1343                     p.parse_opt_abi().unwrap_or(abi::C)
1344                 } else {
1345                     abi::Rust
1346                 };
1347                 p.expect_keyword(keywords::Fn);
1348
1349                 let ident = p.parse_ident();
1350                 let mut generics = p.parse_generics();
1351
1352                 let (explicit_self, d) = p.parse_fn_decl_with_self(|p| {
1353                     // This is somewhat dubious; We don't want to allow
1354                     // argument names to be left off if there is a
1355                     // definition...
1356                     p.parse_arg_general(false)
1357                 });
1358
1359                 p.parse_where_clause(&mut generics);
1360
1361                 let hi = p.last_span.hi;
1362                 match p.token {
1363                   token::Semi => {
1364                     p.bump();
1365                     debug!("parse_trait_methods(): parsing required method");
1366                     RequiredMethod(TypeMethod {
1367                         ident: ident,
1368                         attrs: attrs,
1369                         unsafety: style,
1370                         decl: d,
1371                         generics: generics,
1372                         abi: abi,
1373                         explicit_self: explicit_self,
1374                         id: ast::DUMMY_NODE_ID,
1375                         span: mk_sp(lo, hi),
1376                         vis: vis,
1377                     })
1378                   }
1379                   token::OpenDelim(token::Brace) => {
1380                     debug!("parse_trait_methods(): parsing provided method");
1381                     let (inner_attrs, body) =
1382                         p.parse_inner_attrs_and_block();
1383                     let mut attrs = attrs;
1384                     attrs.push_all(inner_attrs[]);
1385                     ProvidedMethod(P(ast::Method {
1386                         attrs: attrs,
1387                         id: ast::DUMMY_NODE_ID,
1388                         span: mk_sp(lo, hi),
1389                         node: ast::MethDecl(ident,
1390                                             generics,
1391                                             abi,
1392                                             explicit_self,
1393                                             style,
1394                                             d,
1395                                             body,
1396                                             vis)
1397                     }))
1398                   }
1399
1400                   _ => {
1401                       let token_str = p.this_token_to_string();
1402                       p.fatal((format!("expected `;` or `{{`, found `{}`",
1403                                        token_str))[])
1404                   }
1405                 }
1406             }
1407         })
1408     }
1409
1410     /// Parse a possibly mutable type
1411     pub fn parse_mt(&mut self) -> MutTy {
1412         let mutbl = self.parse_mutability();
1413         let t = self.parse_ty();
1414         MutTy { ty: t, mutbl: mutbl }
1415     }
1416
1417     /// Parse [mut/const/imm] ID : TY
1418     /// now used only by obsolete record syntax parser...
1419     pub fn parse_ty_field(&mut self) -> TypeField {
1420         let lo = self.span.lo;
1421         let mutbl = self.parse_mutability();
1422         let id = self.parse_ident();
1423         self.expect(&token::Colon);
1424         let ty = self.parse_ty_sum();
1425         let hi = ty.span.hi;
1426         ast::TypeField {
1427             ident: id,
1428             mt: MutTy { ty: ty, mutbl: mutbl },
1429             span: mk_sp(lo, hi),
1430         }
1431     }
1432
1433     /// Parse optional return type [ -> TY ] in function decl
1434     pub fn parse_ret_ty(&mut self) -> FunctionRetTy {
1435         if self.eat(&token::RArrow) {
1436             if self.eat(&token::Not) {
1437                 NoReturn(self.span)
1438             } else {
1439                 let t = self.parse_ty();
1440
1441                 // We used to allow `fn foo() -> &T + U`, but don't
1442                 // anymore. If we see it, report a useful error.  This
1443                 // only makes sense because `parse_ret_ty` is only
1444                 // used in fn *declarations*, not fn types or where
1445                 // clauses (i.e., not when parsing something like
1446                 // `FnMut() -> T + Send`, where the `+` is legal).
1447                 if self.token == token::BinOp(token::Plus) {
1448                     self.warn("deprecated syntax: `()` are required, see RFC 438 for details");
1449                 }
1450
1451                 Return(t)
1452             }
1453         } else {
1454             let pos = self.span.lo;
1455             Return(P(Ty {
1456                 id: ast::DUMMY_NODE_ID,
1457                 node: TyTup(vec![]),
1458                 span: mk_sp(pos, pos),
1459             }))
1460         }
1461     }
1462
1463     /// Parse a type in a context where `T1+T2` is allowed.
1464     pub fn parse_ty_sum(&mut self) -> P<Ty> {
1465         let lo = self.span.lo;
1466         let lhs = self.parse_ty();
1467
1468         if !self.eat(&token::BinOp(token::Plus)) {
1469             return lhs;
1470         }
1471
1472         let bounds = self.parse_ty_param_bounds(BoundParsingMode::Bare);
1473
1474         // In type grammar, `+` is treated like a binary operator,
1475         // and hence both L and R side are required.
1476         if bounds.len() == 0 {
1477             let last_span = self.last_span;
1478             self.span_err(last_span,
1479                           "at least one type parameter bound \
1480                           must be specified");
1481         }
1482
1483         let sp = mk_sp(lo, self.last_span.hi);
1484         let sum = ast::TyObjectSum(lhs, bounds);
1485         P(Ty {id: ast::DUMMY_NODE_ID, node: sum, span: sp})
1486     }
1487
1488     /// Parse a type.
1489     pub fn parse_ty(&mut self) -> P<Ty> {
1490         maybe_whole!(no_clone self, NtTy);
1491
1492         let lo = self.span.lo;
1493
1494         let t = if self.check(&token::OpenDelim(token::Paren)) {
1495             self.bump();
1496
1497             // (t) is a parenthesized ty
1498             // (t,) is the type of a tuple with only one field,
1499             // of type t
1500             let mut ts = vec![];
1501             let mut last_comma = false;
1502             while self.token != token::CloseDelim(token::Paren) {
1503                 ts.push(self.parse_ty_sum());
1504                 if self.check(&token::Comma) {
1505                     last_comma = true;
1506                     self.bump();
1507                 } else {
1508                     last_comma = false;
1509                     break;
1510                 }
1511             }
1512
1513             self.expect(&token::CloseDelim(token::Paren));
1514             if ts.len() == 1 && !last_comma {
1515                 TyParen(ts.into_iter().nth(0).unwrap())
1516             } else {
1517                 TyTup(ts)
1518             }
1519         } else if self.token == token::Tilde {
1520             // OWNED POINTER
1521             self.bump();
1522             let last_span = self.last_span;
1523             match self.token {
1524                 token::OpenDelim(token::Bracket) => self.obsolete(last_span, ObsoleteOwnedVector),
1525                 _ => self.obsolete(last_span, ObsoleteOwnedType)
1526             }
1527             TyTup(vec![self.parse_ty()])
1528         } else if self.check(&token::BinOp(token::Star)) {
1529             // STAR POINTER (bare pointer?)
1530             self.bump();
1531             TyPtr(self.parse_ptr())
1532         } else if self.check(&token::OpenDelim(token::Bracket)) {
1533             // VECTOR
1534             self.expect(&token::OpenDelim(token::Bracket));
1535             let t = self.parse_ty_sum();
1536
1537             // Parse the `; e` in `[ int; e ]`
1538             // where `e` is a const expression
1539             let t = match self.maybe_parse_fixed_length_of_vec() {
1540                 None => TyVec(t),
1541                 Some(suffix) => TyFixedLengthVec(t, suffix)
1542             };
1543             self.expect(&token::CloseDelim(token::Bracket));
1544             t
1545         } else if self.check(&token::BinOp(token::And)) ||
1546                   self.token == token::AndAnd {
1547             // BORROWED POINTER
1548             self.expect_and();
1549             self.parse_borrowed_pointee()
1550         } else if self.token.is_keyword(keywords::For) {
1551             self.parse_for_in_type()
1552         } else if self.token_is_bare_fn_keyword() ||
1553                   self.token_is_closure_keyword() {
1554             // BARE FUNCTION OR CLOSURE
1555             self.parse_ty_bare_fn_or_ty_closure(Vec::new())
1556         } else if self.check(&token::BinOp(token::Or)) ||
1557                   self.token == token::OrOr ||
1558                   (self.token == token::Lt &&
1559                    self.look_ahead(1, |t| {
1560                        *t == token::Gt || t.is_lifetime()
1561                    })) {
1562             // CLOSURE
1563             self.parse_ty_closure(Vec::new())
1564         } else if self.eat_keyword(keywords::Typeof) {
1565             // TYPEOF
1566             // In order to not be ambiguous, the type must be surrounded by parens.
1567             self.expect(&token::OpenDelim(token::Paren));
1568             let e = self.parse_expr();
1569             self.expect(&token::CloseDelim(token::Paren));
1570             TyTypeof(e)
1571         } else if self.eat_keyword(keywords::Proc) {
1572             self.parse_proc_type(Vec::new())
1573         } else if self.eat_lt() {
1574             // QUALIFIED PATH `<TYPE as TRAIT_REF>::item`
1575             let self_type = self.parse_ty_sum();
1576             self.expect_keyword(keywords::As);
1577             let trait_ref = self.parse_trait_ref();
1578             self.expect(&token::Gt);
1579             self.expect(&token::ModSep);
1580             let item_name = self.parse_ident();
1581             TyQPath(P(QPath {
1582                 self_type: self_type,
1583                 trait_ref: P(trait_ref),
1584                 item_name: item_name,
1585             }))
1586         } else if self.check(&token::ModSep) ||
1587                   self.token.is_ident() ||
1588                   self.token.is_path() {
1589             // NAMED TYPE
1590             self.parse_ty_path()
1591         } else if self.eat(&token::Underscore) {
1592             // TYPE TO BE INFERRED
1593             TyInfer
1594         } else {
1595             let this_token_str = self.this_token_to_string();
1596             let msg = format!("expected type, found `{}`", this_token_str);
1597             self.fatal(msg[]);
1598         };
1599
1600         let sp = mk_sp(lo, self.last_span.hi);
1601         P(Ty {id: ast::DUMMY_NODE_ID, node: t, span: sp})
1602     }
1603
1604     pub fn parse_borrowed_pointee(&mut self) -> Ty_ {
1605         // look for `&'lt` or `&'foo ` and interpret `foo` as the region name:
1606         let opt_lifetime = self.parse_opt_lifetime();
1607
1608         let mt = self.parse_mt();
1609         return TyRptr(opt_lifetime, mt);
1610     }
1611
1612     pub fn parse_ptr(&mut self) -> MutTy {
1613         let mutbl = if self.eat_keyword(keywords::Mut) {
1614             MutMutable
1615         } else if self.eat_keyword(keywords::Const) {
1616             MutImmutable
1617         } else {
1618             let span = self.last_span;
1619             self.span_err(span,
1620                           "bare raw pointers are no longer allowed, you should \
1621                            likely use `*mut T`, but otherwise `*T` is now \
1622                            known as `*const T`");
1623             MutImmutable
1624         };
1625         let t = self.parse_ty();
1626         MutTy { ty: t, mutbl: mutbl }
1627     }
1628
1629     pub fn is_named_argument(&mut self) -> bool {
1630         let offset = match self.token {
1631             token::BinOp(token::And) => 1,
1632             token::AndAnd => 1,
1633             _ if self.token.is_keyword(keywords::Mut) => 1,
1634             _ => 0
1635         };
1636
1637         debug!("parser is_named_argument offset:{}", offset);
1638
1639         if offset == 0 {
1640             is_plain_ident_or_underscore(&self.token)
1641                 && self.look_ahead(1, |t| *t == token::Colon)
1642         } else {
1643             self.look_ahead(offset, |t| is_plain_ident_or_underscore(t))
1644                 && self.look_ahead(offset + 1, |t| *t == token::Colon)
1645         }
1646     }
1647
1648     /// This version of parse arg doesn't necessarily require
1649     /// identifier names.
1650     pub fn parse_arg_general(&mut self, require_name: bool) -> Arg {
1651         let pat = if require_name || self.is_named_argument() {
1652             debug!("parse_arg_general parse_pat (require_name:{})",
1653                    require_name);
1654             let pat = self.parse_pat();
1655
1656             self.expect(&token::Colon);
1657             pat
1658         } else {
1659             debug!("parse_arg_general ident_to_pat");
1660             ast_util::ident_to_pat(ast::DUMMY_NODE_ID,
1661                                    self.last_span,
1662                                    special_idents::invalid)
1663         };
1664
1665         let t = self.parse_ty_sum();
1666
1667         Arg {
1668             ty: t,
1669             pat: pat,
1670             id: ast::DUMMY_NODE_ID,
1671         }
1672     }
1673
1674     /// Parse a single function argument
1675     pub fn parse_arg(&mut self) -> Arg {
1676         self.parse_arg_general(true)
1677     }
1678
1679     /// Parse an argument in a lambda header e.g. |arg, arg|
1680     pub fn parse_fn_block_arg(&mut self) -> Arg {
1681         let pat = self.parse_pat();
1682         let t = if self.eat(&token::Colon) {
1683             self.parse_ty_sum()
1684         } else {
1685             P(Ty {
1686                 id: ast::DUMMY_NODE_ID,
1687                 node: TyInfer,
1688                 span: mk_sp(self.span.lo, self.span.hi),
1689             })
1690         };
1691         Arg {
1692             ty: t,
1693             pat: pat,
1694             id: ast::DUMMY_NODE_ID
1695         }
1696     }
1697
1698     pub fn maybe_parse_fixed_length_of_vec(&mut self) -> Option<P<ast::Expr>> {
1699         if self.check(&token::Semi) {
1700             self.bump();
1701             Some(self.parse_expr())
1702         } else {
1703             None
1704         }
1705     }
1706
1707     /// Matches token_lit = LIT_INTEGER | ...
1708     pub fn lit_from_token(&mut self, tok: &token::Token) -> Lit_ {
1709         match *tok {
1710             token::Interpolated(token::NtExpr(ref v)) => {
1711                 match v.node {
1712                     ExprLit(ref lit) => { lit.node.clone() }
1713                     _ => { self.unexpected_last(tok); }
1714                 }
1715             }
1716             token::Literal(lit, suf) => {
1717                 let (suffix_illegal, out) = match lit {
1718                     token::Byte(i) => (true, LitByte(parse::byte_lit(i.as_str()).0)),
1719                     token::Char(i) => (true, LitChar(parse::char_lit(i.as_str()).0)),
1720
1721                     // there are some valid suffixes for integer and
1722                     // float literals, so all the handling is done
1723                     // internally.
1724                     token::Integer(s) => {
1725                         (false, parse::integer_lit(s.as_str(),
1726                                                    suf.as_ref().map(|s| s.as_str()),
1727                                                    &self.sess.span_diagnostic,
1728                                                    self.last_span))
1729                     }
1730                     token::Float(s) => {
1731                         (false, parse::float_lit(s.as_str(),
1732                                                  suf.as_ref().map(|s| s.as_str()),
1733                                                   &self.sess.span_diagnostic,
1734                                                  self.last_span))
1735                     }
1736
1737                     token::Str_(s) => {
1738                         (true,
1739                          LitStr(token::intern_and_get_ident(parse::str_lit(s.as_str())[]),
1740                                 ast::CookedStr))
1741                     }
1742                     token::StrRaw(s, n) => {
1743                         (true,
1744                          LitStr(
1745                             token::intern_and_get_ident(
1746                                 parse::raw_str_lit(s.as_str())[]),
1747                             ast::RawStr(n)))
1748                     }
1749                     token::Binary(i) =>
1750                         (true, LitBinary(parse::binary_lit(i.as_str()))),
1751                     token::BinaryRaw(i, _) =>
1752                         (true,
1753                          LitBinary(Rc::new(i.as_str().as_bytes().iter().map(|&x| x).collect()))),
1754                 };
1755
1756                 if suffix_illegal {
1757                     let sp = self.last_span;
1758                     self.expect_no_suffix(sp, &*format!("{} literal", lit.short_name()), suf)
1759                 }
1760
1761                 out
1762             }
1763             _ => { self.unexpected_last(tok); }
1764         }
1765     }
1766
1767     /// Matches lit = true | false | token_lit
1768     pub fn parse_lit(&mut self) -> Lit {
1769         let lo = self.span.lo;
1770         let lit = if self.eat_keyword(keywords::True) {
1771             LitBool(true)
1772         } else if self.eat_keyword(keywords::False) {
1773             LitBool(false)
1774         } else {
1775             let token = self.bump_and_get();
1776             let lit = self.lit_from_token(&token);
1777             lit
1778         };
1779         codemap::Spanned { node: lit, span: mk_sp(lo, self.last_span.hi) }
1780     }
1781
1782     /// matches '-' lit | lit
1783     pub fn parse_literal_maybe_minus(&mut self) -> P<Expr> {
1784         let minus_lo = self.span.lo;
1785         let minus_present = self.eat(&token::BinOp(token::Minus));
1786
1787         let lo = self.span.lo;
1788         let literal = P(self.parse_lit());
1789         let hi = self.span.hi;
1790         let expr = self.mk_expr(lo, hi, ExprLit(literal));
1791
1792         if minus_present {
1793             let minus_hi = self.span.hi;
1794             let unary = self.mk_unary(UnNeg, expr);
1795             self.mk_expr(minus_lo, minus_hi, unary)
1796         } else {
1797             expr
1798         }
1799     }
1800
1801     /// Parses a path and optional type parameter bounds, depending on the
1802     /// mode. The `mode` parameter determines whether lifetimes, types, and/or
1803     /// bounds are permitted and whether `::` must precede type parameter
1804     /// groups.
1805     pub fn parse_path(&mut self, mode: PathParsingMode) -> ast::Path {
1806         // Check for a whole path...
1807         let found = match self.token {
1808             token::Interpolated(token::NtPath(_)) => Some(self.bump_and_get()),
1809             _ => None,
1810         };
1811         if let Some(token::Interpolated(token::NtPath(box path))) = found {
1812             return path;
1813         }
1814
1815         let lo = self.span.lo;
1816         let is_global = self.eat(&token::ModSep);
1817
1818         // Parse any number of segments and bound sets. A segment is an
1819         // identifier followed by an optional lifetime and a set of types.
1820         // A bound set is a set of type parameter bounds.
1821         let segments = match mode {
1822             LifetimeAndTypesWithoutColons => {
1823                 self.parse_path_segments_without_colons()
1824             }
1825             LifetimeAndTypesWithColons => {
1826                 self.parse_path_segments_with_colons()
1827             }
1828             NoTypesAllowed => {
1829                 self.parse_path_segments_without_types()
1830             }
1831         };
1832
1833         // Assemble the span.
1834         let span = mk_sp(lo, self.last_span.hi);
1835
1836         // Assemble the result.
1837         ast::Path {
1838             span: span,
1839             global: is_global,
1840             segments: segments,
1841         }
1842     }
1843
1844     /// Examples:
1845     /// - `a::b<T,U>::c<V,W>`
1846     /// - `a::b<T,U>::c(V) -> W`
1847     /// - `a::b<T,U>::c(V)`
1848     pub fn parse_path_segments_without_colons(&mut self) -> Vec<ast::PathSegment> {
1849         let mut segments = Vec::new();
1850         loop {
1851             // First, parse an identifier.
1852             let identifier = self.parse_ident();
1853
1854             // Parse types, optionally.
1855             let parameters = if self.eat_lt() {
1856                 let (lifetimes, types, bindings) = self.parse_generic_values_after_lt();
1857
1858                 ast::AngleBracketedParameters(ast::AngleBracketedParameterData {
1859                     lifetimes: lifetimes,
1860                     types: OwnedSlice::from_vec(types),
1861                     bindings: OwnedSlice::from_vec(bindings),
1862                 })
1863             } else if self.eat(&token::OpenDelim(token::Paren)) {
1864                 let inputs = self.parse_seq_to_end(
1865                     &token::CloseDelim(token::Paren),
1866                     seq_sep_trailing_allowed(token::Comma),
1867                     |p| p.parse_ty_sum());
1868
1869                 let output_ty = if self.eat(&token::RArrow) {
1870                     Some(self.parse_ty())
1871                 } else {
1872                     None
1873                 };
1874
1875                 ast::ParenthesizedParameters(ast::ParenthesizedParameterData {
1876                     inputs: inputs,
1877                     output: output_ty
1878                 })
1879             } else {
1880                 ast::PathParameters::none()
1881             };
1882
1883             // Assemble and push the result.
1884             segments.push(ast::PathSegment { identifier: identifier,
1885                                              parameters: parameters });
1886
1887             // Continue only if we see a `::`
1888             if !self.eat(&token::ModSep) {
1889                 return segments;
1890             }
1891         }
1892     }
1893
1894     /// Examples:
1895     /// - `a::b::<T,U>::c`
1896     pub fn parse_path_segments_with_colons(&mut self) -> Vec<ast::PathSegment> {
1897         let mut segments = Vec::new();
1898         loop {
1899             // First, parse an identifier.
1900             let identifier = self.parse_ident();
1901
1902             // If we do not see a `::`, stop.
1903             if !self.eat(&token::ModSep) {
1904                 segments.push(ast::PathSegment {
1905                     identifier: identifier,
1906                     parameters: ast::AngleBracketedParameters(ast::AngleBracketedParameterData {
1907                         lifetimes: Vec::new(),
1908                         types: OwnedSlice::empty(),
1909                         bindings: OwnedSlice::empty(),
1910                     })
1911                 });
1912                 return segments;
1913             }
1914
1915             // Check for a type segment.
1916             if self.eat_lt() {
1917                 // Consumed `a::b::<`, go look for types
1918                 let (lifetimes, types, bindings) = self.parse_generic_values_after_lt();
1919                 segments.push(ast::PathSegment {
1920                     identifier: identifier,
1921                     parameters: ast::AngleBracketedParameters(ast::AngleBracketedParameterData {
1922                         lifetimes: lifetimes,
1923                         types: OwnedSlice::from_vec(types),
1924                         bindings: OwnedSlice::from_vec(bindings),
1925                     }),
1926                 });
1927
1928                 // Consumed `a::b::<T,U>`, check for `::` before proceeding
1929                 if !self.eat(&token::ModSep) {
1930                     return segments;
1931                 }
1932             } else {
1933                 // Consumed `a::`, go look for `b`
1934                 segments.push(ast::PathSegment {
1935                     identifier: identifier,
1936                     parameters: ast::PathParameters::none(),
1937                 });
1938             }
1939         }
1940     }
1941
1942
1943     /// Examples:
1944     /// - `a::b::c`
1945     pub fn parse_path_segments_without_types(&mut self) -> Vec<ast::PathSegment> {
1946         let mut segments = Vec::new();
1947         loop {
1948             // First, parse an identifier.
1949             let identifier = self.parse_ident();
1950
1951             // Assemble and push the result.
1952             segments.push(ast::PathSegment {
1953                 identifier: identifier,
1954                 parameters: ast::PathParameters::none()
1955             });
1956
1957             // If we do not see a `::`, stop.
1958             if !self.eat(&token::ModSep) {
1959                 return segments;
1960             }
1961         }
1962     }
1963
1964     /// parses 0 or 1 lifetime
1965     pub fn parse_opt_lifetime(&mut self) -> Option<ast::Lifetime> {
1966         match self.token {
1967             token::Lifetime(..) => {
1968                 Some(self.parse_lifetime())
1969             }
1970             _ => {
1971                 None
1972             }
1973         }
1974     }
1975
1976     /// Parses a single lifetime
1977     /// Matches lifetime = LIFETIME
1978     pub fn parse_lifetime(&mut self) -> ast::Lifetime {
1979         match self.token {
1980             token::Lifetime(i) => {
1981                 let span = self.span;
1982                 self.bump();
1983                 return ast::Lifetime {
1984                     id: ast::DUMMY_NODE_ID,
1985                     span: span,
1986                     name: i.name
1987                 };
1988             }
1989             _ => {
1990                 self.fatal(format!("expected a lifetime name")[]);
1991             }
1992         }
1993     }
1994
1995     /// Parses `lifetime_defs = [ lifetime_defs { ',' lifetime_defs } ]` where `lifetime_def  =
1996     /// lifetime [':' lifetimes]`
1997     pub fn parse_lifetime_defs(&mut self) -> Vec<ast::LifetimeDef> {
1998
1999         let mut res = Vec::new();
2000         loop {
2001             match self.token {
2002                 token::Lifetime(_) => {
2003                     let lifetime = self.parse_lifetime();
2004                     let bounds =
2005                         if self.eat(&token::Colon) {
2006                             self.parse_lifetimes(token::BinOp(token::Plus))
2007                         } else {
2008                             Vec::new()
2009                         };
2010                     res.push(ast::LifetimeDef { lifetime: lifetime,
2011                                                 bounds: bounds });
2012                 }
2013
2014                 _ => {
2015                     return res;
2016                 }
2017             }
2018
2019             match self.token {
2020                 token::Comma => { self.bump(); }
2021                 token::Gt => { return res; }
2022                 token::BinOp(token::Shr) => { return res; }
2023                 _ => {
2024                     let this_token_str = self.this_token_to_string();
2025                     let msg = format!("expected `,` or `>` after lifetime \
2026                                       name, found `{}`",
2027                                       this_token_str);
2028                     self.fatal(msg[]);
2029                 }
2030             }
2031         }
2032     }
2033
2034     /// matches lifetimes = ( lifetime ) | ( lifetime , lifetimes ) actually, it matches the empty
2035     /// one too, but putting that in there messes up the grammar....
2036     ///
2037     /// Parses zero or more comma separated lifetimes. Expects each lifetime to be followed by
2038     /// either a comma or `>`.  Used when parsing type parameter lists, where we expect something
2039     /// like `<'a, 'b, T>`.
2040     pub fn parse_lifetimes(&mut self, sep: token::Token) -> Vec<ast::Lifetime> {
2041
2042         let mut res = Vec::new();
2043         loop {
2044             match self.token {
2045                 token::Lifetime(_) => {
2046                     res.push(self.parse_lifetime());
2047                 }
2048                 _ => {
2049                     return res;
2050                 }
2051             }
2052
2053             if self.token != sep {
2054                 return res;
2055             }
2056
2057             self.bump();
2058         }
2059     }
2060
2061     /// Parse mutability declaration (mut/const/imm)
2062     pub fn parse_mutability(&mut self) -> Mutability {
2063         if self.eat_keyword(keywords::Mut) {
2064             MutMutable
2065         } else {
2066             MutImmutable
2067         }
2068     }
2069
2070     /// Parse ident COLON expr
2071     pub fn parse_field(&mut self) -> Field {
2072         let lo = self.span.lo;
2073         let i = self.parse_ident();
2074         let hi = self.last_span.hi;
2075         self.expect(&token::Colon);
2076         let e = self.parse_expr();
2077         ast::Field {
2078             ident: spanned(lo, hi, i),
2079             span: mk_sp(lo, e.span.hi),
2080             expr: e,
2081         }
2082     }
2083
2084     pub fn mk_expr(&mut self, lo: BytePos, hi: BytePos, node: Expr_) -> P<Expr> {
2085         P(Expr {
2086             id: ast::DUMMY_NODE_ID,
2087             node: node,
2088             span: mk_sp(lo, hi),
2089         })
2090     }
2091
2092     pub fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::Expr_ {
2093         ExprUnary(unop, expr)
2094     }
2095
2096     pub fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::Expr_ {
2097         ExprBinary(binop, lhs, rhs)
2098     }
2099
2100     pub fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::Expr_ {
2101         ExprCall(f, args)
2102     }
2103
2104     fn mk_method_call(&mut self,
2105                       ident: ast::SpannedIdent,
2106                       tps: Vec<P<Ty>>,
2107                       args: Vec<P<Expr>>)
2108                       -> ast::Expr_ {
2109         ExprMethodCall(ident, tps, args)
2110     }
2111
2112     pub fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::Expr_ {
2113         ExprIndex(expr, idx)
2114     }
2115
2116     pub fn mk_slice(&mut self,
2117                     expr: P<Expr>,
2118                     start: Option<P<Expr>>,
2119                     end: Option<P<Expr>>,
2120                     _mutbl: Mutability)
2121                     -> ast::Expr_ {
2122         // FIXME: we could give more accurate span info here.
2123         let (lo, hi) = match (&start, &end) {
2124             (&Some(ref s), &Some(ref e)) => (s.span.lo, e.span.hi),
2125             (&Some(ref s), &None) => (s.span.lo, s.span.hi),
2126             (&None, &Some(ref e)) => (e.span.lo, e.span.hi),
2127             (&None, &None) => (DUMMY_SP.lo, DUMMY_SP.hi),
2128         };
2129         ExprIndex(expr, self.mk_expr(lo, hi, ExprRange(start, end)))
2130     }
2131
2132     pub fn mk_range(&mut self,
2133                     start: Option<P<Expr>>,
2134                     end: Option<P<Expr>>)
2135                     -> ast::Expr_ {
2136         ExprRange(start, end)
2137     }
2138
2139     pub fn mk_field(&mut self, expr: P<Expr>, ident: ast::SpannedIdent) -> ast::Expr_ {
2140         ExprField(expr, ident)
2141     }
2142
2143     pub fn mk_tup_field(&mut self, expr: P<Expr>, idx: codemap::Spanned<uint>) -> ast::Expr_ {
2144         ExprTupField(expr, idx)
2145     }
2146
2147     pub fn mk_assign_op(&mut self, binop: ast::BinOp,
2148                         lhs: P<Expr>, rhs: P<Expr>) -> ast::Expr_ {
2149         ExprAssignOp(binop, lhs, rhs)
2150     }
2151
2152     pub fn mk_mac_expr(&mut self, lo: BytePos, hi: BytePos, m: Mac_) -> P<Expr> {
2153         P(Expr {
2154             id: ast::DUMMY_NODE_ID,
2155             node: ExprMac(codemap::Spanned {node: m, span: mk_sp(lo, hi)}),
2156             span: mk_sp(lo, hi),
2157         })
2158     }
2159
2160     pub fn mk_lit_u32(&mut self, i: u32) -> P<Expr> {
2161         let span = &self.span;
2162         let lv_lit = P(codemap::Spanned {
2163             node: LitInt(i as u64, ast::UnsignedIntLit(TyU32)),
2164             span: *span
2165         });
2166
2167         P(Expr {
2168             id: ast::DUMMY_NODE_ID,
2169             node: ExprLit(lv_lit),
2170             span: *span,
2171         })
2172     }
2173
2174     fn expect_open_delim(&mut self) -> token::DelimToken {
2175         match self.token {
2176             token::OpenDelim(delim) => {
2177                 self.bump();
2178                 delim
2179             },
2180             _ => self.fatal("expected open delimiter"),
2181         }
2182     }
2183
2184     /// At the bottom (top?) of the precedence hierarchy,
2185     /// parse things like parenthesized exprs,
2186     /// macros, return, etc.
2187     pub fn parse_bottom_expr(&mut self) -> P<Expr> {
2188         maybe_whole_expr!(self);
2189
2190         let lo = self.span.lo;
2191         let mut hi = self.span.hi;
2192
2193         let ex: Expr_;
2194
2195         match self.token {
2196             token::OpenDelim(token::Paren) => {
2197                 self.bump();
2198
2199                 // (e) is parenthesized e
2200                 // (e,) is a tuple with only one field, e
2201                 let mut es = vec![];
2202                 let mut trailing_comma = false;
2203                 while self.token != token::CloseDelim(token::Paren) {
2204                     es.push(self.parse_expr());
2205                     self.commit_expr(&**es.last().unwrap(), &[],
2206                                      &[token::Comma, token::CloseDelim(token::Paren)]);
2207                     if self.check(&token::Comma) {
2208                         trailing_comma = true;
2209
2210                         self.bump();
2211                     } else {
2212                         trailing_comma = false;
2213                         break;
2214                     }
2215                 }
2216                 self.bump();
2217
2218                 hi = self.span.hi;
2219                 return if es.len() == 1 && !trailing_comma {
2220                     self.mk_expr(lo, hi, ExprParen(es.into_iter().nth(0).unwrap()))
2221                 } else {
2222                     self.mk_expr(lo, hi, ExprTup(es))
2223                 }
2224             },
2225             token::OpenDelim(token::Brace) => {
2226                 self.bump();
2227                 let blk = self.parse_block_tail(lo, DefaultBlock);
2228                 return self.mk_expr(blk.span.lo, blk.span.hi,
2229                                     ExprBlock(blk));
2230             },
2231             token::BinOp(token::Or) |  token::OrOr => {
2232                 return self.parse_lambda_expr(CaptureByRef);
2233             },
2234             // FIXME #13626: Should be able to stick in
2235             // token::SELF_KEYWORD_NAME
2236             token::Ident(id @ ast::Ident {
2237                             name: ast::Name(token::SELF_KEYWORD_NAME_NUM),
2238                             ctxt: _
2239                          }, token::Plain) => {
2240                 self.bump();
2241                 let path = ast_util::ident_to_path(mk_sp(lo, hi), id);
2242                 ex = ExprPath(path);
2243                 hi = self.last_span.hi;
2244             }
2245             token::OpenDelim(token::Bracket) => {
2246                 self.bump();
2247
2248                 if self.check(&token::CloseDelim(token::Bracket)) {
2249                     // Empty vector.
2250                     self.bump();
2251                     ex = ExprVec(Vec::new());
2252                 } else {
2253                     // Nonempty vector.
2254                     let first_expr = self.parse_expr();
2255                     if self.check(&token::Semi) {
2256                         // Repeating vector syntax: [ 0; 512 ]
2257                         self.bump();
2258                         let count = self.parse_expr();
2259                         self.expect(&token::CloseDelim(token::Bracket));
2260                         ex = ExprRepeat(first_expr, count);
2261                     } else if self.check(&token::Comma) {
2262                         // Vector with two or more elements.
2263                         self.bump();
2264                         let remaining_exprs = self.parse_seq_to_end(
2265                             &token::CloseDelim(token::Bracket),
2266                             seq_sep_trailing_allowed(token::Comma),
2267                             |p| p.parse_expr()
2268                                 );
2269                         let mut exprs = vec!(first_expr);
2270                         exprs.extend(remaining_exprs.into_iter());
2271                         ex = ExprVec(exprs);
2272                     } else {
2273                         // Vector with one element.
2274                         self.expect(&token::CloseDelim(token::Bracket));
2275                         ex = ExprVec(vec!(first_expr));
2276                     }
2277                 }
2278                 hi = self.last_span.hi;
2279             }
2280             _ => {
2281                 if self.eat_keyword(keywords::Move) {
2282                     return self.parse_lambda_expr(CaptureByValue);
2283                 }
2284                 if self.eat_keyword(keywords::Proc) {
2285                     let span = self.last_span;
2286                     let _ = self.parse_proc_decl();
2287                     let _ = self.parse_expr();
2288                     return self.obsolete_expr(span, ObsoleteProcExpr);
2289                 }
2290                 if self.eat_keyword(keywords::If) {
2291                     return self.parse_if_expr();
2292                 }
2293                 if self.eat_keyword(keywords::For) {
2294                     return self.parse_for_expr(None);
2295                 }
2296                 if self.eat_keyword(keywords::While) {
2297                     return self.parse_while_expr(None);
2298                 }
2299                 if self.token.is_lifetime() {
2300                     let lifetime = self.get_lifetime();
2301                     self.bump();
2302                     self.expect(&token::Colon);
2303                     if self.eat_keyword(keywords::While) {
2304                         return self.parse_while_expr(Some(lifetime))
2305                     }
2306                     if self.eat_keyword(keywords::For) {
2307                         return self.parse_for_expr(Some(lifetime))
2308                     }
2309                     if self.eat_keyword(keywords::Loop) {
2310                         return self.parse_loop_expr(Some(lifetime))
2311                     }
2312                     self.fatal("expected `while`, `for`, or `loop` after a label")
2313                 }
2314                 if self.eat_keyword(keywords::Loop) {
2315                     return self.parse_loop_expr(None);
2316                 }
2317                 if self.eat_keyword(keywords::Continue) {
2318                     let lo = self.span.lo;
2319                     let ex = if self.token.is_lifetime() {
2320                         let lifetime = self.get_lifetime();
2321                         self.bump();
2322                         ExprAgain(Some(lifetime))
2323                     } else {
2324                         ExprAgain(None)
2325                     };
2326                     let hi = self.span.hi;
2327                     return self.mk_expr(lo, hi, ex);
2328                 }
2329                 if self.eat_keyword(keywords::Match) {
2330                     return self.parse_match_expr();
2331                 }
2332                 if self.eat_keyword(keywords::Unsafe) {
2333                     return self.parse_block_expr(
2334                         lo,
2335                         UnsafeBlock(ast::UserProvided));
2336                 }
2337                 if self.eat_keyword(keywords::Return) {
2338                     // RETURN expression
2339                     if self.token.can_begin_expr() {
2340                         let e = self.parse_expr();
2341                         hi = e.span.hi;
2342                         ex = ExprRet(Some(e));
2343                     } else {
2344                         ex = ExprRet(None);
2345                     }
2346                 } else if self.eat_keyword(keywords::Break) {
2347                     // BREAK expression
2348                     if self.token.is_lifetime() {
2349                         let lifetime = self.get_lifetime();
2350                         self.bump();
2351                         ex = ExprBreak(Some(lifetime));
2352                     } else {
2353                         ex = ExprBreak(None);
2354                     }
2355                     hi = self.span.hi;
2356                 } else if self.check(&token::ModSep) ||
2357                         self.token.is_ident() &&
2358                         !self.token.is_keyword(keywords::True) &&
2359                         !self.token.is_keyword(keywords::False) {
2360                     let pth =
2361                         self.parse_path(LifetimeAndTypesWithColons);
2362
2363                     // `!`, as an operator, is prefix, so we know this isn't that
2364                     if self.check(&token::Not) {
2365                         // MACRO INVOCATION expression
2366                         self.bump();
2367
2368                         let delim = self.expect_open_delim();
2369                         let tts = self.parse_seq_to_end(
2370                             &token::CloseDelim(delim),
2371                             seq_sep_none(),
2372                             |p| p.parse_token_tree());
2373                         let hi = self.span.hi;
2374
2375                         return self.mk_mac_expr(lo,
2376                                                 hi,
2377                                                 MacInvocTT(pth,
2378                                                            tts,
2379                                                            EMPTY_CTXT));
2380                     }
2381                     if self.check(&token::OpenDelim(token::Brace)) {
2382                         // This is a struct literal, unless we're prohibited
2383                         // from parsing struct literals here.
2384                         if !self.restrictions.contains(RESTRICTION_NO_STRUCT_LITERAL) {
2385                             // It's a struct literal.
2386                             self.bump();
2387                             let mut fields = Vec::new();
2388                             let mut base = None;
2389
2390                             while self.token != token::CloseDelim(token::Brace) {
2391                                 if self.eat(&token::DotDot) {
2392                                     base = Some(self.parse_expr());
2393                                     break;
2394                                 }
2395
2396                                 fields.push(self.parse_field());
2397                                 self.commit_expr(&*fields.last().unwrap().expr,
2398                                                  &[token::Comma],
2399                                                  &[token::CloseDelim(token::Brace)]);
2400                             }
2401
2402                             if fields.len() == 0 && base.is_none() {
2403                                 let last_span = self.last_span;
2404                                 self.span_err(last_span,
2405                                               "structure literal must either \
2406                                               have at least one field or use \
2407                                               functional structure update \
2408                                               syntax");
2409                             }
2410
2411                             hi = self.span.hi;
2412                             self.expect(&token::CloseDelim(token::Brace));
2413                             ex = ExprStruct(pth, fields, base);
2414                             return self.mk_expr(lo, hi, ex);
2415                         }
2416                     }
2417
2418                     hi = pth.span.hi;
2419                     ex = ExprPath(pth);
2420                 } else {
2421                     // other literal expression
2422                     let lit = self.parse_lit();
2423                     hi = lit.span.hi;
2424                     ex = ExprLit(P(lit));
2425                 }
2426             }
2427         }
2428
2429         return self.mk_expr(lo, hi, ex);
2430     }
2431
2432     /// Parse a block or unsafe block
2433     pub fn parse_block_expr(&mut self, lo: BytePos, blk_mode: BlockCheckMode)
2434                             -> P<Expr> {
2435         self.expect(&token::OpenDelim(token::Brace));
2436         let blk = self.parse_block_tail(lo, blk_mode);
2437         return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk));
2438     }
2439
2440     /// parse a.b or a(13) or a[4] or just a
2441     pub fn parse_dot_or_call_expr(&mut self) -> P<Expr> {
2442         let b = self.parse_bottom_expr();
2443         self.parse_dot_or_call_expr_with(b)
2444     }
2445
2446     pub fn parse_dot_or_call_expr_with(&mut self, e0: P<Expr>) -> P<Expr> {
2447         let mut e = e0;
2448         let lo = e.span.lo;
2449         let mut hi;
2450         loop {
2451             // expr.f
2452             if self.eat(&token::Dot) {
2453                 match self.token {
2454                   token::Ident(i, _) => {
2455                     let dot = self.last_span.hi;
2456                     hi = self.span.hi;
2457                     self.bump();
2458                     let (_, tys, bindings) = if self.eat(&token::ModSep) {
2459                         self.expect_lt();
2460                         self.parse_generic_values_after_lt()
2461                     } else {
2462                         (Vec::new(), Vec::new(), Vec::new())
2463                     };
2464
2465                     if bindings.len() > 0 {
2466                         let last_span = self.last_span;
2467                         self.span_err(last_span, "type bindings are only permitted on trait paths");
2468                     }
2469
2470                     // expr.f() method call
2471                     match self.token {
2472                         token::OpenDelim(token::Paren) => {
2473                             let mut es = self.parse_unspanned_seq(
2474                                 &token::OpenDelim(token::Paren),
2475                                 &token::CloseDelim(token::Paren),
2476                                 seq_sep_trailing_allowed(token::Comma),
2477                                 |p| p.parse_expr()
2478                             );
2479                             hi = self.last_span.hi;
2480
2481                             es.insert(0, e);
2482                             let id = spanned(dot, hi, i);
2483                             let nd = self.mk_method_call(id, tys, es);
2484                             e = self.mk_expr(lo, hi, nd);
2485                         }
2486                         _ => {
2487                             if !tys.is_empty() {
2488                                 let last_span = self.last_span;
2489                                 self.span_err(last_span,
2490                                               "field expressions may not \
2491                                                have type parameters");
2492                             }
2493
2494                             let id = spanned(dot, hi, i);
2495                             let field = self.mk_field(e, id);
2496                             e = self.mk_expr(lo, hi, field);
2497                         }
2498                     }
2499                   }
2500                   token::Literal(token::Integer(n), suf) => {
2501                     let sp = self.span;
2502
2503                     // A tuple index may not have a suffix
2504                     self.expect_no_suffix(sp, "tuple index", suf);
2505
2506                     let dot = self.last_span.hi;
2507                     hi = self.span.hi;
2508                     self.bump();
2509
2510                     let index = n.as_str().parse::<uint>();
2511                     match index {
2512                         Some(n) => {
2513                             let id = spanned(dot, hi, n);
2514                             let field = self.mk_tup_field(e, id);
2515                             e = self.mk_expr(lo, hi, field);
2516                         }
2517                         None => {
2518                             let last_span = self.last_span;
2519                             self.span_err(last_span, "invalid tuple or tuple struct index");
2520                         }
2521                     }
2522                   }
2523                   token::Literal(token::Float(n), _suf) => {
2524                     self.bump();
2525                     let last_span = self.last_span;
2526                     let fstr = n.as_str();
2527                     self.span_err(last_span,
2528                                   format!("unexpected token: `{}`", n.as_str())[]);
2529                     if fstr.chars().all(|x| "0123456789.".contains_char(x)) {
2530                         let float = match fstr.parse::<f64>() {
2531                             Some(f) => f,
2532                             None => continue,
2533                         };
2534                         self.span_help(last_span,
2535                             format!("try parenthesizing the first index; e.g., `(foo.{}){}`",
2536                                     float.trunc() as uint,
2537                                     float.fract().to_string()[1..])[]);
2538                     }
2539                     self.abort_if_errors();
2540
2541                   }
2542                   _ => self.unexpected()
2543                 }
2544                 continue;
2545             }
2546             if self.expr_is_complete(&*e) { break; }
2547             match self.token {
2548               // expr(...)
2549               token::OpenDelim(token::Paren) => {
2550                 let es = self.parse_unspanned_seq(
2551                     &token::OpenDelim(token::Paren),
2552                     &token::CloseDelim(token::Paren),
2553                     seq_sep_trailing_allowed(token::Comma),
2554                     |p| p.parse_expr()
2555                 );
2556                 hi = self.last_span.hi;
2557
2558                 let nd = self.mk_call(e, es);
2559                 e = self.mk_expr(lo, hi, nd);
2560               }
2561
2562               // expr[...]
2563               // Could be either an index expression or a slicing expression.
2564               // Any slicing non-terminal can have a mutable version with `mut`
2565               // after the opening square bracket.
2566               token::OpenDelim(token::Bracket) => {
2567                 self.bump();
2568                 let mutbl = if self.eat_keyword(keywords::Mut) {
2569                     MutMutable
2570                 } else {
2571                     MutImmutable
2572                 };
2573                 match self.token {
2574                     // e[]
2575                     token::CloseDelim(token::Bracket) => {
2576                         self.bump();
2577                         hi = self.span.hi;
2578                         let slice = self.mk_slice(e, None, None, mutbl);
2579                         e = self.mk_expr(lo, hi, slice)
2580                     }
2581                     // e[..e]
2582                     token::DotDot => {
2583                         self.bump();
2584                         match self.token {
2585                             // e[..]
2586                             token::CloseDelim(token::Bracket) => {
2587                                 self.bump();
2588                                 hi = self.span.hi;
2589                                 let slice = self.mk_slice(e, None, None, mutbl);
2590                                 e = self.mk_expr(lo, hi, slice);
2591
2592                                 self.span_err(e.span, "incorrect slicing expression: `[..]`");
2593                                 self.span_note(e.span,
2594                                     "use `expr[]` to construct a slice of the whole of expr");
2595                             }
2596                             // e[..e]
2597                             _ => {
2598                                 hi = self.span.hi;
2599                                 let e2 = self.parse_expr();
2600                                 self.commit_expr_expecting(&*e2, token::CloseDelim(token::Bracket));
2601                                 let slice = self.mk_slice(e, None, Some(e2), mutbl);
2602                                 e = self.mk_expr(lo, hi, slice)
2603                             }
2604                         }
2605                     }
2606                     // e[e] | e[e..] | e[e..e]
2607                     _ => {
2608                         let ix = self.parse_expr_res(RESTRICTION_NO_DOTS);
2609                         match self.token {
2610                             // e[e..] | e[e..e]
2611                             token::DotDot => {
2612                                 self.bump();
2613                                 let e2 = match self.token {
2614                                     // e[e..]
2615                                     token::CloseDelim(token::Bracket) => {
2616                                         self.bump();
2617                                         None
2618                                     }
2619                                     // e[e..e]
2620                                     _ => {
2621                                         let e2 = self.parse_expr_res(RESTRICTION_NO_DOTS);
2622                                         self.commit_expr_expecting(&*e2,
2623                                             token::CloseDelim(token::Bracket));
2624                                         Some(e2)
2625                                     }
2626                                 };
2627                                 hi = self.span.hi;
2628                                 let slice = self.mk_slice(e, Some(ix), e2, mutbl);
2629                                 e = self.mk_expr(lo, hi, slice)
2630                             }
2631                             // e[e]
2632                             _ => {
2633                                 if mutbl == ast::MutMutable {
2634                                     self.span_err(e.span,
2635                                                   "`mut` keyword is invalid in index expressions");
2636                                 }
2637                                 hi = self.span.hi;
2638                                 self.commit_expr_expecting(&*ix, token::CloseDelim(token::Bracket));
2639                                 let index = self.mk_index(e, ix);
2640                                 e = self.mk_expr(lo, hi, index)
2641                             }
2642                         }
2643                     }
2644                 }
2645               }
2646
2647               // A range expression, either `expr..expr` or `expr..`.
2648               token::DotDot if !self.restrictions.contains(RESTRICTION_NO_DOTS) => {
2649                 self.bump();
2650
2651                 let opt_end = if self.token.can_begin_expr() {
2652                     let end = self.parse_expr_res(RESTRICTION_NO_DOTS);
2653                     Some(end)
2654                 } else {
2655                     None
2656                 };
2657
2658                 let hi = self.span.hi;
2659                 let range = self.mk_range(Some(e), opt_end);
2660                 return self.mk_expr(lo, hi, range);
2661               }
2662               _ => return e
2663             }
2664         }
2665         return e;
2666     }
2667
2668     /// Parse an optional separator followed by a Kleene-style
2669     /// repetition token (+ or *).
2670     pub fn parse_sep_and_kleene_op(&mut self) -> (Option<token::Token>, ast::KleeneOp) {
2671         fn parse_kleene_op(parser: &mut Parser) -> Option<ast::KleeneOp> {
2672             match parser.token {
2673                 token::BinOp(token::Star) => {
2674                     parser.bump();
2675                     Some(ast::ZeroOrMore)
2676                 },
2677                 token::BinOp(token::Plus) => {
2678                     parser.bump();
2679                     Some(ast::OneOrMore)
2680                 },
2681                 _ => None
2682             }
2683         };
2684
2685         match parse_kleene_op(self) {
2686             Some(kleene_op) => return (None, kleene_op),
2687             None => {}
2688         }
2689
2690         let separator = self.bump_and_get();
2691         match parse_kleene_op(self) {
2692             Some(zerok) => (Some(separator), zerok),
2693             None => self.fatal("expected `*` or `+`")
2694         }
2695     }
2696
2697     /// parse a single token tree from the input.
2698     pub fn parse_token_tree(&mut self) -> TokenTree {
2699         // FIXME #6994: currently, this is too eager. It
2700         // parses token trees but also identifies TtSequence's
2701         // and token::SubstNt's; it's too early to know yet
2702         // whether something will be a nonterminal or a seq
2703         // yet.
2704         maybe_whole!(deref self, NtTT);
2705
2706         // this is the fall-through for the 'match' below.
2707         // invariants: the current token is not a left-delimiter,
2708         // not an EOF, and not the desired right-delimiter (if
2709         // it were, parse_seq_to_before_end would have prevented
2710         // reaching this point.
2711         fn parse_non_delim_tt_tok(p: &mut Parser) -> TokenTree {
2712             maybe_whole!(deref p, NtTT);
2713             match p.token {
2714               token::CloseDelim(_) => {
2715                   // This is a conservative error: only report the last unclosed delimiter. The
2716                   // previous unclosed delimiters could actually be closed! The parser just hasn't
2717                   // gotten to them yet.
2718                   match p.open_braces.last() {
2719                       None => {}
2720                       Some(&sp) => p.span_note(sp, "unclosed delimiter"),
2721                   };
2722                   let token_str = p.this_token_to_string();
2723                   p.fatal(format!("incorrect close delimiter: `{}`",
2724                                   token_str)[])
2725               },
2726               /* we ought to allow different depths of unquotation */
2727               token::Dollar if p.quote_depth > 0u => {
2728                 p.bump();
2729                 let sp = p.span;
2730
2731                 if p.token == token::OpenDelim(token::Paren) {
2732                     let seq = p.parse_seq(
2733                         &token::OpenDelim(token::Paren),
2734                         &token::CloseDelim(token::Paren),
2735                         seq_sep_none(),
2736                         |p| p.parse_token_tree()
2737                     );
2738                     let (sep, repeat) = p.parse_sep_and_kleene_op();
2739                     let seq = match seq {
2740                         Spanned { node, .. } => node,
2741                     };
2742                     let name_num = macro_parser::count_names(seq[]);
2743                     TtSequence(mk_sp(sp.lo, p.span.hi),
2744                                Rc::new(SequenceRepetition {
2745                                    tts: seq,
2746                                    separator: sep,
2747                                    op: repeat,
2748                                    num_captures: name_num
2749                                }))
2750                 } else {
2751                     // A nonterminal that matches or not
2752                     let namep = match p.token { token::Ident(_, p) => p, _ => token::Plain };
2753                     let name = p.parse_ident();
2754                     if p.token == token::Colon && p.look_ahead(1, |t| t.is_ident()) {
2755                         p.bump();
2756                         let kindp = match p.token { token::Ident(_, p) => p, _ => token::Plain };
2757                         let nt_kind = p.parse_ident();
2758                         let m = TtToken(sp, MatchNt(name, nt_kind, namep, kindp));
2759                         m
2760                     } else {
2761                         TtToken(sp, SubstNt(name, namep))
2762                     }
2763                 }
2764               }
2765               _ => {
2766                   TtToken(p.span, p.bump_and_get())
2767               }
2768             }
2769         }
2770
2771         match self.token {
2772             token::Eof => {
2773                 let open_braces = self.open_braces.clone();
2774                 for sp in open_braces.iter() {
2775                     self.span_help(*sp, "did you mean to close this delimiter?");
2776                 }
2777                 // There shouldn't really be a span, but it's easier for the test runner
2778                 // if we give it one
2779                 self.fatal("this file contains an un-closed delimiter ");
2780             },
2781             token::OpenDelim(delim) => {
2782                 // The span for beginning of the delimited section
2783                 let pre_span = self.span;
2784
2785                 // Parse the open delimiter.
2786                 self.open_braces.push(self.span);
2787                 let open_span = self.span;
2788                 self.bump();
2789
2790                 // Parse the token trees within the delimeters
2791                 let tts = self.parse_seq_to_before_end(
2792                     &token::CloseDelim(delim),
2793                     seq_sep_none(),
2794                     |p| p.parse_token_tree()
2795                 );
2796
2797                 // Parse the close delimiter.
2798                 let close_span = self.span;
2799                 self.bump();
2800                 self.open_braces.pop().unwrap();
2801
2802                 // Expand to cover the entire delimited token tree
2803                 let span = Span { hi: self.span.hi, ..pre_span };
2804
2805                 TtDelimited(span, Rc::new(Delimited {
2806                     delim: delim,
2807                     open_span: open_span,
2808                     tts: tts,
2809                     close_span: close_span,
2810                 }))
2811             },
2812             _ => parse_non_delim_tt_tok(self),
2813         }
2814     }
2815
2816     // parse a stream of tokens into a list of TokenTree's,
2817     // up to EOF.
2818     pub fn parse_all_token_trees(&mut self) -> Vec<TokenTree> {
2819         let mut tts = Vec::new();
2820         while self.token != token::Eof {
2821             tts.push(self.parse_token_tree());
2822         }
2823         tts
2824     }
2825
2826     /// Parse a prefix-operator expr
2827     pub fn parse_prefix_expr(&mut self) -> P<Expr> {
2828         let lo = self.span.lo;
2829         let hi;
2830
2831         let ex;
2832         match self.token {
2833           token::Not => {
2834             self.bump();
2835             let e = self.parse_prefix_expr();
2836             hi = e.span.hi;
2837             ex = self.mk_unary(UnNot, e);
2838           }
2839           token::BinOp(token::Minus) => {
2840             self.bump();
2841             let e = self.parse_prefix_expr();
2842             hi = e.span.hi;
2843             ex = self.mk_unary(UnNeg, e);
2844           }
2845           token::BinOp(token::Star) => {
2846             self.bump();
2847             let e = self.parse_prefix_expr();
2848             hi = e.span.hi;
2849             ex = self.mk_unary(UnDeref, e);
2850           }
2851           token::BinOp(token::And) | token::AndAnd => {
2852             self.expect_and();
2853             let m = self.parse_mutability();
2854             let e = self.parse_prefix_expr();
2855             hi = e.span.hi;
2856             ex = ExprAddrOf(m, e);
2857           }
2858           token::Tilde => {
2859             self.bump();
2860             let last_span = self.last_span;
2861             match self.token {
2862                 token::OpenDelim(token::Bracket) => {
2863                     self.obsolete(last_span, ObsoleteOwnedVector)
2864                 },
2865                 _ => self.obsolete(last_span, ObsoleteOwnedExpr)
2866             }
2867
2868             let e = self.parse_prefix_expr();
2869             hi = e.span.hi;
2870             ex = self.mk_unary(UnUniq, e);
2871           }
2872           token::DotDot if !self.restrictions.contains(RESTRICTION_NO_DOTS) => {
2873             // A range, closed above: `..expr`.
2874             self.bump();
2875             let e = self.parse_prefix_expr();
2876             hi = e.span.hi;
2877             ex = self.mk_range(None, Some(e));
2878           }
2879           token::Ident(_, _) => {
2880             if !self.token.is_keyword(keywords::Box) {
2881                 return self.parse_dot_or_call_expr();
2882             }
2883
2884             let lo = self.span.lo;
2885
2886             self.bump();
2887
2888             // Check for a place: `box(PLACE) EXPR`.
2889             if self.eat(&token::OpenDelim(token::Paren)) {
2890                 // Support `box() EXPR` as the default.
2891                 if !self.eat(&token::CloseDelim(token::Paren)) {
2892                     let place = self.parse_expr();
2893                     self.expect(&token::CloseDelim(token::Paren));
2894                     // Give a suggestion to use `box()` when a parenthesised expression is used
2895                     if !self.token.can_begin_expr() {
2896                         let span = self.span;
2897                         let this_token_to_string = self.this_token_to_string();
2898                         self.span_err(span,
2899                                       format!("expected expression, found `{}`",
2900                                               this_token_to_string)[]);
2901                         let box_span = mk_sp(lo, self.last_span.hi);
2902                         self.span_help(box_span,
2903                                        "perhaps you meant `box() (foo)` instead?");
2904                         self.abort_if_errors();
2905                     }
2906                     let subexpression = self.parse_prefix_expr();
2907                     hi = subexpression.span.hi;
2908                     ex = ExprBox(Some(place), subexpression);
2909                     return self.mk_expr(lo, hi, ex);
2910                 }
2911             }
2912
2913             // Otherwise, we use the unique pointer default.
2914             let subexpression = self.parse_prefix_expr();
2915             hi = subexpression.span.hi;
2916             // FIXME (pnkfelix): After working out kinks with box
2917             // desugaring, should be `ExprBox(None, subexpression)`
2918             // instead.
2919             ex = self.mk_unary(UnUniq, subexpression);
2920           }
2921           _ => return self.parse_dot_or_call_expr()
2922         }
2923         return self.mk_expr(lo, hi, ex);
2924     }
2925
2926     /// Parse an expression of binops
2927     pub fn parse_binops(&mut self) -> P<Expr> {
2928         let prefix_expr = self.parse_prefix_expr();
2929         self.parse_more_binops(prefix_expr, 0)
2930     }
2931
2932     /// Parse an expression of binops of at least min_prec precedence
2933     pub fn parse_more_binops(&mut self, lhs: P<Expr>, min_prec: uint) -> P<Expr> {
2934         if self.expr_is_complete(&*lhs) { return lhs; }
2935
2936         // Prevent dynamic borrow errors later on by limiting the
2937         // scope of the borrows.
2938         if self.token == token::BinOp(token::Or) &&
2939             self.restrictions.contains(RESTRICTION_NO_BAR_OP) {
2940             return lhs;
2941         }
2942         self.expected_tokens.push(TokenType::Operator);
2943
2944         let cur_opt = self.token.to_binop();
2945         match cur_opt {
2946             Some(cur_op) => {
2947                 let cur_prec = operator_prec(cur_op);
2948                 if cur_prec > min_prec {
2949                     self.bump();
2950                     let expr = self.parse_prefix_expr();
2951                     let rhs = self.parse_more_binops(expr, cur_prec);
2952                     let lhs_span = lhs.span;
2953                     let rhs_span = rhs.span;
2954                     let binary = self.mk_binary(cur_op, lhs, rhs);
2955                     let bin = self.mk_expr(lhs_span.lo, rhs_span.hi, binary);
2956                     self.parse_more_binops(bin, min_prec)
2957                 } else {
2958                     lhs
2959                 }
2960             }
2961             None => {
2962                 if as_prec > min_prec && self.eat_keyword(keywords::As) {
2963                     let rhs = self.parse_ty();
2964                     let _as = self.mk_expr(lhs.span.lo,
2965                                            rhs.span.hi,
2966                                            ExprCast(lhs, rhs));
2967                     self.parse_more_binops(_as, min_prec)
2968                 } else {
2969                     lhs
2970                 }
2971             }
2972         }
2973     }
2974
2975     /// Parse an assignment expression....
2976     /// actually, this seems to be the main entry point for
2977     /// parsing an arbitrary expression.
2978     pub fn parse_assign_expr(&mut self) -> P<Expr> {
2979         let lo = self.span.lo;
2980         let lhs = self.parse_binops();
2981         let restrictions = self.restrictions & RESTRICTION_NO_STRUCT_LITERAL;
2982         match self.token {
2983           token::Eq => {
2984               self.bump();
2985               let rhs = self.parse_expr_res(restrictions);
2986               self.mk_expr(lo, rhs.span.hi, ExprAssign(lhs, rhs))
2987           }
2988           token::BinOpEq(op) => {
2989               self.bump();
2990               let rhs = self.parse_expr_res(restrictions);
2991               let aop = match op {
2992                   token::Plus =>    BiAdd,
2993                   token::Minus =>   BiSub,
2994                   token::Star =>    BiMul,
2995                   token::Slash =>   BiDiv,
2996                   token::Percent => BiRem,
2997                   token::Caret =>   BiBitXor,
2998                   token::And =>     BiBitAnd,
2999                   token::Or =>      BiBitOr,
3000                   token::Shl =>     BiShl,
3001                   token::Shr =>     BiShr
3002               };
3003               let rhs_span = rhs.span;
3004               let assign_op = self.mk_assign_op(aop, lhs, rhs);
3005               self.mk_expr(lo, rhs_span.hi, assign_op)
3006           }
3007           _ => {
3008               lhs
3009           }
3010         }
3011     }
3012
3013     /// Parse an 'if' or 'if let' expression ('if' token already eaten)
3014     pub fn parse_if_expr(&mut self) -> P<Expr> {
3015         if self.token.is_keyword(keywords::Let) {
3016             return self.parse_if_let_expr();
3017         }
3018         let lo = self.last_span.lo;
3019         let cond = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
3020         let thn = self.parse_block();
3021         let mut els: Option<P<Expr>> = None;
3022         let mut hi = thn.span.hi;
3023         if self.eat_keyword(keywords::Else) {
3024             let elexpr = self.parse_else_expr();
3025             hi = elexpr.span.hi;
3026             els = Some(elexpr);
3027         }
3028         self.mk_expr(lo, hi, ExprIf(cond, thn, els))
3029     }
3030
3031     /// Parse an 'if let' expression ('if' token already eaten)
3032     pub fn parse_if_let_expr(&mut self) -> P<Expr> {
3033         let lo = self.last_span.lo;
3034         self.expect_keyword(keywords::Let);
3035         let pat = self.parse_pat();
3036         self.expect(&token::Eq);
3037         let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
3038         let thn = self.parse_block();
3039         let (hi, els) = if self.eat_keyword(keywords::Else) {
3040             let expr = self.parse_else_expr();
3041             (expr.span.hi, Some(expr))
3042         } else {
3043             (thn.span.hi, None)
3044         };
3045         self.mk_expr(lo, hi, ExprIfLet(pat, expr, thn, els))
3046     }
3047
3048     // `|args| expr`
3049     pub fn parse_lambda_expr(&mut self, capture_clause: CaptureClause)
3050                              -> P<Expr>
3051     {
3052         let lo = self.span.lo;
3053         let (decl, optional_unboxed_closure_kind) =
3054             self.parse_fn_block_decl();
3055         let body = self.parse_expr();
3056         let fakeblock = P(ast::Block {
3057             id: ast::DUMMY_NODE_ID,
3058             view_items: Vec::new(),
3059             stmts: Vec::new(),
3060             span: body.span,
3061             expr: Some(body),
3062             rules: DefaultBlock,
3063         });
3064
3065         self.mk_expr(
3066             lo,
3067             fakeblock.span.hi,
3068             ExprClosure(capture_clause, optional_unboxed_closure_kind, decl, fakeblock))
3069     }
3070
3071     pub fn parse_else_expr(&mut self) -> P<Expr> {
3072         if self.eat_keyword(keywords::If) {
3073             return self.parse_if_expr();
3074         } else {
3075             let blk = self.parse_block();
3076             return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk));
3077         }
3078     }
3079
3080     /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3081     pub fn parse_for_expr(&mut self, opt_ident: Option<ast::Ident>) -> P<Expr> {
3082         // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3083
3084         let lo = self.last_span.lo;
3085         let pat = self.parse_pat();
3086         self.expect_keyword(keywords::In);
3087         let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
3088         let loop_block = self.parse_block();
3089         let hi = self.span.hi;
3090
3091         self.mk_expr(lo, hi, ExprForLoop(pat, expr, loop_block, opt_ident))
3092     }
3093
3094     /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3095     pub fn parse_while_expr(&mut self, opt_ident: Option<ast::Ident>) -> P<Expr> {
3096         if self.token.is_keyword(keywords::Let) {
3097             return self.parse_while_let_expr(opt_ident);
3098         }
3099         let lo = self.last_span.lo;
3100         let cond = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
3101         let body = self.parse_block();
3102         let hi = body.span.hi;
3103         return self.mk_expr(lo, hi, ExprWhile(cond, body, opt_ident));
3104     }
3105
3106     /// Parse a 'while let' expression ('while' token already eaten)
3107     pub fn parse_while_let_expr(&mut self, opt_ident: Option<ast::Ident>) -> P<Expr> {
3108         let lo = self.last_span.lo;
3109         self.expect_keyword(keywords::Let);
3110         let pat = self.parse_pat();
3111         self.expect(&token::Eq);
3112         let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
3113         let body = self.parse_block();
3114         let hi = body.span.hi;
3115         return self.mk_expr(lo, hi, ExprWhileLet(pat, expr, body, opt_ident));
3116     }
3117
3118     pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::Ident>) -> P<Expr> {
3119         let lo = self.last_span.lo;
3120         let body = self.parse_block();
3121         let hi = body.span.hi;
3122         self.mk_expr(lo, hi, ExprLoop(body, opt_ident))
3123     }
3124
3125     fn parse_match_expr(&mut self) -> P<Expr> {
3126         let lo = self.last_span.lo;
3127         let discriminant = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
3128         self.commit_expr_expecting(&*discriminant, token::OpenDelim(token::Brace));
3129         let mut arms: Vec<Arm> = Vec::new();
3130         while self.token != token::CloseDelim(token::Brace) {
3131             arms.push(self.parse_arm());
3132         }
3133         let hi = self.span.hi;
3134         self.bump();
3135         return self.mk_expr(lo, hi, ExprMatch(discriminant, arms, MatchSource::Normal));
3136     }
3137
3138     pub fn parse_arm(&mut self) -> Arm {
3139         let attrs = self.parse_outer_attributes();
3140         let pats = self.parse_pats();
3141         let mut guard = None;
3142         if self.eat_keyword(keywords::If) {
3143             guard = Some(self.parse_expr());
3144         }
3145         self.expect(&token::FatArrow);
3146         let expr = self.parse_expr_res(RESTRICTION_STMT_EXPR);
3147
3148         let require_comma =
3149             !classify::expr_is_simple_block(&*expr)
3150             && self.token != token::CloseDelim(token::Brace);
3151
3152         if require_comma {
3153             self.commit_expr(&*expr, &[token::Comma], &[token::CloseDelim(token::Brace)]);
3154         } else {
3155             self.eat(&token::Comma);
3156         }
3157
3158         ast::Arm {
3159             attrs: attrs,
3160             pats: pats,
3161             guard: guard,
3162             body: expr,
3163         }
3164     }
3165
3166     /// Parse an expression
3167     pub fn parse_expr(&mut self) -> P<Expr> {
3168         return self.parse_expr_res(UNRESTRICTED);
3169     }
3170
3171     /// Parse an expression, subject to the given restrictions
3172     pub fn parse_expr_res(&mut self, r: Restrictions) -> P<Expr> {
3173         let old = self.restrictions;
3174         self.restrictions = r;
3175         let e = self.parse_assign_expr();
3176         self.restrictions = old;
3177         return e;
3178     }
3179
3180     /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3181     fn parse_initializer(&mut self) -> Option<P<Expr>> {
3182         if self.check(&token::Eq) {
3183             self.bump();
3184             Some(self.parse_expr())
3185         } else {
3186             None
3187         }
3188     }
3189
3190     /// Parse patterns, separated by '|' s
3191     fn parse_pats(&mut self) -> Vec<P<Pat>> {
3192         let mut pats = Vec::new();
3193         loop {
3194             pats.push(self.parse_pat());
3195             if self.check(&token::BinOp(token::Or)) { self.bump(); }
3196             else { return pats; }
3197         };
3198     }
3199
3200     fn parse_pat_vec_elements(
3201         &mut self,
3202     ) -> (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>) {
3203         let mut before = Vec::new();
3204         let mut slice = None;
3205         let mut after = Vec::new();
3206         let mut first = true;
3207         let mut before_slice = true;
3208
3209         while self.token != token::CloseDelim(token::Bracket) {
3210             if first {
3211                 first = false;
3212             } else {
3213                 self.expect(&token::Comma);
3214
3215                 if self.token == token::CloseDelim(token::Bracket)
3216                         && (before_slice || after.len() != 0) {
3217                     break
3218                 }
3219             }
3220
3221             if before_slice {
3222                 if self.check(&token::DotDot) {
3223                     self.bump();
3224
3225                     if self.check(&token::Comma) ||
3226                             self.check(&token::CloseDelim(token::Bracket)) {
3227                         slice = Some(P(ast::Pat {
3228                             id: ast::DUMMY_NODE_ID,
3229                             node: PatWild(PatWildMulti),
3230                             span: self.span,
3231                         }));
3232                         before_slice = false;
3233                     } else {
3234                         let _ = self.parse_pat();
3235                         let span = self.span;
3236                         self.obsolete(span, ObsoleteSubsliceMatch);
3237                     }
3238                     continue
3239                 }
3240             }
3241
3242             let subpat = self.parse_pat();
3243             if before_slice && self.check(&token::DotDot) {
3244                 self.bump();
3245                 slice = Some(subpat);
3246                 before_slice = false;
3247             } else if before_slice {
3248                 before.push(subpat);
3249             } else {
3250                 after.push(subpat);
3251             }
3252         }
3253
3254         (before, slice, after)
3255     }
3256
3257     /// Parse the fields of a struct-like pattern
3258     fn parse_pat_fields(&mut self) -> (Vec<codemap::Spanned<ast::FieldPat>> , bool) {
3259         let mut fields = Vec::new();
3260         let mut etc = false;
3261         let mut first = true;
3262         while self.token != token::CloseDelim(token::Brace) {
3263             if first {
3264                 first = false;
3265             } else {
3266                 self.expect(&token::Comma);
3267                 // accept trailing commas
3268                 if self.check(&token::CloseDelim(token::Brace)) { break }
3269             }
3270
3271             let lo = self.span.lo;
3272             let hi;
3273
3274             if self.check(&token::DotDot) {
3275                 self.bump();
3276                 if self.token != token::CloseDelim(token::Brace) {
3277                     let token_str = self.this_token_to_string();
3278                     self.fatal(format!("expected `{}`, found `{}`", "}",
3279                                        token_str)[])
3280                 }
3281                 etc = true;
3282                 break;
3283             }
3284
3285             let bind_type = if self.eat_keyword(keywords::Mut) {
3286                 BindByValue(MutMutable)
3287             } else if self.eat_keyword(keywords::Ref) {
3288                 BindByRef(self.parse_mutability())
3289             } else {
3290                 BindByValue(MutImmutable)
3291             };
3292
3293             let fieldname = self.parse_ident();
3294
3295             let (subpat, is_shorthand) = if self.check(&token::Colon) {
3296                 match bind_type {
3297                     BindByRef(..) | BindByValue(MutMutable) => {
3298                         let token_str = self.this_token_to_string();
3299                         self.fatal(format!("unexpected `{}`",
3300                                            token_str)[])
3301                     }
3302                     _ => {}
3303                 }
3304
3305                 self.bump();
3306                 let pat = self.parse_pat();
3307                 hi = pat.span.hi;
3308                 (pat, false)
3309             } else {
3310                 hi = self.last_span.hi;
3311                 let fieldpath = codemap::Spanned{span:self.last_span, node: fieldname};
3312                 (P(ast::Pat {
3313                     id: ast::DUMMY_NODE_ID,
3314                     node: PatIdent(bind_type, fieldpath, None),
3315                     span: self.last_span
3316                 }), true)
3317             };
3318             fields.push(codemap::Spanned { span: mk_sp(lo, hi),
3319                                            node: ast::FieldPat { ident: fieldname,
3320                                                                  pat: subpat,
3321                                                                  is_shorthand: is_shorthand }});
3322         }
3323         return (fields, etc);
3324     }
3325
3326     /// Parse a pattern.
3327     pub fn parse_pat(&mut self) -> P<Pat> {
3328         maybe_whole!(self, NtPat);
3329
3330         let lo = self.span.lo;
3331         let mut hi;
3332         let pat;
3333         match self.token {
3334             // parse _
3335           token::Underscore => {
3336             self.bump();
3337             pat = PatWild(PatWildSingle);
3338             hi = self.last_span.hi;
3339             return P(ast::Pat {
3340                 id: ast::DUMMY_NODE_ID,
3341                 node: pat,
3342                 span: mk_sp(lo, hi)
3343             })
3344           }
3345           token::Tilde => {
3346             // parse ~pat
3347             self.bump();
3348             let sub = self.parse_pat();
3349             pat = PatBox(sub);
3350             let last_span = self.last_span;
3351             hi = last_span.hi;
3352             self.obsolete(last_span, ObsoleteOwnedPattern);
3353             return P(ast::Pat {
3354                 id: ast::DUMMY_NODE_ID,
3355                 node: pat,
3356                 span: mk_sp(lo, hi)
3357             })
3358           }
3359           token::BinOp(token::And) | token::AndAnd => {
3360             // parse &pat
3361             let lo = self.span.lo;
3362             self.expect_and();
3363             let sub = self.parse_pat();
3364             pat = PatRegion(sub);
3365             hi = self.last_span.hi;
3366             return P(ast::Pat {
3367                 id: ast::DUMMY_NODE_ID,
3368                 node: pat,
3369                 span: mk_sp(lo, hi)
3370             })
3371           }
3372           token::OpenDelim(token::Paren) => {
3373             // parse (pat,pat,pat,...) as tuple
3374             self.bump();
3375             if self.check(&token::CloseDelim(token::Paren)) {
3376                 self.bump();
3377                 pat = PatTup(vec![]);
3378             } else {
3379                 let mut fields = vec!(self.parse_pat());
3380                 if self.look_ahead(1, |t| *t != token::CloseDelim(token::Paren)) {
3381                     while self.check(&token::Comma) {
3382                         self.bump();
3383                         if self.check(&token::CloseDelim(token::Paren)) { break; }
3384                         fields.push(self.parse_pat());
3385                     }
3386                 }
3387                 if fields.len() == 1 { self.expect(&token::Comma); }
3388                 self.expect(&token::CloseDelim(token::Paren));
3389                 pat = PatTup(fields);
3390             }
3391             hi = self.last_span.hi;
3392             return P(ast::Pat {
3393                 id: ast::DUMMY_NODE_ID,
3394                 node: pat,
3395                 span: mk_sp(lo, hi)
3396             })
3397           }
3398           token::OpenDelim(token::Bracket) => {
3399             // parse [pat,pat,...] as vector pattern
3400             self.bump();
3401             let (before, slice, after) =
3402                 self.parse_pat_vec_elements();
3403
3404             self.expect(&token::CloseDelim(token::Bracket));
3405             pat = ast::PatVec(before, slice, after);
3406             hi = self.last_span.hi;
3407             return P(ast::Pat {
3408                 id: ast::DUMMY_NODE_ID,
3409                 node: pat,
3410                 span: mk_sp(lo, hi)
3411             })
3412           }
3413           _ => {}
3414         }
3415         // at this point, token != _, ~, &, &&, (, [
3416
3417         if (!(self.token.is_ident() || self.token.is_path())
3418               && self.token != token::ModSep)
3419                 || self.token.is_keyword(keywords::True)
3420                 || self.token.is_keyword(keywords::False) {
3421             // Parse an expression pattern or exp .. exp.
3422             //
3423             // These expressions are limited to literals (possibly
3424             // preceded by unary-minus) or identifiers.
3425             let val = self.parse_literal_maybe_minus();
3426             if (self.check(&token::DotDotDot)) &&
3427                     self.look_ahead(1, |t| {
3428                         *t != token::Comma && *t != token::CloseDelim(token::Bracket)
3429                     }) {
3430                 self.bump();
3431                 let end = if self.token.is_ident() || self.token.is_path() {
3432                     let path = self.parse_path(LifetimeAndTypesWithColons);
3433                     let hi = self.span.hi;
3434                     self.mk_expr(lo, hi, ExprPath(path))
3435                 } else {
3436                     self.parse_literal_maybe_minus()
3437                 };
3438                 pat = PatRange(val, end);
3439             } else {
3440                 pat = PatLit(val);
3441             }
3442         } else if self.eat_keyword(keywords::Mut) {
3443             pat = self.parse_pat_ident(BindByValue(MutMutable));
3444         } else if self.eat_keyword(keywords::Ref) {
3445             // parse ref pat
3446             let mutbl = self.parse_mutability();
3447             pat = self.parse_pat_ident(BindByRef(mutbl));
3448         } else if self.eat_keyword(keywords::Box) {
3449             // `box PAT`
3450             //
3451             // FIXME(#13910): Rename to `PatBox` and extend to full DST
3452             // support.
3453             let sub = self.parse_pat();
3454             pat = PatBox(sub);
3455             hi = self.last_span.hi;
3456             return P(ast::Pat {
3457                 id: ast::DUMMY_NODE_ID,
3458                 node: pat,
3459                 span: mk_sp(lo, hi)
3460             })
3461         } else {
3462             let can_be_enum_or_struct = self.look_ahead(1, |t| {
3463                 match *t {
3464                     token::OpenDelim(_) | token::Lt | token::ModSep => true,
3465                     _ => false,
3466                 }
3467             });
3468
3469             if self.look_ahead(1, |t| *t == token::DotDotDot) &&
3470                     self.look_ahead(2, |t| {
3471                         *t != token::Comma && *t != token::CloseDelim(token::Bracket)
3472                     }) {
3473                 let start = self.parse_expr_res(RESTRICTION_NO_BAR_OP);
3474                 self.eat(&token::DotDotDot);
3475                 let end = self.parse_expr_res(RESTRICTION_NO_BAR_OP);
3476                 pat = PatRange(start, end);
3477             } else if self.token.is_plain_ident() && !can_be_enum_or_struct {
3478                 let id = self.parse_ident();
3479                 let id_span = self.last_span;
3480                 let pth1 = codemap::Spanned{span:id_span, node: id};
3481                 if self.eat(&token::Not) {
3482                     // macro invocation
3483                     let delim = self.expect_open_delim();
3484                     let tts = self.parse_seq_to_end(&token::CloseDelim(delim),
3485                                                     seq_sep_none(),
3486                                                     |p| p.parse_token_tree());
3487
3488                     let mac = MacInvocTT(ident_to_path(id_span,id), tts, EMPTY_CTXT);
3489                     pat = ast::PatMac(codemap::Spanned {node: mac, span: self.span});
3490                 } else {
3491                     let sub = if self.eat(&token::At) {
3492                         // parse foo @ pat
3493                         Some(self.parse_pat())
3494                     } else {
3495                         // or just foo
3496                         None
3497                     };
3498                     pat = PatIdent(BindByValue(MutImmutable), pth1, sub);
3499                 }
3500             } else {
3501                 // parse an enum pat
3502                 let enum_path = self.parse_path(LifetimeAndTypesWithColons);
3503                 match self.token {
3504                     token::OpenDelim(token::Brace) => {
3505                         self.bump();
3506                         let (fields, etc) =
3507                             self.parse_pat_fields();
3508                         self.bump();
3509                         pat = PatStruct(enum_path, fields, etc);
3510                     }
3511                     _ => {
3512                         let mut args: Vec<P<Pat>> = Vec::new();
3513                         match self.token {
3514                           token::OpenDelim(token::Paren) => {
3515                             let is_dotdot = self.look_ahead(1, |t| {
3516                                 match *t {
3517                                     token::DotDot => true,
3518                                     _ => false,
3519                                 }
3520                             });
3521                             if is_dotdot {
3522                                 // This is a "top constructor only" pat
3523                                 self.bump();
3524                                 self.bump();
3525                                 self.expect(&token::CloseDelim(token::Paren));
3526                                 pat = PatEnum(enum_path, None);
3527                             } else {
3528                                 args = self.parse_enum_variant_seq(
3529                                     &token::OpenDelim(token::Paren),
3530                                     &token::CloseDelim(token::Paren),
3531                                     seq_sep_trailing_allowed(token::Comma),
3532                                     |p| p.parse_pat()
3533                                 );
3534                                 pat = PatEnum(enum_path, Some(args));
3535                             }
3536                           },
3537                           _ => {
3538                               if !enum_path.global &&
3539                                   enum_path.segments.len() == 1 &&
3540                                   enum_path.segments[0].parameters.is_empty()
3541                               {
3542                                   // it could still be either an enum
3543                                   // or an identifier pattern, resolve
3544                                   // will sort it out:
3545                                   pat = PatIdent(BindByValue(MutImmutable),
3546                                                  codemap::Spanned{
3547                                                     span: enum_path.span,
3548                                                     node: enum_path.segments[0]
3549                                                            .identifier},
3550                                                  None);
3551                               } else {
3552                                   pat = PatEnum(enum_path, Some(args));
3553                               }
3554                           }
3555                         }
3556                     }
3557                 }
3558             }
3559         }
3560         hi = self.last_span.hi;
3561         P(ast::Pat {
3562             id: ast::DUMMY_NODE_ID,
3563             node: pat,
3564             span: mk_sp(lo, hi),
3565         })
3566     }
3567
3568     /// Parse ident or ident @ pat
3569     /// used by the copy foo and ref foo patterns to give a good
3570     /// error message when parsing mistakes like ref foo(a,b)
3571     fn parse_pat_ident(&mut self,
3572                        binding_mode: ast::BindingMode)
3573                        -> ast::Pat_ {
3574         if !self.token.is_plain_ident() {
3575             let span = self.span;
3576             let tok_str = self.this_token_to_string();
3577             self.span_fatal(span,
3578                             format!("expected identifier, found `{}`", tok_str)[]);
3579         }
3580         let ident = self.parse_ident();
3581         let last_span = self.last_span;
3582         let name = codemap::Spanned{span: last_span, node: ident};
3583         let sub = if self.eat(&token::At) {
3584             Some(self.parse_pat())
3585         } else {
3586             None
3587         };
3588
3589         // just to be friendly, if they write something like
3590         //   ref Some(i)
3591         // we end up here with ( as the current token.  This shortly
3592         // leads to a parse error.  Note that if there is no explicit
3593         // binding mode then we do not end up here, because the lookahead
3594         // will direct us over to parse_enum_variant()
3595         if self.token == token::OpenDelim(token::Paren) {
3596             let last_span = self.last_span;
3597             self.span_fatal(
3598                 last_span,
3599                 "expected identifier, found enum pattern");
3600         }
3601
3602         PatIdent(binding_mode, name, sub)
3603     }
3604
3605     /// Parse a local variable declaration
3606     fn parse_local(&mut self) -> P<Local> {
3607         let lo = self.span.lo;
3608         let pat = self.parse_pat();
3609
3610         let mut ty = None;
3611         if self.eat(&token::Colon) {
3612             ty = Some(self.parse_ty_sum());
3613         }
3614         let init = self.parse_initializer();
3615         P(ast::Local {
3616             ty: ty,
3617             pat: pat,
3618             init: init,
3619             id: ast::DUMMY_NODE_ID,
3620             span: mk_sp(lo, self.last_span.hi),
3621             source: LocalLet,
3622         })
3623     }
3624
3625     /// Parse a "let" stmt
3626     fn parse_let(&mut self) -> P<Decl> {
3627         let lo = self.span.lo;
3628         let local = self.parse_local();
3629         P(spanned(lo, self.last_span.hi, DeclLocal(local)))
3630     }
3631
3632     /// Parse a structure field
3633     fn parse_name_and_ty(&mut self, pr: Visibility,
3634                          attrs: Vec<Attribute> ) -> StructField {
3635         let lo = self.span.lo;
3636         if !self.token.is_plain_ident() {
3637             self.fatal("expected ident");
3638         }
3639         let name = self.parse_ident();
3640         self.expect(&token::Colon);
3641         let ty = self.parse_ty_sum();
3642         spanned(lo, self.last_span.hi, ast::StructField_ {
3643             kind: NamedField(name, pr),
3644             id: ast::DUMMY_NODE_ID,
3645             ty: ty,
3646             attrs: attrs,
3647         })
3648     }
3649
3650     /// Get an expected item after attributes error message.
3651     fn expected_item_err(attrs: &[Attribute]) -> &'static str {
3652         match attrs.last() {
3653             Some(&Attribute { node: ast::Attribute_ { is_sugared_doc: true, .. }, .. }) => {
3654                 "expected item after doc comment"
3655             }
3656             _ => "expected item after attributes",
3657         }
3658     }
3659
3660     /// Parse a statement. may include decl.
3661     /// Precondition: any attributes are parsed already
3662     pub fn parse_stmt(&mut self, item_attrs: Vec<Attribute>) -> P<Stmt> {
3663         maybe_whole!(self, NtStmt);
3664
3665         fn check_expected_item(p: &mut Parser, attrs: &[Attribute]) {
3666             // If we have attributes then we should have an item
3667             if !attrs.is_empty() {
3668                 let last_span = p.last_span;
3669                 p.span_err(last_span, Parser::expected_item_err(attrs));
3670             }
3671         }
3672
3673         let lo = self.span.lo;
3674         if self.token.is_keyword(keywords::Let) {
3675             check_expected_item(self, item_attrs[]);
3676             self.expect_keyword(keywords::Let);
3677             let decl = self.parse_let();
3678             P(spanned(lo, decl.span.hi, StmtDecl(decl, ast::DUMMY_NODE_ID)))
3679         } else if self.token.is_ident()
3680             && !self.token.is_any_keyword()
3681             && self.look_ahead(1, |t| *t == token::Not) {
3682             // it's a macro invocation:
3683
3684             check_expected_item(self, item_attrs[]);
3685
3686             // Potential trouble: if we allow macros with paths instead of
3687             // idents, we'd need to look ahead past the whole path here...
3688             let pth = self.parse_path(NoTypesAllowed);
3689             self.bump();
3690
3691             let id = match self.token {
3692                 token::OpenDelim(_) => token::special_idents::invalid, // no special identifier
3693                 _ => self.parse_ident(),
3694             };
3695
3696             // check that we're pointing at delimiters (need to check
3697             // again after the `if`, because of `parse_ident`
3698             // consuming more tokens).
3699             let delim = match self.token {
3700                 token::OpenDelim(delim) => delim,
3701                 _ => {
3702                     // we only expect an ident if we didn't parse one
3703                     // above.
3704                     let ident_str = if id.name == token::special_idents::invalid.name {
3705                         "identifier, "
3706                     } else {
3707                         ""
3708                     };
3709                     let tok_str = self.this_token_to_string();
3710                     self.fatal(format!("expected {}`(` or `{{`, found `{}`",
3711                                        ident_str,
3712                                        tok_str)[])
3713                 },
3714             };
3715
3716             let tts = self.parse_unspanned_seq(
3717                 &token::OpenDelim(delim),
3718                 &token::CloseDelim(delim),
3719                 seq_sep_none(),
3720                 |p| p.parse_token_tree()
3721             );
3722             let hi = self.span.hi;
3723
3724             let style = if delim == token::Brace {
3725                 MacStmtWithBraces
3726             } else {
3727                 MacStmtWithoutBraces
3728             };
3729
3730             if id.name == token::special_idents::invalid.name {
3731                 P(spanned(lo,
3732                           hi,
3733                           StmtMac(P(spanned(lo,
3734                                           hi,
3735                                           MacInvocTT(pth, tts, EMPTY_CTXT))),
3736                                   style)))
3737             } else {
3738                 // if it has a special ident, it's definitely an item
3739                 //
3740                 // Require a semicolon or braces.
3741                 if style != MacStmtWithBraces {
3742                     if !self.eat(&token::Semi) {
3743                         let last_span = self.last_span;
3744                         self.span_err(last_span,
3745                                       "macros that expand to items must \
3746                                        either be surrounded with braces or \
3747                                        followed by a semicolon");
3748                     }
3749                 }
3750                 P(spanned(lo, hi, StmtDecl(
3751                     P(spanned(lo, hi, DeclItem(
3752                         self.mk_item(
3753                             lo, hi, id /*id is good here*/,
3754                             ItemMac(spanned(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT))),
3755                             Inherited, Vec::new(/*no attrs*/))))),
3756                     ast::DUMMY_NODE_ID)))
3757             }
3758         } else {
3759             let found_attrs = !item_attrs.is_empty();
3760             let item_err = Parser::expected_item_err(item_attrs[]);
3761             match self.parse_item_or_view_item(item_attrs, false) {
3762                 IoviItem(i) => {
3763                     let hi = i.span.hi;
3764                     let decl = P(spanned(lo, hi, DeclItem(i)));
3765                     P(spanned(lo, hi, StmtDecl(decl, ast::DUMMY_NODE_ID)))
3766                 }
3767                 IoviViewItem(vi) => {
3768                     self.span_fatal(vi.span,
3769                                     "view items must be declared at the top of the block");
3770                 }
3771                 IoviForeignItem(_) => {
3772                     self.fatal("foreign items are not allowed here");
3773                 }
3774                 IoviNone(_) => {
3775                     if found_attrs {
3776                         let last_span = self.last_span;
3777                         self.span_err(last_span, item_err);
3778                     }
3779
3780                     // Remainder are line-expr stmts.
3781                     let e = self.parse_expr_res(RESTRICTION_STMT_EXPR);
3782                     P(spanned(lo, e.span.hi, StmtExpr(e, ast::DUMMY_NODE_ID)))
3783                 }
3784             }
3785         }
3786     }
3787
3788     /// Is this expression a successfully-parsed statement?
3789     fn expr_is_complete(&mut self, e: &Expr) -> bool {
3790         self.restrictions.contains(RESTRICTION_STMT_EXPR) &&
3791             !classify::expr_requires_semi_to_be_stmt(e)
3792     }
3793
3794     /// Parse a block. No inner attrs are allowed.
3795     pub fn parse_block(&mut self) -> P<Block> {
3796         maybe_whole!(no_clone self, NtBlock);
3797
3798         let lo = self.span.lo;
3799
3800         if !self.eat(&token::OpenDelim(token::Brace)) {
3801             let sp = self.span;
3802             let tok = self.this_token_to_string();
3803             self.span_fatal_help(sp,
3804                                  format!("expected `{{`, found `{}`", tok)[],
3805                                  "place this code inside a block");
3806         }
3807
3808         return self.parse_block_tail_(lo, DefaultBlock, Vec::new());
3809     }
3810
3811     /// Parse a block. Inner attrs are allowed.
3812     fn parse_inner_attrs_and_block(&mut self)
3813         -> (Vec<Attribute> , P<Block>) {
3814
3815         maybe_whole!(pair_empty self, NtBlock);
3816
3817         let lo = self.span.lo;
3818         self.expect(&token::OpenDelim(token::Brace));
3819         let (inner, next) = self.parse_inner_attrs_and_next();
3820
3821         (inner, self.parse_block_tail_(lo, DefaultBlock, next))
3822     }
3823
3824     /// Precondition: already parsed the '{' or '#{'
3825     /// I guess that also means "already parsed the 'impure'" if
3826     /// necessary, and this should take a qualifier.
3827     /// Some blocks start with "#{"...
3828     fn parse_block_tail(&mut self, lo: BytePos, s: BlockCheckMode) -> P<Block> {
3829         self.parse_block_tail_(lo, s, Vec::new())
3830     }
3831
3832     /// Parse the rest of a block expression or function body
3833     fn parse_block_tail_(&mut self, lo: BytePos, s: BlockCheckMode,
3834                          first_item_attrs: Vec<Attribute> ) -> P<Block> {
3835         let mut stmts = Vec::new();
3836         let mut expr = None;
3837
3838         // wouldn't it be more uniform to parse view items only, here?
3839         let ParsedItemsAndViewItems {
3840             attrs_remaining,
3841             view_items,
3842             items,
3843             ..
3844         } = self.parse_items_and_view_items(first_item_attrs,
3845                                             false, false);
3846
3847         for item in items.into_iter() {
3848             let span = item.span;
3849             let decl = P(spanned(span.lo, span.hi, DeclItem(item)));
3850             stmts.push(P(spanned(span.lo, span.hi, StmtDecl(decl, ast::DUMMY_NODE_ID))));
3851         }
3852
3853         let mut attributes_box = attrs_remaining;
3854
3855         while self.token != token::CloseDelim(token::Brace) {
3856             // parsing items even when they're not allowed lets us give
3857             // better error messages and recover more gracefully.
3858             attributes_box.push_all(self.parse_outer_attributes()[]);
3859             match self.token {
3860                 token::Semi => {
3861                     if !attributes_box.is_empty() {
3862                         let last_span = self.last_span;
3863                         self.span_err(last_span,
3864                                       Parser::expected_item_err(attributes_box[]));
3865                         attributes_box = Vec::new();
3866                     }
3867                     self.bump(); // empty
3868                 }
3869                 token::CloseDelim(token::Brace) => {
3870                     // fall through and out.
3871                 }
3872                 _ => {
3873                     let stmt = self.parse_stmt(attributes_box);
3874                     attributes_box = Vec::new();
3875                     stmt.and_then(|Spanned {node, span}| match node {
3876                         StmtExpr(e, stmt_id) => {
3877                             self.handle_expression_like_statement(e,
3878                                                                   stmt_id,
3879                                                                   span,
3880                                                                   &mut stmts,
3881                                                                   &mut expr);
3882                         }
3883                         StmtMac(macro, MacStmtWithoutBraces) => {
3884                             // statement macro without braces; might be an
3885                             // expr depending on whether a semicolon follows
3886                             match self.token {
3887                                 token::Semi => {
3888                                     stmts.push(P(Spanned {
3889                                         node: StmtMac(macro,
3890                                                       MacStmtWithSemicolon),
3891                                         span: span,
3892                                     }));
3893                                     self.bump();
3894                                 }
3895                                 _ => {
3896                                     let e = self.mk_mac_expr(span.lo,
3897                                                              span.hi,
3898                                                              macro.and_then(|m| m.node));
3899                                     let e =
3900                                         self.parse_dot_or_call_expr_with(e);
3901                                     self.handle_expression_like_statement(
3902                                         e,
3903                                         ast::DUMMY_NODE_ID,
3904                                         span,
3905                                         &mut stmts,
3906                                         &mut expr);
3907                                 }
3908                             }
3909                         }
3910                         StmtMac(m, style) => {
3911                             // statement macro; might be an expr
3912                             match self.token {
3913                                 token::Semi => {
3914                                     stmts.push(P(Spanned {
3915                                         node: StmtMac(m,
3916                                                       MacStmtWithSemicolon),
3917                                         span: span,
3918                                     }));
3919                                     self.bump();
3920                                 }
3921                                 token::CloseDelim(token::Brace) => {
3922                                     // if a block ends in `m!(arg)` without
3923                                     // a `;`, it must be an expr
3924                                     expr = Some(
3925                                         self.mk_mac_expr(span.lo,
3926                                                          span.hi,
3927                                                          m.and_then(|x| x.node)));
3928                                 }
3929                                 _ => {
3930                                     stmts.push(P(Spanned {
3931                                         node: StmtMac(m, style),
3932                                         span: span
3933                                     }));
3934                                 }
3935                             }
3936                         }
3937                         _ => { // all other kinds of statements:
3938                             if classify::stmt_ends_with_semi(&node) {
3939                                 self.commit_stmt_expecting(token::Semi);
3940                             }
3941
3942                             stmts.push(P(Spanned {
3943                                 node: node,
3944                                 span: span
3945                             }));
3946                         }
3947                     })
3948                 }
3949             }
3950         }
3951
3952         if !attributes_box.is_empty() {
3953             let last_span = self.last_span;
3954             self.span_err(last_span,
3955                           Parser::expected_item_err(attributes_box[]));
3956         }
3957
3958         let hi = self.span.hi;
3959         self.bump();
3960         P(ast::Block {
3961             view_items: view_items,
3962             stmts: stmts,
3963             expr: expr,
3964             id: ast::DUMMY_NODE_ID,
3965             rules: s,
3966             span: mk_sp(lo, hi),
3967         })
3968     }
3969
3970     fn handle_expression_like_statement(
3971             &mut self,
3972             e: P<Expr>,
3973             stmt_id: NodeId,
3974             span: Span,
3975             stmts: &mut Vec<P<Stmt>>,
3976             last_block_expr: &mut Option<P<Expr>>) {
3977         // expression without semicolon
3978         if classify::expr_requires_semi_to_be_stmt(&*e) {
3979             // Just check for errors and recover; do not eat semicolon yet.
3980             self.commit_stmt(&[],
3981                              &[token::Semi, token::CloseDelim(token::Brace)]);
3982         }
3983
3984         match self.token {
3985             token::Semi => {
3986                 self.bump();
3987                 let span_with_semi = Span {
3988                     lo: span.lo,
3989                     hi: self.last_span.hi,
3990                     expn_id: span.expn_id,
3991                 };
3992                 stmts.push(P(Spanned {
3993                     node: StmtSemi(e, stmt_id),
3994                     span: span_with_semi,
3995                 }));
3996             }
3997             token::CloseDelim(token::Brace) => *last_block_expr = Some(e),
3998             _ => {
3999                 stmts.push(P(Spanned {
4000                     node: StmtExpr(e, stmt_id),
4001                     span: span
4002                 }));
4003             }
4004         }
4005     }
4006
4007     // Parses a sequence of bounds if a `:` is found,
4008     // otherwise returns empty list.
4009     fn parse_colon_then_ty_param_bounds(&mut self,
4010                                         mode: BoundParsingMode)
4011                                         -> OwnedSlice<TyParamBound>
4012     {
4013         if !self.eat(&token::Colon) {
4014             OwnedSlice::empty()
4015         } else {
4016             self.parse_ty_param_bounds(mode)
4017         }
4018     }
4019
4020     // matches bounds    = ( boundseq )?
4021     // where   boundseq  = ( polybound + boundseq ) | polybound
4022     // and     polybound = ( 'for' '<' 'region '>' )? bound
4023     // and     bound     = 'region | trait_ref
4024     fn parse_ty_param_bounds(&mut self,
4025                              mode: BoundParsingMode)
4026                              -> OwnedSlice<TyParamBound>
4027     {
4028         let mut result = vec!();
4029         loop {
4030             let question_span = self.span;
4031             let ate_question = self.eat(&token::Question);
4032             match self.token {
4033                 token::Lifetime(lifetime) => {
4034                     if ate_question {
4035                         self.span_err(question_span,
4036                                       "`?` may only modify trait bounds, not lifetime bounds");
4037                     }
4038                     result.push(RegionTyParamBound(ast::Lifetime {
4039                         id: ast::DUMMY_NODE_ID,
4040                         span: self.span,
4041                         name: lifetime.name
4042                     }));
4043                     self.bump();
4044                 }
4045                 token::ModSep | token::Ident(..) => {
4046                     let poly_trait_ref = self.parse_poly_trait_ref();
4047                     let modifier = if ate_question {
4048                         if mode == BoundParsingMode::Modified {
4049                             TraitBoundModifier::Maybe
4050                         } else {
4051                             self.span_err(question_span,
4052                                           "unexpected `?`");
4053                             TraitBoundModifier::None
4054                         }
4055                     } else {
4056                         TraitBoundModifier::None
4057                     };
4058                     result.push(TraitTyParamBound(poly_trait_ref, modifier))
4059                 }
4060                 _ => break,
4061             }
4062
4063             if !self.eat(&token::BinOp(token::Plus)) {
4064                 break;
4065             }
4066         }
4067
4068         return OwnedSlice::from_vec(result);
4069     }
4070
4071     fn trait_ref_from_ident(ident: Ident, span: Span) -> TraitRef {
4072         let segment = ast::PathSegment {
4073             identifier: ident,
4074             parameters: ast::PathParameters::none()
4075         };
4076         let path = ast::Path {
4077             span: span,
4078             global: false,
4079             segments: vec![segment],
4080         };
4081         ast::TraitRef {
4082             path: path,
4083             ref_id: ast::DUMMY_NODE_ID,
4084         }
4085     }
4086
4087     /// Matches typaram = (unbound `?`)? IDENT (`?` unbound)? optbounds ( EQ ty )?
4088     fn parse_ty_param(&mut self) -> TyParam {
4089         // This is a bit hacky. Currently we are only interested in a single
4090         // unbound, and it may only be `Sized`. To avoid backtracking and other
4091         // complications, we parse an ident, then check for `?`. If we find it,
4092         // we use the ident as the unbound, otherwise, we use it as the name of
4093         // type param. Even worse, for now, we need to check for `?` before or
4094         // after the bound.
4095         let mut span = self.span;
4096         let mut ident = self.parse_ident();
4097         let mut unbound = None;
4098         if self.eat(&token::Question) {
4099             let tref = Parser::trait_ref_from_ident(ident, span);
4100             unbound = Some(tref);
4101             span = self.span;
4102             ident = self.parse_ident();
4103         }
4104
4105         let mut bounds = self.parse_colon_then_ty_param_bounds(BoundParsingMode::Modified);
4106         if let Some(unbound) = unbound {
4107             let mut bounds_as_vec = bounds.into_vec();
4108             bounds_as_vec.push(TraitTyParamBound(PolyTraitRef { bound_lifetimes: vec![],
4109                                                                 trait_ref: unbound },
4110                                                  TraitBoundModifier::Maybe));
4111             bounds = OwnedSlice::from_vec(bounds_as_vec);
4112         };
4113
4114         let default = if self.check(&token::Eq) {
4115             self.bump();
4116             Some(self.parse_ty_sum())
4117         }
4118         else { None };
4119
4120         TyParam {
4121             ident: ident,
4122             id: ast::DUMMY_NODE_ID,
4123             bounds: bounds,
4124             default: default,
4125             span: span,
4126         }
4127     }
4128
4129     /// Parse a set of optional generic type parameter declarations. Where
4130     /// clauses are not parsed here, and must be added later via
4131     /// `parse_where_clause()`.
4132     ///
4133     /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
4134     ///                  | ( < lifetimes , typaramseq ( , )? > )
4135     /// where   typaramseq = ( typaram ) | ( typaram , typaramseq )
4136     pub fn parse_generics(&mut self) -> ast::Generics {
4137         if self.eat(&token::Lt) {
4138             let lifetime_defs = self.parse_lifetime_defs();
4139             let mut seen_default = false;
4140             let ty_params = self.parse_seq_to_gt(Some(token::Comma), |p| {
4141                 p.forbid_lifetime();
4142                 let ty_param = p.parse_ty_param();
4143                 if ty_param.default.is_some() {
4144                     seen_default = true;
4145                 } else if seen_default {
4146                     let last_span = p.last_span;
4147                     p.span_err(last_span,
4148                                "type parameters with a default must be trailing");
4149                 }
4150                 ty_param
4151             });
4152             ast::Generics {
4153                 lifetimes: lifetime_defs,
4154                 ty_params: ty_params,
4155                 where_clause: WhereClause {
4156                     id: ast::DUMMY_NODE_ID,
4157                     predicates: Vec::new(),
4158                 }
4159             }
4160         } else {
4161             ast_util::empty_generics()
4162         }
4163     }
4164
4165     fn parse_generic_values_after_lt(&mut self)
4166                                      -> (Vec<ast::Lifetime>, Vec<P<Ty>>, Vec<P<TypeBinding>>) {
4167         let lifetimes = self.parse_lifetimes(token::Comma);
4168
4169         // First parse types.
4170         let (types, returned) = self.parse_seq_to_gt_or_return(
4171             Some(token::Comma),
4172             |p| {
4173                 p.forbid_lifetime();
4174                 if p.look_ahead(1, |t| t == &token::Eq) {
4175                     None
4176                 } else {
4177                     Some(p.parse_ty_sum())
4178                 }
4179             }
4180         );
4181
4182         // If we found the `>`, don't continue.
4183         if !returned {
4184             return (lifetimes, types.into_vec(), Vec::new());
4185         }
4186
4187         // Then parse type bindings.
4188         let bindings = self.parse_seq_to_gt(
4189             Some(token::Comma),
4190             |p| {
4191                 p.forbid_lifetime();
4192                 let lo = p.span.lo;
4193                 let ident = p.parse_ident();
4194                 let found_eq = p.eat(&token::Eq);
4195                 if !found_eq {
4196                     let span = p.span;
4197                     p.span_warn(span, "whoops, no =?");
4198                 }
4199                 let ty = p.parse_ty();
4200                 let hi = p.span.hi;
4201                 let span = mk_sp(lo, hi);
4202                 return P(TypeBinding{id: ast::DUMMY_NODE_ID,
4203                     ident: ident,
4204                     ty: ty,
4205                     span: span,
4206                 });
4207             }
4208         );
4209         (lifetimes, types.into_vec(), bindings.into_vec())
4210     }
4211
4212     fn forbid_lifetime(&mut self) {
4213         if self.token.is_lifetime() {
4214             let span = self.span;
4215             self.span_fatal(span, "lifetime parameters must be declared \
4216                                         prior to type parameters");
4217         }
4218     }
4219
4220     /// Parses an optional `where` clause and places it in `generics`.
4221     ///
4222     /// ```
4223     /// where T : Trait<U, V> + 'b, 'a : 'b
4224     /// ```
4225     fn parse_where_clause(&mut self, generics: &mut ast::Generics) {
4226         if !self.eat_keyword(keywords::Where) {
4227             return
4228         }
4229
4230         let mut parsed_something = false;
4231         loop {
4232             let lo = self.span.lo;
4233             match self.token {
4234                 token::OpenDelim(token::Brace) => {
4235                     break
4236                 }
4237
4238                 token::Lifetime(..) => {
4239                     let bounded_lifetime =
4240                         self.parse_lifetime();
4241
4242                     self.eat(&token::Colon);
4243
4244                     let bounds =
4245                         self.parse_lifetimes(token::BinOp(token::Plus));
4246
4247                     let hi = self.span.hi;
4248                     let span = mk_sp(lo, hi);
4249
4250                     generics.where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
4251                         ast::WhereRegionPredicate {
4252                             span: span,
4253                             lifetime: bounded_lifetime,
4254                             bounds: bounds
4255                         }
4256                     ));
4257
4258                     parsed_something = true;
4259                 }
4260
4261                 _ => {
4262                     let bounded_ty = self.parse_ty();
4263
4264                     if self.eat(&token::Colon) {
4265                         let bounds = self.parse_ty_param_bounds(BoundParsingMode::Bare);
4266                         let hi = self.span.hi;
4267                         let span = mk_sp(lo, hi);
4268
4269                         if bounds.len() == 0 {
4270                             self.span_err(span,
4271                                           "each predicate in a `where` clause must have \
4272                                    at least one bound in it");
4273                         }
4274
4275                         generics.where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
4276                                 ast::WhereBoundPredicate {
4277                                     span: span,
4278                                     bounded_ty: bounded_ty,
4279                                     bounds: bounds,
4280                         }));
4281
4282                         parsed_something = true;
4283                     } else if self.eat(&token::Eq) {
4284                         // let ty = self.parse_ty();
4285                         let hi = self.span.hi;
4286                         let span = mk_sp(lo, hi);
4287                         // generics.where_clause.predicates.push(
4288                         //     ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
4289                         //         id: ast::DUMMY_NODE_ID,
4290                         //         span: span,
4291                         //         path: panic!("NYI"), //bounded_ty,
4292                         //         ty: ty,
4293                         // }));
4294                         // parsed_something = true;
4295                         // // FIXME(#18433)
4296                         self.span_err(span,
4297                                      "equality constraints are not yet supported \
4298                                      in where clauses (#20041)");
4299                     } else {
4300                         let last_span = self.last_span;
4301                         self.span_err(last_span,
4302                               "unexpected token in `where` clause");
4303                     }
4304                 }
4305             };
4306
4307             if !self.eat(&token::Comma) {
4308                 break
4309             }
4310         }
4311
4312         if !parsed_something {
4313             let last_span = self.last_span;
4314             self.span_err(last_span,
4315                           "a `where` clause must have at least one predicate \
4316                            in it");
4317         }
4318     }
4319
4320     fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
4321                      -> (Vec<Arg> , bool) {
4322         let sp = self.span;
4323         let mut args: Vec<Option<Arg>> =
4324             self.parse_unspanned_seq(
4325                 &token::OpenDelim(token::Paren),
4326                 &token::CloseDelim(token::Paren),
4327                 seq_sep_trailing_allowed(token::Comma),
4328                 |p| {
4329                     if p.token == token::DotDotDot {
4330                         p.bump();
4331                         if allow_variadic {
4332                             if p.token != token::CloseDelim(token::Paren) {
4333                                 let span = p.span;
4334                                 p.span_fatal(span,
4335                                     "`...` must be last in argument list for variadic function");
4336                             }
4337                         } else {
4338                             let span = p.span;
4339                             p.span_fatal(span,
4340                                          "only foreign functions are allowed to be variadic");
4341                         }
4342                         None
4343                     } else {
4344                         Some(p.parse_arg_general(named_args))
4345                     }
4346                 }
4347             );
4348
4349         let variadic = match args.pop() {
4350             Some(None) => true,
4351             Some(x) => {
4352                 // Need to put back that last arg
4353                 args.push(x);
4354                 false
4355             }
4356             None => false
4357         };
4358
4359         if variadic && args.is_empty() {
4360             self.span_err(sp,
4361                           "variadic function must be declared with at least one named argument");
4362         }
4363
4364         let args = args.into_iter().map(|x| x.unwrap()).collect();
4365
4366         (args, variadic)
4367     }
4368
4369     /// Parse the argument list and result type of a function declaration
4370     pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> P<FnDecl> {
4371
4372         let (args, variadic) = self.parse_fn_args(true, allow_variadic);
4373         let ret_ty = self.parse_ret_ty();
4374
4375         P(FnDecl {
4376             inputs: args,
4377             output: ret_ty,
4378             variadic: variadic
4379         })
4380     }
4381
4382     fn is_self_ident(&mut self) -> bool {
4383         match self.token {
4384           token::Ident(id, token::Plain) => id.name == special_idents::self_.name,
4385           _ => false
4386         }
4387     }
4388
4389     fn expect_self_ident(&mut self) -> ast::Ident {
4390         match self.token {
4391             token::Ident(id, token::Plain) if id.name == special_idents::self_.name => {
4392                 self.bump();
4393                 id
4394             },
4395             _ => {
4396                 let token_str = self.this_token_to_string();
4397                 self.fatal(format!("expected `self`, found `{}`",
4398                                    token_str)[])
4399             }
4400         }
4401     }
4402
4403     /// Parse the argument list and result type of a function
4404     /// that may have a self type.
4405     fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> (ExplicitSelf, P<FnDecl>) where
4406         F: FnMut(&mut Parser) -> Arg,
4407     {
4408         fn maybe_parse_borrowed_explicit_self(this: &mut Parser)
4409                                               -> ast::ExplicitSelf_ {
4410             // The following things are possible to see here:
4411             //
4412             //     fn(&mut self)
4413             //     fn(&mut self)
4414             //     fn(&'lt self)
4415             //     fn(&'lt mut self)
4416             //
4417             // We already know that the current token is `&`.
4418
4419             if this.look_ahead(1, |t| t.is_keyword(keywords::Self)) {
4420                 this.bump();
4421                 SelfRegion(None, MutImmutable, this.expect_self_ident())
4422             } else if this.look_ahead(1, |t| t.is_mutability()) &&
4423                       this.look_ahead(2, |t| t.is_keyword(keywords::Self)) {
4424                 this.bump();
4425                 let mutability = this.parse_mutability();
4426                 SelfRegion(None, mutability, this.expect_self_ident())
4427             } else if this.look_ahead(1, |t| t.is_lifetime()) &&
4428                       this.look_ahead(2, |t| t.is_keyword(keywords::Self)) {
4429                 this.bump();
4430                 let lifetime = this.parse_lifetime();
4431                 SelfRegion(Some(lifetime), MutImmutable, this.expect_self_ident())
4432             } else if this.look_ahead(1, |t| t.is_lifetime()) &&
4433                       this.look_ahead(2, |t| t.is_mutability()) &&
4434                       this.look_ahead(3, |t| t.is_keyword(keywords::Self)) {
4435                 this.bump();
4436                 let lifetime = this.parse_lifetime();
4437                 let mutability = this.parse_mutability();
4438                 SelfRegion(Some(lifetime), mutability, this.expect_self_ident())
4439             } else {
4440                 SelfStatic
4441             }
4442         }
4443
4444         self.expect(&token::OpenDelim(token::Paren));
4445
4446         // A bit of complexity and lookahead is needed here in order to be
4447         // backwards compatible.
4448         let lo = self.span.lo;
4449         let mut self_ident_lo = self.span.lo;
4450         let mut self_ident_hi = self.span.hi;
4451
4452         let mut mutbl_self = MutImmutable;
4453         let explicit_self = match self.token {
4454             token::BinOp(token::And) => {
4455                 let eself = maybe_parse_borrowed_explicit_self(self);
4456                 self_ident_lo = self.last_span.lo;
4457                 self_ident_hi = self.last_span.hi;
4458                 eself
4459             }
4460             token::Tilde => {
4461                 // We need to make sure it isn't a type
4462                 if self.look_ahead(1, |t| t.is_keyword(keywords::Self)) {
4463                     self.bump();
4464                     drop(self.expect_self_ident());
4465                     let last_span = self.last_span;
4466                     self.obsolete(last_span, ObsoleteOwnedSelf)
4467                 }
4468                 SelfStatic
4469             }
4470             token::BinOp(token::Star) => {
4471                 // Possibly "*self" or "*mut self" -- not supported. Try to avoid
4472                 // emitting cryptic "unexpected token" errors.
4473                 self.bump();
4474                 let _mutability = if self.token.is_mutability() {
4475                     self.parse_mutability()
4476                 } else {
4477                     MutImmutable
4478                 };
4479                 if self.is_self_ident() {
4480                     let span = self.span;
4481                     self.span_err(span, "cannot pass self by unsafe pointer");
4482                     self.bump();
4483                 }
4484                 // error case, making bogus self ident:
4485                 SelfValue(special_idents::self_)
4486             }
4487             token::Ident(..) => {
4488                 if self.is_self_ident() {
4489                     let self_ident = self.expect_self_ident();
4490
4491                     // Determine whether this is the fully explicit form, `self:
4492                     // TYPE`.
4493                     if self.eat(&token::Colon) {
4494                         SelfExplicit(self.parse_ty_sum(), self_ident)
4495                     } else {
4496                         SelfValue(self_ident)
4497                     }
4498                 } else if self.token.is_mutability() &&
4499                         self.look_ahead(1, |t| t.is_keyword(keywords::Self)) {
4500                     mutbl_self = self.parse_mutability();
4501                     let self_ident = self.expect_self_ident();
4502
4503                     // Determine whether this is the fully explicit form,
4504                     // `self: TYPE`.
4505                     if self.eat(&token::Colon) {
4506                         SelfExplicit(self.parse_ty_sum(), self_ident)
4507                     } else {
4508                         SelfValue(self_ident)
4509                     }
4510                 } else if self.token.is_mutability() &&
4511                         self.look_ahead(1, |t| *t == token::Tilde) &&
4512                         self.look_ahead(2, |t| t.is_keyword(keywords::Self)) {
4513                     mutbl_self = self.parse_mutability();
4514                     self.bump();
4515                     drop(self.expect_self_ident());
4516                     let last_span = self.last_span;
4517                     self.obsolete(last_span, ObsoleteOwnedSelf);
4518                     SelfStatic
4519                 } else {
4520                     SelfStatic
4521                 }
4522             }
4523             _ => SelfStatic,
4524         };
4525
4526         let explicit_self_sp = mk_sp(self_ident_lo, self_ident_hi);
4527
4528         // shared fall-through for the three cases below. borrowing prevents simply
4529         // writing this as a closure
4530         macro_rules! parse_remaining_arguments {
4531             ($self_id:ident) =>
4532             {
4533             // If we parsed a self type, expect a comma before the argument list.
4534             match self.token {
4535                 token::Comma => {
4536                     self.bump();
4537                     let sep = seq_sep_trailing_allowed(token::Comma);
4538                     let mut fn_inputs = self.parse_seq_to_before_end(
4539                         &token::CloseDelim(token::Paren),
4540                         sep,
4541                         parse_arg_fn
4542                     );
4543                     fn_inputs.insert(0, Arg::new_self(explicit_self_sp, mutbl_self, $self_id));
4544                     fn_inputs
4545                 }
4546                 token::CloseDelim(token::Paren) => {
4547                     vec!(Arg::new_self(explicit_self_sp, mutbl_self, $self_id))
4548                 }
4549                 _ => {
4550                     let token_str = self.this_token_to_string();
4551                     self.fatal(format!("expected `,` or `)`, found `{}`",
4552                                        token_str)[])
4553                 }
4554             }
4555             }
4556         }
4557
4558         let fn_inputs = match explicit_self {
4559             SelfStatic =>  {
4560                 let sep = seq_sep_trailing_allowed(token::Comma);
4561                 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)
4562             }
4563             SelfValue(id) => parse_remaining_arguments!(id),
4564             SelfRegion(_,_,id) => parse_remaining_arguments!(id),
4565             SelfExplicit(_,id) => parse_remaining_arguments!(id),
4566         };
4567
4568
4569         self.expect(&token::CloseDelim(token::Paren));
4570
4571         let hi = self.span.hi;
4572
4573         let ret_ty = self.parse_ret_ty();
4574
4575         let fn_decl = P(FnDecl {
4576             inputs: fn_inputs,
4577             output: ret_ty,
4578             variadic: false
4579         });
4580
4581         (spanned(lo, hi, explicit_self), fn_decl)
4582     }
4583
4584     // parse the |arg, arg| header on a lambda
4585     fn parse_fn_block_decl(&mut self)
4586                            -> (P<FnDecl>, Option<UnboxedClosureKind>) {
4587         let (optional_unboxed_closure_kind, inputs_captures) = {
4588             if self.eat(&token::OrOr) {
4589                 (None, Vec::new())
4590             } else {
4591                 self.expect(&token::BinOp(token::Or));
4592                 let optional_unboxed_closure_kind =
4593                     self.parse_optional_unboxed_closure_kind();
4594                 let args = self.parse_seq_to_before_end(
4595                     &token::BinOp(token::Or),
4596                     seq_sep_trailing_allowed(token::Comma),
4597                     |p| p.parse_fn_block_arg()
4598                 );
4599                 self.bump();
4600                 (optional_unboxed_closure_kind, args)
4601             }
4602         };
4603         let output = if self.check(&token::RArrow) {
4604             self.parse_ret_ty()
4605         } else {
4606             Return(P(Ty {
4607                 id: ast::DUMMY_NODE_ID,
4608                 node: TyInfer,
4609                 span: self.span,
4610             }))
4611         };
4612
4613         (P(FnDecl {
4614             inputs: inputs_captures,
4615             output: output,
4616             variadic: false
4617         }), optional_unboxed_closure_kind)
4618     }
4619
4620     /// Parses the `(arg, arg) -> return_type` header on a procedure.
4621     fn parse_proc_decl(&mut self) -> P<FnDecl> {
4622         let inputs =
4623             self.parse_unspanned_seq(&token::OpenDelim(token::Paren),
4624                                      &token::CloseDelim(token::Paren),
4625                                      seq_sep_trailing_allowed(token::Comma),
4626                                      |p| p.parse_fn_block_arg());
4627
4628         let output = if self.check(&token::RArrow) {
4629             self.parse_ret_ty()
4630         } else {
4631             Return(P(Ty {
4632                 id: ast::DUMMY_NODE_ID,
4633                 node: TyInfer,
4634                 span: self.span,
4635             }))
4636         };
4637
4638         P(FnDecl {
4639             inputs: inputs,
4640             output: output,
4641             variadic: false
4642         })
4643     }
4644
4645     /// Parse the name and optional generic types of a function header.
4646     fn parse_fn_header(&mut self) -> (Ident, ast::Generics) {
4647         let id = self.parse_ident();
4648         let generics = self.parse_generics();
4649         (id, generics)
4650     }
4651
4652     fn mk_item(&mut self, lo: BytePos, hi: BytePos, ident: Ident,
4653                node: Item_, vis: Visibility,
4654                attrs: Vec<Attribute>) -> P<Item> {
4655         P(Item {
4656             ident: ident,
4657             attrs: attrs,
4658             id: ast::DUMMY_NODE_ID,
4659             node: node,
4660             vis: vis,
4661             span: mk_sp(lo, hi)
4662         })
4663     }
4664
4665     /// Parse an item-position function declaration.
4666     fn parse_item_fn(&mut self, unsafety: Unsafety, abi: abi::Abi) -> ItemInfo {
4667         let (ident, mut generics) = self.parse_fn_header();
4668         let decl = self.parse_fn_decl(false);
4669         self.parse_where_clause(&mut generics);
4670         let (inner_attrs, body) = self.parse_inner_attrs_and_block();
4671         (ident, ItemFn(decl, unsafety, abi, generics, body), Some(inner_attrs))
4672     }
4673
4674     /// Parse a method in a trait impl
4675     pub fn parse_method_with_outer_attributes(&mut self) -> P<Method> {
4676         let attrs = self.parse_outer_attributes();
4677         let visa = self.parse_visibility();
4678         self.parse_method(attrs, visa)
4679     }
4680
4681     /// Parse a method in a trait impl, starting with `attrs` attributes.
4682     pub fn parse_method(&mut self,
4683                         attrs: Vec<Attribute>,
4684                         visa: Visibility)
4685                         -> P<Method> {
4686         let lo = self.span.lo;
4687
4688         // code copied from parse_macro_use_or_failure... abstraction!
4689         let (method_, hi, new_attrs) = {
4690             if !self.token.is_any_keyword()
4691                 && self.look_ahead(1, |t| *t == token::Not)
4692                 && (self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren))
4693                     || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) {
4694                 // method macro.
4695                 let pth = self.parse_path(NoTypesAllowed);
4696                 self.expect(&token::Not);
4697
4698                 // eat a matched-delimiter token tree:
4699                 let delim = self.expect_open_delim();
4700                 let tts = self.parse_seq_to_end(&token::CloseDelim(delim),
4701                                                 seq_sep_none(),
4702                                                 |p| p.parse_token_tree());
4703                 let m_ = ast::MacInvocTT(pth, tts, EMPTY_CTXT);
4704                 let m: ast::Mac = codemap::Spanned { node: m_,
4705                                                  span: mk_sp(self.span.lo,
4706                                                              self.span.hi) };
4707                 if delim != token::Brace {
4708                     self.expect(&token::Semi)
4709                 }
4710                 (ast::MethMac(m), self.span.hi, attrs)
4711             } else {
4712                 let unsafety = self.parse_unsafety();
4713                 let abi = if self.eat_keyword(keywords::Extern) {
4714                     self.parse_opt_abi().unwrap_or(abi::C)
4715                 } else {
4716                     abi::Rust
4717                 };
4718                 self.expect_keyword(keywords::Fn);
4719                 let ident = self.parse_ident();
4720                 let mut generics = self.parse_generics();
4721                 let (explicit_self, decl) = self.parse_fn_decl_with_self(|p| {
4722                         p.parse_arg()
4723                     });
4724                 self.parse_where_clause(&mut generics);
4725                 let (inner_attrs, body) = self.parse_inner_attrs_and_block();
4726                 let body_span = body.span;
4727                 let mut new_attrs = attrs;
4728                 new_attrs.push_all(inner_attrs[]);
4729                 (ast::MethDecl(ident,
4730                                generics,
4731                                abi,
4732                                explicit_self,
4733                                unsafety,
4734                                decl,
4735                                body,
4736                                visa),
4737                  body_span.hi, new_attrs)
4738             }
4739         };
4740         P(ast::Method {
4741             attrs: new_attrs,
4742             id: ast::DUMMY_NODE_ID,
4743             span: mk_sp(lo, hi),
4744             node: method_,
4745         })
4746     }
4747
4748     /// Parse trait Foo { ... }
4749     fn parse_item_trait(&mut self, unsafety: Unsafety) -> ItemInfo {
4750         let ident = self.parse_ident();
4751         let mut tps = self.parse_generics();
4752         let unbound = self.parse_for_sized();
4753
4754         // Parse supertrait bounds.
4755         let mut bounds = self.parse_colon_then_ty_param_bounds(BoundParsingMode::Bare);
4756
4757         if let Some(unbound) = unbound {
4758             let mut bounds_as_vec = bounds.into_vec();
4759             bounds_as_vec.push(TraitTyParamBound(PolyTraitRef { bound_lifetimes: vec![],
4760                                                                 trait_ref: unbound },
4761                                                  TraitBoundModifier::Maybe));
4762             bounds = OwnedSlice::from_vec(bounds_as_vec);
4763         };
4764
4765         self.parse_where_clause(&mut tps);
4766
4767         let meths = self.parse_trait_items();
4768         (ident, ItemTrait(unsafety, tps, bounds, meths), None)
4769     }
4770
4771     fn parse_impl_items(&mut self) -> (Vec<ImplItem>, Vec<Attribute>) {
4772         let mut impl_items = Vec::new();
4773         self.expect(&token::OpenDelim(token::Brace));
4774         let (inner_attrs, mut method_attrs) =
4775             self.parse_inner_attrs_and_next();
4776         while !self.eat(&token::CloseDelim(token::Brace)) {
4777             method_attrs.extend(self.parse_outer_attributes().into_iter());
4778             let vis = self.parse_visibility();
4779             if self.eat_keyword(keywords::Type) {
4780                 impl_items.push(TypeImplItem(P(self.parse_typedef(
4781                             method_attrs,
4782                             vis))))
4783             } else {
4784                 impl_items.push(MethodImplItem(self.parse_method(
4785                             method_attrs,
4786                             vis)));
4787             }
4788             method_attrs = self.parse_outer_attributes();
4789         }
4790         (impl_items, inner_attrs)
4791     }
4792
4793     /// Parses two variants (with the region/type params always optional):
4794     ///    impl<T> Foo { ... }
4795     ///    impl<T> ToString for ~[T] { ... }
4796     fn parse_item_impl(&mut self, unsafety: ast::Unsafety) -> ItemInfo {
4797         // First, parse type parameters if necessary.
4798         let mut generics = self.parse_generics();
4799
4800         // Special case: if the next identifier that follows is '(', don't
4801         // allow this to be parsed as a trait.
4802         let could_be_trait = self.token != token::OpenDelim(token::Paren);
4803
4804         // Parse the trait.
4805         let mut ty = self.parse_ty_sum();
4806
4807         // Parse traits, if necessary.
4808         let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) {
4809             // New-style trait. Reinterpret the type as a trait.
4810             let opt_trait_ref = match ty.node {
4811                 TyPath(ref path, node_id) => {
4812                     Some(TraitRef {
4813                         path: (*path).clone(),
4814                         ref_id: node_id,
4815                     })
4816                 }
4817                 _ => {
4818                     self.span_err(ty.span, "not a trait");
4819                     None
4820                 }
4821             };
4822
4823             ty = self.parse_ty_sum();
4824             opt_trait_ref
4825         } else {
4826             None
4827         };
4828
4829         self.parse_where_clause(&mut generics);
4830         let (impl_items, attrs) = self.parse_impl_items();
4831
4832         let ident = ast_util::impl_pretty_name(&opt_trait, &*ty);
4833
4834         (ident,
4835          ItemImpl(unsafety, generics, opt_trait, ty, impl_items),
4836          Some(attrs))
4837     }
4838
4839     /// Parse a::B<String,int>
4840     fn parse_trait_ref(&mut self) -> TraitRef {
4841         ast::TraitRef {
4842             path: self.parse_path(LifetimeAndTypesWithoutColons),
4843             ref_id: ast::DUMMY_NODE_ID,
4844         }
4845     }
4846
4847     fn parse_late_bound_lifetime_defs(&mut self) -> Vec<ast::LifetimeDef> {
4848         if self.eat_keyword(keywords::For) {
4849             self.expect(&token::Lt);
4850             let lifetime_defs = self.parse_lifetime_defs();
4851             self.expect_gt();
4852             lifetime_defs
4853         } else {
4854             Vec::new()
4855         }
4856     }
4857
4858     /// Parse for<'l> a::B<String,int>
4859     fn parse_poly_trait_ref(&mut self) -> PolyTraitRef {
4860         let lifetime_defs = self.parse_late_bound_lifetime_defs();
4861
4862         ast::PolyTraitRef {
4863             bound_lifetimes: lifetime_defs,
4864             trait_ref: self.parse_trait_ref()
4865         }
4866     }
4867
4868     /// Parse struct Foo { ... }
4869     fn parse_item_struct(&mut self) -> ItemInfo {
4870         let class_name = self.parse_ident();
4871         let mut generics = self.parse_generics();
4872
4873         if self.eat(&token::Colon) {
4874             let ty = self.parse_ty_sum();
4875             self.span_err(ty.span, "`virtual` structs have been removed from the language");
4876         }
4877
4878         self.parse_where_clause(&mut generics);
4879
4880         let mut fields: Vec<StructField>;
4881         let is_tuple_like;
4882
4883         if self.eat(&token::OpenDelim(token::Brace)) {
4884             // It's a record-like struct.
4885             is_tuple_like = false;
4886             fields = Vec::new();
4887             while self.token != token::CloseDelim(token::Brace) {
4888                 fields.push(self.parse_struct_decl_field(true));
4889             }
4890             if fields.len() == 0 {
4891                 self.fatal(format!("unit-like struct definition should be \
4892                                     written as `struct {};`",
4893                                    token::get_ident(class_name))[]);
4894             }
4895             self.bump();
4896         } else if self.check(&token::OpenDelim(token::Paren)) {
4897             // It's a tuple-like struct.
4898             is_tuple_like = true;
4899             fields = self.parse_unspanned_seq(
4900                 &token::OpenDelim(token::Paren),
4901                 &token::CloseDelim(token::Paren),
4902                 seq_sep_trailing_allowed(token::Comma),
4903                 |p| {
4904                 let attrs = p.parse_outer_attributes();
4905                 let lo = p.span.lo;
4906                 let struct_field_ = ast::StructField_ {
4907                     kind: UnnamedField(p.parse_visibility()),
4908                     id: ast::DUMMY_NODE_ID,
4909                     ty: p.parse_ty_sum(),
4910                     attrs: attrs,
4911                 };
4912                 spanned(lo, p.span.hi, struct_field_)
4913             });
4914             if fields.len() == 0 {
4915                 self.fatal(format!("unit-like struct definition should be \
4916                                     written as `struct {};`",
4917                                    token::get_ident(class_name))[]);
4918             }
4919             self.expect(&token::Semi);
4920         } else if self.eat(&token::Semi) {
4921             // It's a unit-like struct.
4922             is_tuple_like = true;
4923             fields = Vec::new();
4924         } else {
4925             let token_str = self.this_token_to_string();
4926             self.fatal(format!("expected `{}`, `(`, or `;` after struct \
4927                                 name, found `{}`", "{",
4928                                token_str)[])
4929         }
4930
4931         let _ = ast::DUMMY_NODE_ID;  // FIXME: Workaround for crazy bug.
4932         let new_id = ast::DUMMY_NODE_ID;
4933         (class_name,
4934          ItemStruct(P(ast::StructDef {
4935              fields: fields,
4936              ctor_id: if is_tuple_like { Some(new_id) } else { None },
4937          }), generics),
4938          None)
4939     }
4940
4941     /// Parse a structure field declaration
4942     pub fn parse_single_struct_field(&mut self,
4943                                      vis: Visibility,
4944                                      attrs: Vec<Attribute> )
4945                                      -> StructField {
4946         let a_var = self.parse_name_and_ty(vis, attrs);
4947         match self.token {
4948             token::Comma => {
4949                 self.bump();
4950             }
4951             token::CloseDelim(token::Brace) => {}
4952             _ => {
4953                 let span = self.span;
4954                 let token_str = self.this_token_to_string();
4955                 self.span_fatal_help(span,
4956                                      format!("expected `,`, or `}}`, found `{}`",
4957                                              token_str)[],
4958                                      "struct fields should be separated by commas")
4959             }
4960         }
4961         a_var
4962     }
4963
4964     /// Parse an element of a struct definition
4965     fn parse_struct_decl_field(&mut self, allow_pub: bool) -> StructField {
4966
4967         let attrs = self.parse_outer_attributes();
4968
4969         if self.eat_keyword(keywords::Pub) {
4970             if !allow_pub {
4971                 let span = self.last_span;
4972                 self.span_err(span, "`pub` is not allowed here");
4973             }
4974             return self.parse_single_struct_field(Public, attrs);
4975         }
4976
4977         return self.parse_single_struct_field(Inherited, attrs);
4978     }
4979
4980     /// Parse visibility: PUB, PRIV, or nothing
4981     fn parse_visibility(&mut self) -> Visibility {
4982         if self.eat_keyword(keywords::Pub) { Public }
4983         else { Inherited }
4984     }
4985
4986     fn parse_for_sized(&mut self) -> Option<ast::TraitRef> {
4987         // FIXME, this should really use TraitBoundModifier, but it will get
4988         // re-jigged shortly in any case, so leaving the hacky version for now.
4989         if self.eat_keyword(keywords::For) {
4990             let span = self.span;
4991             let mut ate_question = false;
4992             if self.eat(&token::Question) {
4993                 ate_question = true;
4994             }
4995             let ident = self.parse_ident();
4996             if self.eat(&token::Question) {
4997                 if ate_question {
4998                     self.span_err(span,
4999                         "unexpected `?`");
5000                 }
5001                 ate_question = true;
5002             }
5003             if !ate_question {
5004                 self.span_err(span,
5005                     "expected `?Sized` after `for` in trait item");
5006                 return None;
5007             }
5008             let tref = Parser::trait_ref_from_ident(ident, span);
5009             Some(tref)
5010         } else {
5011             None
5012         }
5013     }
5014
5015     /// Given a termination token and a vector of already-parsed
5016     /// attributes (of length 0 or 1), parse all of the items in a module
5017     fn parse_mod_items(&mut self,
5018                        term: token::Token,
5019                        first_item_attrs: Vec<Attribute>,
5020                        inner_lo: BytePos)
5021                        -> Mod {
5022         // parse all of the items up to closing or an attribute.
5023         // view items are legal here.
5024         let ParsedItemsAndViewItems {
5025             attrs_remaining,
5026             view_items,
5027             items: starting_items,
5028             ..
5029         } = self.parse_items_and_view_items(first_item_attrs, true, true);
5030         let mut items: Vec<P<Item>> = starting_items;
5031         let attrs_remaining_len = attrs_remaining.len();
5032
5033         // don't think this other loop is even necessary....
5034
5035         let mut first = true;
5036         while self.token != term {
5037             let mut attrs = self.parse_outer_attributes();
5038             if first {
5039                 let mut tmp = attrs_remaining.clone();
5040                 tmp.push_all(attrs[]);
5041                 attrs = tmp;
5042                 first = false;
5043             }
5044             debug!("parse_mod_items: parse_item_or_view_item(attrs={})",
5045                    attrs);
5046             match self.parse_item_or_view_item(attrs,
5047                                                true /* macros allowed */) {
5048               IoviItem(item) => items.push(item),
5049               IoviViewItem(view_item) => {
5050                 self.span_fatal(view_item.span,
5051                                 "view items must be declared at the top of \
5052                                  the module");
5053               }
5054               _ => {
5055                   let token_str = self.this_token_to_string();
5056                   self.fatal(format!("expected item, found `{}`",
5057                                      token_str)[])
5058               }
5059             }
5060         }
5061
5062         if first && attrs_remaining_len > 0u {
5063             // We parsed attributes for the first item but didn't find it
5064             let last_span = self.last_span;
5065             self.span_err(last_span,
5066                           Parser::expected_item_err(attrs_remaining[]));
5067         }
5068
5069         ast::Mod {
5070             inner: mk_sp(inner_lo, self.span.lo),
5071             view_items: view_items,
5072             items: items
5073         }
5074     }
5075
5076     fn parse_item_const(&mut self, m: Option<Mutability>) -> ItemInfo {
5077         let id = self.parse_ident();
5078         self.expect(&token::Colon);
5079         let ty = self.parse_ty_sum();
5080         self.expect(&token::Eq);
5081         let e = self.parse_expr();
5082         self.commit_expr_expecting(&*e, token::Semi);
5083         let item = match m {
5084             Some(m) => ItemStatic(ty, m, e),
5085             None => ItemConst(ty, e),
5086         };
5087         (id, item, None)
5088     }
5089
5090     /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
5091     fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> ItemInfo {
5092         let id_span = self.span;
5093         let id = self.parse_ident();
5094         if self.check(&token::Semi) {
5095             self.bump();
5096             // This mod is in an external file. Let's go get it!
5097             let (m, attrs) = self.eval_src_mod(id, outer_attrs, id_span);
5098             (id, m, Some(attrs))
5099         } else {
5100             self.push_mod_path(id, outer_attrs);
5101             self.expect(&token::OpenDelim(token::Brace));
5102             let mod_inner_lo = self.span.lo;
5103             let old_owns_directory = self.owns_directory;
5104             self.owns_directory = true;
5105             let (inner, next) = self.parse_inner_attrs_and_next();
5106             let m = self.parse_mod_items(token::CloseDelim(token::Brace), next, mod_inner_lo);
5107             self.expect(&token::CloseDelim(token::Brace));
5108             self.owns_directory = old_owns_directory;
5109             self.pop_mod_path();
5110             (id, ItemMod(m), Some(inner))
5111         }
5112     }
5113
5114     fn push_mod_path(&mut self, id: Ident, attrs: &[Attribute]) {
5115         let default_path = self.id_to_interned_str(id);
5116         let file_path = match ::attr::first_attr_value_str_by_name(attrs,
5117                                                                    "path") {
5118             Some(d) => d,
5119             None => default_path,
5120         };
5121         self.mod_path_stack.push(file_path)
5122     }
5123
5124     fn pop_mod_path(&mut self) {
5125         self.mod_path_stack.pop().unwrap();
5126     }
5127
5128     /// Read a module from a source file.
5129     fn eval_src_mod(&mut self,
5130                     id: ast::Ident,
5131                     outer_attrs: &[ast::Attribute],
5132                     id_sp: Span)
5133                     -> (ast::Item_, Vec<ast::Attribute> ) {
5134         let mut prefix = Path::new(self.sess.span_diagnostic.cm.span_to_filename(self.span));
5135         prefix.pop();
5136         let mod_path = Path::new(".").join_many(self.mod_path_stack[]);
5137         let dir_path = prefix.join(&mod_path);
5138         let mod_string = token::get_ident(id);
5139         let (file_path, owns_directory) = match ::attr::first_attr_value_str_by_name(
5140                 outer_attrs, "path") {
5141             Some(d) => (dir_path.join(d), true),
5142             None => {
5143                 let mod_name = mod_string.get().to_string();
5144                 let default_path_str = format!("{}.rs", mod_name);
5145                 let secondary_path_str = format!("{}/mod.rs", mod_name);
5146                 let default_path = dir_path.join(default_path_str[]);
5147                 let secondary_path = dir_path.join(secondary_path_str[]);
5148                 let default_exists = default_path.exists();
5149                 let secondary_exists = secondary_path.exists();
5150
5151                 if !self.owns_directory {
5152                     self.span_err(id_sp,
5153                                   "cannot declare a new module at this location");
5154                     let this_module = match self.mod_path_stack.last() {
5155                         Some(name) => name.get().to_string(),
5156                         None => self.root_module_name.as_ref().unwrap().clone(),
5157                     };
5158                     self.span_note(id_sp,
5159                                    format!("maybe move this module `{0}` \
5160                                             to its own directory via \
5161                                             `{0}/mod.rs`",
5162                                            this_module)[]);
5163                     if default_exists || secondary_exists {
5164                         self.span_note(id_sp,
5165                                        format!("... or maybe `use` the module \
5166                                                 `{}` instead of possibly \
5167                                                 redeclaring it",
5168                                                mod_name)[]);
5169                     }
5170                     self.abort_if_errors();
5171                 }
5172
5173                 match (default_exists, secondary_exists) {
5174                     (true, false) => (default_path, false),
5175                     (false, true) => (secondary_path, true),
5176                     (false, false) => {
5177                         self.span_fatal_help(id_sp,
5178                                              format!("file not found for module `{}`",
5179                                                      mod_name)[],
5180                                              format!("name the file either {} or {} inside \
5181                                                      the directory {}",
5182                                                      default_path_str,
5183                                                      secondary_path_str,
5184                                                      dir_path.display())[]);
5185                     }
5186                     (true, true) => {
5187                         self.span_fatal_help(
5188                             id_sp,
5189                             format!("file for module `{}` found at both {} \
5190                                      and {}",
5191                                     mod_name,
5192                                     default_path_str,
5193                                     secondary_path_str)[],
5194                             "delete or rename one of them to remove the ambiguity");
5195                     }
5196                 }
5197             }
5198         };
5199
5200         self.eval_src_mod_from_path(file_path, owns_directory,
5201                                     mod_string.get().to_string(), id_sp)
5202     }
5203
5204     fn eval_src_mod_from_path(&mut self,
5205                               path: Path,
5206                               owns_directory: bool,
5207                               name: String,
5208                               id_sp: Span) -> (ast::Item_, Vec<ast::Attribute> ) {
5209         let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
5210         match included_mod_stack.iter().position(|p| *p == path) {
5211             Some(i) => {
5212                 let mut err = String::from_str("circular modules: ");
5213                 let len = included_mod_stack.len();
5214                 for p in included_mod_stack.slice(i, len).iter() {
5215                     err.push_str(p.display().as_cow()[]);
5216                     err.push_str(" -> ");
5217                 }
5218                 err.push_str(path.display().as_cow()[]);
5219                 self.span_fatal(id_sp, err[]);
5220             }
5221             None => ()
5222         }
5223         included_mod_stack.push(path.clone());
5224         drop(included_mod_stack);
5225
5226         let mut p0 =
5227             new_sub_parser_from_file(self.sess,
5228                                      self.cfg.clone(),
5229                                      &path,
5230                                      owns_directory,
5231                                      Some(name),
5232                                      id_sp);
5233         let mod_inner_lo = p0.span.lo;
5234         let (mod_attrs, next) = p0.parse_inner_attrs_and_next();
5235         let first_item_outer_attrs = next;
5236         let m0 = p0.parse_mod_items(token::Eof, first_item_outer_attrs, mod_inner_lo);
5237         self.sess.included_mod_stack.borrow_mut().pop();
5238         return (ast::ItemMod(m0), mod_attrs);
5239     }
5240
5241     /// Parse a function declaration from a foreign module
5242     fn parse_item_foreign_fn(&mut self, vis: ast::Visibility,
5243                              attrs: Vec<Attribute>) -> P<ForeignItem> {
5244         let lo = self.span.lo;
5245         self.expect_keyword(keywords::Fn);
5246
5247         let (ident, mut generics) = self.parse_fn_header();
5248         let decl = self.parse_fn_decl(true);
5249         self.parse_where_clause(&mut generics);
5250         let hi = self.span.hi;
5251         self.expect(&token::Semi);
5252         P(ast::ForeignItem {
5253             ident: ident,
5254             attrs: attrs,
5255             node: ForeignItemFn(decl, generics),
5256             id: ast::DUMMY_NODE_ID,
5257             span: mk_sp(lo, hi),
5258             vis: vis
5259         })
5260     }
5261
5262     /// Parse a static item from a foreign module
5263     fn parse_item_foreign_static(&mut self, vis: ast::Visibility,
5264                                  attrs: Vec<Attribute>) -> P<ForeignItem> {
5265         let lo = self.span.lo;
5266
5267         self.expect_keyword(keywords::Static);
5268         let mutbl = self.eat_keyword(keywords::Mut);
5269
5270         let ident = self.parse_ident();
5271         self.expect(&token::Colon);
5272         let ty = self.parse_ty_sum();
5273         let hi = self.span.hi;
5274         self.expect(&token::Semi);
5275         P(ForeignItem {
5276             ident: ident,
5277             attrs: attrs,
5278             node: ForeignItemStatic(ty, mutbl),
5279             id: ast::DUMMY_NODE_ID,
5280             span: mk_sp(lo, hi),
5281             vis: vis
5282         })
5283     }
5284
5285     /// At this point, this is essentially a wrapper for
5286     /// parse_foreign_items.
5287     fn parse_foreign_mod_items(&mut self,
5288                                abi: abi::Abi,
5289                                first_item_attrs: Vec<Attribute> )
5290                                -> ForeignMod {
5291         let ParsedItemsAndViewItems {
5292             attrs_remaining,
5293             view_items,
5294             items: _,
5295             foreign_items,
5296         } = self.parse_foreign_items(first_item_attrs, true);
5297         if !attrs_remaining.is_empty() {
5298             let last_span = self.last_span;
5299             self.span_err(last_span,
5300                           Parser::expected_item_err(attrs_remaining[]));
5301         }
5302         assert!(self.token == token::CloseDelim(token::Brace));
5303         ast::ForeignMod {
5304             abi: abi,
5305             view_items: view_items,
5306             items: foreign_items
5307         }
5308     }
5309
5310     /// Parse extern crate links
5311     ///
5312     /// # Example
5313     ///
5314     /// extern crate url;
5315     /// extern crate foo = "bar"; //deprecated
5316     /// extern crate "bar" as foo;
5317     fn parse_item_extern_crate(&mut self,
5318                                 lo: BytePos,
5319                                 visibility: Visibility,
5320                                 attrs: Vec<Attribute> )
5321                                 -> ItemOrViewItem {
5322
5323         let span = self.span;
5324         let (maybe_path, ident) = match self.token {
5325             token::Ident(..) => {
5326                 let the_ident = self.parse_ident();
5327                 let path = if self.token == token::Eq {
5328                     self.bump();
5329                     let path = self.parse_str();
5330                     let span = self.span;
5331                     self.obsolete(span, ObsoleteExternCrateRenaming);
5332                     Some(path)
5333                 } else if self.eat_keyword(keywords::As) {
5334                     // skip the ident if there is one
5335                     if self.token.is_ident() { self.bump(); }
5336
5337                     self.span_err(span, "expected `;`, found `as`");
5338                     self.span_help(span,
5339                                    format!("perhaps you meant to enclose the crate name `{}` in \
5340                                            a string?",
5341                                           the_ident.as_str())[]);
5342                     None
5343                 } else {
5344                     None
5345                 };
5346                 self.expect(&token::Semi);
5347                 (path, the_ident)
5348             },
5349             token::Literal(token::Str_(..), suf) | token::Literal(token::StrRaw(..), suf) => {
5350                 let sp = self.span;
5351                 self.expect_no_suffix(sp, "extern crate name", suf);
5352                 // forgo the internal suffix check of `parse_str` to
5353                 // avoid repeats (this unwrap will always succeed due
5354                 // to the restriction of the `match`)
5355                 let (s, style, _) = self.parse_optional_str().unwrap();
5356                 self.expect_keyword(keywords::As);
5357                 let the_ident = self.parse_ident();
5358                 self.expect(&token::Semi);
5359                 (Some((s, style)), the_ident)
5360             },
5361             _ => {
5362                 let span = self.span;
5363                 let token_str = self.this_token_to_string();
5364                 self.span_fatal(span,
5365                                 format!("expected extern crate name but \
5366                                          found `{}`",
5367                                         token_str)[]);
5368             }
5369         };
5370
5371         IoviViewItem(ast::ViewItem {
5372                 node: ViewItemExternCrate(ident, maybe_path, ast::DUMMY_NODE_ID),
5373                 attrs: attrs,
5374                 vis: visibility,
5375                 span: mk_sp(lo, self.last_span.hi)
5376             })
5377     }
5378
5379     /// Parse `extern` for foreign ABIs
5380     /// modules.
5381     ///
5382     /// `extern` is expected to have been
5383     /// consumed before calling this method
5384     ///
5385     /// # Examples:
5386     ///
5387     /// extern "C" {}
5388     /// extern {}
5389     fn parse_item_foreign_mod(&mut self,
5390                               lo: BytePos,
5391                               opt_abi: Option<abi::Abi>,
5392                               visibility: Visibility,
5393                               attrs: Vec<Attribute> )
5394                               -> ItemOrViewItem {
5395
5396         self.expect(&token::OpenDelim(token::Brace));
5397
5398         let abi = opt_abi.unwrap_or(abi::C);
5399
5400         let (inner, next) = self.parse_inner_attrs_and_next();
5401         let m = self.parse_foreign_mod_items(abi, next);
5402         self.expect(&token::CloseDelim(token::Brace));
5403
5404         let last_span = self.last_span;
5405         let item = self.mk_item(lo,
5406                                 last_span.hi,
5407                                 special_idents::invalid,
5408                                 ItemForeignMod(m),
5409                                 visibility,
5410                                 maybe_append(attrs, Some(inner)));
5411         return IoviItem(item);
5412     }
5413
5414     /// Parse type Foo = Bar;
5415     fn parse_item_type(&mut self) -> ItemInfo {
5416         let ident = self.parse_ident();
5417         let mut tps = self.parse_generics();
5418         self.parse_where_clause(&mut tps);
5419         self.expect(&token::Eq);
5420         let ty = self.parse_ty_sum();
5421         self.expect(&token::Semi);
5422         (ident, ItemTy(ty, tps), None)
5423     }
5424
5425     /// Parse a structure-like enum variant definition
5426     /// this should probably be renamed or refactored...
5427     fn parse_struct_def(&mut self) -> P<StructDef> {
5428         let mut fields: Vec<StructField> = Vec::new();
5429         while self.token != token::CloseDelim(token::Brace) {
5430             fields.push(self.parse_struct_decl_field(false));
5431         }
5432         self.bump();
5433
5434         P(StructDef {
5435             fields: fields,
5436             ctor_id: None,
5437         })
5438     }
5439
5440     /// Parse the part of an "enum" decl following the '{'
5441     fn parse_enum_def(&mut self, _generics: &ast::Generics) -> EnumDef {
5442         let mut variants = Vec::new();
5443         let mut all_nullary = true;
5444         let mut any_disr = None;
5445         while self.token != token::CloseDelim(token::Brace) {
5446             let variant_attrs = self.parse_outer_attributes();
5447             let vlo = self.span.lo;
5448
5449             let vis = self.parse_visibility();
5450
5451             let ident;
5452             let kind;
5453             let mut args = Vec::new();
5454             let mut disr_expr = None;
5455             ident = self.parse_ident();
5456             if self.eat(&token::OpenDelim(token::Brace)) {
5457                 // Parse a struct variant.
5458                 all_nullary = false;
5459                 let start_span = self.span;
5460                 let struct_def = self.parse_struct_def();
5461                 if struct_def.fields.len() == 0 {
5462                     self.span_err(start_span,
5463                         format!("unit-like struct variant should be written \
5464                                  without braces, as `{},`",
5465                                 token::get_ident(ident))[]);
5466                 }
5467                 kind = StructVariantKind(struct_def);
5468             } else if self.check(&token::OpenDelim(token::Paren)) {
5469                 all_nullary = false;
5470                 let arg_tys = self.parse_enum_variant_seq(
5471                     &token::OpenDelim(token::Paren),
5472                     &token::CloseDelim(token::Paren),
5473                     seq_sep_trailing_allowed(token::Comma),
5474                     |p| p.parse_ty_sum()
5475                 );
5476                 for ty in arg_tys.into_iter() {
5477                     args.push(ast::VariantArg {
5478                         ty: ty,
5479                         id: ast::DUMMY_NODE_ID,
5480                     });
5481                 }
5482                 kind = TupleVariantKind(args);
5483             } else if self.eat(&token::Eq) {
5484                 disr_expr = Some(self.parse_expr());
5485                 any_disr = disr_expr.as_ref().map(|expr| expr.span);
5486                 kind = TupleVariantKind(args);
5487             } else {
5488                 kind = TupleVariantKind(Vec::new());
5489             }
5490
5491             let vr = ast::Variant_ {
5492                 name: ident,
5493                 attrs: variant_attrs,
5494                 kind: kind,
5495                 id: ast::DUMMY_NODE_ID,
5496                 disr_expr: disr_expr,
5497                 vis: vis,
5498             };
5499             variants.push(P(spanned(vlo, self.last_span.hi, vr)));
5500
5501             if !self.eat(&token::Comma) { break; }
5502         }
5503         self.expect(&token::CloseDelim(token::Brace));
5504         match any_disr {
5505             Some(disr_span) if !all_nullary =>
5506                 self.span_err(disr_span,
5507                     "discriminator values can only be used with a c-like enum"),
5508             _ => ()
5509         }
5510
5511         ast::EnumDef { variants: variants }
5512     }
5513
5514     /// Parse an "enum" declaration
5515     fn parse_item_enum(&mut self) -> ItemInfo {
5516         let id = self.parse_ident();
5517         let mut generics = self.parse_generics();
5518         self.parse_where_clause(&mut generics);
5519         self.expect(&token::OpenDelim(token::Brace));
5520
5521         let enum_definition = self.parse_enum_def(&generics);
5522         (id, ItemEnum(enum_definition, generics), None)
5523     }
5524
5525     fn fn_expr_lookahead(tok: &token::Token) -> bool {
5526         match *tok {
5527           token::OpenDelim(token::Paren) | token::At | token::Tilde | token::BinOp(_) => true,
5528           _ => false
5529         }
5530     }
5531
5532     /// Parses a string as an ABI spec on an extern type or module. Consumes
5533     /// the `extern` keyword, if one is found.
5534     fn parse_opt_abi(&mut self) -> Option<abi::Abi> {
5535         match self.token {
5536             token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
5537                 let sp = self.span;
5538                 self.expect_no_suffix(sp, "ABI spec", suf);
5539                 self.bump();
5540                 let the_string = s.as_str();
5541                 match abi::lookup(the_string) {
5542                     Some(abi) => Some(abi),
5543                     None => {
5544                         let last_span = self.last_span;
5545                         self.span_err(
5546                             last_span,
5547                             format!("illegal ABI: expected one of [{}], \
5548                                      found `{}`",
5549                                     abi::all_names().connect(", "),
5550                                     the_string)[]);
5551                         None
5552                     }
5553                 }
5554             }
5555
5556             _ => None,
5557         }
5558     }
5559
5560     /// Parse one of the items or view items allowed by the
5561     /// flags; on failure, return IoviNone.
5562     /// NB: this function no longer parses the items inside an
5563     /// extern crate.
5564     fn parse_item_or_view_item(&mut self,
5565                                attrs: Vec<Attribute> ,
5566                                macros_allowed: bool)
5567                                -> ItemOrViewItem {
5568         let nt_item = match self.token {
5569             token::Interpolated(token::NtItem(ref item)) => {
5570                 Some((**item).clone())
5571             }
5572             _ => None
5573         };
5574         match nt_item {
5575             Some(mut item) => {
5576                 self.bump();
5577                 let mut attrs = attrs;
5578                 mem::swap(&mut item.attrs, &mut attrs);
5579                 item.attrs.extend(attrs.into_iter());
5580                 return IoviItem(P(item));
5581             }
5582             None => {}
5583         }
5584
5585         let lo = self.span.lo;
5586
5587         let visibility = self.parse_visibility();
5588
5589         // must be a view item:
5590         if self.eat_keyword(keywords::Use) {
5591             // USE ITEM (IoviViewItem)
5592             let view_item = self.parse_use();
5593             self.expect(&token::Semi);
5594             return IoviViewItem(ast::ViewItem {
5595                 node: view_item,
5596                 attrs: attrs,
5597                 vis: visibility,
5598                 span: mk_sp(lo, self.last_span.hi)
5599             });
5600         }
5601         // either a view item or an item:
5602         if self.eat_keyword(keywords::Extern) {
5603             let next_is_mod = self.eat_keyword(keywords::Mod);
5604
5605             if next_is_mod || self.eat_keyword(keywords::Crate) {
5606                 if next_is_mod {
5607                     let last_span = self.last_span;
5608                     self.span_err(mk_sp(lo, last_span.hi),
5609                                  format!("`extern mod` is obsolete, use \
5610                                           `extern crate` instead \
5611                                           to refer to external \
5612                                           crates.")[])
5613                 }
5614                 return self.parse_item_extern_crate(lo, visibility, attrs);
5615             }
5616
5617             let opt_abi = self.parse_opt_abi();
5618
5619             if self.eat_keyword(keywords::Fn) {
5620                 // EXTERN FUNCTION ITEM
5621                 let abi = opt_abi.unwrap_or(abi::C);
5622                 let (ident, item_, extra_attrs) =
5623                     self.parse_item_fn(Unsafety::Normal, abi);
5624                 let last_span = self.last_span;
5625                 let item = self.mk_item(lo,
5626                                         last_span.hi,
5627                                         ident,
5628                                         item_,
5629                                         visibility,
5630                                         maybe_append(attrs, extra_attrs));
5631                 return IoviItem(item);
5632             } else if self.check(&token::OpenDelim(token::Brace)) {
5633                 return self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs);
5634             }
5635
5636             let span = self.span;
5637             let token_str = self.this_token_to_string();
5638             self.span_fatal(span,
5639                             format!("expected `{}` or `fn`, found `{}`", "{",
5640                                     token_str)[]);
5641         }
5642
5643         if self.eat_keyword(keywords::Virtual) {
5644             let span = self.span;
5645             self.span_err(span, "`virtual` structs have been removed from the language");
5646         }
5647
5648         // the rest are all guaranteed to be items:
5649         if self.token.is_keyword(keywords::Static) {
5650             // STATIC ITEM
5651             self.bump();
5652             let m = if self.eat_keyword(keywords::Mut) {MutMutable} else {MutImmutable};
5653             let (ident, item_, extra_attrs) = self.parse_item_const(Some(m));
5654             let last_span = self.last_span;
5655             let item = self.mk_item(lo,
5656                                     last_span.hi,
5657                                     ident,
5658                                     item_,
5659                                     visibility,
5660                                     maybe_append(attrs, extra_attrs));
5661             return IoviItem(item);
5662         }
5663         if self.token.is_keyword(keywords::Const) {
5664             // CONST ITEM
5665             self.bump();
5666             if self.eat_keyword(keywords::Mut) {
5667                 let last_span = self.last_span;
5668                 self.span_err(last_span, "const globals cannot be mutable");
5669                 self.span_help(last_span, "did you mean to declare a static?");
5670             }
5671             let (ident, item_, extra_attrs) = self.parse_item_const(None);
5672             let last_span = self.last_span;
5673             let item = self.mk_item(lo,
5674                                     last_span.hi,
5675                                     ident,
5676                                     item_,
5677                                     visibility,
5678                                     maybe_append(attrs, extra_attrs));
5679             return IoviItem(item);
5680         }
5681         if self.token.is_keyword(keywords::Unsafe) &&
5682             self.look_ahead(1u, |t| t.is_keyword(keywords::Trait))
5683         {
5684             // UNSAFE TRAIT ITEM
5685             self.expect_keyword(keywords::Unsafe);
5686             self.expect_keyword(keywords::Trait);
5687             let (ident, item_, extra_attrs) =
5688                 self.parse_item_trait(ast::Unsafety::Unsafe);
5689             let last_span = self.last_span;
5690             let item = self.mk_item(lo,
5691                                     last_span.hi,
5692                                     ident,
5693                                     item_,
5694                                     visibility,
5695                                     maybe_append(attrs, extra_attrs));
5696             return IoviItem(item);
5697         }
5698         if self.token.is_keyword(keywords::Unsafe) &&
5699             self.look_ahead(1u, |t| t.is_keyword(keywords::Impl))
5700         {
5701             // IMPL ITEM
5702             self.expect_keyword(keywords::Unsafe);
5703             self.expect_keyword(keywords::Impl);
5704             let (ident, item_, extra_attrs) = self.parse_item_impl(ast::Unsafety::Unsafe);
5705             let last_span = self.last_span;
5706             let item = self.mk_item(lo,
5707                                     last_span.hi,
5708                                     ident,
5709                                     item_,
5710                                     visibility,
5711                                     maybe_append(attrs, extra_attrs));
5712             return IoviItem(item);
5713         }
5714         if self.token.is_keyword(keywords::Fn) &&
5715                 self.look_ahead(1, |f| !Parser::fn_expr_lookahead(f)) {
5716             // FUNCTION ITEM
5717             self.bump();
5718             let (ident, item_, extra_attrs) =
5719                 self.parse_item_fn(Unsafety::Normal, abi::Rust);
5720             let last_span = self.last_span;
5721             let item = self.mk_item(lo,
5722                                     last_span.hi,
5723                                     ident,
5724                                     item_,
5725                                     visibility,
5726                                     maybe_append(attrs, extra_attrs));
5727             return IoviItem(item);
5728         }
5729         if self.token.is_keyword(keywords::Unsafe)
5730             && self.look_ahead(1u, |t| *t != token::OpenDelim(token::Brace)) {
5731             // UNSAFE FUNCTION ITEM
5732             self.bump();
5733             let abi = if self.eat_keyword(keywords::Extern) {
5734                 self.parse_opt_abi().unwrap_or(abi::C)
5735             } else {
5736                 abi::Rust
5737             };
5738             self.expect_keyword(keywords::Fn);
5739             let (ident, item_, extra_attrs) =
5740                 self.parse_item_fn(Unsafety::Unsafe, abi);
5741             let last_span = self.last_span;
5742             let item = self.mk_item(lo,
5743                                     last_span.hi,
5744                                     ident,
5745                                     item_,
5746                                     visibility,
5747                                     maybe_append(attrs, extra_attrs));
5748             return IoviItem(item);
5749         }
5750         if self.eat_keyword(keywords::Mod) {
5751             // MODULE ITEM
5752             let (ident, item_, extra_attrs) =
5753                 self.parse_item_mod(attrs[]);
5754             let last_span = self.last_span;
5755             let item = self.mk_item(lo,
5756                                     last_span.hi,
5757                                     ident,
5758                                     item_,
5759                                     visibility,
5760                                     maybe_append(attrs, extra_attrs));
5761             return IoviItem(item);
5762         }
5763         if self.eat_keyword(keywords::Type) {
5764             // TYPE ITEM
5765             let (ident, item_, extra_attrs) = self.parse_item_type();
5766             let last_span = self.last_span;
5767             let item = self.mk_item(lo,
5768                                     last_span.hi,
5769                                     ident,
5770                                     item_,
5771                                     visibility,
5772                                     maybe_append(attrs, extra_attrs));
5773             return IoviItem(item);
5774         }
5775         if self.eat_keyword(keywords::Enum) {
5776             // ENUM ITEM
5777             let (ident, item_, extra_attrs) = self.parse_item_enum();
5778             let last_span = self.last_span;
5779             let item = self.mk_item(lo,
5780                                     last_span.hi,
5781                                     ident,
5782                                     item_,
5783                                     visibility,
5784                                     maybe_append(attrs, extra_attrs));
5785             return IoviItem(item);
5786         }
5787         if self.eat_keyword(keywords::Trait) {
5788             // TRAIT ITEM
5789             let (ident, item_, extra_attrs) =
5790                 self.parse_item_trait(ast::Unsafety::Normal);
5791             let last_span = self.last_span;
5792             let item = self.mk_item(lo,
5793                                     last_span.hi,
5794                                     ident,
5795                                     item_,
5796                                     visibility,
5797                                     maybe_append(attrs, extra_attrs));
5798             return IoviItem(item);
5799         }
5800         if self.eat_keyword(keywords::Impl) {
5801             // IMPL ITEM
5802             let (ident, item_, extra_attrs) = self.parse_item_impl(ast::Unsafety::Normal);
5803             let last_span = self.last_span;
5804             let item = self.mk_item(lo,
5805                                     last_span.hi,
5806                                     ident,
5807                                     item_,
5808                                     visibility,
5809                                     maybe_append(attrs, extra_attrs));
5810             return IoviItem(item);
5811         }
5812         if self.eat_keyword(keywords::Struct) {
5813             // STRUCT ITEM
5814             let (ident, item_, extra_attrs) = self.parse_item_struct();
5815             let last_span = self.last_span;
5816             let item = self.mk_item(lo,
5817                                     last_span.hi,
5818                                     ident,
5819                                     item_,
5820                                     visibility,
5821                                     maybe_append(attrs, extra_attrs));
5822             return IoviItem(item);
5823         }
5824         self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility)
5825     }
5826
5827     /// Parse a foreign item; on failure, return IoviNone.
5828     fn parse_foreign_item(&mut self,
5829                           attrs: Vec<Attribute> ,
5830                           macros_allowed: bool)
5831                           -> ItemOrViewItem {
5832         maybe_whole!(iovi self, NtItem);
5833         let lo = self.span.lo;
5834
5835         let visibility = self.parse_visibility();
5836
5837         if self.token.is_keyword(keywords::Static) {
5838             // FOREIGN STATIC ITEM
5839             let item = self.parse_item_foreign_static(visibility, attrs);
5840             return IoviForeignItem(item);
5841         }
5842         if self.token.is_keyword(keywords::Fn) || self.token.is_keyword(keywords::Unsafe) {
5843             // FOREIGN FUNCTION ITEM
5844             let item = self.parse_item_foreign_fn(visibility, attrs);
5845             return IoviForeignItem(item);
5846         }
5847         self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility)
5848     }
5849
5850     /// This is the fall-through for parsing items.
5851     fn parse_macro_use_or_failure(
5852         &mut self,
5853         attrs: Vec<Attribute> ,
5854         macros_allowed: bool,
5855         lo: BytePos,
5856         visibility: Visibility
5857     ) -> ItemOrViewItem {
5858         if macros_allowed && !self.token.is_any_keyword()
5859                 && self.look_ahead(1, |t| *t == token::Not)
5860                 && (self.look_ahead(2, |t| t.is_plain_ident())
5861                     || self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren))
5862                     || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) {
5863             // MACRO INVOCATION ITEM
5864
5865             // item macro.
5866             let pth = self.parse_path(NoTypesAllowed);
5867             self.expect(&token::Not);
5868
5869             // a 'special' identifier (like what `macro_rules!` uses)
5870             // is optional. We should eventually unify invoc syntax
5871             // and remove this.
5872             let id = if self.token.is_plain_ident() {
5873                 self.parse_ident()
5874             } else {
5875                 token::special_idents::invalid // no special identifier
5876             };
5877             // eat a matched-delimiter token tree:
5878             let delim = self.expect_open_delim();
5879             let tts = self.parse_seq_to_end(&token::CloseDelim(delim),
5880                                             seq_sep_none(),
5881                                             |p| p.parse_token_tree());
5882             // single-variant-enum... :
5883             let m = ast::MacInvocTT(pth, tts, EMPTY_CTXT);
5884             let m: ast::Mac = codemap::Spanned { node: m,
5885                                              span: mk_sp(self.span.lo,
5886                                                          self.span.hi) };
5887
5888             if delim != token::Brace {
5889                 if !self.eat(&token::Semi) {
5890                     let last_span = self.last_span;
5891                     self.span_err(last_span,
5892                                   "macros that expand to items must either \
5893                                    be surrounded with braces or followed by \
5894                                    a semicolon");
5895                 }
5896             }
5897
5898             let item_ = ItemMac(m);
5899             let last_span = self.last_span;
5900             let item = self.mk_item(lo,
5901                                     last_span.hi,
5902                                     id,
5903                                     item_,
5904                                     visibility,
5905                                     attrs);
5906             return IoviItem(item);
5907         }
5908
5909         // FAILURE TO PARSE ITEM
5910         match visibility {
5911             Inherited => {}
5912             Public => {
5913                 let last_span = self.last_span;
5914                 self.span_fatal(last_span, "unmatched visibility `pub`");
5915             }
5916         }
5917         return IoviNone(attrs);
5918     }
5919
5920     pub fn parse_item_with_outer_attributes(&mut self) -> Option<P<Item>> {
5921         let attrs = self.parse_outer_attributes();
5922         self.parse_item(attrs)
5923     }
5924
5925     pub fn parse_item(&mut self, attrs: Vec<Attribute>) -> Option<P<Item>> {
5926         match self.parse_item_or_view_item(attrs, true) {
5927             IoviNone(_) => None,
5928             IoviViewItem(_) =>
5929                 self.fatal("view items are not allowed here"),
5930             IoviForeignItem(_) =>
5931                 self.fatal("foreign items are not allowed here"),
5932             IoviItem(item) => Some(item)
5933         }
5934     }
5935
5936     /// Parse a ViewItem, e.g. `use foo::bar` or `extern crate foo`
5937     pub fn parse_view_item(&mut self, attrs: Vec<Attribute>) -> ViewItem {
5938         match self.parse_item_or_view_item(attrs, false) {
5939             IoviViewItem(vi) => vi,
5940             _ => self.fatal("expected `use` or `extern crate`"),
5941         }
5942     }
5943
5944     /// Parse, e.g., "use a::b::{z,y}"
5945     fn parse_use(&mut self) -> ViewItem_ {
5946         return ViewItemUse(self.parse_view_path());
5947     }
5948
5949
5950     /// Matches view_path : MOD? non_global_path as IDENT
5951     /// | MOD? non_global_path MOD_SEP LBRACE RBRACE
5952     /// | MOD? non_global_path MOD_SEP LBRACE ident_seq RBRACE
5953     /// | MOD? non_global_path MOD_SEP STAR
5954     /// | MOD? non_global_path
5955     fn parse_view_path(&mut self) -> P<ViewPath> {
5956         let lo = self.span.lo;
5957
5958         if self.check(&token::OpenDelim(token::Brace)) {
5959             // use {foo,bar}
5960             let idents = self.parse_unspanned_seq(
5961                 &token::OpenDelim(token::Brace),
5962                 &token::CloseDelim(token::Brace),
5963                 seq_sep_trailing_allowed(token::Comma),
5964                 |p| p.parse_path_list_item());
5965             let path = ast::Path {
5966                 span: mk_sp(lo, self.span.hi),
5967                 global: false,
5968                 segments: Vec::new()
5969             };
5970             return P(spanned(lo, self.span.hi,
5971                              ViewPathList(path, idents, ast::DUMMY_NODE_ID)));
5972         }
5973
5974         let first_ident = self.parse_ident();
5975         let mut path = vec!(first_ident);
5976         match self.token {
5977           token::Eq => {
5978             // x = foo::bar
5979             self.bump();
5980             let path_lo = self.span.lo;
5981             path = vec!(self.parse_ident());
5982             while self.check(&token::ModSep) {
5983                 self.bump();
5984                 let id = self.parse_ident();
5985                 path.push(id);
5986             }
5987             let span = mk_sp(path_lo, self.span.hi);
5988             self.obsolete(span, ObsoleteImportRenaming);
5989             let path = ast::Path {
5990                 span: span,
5991                 global: false,
5992                 segments: path.into_iter().map(|identifier| {
5993                     ast::PathSegment {
5994                         identifier: identifier,
5995                         parameters: ast::PathParameters::none(),
5996                     }
5997                 }).collect()
5998             };
5999             return P(spanned(lo, self.span.hi,
6000                              ViewPathSimple(first_ident, path,
6001                                            ast::DUMMY_NODE_ID)));
6002           }
6003
6004           token::ModSep => {
6005             // foo::bar or foo::{a,b,c} or foo::*
6006             while self.check(&token::ModSep) {
6007                 self.bump();
6008
6009                 match self.token {
6010                   token::Ident(i, _) => {
6011                     self.bump();
6012                     path.push(i);
6013                   }
6014
6015                   // foo::bar::{a,b,c}
6016                   token::OpenDelim(token::Brace) => {
6017                     let idents = self.parse_unspanned_seq(
6018                         &token::OpenDelim(token::Brace),
6019                         &token::CloseDelim(token::Brace),
6020                         seq_sep_trailing_allowed(token::Comma),
6021                         |p| p.parse_path_list_item()
6022                     );
6023                     let path = ast::Path {
6024                         span: mk_sp(lo, self.span.hi),
6025                         global: false,
6026                         segments: path.into_iter().map(|identifier| {
6027                             ast::PathSegment {
6028                                 identifier: identifier,
6029                                 parameters: ast::PathParameters::none(),
6030                             }
6031                         }).collect()
6032                     };
6033                     return P(spanned(lo, self.span.hi,
6034                                      ViewPathList(path, idents, ast::DUMMY_NODE_ID)));
6035                   }
6036
6037                   // foo::bar::*
6038                   token::BinOp(token::Star) => {
6039                     self.bump();
6040                     let path = ast::Path {
6041                         span: mk_sp(lo, self.span.hi),
6042                         global: false,
6043                         segments: path.into_iter().map(|identifier| {
6044                             ast::PathSegment {
6045                                 identifier: identifier,
6046                                 parameters: ast::PathParameters::none(),
6047                             }
6048                         }).collect()
6049                     };
6050                     return P(spanned(lo, self.span.hi,
6051                                      ViewPathGlob(path, ast::DUMMY_NODE_ID)));
6052                   }
6053
6054                   _ => break
6055                 }
6056             }
6057           }
6058           _ => ()
6059         }
6060         let mut rename_to = path[path.len() - 1u];
6061         let path = ast::Path {
6062             span: mk_sp(lo, self.last_span.hi),
6063             global: false,
6064             segments: path.into_iter().map(|identifier| {
6065                 ast::PathSegment {
6066                     identifier: identifier,
6067                     parameters: ast::PathParameters::none(),
6068                 }
6069             }).collect()
6070         };
6071         if self.eat_keyword(keywords::As) {
6072             rename_to = self.parse_ident()
6073         }
6074         P(spanned(lo,
6075                   self.last_span.hi,
6076                   ViewPathSimple(rename_to, path, ast::DUMMY_NODE_ID)))
6077     }
6078
6079     /// Parses a sequence of items. Stops when it finds program
6080     /// text that can't be parsed as an item
6081     /// - mod_items uses extern_mod_allowed = true
6082     /// - block_tail_ uses extern_mod_allowed = false
6083     fn parse_items_and_view_items(&mut self,
6084                                   first_item_attrs: Vec<Attribute> ,
6085                                   mut extern_mod_allowed: bool,
6086                                   macros_allowed: bool)
6087                                   -> ParsedItemsAndViewItems {
6088         let mut attrs = first_item_attrs;
6089         attrs.push_all(self.parse_outer_attributes()[]);
6090         // First, parse view items.
6091         let mut view_items : Vec<ast::ViewItem> = Vec::new();
6092         let mut items = Vec::new();
6093
6094         // I think this code would probably read better as a single
6095         // loop with a mutable three-state-variable (for extern crates,
6096         // view items, and regular items) ... except that because
6097         // of macros, I'd like to delay that entire check until later.
6098         loop {
6099             match self.parse_item_or_view_item(attrs, macros_allowed) {
6100                 IoviNone(attrs) => {
6101                     return ParsedItemsAndViewItems {
6102                         attrs_remaining: attrs,
6103                         view_items: view_items,
6104                         items: items,
6105                         foreign_items: Vec::new()
6106                     }
6107                 }
6108                 IoviViewItem(view_item) => {
6109                     match view_item.node {
6110                         ViewItemUse(..) => {
6111                             // `extern crate` must precede `use`.
6112                             extern_mod_allowed = false;
6113                         }
6114                         ViewItemExternCrate(..) if !extern_mod_allowed => {
6115                             self.span_err(view_item.span,
6116                                           "\"extern crate\" declarations are \
6117                                            not allowed here");
6118                         }
6119                         ViewItemExternCrate(..) => {}
6120                     }
6121                     view_items.push(view_item);
6122                 }
6123                 IoviItem(item) => {
6124                     items.push(item);
6125                     attrs = self.parse_outer_attributes();
6126                     break;
6127                 }
6128                 IoviForeignItem(_) => {
6129                     panic!();
6130                 }
6131             }
6132             attrs = self.parse_outer_attributes();
6133         }
6134
6135         // Next, parse items.
6136         loop {
6137             match self.parse_item_or_view_item(attrs, macros_allowed) {
6138                 IoviNone(returned_attrs) => {
6139                     attrs = returned_attrs;
6140                     break
6141                 }
6142                 IoviViewItem(view_item) => {
6143                     attrs = self.parse_outer_attributes();
6144                     self.span_err(view_item.span,
6145                                   "`use` and `extern crate` declarations must precede items");
6146                 }
6147                 IoviItem(item) => {
6148                     attrs = self.parse_outer_attributes();
6149                     items.push(item)
6150                 }
6151                 IoviForeignItem(_) => {
6152                     panic!();
6153                 }
6154             }
6155         }
6156
6157         ParsedItemsAndViewItems {
6158             attrs_remaining: attrs,
6159             view_items: view_items,
6160             items: items,
6161             foreign_items: Vec::new()
6162         }
6163     }
6164
6165     /// Parses a sequence of foreign items. Stops when it finds program
6166     /// text that can't be parsed as an item
6167     fn parse_foreign_items(&mut self, first_item_attrs: Vec<Attribute> ,
6168                            macros_allowed: bool)
6169         -> ParsedItemsAndViewItems {
6170         let mut attrs = first_item_attrs;
6171         attrs.push_all(self.parse_outer_attributes()[]);
6172         let mut foreign_items = Vec::new();
6173         loop {
6174             match self.parse_foreign_item(attrs, macros_allowed) {
6175                 IoviNone(returned_attrs) => {
6176                     if self.check(&token::CloseDelim(token::Brace)) {
6177                         attrs = returned_attrs;
6178                         break
6179                     }
6180                     self.unexpected();
6181                 },
6182                 IoviViewItem(view_item) => {
6183                     // I think this can't occur:
6184                     self.span_err(view_item.span,
6185                                   "`use` and `extern crate` declarations must precede items");
6186                 }
6187                 IoviItem(item) => {
6188                     // FIXME #5668: this will occur for a macro invocation:
6189                     self.span_fatal(item.span, "macros cannot expand to foreign items");
6190                 }
6191                 IoviForeignItem(foreign_item) => {
6192                     foreign_items.push(foreign_item);
6193                 }
6194             }
6195             attrs = self.parse_outer_attributes();
6196         }
6197
6198         ParsedItemsAndViewItems {
6199             attrs_remaining: attrs,
6200             view_items: Vec::new(),
6201             items: Vec::new(),
6202             foreign_items: foreign_items
6203         }
6204     }
6205
6206     /// Parses a source module as a crate. This is the main
6207     /// entry point for the parser.
6208     pub fn parse_crate_mod(&mut self) -> Crate {
6209         let lo = self.span.lo;
6210         // parse the crate's inner attrs, maybe (oops) one
6211         // of the attrs of an item:
6212         let (inner, next) = self.parse_inner_attrs_and_next();
6213         let first_item_outer_attrs = next;
6214         // parse the items inside the crate:
6215         let m = self.parse_mod_items(token::Eof, first_item_outer_attrs, lo);
6216
6217         ast::Crate {
6218             module: m,
6219             attrs: inner,
6220             config: self.cfg.clone(),
6221             span: mk_sp(lo, self.span.lo),
6222             exported_macros: Vec::new(),
6223         }
6224     }
6225
6226     pub fn parse_optional_str(&mut self)
6227                               -> Option<(InternedString, ast::StrStyle, Option<ast::Name>)> {
6228         let ret = match self.token {
6229             token::Literal(token::Str_(s), suf) => {
6230                 (self.id_to_interned_str(s.ident()), ast::CookedStr, suf)
6231             }
6232             token::Literal(token::StrRaw(s, n), suf) => {
6233                 (self.id_to_interned_str(s.ident()), ast::RawStr(n), suf)
6234             }
6235             _ => return None
6236         };
6237         self.bump();
6238         Some(ret)
6239     }
6240
6241     pub fn parse_str(&mut self) -> (InternedString, StrStyle) {
6242         match self.parse_optional_str() {
6243             Some((s, style, suf)) => {
6244                 let sp = self.last_span;
6245                 self.expect_no_suffix(sp, "str literal", suf);
6246                 (s, style)
6247             }
6248             _ =>  self.fatal("expected string literal")
6249         }
6250     }
6251 }