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