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