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