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