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