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