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