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