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