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