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