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