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