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