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