]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/parse/parser.rs
mk: The beta channel produces things called 'beta'
[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};
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_name: item_name,
1577             }))
1578         } else if self.check(&token::ModSep) ||
1579                   self.token.is_ident() ||
1580                   self.token.is_path() {
1581             // NAMED TYPE
1582             self.parse_ty_path()
1583         } else if self.eat(&token::Underscore) {
1584             // TYPE TO BE INFERRED
1585             TyInfer
1586         } else {
1587             let this_token_str = self.this_token_to_string();
1588             let msg = format!("expected type, found `{}`", this_token_str);
1589             self.fatal(&msg[]);
1590         };
1591
1592         let sp = mk_sp(lo, self.last_span.hi);
1593         P(Ty {id: ast::DUMMY_NODE_ID, node: t, span: sp})
1594     }
1595
1596     pub fn parse_borrowed_pointee(&mut self) -> Ty_ {
1597         // look for `&'lt` or `&'foo ` and interpret `foo` as the region name:
1598         let opt_lifetime = self.parse_opt_lifetime();
1599
1600         let mt = self.parse_mt();
1601         return TyRptr(opt_lifetime, mt);
1602     }
1603
1604     pub fn parse_ptr(&mut self) -> MutTy {
1605         let mutbl = if self.eat_keyword(keywords::Mut) {
1606             MutMutable
1607         } else if self.eat_keyword(keywords::Const) {
1608             MutImmutable
1609         } else {
1610             let span = self.last_span;
1611             self.span_err(span,
1612                           "bare raw pointers are no longer allowed, you should \
1613                            likely use `*mut T`, but otherwise `*T` is now \
1614                            known as `*const T`");
1615             MutImmutable
1616         };
1617         let t = self.parse_ty();
1618         MutTy { ty: t, mutbl: mutbl }
1619     }
1620
1621     pub fn is_named_argument(&mut self) -> bool {
1622         let offset = match self.token {
1623             token::BinOp(token::And) => 1,
1624             token::AndAnd => 1,
1625             _ if self.token.is_keyword(keywords::Mut) => 1,
1626             _ => 0
1627         };
1628
1629         debug!("parser is_named_argument offset:{}", offset);
1630
1631         if offset == 0 {
1632             is_plain_ident_or_underscore(&self.token)
1633                 && self.look_ahead(1, |t| *t == token::Colon)
1634         } else {
1635             self.look_ahead(offset, |t| is_plain_ident_or_underscore(t))
1636                 && self.look_ahead(offset + 1, |t| *t == token::Colon)
1637         }
1638     }
1639
1640     /// This version of parse arg doesn't necessarily require
1641     /// identifier names.
1642     pub fn parse_arg_general(&mut self, require_name: bool) -> Arg {
1643         let pat = if require_name || self.is_named_argument() {
1644             debug!("parse_arg_general parse_pat (require_name:{})",
1645                    require_name);
1646             let pat = self.parse_pat();
1647
1648             self.expect(&token::Colon);
1649             pat
1650         } else {
1651             debug!("parse_arg_general ident_to_pat");
1652             ast_util::ident_to_pat(ast::DUMMY_NODE_ID,
1653                                    self.last_span,
1654                                    special_idents::invalid)
1655         };
1656
1657         let t = self.parse_ty_sum();
1658
1659         Arg {
1660             ty: t,
1661             pat: pat,
1662             id: ast::DUMMY_NODE_ID,
1663         }
1664     }
1665
1666     /// Parse a single function argument
1667     pub fn parse_arg(&mut self) -> Arg {
1668         self.parse_arg_general(true)
1669     }
1670
1671     /// Parse an argument in a lambda header e.g. |arg, arg|
1672     pub fn parse_fn_block_arg(&mut self) -> Arg {
1673         let pat = self.parse_pat();
1674         let t = if self.eat(&token::Colon) {
1675             self.parse_ty_sum()
1676         } else {
1677             P(Ty {
1678                 id: ast::DUMMY_NODE_ID,
1679                 node: TyInfer,
1680                 span: mk_sp(self.span.lo, self.span.hi),
1681             })
1682         };
1683         Arg {
1684             ty: t,
1685             pat: pat,
1686             id: ast::DUMMY_NODE_ID
1687         }
1688     }
1689
1690     pub fn maybe_parse_fixed_length_of_vec(&mut self) -> Option<P<ast::Expr>> {
1691         if self.check(&token::Semi) {
1692             self.bump();
1693             Some(self.parse_expr())
1694         } else {
1695             None
1696         }
1697     }
1698
1699     /// Matches token_lit = LIT_INTEGER | ...
1700     pub fn lit_from_token(&mut self, tok: &token::Token) -> Lit_ {
1701         match *tok {
1702             token::Interpolated(token::NtExpr(ref v)) => {
1703                 match v.node {
1704                     ExprLit(ref lit) => { lit.node.clone() }
1705                     _ => { self.unexpected_last(tok); }
1706                 }
1707             }
1708             token::Literal(lit, suf) => {
1709                 let (suffix_illegal, out) = match lit {
1710                     token::Byte(i) => (true, LitByte(parse::byte_lit(i.as_str()).0)),
1711                     token::Char(i) => (true, LitChar(parse::char_lit(i.as_str()).0)),
1712
1713                     // there are some valid suffixes for integer and
1714                     // float literals, so all the handling is done
1715                     // internally.
1716                     token::Integer(s) => {
1717                         (false, parse::integer_lit(s.as_str(),
1718                                                    suf.as_ref().map(|s| s.as_str()),
1719                                                    &self.sess.span_diagnostic,
1720                                                    self.last_span))
1721                     }
1722                     token::Float(s) => {
1723                         (false, parse::float_lit(s.as_str(),
1724                                                  suf.as_ref().map(|s| s.as_str()),
1725                                                   &self.sess.span_diagnostic,
1726                                                  self.last_span))
1727                     }
1728
1729                     token::Str_(s) => {
1730                         (true,
1731                          LitStr(token::intern_and_get_ident(parse::str_lit(s.as_str()).as_slice()),
1732                                 ast::CookedStr))
1733                     }
1734                     token::StrRaw(s, n) => {
1735                         (true,
1736                          LitStr(
1737                             token::intern_and_get_ident(&parse::raw_str_lit(s.as_str())[]),
1738                             ast::RawStr(n)))
1739                     }
1740                     token::Binary(i) =>
1741                         (true, LitBinary(parse::binary_lit(i.as_str()))),
1742                     token::BinaryRaw(i, _) =>
1743                         (true,
1744                          LitBinary(Rc::new(i.as_str().as_bytes().iter().map(|&x| x).collect()))),
1745                 };
1746
1747                 if suffix_illegal {
1748                     let sp = self.last_span;
1749                     self.expect_no_suffix(sp, &*format!("{} literal", lit.short_name()), suf)
1750                 }
1751
1752                 out
1753             }
1754             _ => { self.unexpected_last(tok); }
1755         }
1756     }
1757
1758     /// Matches lit = true | false | token_lit
1759     pub fn parse_lit(&mut self) -> Lit {
1760         let lo = self.span.lo;
1761         let lit = if self.eat_keyword(keywords::True) {
1762             LitBool(true)
1763         } else if self.eat_keyword(keywords::False) {
1764             LitBool(false)
1765         } else {
1766             let token = self.bump_and_get();
1767             let lit = self.lit_from_token(&token);
1768             lit
1769         };
1770         codemap::Spanned { node: lit, span: mk_sp(lo, self.last_span.hi) }
1771     }
1772
1773     /// matches '-' lit | lit
1774     pub fn parse_literal_maybe_minus(&mut self) -> P<Expr> {
1775         let minus_lo = self.span.lo;
1776         let minus_present = self.eat(&token::BinOp(token::Minus));
1777
1778         let lo = self.span.lo;
1779         let literal = P(self.parse_lit());
1780         let hi = self.span.hi;
1781         let expr = self.mk_expr(lo, hi, ExprLit(literal));
1782
1783         if minus_present {
1784             let minus_hi = self.span.hi;
1785             let unary = self.mk_unary(UnNeg, expr);
1786             self.mk_expr(minus_lo, minus_hi, unary)
1787         } else {
1788             expr
1789         }
1790     }
1791
1792     /// Parses a path and optional type parameter bounds, depending on the
1793     /// mode. The `mode` parameter determines whether lifetimes, types, and/or
1794     /// bounds are permitted and whether `::` must precede type parameter
1795     /// groups.
1796     pub fn parse_path(&mut self, mode: PathParsingMode) -> ast::Path {
1797         // Check for a whole path...
1798         let found = match self.token {
1799             token::Interpolated(token::NtPath(_)) => Some(self.bump_and_get()),
1800             _ => None,
1801         };
1802         if let Some(token::Interpolated(token::NtPath(box path))) = found {
1803             return path;
1804         }
1805
1806         let lo = self.span.lo;
1807         let is_global = self.eat(&token::ModSep);
1808
1809         // Parse any number of segments and bound sets. A segment is an
1810         // identifier followed by an optional lifetime and a set of types.
1811         // A bound set is a set of type parameter bounds.
1812         let segments = match mode {
1813             LifetimeAndTypesWithoutColons => {
1814                 self.parse_path_segments_without_colons()
1815             }
1816             LifetimeAndTypesWithColons => {
1817                 self.parse_path_segments_with_colons()
1818             }
1819             NoTypesAllowed => {
1820                 self.parse_path_segments_without_types()
1821             }
1822         };
1823
1824         // Assemble the span.
1825         let span = mk_sp(lo, self.last_span.hi);
1826
1827         // Assemble the result.
1828         ast::Path {
1829             span: span,
1830             global: is_global,
1831             segments: segments,
1832         }
1833     }
1834
1835     /// Examples:
1836     /// - `a::b<T,U>::c<V,W>`
1837     /// - `a::b<T,U>::c(V) -> W`
1838     /// - `a::b<T,U>::c(V)`
1839     pub fn parse_path_segments_without_colons(&mut self) -> Vec<ast::PathSegment> {
1840         let mut segments = Vec::new();
1841         loop {
1842             // First, parse an identifier.
1843             let identifier = self.parse_ident();
1844
1845             // Parse types, optionally.
1846             let parameters = if self.eat_lt() {
1847                 let (lifetimes, types, bindings) = self.parse_generic_values_after_lt();
1848
1849                 ast::AngleBracketedParameters(ast::AngleBracketedParameterData {
1850                     lifetimes: lifetimes,
1851                     types: OwnedSlice::from_vec(types),
1852                     bindings: OwnedSlice::from_vec(bindings),
1853                 })
1854             } else if self.eat(&token::OpenDelim(token::Paren)) {
1855                 let inputs = self.parse_seq_to_end(
1856                     &token::CloseDelim(token::Paren),
1857                     seq_sep_trailing_allowed(token::Comma),
1858                     |p| p.parse_ty_sum());
1859
1860                 let output_ty = if self.eat(&token::RArrow) {
1861                     Some(self.parse_ty())
1862                 } else {
1863                     None
1864                 };
1865
1866                 ast::ParenthesizedParameters(ast::ParenthesizedParameterData {
1867                     inputs: inputs,
1868                     output: output_ty
1869                 })
1870             } else {
1871                 ast::PathParameters::none()
1872             };
1873
1874             // Assemble and push the result.
1875             segments.push(ast::PathSegment { identifier: identifier,
1876                                              parameters: parameters });
1877
1878             // Continue only if we see a `::`
1879             if !self.eat(&token::ModSep) {
1880                 return segments;
1881             }
1882         }
1883     }
1884
1885     /// Examples:
1886     /// - `a::b::<T,U>::c`
1887     pub fn parse_path_segments_with_colons(&mut self) -> Vec<ast::PathSegment> {
1888         let mut segments = Vec::new();
1889         loop {
1890             // First, parse an identifier.
1891             let identifier = self.parse_ident();
1892
1893             // If we do not see a `::`, stop.
1894             if !self.eat(&token::ModSep) {
1895                 segments.push(ast::PathSegment {
1896                     identifier: identifier,
1897                     parameters: ast::AngleBracketedParameters(ast::AngleBracketedParameterData {
1898                         lifetimes: Vec::new(),
1899                         types: OwnedSlice::empty(),
1900                         bindings: OwnedSlice::empty(),
1901                     })
1902                 });
1903                 return segments;
1904             }
1905
1906             // Check for a type segment.
1907             if self.eat_lt() {
1908                 // Consumed `a::b::<`, go look for types
1909                 let (lifetimes, types, bindings) = self.parse_generic_values_after_lt();
1910                 segments.push(ast::PathSegment {
1911                     identifier: identifier,
1912                     parameters: ast::AngleBracketedParameters(ast::AngleBracketedParameterData {
1913                         lifetimes: lifetimes,
1914                         types: OwnedSlice::from_vec(types),
1915                         bindings: OwnedSlice::from_vec(bindings),
1916                     }),
1917                 });
1918
1919                 // Consumed `a::b::<T,U>`, check for `::` before proceeding
1920                 if !self.eat(&token::ModSep) {
1921                     return segments;
1922                 }
1923             } else {
1924                 // Consumed `a::`, go look for `b`
1925                 segments.push(ast::PathSegment {
1926                     identifier: identifier,
1927                     parameters: ast::PathParameters::none(),
1928                 });
1929             }
1930         }
1931     }
1932
1933
1934     /// Examples:
1935     /// - `a::b::c`
1936     pub fn parse_path_segments_without_types(&mut self) -> Vec<ast::PathSegment> {
1937         let mut segments = Vec::new();
1938         loop {
1939             // First, parse an identifier.
1940             let identifier = self.parse_ident();
1941
1942             // Assemble and push the result.
1943             segments.push(ast::PathSegment {
1944                 identifier: identifier,
1945                 parameters: ast::PathParameters::none()
1946             });
1947
1948             // If we do not see a `::`, stop.
1949             if !self.eat(&token::ModSep) {
1950                 return segments;
1951             }
1952         }
1953     }
1954
1955     /// parses 0 or 1 lifetime
1956     pub fn parse_opt_lifetime(&mut self) -> Option<ast::Lifetime> {
1957         match self.token {
1958             token::Lifetime(..) => {
1959                 Some(self.parse_lifetime())
1960             }
1961             _ => {
1962                 None
1963             }
1964         }
1965     }
1966
1967     /// Parses a single lifetime
1968     /// Matches lifetime = LIFETIME
1969     pub fn parse_lifetime(&mut self) -> ast::Lifetime {
1970         match self.token {
1971             token::Lifetime(i) => {
1972                 let span = self.span;
1973                 self.bump();
1974                 return ast::Lifetime {
1975                     id: ast::DUMMY_NODE_ID,
1976                     span: span,
1977                     name: i.name
1978                 };
1979             }
1980             _ => {
1981                 self.fatal(&format!("expected a lifetime name")[]);
1982             }
1983         }
1984     }
1985
1986     /// Parses `lifetime_defs = [ lifetime_defs { ',' lifetime_defs } ]` where `lifetime_def  =
1987     /// lifetime [':' lifetimes]`
1988     pub fn parse_lifetime_defs(&mut self) -> Vec<ast::LifetimeDef> {
1989
1990         let mut res = Vec::new();
1991         loop {
1992             match self.token {
1993                 token::Lifetime(_) => {
1994                     let lifetime = self.parse_lifetime();
1995                     let bounds =
1996                         if self.eat(&token::Colon) {
1997                             self.parse_lifetimes(token::BinOp(token::Plus))
1998                         } else {
1999                             Vec::new()
2000                         };
2001                     res.push(ast::LifetimeDef { lifetime: lifetime,
2002                                                 bounds: bounds });
2003                 }
2004
2005                 _ => {
2006                     return res;
2007                 }
2008             }
2009
2010             match self.token {
2011                 token::Comma => { self.bump(); }
2012                 token::Gt => { return res; }
2013                 token::BinOp(token::Shr) => { return res; }
2014                 _ => {
2015                     let this_token_str = self.this_token_to_string();
2016                     let msg = format!("expected `,` or `>` after lifetime \
2017                                       name, found `{}`",
2018                                       this_token_str);
2019                     self.fatal(&msg[]);
2020                 }
2021             }
2022         }
2023     }
2024
2025     /// matches lifetimes = ( lifetime ) | ( lifetime , lifetimes ) actually, it matches the empty
2026     /// one too, but putting that in there messes up the grammar....
2027     ///
2028     /// Parses zero or more comma separated lifetimes. Expects each lifetime to be followed by
2029     /// either a comma or `>`.  Used when parsing type parameter lists, where we expect something
2030     /// like `<'a, 'b, T>`.
2031     pub fn parse_lifetimes(&mut self, sep: token::Token) -> Vec<ast::Lifetime> {
2032
2033         let mut res = Vec::new();
2034         loop {
2035             match self.token {
2036                 token::Lifetime(_) => {
2037                     res.push(self.parse_lifetime());
2038                 }
2039                 _ => {
2040                     return res;
2041                 }
2042             }
2043
2044             if self.token != sep {
2045                 return res;
2046             }
2047
2048             self.bump();
2049         }
2050     }
2051
2052     /// Parse mutability declaration (mut/const/imm)
2053     pub fn parse_mutability(&mut self) -> Mutability {
2054         if self.eat_keyword(keywords::Mut) {
2055             MutMutable
2056         } else {
2057             MutImmutable
2058         }
2059     }
2060
2061     /// Parse ident COLON expr
2062     pub fn parse_field(&mut self) -> Field {
2063         let lo = self.span.lo;
2064         let i = self.parse_ident();
2065         let hi = self.last_span.hi;
2066         self.expect(&token::Colon);
2067         let e = self.parse_expr();
2068         ast::Field {
2069             ident: spanned(lo, hi, i),
2070             span: mk_sp(lo, e.span.hi),
2071             expr: e,
2072         }
2073     }
2074
2075     pub fn mk_expr(&mut self, lo: BytePos, hi: BytePos, node: Expr_) -> P<Expr> {
2076         P(Expr {
2077             id: ast::DUMMY_NODE_ID,
2078             node: node,
2079             span: mk_sp(lo, hi),
2080         })
2081     }
2082
2083     pub fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::Expr_ {
2084         ExprUnary(unop, expr)
2085     }
2086
2087     pub fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::Expr_ {
2088         ExprBinary(binop, lhs, rhs)
2089     }
2090
2091     pub fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::Expr_ {
2092         ExprCall(f, args)
2093     }
2094
2095     fn mk_method_call(&mut self,
2096                       ident: ast::SpannedIdent,
2097                       tps: Vec<P<Ty>>,
2098                       args: Vec<P<Expr>>)
2099                       -> ast::Expr_ {
2100         ExprMethodCall(ident, tps, args)
2101     }
2102
2103     pub fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::Expr_ {
2104         ExprIndex(expr, idx)
2105     }
2106
2107     pub fn mk_range(&mut self,
2108                     start: Option<P<Expr>>,
2109                     end: Option<P<Expr>>)
2110                     -> ast::Expr_ {
2111         ExprRange(start, end)
2112     }
2113
2114     pub fn mk_field(&mut self, expr: P<Expr>, ident: ast::SpannedIdent) -> ast::Expr_ {
2115         ExprField(expr, ident)
2116     }
2117
2118     pub fn mk_tup_field(&mut self, expr: P<Expr>, idx: codemap::Spanned<uint>) -> ast::Expr_ {
2119         ExprTupField(expr, idx)
2120     }
2121
2122     pub fn mk_assign_op(&mut self, binop: ast::BinOp,
2123                         lhs: P<Expr>, rhs: P<Expr>) -> ast::Expr_ {
2124         ExprAssignOp(binop, lhs, rhs)
2125     }
2126
2127     pub fn mk_mac_expr(&mut self, lo: BytePos, hi: BytePos, m: Mac_) -> P<Expr> {
2128         P(Expr {
2129             id: ast::DUMMY_NODE_ID,
2130             node: ExprMac(codemap::Spanned {node: m, span: mk_sp(lo, hi)}),
2131             span: mk_sp(lo, hi),
2132         })
2133     }
2134
2135     pub fn mk_lit_u32(&mut self, i: u32) -> P<Expr> {
2136         let span = &self.span;
2137         let lv_lit = P(codemap::Spanned {
2138             node: LitInt(i as u64, ast::UnsignedIntLit(TyU32)),
2139             span: *span
2140         });
2141
2142         P(Expr {
2143             id: ast::DUMMY_NODE_ID,
2144             node: ExprLit(lv_lit),
2145             span: *span,
2146         })
2147     }
2148
2149     fn expect_open_delim(&mut self) -> token::DelimToken {
2150         match self.token {
2151             token::OpenDelim(delim) => {
2152                 self.bump();
2153                 delim
2154             },
2155             _ => self.fatal("expected open delimiter"),
2156         }
2157     }
2158
2159     /// At the bottom (top?) of the precedence hierarchy,
2160     /// parse things like parenthesized exprs,
2161     /// macros, return, etc.
2162     pub fn parse_bottom_expr(&mut self) -> P<Expr> {
2163         maybe_whole_expr!(self);
2164
2165         let lo = self.span.lo;
2166         let mut hi = self.span.hi;
2167
2168         let ex: Expr_;
2169
2170         match self.token {
2171             token::OpenDelim(token::Paren) => {
2172                 self.bump();
2173
2174                 // (e) is parenthesized e
2175                 // (e,) is a tuple with only one field, e
2176                 let mut es = vec![];
2177                 let mut trailing_comma = false;
2178                 while self.token != token::CloseDelim(token::Paren) {
2179                     es.push(self.parse_expr());
2180                     self.commit_expr(&**es.last().unwrap(), &[],
2181                                      &[token::Comma, token::CloseDelim(token::Paren)]);
2182                     if self.check(&token::Comma) {
2183                         trailing_comma = true;
2184
2185                         self.bump();
2186                     } else {
2187                         trailing_comma = false;
2188                         break;
2189                     }
2190                 }
2191                 self.bump();
2192
2193                 hi = self.span.hi;
2194                 return if es.len() == 1 && !trailing_comma {
2195                     self.mk_expr(lo, hi, ExprParen(es.into_iter().nth(0).unwrap()))
2196                 } else {
2197                     self.mk_expr(lo, hi, ExprTup(es))
2198                 }
2199             },
2200             token::OpenDelim(token::Brace) => {
2201                 self.bump();
2202                 let blk = self.parse_block_tail(lo, DefaultBlock);
2203                 return self.mk_expr(blk.span.lo, blk.span.hi,
2204                                     ExprBlock(blk));
2205             },
2206             token::BinOp(token::Or) |  token::OrOr => {
2207                 return self.parse_lambda_expr(CaptureByRef);
2208             },
2209             // FIXME #13626: Should be able to stick in
2210             // token::SELF_KEYWORD_NAME
2211             token::Ident(id @ ast::Ident {
2212                             name: ast::Name(token::SELF_KEYWORD_NAME_NUM),
2213                             ctxt: _
2214                          }, token::Plain) => {
2215                 self.bump();
2216                 let path = ast_util::ident_to_path(mk_sp(lo, hi), id);
2217                 ex = ExprPath(path);
2218                 hi = self.last_span.hi;
2219             }
2220             token::OpenDelim(token::Bracket) => {
2221                 self.bump();
2222
2223                 if self.check(&token::CloseDelim(token::Bracket)) {
2224                     // Empty vector.
2225                     self.bump();
2226                     ex = ExprVec(Vec::new());
2227                 } else {
2228                     // Nonempty vector.
2229                     let first_expr = self.parse_expr();
2230                     if self.check(&token::Semi) {
2231                         // Repeating vector syntax: [ 0; 512 ]
2232                         self.bump();
2233                         let count = self.parse_expr();
2234                         self.expect(&token::CloseDelim(token::Bracket));
2235                         ex = ExprRepeat(first_expr, count);
2236                     } else if self.check(&token::Comma) {
2237                         // Vector with two or more elements.
2238                         self.bump();
2239                         let remaining_exprs = self.parse_seq_to_end(
2240                             &token::CloseDelim(token::Bracket),
2241                             seq_sep_trailing_allowed(token::Comma),
2242                             |p| p.parse_expr()
2243                                 );
2244                         let mut exprs = vec!(first_expr);
2245                         exprs.extend(remaining_exprs.into_iter());
2246                         ex = ExprVec(exprs);
2247                     } else {
2248                         // Vector with one element.
2249                         self.expect(&token::CloseDelim(token::Bracket));
2250                         ex = ExprVec(vec!(first_expr));
2251                     }
2252                 }
2253                 hi = self.last_span.hi;
2254             }
2255             _ => {
2256                 if self.eat_keyword(keywords::Move) {
2257                     return self.parse_lambda_expr(CaptureByValue);
2258                 }
2259                 if self.eat_keyword(keywords::Proc) {
2260                     let span = self.last_span;
2261                     let _ = self.parse_proc_decl();
2262                     let _ = self.parse_expr();
2263                     return self.obsolete_expr(span, ObsoleteSyntax::ProcExpr);
2264                 }
2265                 if self.eat_keyword(keywords::If) {
2266                     return self.parse_if_expr();
2267                 }
2268                 if self.eat_keyword(keywords::For) {
2269                     return self.parse_for_expr(None);
2270                 }
2271                 if self.eat_keyword(keywords::While) {
2272                     return self.parse_while_expr(None);
2273                 }
2274                 if self.token.is_lifetime() {
2275                     let lifetime = self.get_lifetime();
2276                     self.bump();
2277                     self.expect(&token::Colon);
2278                     if self.eat_keyword(keywords::While) {
2279                         return self.parse_while_expr(Some(lifetime))
2280                     }
2281                     if self.eat_keyword(keywords::For) {
2282                         return self.parse_for_expr(Some(lifetime))
2283                     }
2284                     if self.eat_keyword(keywords::Loop) {
2285                         return self.parse_loop_expr(Some(lifetime))
2286                     }
2287                     self.fatal("expected `while`, `for`, or `loop` after a label")
2288                 }
2289                 if self.eat_keyword(keywords::Loop) {
2290                     return self.parse_loop_expr(None);
2291                 }
2292                 if self.eat_keyword(keywords::Continue) {
2293                     let lo = self.span.lo;
2294                     let ex = if self.token.is_lifetime() {
2295                         let lifetime = self.get_lifetime();
2296                         self.bump();
2297                         ExprAgain(Some(lifetime))
2298                     } else {
2299                         ExprAgain(None)
2300                     };
2301                     let hi = self.span.hi;
2302                     return self.mk_expr(lo, hi, ex);
2303                 }
2304                 if self.eat_keyword(keywords::Match) {
2305                     return self.parse_match_expr();
2306                 }
2307                 if self.eat_keyword(keywords::Unsafe) {
2308                     return self.parse_block_expr(
2309                         lo,
2310                         UnsafeBlock(ast::UserProvided));
2311                 }
2312                 if self.eat_keyword(keywords::Return) {
2313                     // RETURN expression
2314                     if self.token.can_begin_expr() {
2315                         let e = self.parse_expr();
2316                         hi = e.span.hi;
2317                         ex = ExprRet(Some(e));
2318                     } else {
2319                         ex = ExprRet(None);
2320                     }
2321                 } else if self.eat_keyword(keywords::Break) {
2322                     // BREAK expression
2323                     if self.token.is_lifetime() {
2324                         let lifetime = self.get_lifetime();
2325                         self.bump();
2326                         ex = ExprBreak(Some(lifetime));
2327                     } else {
2328                         ex = ExprBreak(None);
2329                     }
2330                     hi = self.span.hi;
2331                 } else if self.check(&token::ModSep) ||
2332                         self.token.is_ident() &&
2333                         !self.token.is_keyword(keywords::True) &&
2334                         !self.token.is_keyword(keywords::False) {
2335                     let pth =
2336                         self.parse_path(LifetimeAndTypesWithColons);
2337
2338                     // `!`, as an operator, is prefix, so we know this isn't that
2339                     if self.check(&token::Not) {
2340                         // MACRO INVOCATION expression
2341                         self.bump();
2342
2343                         let delim = self.expect_open_delim();
2344                         let tts = self.parse_seq_to_end(
2345                             &token::CloseDelim(delim),
2346                             seq_sep_none(),
2347                             |p| p.parse_token_tree());
2348                         let hi = self.span.hi;
2349
2350                         return self.mk_mac_expr(lo,
2351                                                 hi,
2352                                                 MacInvocTT(pth,
2353                                                            tts,
2354                                                            EMPTY_CTXT));
2355                     }
2356                     if self.check(&token::OpenDelim(token::Brace)) {
2357                         // This is a struct literal, unless we're prohibited
2358                         // from parsing struct literals here.
2359                         if !self.restrictions.contains(RESTRICTION_NO_STRUCT_LITERAL) {
2360                             // It's a struct literal.
2361                             self.bump();
2362                             let mut fields = Vec::new();
2363                             let mut base = None;
2364
2365                             while self.token != token::CloseDelim(token::Brace) {
2366                                 if self.eat(&token::DotDot) {
2367                                     base = Some(self.parse_expr());
2368                                     break;
2369                                 }
2370
2371                                 fields.push(self.parse_field());
2372                                 self.commit_expr(&*fields.last().unwrap().expr,
2373                                                  &[token::Comma],
2374                                                  &[token::CloseDelim(token::Brace)]);
2375                             }
2376
2377                             if fields.len() == 0 && base.is_none() {
2378                                 let last_span = self.last_span;
2379                                 self.span_err(last_span,
2380                                               "structure literal must either \
2381                                               have at least one field or use \
2382                                               functional structure update \
2383                                               syntax");
2384                             }
2385
2386                             hi = self.span.hi;
2387                             self.expect(&token::CloseDelim(token::Brace));
2388                             ex = ExprStruct(pth, fields, base);
2389                             return self.mk_expr(lo, hi, ex);
2390                         }
2391                     }
2392
2393                     hi = pth.span.hi;
2394                     ex = ExprPath(pth);
2395                 } else {
2396                     // other literal expression
2397                     let lit = self.parse_lit();
2398                     hi = lit.span.hi;
2399                     ex = ExprLit(P(lit));
2400                 }
2401             }
2402         }
2403
2404         return self.mk_expr(lo, hi, ex);
2405     }
2406
2407     /// Parse a block or unsafe block
2408     pub fn parse_block_expr(&mut self, lo: BytePos, blk_mode: BlockCheckMode)
2409                             -> P<Expr> {
2410         self.expect(&token::OpenDelim(token::Brace));
2411         let blk = self.parse_block_tail(lo, blk_mode);
2412         return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk));
2413     }
2414
2415     /// parse a.b or a(13) or a[4] or just a
2416     pub fn parse_dot_or_call_expr(&mut self) -> P<Expr> {
2417         let b = self.parse_bottom_expr();
2418         self.parse_dot_or_call_expr_with(b)
2419     }
2420
2421     pub fn parse_dot_or_call_expr_with(&mut self, e0: P<Expr>) -> P<Expr> {
2422         let mut e = e0;
2423         let lo = e.span.lo;
2424         let mut hi;
2425         loop {
2426             // expr.f
2427             if self.eat(&token::Dot) {
2428                 match self.token {
2429                   token::Ident(i, _) => {
2430                     let dot = self.last_span.hi;
2431                     hi = self.span.hi;
2432                     self.bump();
2433                     let (_, tys, bindings) = if self.eat(&token::ModSep) {
2434                         self.expect_lt();
2435                         self.parse_generic_values_after_lt()
2436                     } else {
2437                         (Vec::new(), Vec::new(), Vec::new())
2438                     };
2439
2440                     if bindings.len() > 0 {
2441                         let last_span = self.last_span;
2442                         self.span_err(last_span, "type bindings are only permitted on trait paths");
2443                     }
2444
2445                     // expr.f() method call
2446                     match self.token {
2447                         token::OpenDelim(token::Paren) => {
2448                             let mut es = self.parse_unspanned_seq(
2449                                 &token::OpenDelim(token::Paren),
2450                                 &token::CloseDelim(token::Paren),
2451                                 seq_sep_trailing_allowed(token::Comma),
2452                                 |p| p.parse_expr()
2453                             );
2454                             hi = self.last_span.hi;
2455
2456                             es.insert(0, e);
2457                             let id = spanned(dot, hi, i);
2458                             let nd = self.mk_method_call(id, tys, es);
2459                             e = self.mk_expr(lo, hi, nd);
2460                         }
2461                         _ => {
2462                             if !tys.is_empty() {
2463                                 let last_span = self.last_span;
2464                                 self.span_err(last_span,
2465                                               "field expressions may not \
2466                                                have type parameters");
2467                             }
2468
2469                             let id = spanned(dot, hi, i);
2470                             let field = self.mk_field(e, id);
2471                             e = self.mk_expr(lo, hi, field);
2472                         }
2473                     }
2474                   }
2475                   token::Literal(token::Integer(n), suf) => {
2476                     let sp = self.span;
2477
2478                     // A tuple index may not have a suffix
2479                     self.expect_no_suffix(sp, "tuple index", suf);
2480
2481                     let dot = self.last_span.hi;
2482                     hi = self.span.hi;
2483                     self.bump();
2484
2485                     let index = n.as_str().parse::<uint>();
2486                     match index {
2487                         Some(n) => {
2488                             let id = spanned(dot, hi, n);
2489                             let field = self.mk_tup_field(e, id);
2490                             e = self.mk_expr(lo, hi, field);
2491                         }
2492                         None => {
2493                             let last_span = self.last_span;
2494                             self.span_err(last_span, "invalid tuple or tuple struct index");
2495                         }
2496                     }
2497                   }
2498                   token::Literal(token::Float(n), _suf) => {
2499                     self.bump();
2500                     let last_span = self.last_span;
2501                     let fstr = n.as_str();
2502                     self.span_err(last_span,
2503                                   &format!("unexpected token: `{}`", n.as_str())[]);
2504                     if fstr.chars().all(|x| "0123456789.".contains_char(x)) {
2505                         let float = match fstr.parse::<f64>() {
2506                             Some(f) => f,
2507                             None => continue,
2508                         };
2509                         self.span_help(last_span,
2510                             &format!("try parenthesizing the first index; e.g., `(foo.{}){}`",
2511                                     float.trunc() as uint,
2512                                     &float.fract().to_string()[1..])[]);
2513                     }
2514                     self.abort_if_errors();
2515
2516                   }
2517                   _ => self.unexpected()
2518                 }
2519                 continue;
2520             }
2521             if self.expr_is_complete(&*e) { break; }
2522             match self.token {
2523               // expr(...)
2524               token::OpenDelim(token::Paren) => {
2525                 let es = self.parse_unspanned_seq(
2526                     &token::OpenDelim(token::Paren),
2527                     &token::CloseDelim(token::Paren),
2528                     seq_sep_trailing_allowed(token::Comma),
2529                     |p| p.parse_expr()
2530                 );
2531                 hi = self.last_span.hi;
2532
2533                 let nd = self.mk_call(e, es);
2534                 e = self.mk_expr(lo, hi, nd);
2535               }
2536
2537               // expr[...]
2538               // Could be either an index expression or a slicing expression.
2539               token::OpenDelim(token::Bracket) => {
2540                 let bracket_pos = self.span.lo;
2541                 self.bump();
2542
2543                 let mut found_dotdot = false;
2544                 if self.token == token::DotDot &&
2545                    self.look_ahead(1, |t| t == &token::CloseDelim(token::Bracket)) {
2546                     // Using expr[..], which is a mistake, should be expr[]
2547                     self.bump();
2548                     self.bump();
2549                     found_dotdot = true;
2550                 }
2551
2552                 if found_dotdot || self.eat(&token::CloseDelim(token::Bracket)) {
2553                     // No expression, expand to a FullRange
2554                     // FIXME(#20516) It would be better to use a lang item or
2555                     // something for FullRange.
2556                     hi = self.last_span.hi;
2557                     let range = ExprStruct(ident_to_path(mk_sp(lo, hi),
2558                                                          token::special_idents::FullRange),
2559                                            vec![],
2560                                            None);
2561                     let ix = self.mk_expr(bracket_pos, hi, range);
2562                     let index = self.mk_index(e, ix);
2563                     e = self.mk_expr(lo, hi, index)
2564                 } else {
2565                     let ix = self.parse_expr();
2566                     hi = self.span.hi;
2567                     self.commit_expr_expecting(&*ix, token::CloseDelim(token::Bracket));
2568                     let index = self.mk_index(e, ix);
2569                     e = self.mk_expr(lo, hi, index)
2570                 }
2571
2572                 if found_dotdot {
2573                     self.span_err(e.span, "incorrect slicing expression: `[..]`");
2574                     self.span_note(e.span,
2575                                    "use `&expr[]` to construct a slice of the whole of expr");
2576                 }
2577               }
2578               _ => return e
2579             }
2580         }
2581         return e;
2582     }
2583
2584     // Parse unquoted tokens after a `$` in a token tree
2585     fn parse_unquoted(&mut self) -> TokenTree {
2586         let mut sp = self.span;
2587         let (name, namep) = match self.token {
2588             token::Dollar => {
2589                 self.bump();
2590
2591                 if self.token == token::OpenDelim(token::Paren) {
2592                     let Spanned { node: seq, span: seq_span } = self.parse_seq(
2593                         &token::OpenDelim(token::Paren),
2594                         &token::CloseDelim(token::Paren),
2595                         seq_sep_none(),
2596                         |p| p.parse_token_tree()
2597                     );
2598                     let (sep, repeat) = self.parse_sep_and_kleene_op();
2599                     let name_num = macro_parser::count_names(seq.as_slice());
2600                     return TtSequence(mk_sp(sp.lo, seq_span.hi),
2601                                       Rc::new(SequenceRepetition {
2602                                           tts: seq,
2603                                           separator: sep,
2604                                           op: repeat,
2605                                           num_captures: name_num
2606                                       }));
2607                 } else if self.token.is_keyword_allow_following_colon(keywords::Crate) {
2608                     self.bump();
2609                     return TtToken(sp, SpecialVarNt(SpecialMacroVar::CrateMacroVar));
2610                 } else {
2611                     sp = mk_sp(sp.lo, self.span.hi);
2612                     let namep = match self.token { token::Ident(_, p) => p, _ => token::Plain };
2613                     let name = self.parse_ident();
2614                     (name, namep)
2615                 }
2616             }
2617             token::SubstNt(name, namep) => {
2618                 self.bump();
2619                 (name, namep)
2620             }
2621             _ => unreachable!()
2622         };
2623         // continue by trying to parse the `:ident` after `$name`
2624         if self.token == token::Colon && self.look_ahead(1, |t| t.is_ident() &&
2625                                                                 !t.is_strict_keyword() &&
2626                                                                 !t.is_reserved_keyword()) {
2627             self.bump();
2628             sp = mk_sp(sp.lo, self.span.hi);
2629             let kindp = match self.token { token::Ident(_, p) => p, _ => token::Plain };
2630             let nt_kind = self.parse_ident();
2631             TtToken(sp, MatchNt(name, nt_kind, namep, kindp))
2632         } else {
2633             TtToken(sp, SubstNt(name, namep))
2634         }
2635     }
2636
2637     pub fn check_unknown_macro_variable(&mut self) {
2638         if self.quote_depth == 0u {
2639             match self.token {
2640                 token::SubstNt(name, _) =>
2641                     self.fatal(&format!("unknown macro variable `{}`",
2642                                        token::get_ident(name))[]),
2643                 _ => {}
2644             }
2645         }
2646     }
2647
2648     /// Parse an optional separator followed by a Kleene-style
2649     /// repetition token (+ or *).
2650     pub fn parse_sep_and_kleene_op(&mut self) -> (Option<token::Token>, ast::KleeneOp) {
2651         fn parse_kleene_op(parser: &mut Parser) -> Option<ast::KleeneOp> {
2652             match parser.token {
2653                 token::BinOp(token::Star) => {
2654                     parser.bump();
2655                     Some(ast::ZeroOrMore)
2656                 },
2657                 token::BinOp(token::Plus) => {
2658                     parser.bump();
2659                     Some(ast::OneOrMore)
2660                 },
2661                 _ => None
2662             }
2663         };
2664
2665         match parse_kleene_op(self) {
2666             Some(kleene_op) => return (None, kleene_op),
2667             None => {}
2668         }
2669
2670         let separator = self.bump_and_get();
2671         match parse_kleene_op(self) {
2672             Some(zerok) => (Some(separator), zerok),
2673             None => self.fatal("expected `*` or `+`")
2674         }
2675     }
2676
2677     /// parse a single token tree from the input.
2678     pub fn parse_token_tree(&mut self) -> TokenTree {
2679         // FIXME #6994: currently, this is too eager. It
2680         // parses token trees but also identifies TtSequence's
2681         // and token::SubstNt's; it's too early to know yet
2682         // whether something will be a nonterminal or a seq
2683         // yet.
2684         maybe_whole!(deref self, NtTT);
2685
2686         // this is the fall-through for the 'match' below.
2687         // invariants: the current token is not a left-delimiter,
2688         // not an EOF, and not the desired right-delimiter (if
2689         // it were, parse_seq_to_before_end would have prevented
2690         // reaching this point.
2691         fn parse_non_delim_tt_tok(p: &mut Parser) -> TokenTree {
2692             maybe_whole!(deref p, NtTT);
2693             match p.token {
2694                 token::CloseDelim(_) => {
2695                     // This is a conservative error: only report the last unclosed delimiter. The
2696                     // previous unclosed delimiters could actually be closed! The parser just hasn't
2697                     // gotten to them yet.
2698                     match p.open_braces.last() {
2699                         None => {}
2700                         Some(&sp) => p.span_note(sp, "unclosed delimiter"),
2701                     };
2702                     let token_str = p.this_token_to_string();
2703                     p.fatal(&format!("incorrect close delimiter: `{}`",
2704                                     token_str)[])
2705                 },
2706                 /* we ought to allow different depths of unquotation */
2707                 token::Dollar | token::SubstNt(..) if p.quote_depth > 0u => {
2708                     p.parse_unquoted()
2709                 }
2710                 _ => {
2711                     TtToken(p.span, p.bump_and_get())
2712                 }
2713             }
2714         }
2715
2716         match self.token {
2717             token::Eof => {
2718                 let open_braces = self.open_braces.clone();
2719                 for sp in open_braces.iter() {
2720                     self.span_help(*sp, "did you mean to close this delimiter?");
2721                 }
2722                 // There shouldn't really be a span, but it's easier for the test runner
2723                 // if we give it one
2724                 self.fatal("this file contains an un-closed delimiter ");
2725             },
2726             token::OpenDelim(delim) => {
2727                 // The span for beginning of the delimited section
2728                 let pre_span = self.span;
2729
2730                 // Parse the open delimiter.
2731                 self.open_braces.push(self.span);
2732                 let open_span = self.span;
2733                 self.bump();
2734
2735                 // Parse the token trees within the delimiters
2736                 let tts = self.parse_seq_to_before_end(
2737                     &token::CloseDelim(delim),
2738                     seq_sep_none(),
2739                     |p| p.parse_token_tree()
2740                 );
2741
2742                 // Parse the close delimiter.
2743                 let close_span = self.span;
2744                 self.bump();
2745                 self.open_braces.pop().unwrap();
2746
2747                 // Expand to cover the entire delimited token tree
2748                 let span = Span { hi: self.span.hi, ..pre_span };
2749
2750                 TtDelimited(span, Rc::new(Delimited {
2751                     delim: delim,
2752                     open_span: open_span,
2753                     tts: tts,
2754                     close_span: close_span,
2755                 }))
2756             },
2757             _ => parse_non_delim_tt_tok(self),
2758         }
2759     }
2760
2761     // parse a stream of tokens into a list of TokenTree's,
2762     // up to EOF.
2763     pub fn parse_all_token_trees(&mut self) -> Vec<TokenTree> {
2764         let mut tts = Vec::new();
2765         while self.token != token::Eof {
2766             tts.push(self.parse_token_tree());
2767         }
2768         tts
2769     }
2770
2771     /// Parse a prefix-operator expr
2772     pub fn parse_prefix_expr(&mut self) -> P<Expr> {
2773         let lo = self.span.lo;
2774         let hi;
2775
2776         let ex;
2777         match self.token {
2778           token::Not => {
2779             self.bump();
2780             let e = self.parse_prefix_expr();
2781             hi = e.span.hi;
2782             ex = self.mk_unary(UnNot, e);
2783           }
2784           token::BinOp(token::Minus) => {
2785             self.bump();
2786             let e = self.parse_prefix_expr();
2787             hi = e.span.hi;
2788             ex = self.mk_unary(UnNeg, e);
2789           }
2790           token::BinOp(token::Star) => {
2791             self.bump();
2792             let e = self.parse_prefix_expr();
2793             hi = e.span.hi;
2794             ex = self.mk_unary(UnDeref, e);
2795           }
2796           token::BinOp(token::And) | token::AndAnd => {
2797             self.expect_and();
2798             let m = self.parse_mutability();
2799             let e = self.parse_prefix_expr();
2800             hi = e.span.hi;
2801             ex = ExprAddrOf(m, e);
2802           }
2803           token::Tilde => {
2804             self.bump();
2805             let last_span = self.last_span;
2806             match self.token {
2807                 token::OpenDelim(token::Bracket) => {
2808                     self.obsolete(last_span, ObsoleteSyntax::OwnedVector)
2809                 },
2810                 _ => self.obsolete(last_span, ObsoleteSyntax::OwnedExpr)
2811             }
2812
2813             let e = self.parse_prefix_expr();
2814             hi = e.span.hi;
2815             ex = self.mk_unary(UnUniq, e);
2816           }
2817           token::DotDot if !self.restrictions.contains(RESTRICTION_NO_DOTS) => {
2818             // A range, closed above: `..expr`.
2819             self.bump();
2820             let e = self.parse_expr();
2821             hi = e.span.hi;
2822             ex = self.mk_range(None, Some(e));
2823           }
2824           token::Ident(_, _) => {
2825             if !self.token.is_keyword(keywords::Box) {
2826                 return self.parse_dot_or_call_expr();
2827             }
2828
2829             let lo = self.span.lo;
2830
2831             self.bump();
2832
2833             // Check for a place: `box(PLACE) EXPR`.
2834             if self.eat(&token::OpenDelim(token::Paren)) {
2835                 // Support `box() EXPR` as the default.
2836                 if !self.eat(&token::CloseDelim(token::Paren)) {
2837                     let place = self.parse_expr();
2838                     self.expect(&token::CloseDelim(token::Paren));
2839                     // Give a suggestion to use `box()` when a parenthesised expression is used
2840                     if !self.token.can_begin_expr() {
2841                         let span = self.span;
2842                         let this_token_to_string = self.this_token_to_string();
2843                         self.span_err(span,
2844                                       &format!("expected expression, found `{}`",
2845                                               this_token_to_string)[]);
2846                         let box_span = mk_sp(lo, self.last_span.hi);
2847                         self.span_help(box_span,
2848                                        "perhaps you meant `box() (foo)` instead?");
2849                         self.abort_if_errors();
2850                     }
2851                     let subexpression = self.parse_prefix_expr();
2852                     hi = subexpression.span.hi;
2853                     ex = ExprBox(Some(place), subexpression);
2854                     return self.mk_expr(lo, hi, ex);
2855                 }
2856             }
2857
2858             // Otherwise, we use the unique pointer default.
2859             let subexpression = self.parse_prefix_expr();
2860             hi = subexpression.span.hi;
2861             // FIXME (pnkfelix): After working out kinks with box
2862             // desugaring, should be `ExprBox(None, subexpression)`
2863             // instead.
2864             ex = self.mk_unary(UnUniq, subexpression);
2865           }
2866           _ => return self.parse_dot_or_call_expr()
2867         }
2868         return self.mk_expr(lo, hi, ex);
2869     }
2870
2871     /// Parse an expression of binops
2872     pub fn parse_binops(&mut self) -> P<Expr> {
2873         let prefix_expr = self.parse_prefix_expr();
2874         self.parse_more_binops(prefix_expr, 0)
2875     }
2876
2877     /// Parse an expression of binops of at least min_prec precedence
2878     pub fn parse_more_binops(&mut self, lhs: P<Expr>, min_prec: uint) -> P<Expr> {
2879         if self.expr_is_complete(&*lhs) { return lhs; }
2880
2881         // Prevent dynamic borrow errors later on by limiting the
2882         // scope of the borrows.
2883         if self.token == token::BinOp(token::Or) &&
2884             self.restrictions.contains(RESTRICTION_NO_BAR_OP) {
2885             return lhs;
2886         }
2887
2888         self.expected_tokens.push(TokenType::Operator);
2889
2890         let cur_opt = self.token.to_binop();
2891         match cur_opt {
2892             Some(cur_op) => {
2893                 if ast_util::is_comparison_binop(cur_op) {
2894                     self.check_no_chained_comparison(&*lhs, cur_op)
2895                 }
2896                 let cur_prec = operator_prec(cur_op);
2897                 if cur_prec > min_prec {
2898                     self.bump();
2899                     let expr = self.parse_prefix_expr();
2900                     let rhs = self.parse_more_binops(expr, cur_prec);
2901                     let lhs_span = lhs.span;
2902                     let rhs_span = rhs.span;
2903                     let binary = self.mk_binary(cur_op, lhs, rhs);
2904                     let bin = self.mk_expr(lhs_span.lo, rhs_span.hi, binary);
2905                     self.parse_more_binops(bin, min_prec)
2906                 } else {
2907                     lhs
2908                 }
2909             }
2910             None => {
2911                 if as_prec > min_prec && self.eat_keyword(keywords::As) {
2912                     let rhs = self.parse_ty();
2913                     let _as = self.mk_expr(lhs.span.lo,
2914                                            rhs.span.hi,
2915                                            ExprCast(lhs, rhs));
2916                     self.parse_more_binops(_as, min_prec)
2917                 } else {
2918                     lhs
2919                 }
2920             }
2921         }
2922     }
2923
2924     /// Produce an error if comparison operators are chained (RFC #558).
2925     /// We only need to check lhs, not rhs, because all comparison ops
2926     /// have same precedence and are left-associative
2927     fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: ast::BinOp) {
2928         debug_assert!(ast_util::is_comparison_binop(outer_op));
2929         match lhs.node {
2930             ExprBinary(op, _, _) if ast_util::is_comparison_binop(op) => {
2931                 let op_span = self.span;
2932                 self.span_err(op_span,
2933                     "Chained comparison operators require parentheses");
2934                 if op == BiLt && outer_op == BiGt {
2935                     self.span_help(op_span,
2936                         "Use ::< instead of < if you meant to specify type arguments.");
2937                 }
2938             }
2939             _ => {}
2940         }
2941     }
2942
2943     /// Parse an assignment expression....
2944     /// actually, this seems to be the main entry point for
2945     /// parsing an arbitrary expression.
2946     pub fn parse_assign_expr(&mut self) -> P<Expr> {
2947         let lhs = self.parse_binops();
2948         self.parse_assign_expr_with(lhs)
2949     }
2950
2951     pub fn parse_assign_expr_with(&mut self, lhs: P<Expr>) -> P<Expr> {
2952         let restrictions = self.restrictions & RESTRICTION_NO_STRUCT_LITERAL;
2953         match self.token {
2954           token::Eq => {
2955               self.bump();
2956               let rhs = self.parse_expr_res(restrictions);
2957               self.mk_expr(lhs.span.lo, rhs.span.hi, ExprAssign(lhs, rhs))
2958           }
2959           token::BinOpEq(op) => {
2960               self.bump();
2961               let rhs = self.parse_expr_res(restrictions);
2962               let aop = match op {
2963                   token::Plus =>    BiAdd,
2964                   token::Minus =>   BiSub,
2965                   token::Star =>    BiMul,
2966                   token::Slash =>   BiDiv,
2967                   token::Percent => BiRem,
2968                   token::Caret =>   BiBitXor,
2969                   token::And =>     BiBitAnd,
2970                   token::Or =>      BiBitOr,
2971                   token::Shl =>     BiShl,
2972                   token::Shr =>     BiShr
2973               };
2974               let rhs_span = rhs.span;
2975               let span = lhs.span;
2976               let assign_op = self.mk_assign_op(aop, lhs, rhs);
2977               self.mk_expr(span.lo, rhs_span.hi, assign_op)
2978           }
2979           // A range expression, either `expr..expr` or `expr..`.
2980           token::DotDot if !self.restrictions.contains(RESTRICTION_NO_DOTS) => {
2981             self.bump();
2982
2983             let opt_end = if self.token.can_begin_expr() {
2984                 let end = self.parse_expr_res(RESTRICTION_NO_DOTS);
2985                 Some(end)
2986             } else {
2987                 None
2988             };
2989
2990             let lo = lhs.span.lo;
2991             let hi = self.span.hi;
2992             let range = self.mk_range(Some(lhs), opt_end);
2993             return self.mk_expr(lo, hi, range);
2994           }
2995
2996           _ => {
2997               lhs
2998           }
2999         }
3000     }
3001
3002     /// Parse an 'if' or 'if let' expression ('if' token already eaten)
3003     pub fn parse_if_expr(&mut self) -> P<Expr> {
3004         if self.token.is_keyword(keywords::Let) {
3005             return self.parse_if_let_expr();
3006         }
3007         let lo = self.last_span.lo;
3008         let cond = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
3009         let thn = self.parse_block();
3010         let mut els: Option<P<Expr>> = None;
3011         let mut hi = thn.span.hi;
3012         if self.eat_keyword(keywords::Else) {
3013             let elexpr = self.parse_else_expr();
3014             hi = elexpr.span.hi;
3015             els = Some(elexpr);
3016         }
3017         self.mk_expr(lo, hi, ExprIf(cond, thn, els))
3018     }
3019
3020     /// Parse an 'if let' expression ('if' token already eaten)
3021     pub fn parse_if_let_expr(&mut self) -> P<Expr> {
3022         let lo = self.last_span.lo;
3023         self.expect_keyword(keywords::Let);
3024         let pat = self.parse_pat();
3025         self.expect(&token::Eq);
3026         let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
3027         let thn = self.parse_block();
3028         let (hi, els) = if self.eat_keyword(keywords::Else) {
3029             let expr = self.parse_else_expr();
3030             (expr.span.hi, Some(expr))
3031         } else {
3032             (thn.span.hi, None)
3033         };
3034         self.mk_expr(lo, hi, ExprIfLet(pat, expr, thn, els))
3035     }
3036
3037     // `|args| expr`
3038     pub fn parse_lambda_expr(&mut self, capture_clause: CaptureClause)
3039                              -> P<Expr>
3040     {
3041         let lo = self.span.lo;
3042         let (decl, optional_unboxed_closure_kind) =
3043             self.parse_fn_block_decl();
3044         let body = self.parse_expr();
3045         let fakeblock = P(ast::Block {
3046             id: ast::DUMMY_NODE_ID,
3047             view_items: Vec::new(),
3048             stmts: Vec::new(),
3049             span: body.span,
3050             expr: Some(body),
3051             rules: DefaultBlock,
3052         });
3053
3054         self.mk_expr(
3055             lo,
3056             fakeblock.span.hi,
3057             ExprClosure(capture_clause, optional_unboxed_closure_kind, decl, fakeblock))
3058     }
3059
3060     pub fn parse_else_expr(&mut self) -> P<Expr> {
3061         if self.eat_keyword(keywords::If) {
3062             return self.parse_if_expr();
3063         } else {
3064             let blk = self.parse_block();
3065             return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk));
3066         }
3067     }
3068
3069     /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3070     pub fn parse_for_expr(&mut self, opt_ident: Option<ast::Ident>) -> P<Expr> {
3071         // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3072
3073         let lo = self.last_span.lo;
3074         let pat = self.parse_pat();
3075         self.expect_keyword(keywords::In);
3076         let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
3077         let loop_block = self.parse_block();
3078         let hi = self.span.hi;
3079
3080         self.mk_expr(lo, hi, ExprForLoop(pat, expr, loop_block, opt_ident))
3081     }
3082
3083     /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3084     pub fn parse_while_expr(&mut self, opt_ident: Option<ast::Ident>) -> P<Expr> {
3085         if self.token.is_keyword(keywords::Let) {
3086             return self.parse_while_let_expr(opt_ident);
3087         }
3088         let lo = self.last_span.lo;
3089         let cond = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
3090         let body = self.parse_block();
3091         let hi = body.span.hi;
3092         return self.mk_expr(lo, hi, ExprWhile(cond, body, opt_ident));
3093     }
3094
3095     /// Parse a 'while let' expression ('while' token already eaten)
3096     pub fn parse_while_let_expr(&mut self, opt_ident: Option<ast::Ident>) -> P<Expr> {
3097         let lo = self.last_span.lo;
3098         self.expect_keyword(keywords::Let);
3099         let pat = self.parse_pat();
3100         self.expect(&token::Eq);
3101         let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
3102         let body = self.parse_block();
3103         let hi = body.span.hi;
3104         return self.mk_expr(lo, hi, ExprWhileLet(pat, expr, body, opt_ident));
3105     }
3106
3107     pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::Ident>) -> P<Expr> {
3108         let lo = self.last_span.lo;
3109         let body = self.parse_block();
3110         let hi = body.span.hi;
3111         self.mk_expr(lo, hi, ExprLoop(body, opt_ident))
3112     }
3113
3114     fn parse_match_expr(&mut self) -> P<Expr> {
3115         let lo = self.last_span.lo;
3116         let discriminant = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
3117         self.commit_expr_expecting(&*discriminant, token::OpenDelim(token::Brace));
3118         let mut arms: Vec<Arm> = Vec::new();
3119         while self.token != token::CloseDelim(token::Brace) {
3120             arms.push(self.parse_arm());
3121         }
3122         let hi = self.span.hi;
3123         self.bump();
3124         return self.mk_expr(lo, hi, ExprMatch(discriminant, arms, MatchSource::Normal));
3125     }
3126
3127     pub fn parse_arm(&mut self) -> Arm {
3128         let attrs = self.parse_outer_attributes();
3129         let pats = self.parse_pats();
3130         let mut guard = None;
3131         if self.eat_keyword(keywords::If) {
3132             guard = Some(self.parse_expr());
3133         }
3134         self.expect(&token::FatArrow);
3135         let expr = self.parse_expr_res(RESTRICTION_STMT_EXPR);
3136
3137         let require_comma =
3138             !classify::expr_is_simple_block(&*expr)
3139             && self.token != token::CloseDelim(token::Brace);
3140
3141         if require_comma {
3142             self.commit_expr(&*expr, &[token::Comma], &[token::CloseDelim(token::Brace)]);
3143         } else {
3144             self.eat(&token::Comma);
3145         }
3146
3147         ast::Arm {
3148             attrs: attrs,
3149             pats: pats,
3150             guard: guard,
3151             body: expr,
3152         }
3153     }
3154
3155     /// Parse an expression
3156     pub fn parse_expr(&mut self) -> P<Expr> {
3157         return self.parse_expr_res(UNRESTRICTED);
3158     }
3159
3160     /// Parse an expression, subject to the given restrictions
3161     pub fn parse_expr_res(&mut self, r: Restrictions) -> P<Expr> {
3162         let old = self.restrictions;
3163         self.restrictions = r;
3164         let e = self.parse_assign_expr();
3165         self.restrictions = old;
3166         return e;
3167     }
3168
3169     /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3170     fn parse_initializer(&mut self) -> Option<P<Expr>> {
3171         if self.check(&token::Eq) {
3172             self.bump();
3173             Some(self.parse_expr())
3174         } else {
3175             None
3176         }
3177     }
3178
3179     /// Parse patterns, separated by '|' s
3180     fn parse_pats(&mut self) -> Vec<P<Pat>> {
3181         let mut pats = Vec::new();
3182         loop {
3183             pats.push(self.parse_pat());
3184             if self.check(&token::BinOp(token::Or)) { self.bump(); }
3185             else { return pats; }
3186         };
3187     }
3188
3189     fn parse_pat_vec_elements(
3190         &mut self,
3191     ) -> (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>) {
3192         let mut before = Vec::new();
3193         let mut slice = None;
3194         let mut after = Vec::new();
3195         let mut first = true;
3196         let mut before_slice = true;
3197
3198         while self.token != token::CloseDelim(token::Bracket) {
3199             if first {
3200                 first = false;
3201             } else {
3202                 self.expect(&token::Comma);
3203
3204                 if self.token == token::CloseDelim(token::Bracket)
3205                         && (before_slice || after.len() != 0) {
3206                     break
3207                 }
3208             }
3209
3210             if before_slice {
3211                 if self.check(&token::DotDot) {
3212                     self.bump();
3213
3214                     if self.check(&token::Comma) ||
3215                             self.check(&token::CloseDelim(token::Bracket)) {
3216                         slice = Some(P(ast::Pat {
3217                             id: ast::DUMMY_NODE_ID,
3218                             node: PatWild(PatWildMulti),
3219                             span: self.span,
3220                         }));
3221                         before_slice = false;
3222                     } else {
3223                         let _ = self.parse_pat();
3224                         let span = self.span;
3225                         self.obsolete(span, ObsoleteSyntax::SubsliceMatch);
3226                     }
3227                     continue
3228                 }
3229             }
3230
3231             let subpat = self.parse_pat();
3232             if before_slice && self.check(&token::DotDot) {
3233                 self.bump();
3234                 slice = Some(subpat);
3235                 before_slice = false;
3236             } else if before_slice {
3237                 before.push(subpat);
3238             } else {
3239                 after.push(subpat);
3240             }
3241         }
3242
3243         (before, slice, after)
3244     }
3245
3246     /// Parse the fields of a struct-like pattern
3247     fn parse_pat_fields(&mut self) -> (Vec<codemap::Spanned<ast::FieldPat>> , bool) {
3248         let mut fields = Vec::new();
3249         let mut etc = false;
3250         let mut first = true;
3251         while self.token != token::CloseDelim(token::Brace) {
3252             if first {
3253                 first = false;
3254             } else {
3255                 self.expect(&token::Comma);
3256                 // accept trailing commas
3257                 if self.check(&token::CloseDelim(token::Brace)) { break }
3258             }
3259
3260             let lo = self.span.lo;
3261             let hi;
3262
3263             if self.check(&token::DotDot) {
3264                 self.bump();
3265                 if self.token != token::CloseDelim(token::Brace) {
3266                     let token_str = self.this_token_to_string();
3267                     self.fatal(&format!("expected `{}`, found `{}`", "}",
3268                                        token_str)[])
3269                 }
3270                 etc = true;
3271                 break;
3272             }
3273
3274             let bind_type = if self.eat_keyword(keywords::Mut) {
3275                 BindByValue(MutMutable)
3276             } else if self.eat_keyword(keywords::Ref) {
3277                 BindByRef(self.parse_mutability())
3278             } else {
3279                 BindByValue(MutImmutable)
3280             };
3281
3282             let fieldname = self.parse_ident();
3283
3284             let (subpat, is_shorthand) = if self.check(&token::Colon) {
3285                 match bind_type {
3286                     BindByRef(..) | BindByValue(MutMutable) => {
3287                         let token_str = self.this_token_to_string();
3288                         self.fatal(&format!("unexpected `{}`",
3289                                            token_str)[])
3290                     }
3291                     _ => {}
3292                 }
3293
3294                 self.bump();
3295                 let pat = self.parse_pat();
3296                 hi = pat.span.hi;
3297                 (pat, false)
3298             } else {
3299                 hi = self.last_span.hi;
3300                 let fieldpath = codemap::Spanned{span:self.last_span, node: fieldname};
3301                 (P(ast::Pat {
3302                     id: ast::DUMMY_NODE_ID,
3303                     node: PatIdent(bind_type, fieldpath, None),
3304                     span: self.last_span
3305                 }), true)
3306             };
3307             fields.push(codemap::Spanned { span: mk_sp(lo, hi),
3308                                            node: ast::FieldPat { ident: fieldname,
3309                                                                  pat: subpat,
3310                                                                  is_shorthand: is_shorthand }});
3311         }
3312         return (fields, etc);
3313     }
3314
3315     /// Parse a pattern.
3316     pub fn parse_pat(&mut self) -> P<Pat> {
3317         maybe_whole!(self, NtPat);
3318
3319         let lo = self.span.lo;
3320         let mut hi;
3321         let pat;
3322         match self.token {
3323             // parse _
3324           token::Underscore => {
3325             self.bump();
3326             pat = PatWild(PatWildSingle);
3327             hi = self.last_span.hi;
3328             return P(ast::Pat {
3329                 id: ast::DUMMY_NODE_ID,
3330                 node: pat,
3331                 span: mk_sp(lo, hi)
3332             })
3333           }
3334           token::Tilde => {
3335             // parse ~pat
3336             self.bump();
3337             let sub = self.parse_pat();
3338             pat = PatBox(sub);
3339             let last_span = self.last_span;
3340             hi = last_span.hi;
3341             self.obsolete(last_span, ObsoleteSyntax::OwnedPattern);
3342             return P(ast::Pat {
3343                 id: ast::DUMMY_NODE_ID,
3344                 node: pat,
3345                 span: mk_sp(lo, hi)
3346             })
3347           }
3348           token::BinOp(token::And) | token::AndAnd => {
3349             // parse &pat and &mut pat
3350             let lo = self.span.lo;
3351             self.expect_and();
3352             let mutability = if self.eat_keyword(keywords::Mut) {
3353                 ast::MutMutable
3354             } else {
3355                 ast::MutImmutable
3356             };
3357             let sub = self.parse_pat();
3358             pat = PatRegion(sub, mutability);
3359             hi = self.last_span.hi;
3360             return P(ast::Pat {
3361                 id: ast::DUMMY_NODE_ID,
3362                 node: pat,
3363                 span: mk_sp(lo, hi)
3364             })
3365           }
3366           token::OpenDelim(token::Paren) => {
3367             // parse (pat,pat,pat,...) as tuple
3368             self.bump();
3369             if self.check(&token::CloseDelim(token::Paren)) {
3370                 self.bump();
3371                 pat = PatTup(vec![]);
3372             } else {
3373                 let mut fields = vec!(self.parse_pat());
3374                 if self.look_ahead(1, |t| *t != token::CloseDelim(token::Paren)) {
3375                     while self.check(&token::Comma) {
3376                         self.bump();
3377                         if self.check(&token::CloseDelim(token::Paren)) { break; }
3378                         fields.push(self.parse_pat());
3379                     }
3380                 }
3381                 if fields.len() == 1 { self.expect(&token::Comma); }
3382                 self.expect(&token::CloseDelim(token::Paren));
3383                 pat = PatTup(fields);
3384             }
3385             hi = self.last_span.hi;
3386             return P(ast::Pat {
3387                 id: ast::DUMMY_NODE_ID,
3388                 node: pat,
3389                 span: mk_sp(lo, hi)
3390             })
3391           }
3392           token::OpenDelim(token::Bracket) => {
3393             // parse [pat,pat,...] as vector pattern
3394             self.bump();
3395             let (before, slice, after) =
3396                 self.parse_pat_vec_elements();
3397
3398             self.expect(&token::CloseDelim(token::Bracket));
3399             pat = ast::PatVec(before, slice, after);
3400             hi = self.last_span.hi;
3401             return P(ast::Pat {
3402                 id: ast::DUMMY_NODE_ID,
3403                 node: pat,
3404                 span: mk_sp(lo, hi)
3405             })
3406           }
3407           _ => {}
3408         }
3409         // at this point, token != _, ~, &, &&, (, [
3410
3411         if (!(self.token.is_ident() || self.token.is_path())
3412               && self.token != token::ModSep)
3413                 || self.token.is_keyword(keywords::True)
3414                 || self.token.is_keyword(keywords::False) {
3415             // Parse an expression pattern or exp .. exp.
3416             //
3417             // These expressions are limited to literals (possibly
3418             // preceded by unary-minus) or identifiers.
3419             let val = self.parse_literal_maybe_minus();
3420             if (self.check(&token::DotDotDot)) &&
3421                     self.look_ahead(1, |t| {
3422                         *t != token::Comma && *t != token::CloseDelim(token::Bracket)
3423                     }) {
3424                 self.bump();
3425                 let end = if self.token.is_ident() || self.token.is_path() {
3426                     let path = self.parse_path(LifetimeAndTypesWithColons);
3427                     let hi = self.span.hi;
3428                     self.mk_expr(lo, hi, ExprPath(path))
3429                 } else {
3430                     self.parse_literal_maybe_minus()
3431                 };
3432                 pat = PatRange(val, end);
3433             } else {
3434                 pat = PatLit(val);
3435             }
3436         } else if self.eat_keyword(keywords::Mut) {
3437             pat = self.parse_pat_ident(BindByValue(MutMutable));
3438         } else if self.eat_keyword(keywords::Ref) {
3439             // parse ref pat
3440             let mutbl = self.parse_mutability();
3441             pat = self.parse_pat_ident(BindByRef(mutbl));
3442         } else if self.eat_keyword(keywords::Box) {
3443             // `box PAT`
3444             //
3445             // FIXME(#13910): Rename to `PatBox` and extend to full DST
3446             // support.
3447             let sub = self.parse_pat();
3448             pat = PatBox(sub);
3449             hi = self.last_span.hi;
3450             return P(ast::Pat {
3451                 id: ast::DUMMY_NODE_ID,
3452                 node: pat,
3453                 span: mk_sp(lo, hi)
3454             })
3455         } else {
3456             let can_be_enum_or_struct = self.look_ahead(1, |t| {
3457                 match *t {
3458                     token::OpenDelim(_) | token::Lt | token::ModSep => true,
3459                     _ => false,
3460                 }
3461             });
3462
3463             if self.look_ahead(1, |t| *t == token::DotDotDot) &&
3464                     self.look_ahead(2, |t| {
3465                         *t != token::Comma && *t != token::CloseDelim(token::Bracket)
3466                     }) {
3467                 let start = self.parse_expr_res(RESTRICTION_NO_BAR_OP);
3468                 self.eat(&token::DotDotDot);
3469                 let end = self.parse_expr_res(RESTRICTION_NO_BAR_OP);
3470                 pat = PatRange(start, end);
3471             } else if self.token.is_plain_ident() && !can_be_enum_or_struct {
3472                 let id = self.parse_ident();
3473                 let id_span = self.last_span;
3474                 let pth1 = codemap::Spanned{span:id_span, node: id};
3475                 if self.eat(&token::Not) {
3476                     // macro invocation
3477                     let delim = self.expect_open_delim();
3478                     let tts = self.parse_seq_to_end(&token::CloseDelim(delim),
3479                                                     seq_sep_none(),
3480                                                     |p| p.parse_token_tree());
3481
3482                     let mac = MacInvocTT(ident_to_path(id_span,id), tts, EMPTY_CTXT);
3483                     pat = ast::PatMac(codemap::Spanned {node: mac, span: self.span});
3484                 } else {
3485                     let sub = if self.eat(&token::At) {
3486                         // parse foo @ pat
3487                         Some(self.parse_pat())
3488                     } else {
3489                         // or just foo
3490                         None
3491                     };
3492                     pat = PatIdent(BindByValue(MutImmutable), pth1, sub);
3493                 }
3494             } else {
3495                 // parse an enum pat
3496                 let enum_path = self.parse_path(LifetimeAndTypesWithColons);
3497                 match self.token {
3498                     token::OpenDelim(token::Brace) => {
3499                         self.bump();
3500                         let (fields, etc) =
3501                             self.parse_pat_fields();
3502                         self.bump();
3503                         pat = PatStruct(enum_path, fields, etc);
3504                     }
3505                     _ => {
3506                         let mut args: Vec<P<Pat>> = Vec::new();
3507                         match self.token {
3508                           token::OpenDelim(token::Paren) => {
3509                             let is_dotdot = self.look_ahead(1, |t| {
3510                                 match *t {
3511                                     token::DotDot => true,
3512                                     _ => false,
3513                                 }
3514                             });
3515                             if is_dotdot {
3516                                 // This is a "top constructor only" pat
3517                                 self.bump();
3518                                 self.bump();
3519                                 self.expect(&token::CloseDelim(token::Paren));
3520                                 pat = PatEnum(enum_path, None);
3521                             } else {
3522                                 args = self.parse_enum_variant_seq(
3523                                     &token::OpenDelim(token::Paren),
3524                                     &token::CloseDelim(token::Paren),
3525                                     seq_sep_trailing_allowed(token::Comma),
3526                                     |p| p.parse_pat()
3527                                 );
3528                                 pat = PatEnum(enum_path, Some(args));
3529                             }
3530                           },
3531                           _ => {
3532                               if !enum_path.global &&
3533                                   enum_path.segments.len() == 1 &&
3534                                   enum_path.segments[0].parameters.is_empty()
3535                               {
3536                                   // it could still be either an enum
3537                                   // or an identifier pattern, resolve
3538                                   // will sort it out:
3539                                   pat = PatIdent(BindByValue(MutImmutable),
3540                                                  codemap::Spanned{
3541                                                     span: enum_path.span,
3542                                                     node: enum_path.segments[0]
3543                                                            .identifier},
3544                                                  None);
3545                               } else {
3546                                   pat = PatEnum(enum_path, Some(args));
3547                               }
3548                           }
3549                         }
3550                     }
3551                 }
3552             }
3553         }
3554         hi = self.last_span.hi;
3555         P(ast::Pat {
3556             id: ast::DUMMY_NODE_ID,
3557             node: pat,
3558             span: mk_sp(lo, hi),
3559         })
3560     }
3561
3562     /// Parse ident or ident @ pat
3563     /// used by the copy foo and ref foo patterns to give a good
3564     /// error message when parsing mistakes like ref foo(a,b)
3565     fn parse_pat_ident(&mut self,
3566                        binding_mode: ast::BindingMode)
3567                        -> ast::Pat_ {
3568         if !self.token.is_plain_ident() {
3569             let span = self.span;
3570             let tok_str = self.this_token_to_string();
3571             self.span_fatal(span,
3572                             &format!("expected identifier, found `{}`", tok_str)[]);
3573         }
3574         let ident = self.parse_ident();
3575         let last_span = self.last_span;
3576         let name = codemap::Spanned{span: last_span, node: ident};
3577         let sub = if self.eat(&token::At) {
3578             Some(self.parse_pat())
3579         } else {
3580             None
3581         };
3582
3583         // just to be friendly, if they write something like
3584         //   ref Some(i)
3585         // we end up here with ( as the current token.  This shortly
3586         // leads to a parse error.  Note that if there is no explicit
3587         // binding mode then we do not end up here, because the lookahead
3588         // will direct us over to parse_enum_variant()
3589         if self.token == token::OpenDelim(token::Paren) {
3590             let last_span = self.last_span;
3591             self.span_fatal(
3592                 last_span,
3593                 "expected identifier, found enum pattern");
3594         }
3595
3596         PatIdent(binding_mode, name, sub)
3597     }
3598
3599     /// Parse a local variable declaration
3600     fn parse_local(&mut self) -> P<Local> {
3601         let lo = self.span.lo;
3602         let pat = self.parse_pat();
3603
3604         let mut ty = None;
3605         if self.eat(&token::Colon) {
3606             ty = Some(self.parse_ty_sum());
3607         }
3608         let init = self.parse_initializer();
3609         P(ast::Local {
3610             ty: ty,
3611             pat: pat,
3612             init: init,
3613             id: ast::DUMMY_NODE_ID,
3614             span: mk_sp(lo, self.last_span.hi),
3615             source: LocalLet,
3616         })
3617     }
3618
3619     /// Parse a "let" stmt
3620     fn parse_let(&mut self) -> P<Decl> {
3621         let lo = self.span.lo;
3622         let local = self.parse_local();
3623         P(spanned(lo, self.last_span.hi, DeclLocal(local)))
3624     }
3625
3626     /// Parse a structure field
3627     fn parse_name_and_ty(&mut self, pr: Visibility,
3628                          attrs: Vec<Attribute> ) -> StructField {
3629         let lo = self.span.lo;
3630         if !self.token.is_plain_ident() {
3631             self.fatal("expected ident");
3632         }
3633         let name = self.parse_ident();
3634         self.expect(&token::Colon);
3635         let ty = self.parse_ty_sum();
3636         spanned(lo, self.last_span.hi, ast::StructField_ {
3637             kind: NamedField(name, pr),
3638             id: ast::DUMMY_NODE_ID,
3639             ty: ty,
3640             attrs: attrs,
3641         })
3642     }
3643
3644     /// Get an expected item after attributes error message.
3645     fn expected_item_err(attrs: &[Attribute]) -> &'static str {
3646         match attrs.last() {
3647             Some(&Attribute { node: ast::Attribute_ { is_sugared_doc: true, .. }, .. }) => {
3648                 "expected item after doc comment"
3649             }
3650             _ => "expected item after attributes",
3651         }
3652     }
3653
3654     /// Parse a statement. may include decl.
3655     /// Precondition: any attributes are parsed already
3656     pub fn parse_stmt(&mut self, item_attrs: Vec<Attribute>) -> P<Stmt> {
3657         maybe_whole!(self, NtStmt);
3658
3659         fn check_expected_item(p: &mut Parser, attrs: &[Attribute]) {
3660             // If we have attributes then we should have an item
3661             if !attrs.is_empty() {
3662                 let last_span = p.last_span;
3663                 p.span_err(last_span, Parser::expected_item_err(attrs));
3664             }
3665         }
3666
3667         let lo = self.span.lo;
3668         if self.token.is_keyword(keywords::Let) {
3669             check_expected_item(self, &item_attrs[]);
3670             self.expect_keyword(keywords::Let);
3671             let decl = self.parse_let();
3672             P(spanned(lo, decl.span.hi, StmtDecl(decl, ast::DUMMY_NODE_ID)))
3673         } else if self.token.is_ident()
3674             && !self.token.is_any_keyword()
3675             && self.look_ahead(1, |t| *t == token::Not) {
3676             // it's a macro invocation:
3677
3678             check_expected_item(self, &item_attrs[]);
3679
3680             // Potential trouble: if we allow macros with paths instead of
3681             // idents, we'd need to look ahead past the whole path here...
3682             let pth = self.parse_path(NoTypesAllowed);
3683             self.bump();
3684
3685             let id = match self.token {
3686                 token::OpenDelim(_) => token::special_idents::invalid, // no special identifier
3687                 _ => self.parse_ident(),
3688             };
3689
3690             // check that we're pointing at delimiters (need to check
3691             // again after the `if`, because of `parse_ident`
3692             // consuming more tokens).
3693             let delim = match self.token {
3694                 token::OpenDelim(delim) => delim,
3695                 _ => {
3696                     // we only expect an ident if we didn't parse one
3697                     // above.
3698                     let ident_str = if id.name == token::special_idents::invalid.name {
3699                         "identifier, "
3700                     } else {
3701                         ""
3702                     };
3703                     let tok_str = self.this_token_to_string();
3704                     self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
3705                                        ident_str,
3706                                        tok_str)[])
3707                 },
3708             };
3709
3710             let tts = self.parse_unspanned_seq(
3711                 &token::OpenDelim(delim),
3712                 &token::CloseDelim(delim),
3713                 seq_sep_none(),
3714                 |p| p.parse_token_tree()
3715             );
3716             let hi = self.span.hi;
3717
3718             let style = if delim == token::Brace {
3719                 MacStmtWithBraces
3720             } else {
3721                 MacStmtWithoutBraces
3722             };
3723
3724             if id.name == token::special_idents::invalid.name {
3725                 P(spanned(lo,
3726                           hi,
3727                           StmtMac(P(spanned(lo,
3728                                           hi,
3729                                           MacInvocTT(pth, tts, EMPTY_CTXT))),
3730                                   style)))
3731             } else {
3732                 // if it has a special ident, it's definitely an item
3733                 //
3734                 // Require a semicolon or braces.
3735                 if style != MacStmtWithBraces {
3736                     if !self.eat(&token::Semi) {
3737                         let last_span = self.last_span;
3738                         self.span_err(last_span,
3739                                       "macros that expand to items must \
3740                                        either be surrounded with braces or \
3741                                        followed by a semicolon");
3742                     }
3743                 }
3744                 P(spanned(lo, hi, StmtDecl(
3745                     P(spanned(lo, hi, DeclItem(
3746                         self.mk_item(
3747                             lo, hi, id /*id is good here*/,
3748                             ItemMac(spanned(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT))),
3749                             Inherited, Vec::new(/*no attrs*/))))),
3750                     ast::DUMMY_NODE_ID)))
3751             }
3752         } else {
3753             let found_attrs = !item_attrs.is_empty();
3754             let item_err = Parser::expected_item_err(&item_attrs[]);
3755             match self.parse_item_or_view_item(item_attrs, false) {
3756                 IoviItem(i) => {
3757                     let hi = i.span.hi;
3758                     let decl = P(spanned(lo, hi, DeclItem(i)));
3759                     P(spanned(lo, hi, StmtDecl(decl, ast::DUMMY_NODE_ID)))
3760                 }
3761                 IoviViewItem(vi) => {
3762                     self.span_fatal(vi.span,
3763                                     "view items must be declared at the top of the block");
3764                 }
3765                 IoviForeignItem(_) => {
3766                     self.fatal("foreign items are not allowed here");
3767                 }
3768                 IoviNone(_) => {
3769                     if found_attrs {
3770                         let last_span = self.last_span;
3771                         self.span_err(last_span, item_err);
3772                     }
3773
3774                     // Remainder are line-expr stmts.
3775                     let e = self.parse_expr_res(RESTRICTION_STMT_EXPR);
3776                     P(spanned(lo, e.span.hi, StmtExpr(e, ast::DUMMY_NODE_ID)))
3777                 }
3778             }
3779         }
3780     }
3781
3782     /// Is this expression a successfully-parsed statement?
3783     fn expr_is_complete(&mut self, e: &Expr) -> bool {
3784         self.restrictions.contains(RESTRICTION_STMT_EXPR) &&
3785             !classify::expr_requires_semi_to_be_stmt(e)
3786     }
3787
3788     /// Parse a block. No inner attrs are allowed.
3789     pub fn parse_block(&mut self) -> P<Block> {
3790         maybe_whole!(no_clone self, NtBlock);
3791
3792         let lo = self.span.lo;
3793
3794         if !self.eat(&token::OpenDelim(token::Brace)) {
3795             let sp = self.span;
3796             let tok = self.this_token_to_string();
3797             self.span_fatal_help(sp,
3798                                  &format!("expected `{{`, found `{}`", tok)[],
3799                                  "place this code inside a block");
3800         }
3801
3802         return self.parse_block_tail_(lo, DefaultBlock, Vec::new());
3803     }
3804
3805     /// Parse a block. Inner attrs are allowed.
3806     fn parse_inner_attrs_and_block(&mut self)
3807         -> (Vec<Attribute> , P<Block>) {
3808
3809         maybe_whole!(pair_empty self, NtBlock);
3810
3811         let lo = self.span.lo;
3812         self.expect(&token::OpenDelim(token::Brace));
3813         let (inner, next) = self.parse_inner_attrs_and_next();
3814
3815         (inner, self.parse_block_tail_(lo, DefaultBlock, next))
3816     }
3817
3818     /// Precondition: already parsed the '{' or '#{'
3819     /// I guess that also means "already parsed the 'impure'" if
3820     /// necessary, and this should take a qualifier.
3821     /// Some blocks start with "#{"...
3822     fn parse_block_tail(&mut self, lo: BytePos, s: BlockCheckMode) -> P<Block> {
3823         self.parse_block_tail_(lo, s, Vec::new())
3824     }
3825
3826     /// Parse the rest of a block expression or function body
3827     fn parse_block_tail_(&mut self, lo: BytePos, s: BlockCheckMode,
3828                          first_item_attrs: Vec<Attribute> ) -> P<Block> {
3829         let mut stmts = Vec::new();
3830         let mut expr = None;
3831
3832         // wouldn't it be more uniform to parse view items only, here?
3833         let ParsedItemsAndViewItems {
3834             attrs_remaining,
3835             view_items,
3836             items,
3837             ..
3838         } = self.parse_items_and_view_items(first_item_attrs,
3839                                             false, false);
3840
3841         for item in items.into_iter() {
3842             let span = item.span;
3843             let decl = P(spanned(span.lo, span.hi, DeclItem(item)));
3844             stmts.push(P(spanned(span.lo, span.hi, StmtDecl(decl, ast::DUMMY_NODE_ID))));
3845         }
3846
3847         let mut attributes_box = attrs_remaining;
3848
3849         while self.token != token::CloseDelim(token::Brace) {
3850             // parsing items even when they're not allowed lets us give
3851             // better error messages and recover more gracefully.
3852             attributes_box.push_all(&self.parse_outer_attributes()[]);
3853             match self.token {
3854                 token::Semi => {
3855                     if !attributes_box.is_empty() {
3856                         let last_span = self.last_span;
3857                         self.span_err(last_span,
3858                                       Parser::expected_item_err(&attributes_box[]));
3859                         attributes_box = Vec::new();
3860                     }
3861                     self.bump(); // empty
3862                 }
3863                 token::CloseDelim(token::Brace) => {
3864                     // fall through and out.
3865                 }
3866                 _ => {
3867                     let stmt = self.parse_stmt(attributes_box);
3868                     attributes_box = Vec::new();
3869                     stmt.and_then(|Spanned {node, span}| match node {
3870                         StmtExpr(e, stmt_id) => {
3871                             self.handle_expression_like_statement(e,
3872                                                                   stmt_id,
3873                                                                   span,
3874                                                                   &mut stmts,
3875                                                                   &mut expr);
3876                         }
3877                         StmtMac(mac, MacStmtWithoutBraces) => {
3878                             // statement macro without braces; might be an
3879                             // expr depending on whether a semicolon follows
3880                             match self.token {
3881                                 token::Semi => {
3882                                     stmts.push(P(Spanned {
3883                                         node: StmtMac(mac,
3884                                                       MacStmtWithSemicolon),
3885                                         span: span,
3886                                     }));
3887                                     self.bump();
3888                                 }
3889                                 _ => {
3890                                     let e = self.mk_mac_expr(span.lo,
3891                                                              span.hi,
3892                                                              mac.and_then(|m| m.node));
3893                                     let e = self.parse_dot_or_call_expr_with(e);
3894                                     let e = self.parse_more_binops(e, 0);
3895                                     let e = self.parse_assign_expr_with(e);
3896                                     self.handle_expression_like_statement(
3897                                         e,
3898                                         ast::DUMMY_NODE_ID,
3899                                         span,
3900                                         &mut stmts,
3901                                         &mut expr);
3902                                 }
3903                             }
3904                         }
3905                         StmtMac(m, style) => {
3906                             // statement macro; might be an expr
3907                             match self.token {
3908                                 token::Semi => {
3909                                     stmts.push(P(Spanned {
3910                                         node: StmtMac(m,
3911                                                       MacStmtWithSemicolon),
3912                                         span: span,
3913                                     }));
3914                                     self.bump();
3915                                 }
3916                                 token::CloseDelim(token::Brace) => {
3917                                     // if a block ends in `m!(arg)` without
3918                                     // a `;`, it must be an expr
3919                                     expr = Some(
3920                                         self.mk_mac_expr(span.lo,
3921                                                          span.hi,
3922                                                          m.and_then(|x| x.node)));
3923                                 }
3924                                 _ => {
3925                                     stmts.push(P(Spanned {
3926                                         node: StmtMac(m, style),
3927                                         span: span
3928                                     }));
3929                                 }
3930                             }
3931                         }
3932                         _ => { // all other kinds of statements:
3933                             if classify::stmt_ends_with_semi(&node) {
3934                                 self.commit_stmt_expecting(token::Semi);
3935                             }
3936
3937                             stmts.push(P(Spanned {
3938                                 node: node,
3939                                 span: span
3940                             }));
3941                         }
3942                     })
3943                 }
3944             }
3945         }
3946
3947         if !attributes_box.is_empty() {
3948             let last_span = self.last_span;
3949             self.span_err(last_span,
3950                           Parser::expected_item_err(&attributes_box[]));
3951         }
3952
3953         let hi = self.span.hi;
3954         self.bump();
3955         P(ast::Block {
3956             view_items: view_items,
3957             stmts: stmts,
3958             expr: expr,
3959             id: ast::DUMMY_NODE_ID,
3960             rules: s,
3961             span: mk_sp(lo, hi),
3962         })
3963     }
3964
3965     fn handle_expression_like_statement(
3966             &mut self,
3967             e: P<Expr>,
3968             stmt_id: NodeId,
3969             span: Span,
3970             stmts: &mut Vec<P<Stmt>>,
3971             last_block_expr: &mut Option<P<Expr>>) {
3972         // expression without semicolon
3973         if classify::expr_requires_semi_to_be_stmt(&*e) {
3974             // Just check for errors and recover; do not eat semicolon yet.
3975             self.commit_stmt(&[],
3976                              &[token::Semi, token::CloseDelim(token::Brace)]);
3977         }
3978
3979         match self.token {
3980             token::Semi => {
3981                 self.bump();
3982                 let span_with_semi = Span {
3983                     lo: span.lo,
3984                     hi: self.last_span.hi,
3985                     expn_id: span.expn_id,
3986                 };
3987                 stmts.push(P(Spanned {
3988                     node: StmtSemi(e, stmt_id),
3989                     span: span_with_semi,
3990                 }));
3991             }
3992             token::CloseDelim(token::Brace) => *last_block_expr = Some(e),
3993             _ => {
3994                 stmts.push(P(Spanned {
3995                     node: StmtExpr(e, stmt_id),
3996                     span: span
3997                 }));
3998             }
3999         }
4000     }
4001
4002     // Parses a sequence of bounds if a `:` is found,
4003     // otherwise returns empty list.
4004     fn parse_colon_then_ty_param_bounds(&mut self,
4005                                         mode: BoundParsingMode)
4006                                         -> OwnedSlice<TyParamBound>
4007     {
4008         if !self.eat(&token::Colon) {
4009             OwnedSlice::empty()
4010         } else {
4011             self.parse_ty_param_bounds(mode)
4012         }
4013     }
4014
4015     // matches bounds    = ( boundseq )?
4016     // where   boundseq  = ( polybound + boundseq ) | polybound
4017     // and     polybound = ( 'for' '<' 'region '>' )? bound
4018     // and     bound     = 'region | trait_ref
4019     fn parse_ty_param_bounds(&mut self,
4020                              mode: BoundParsingMode)
4021                              -> OwnedSlice<TyParamBound>
4022     {
4023         let mut result = vec!();
4024         loop {
4025             let question_span = self.span;
4026             let ate_question = self.eat(&token::Question);
4027             match self.token {
4028                 token::Lifetime(lifetime) => {
4029                     if ate_question {
4030                         self.span_err(question_span,
4031                                       "`?` may only modify trait bounds, not lifetime bounds");
4032                     }
4033                     result.push(RegionTyParamBound(ast::Lifetime {
4034                         id: ast::DUMMY_NODE_ID,
4035                         span: self.span,
4036                         name: lifetime.name
4037                     }));
4038                     self.bump();
4039                 }
4040                 token::ModSep | token::Ident(..) => {
4041                     let poly_trait_ref = self.parse_poly_trait_ref();
4042                     let modifier = if ate_question {
4043                         if mode == BoundParsingMode::Modified {
4044                             TraitBoundModifier::Maybe
4045                         } else {
4046                             self.span_err(question_span,
4047                                           "unexpected `?`");
4048                             TraitBoundModifier::None
4049                         }
4050                     } else {
4051                         TraitBoundModifier::None
4052                     };
4053                     result.push(TraitTyParamBound(poly_trait_ref, modifier))
4054                 }
4055                 _ => break,
4056             }
4057
4058             if !self.eat(&token::BinOp(token::Plus)) {
4059                 break;
4060             }
4061         }
4062
4063         return OwnedSlice::from_vec(result);
4064     }
4065
4066     fn trait_ref_from_ident(ident: Ident, span: Span) -> TraitRef {
4067         let segment = ast::PathSegment {
4068             identifier: ident,
4069             parameters: ast::PathParameters::none()
4070         };
4071         let path = ast::Path {
4072             span: span,
4073             global: false,
4074             segments: vec![segment],
4075         };
4076         ast::TraitRef {
4077             path: path,
4078             ref_id: ast::DUMMY_NODE_ID,
4079         }
4080     }
4081
4082     /// Matches typaram = (unbound `?`)? IDENT (`?` unbound)? optbounds ( EQ ty )?
4083     fn parse_ty_param(&mut self) -> TyParam {
4084         // This is a bit hacky. Currently we are only interested in a single
4085         // unbound, and it may only be `Sized`. To avoid backtracking and other
4086         // complications, we parse an ident, then check for `?`. If we find it,
4087         // we use the ident as the unbound, otherwise, we use it as the name of
4088         // type param. Even worse, we need to check for `?` before or after the
4089         // bound.
4090         let mut span = self.span;
4091         let mut ident = self.parse_ident();
4092         let mut unbound = None;
4093         if self.eat(&token::Question) {
4094             let tref = Parser::trait_ref_from_ident(ident, span);
4095             unbound = Some(tref);
4096             span = self.span;
4097             ident = self.parse_ident();
4098             self.obsolete(span, ObsoleteSyntax::Sized);
4099         }
4100
4101         let mut bounds = self.parse_colon_then_ty_param_bounds(BoundParsingMode::Modified);
4102         if let Some(unbound) = unbound {
4103             let mut bounds_as_vec = bounds.into_vec();
4104             bounds_as_vec.push(TraitTyParamBound(PolyTraitRef { bound_lifetimes: vec![],
4105                                                                 trait_ref: unbound },
4106                                                  TraitBoundModifier::Maybe));
4107             bounds = OwnedSlice::from_vec(bounds_as_vec);
4108         };
4109
4110         let default = if self.check(&token::Eq) {
4111             self.bump();
4112             Some(self.parse_ty_sum())
4113         }
4114         else { None };
4115
4116         TyParam {
4117             ident: ident,
4118             id: ast::DUMMY_NODE_ID,
4119             bounds: bounds,
4120             default: default,
4121             span: span,
4122         }
4123     }
4124
4125     /// Parse a set of optional generic type parameter declarations. Where
4126     /// clauses are not parsed here, and must be added later via
4127     /// `parse_where_clause()`.
4128     ///
4129     /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
4130     ///                  | ( < lifetimes , typaramseq ( , )? > )
4131     /// where   typaramseq = ( typaram ) | ( typaram , typaramseq )
4132     pub fn parse_generics(&mut self) -> ast::Generics {
4133         if self.eat(&token::Lt) {
4134             let lifetime_defs = self.parse_lifetime_defs();
4135             let mut seen_default = false;
4136             let ty_params = self.parse_seq_to_gt(Some(token::Comma), |p| {
4137                 p.forbid_lifetime();
4138                 let ty_param = p.parse_ty_param();
4139                 if ty_param.default.is_some() {
4140                     seen_default = true;
4141                 } else if seen_default {
4142                     let last_span = p.last_span;
4143                     p.span_err(last_span,
4144                                "type parameters with a default must be trailing");
4145                 }
4146                 ty_param
4147             });
4148             ast::Generics {
4149                 lifetimes: lifetime_defs,
4150                 ty_params: ty_params,
4151                 where_clause: WhereClause {
4152                     id: ast::DUMMY_NODE_ID,
4153                     predicates: Vec::new(),
4154                 }
4155             }
4156         } else {
4157             ast_util::empty_generics()
4158         }
4159     }
4160
4161     fn parse_generic_values_after_lt(&mut self)
4162                                      -> (Vec<ast::Lifetime>, Vec<P<Ty>>, Vec<P<TypeBinding>>) {
4163         let lifetimes = self.parse_lifetimes(token::Comma);
4164
4165         // First parse types.
4166         let (types, returned) = self.parse_seq_to_gt_or_return(
4167             Some(token::Comma),
4168             |p| {
4169                 p.forbid_lifetime();
4170                 if p.look_ahead(1, |t| t == &token::Eq) {
4171                     None
4172                 } else {
4173                     Some(p.parse_ty_sum())
4174                 }
4175             }
4176         );
4177
4178         // If we found the `>`, don't continue.
4179         if !returned {
4180             return (lifetimes, types.into_vec(), Vec::new());
4181         }
4182
4183         // Then parse type bindings.
4184         let bindings = self.parse_seq_to_gt(
4185             Some(token::Comma),
4186             |p| {
4187                 p.forbid_lifetime();
4188                 let lo = p.span.lo;
4189                 let ident = p.parse_ident();
4190                 let found_eq = p.eat(&token::Eq);
4191                 if !found_eq {
4192                     let span = p.span;
4193                     p.span_warn(span, "whoops, no =?");
4194                 }
4195                 let ty = p.parse_ty();
4196                 let hi = p.span.hi;
4197                 let span = mk_sp(lo, hi);
4198                 return P(TypeBinding{id: ast::DUMMY_NODE_ID,
4199                     ident: ident,
4200                     ty: ty,
4201                     span: span,
4202                 });
4203             }
4204         );
4205         (lifetimes, types.into_vec(), bindings.into_vec())
4206     }
4207
4208     fn forbid_lifetime(&mut self) {
4209         if self.token.is_lifetime() {
4210             let span = self.span;
4211             self.span_fatal(span, "lifetime parameters must be declared \
4212                                         prior to type parameters");
4213         }
4214     }
4215
4216     /// Parses an optional `where` clause and places it in `generics`.
4217     ///
4218     /// ```
4219     /// where T : Trait<U, V> + 'b, 'a : 'b
4220     /// ```
4221     fn parse_where_clause(&mut self, generics: &mut ast::Generics) {
4222         if !self.eat_keyword(keywords::Where) {
4223             return
4224         }
4225
4226         let mut parsed_something = false;
4227         loop {
4228             let lo = self.span.lo;
4229             match self.token {
4230                 token::OpenDelim(token::Brace) => {
4231                     break
4232                 }
4233
4234                 token::Lifetime(..) => {
4235                     let bounded_lifetime =
4236                         self.parse_lifetime();
4237
4238                     self.eat(&token::Colon);
4239
4240                     let bounds =
4241                         self.parse_lifetimes(token::BinOp(token::Plus));
4242
4243                     let hi = self.span.hi;
4244                     let span = mk_sp(lo, hi);
4245
4246                     generics.where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
4247                         ast::WhereRegionPredicate {
4248                             span: span,
4249                             lifetime: bounded_lifetime,
4250                             bounds: bounds
4251                         }
4252                     ));
4253
4254                     parsed_something = true;
4255                 }
4256
4257                 _ => {
4258                     let bounded_ty = self.parse_ty();
4259
4260                     if self.eat(&token::Colon) {
4261                         let bounds = self.parse_ty_param_bounds(BoundParsingMode::Bare);
4262                         let hi = self.span.hi;
4263                         let span = mk_sp(lo, hi);
4264
4265                         if bounds.len() == 0 {
4266                             self.span_err(span,
4267                                           "each predicate in a `where` clause must have \
4268                                    at least one bound in it");
4269                         }
4270
4271                         generics.where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
4272                                 ast::WhereBoundPredicate {
4273                                     span: span,
4274                                     bounded_ty: bounded_ty,
4275                                     bounds: bounds,
4276                         }));
4277
4278                         parsed_something = true;
4279                     } else if self.eat(&token::Eq) {
4280                         // let ty = self.parse_ty();
4281                         let hi = self.span.hi;
4282                         let span = mk_sp(lo, hi);
4283                         // generics.where_clause.predicates.push(
4284                         //     ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
4285                         //         id: ast::DUMMY_NODE_ID,
4286                         //         span: span,
4287                         //         path: panic!("NYI"), //bounded_ty,
4288                         //         ty: ty,
4289                         // }));
4290                         // parsed_something = true;
4291                         // // FIXME(#18433)
4292                         self.span_err(span,
4293                                      "equality constraints are not yet supported \
4294                                      in where clauses (#20041)");
4295                     } else {
4296                         let last_span = self.last_span;
4297                         self.span_err(last_span,
4298                               "unexpected token in `where` clause");
4299                     }
4300                 }
4301             };
4302
4303             if !self.eat(&token::Comma) {
4304                 break
4305             }
4306         }
4307
4308         if !parsed_something {
4309             let last_span = self.last_span;
4310             self.span_err(last_span,
4311                           "a `where` clause must have at least one predicate \
4312                            in it");
4313         }
4314     }
4315
4316     fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
4317                      -> (Vec<Arg> , bool) {
4318         let sp = self.span;
4319         let mut args: Vec<Option<Arg>> =
4320             self.parse_unspanned_seq(
4321                 &token::OpenDelim(token::Paren),
4322                 &token::CloseDelim(token::Paren),
4323                 seq_sep_trailing_allowed(token::Comma),
4324                 |p| {
4325                     if p.token == token::DotDotDot {
4326                         p.bump();
4327                         if allow_variadic {
4328                             if p.token != token::CloseDelim(token::Paren) {
4329                                 let span = p.span;
4330                                 p.span_fatal(span,
4331                                     "`...` must be last in argument list for variadic function");
4332                             }
4333                         } else {
4334                             let span = p.span;
4335                             p.span_fatal(span,
4336                                          "only foreign functions are allowed to be variadic");
4337                         }
4338                         None
4339                     } else {
4340                         Some(p.parse_arg_general(named_args))
4341                     }
4342                 }
4343             );
4344
4345         let variadic = match args.pop() {
4346             Some(None) => true,
4347             Some(x) => {
4348                 // Need to put back that last arg
4349                 args.push(x);
4350                 false
4351             }
4352             None => false
4353         };
4354
4355         if variadic && args.is_empty() {
4356             self.span_err(sp,
4357                           "variadic function must be declared with at least one named argument");
4358         }
4359
4360         let args = args.into_iter().map(|x| x.unwrap()).collect();
4361
4362         (args, variadic)
4363     }
4364
4365     /// Parse the argument list and result type of a function declaration
4366     pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> P<FnDecl> {
4367
4368         let (args, variadic) = self.parse_fn_args(true, allow_variadic);
4369         let ret_ty = self.parse_ret_ty();
4370
4371         P(FnDecl {
4372             inputs: args,
4373             output: ret_ty,
4374             variadic: variadic
4375         })
4376     }
4377
4378     fn is_self_ident(&mut self) -> bool {
4379         match self.token {
4380           token::Ident(id, token::Plain) => id.name == special_idents::self_.name,
4381           _ => false
4382         }
4383     }
4384
4385     fn expect_self_ident(&mut self) -> ast::Ident {
4386         match self.token {
4387             token::Ident(id, token::Plain) if id.name == special_idents::self_.name => {
4388                 self.bump();
4389                 id
4390             },
4391             _ => {
4392                 let token_str = self.this_token_to_string();
4393                 self.fatal(&format!("expected `self`, found `{}`",
4394                                    token_str)[])
4395             }
4396         }
4397     }
4398
4399     /// Parse the argument list and result type of a function
4400     /// that may have a self type.
4401     fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> (ExplicitSelf, P<FnDecl>) where
4402         F: FnMut(&mut Parser) -> Arg,
4403     {
4404         fn maybe_parse_borrowed_explicit_self(this: &mut Parser)
4405                                               -> ast::ExplicitSelf_ {
4406             // The following things are possible to see here:
4407             //
4408             //     fn(&mut self)
4409             //     fn(&mut self)
4410             //     fn(&'lt self)
4411             //     fn(&'lt mut self)
4412             //
4413             // We already know that the current token is `&`.
4414
4415             if this.look_ahead(1, |t| t.is_keyword(keywords::Self)) {
4416                 this.bump();
4417                 SelfRegion(None, MutImmutable, this.expect_self_ident())
4418             } else if this.look_ahead(1, |t| t.is_mutability()) &&
4419                       this.look_ahead(2, |t| t.is_keyword(keywords::Self)) {
4420                 this.bump();
4421                 let mutability = this.parse_mutability();
4422                 SelfRegion(None, mutability, this.expect_self_ident())
4423             } else if this.look_ahead(1, |t| t.is_lifetime()) &&
4424                       this.look_ahead(2, |t| t.is_keyword(keywords::Self)) {
4425                 this.bump();
4426                 let lifetime = this.parse_lifetime();
4427                 SelfRegion(Some(lifetime), MutImmutable, this.expect_self_ident())
4428             } else if this.look_ahead(1, |t| t.is_lifetime()) &&
4429                       this.look_ahead(2, |t| t.is_mutability()) &&
4430                       this.look_ahead(3, |t| t.is_keyword(keywords::Self)) {
4431                 this.bump();
4432                 let lifetime = this.parse_lifetime();
4433                 let mutability = this.parse_mutability();
4434                 SelfRegion(Some(lifetime), mutability, this.expect_self_ident())
4435             } else {
4436                 SelfStatic
4437             }
4438         }
4439
4440         self.expect(&token::OpenDelim(token::Paren));
4441
4442         // A bit of complexity and lookahead is needed here in order to be
4443         // backwards compatible.
4444         let lo = self.span.lo;
4445         let mut self_ident_lo = self.span.lo;
4446         let mut self_ident_hi = self.span.hi;
4447
4448         let mut mutbl_self = MutImmutable;
4449         let explicit_self = match self.token {
4450             token::BinOp(token::And) => {
4451                 let eself = maybe_parse_borrowed_explicit_self(self);
4452                 self_ident_lo = self.last_span.lo;
4453                 self_ident_hi = self.last_span.hi;
4454                 eself
4455             }
4456             token::Tilde => {
4457                 // We need to make sure it isn't a type
4458                 if self.look_ahead(1, |t| t.is_keyword(keywords::Self)) {
4459                     self.bump();
4460                     drop(self.expect_self_ident());
4461                     let last_span = self.last_span;
4462                     self.obsolete(last_span, ObsoleteSyntax::OwnedSelf)
4463                 }
4464                 SelfStatic
4465             }
4466             token::BinOp(token::Star) => {
4467                 // Possibly "*self" or "*mut self" -- not supported. Try to avoid
4468                 // emitting cryptic "unexpected token" errors.
4469                 self.bump();
4470                 let _mutability = if self.token.is_mutability() {
4471                     self.parse_mutability()
4472                 } else {
4473                     MutImmutable
4474                 };
4475                 if self.is_self_ident() {
4476                     let span = self.span;
4477                     self.span_err(span, "cannot pass self by unsafe pointer");
4478                     self.bump();
4479                 }
4480                 // error case, making bogus self ident:
4481                 SelfValue(special_idents::self_)
4482             }
4483             token::Ident(..) => {
4484                 if self.is_self_ident() {
4485                     let self_ident = self.expect_self_ident();
4486
4487                     // Determine whether this is the fully explicit form, `self:
4488                     // TYPE`.
4489                     if self.eat(&token::Colon) {
4490                         SelfExplicit(self.parse_ty_sum(), self_ident)
4491                     } else {
4492                         SelfValue(self_ident)
4493                     }
4494                 } else if self.token.is_mutability() &&
4495                         self.look_ahead(1, |t| t.is_keyword(keywords::Self)) {
4496                     mutbl_self = self.parse_mutability();
4497                     let self_ident = self.expect_self_ident();
4498
4499                     // Determine whether this is the fully explicit form,
4500                     // `self: TYPE`.
4501                     if self.eat(&token::Colon) {
4502                         SelfExplicit(self.parse_ty_sum(), self_ident)
4503                     } else {
4504                         SelfValue(self_ident)
4505                     }
4506                 } else if self.token.is_mutability() &&
4507                         self.look_ahead(1, |t| *t == token::Tilde) &&
4508                         self.look_ahead(2, |t| t.is_keyword(keywords::Self)) {
4509                     mutbl_self = self.parse_mutability();
4510                     self.bump();
4511                     drop(self.expect_self_ident());
4512                     let last_span = self.last_span;
4513                     self.obsolete(last_span, ObsoleteSyntax::OwnedSelf);
4514                     SelfStatic
4515                 } else {
4516                     SelfStatic
4517                 }
4518             }
4519             _ => SelfStatic,
4520         };
4521
4522         let explicit_self_sp = mk_sp(self_ident_lo, self_ident_hi);
4523
4524         // shared fall-through for the three cases below. borrowing prevents simply
4525         // writing this as a closure
4526         macro_rules! parse_remaining_arguments {
4527             ($self_id:ident) =>
4528             {
4529             // If we parsed a self type, expect a comma before the argument list.
4530             match self.token {
4531                 token::Comma => {
4532                     self.bump();
4533                     let sep = seq_sep_trailing_allowed(token::Comma);
4534                     let mut fn_inputs = self.parse_seq_to_before_end(
4535                         &token::CloseDelim(token::Paren),
4536                         sep,
4537                         parse_arg_fn
4538                     );
4539                     fn_inputs.insert(0, Arg::new_self(explicit_self_sp, mutbl_self, $self_id));
4540                     fn_inputs
4541                 }
4542                 token::CloseDelim(token::Paren) => {
4543                     vec!(Arg::new_self(explicit_self_sp, mutbl_self, $self_id))
4544                 }
4545                 _ => {
4546                     let token_str = self.this_token_to_string();
4547                     self.fatal(&format!("expected `,` or `)`, found `{}`",
4548                                        token_str)[])
4549                 }
4550             }
4551             }
4552         }
4553
4554         let fn_inputs = match explicit_self {
4555             SelfStatic =>  {
4556                 let sep = seq_sep_trailing_allowed(token::Comma);
4557                 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)
4558             }
4559             SelfValue(id) => parse_remaining_arguments!(id),
4560             SelfRegion(_,_,id) => parse_remaining_arguments!(id),
4561             SelfExplicit(_,id) => parse_remaining_arguments!(id),
4562         };
4563
4564
4565         self.expect(&token::CloseDelim(token::Paren));
4566
4567         let hi = self.span.hi;
4568
4569         let ret_ty = self.parse_ret_ty();
4570
4571         let fn_decl = P(FnDecl {
4572             inputs: fn_inputs,
4573             output: ret_ty,
4574             variadic: false
4575         });
4576
4577         (spanned(lo, hi, explicit_self), fn_decl)
4578     }
4579
4580     // parse the |arg, arg| header on a lambda
4581     fn parse_fn_block_decl(&mut self)
4582                            -> (P<FnDecl>, Option<UnboxedClosureKind>) {
4583         let (optional_unboxed_closure_kind, inputs_captures) = {
4584             if self.eat(&token::OrOr) {
4585                 (None, Vec::new())
4586             } else {
4587                 self.expect(&token::BinOp(token::Or));
4588                 let optional_unboxed_closure_kind =
4589                     self.parse_optional_unboxed_closure_kind();
4590                 let args = self.parse_seq_to_before_end(
4591                     &token::BinOp(token::Or),
4592                     seq_sep_trailing_allowed(token::Comma),
4593                     |p| p.parse_fn_block_arg()
4594                 );
4595                 self.bump();
4596                 (optional_unboxed_closure_kind, args)
4597             }
4598         };
4599         let output = if self.check(&token::RArrow) {
4600             self.parse_ret_ty()
4601         } else {
4602             Return(P(Ty {
4603                 id: ast::DUMMY_NODE_ID,
4604                 node: TyInfer,
4605                 span: self.span,
4606             }))
4607         };
4608
4609         (P(FnDecl {
4610             inputs: inputs_captures,
4611             output: output,
4612             variadic: false
4613         }), optional_unboxed_closure_kind)
4614     }
4615
4616     /// Parses the `(arg, arg) -> return_type` header on a procedure.
4617     fn parse_proc_decl(&mut self) -> P<FnDecl> {
4618         let inputs =
4619             self.parse_unspanned_seq(&token::OpenDelim(token::Paren),
4620                                      &token::CloseDelim(token::Paren),
4621                                      seq_sep_trailing_allowed(token::Comma),
4622                                      |p| p.parse_fn_block_arg());
4623
4624         let output = if self.check(&token::RArrow) {
4625             self.parse_ret_ty()
4626         } else {
4627             Return(P(Ty {
4628                 id: ast::DUMMY_NODE_ID,
4629                 node: TyInfer,
4630                 span: self.span,
4631             }))
4632         };
4633
4634         P(FnDecl {
4635             inputs: inputs,
4636             output: output,
4637             variadic: false
4638         })
4639     }
4640
4641     /// Parse the name and optional generic types of a function header.
4642     fn parse_fn_header(&mut self) -> (Ident, ast::Generics) {
4643         let id = self.parse_ident();
4644         let generics = self.parse_generics();
4645         (id, generics)
4646     }
4647
4648     fn mk_item(&mut self, lo: BytePos, hi: BytePos, ident: Ident,
4649                node: Item_, vis: Visibility,
4650                attrs: Vec<Attribute>) -> P<Item> {
4651         P(Item {
4652             ident: ident,
4653             attrs: attrs,
4654             id: ast::DUMMY_NODE_ID,
4655             node: node,
4656             vis: vis,
4657             span: mk_sp(lo, hi)
4658         })
4659     }
4660
4661     /// Parse an item-position function declaration.
4662     fn parse_item_fn(&mut self, unsafety: Unsafety, abi: abi::Abi) -> ItemInfo {
4663         let (ident, mut generics) = self.parse_fn_header();
4664         let decl = self.parse_fn_decl(false);
4665         self.parse_where_clause(&mut generics);
4666         let (inner_attrs, body) = self.parse_inner_attrs_and_block();
4667         (ident, ItemFn(decl, unsafety, abi, generics, body), Some(inner_attrs))
4668     }
4669
4670     /// Parse a method in a trait impl
4671     pub fn parse_method_with_outer_attributes(&mut self) -> P<Method> {
4672         let attrs = self.parse_outer_attributes();
4673         let visa = self.parse_visibility();
4674         self.parse_method(attrs, visa)
4675     }
4676
4677     /// Parse a method in a trait impl, starting with `attrs` attributes.
4678     pub fn parse_method(&mut self,
4679                         attrs: Vec<Attribute>,
4680                         visa: Visibility)
4681                         -> P<Method> {
4682         let lo = self.span.lo;
4683
4684         // code copied from parse_macro_use_or_failure... abstraction!
4685         let (method_, hi, new_attrs) = {
4686             if !self.token.is_any_keyword()
4687                 && self.look_ahead(1, |t| *t == token::Not)
4688                 && (self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren))
4689                     || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) {
4690                 // method macro.
4691                 let pth = self.parse_path(NoTypesAllowed);
4692                 self.expect(&token::Not);
4693
4694                 // eat a matched-delimiter token tree:
4695                 let delim = self.expect_open_delim();
4696                 let tts = self.parse_seq_to_end(&token::CloseDelim(delim),
4697                                                 seq_sep_none(),
4698                                                 |p| p.parse_token_tree());
4699                 let m_ = ast::MacInvocTT(pth, tts, EMPTY_CTXT);
4700                 let m: ast::Mac = codemap::Spanned { node: m_,
4701                                                  span: mk_sp(self.span.lo,
4702                                                              self.span.hi) };
4703                 if delim != token::Brace {
4704                     self.expect(&token::Semi)
4705                 }
4706                 (ast::MethMac(m), self.span.hi, attrs)
4707             } else {
4708                 let unsafety = self.parse_unsafety();
4709                 let abi = if self.eat_keyword(keywords::Extern) {
4710                     self.parse_opt_abi().unwrap_or(abi::C)
4711                 } else {
4712                     abi::Rust
4713                 };
4714                 self.expect_keyword(keywords::Fn);
4715                 let ident = self.parse_ident();
4716                 let mut generics = self.parse_generics();
4717                 let (explicit_self, decl) = self.parse_fn_decl_with_self(|p| {
4718                         p.parse_arg()
4719                     });
4720                 self.parse_where_clause(&mut generics);
4721                 let (inner_attrs, body) = self.parse_inner_attrs_and_block();
4722                 let body_span = body.span;
4723                 let mut new_attrs = attrs;
4724                 new_attrs.push_all(&inner_attrs[]);
4725                 (ast::MethDecl(ident,
4726                                generics,
4727                                abi,
4728                                explicit_self,
4729                                unsafety,
4730                                decl,
4731                                body,
4732                                visa),
4733                  body_span.hi, new_attrs)
4734             }
4735         };
4736         P(ast::Method {
4737             attrs: new_attrs,
4738             id: ast::DUMMY_NODE_ID,
4739             span: mk_sp(lo, hi),
4740             node: method_,
4741         })
4742     }
4743
4744     /// Parse trait Foo { ... }
4745     fn parse_item_trait(&mut self, unsafety: Unsafety) -> ItemInfo {
4746         let ident = self.parse_ident();
4747         let mut tps = self.parse_generics();
4748         let unbound = self.parse_for_sized();
4749
4750         // Parse supertrait bounds.
4751         let mut bounds = self.parse_colon_then_ty_param_bounds(BoundParsingMode::Bare);
4752
4753         if let Some(unbound) = unbound {
4754             let mut bounds_as_vec = bounds.into_vec();
4755             bounds_as_vec.push(TraitTyParamBound(PolyTraitRef { bound_lifetimes: vec![],
4756                                                                 trait_ref: unbound },
4757                                                  TraitBoundModifier::Maybe));
4758             bounds = OwnedSlice::from_vec(bounds_as_vec);
4759         };
4760
4761         self.parse_where_clause(&mut tps);
4762
4763         let meths = self.parse_trait_items();
4764         (ident, ItemTrait(unsafety, tps, bounds, meths), None)
4765     }
4766
4767     fn parse_impl_items(&mut self) -> (Vec<ImplItem>, Vec<Attribute>) {
4768         let mut impl_items = Vec::new();
4769         self.expect(&token::OpenDelim(token::Brace));
4770         let (inner_attrs, mut method_attrs) =
4771             self.parse_inner_attrs_and_next();
4772         loop {
4773             method_attrs.extend(self.parse_outer_attributes().into_iter());
4774             if method_attrs.is_empty() && self.eat(&token::CloseDelim(token::Brace)) {
4775                 break;
4776             }
4777
4778             let vis = self.parse_visibility();
4779             if self.eat_keyword(keywords::Type) {
4780                 impl_items.push(TypeImplItem(P(self.parse_typedef(
4781                             method_attrs,
4782                             vis))))
4783             } else {
4784                 impl_items.push(MethodImplItem(self.parse_method(
4785                             method_attrs,
4786                             vis)));
4787             }
4788             method_attrs = vec![];
4789         }
4790         (impl_items, inner_attrs)
4791     }
4792
4793     /// Parses two variants (with the region/type params always optional):
4794     ///    impl<T> Foo { ... }
4795     ///    impl<T> ToString for ~[T] { ... }
4796     fn parse_item_impl(&mut self, unsafety: ast::Unsafety) -> ItemInfo {
4797         // First, parse type parameters if necessary.
4798         let mut generics = self.parse_generics();
4799
4800         // Special case: if the next identifier that follows is '(', don't
4801         // allow this to be parsed as a trait.
4802         let could_be_trait = self.token != token::OpenDelim(token::Paren);
4803
4804         let neg_span = self.span;
4805         let polarity = if self.eat(&token::Not) {
4806             ast::ImplPolarity::Negative
4807         } else {
4808             ast::ImplPolarity::Positive
4809         };
4810
4811         // Parse the trait.
4812         let mut ty = self.parse_ty_sum();
4813
4814         // Parse traits, if necessary.
4815         let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) {
4816             // New-style trait. Reinterpret the type as a trait.
4817             let opt_trait_ref = match ty.node {
4818                 TyPath(ref path, node_id) => {
4819                     Some(TraitRef {
4820                         path: (*path).clone(),
4821                         ref_id: node_id,
4822                     })
4823                 }
4824                 _ => {
4825                     self.span_err(ty.span, "not a trait");
4826                     None
4827                 }
4828             };
4829
4830             ty = self.parse_ty_sum();
4831             opt_trait_ref
4832         } else {
4833             match polarity {
4834                 ast::ImplPolarity::Negative => {
4835                     // This is a negated type implementation
4836                     // `impl !MyType {}`, which is not allowed.
4837                     self.span_err(neg_span, "inherent implementation can't be negated");
4838                 },
4839                 _ => {}
4840             }
4841             None
4842         };
4843
4844         self.parse_where_clause(&mut generics);
4845         let (impl_items, attrs) = self.parse_impl_items();
4846
4847         let ident = ast_util::impl_pretty_name(&opt_trait, &*ty);
4848
4849         (ident,
4850          ItemImpl(unsafety, polarity, generics, opt_trait, ty, impl_items),
4851          Some(attrs))
4852     }
4853
4854     /// Parse a::B<String,int>
4855     fn parse_trait_ref(&mut self) -> TraitRef {
4856         ast::TraitRef {
4857             path: self.parse_path(LifetimeAndTypesWithoutColons),
4858             ref_id: ast::DUMMY_NODE_ID,
4859         }
4860     }
4861
4862     fn parse_late_bound_lifetime_defs(&mut self) -> Vec<ast::LifetimeDef> {
4863         if self.eat_keyword(keywords::For) {
4864             self.expect(&token::Lt);
4865             let lifetime_defs = self.parse_lifetime_defs();
4866             self.expect_gt();
4867             lifetime_defs
4868         } else {
4869             Vec::new()
4870         }
4871     }
4872
4873     /// Parse for<'l> a::B<String,int>
4874     fn parse_poly_trait_ref(&mut self) -> PolyTraitRef {
4875         let lifetime_defs = self.parse_late_bound_lifetime_defs();
4876
4877         ast::PolyTraitRef {
4878             bound_lifetimes: lifetime_defs,
4879             trait_ref: self.parse_trait_ref()
4880         }
4881     }
4882
4883     /// Parse struct Foo { ... }
4884     fn parse_item_struct(&mut self) -> ItemInfo {
4885         let class_name = self.parse_ident();
4886         let mut generics = self.parse_generics();
4887
4888         if self.eat(&token::Colon) {
4889             let ty = self.parse_ty_sum();
4890             self.span_err(ty.span, "`virtual` structs have been removed from the language");
4891         }
4892
4893         // There is a special case worth noting here, as reported in issue #17904.
4894         // If we are parsing a tuple struct it is the case that the where clause
4895         // should follow the field list. Like so:
4896         //
4897         // struct Foo<T>(T) where T: Copy;
4898         //
4899         // If we are parsing a normal record-style struct it is the case
4900         // that the where clause comes before the body, and after the generics.
4901         // So if we look ahead and see a brace or a where-clause we begin
4902         // parsing a record style struct.
4903         //
4904         // Otherwise if we look ahead and see a paren we parse a tuple-style
4905         // struct.
4906
4907         let (fields, ctor_id) = if self.token.is_keyword(keywords::Where) {
4908             self.parse_where_clause(&mut generics);
4909             if self.eat(&token::Semi) {
4910                 // If we see a: `struct Foo<T> where T: Copy;` style decl.
4911                 (Vec::new(), Some(ast::DUMMY_NODE_ID))
4912             } else {
4913                 // If we see: `struct Foo<T> where T: Copy { ... }`
4914                 (self.parse_record_struct_body(&class_name), None)
4915             }
4916         // No `where` so: `struct Foo<T>;`
4917         } else if self.eat(&token::Semi) {
4918             (Vec::new(), Some(ast::DUMMY_NODE_ID))
4919         // Record-style struct definition
4920         } else if self.token == token::OpenDelim(token::Brace) {
4921             let fields = self.parse_record_struct_body(&class_name);
4922             (fields, None)
4923         // Tuple-style struct definition with optional where-clause.
4924         } else {
4925             let fields = self.parse_tuple_struct_body(&class_name, &mut generics);
4926             (fields, Some(ast::DUMMY_NODE_ID))
4927         };
4928
4929         (class_name,
4930          ItemStruct(P(ast::StructDef {
4931              fields: fields,
4932              ctor_id: ctor_id,
4933          }), generics),
4934          None)
4935     }
4936
4937     pub fn parse_record_struct_body(&mut self, class_name: &ast::Ident) -> Vec<StructField> {
4938         let mut fields = Vec::new();
4939         if self.eat(&token::OpenDelim(token::Brace)) {
4940             while self.token != token::CloseDelim(token::Brace) {
4941                 fields.push(self.parse_struct_decl_field(true));
4942             }
4943
4944             if fields.len() == 0 {
4945                 self.fatal(&format!("unit-like struct definition should be \
4946                     written as `struct {};`",
4947                     token::get_ident(class_name.clone()))[]);
4948             }
4949
4950             self.bump();
4951         } else {
4952             let token_str = self.this_token_to_string();
4953             self.fatal(&format!("expected `where`, or `{}` after struct \
4954                                 name, found `{}`", "{",
4955                                 token_str)[]);
4956         }
4957
4958         fields
4959     }
4960
4961     pub fn parse_tuple_struct_body(&mut self,
4962                                    class_name: &ast::Ident,
4963                                    generics: &mut ast::Generics)
4964                                    -> Vec<StructField> {
4965         // This is the case where we find `struct Foo<T>(T) where T: Copy;`
4966         if self.check(&token::OpenDelim(token::Paren)) {
4967             let fields = self.parse_unspanned_seq(
4968                 &token::OpenDelim(token::Paren),
4969                 &token::CloseDelim(token::Paren),
4970                 seq_sep_trailing_allowed(token::Comma),
4971                 |p| {
4972                     let attrs = p.parse_outer_attributes();
4973                     let lo = p.span.lo;
4974                     let struct_field_ = ast::StructField_ {
4975                         kind: UnnamedField(p.parse_visibility()),
4976                         id: ast::DUMMY_NODE_ID,
4977                         ty: p.parse_ty_sum(),
4978                         attrs: attrs,
4979                     };
4980                     spanned(lo, p.span.hi, struct_field_)
4981                 });
4982
4983             if fields.len() == 0 {
4984                 self.fatal(&format!("unit-like struct definition should be \
4985                     written as `struct {};`",
4986                     token::get_ident(class_name.clone()))[]);
4987             }
4988
4989             self.parse_where_clause(generics);
4990             self.expect(&token::Semi);
4991             fields
4992         // This is the case where we just see struct Foo<T> where T: Copy;
4993         } else if self.token.is_keyword(keywords::Where) {
4994             self.parse_where_clause(generics);
4995             self.expect(&token::Semi);
4996             Vec::new()
4997         // This case is where we see: `struct Foo<T>;`
4998         } else {
4999             let token_str = self.this_token_to_string();
5000             self.fatal(&format!("expected `where`, `{}`, `(`, or `;` after struct \
5001                 name, found `{}`", "{", token_str)[]);
5002         }
5003     }
5004
5005     /// Parse a structure field declaration
5006     pub fn parse_single_struct_field(&mut self,
5007                                      vis: Visibility,
5008                                      attrs: Vec<Attribute> )
5009                                      -> StructField {
5010         let a_var = self.parse_name_and_ty(vis, attrs);
5011         match self.token {
5012             token::Comma => {
5013                 self.bump();
5014             }
5015             token::CloseDelim(token::Brace) => {}
5016             _ => {
5017                 let span = self.span;
5018                 let token_str = self.this_token_to_string();
5019                 self.span_fatal_help(span,
5020                                      &format!("expected `,`, or `}}`, found `{}`",
5021                                              token_str)[],
5022                                      "struct fields should be separated by commas")
5023             }
5024         }
5025         a_var
5026     }
5027
5028     /// Parse an element of a struct definition
5029     fn parse_struct_decl_field(&mut self, allow_pub: bool) -> StructField {
5030
5031         let attrs = self.parse_outer_attributes();
5032
5033         if self.eat_keyword(keywords::Pub) {
5034             if !allow_pub {
5035                 let span = self.last_span;
5036                 self.span_err(span, "`pub` is not allowed here");
5037             }
5038             return self.parse_single_struct_field(Public, attrs);
5039         }
5040
5041         return self.parse_single_struct_field(Inherited, attrs);
5042     }
5043
5044     /// Parse visibility: PUB, PRIV, or nothing
5045     fn parse_visibility(&mut self) -> Visibility {
5046         if self.eat_keyword(keywords::Pub) { Public }
5047         else { Inherited }
5048     }
5049
5050     fn parse_for_sized(&mut self) -> Option<ast::TraitRef> {
5051         // FIXME, this should really use TraitBoundModifier, but it will get
5052         // re-jigged shortly in any case, so leaving the hacky version for now.
5053         if self.eat_keyword(keywords::For) {
5054             let span = self.span;
5055
5056             let mut ate_question = false;
5057             if self.eat(&token::Question) {
5058                 ate_question = true;
5059             }
5060             let ident = self.parse_ident();
5061             if self.eat(&token::Question) {
5062                 if ate_question {
5063                     self.span_err(span,
5064                         "unexpected `?`");
5065                 }
5066                 ate_question = true;
5067             }
5068             if !ate_question {
5069                 self.span_err(span,
5070                     "expected `?Sized` after `for` in trait item");
5071                 return None;
5072             }
5073             let _tref = Parser::trait_ref_from_ident(ident, span);
5074
5075             self.obsolete(span, ObsoleteSyntax::ForSized);
5076
5077             None
5078         } else {
5079             None
5080         }
5081     }
5082
5083     /// Given a termination token and a vector of already-parsed
5084     /// attributes (of length 0 or 1), parse all of the items in a module
5085     fn parse_mod_items(&mut self,
5086                        term: token::Token,
5087                        first_item_attrs: Vec<Attribute>,
5088                        inner_lo: BytePos)
5089                        -> Mod {
5090         // parse all of the items up to closing or an attribute.
5091         // view items are legal here.
5092         let ParsedItemsAndViewItems {
5093             attrs_remaining,
5094             view_items,
5095             items: starting_items,
5096             ..
5097         } = self.parse_items_and_view_items(first_item_attrs, true, true);
5098         let mut items: Vec<P<Item>> = starting_items;
5099         let attrs_remaining_len = attrs_remaining.len();
5100
5101         // don't think this other loop is even necessary....
5102
5103         let mut first = true;
5104         while self.token != term {
5105             let mut attrs = self.parse_outer_attributes();
5106             if first {
5107                 let mut tmp = attrs_remaining.clone();
5108                 tmp.push_all(&attrs[]);
5109                 attrs = tmp;
5110                 first = false;
5111             }
5112             debug!("parse_mod_items: parse_item_or_view_item(attrs={:?})",
5113                    attrs);
5114             match self.parse_item_or_view_item(attrs,
5115                                                true /* macros allowed */) {
5116               IoviItem(item) => items.push(item),
5117               IoviViewItem(view_item) => {
5118                 self.span_fatal(view_item.span,
5119                                 "view items must be declared at the top of \
5120                                  the module");
5121               }
5122               _ => {
5123                   let token_str = self.this_token_to_string();
5124                   self.fatal(&format!("expected item, found `{}`",
5125                                      token_str)[])
5126               }
5127             }
5128         }
5129
5130         if first && attrs_remaining_len > 0u {
5131             // We parsed attributes for the first item but didn't find it
5132             let last_span = self.last_span;
5133             self.span_err(last_span,
5134                           Parser::expected_item_err(&attrs_remaining[]));
5135         }
5136
5137         ast::Mod {
5138             inner: mk_sp(inner_lo, self.span.lo),
5139             view_items: view_items,
5140             items: items
5141         }
5142     }
5143
5144     fn parse_item_const(&mut self, m: Option<Mutability>) -> ItemInfo {
5145         let id = self.parse_ident();
5146         self.expect(&token::Colon);
5147         let ty = self.parse_ty_sum();
5148         self.expect(&token::Eq);
5149         let e = self.parse_expr();
5150         self.commit_expr_expecting(&*e, token::Semi);
5151         let item = match m {
5152             Some(m) => ItemStatic(ty, m, e),
5153             None => ItemConst(ty, e),
5154         };
5155         (id, item, None)
5156     }
5157
5158     /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
5159     fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> ItemInfo {
5160         let id_span = self.span;
5161         let id = self.parse_ident();
5162         if self.check(&token::Semi) {
5163             self.bump();
5164             // This mod is in an external file. Let's go get it!
5165             let (m, attrs) = self.eval_src_mod(id, outer_attrs, id_span);
5166             (id, m, Some(attrs))
5167         } else {
5168             self.push_mod_path(id, outer_attrs);
5169             self.expect(&token::OpenDelim(token::Brace));
5170             let mod_inner_lo = self.span.lo;
5171             let old_owns_directory = self.owns_directory;
5172             self.owns_directory = true;
5173             let (inner, next) = self.parse_inner_attrs_and_next();
5174             let m = self.parse_mod_items(token::CloseDelim(token::Brace), next, mod_inner_lo);
5175             self.expect(&token::CloseDelim(token::Brace));
5176             self.owns_directory = old_owns_directory;
5177             self.pop_mod_path();
5178             (id, ItemMod(m), Some(inner))
5179         }
5180     }
5181
5182     fn push_mod_path(&mut self, id: Ident, attrs: &[Attribute]) {
5183         let default_path = self.id_to_interned_str(id);
5184         let file_path = match ::attr::first_attr_value_str_by_name(attrs,
5185                                                                    "path") {
5186             Some(d) => d,
5187             None => default_path,
5188         };
5189         self.mod_path_stack.push(file_path)
5190     }
5191
5192     fn pop_mod_path(&mut self) {
5193         self.mod_path_stack.pop().unwrap();
5194     }
5195
5196     /// Read a module from a source file.
5197     fn eval_src_mod(&mut self,
5198                     id: ast::Ident,
5199                     outer_attrs: &[ast::Attribute],
5200                     id_sp: Span)
5201                     -> (ast::Item_, Vec<ast::Attribute> ) {
5202         let mut prefix = Path::new(self.sess.span_diagnostic.cm.span_to_filename(self.span));
5203         prefix.pop();
5204         let mod_path = Path::new(".").join_many(&self.mod_path_stack[]);
5205         let dir_path = prefix.join(&mod_path);
5206         let mod_string = token::get_ident(id);
5207         let (file_path, owns_directory) = match ::attr::first_attr_value_str_by_name(
5208                 outer_attrs, "path") {
5209             Some(d) => (dir_path.join(d), true),
5210             None => {
5211                 let mod_name = mod_string.get().to_string();
5212                 let default_path_str = format!("{}.rs", mod_name);
5213                 let secondary_path_str = format!("{}/mod.rs", mod_name);
5214                 let default_path = dir_path.join(&default_path_str[]);
5215                 let secondary_path = dir_path.join(&secondary_path_str[]);
5216                 let default_exists = default_path.exists();
5217                 let secondary_exists = secondary_path.exists();
5218
5219                 if !self.owns_directory {
5220                     self.span_err(id_sp,
5221                                   "cannot declare a new module at this location");
5222                     let this_module = match self.mod_path_stack.last() {
5223                         Some(name) => name.get().to_string(),
5224                         None => self.root_module_name.as_ref().unwrap().clone(),
5225                     };
5226                     self.span_note(id_sp,
5227                                    &format!("maybe move this module `{0}` \
5228                                             to its own directory via \
5229                                             `{0}/mod.rs`",
5230                                            this_module)[]);
5231                     if default_exists || secondary_exists {
5232                         self.span_note(id_sp,
5233                                        &format!("... or maybe `use` the module \
5234                                                 `{}` instead of possibly \
5235                                                 redeclaring it",
5236                                                mod_name)[]);
5237                     }
5238                     self.abort_if_errors();
5239                 }
5240
5241                 match (default_exists, secondary_exists) {
5242                     (true, false) => (default_path, false),
5243                     (false, true) => (secondary_path, true),
5244                     (false, false) => {
5245                         self.span_fatal_help(id_sp,
5246                                              &format!("file not found for module `{}`",
5247                                                      mod_name)[],
5248                                              &format!("name the file either {} or {} inside \
5249                                                      the directory {:?}",
5250                                                      default_path_str,
5251                                                      secondary_path_str,
5252                                                      dir_path.display())[]);
5253                     }
5254                     (true, true) => {
5255                         self.span_fatal_help(
5256                             id_sp,
5257                             &format!("file for module `{}` found at both {} \
5258                                      and {}",
5259                                     mod_name,
5260                                     default_path_str,
5261                                     secondary_path_str)[],
5262                             "delete or rename one of them to remove the ambiguity");
5263                     }
5264                 }
5265             }
5266         };
5267
5268         self.eval_src_mod_from_path(file_path, owns_directory,
5269                                     mod_string.get().to_string(), id_sp)
5270     }
5271
5272     fn eval_src_mod_from_path(&mut self,
5273                               path: Path,
5274                               owns_directory: bool,
5275                               name: String,
5276                               id_sp: Span) -> (ast::Item_, Vec<ast::Attribute> ) {
5277         let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
5278         match included_mod_stack.iter().position(|p| *p == path) {
5279             Some(i) => {
5280                 let mut err = String::from_str("circular modules: ");
5281                 let len = included_mod_stack.len();
5282                 for p in included_mod_stack.slice(i, len).iter() {
5283                     err.push_str(&p.display().as_cow()[]);
5284                     err.push_str(" -> ");
5285                 }
5286                 err.push_str(&path.display().as_cow()[]);
5287                 self.span_fatal(id_sp, &err[]);
5288             }
5289             None => ()
5290         }
5291         included_mod_stack.push(path.clone());
5292         drop(included_mod_stack);
5293
5294         let mut p0 =
5295             new_sub_parser_from_file(self.sess,
5296                                      self.cfg.clone(),
5297                                      &path,
5298                                      owns_directory,
5299                                      Some(name),
5300                                      id_sp);
5301         let mod_inner_lo = p0.span.lo;
5302         let (mod_attrs, next) = p0.parse_inner_attrs_and_next();
5303         let first_item_outer_attrs = next;
5304         let m0 = p0.parse_mod_items(token::Eof, first_item_outer_attrs, mod_inner_lo);
5305         self.sess.included_mod_stack.borrow_mut().pop();
5306         return (ast::ItemMod(m0), mod_attrs);
5307     }
5308
5309     /// Parse a function declaration from a foreign module
5310     fn parse_item_foreign_fn(&mut self, vis: ast::Visibility,
5311                              attrs: Vec<Attribute>) -> P<ForeignItem> {
5312         let lo = self.span.lo;
5313         self.expect_keyword(keywords::Fn);
5314
5315         let (ident, mut generics) = self.parse_fn_header();
5316         let decl = self.parse_fn_decl(true);
5317         self.parse_where_clause(&mut generics);
5318         let hi = self.span.hi;
5319         self.expect(&token::Semi);
5320         P(ast::ForeignItem {
5321             ident: ident,
5322             attrs: attrs,
5323             node: ForeignItemFn(decl, generics),
5324             id: ast::DUMMY_NODE_ID,
5325             span: mk_sp(lo, hi),
5326             vis: vis
5327         })
5328     }
5329
5330     /// Parse a static item from a foreign module
5331     fn parse_item_foreign_static(&mut self, vis: ast::Visibility,
5332                                  attrs: Vec<Attribute>) -> P<ForeignItem> {
5333         let lo = self.span.lo;
5334
5335         self.expect_keyword(keywords::Static);
5336         let mutbl = self.eat_keyword(keywords::Mut);
5337
5338         let ident = self.parse_ident();
5339         self.expect(&token::Colon);
5340         let ty = self.parse_ty_sum();
5341         let hi = self.span.hi;
5342         self.expect(&token::Semi);
5343         P(ForeignItem {
5344             ident: ident,
5345             attrs: attrs,
5346             node: ForeignItemStatic(ty, mutbl),
5347             id: ast::DUMMY_NODE_ID,
5348             span: mk_sp(lo, hi),
5349             vis: vis
5350         })
5351     }
5352
5353     /// At this point, this is essentially a wrapper for
5354     /// parse_foreign_items.
5355     fn parse_foreign_mod_items(&mut self,
5356                                abi: abi::Abi,
5357                                first_item_attrs: Vec<Attribute> )
5358                                -> ForeignMod {
5359         let ParsedItemsAndViewItems {
5360             attrs_remaining,
5361             view_items,
5362             items: _,
5363             foreign_items,
5364         } = self.parse_foreign_items(first_item_attrs, true);
5365         if !attrs_remaining.is_empty() {
5366             let last_span = self.last_span;
5367             self.span_err(last_span,
5368                           Parser::expected_item_err(&attrs_remaining[]));
5369         }
5370         assert!(self.token == token::CloseDelim(token::Brace));
5371         ast::ForeignMod {
5372             abi: abi,
5373             view_items: view_items,
5374             items: foreign_items
5375         }
5376     }
5377
5378     /// Parse extern crate links
5379     ///
5380     /// # Example
5381     ///
5382     /// extern crate url;
5383     /// extern crate foo = "bar"; //deprecated
5384     /// extern crate "bar" as foo;
5385     fn parse_item_extern_crate(&mut self,
5386                                 lo: BytePos,
5387                                 visibility: Visibility,
5388                                 attrs: Vec<Attribute> )
5389                                 -> ItemOrViewItem {
5390
5391         let span = self.span;
5392         let (maybe_path, ident) = match self.token {
5393             token::Ident(..) => {
5394                 let the_ident = self.parse_ident();
5395                 let path = if self.token == token::Eq {
5396                     self.bump();
5397                     let path = self.parse_str();
5398                     let span = self.span;
5399                     self.obsolete(span, ObsoleteSyntax::ExternCrateRenaming);
5400                     Some(path)
5401                 } else if self.eat_keyword(keywords::As) {
5402                     // skip the ident if there is one
5403                     if self.token.is_ident() { self.bump(); }
5404
5405                     self.span_err(span, "expected `;`, found `as`");
5406                     self.span_help(span,
5407                                    &format!("perhaps you meant to enclose the crate name `{}` in \
5408                                            a string?",
5409                                           the_ident.as_str())[]);
5410                     None
5411                 } else {
5412                     None
5413                 };
5414                 self.expect(&token::Semi);
5415                 (path, the_ident)
5416             },
5417             token::Literal(token::Str_(..), suf) | token::Literal(token::StrRaw(..), suf) => {
5418                 let sp = self.span;
5419                 self.expect_no_suffix(sp, "extern crate name", suf);
5420                 // forgo the internal suffix check of `parse_str` to
5421                 // avoid repeats (this unwrap will always succeed due
5422                 // to the restriction of the `match`)
5423                 let (s, style, _) = self.parse_optional_str().unwrap();
5424                 self.expect_keyword(keywords::As);
5425                 let the_ident = self.parse_ident();
5426                 self.expect(&token::Semi);
5427                 (Some((s, style)), the_ident)
5428             },
5429             _ => {
5430                 let span = self.span;
5431                 let token_str = self.this_token_to_string();
5432                 self.span_fatal(span,
5433                                 &format!("expected extern crate name but \
5434                                          found `{}`",
5435                                         token_str)[]);
5436             }
5437         };
5438
5439         IoviViewItem(ast::ViewItem {
5440                 node: ViewItemExternCrate(ident, maybe_path, ast::DUMMY_NODE_ID),
5441                 attrs: attrs,
5442                 vis: visibility,
5443                 span: mk_sp(lo, self.last_span.hi)
5444             })
5445     }
5446
5447     /// Parse `extern` for foreign ABIs
5448     /// modules.
5449     ///
5450     /// `extern` is expected to have been
5451     /// consumed before calling this method
5452     ///
5453     /// # Examples:
5454     ///
5455     /// extern "C" {}
5456     /// extern {}
5457     fn parse_item_foreign_mod(&mut self,
5458                               lo: BytePos,
5459                               opt_abi: Option<abi::Abi>,
5460                               visibility: Visibility,
5461                               attrs: Vec<Attribute> )
5462                               -> ItemOrViewItem {
5463
5464         self.expect(&token::OpenDelim(token::Brace));
5465
5466         let abi = opt_abi.unwrap_or(abi::C);
5467
5468         let (inner, next) = self.parse_inner_attrs_and_next();
5469         let m = self.parse_foreign_mod_items(abi, next);
5470         self.expect(&token::CloseDelim(token::Brace));
5471
5472         let last_span = self.last_span;
5473         let item = self.mk_item(lo,
5474                                 last_span.hi,
5475                                 special_idents::invalid,
5476                                 ItemForeignMod(m),
5477                                 visibility,
5478                                 maybe_append(attrs, Some(inner)));
5479         return IoviItem(item);
5480     }
5481
5482     /// Parse type Foo = Bar;
5483     fn parse_item_type(&mut self) -> ItemInfo {
5484         let ident = self.parse_ident();
5485         let mut tps = self.parse_generics();
5486         self.parse_where_clause(&mut tps);
5487         self.expect(&token::Eq);
5488         let ty = self.parse_ty_sum();
5489         self.expect(&token::Semi);
5490         (ident, ItemTy(ty, tps), None)
5491     }
5492
5493     /// Parse a structure-like enum variant definition
5494     /// this should probably be renamed or refactored...
5495     fn parse_struct_def(&mut self) -> P<StructDef> {
5496         let mut fields: Vec<StructField> = Vec::new();
5497         while self.token != token::CloseDelim(token::Brace) {
5498             fields.push(self.parse_struct_decl_field(false));
5499         }
5500         self.bump();
5501
5502         P(StructDef {
5503             fields: fields,
5504             ctor_id: None,
5505         })
5506     }
5507
5508     /// Parse the part of an "enum" decl following the '{'
5509     fn parse_enum_def(&mut self, _generics: &ast::Generics) -> EnumDef {
5510         let mut variants = Vec::new();
5511         let mut all_nullary = true;
5512         let mut any_disr = None;
5513         while self.token != token::CloseDelim(token::Brace) {
5514             let variant_attrs = self.parse_outer_attributes();
5515             let vlo = self.span.lo;
5516
5517             let vis = self.parse_visibility();
5518
5519             let ident;
5520             let kind;
5521             let mut args = Vec::new();
5522             let mut disr_expr = None;
5523             ident = self.parse_ident();
5524             if self.eat(&token::OpenDelim(token::Brace)) {
5525                 // Parse a struct variant.
5526                 all_nullary = false;
5527                 let start_span = self.span;
5528                 let struct_def = self.parse_struct_def();
5529                 if struct_def.fields.len() == 0 {
5530                     self.span_err(start_span,
5531                         &format!("unit-like struct variant should be written \
5532                                  without braces, as `{},`",
5533                                 token::get_ident(ident))[]);
5534                 }
5535                 kind = StructVariantKind(struct_def);
5536             } else if self.check(&token::OpenDelim(token::Paren)) {
5537                 all_nullary = false;
5538                 let arg_tys = self.parse_enum_variant_seq(
5539                     &token::OpenDelim(token::Paren),
5540                     &token::CloseDelim(token::Paren),
5541                     seq_sep_trailing_allowed(token::Comma),
5542                     |p| p.parse_ty_sum()
5543                 );
5544                 for ty in arg_tys.into_iter() {
5545                     args.push(ast::VariantArg {
5546                         ty: ty,
5547                         id: ast::DUMMY_NODE_ID,
5548                     });
5549                 }
5550                 kind = TupleVariantKind(args);
5551             } else if self.eat(&token::Eq) {
5552                 disr_expr = Some(self.parse_expr());
5553                 any_disr = disr_expr.as_ref().map(|expr| expr.span);
5554                 kind = TupleVariantKind(args);
5555             } else {
5556                 kind = TupleVariantKind(Vec::new());
5557             }
5558
5559             let vr = ast::Variant_ {
5560                 name: ident,
5561                 attrs: variant_attrs,
5562                 kind: kind,
5563                 id: ast::DUMMY_NODE_ID,
5564                 disr_expr: disr_expr,
5565                 vis: vis,
5566             };
5567             variants.push(P(spanned(vlo, self.last_span.hi, vr)));
5568
5569             if !self.eat(&token::Comma) { break; }
5570         }
5571         self.expect(&token::CloseDelim(token::Brace));
5572         match any_disr {
5573             Some(disr_span) if !all_nullary =>
5574                 self.span_err(disr_span,
5575                     "discriminator values can only be used with a c-like enum"),
5576             _ => ()
5577         }
5578
5579         ast::EnumDef { variants: variants }
5580     }
5581
5582     /// Parse an "enum" declaration
5583     fn parse_item_enum(&mut self) -> ItemInfo {
5584         let id = self.parse_ident();
5585         let mut generics = self.parse_generics();
5586         self.parse_where_clause(&mut generics);
5587         self.expect(&token::OpenDelim(token::Brace));
5588
5589         let enum_definition = self.parse_enum_def(&generics);
5590         (id, ItemEnum(enum_definition, generics), None)
5591     }
5592
5593     fn fn_expr_lookahead(tok: &token::Token) -> bool {
5594         match *tok {
5595           token::OpenDelim(token::Paren) | token::At | token::Tilde | token::BinOp(_) => true,
5596           _ => false
5597         }
5598     }
5599
5600     /// Parses a string as an ABI spec on an extern type or module. Consumes
5601     /// the `extern` keyword, if one is found.
5602     fn parse_opt_abi(&mut self) -> Option<abi::Abi> {
5603         match self.token {
5604             token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
5605                 let sp = self.span;
5606                 self.expect_no_suffix(sp, "ABI spec", suf);
5607                 self.bump();
5608                 let the_string = s.as_str();
5609                 match abi::lookup(the_string) {
5610                     Some(abi) => Some(abi),
5611                     None => {
5612                         let last_span = self.last_span;
5613                         self.span_err(
5614                             last_span,
5615                             &format!("illegal ABI: expected one of [{}], \
5616                                      found `{}`",
5617                                     abi::all_names().connect(", "),
5618                                     the_string)[]);
5619                         None
5620                     }
5621                 }
5622             }
5623
5624             _ => None,
5625         }
5626     }
5627
5628     /// Parse one of the items or view items allowed by the
5629     /// flags; on failure, return IoviNone.
5630     /// NB: this function no longer parses the items inside an
5631     /// extern crate.
5632     fn parse_item_or_view_item(&mut self,
5633                                attrs: Vec<Attribute> ,
5634                                macros_allowed: bool)
5635                                -> ItemOrViewItem {
5636         let nt_item = match self.token {
5637             token::Interpolated(token::NtItem(ref item)) => {
5638                 Some((**item).clone())
5639             }
5640             _ => None
5641         };
5642         match nt_item {
5643             Some(mut item) => {
5644                 self.bump();
5645                 let mut attrs = attrs;
5646                 mem::swap(&mut item.attrs, &mut attrs);
5647                 item.attrs.extend(attrs.into_iter());
5648                 return IoviItem(P(item));
5649             }
5650             None => {}
5651         }
5652
5653         let lo = self.span.lo;
5654
5655         let visibility = self.parse_visibility();
5656
5657         // must be a view item:
5658         if self.eat_keyword(keywords::Use) {
5659             // USE ITEM (IoviViewItem)
5660             let view_item = self.parse_use();
5661             self.expect(&token::Semi);
5662             return IoviViewItem(ast::ViewItem {
5663                 node: view_item,
5664                 attrs: attrs,
5665                 vis: visibility,
5666                 span: mk_sp(lo, self.last_span.hi)
5667             });
5668         }
5669         // either a view item or an item:
5670         if self.eat_keyword(keywords::Extern) {
5671             let next_is_mod = self.eat_keyword(keywords::Mod);
5672
5673             if next_is_mod || self.eat_keyword(keywords::Crate) {
5674                 if next_is_mod {
5675                     let last_span = self.last_span;
5676                     self.span_err(mk_sp(lo, last_span.hi),
5677                                  &format!("`extern mod` is obsolete, use \
5678                                           `extern crate` instead \
5679                                           to refer to external \
5680                                           crates.")[])
5681                 }
5682                 return self.parse_item_extern_crate(lo, visibility, attrs);
5683             }
5684
5685             let opt_abi = self.parse_opt_abi();
5686
5687             if self.eat_keyword(keywords::Fn) {
5688                 // EXTERN FUNCTION ITEM
5689                 let abi = opt_abi.unwrap_or(abi::C);
5690                 let (ident, item_, extra_attrs) =
5691                     self.parse_item_fn(Unsafety::Normal, abi);
5692                 let last_span = self.last_span;
5693                 let item = self.mk_item(lo,
5694                                         last_span.hi,
5695                                         ident,
5696                                         item_,
5697                                         visibility,
5698                                         maybe_append(attrs, extra_attrs));
5699                 return IoviItem(item);
5700             } else if self.check(&token::OpenDelim(token::Brace)) {
5701                 return self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs);
5702             }
5703
5704             let span = self.span;
5705             let token_str = self.this_token_to_string();
5706             self.span_fatal(span,
5707                             &format!("expected `{}` or `fn`, found `{}`", "{",
5708                                     token_str)[]);
5709         }
5710
5711         if self.eat_keyword(keywords::Virtual) {
5712             let span = self.span;
5713             self.span_err(span, "`virtual` structs have been removed from the language");
5714         }
5715
5716         // the rest are all guaranteed to be items:
5717         if self.token.is_keyword(keywords::Static) {
5718             // STATIC ITEM
5719             self.bump();
5720             let m = if self.eat_keyword(keywords::Mut) {MutMutable} else {MutImmutable};
5721             let (ident, item_, extra_attrs) = self.parse_item_const(Some(m));
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         }
5731         if self.token.is_keyword(keywords::Const) {
5732             // CONST ITEM
5733             self.bump();
5734             if self.eat_keyword(keywords::Mut) {
5735                 let last_span = self.last_span;
5736                 self.span_err(last_span, "const globals cannot be mutable");
5737                 self.span_help(last_span, "did you mean to declare a static?");
5738             }
5739             let (ident, item_, extra_attrs) = self.parse_item_const(None);
5740             let last_span = self.last_span;
5741             let item = self.mk_item(lo,
5742                                     last_span.hi,
5743                                     ident,
5744                                     item_,
5745                                     visibility,
5746                                     maybe_append(attrs, extra_attrs));
5747             return IoviItem(item);
5748         }
5749         if self.token.is_keyword(keywords::Unsafe) &&
5750             self.look_ahead(1u, |t| t.is_keyword(keywords::Trait))
5751         {
5752             // UNSAFE TRAIT ITEM
5753             self.expect_keyword(keywords::Unsafe);
5754             self.expect_keyword(keywords::Trait);
5755             let (ident, item_, extra_attrs) =
5756                 self.parse_item_trait(ast::Unsafety::Unsafe);
5757             let last_span = self.last_span;
5758             let item = self.mk_item(lo,
5759                                     last_span.hi,
5760                                     ident,
5761                                     item_,
5762                                     visibility,
5763                                     maybe_append(attrs, extra_attrs));
5764             return IoviItem(item);
5765         }
5766         if self.token.is_keyword(keywords::Unsafe) &&
5767             self.look_ahead(1u, |t| t.is_keyword(keywords::Impl))
5768         {
5769             // IMPL ITEM
5770             self.expect_keyword(keywords::Unsafe);
5771             self.expect_keyword(keywords::Impl);
5772             let (ident, item_, extra_attrs) = self.parse_item_impl(ast::Unsafety::Unsafe);
5773             let last_span = self.last_span;
5774             let item = self.mk_item(lo,
5775                                     last_span.hi,
5776                                     ident,
5777                                     item_,
5778                                     visibility,
5779                                     maybe_append(attrs, extra_attrs));
5780             return IoviItem(item);
5781         }
5782         if self.token.is_keyword(keywords::Fn) &&
5783                 self.look_ahead(1, |f| !Parser::fn_expr_lookahead(f)) {
5784             // FUNCTION ITEM
5785             self.bump();
5786             let (ident, item_, extra_attrs) =
5787                 self.parse_item_fn(Unsafety::Normal, abi::Rust);
5788             let last_span = self.last_span;
5789             let item = self.mk_item(lo,
5790                                     last_span.hi,
5791                                     ident,
5792                                     item_,
5793                                     visibility,
5794                                     maybe_append(attrs, extra_attrs));
5795             return IoviItem(item);
5796         }
5797         if self.token.is_keyword(keywords::Unsafe)
5798             && self.look_ahead(1u, |t| *t != token::OpenDelim(token::Brace)) {
5799             // UNSAFE FUNCTION ITEM
5800             self.bump();
5801             let abi = if self.eat_keyword(keywords::Extern) {
5802                 self.parse_opt_abi().unwrap_or(abi::C)
5803             } else {
5804                 abi::Rust
5805             };
5806             self.expect_keyword(keywords::Fn);
5807             let (ident, item_, extra_attrs) =
5808                 self.parse_item_fn(Unsafety::Unsafe, abi);
5809             let last_span = self.last_span;
5810             let item = self.mk_item(lo,
5811                                     last_span.hi,
5812                                     ident,
5813                                     item_,
5814                                     visibility,
5815                                     maybe_append(attrs, extra_attrs));
5816             return IoviItem(item);
5817         }
5818         if self.eat_keyword(keywords::Mod) {
5819             // MODULE ITEM
5820             let (ident, item_, extra_attrs) =
5821                 self.parse_item_mod(&attrs[]);
5822             let last_span = self.last_span;
5823             let item = self.mk_item(lo,
5824                                     last_span.hi,
5825                                     ident,
5826                                     item_,
5827                                     visibility,
5828                                     maybe_append(attrs, extra_attrs));
5829             return IoviItem(item);
5830         }
5831         if self.eat_keyword(keywords::Type) {
5832             // TYPE ITEM
5833             let (ident, item_, extra_attrs) = self.parse_item_type();
5834             let last_span = self.last_span;
5835             let item = self.mk_item(lo,
5836                                     last_span.hi,
5837                                     ident,
5838                                     item_,
5839                                     visibility,
5840                                     maybe_append(attrs, extra_attrs));
5841             return IoviItem(item);
5842         }
5843         if self.eat_keyword(keywords::Enum) {
5844             // ENUM ITEM
5845             let (ident, item_, extra_attrs) = self.parse_item_enum();
5846             let last_span = self.last_span;
5847             let item = self.mk_item(lo,
5848                                     last_span.hi,
5849                                     ident,
5850                                     item_,
5851                                     visibility,
5852                                     maybe_append(attrs, extra_attrs));
5853             return IoviItem(item);
5854         }
5855         if self.eat_keyword(keywords::Trait) {
5856             // TRAIT ITEM
5857             let (ident, item_, extra_attrs) =
5858                 self.parse_item_trait(ast::Unsafety::Normal);
5859             let last_span = self.last_span;
5860             let item = self.mk_item(lo,
5861                                     last_span.hi,
5862                                     ident,
5863                                     item_,
5864                                     visibility,
5865                                     maybe_append(attrs, extra_attrs));
5866             return IoviItem(item);
5867         }
5868         if self.eat_keyword(keywords::Impl) {
5869             // IMPL ITEM
5870             let (ident, item_, extra_attrs) = self.parse_item_impl(ast::Unsafety::Normal);
5871             let last_span = self.last_span;
5872             let item = self.mk_item(lo,
5873                                     last_span.hi,
5874                                     ident,
5875                                     item_,
5876                                     visibility,
5877                                     maybe_append(attrs, extra_attrs));
5878             return IoviItem(item);
5879         }
5880         if self.eat_keyword(keywords::Struct) {
5881             // STRUCT ITEM
5882             let (ident, item_, extra_attrs) = self.parse_item_struct();
5883             let last_span = self.last_span;
5884             let item = self.mk_item(lo,
5885                                     last_span.hi,
5886                                     ident,
5887                                     item_,
5888                                     visibility,
5889                                     maybe_append(attrs, extra_attrs));
5890             return IoviItem(item);
5891         }
5892         self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility)
5893     }
5894
5895     /// Parse a foreign item; on failure, return IoviNone.
5896     fn parse_foreign_item(&mut self,
5897                           attrs: Vec<Attribute> ,
5898                           macros_allowed: bool)
5899                           -> ItemOrViewItem {
5900         maybe_whole!(iovi self, NtItem);
5901         let lo = self.span.lo;
5902
5903         let visibility = self.parse_visibility();
5904
5905         if self.token.is_keyword(keywords::Static) {
5906             // FOREIGN STATIC ITEM
5907             let item = self.parse_item_foreign_static(visibility, attrs);
5908             return IoviForeignItem(item);
5909         }
5910         if self.token.is_keyword(keywords::Fn) || self.token.is_keyword(keywords::Unsafe) {
5911             // FOREIGN FUNCTION ITEM
5912             let item = self.parse_item_foreign_fn(visibility, attrs);
5913             return IoviForeignItem(item);
5914         }
5915         self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility)
5916     }
5917
5918     /// This is the fall-through for parsing items.
5919     fn parse_macro_use_or_failure(
5920         &mut self,
5921         attrs: Vec<Attribute> ,
5922         macros_allowed: bool,
5923         lo: BytePos,
5924         visibility: Visibility
5925     ) -> ItemOrViewItem {
5926         if macros_allowed && !self.token.is_any_keyword()
5927                 && self.look_ahead(1, |t| *t == token::Not)
5928                 && (self.look_ahead(2, |t| t.is_plain_ident())
5929                     || self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren))
5930                     || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) {
5931             // MACRO INVOCATION ITEM
5932
5933             // item macro.
5934             let pth = self.parse_path(NoTypesAllowed);
5935             self.expect(&token::Not);
5936
5937             // a 'special' identifier (like what `macro_rules!` uses)
5938             // is optional. We should eventually unify invoc syntax
5939             // and remove this.
5940             let id = if self.token.is_plain_ident() {
5941                 self.parse_ident()
5942             } else {
5943                 token::special_idents::invalid // no special identifier
5944             };
5945             // eat a matched-delimiter token tree:
5946             let delim = self.expect_open_delim();
5947             let tts = self.parse_seq_to_end(&token::CloseDelim(delim),
5948                                             seq_sep_none(),
5949                                             |p| p.parse_token_tree());
5950             // single-variant-enum... :
5951             let m = ast::MacInvocTT(pth, tts, EMPTY_CTXT);
5952             let m: ast::Mac = codemap::Spanned { node: m,
5953                                              span: mk_sp(self.span.lo,
5954                                                          self.span.hi) };
5955
5956             if delim != token::Brace {
5957                 if !self.eat(&token::Semi) {
5958                     let last_span = self.last_span;
5959                     self.span_err(last_span,
5960                                   "macros that expand to items must either \
5961                                    be surrounded with braces or followed by \
5962                                    a semicolon");
5963                 }
5964             }
5965
5966             let item_ = ItemMac(m);
5967             let last_span = self.last_span;
5968             let item = self.mk_item(lo,
5969                                     last_span.hi,
5970                                     id,
5971                                     item_,
5972                                     visibility,
5973                                     attrs);
5974             return IoviItem(item);
5975         }
5976
5977         // FAILURE TO PARSE ITEM
5978         match visibility {
5979             Inherited => {}
5980             Public => {
5981                 let last_span = self.last_span;
5982                 self.span_fatal(last_span, "unmatched visibility `pub`");
5983             }
5984         }
5985         return IoviNone(attrs);
5986     }
5987
5988     pub fn parse_item_with_outer_attributes(&mut self) -> Option<P<Item>> {
5989         let attrs = self.parse_outer_attributes();
5990         self.parse_item(attrs)
5991     }
5992
5993     pub fn parse_item(&mut self, attrs: Vec<Attribute>) -> Option<P<Item>> {
5994         match self.parse_item_or_view_item(attrs, true) {
5995             IoviNone(_) => None,
5996             IoviViewItem(_) =>
5997                 self.fatal("view items are not allowed here"),
5998             IoviForeignItem(_) =>
5999                 self.fatal("foreign items are not allowed here"),
6000             IoviItem(item) => Some(item)
6001         }
6002     }
6003
6004     /// Parse a ViewItem, e.g. `use foo::bar` or `extern crate foo`
6005     pub fn parse_view_item(&mut self, attrs: Vec<Attribute>) -> ViewItem {
6006         match self.parse_item_or_view_item(attrs, false) {
6007             IoviViewItem(vi) => vi,
6008             _ => self.fatal("expected `use` or `extern crate`"),
6009         }
6010     }
6011
6012     /// Parse, e.g., "use a::b::{z,y}"
6013     fn parse_use(&mut self) -> ViewItem_ {
6014         return ViewItemUse(self.parse_view_path());
6015     }
6016
6017
6018     /// Matches view_path : MOD? non_global_path as IDENT
6019     /// | MOD? non_global_path MOD_SEP LBRACE RBRACE
6020     /// | MOD? non_global_path MOD_SEP LBRACE ident_seq RBRACE
6021     /// | MOD? non_global_path MOD_SEP STAR
6022     /// | MOD? non_global_path
6023     fn parse_view_path(&mut self) -> P<ViewPath> {
6024         let lo = self.span.lo;
6025
6026         // Allow a leading :: because the paths are absolute either way.
6027         // This occurs with "use $crate::..." in macros.
6028         self.eat(&token::ModSep);
6029
6030         if self.check(&token::OpenDelim(token::Brace)) {
6031             // use {foo,bar}
6032             let idents = self.parse_unspanned_seq(
6033                 &token::OpenDelim(token::Brace),
6034                 &token::CloseDelim(token::Brace),
6035                 seq_sep_trailing_allowed(token::Comma),
6036                 |p| p.parse_path_list_item());
6037             let path = ast::Path {
6038                 span: mk_sp(lo, self.span.hi),
6039                 global: false,
6040                 segments: Vec::new()
6041             };
6042             return P(spanned(lo, self.span.hi,
6043                              ViewPathList(path, idents, ast::DUMMY_NODE_ID)));
6044         }
6045
6046         let first_ident = self.parse_ident();
6047         let mut path = vec!(first_ident);
6048         match self.token {
6049           token::Eq => {
6050             // x = foo::bar
6051             self.bump();
6052             let path_lo = self.span.lo;
6053             path = vec!(self.parse_ident());
6054             while self.check(&token::ModSep) {
6055                 self.bump();
6056                 let id = self.parse_ident();
6057                 path.push(id);
6058             }
6059             let span = mk_sp(path_lo, self.span.hi);
6060             self.obsolete(span, ObsoleteSyntax::ImportRenaming);
6061             let path = ast::Path {
6062                 span: span,
6063                 global: false,
6064                 segments: path.into_iter().map(|identifier| {
6065                     ast::PathSegment {
6066                         identifier: identifier,
6067                         parameters: ast::PathParameters::none(),
6068                     }
6069                 }).collect()
6070             };
6071             return P(spanned(lo, self.span.hi,
6072                              ViewPathSimple(first_ident, path,
6073                                            ast::DUMMY_NODE_ID)));
6074           }
6075
6076           token::ModSep => {
6077             // foo::bar or foo::{a,b,c} or foo::*
6078             while self.check(&token::ModSep) {
6079                 self.bump();
6080
6081                 match self.token {
6082                   token::Ident(i, _) => {
6083                     self.bump();
6084                     path.push(i);
6085                   }
6086
6087                   // foo::bar::{a,b,c}
6088                   token::OpenDelim(token::Brace) => {
6089                     let idents = self.parse_unspanned_seq(
6090                         &token::OpenDelim(token::Brace),
6091                         &token::CloseDelim(token::Brace),
6092                         seq_sep_trailing_allowed(token::Comma),
6093                         |p| p.parse_path_list_item()
6094                     );
6095                     let path = ast::Path {
6096                         span: mk_sp(lo, self.span.hi),
6097                         global: false,
6098                         segments: path.into_iter().map(|identifier| {
6099                             ast::PathSegment {
6100                                 identifier: identifier,
6101                                 parameters: ast::PathParameters::none(),
6102                             }
6103                         }).collect()
6104                     };
6105                     return P(spanned(lo, self.span.hi,
6106                                      ViewPathList(path, idents, ast::DUMMY_NODE_ID)));
6107                   }
6108
6109                   // foo::bar::*
6110                   token::BinOp(token::Star) => {
6111                     self.bump();
6112                     let path = ast::Path {
6113                         span: mk_sp(lo, self.span.hi),
6114                         global: false,
6115                         segments: path.into_iter().map(|identifier| {
6116                             ast::PathSegment {
6117                                 identifier: identifier,
6118                                 parameters: ast::PathParameters::none(),
6119                             }
6120                         }).collect()
6121                     };
6122                     return P(spanned(lo, self.span.hi,
6123                                      ViewPathGlob(path, ast::DUMMY_NODE_ID)));
6124                   }
6125
6126                   _ => break
6127                 }
6128             }
6129           }
6130           _ => ()
6131         }
6132         let mut rename_to = path[path.len() - 1u];
6133         let path = ast::Path {
6134             span: mk_sp(lo, self.last_span.hi),
6135             global: false,
6136             segments: path.into_iter().map(|identifier| {
6137                 ast::PathSegment {
6138                     identifier: identifier,
6139                     parameters: ast::PathParameters::none(),
6140                 }
6141             }).collect()
6142         };
6143         if self.eat_keyword(keywords::As) {
6144             rename_to = self.parse_ident()
6145         }
6146         P(spanned(lo,
6147                   self.last_span.hi,
6148                   ViewPathSimple(rename_to, path, ast::DUMMY_NODE_ID)))
6149     }
6150
6151     /// Parses a sequence of items. Stops when it finds program
6152     /// text that can't be parsed as an item
6153     /// - mod_items uses extern_mod_allowed = true
6154     /// - block_tail_ uses extern_mod_allowed = false
6155     fn parse_items_and_view_items(&mut self,
6156                                   first_item_attrs: Vec<Attribute> ,
6157                                   mut extern_mod_allowed: bool,
6158                                   macros_allowed: bool)
6159                                   -> ParsedItemsAndViewItems {
6160         let mut attrs = first_item_attrs;
6161         attrs.push_all(&self.parse_outer_attributes()[]);
6162         // First, parse view items.
6163         let mut view_items : Vec<ast::ViewItem> = Vec::new();
6164         let mut items = Vec::new();
6165
6166         // I think this code would probably read better as a single
6167         // loop with a mutable three-state-variable (for extern crates,
6168         // view items, and regular items) ... except that because
6169         // of macros, I'd like to delay that entire check until later.
6170         loop {
6171             match self.parse_item_or_view_item(attrs, macros_allowed) {
6172                 IoviNone(attrs) => {
6173                     return ParsedItemsAndViewItems {
6174                         attrs_remaining: attrs,
6175                         view_items: view_items,
6176                         items: items,
6177                         foreign_items: Vec::new()
6178                     }
6179                 }
6180                 IoviViewItem(view_item) => {
6181                     match view_item.node {
6182                         ViewItemUse(..) => {
6183                             // `extern crate` must precede `use`.
6184                             extern_mod_allowed = false;
6185                         }
6186                         ViewItemExternCrate(..) if !extern_mod_allowed => {
6187                             self.span_err(view_item.span,
6188                                           "\"extern crate\" declarations are \
6189                                            not allowed here");
6190                         }
6191                         ViewItemExternCrate(..) => {}
6192                     }
6193                     view_items.push(view_item);
6194                 }
6195                 IoviItem(item) => {
6196                     items.push(item);
6197                     attrs = self.parse_outer_attributes();
6198                     break;
6199                 }
6200                 IoviForeignItem(_) => {
6201                     panic!();
6202                 }
6203             }
6204             attrs = self.parse_outer_attributes();
6205         }
6206
6207         // Next, parse items.
6208         loop {
6209             match self.parse_item_or_view_item(attrs, macros_allowed) {
6210                 IoviNone(returned_attrs) => {
6211                     attrs = returned_attrs;
6212                     break
6213                 }
6214                 IoviViewItem(view_item) => {
6215                     attrs = self.parse_outer_attributes();
6216                     self.span_err(view_item.span,
6217                                   "`use` and `extern crate` declarations must precede items");
6218                 }
6219                 IoviItem(item) => {
6220                     attrs = self.parse_outer_attributes();
6221                     items.push(item)
6222                 }
6223                 IoviForeignItem(_) => {
6224                     panic!();
6225                 }
6226             }
6227         }
6228
6229         ParsedItemsAndViewItems {
6230             attrs_remaining: attrs,
6231             view_items: view_items,
6232             items: items,
6233             foreign_items: Vec::new()
6234         }
6235     }
6236
6237     /// Parses a sequence of foreign items. Stops when it finds program
6238     /// text that can't be parsed as an item
6239     fn parse_foreign_items(&mut self, first_item_attrs: Vec<Attribute> ,
6240                            macros_allowed: bool)
6241         -> ParsedItemsAndViewItems {
6242         let mut attrs = first_item_attrs;
6243         attrs.push_all(&self.parse_outer_attributes()[]);
6244         let mut foreign_items = Vec::new();
6245         loop {
6246             match self.parse_foreign_item(attrs, macros_allowed) {
6247                 IoviNone(returned_attrs) => {
6248                     if self.check(&token::CloseDelim(token::Brace)) {
6249                         attrs = returned_attrs;
6250                         break
6251                     }
6252                     self.unexpected();
6253                 },
6254                 IoviViewItem(view_item) => {
6255                     // I think this can't occur:
6256                     self.span_err(view_item.span,
6257                                   "`use` and `extern crate` declarations must precede items");
6258                 }
6259                 IoviItem(item) => {
6260                     // FIXME #5668: this will occur for a macro invocation:
6261                     self.span_fatal(item.span, "macros cannot expand to foreign items");
6262                 }
6263                 IoviForeignItem(foreign_item) => {
6264                     foreign_items.push(foreign_item);
6265                 }
6266             }
6267             attrs = self.parse_outer_attributes();
6268         }
6269
6270         ParsedItemsAndViewItems {
6271             attrs_remaining: attrs,
6272             view_items: Vec::new(),
6273             items: Vec::new(),
6274             foreign_items: foreign_items
6275         }
6276     }
6277
6278     /// Parses a source module as a crate. This is the main
6279     /// entry point for the parser.
6280     pub fn parse_crate_mod(&mut self) -> Crate {
6281         let lo = self.span.lo;
6282         // parse the crate's inner attrs, maybe (oops) one
6283         // of the attrs of an item:
6284         let (inner, next) = self.parse_inner_attrs_and_next();
6285         let first_item_outer_attrs = next;
6286         // parse the items inside the crate:
6287         let m = self.parse_mod_items(token::Eof, first_item_outer_attrs, lo);
6288
6289         ast::Crate {
6290             module: m,
6291             attrs: inner,
6292             config: self.cfg.clone(),
6293             span: mk_sp(lo, self.span.lo),
6294             exported_macros: Vec::new(),
6295         }
6296     }
6297
6298     pub fn parse_optional_str(&mut self)
6299                               -> Option<(InternedString, ast::StrStyle, Option<ast::Name>)> {
6300         let ret = match self.token {
6301             token::Literal(token::Str_(s), suf) => {
6302                 (self.id_to_interned_str(s.ident()), ast::CookedStr, suf)
6303             }
6304             token::Literal(token::StrRaw(s, n), suf) => {
6305                 (self.id_to_interned_str(s.ident()), ast::RawStr(n), suf)
6306             }
6307             _ => return None
6308         };
6309         self.bump();
6310         Some(ret)
6311     }
6312
6313     pub fn parse_str(&mut self) -> (InternedString, StrStyle) {
6314         match self.parse_optional_str() {
6315             Some((s, style, suf)) => {
6316                 let sp = self.last_span;
6317                 self.expect_no_suffix(sp, "str literal", suf);
6318                 (s, style)
6319             }
6320             _ =>  self.fatal("expected string literal")
6321         }
6322     }
6323 }