]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/parse/parser.rs
Auto merge of #23678 - richo:check-flightcheck, r=alexcrichton
[rust.git] / src / libsyntax / parse / parser.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 pub use self::PathParsingMode::*;
12
13 use abi;
14 use ast::BareFnTy;
15 use ast::{RegionTyParamBound, TraitTyParamBound, TraitBoundModifier};
16 use ast::{Public, Unsafety};
17 use ast::{Mod, BiAdd, Arg, Arm, Attribute, BindByRef, BindByValue};
18 use ast::{BiBitAnd, BiBitOr, BiBitXor, BiRem, BiLt, BiGt, Block};
19 use ast::{BlockCheckMode, CaptureByRef, CaptureByValue, CaptureClause};
20 use ast::{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                 self.bump();
2316
2317                 let ix = self.parse_expr();
2318                 hi = self.span.hi;
2319                 self.commit_expr_expecting(&*ix, token::CloseDelim(token::Bracket));
2320                 let index = self.mk_index(e, ix);
2321                 e = self.mk_expr(lo, hi, index)
2322               }
2323               _ => return e
2324             }
2325         }
2326         return e;
2327     }
2328
2329     // Parse unquoted tokens after a `$` in a token tree
2330     fn parse_unquoted(&mut self) -> TokenTree {
2331         let mut sp = self.span;
2332         let (name, namep) = match self.token {
2333             token::Dollar => {
2334                 self.bump();
2335
2336                 if self.token == token::OpenDelim(token::Paren) {
2337                     let Spanned { node: seq, span: seq_span } = self.parse_seq(
2338                         &token::OpenDelim(token::Paren),
2339                         &token::CloseDelim(token::Paren),
2340                         seq_sep_none(),
2341                         |p| p.parse_token_tree()
2342                     );
2343                     let (sep, repeat) = self.parse_sep_and_kleene_op();
2344                     let name_num = macro_parser::count_names(&seq);
2345                     return TtSequence(mk_sp(sp.lo, seq_span.hi),
2346                                       Rc::new(SequenceRepetition {
2347                                           tts: seq,
2348                                           separator: sep,
2349                                           op: repeat,
2350                                           num_captures: name_num
2351                                       }));
2352                 } else if self.token.is_keyword_allow_following_colon(keywords::Crate) {
2353                     self.bump();
2354                     return TtToken(sp, SpecialVarNt(SpecialMacroVar::CrateMacroVar));
2355                 } else {
2356                     sp = mk_sp(sp.lo, self.span.hi);
2357                     let namep = match self.token { token::Ident(_, p) => p, _ => token::Plain };
2358                     let name = self.parse_ident();
2359                     (name, namep)
2360                 }
2361             }
2362             token::SubstNt(name, namep) => {
2363                 self.bump();
2364                 (name, namep)
2365             }
2366             _ => unreachable!()
2367         };
2368         // continue by trying to parse the `:ident` after `$name`
2369         if self.token == token::Colon && self.look_ahead(1, |t| t.is_ident() &&
2370                                                                 !t.is_strict_keyword() &&
2371                                                                 !t.is_reserved_keyword()) {
2372             self.bump();
2373             sp = mk_sp(sp.lo, self.span.hi);
2374             let kindp = match self.token { token::Ident(_, p) => p, _ => token::Plain };
2375             let nt_kind = self.parse_ident();
2376             TtToken(sp, MatchNt(name, nt_kind, namep, kindp))
2377         } else {
2378             TtToken(sp, SubstNt(name, namep))
2379         }
2380     }
2381
2382     pub fn check_unknown_macro_variable(&mut self) {
2383         if self.quote_depth == 0 {
2384             match self.token {
2385                 token::SubstNt(name, _) =>
2386                     self.fatal(&format!("unknown macro variable `{}`",
2387                                        token::get_ident(name))),
2388                 _ => {}
2389             }
2390         }
2391     }
2392
2393     /// Parse an optional separator followed by a Kleene-style
2394     /// repetition token (+ or *).
2395     pub fn parse_sep_and_kleene_op(&mut self) -> (Option<token::Token>, ast::KleeneOp) {
2396         fn parse_kleene_op(parser: &mut Parser) -> Option<ast::KleeneOp> {
2397             match parser.token {
2398                 token::BinOp(token::Star) => {
2399                     parser.bump();
2400                     Some(ast::ZeroOrMore)
2401                 },
2402                 token::BinOp(token::Plus) => {
2403                     parser.bump();
2404                     Some(ast::OneOrMore)
2405                 },
2406                 _ => None
2407             }
2408         };
2409
2410         match parse_kleene_op(self) {
2411             Some(kleene_op) => return (None, kleene_op),
2412             None => {}
2413         }
2414
2415         let separator = self.bump_and_get();
2416         match parse_kleene_op(self) {
2417             Some(zerok) => (Some(separator), zerok),
2418             None => self.fatal("expected `*` or `+`")
2419         }
2420     }
2421
2422     /// parse a single token tree from the input.
2423     pub fn parse_token_tree(&mut self) -> TokenTree {
2424         // FIXME #6994: currently, this is too eager. It
2425         // parses token trees but also identifies TtSequence's
2426         // and token::SubstNt's; it's too early to know yet
2427         // whether something will be a nonterminal or a seq
2428         // yet.
2429         maybe_whole!(deref self, NtTT);
2430
2431         // this is the fall-through for the 'match' below.
2432         // invariants: the current token is not a left-delimiter,
2433         // not an EOF, and not the desired right-delimiter (if
2434         // it were, parse_seq_to_before_end would have prevented
2435         // reaching this point.
2436         fn parse_non_delim_tt_tok(p: &mut Parser) -> TokenTree {
2437             maybe_whole!(deref p, NtTT);
2438             match p.token {
2439                 token::CloseDelim(_) => {
2440                     // This is a conservative error: only report the last unclosed delimiter. The
2441                     // previous unclosed delimiters could actually be closed! The parser just hasn't
2442                     // gotten to them yet.
2443                     match p.open_braces.last() {
2444                         None => {}
2445                         Some(&sp) => p.span_note(sp, "unclosed delimiter"),
2446                     };
2447                     let token_str = p.this_token_to_string();
2448                     p.fatal(&format!("incorrect close delimiter: `{}`",
2449                                     token_str))
2450                 },
2451                 /* we ought to allow different depths of unquotation */
2452                 token::Dollar | token::SubstNt(..) if p.quote_depth > 0 => {
2453                     p.parse_unquoted()
2454                 }
2455                 _ => {
2456                     TtToken(p.span, p.bump_and_get())
2457                 }
2458             }
2459         }
2460
2461         match self.token {
2462             token::Eof => {
2463                 let open_braces = self.open_braces.clone();
2464                 for sp in &open_braces {
2465                     self.span_help(*sp, "did you mean to close this delimiter?");
2466                 }
2467                 // There shouldn't really be a span, but it's easier for the test runner
2468                 // if we give it one
2469                 self.fatal("this file contains an un-closed delimiter ");
2470             },
2471             token::OpenDelim(delim) => {
2472                 // The span for beginning of the delimited section
2473                 let pre_span = self.span;
2474
2475                 // Parse the open delimiter.
2476                 self.open_braces.push(self.span);
2477                 let open_span = self.span;
2478                 self.bump();
2479
2480                 // Parse the token trees within the delimiters
2481                 let tts = self.parse_seq_to_before_end(
2482                     &token::CloseDelim(delim),
2483                     seq_sep_none(),
2484                     |p| p.parse_token_tree()
2485                 );
2486
2487                 // Parse the close delimiter.
2488                 let close_span = self.span;
2489                 self.bump();
2490                 self.open_braces.pop().unwrap();
2491
2492                 // Expand to cover the entire delimited token tree
2493                 let span = Span { hi: close_span.hi, ..pre_span };
2494
2495                 TtDelimited(span, Rc::new(Delimited {
2496                     delim: delim,
2497                     open_span: open_span,
2498                     tts: tts,
2499                     close_span: close_span,
2500                 }))
2501             },
2502             _ => parse_non_delim_tt_tok(self),
2503         }
2504     }
2505
2506     // parse a stream of tokens into a list of TokenTree's,
2507     // up to EOF.
2508     pub fn parse_all_token_trees(&mut self) -> Vec<TokenTree> {
2509         let mut tts = Vec::new();
2510         while self.token != token::Eof {
2511             tts.push(self.parse_token_tree());
2512         }
2513         tts
2514     }
2515
2516     /// Parse a prefix-operator expr
2517     pub fn parse_prefix_expr(&mut self) -> P<Expr> {
2518         let lo = self.span.lo;
2519         let hi;
2520
2521         // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2522         let ex;
2523         match self.token {
2524           token::Not => {
2525             self.bump();
2526             let e = self.parse_prefix_expr();
2527             hi = e.span.hi;
2528             ex = self.mk_unary(UnNot, e);
2529           }
2530           token::BinOp(token::Minus) => {
2531             self.bump();
2532             let e = self.parse_prefix_expr();
2533             hi = e.span.hi;
2534             ex = self.mk_unary(UnNeg, e);
2535           }
2536           token::BinOp(token::Star) => {
2537             self.bump();
2538             let e = self.parse_prefix_expr();
2539             hi = e.span.hi;
2540             ex = self.mk_unary(UnDeref, e);
2541           }
2542           token::BinOp(token::And) | token::AndAnd => {
2543             self.expect_and();
2544             let m = self.parse_mutability();
2545             let e = self.parse_prefix_expr();
2546             hi = e.span.hi;
2547             ex = ExprAddrOf(m, e);
2548           }
2549           token::Ident(_, _) => {
2550             if !self.check_keyword(keywords::Box) {
2551                 return self.parse_dot_or_call_expr();
2552             }
2553
2554             let lo = self.span.lo;
2555
2556             self.bump();
2557
2558             // Check for a place: `box(PLACE) EXPR`.
2559             if self.eat(&token::OpenDelim(token::Paren)) {
2560                 // Support `box() EXPR` as the default.
2561                 if !self.eat(&token::CloseDelim(token::Paren)) {
2562                     let place = self.parse_expr();
2563                     self.expect(&token::CloseDelim(token::Paren));
2564                     // Give a suggestion to use `box()` when a parenthesised expression is used
2565                     if !self.token.can_begin_expr() {
2566                         let span = self.span;
2567                         let this_token_to_string = self.this_token_to_string();
2568                         self.span_err(span,
2569                                       &format!("expected expression, found `{}`",
2570                                               this_token_to_string));
2571                         let box_span = mk_sp(lo, self.last_span.hi);
2572                         self.span_help(box_span,
2573                                        "perhaps you meant `box() (foo)` instead?");
2574                         self.abort_if_errors();
2575                     }
2576                     let subexpression = self.parse_prefix_expr();
2577                     hi = subexpression.span.hi;
2578                     ex = ExprBox(Some(place), subexpression);
2579                     return self.mk_expr(lo, hi, ex);
2580                 }
2581             }
2582
2583             // Otherwise, we use the unique pointer default.
2584             let subexpression = self.parse_prefix_expr();
2585             hi = subexpression.span.hi;
2586             // FIXME (pnkfelix): After working out kinks with box
2587             // desugaring, should be `ExprBox(None, subexpression)`
2588             // instead.
2589             ex = self.mk_unary(UnUniq, subexpression);
2590           }
2591           _ => return self.parse_dot_or_call_expr()
2592         }
2593         return self.mk_expr(lo, hi, ex);
2594     }
2595
2596     /// Parse an expression of binops
2597     pub fn parse_binops(&mut self) -> P<Expr> {
2598         let prefix_expr = self.parse_prefix_expr();
2599         self.parse_more_binops(prefix_expr, 0)
2600     }
2601
2602     /// Parse an expression of binops of at least min_prec precedence
2603     pub fn parse_more_binops(&mut self, lhs: P<Expr>, min_prec: usize) -> P<Expr> {
2604         if self.expr_is_complete(&*lhs) { return lhs; }
2605
2606         // Prevent dynamic borrow errors later on by limiting the
2607         // scope of the borrows.
2608         if self.token == token::BinOp(token::Or) &&
2609             self.restrictions.contains(RESTRICTION_NO_BAR_OP) {
2610             return lhs;
2611         }
2612
2613         self.expected_tokens.push(TokenType::Operator);
2614
2615         let cur_op_span = self.span;
2616         let cur_opt = self.token.to_binop();
2617         match cur_opt {
2618             Some(cur_op) => {
2619                 if ast_util::is_comparison_binop(cur_op) {
2620                     self.check_no_chained_comparison(&*lhs, cur_op)
2621                 }
2622                 let cur_prec = operator_prec(cur_op);
2623                 if cur_prec >= min_prec {
2624                     self.bump();
2625                     let expr = self.parse_prefix_expr();
2626                     let rhs = self.parse_more_binops(expr, cur_prec + 1);
2627                     let lhs_span = lhs.span;
2628                     let rhs_span = rhs.span;
2629                     let binary = self.mk_binary(codemap::respan(cur_op_span, cur_op), lhs, rhs);
2630                     let bin = self.mk_expr(lhs_span.lo, rhs_span.hi, binary);
2631                     self.parse_more_binops(bin, min_prec)
2632                 } else {
2633                     lhs
2634                 }
2635             }
2636             None => {
2637                 if AS_PREC >= min_prec && self.eat_keyword_noexpect(keywords::As) {
2638                     let rhs = self.parse_ty();
2639                     let _as = self.mk_expr(lhs.span.lo,
2640                                            rhs.span.hi,
2641                                            ExprCast(lhs, rhs));
2642                     self.parse_more_binops(_as, min_prec)
2643                 } else {
2644                     lhs
2645                 }
2646             }
2647         }
2648     }
2649
2650     /// Produce an error if comparison operators are chained (RFC #558).
2651     /// We only need to check lhs, not rhs, because all comparison ops
2652     /// have same precedence and are left-associative
2653     fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: ast::BinOp_) {
2654         debug_assert!(ast_util::is_comparison_binop(outer_op));
2655         match lhs.node {
2656             ExprBinary(op, _, _) if ast_util::is_comparison_binop(op.node) => {
2657                 // respan to include both operators
2658                 let op_span = mk_sp(op.span.lo, self.span.hi);
2659                 self.span_err(op_span,
2660                     "chained comparison operators require parentheses");
2661                 if op.node == BiLt && outer_op == BiGt {
2662                     self.fileline_help(op_span,
2663                         "use `::<...>` instead of `<...>` if you meant to specify type arguments");
2664                 }
2665             }
2666             _ => {}
2667         }
2668     }
2669
2670     /// Parse an assignment expression....
2671     /// actually, this seems to be the main entry point for
2672     /// parsing an arbitrary expression.
2673     pub fn parse_assign_expr(&mut self) -> P<Expr> {
2674         match self.token {
2675           token::DotDot => {
2676             // prefix-form of range notation '..expr'
2677             // This has the same precedence as assignment expressions
2678             // (much lower than other prefix expressions) to be consistent
2679             // with the postfix-form 'expr..'
2680             let lo = self.span.lo;
2681             self.bump();
2682             let opt_end = if self.is_at_start_of_range_notation_rhs() {
2683                 let end = self.parse_binops();
2684                 Some(end)
2685             } else {
2686                 None
2687             };
2688             let hi = self.span.hi;
2689             let ex = self.mk_range(None, opt_end);
2690             self.mk_expr(lo, hi, ex)
2691           }
2692           _ => {
2693             let lhs = self.parse_binops();
2694             self.parse_assign_expr_with(lhs)
2695           }
2696         }
2697     }
2698
2699     pub fn parse_assign_expr_with(&mut self, lhs: P<Expr>) -> P<Expr> {
2700         let restrictions = self.restrictions & RESTRICTION_NO_STRUCT_LITERAL;
2701         let op_span = self.span;
2702         match self.token {
2703           token::Eq => {
2704               self.bump();
2705               let rhs = self.parse_expr_res(restrictions);
2706               self.mk_expr(lhs.span.lo, rhs.span.hi, ExprAssign(lhs, rhs))
2707           }
2708           token::BinOpEq(op) => {
2709               self.bump();
2710               let rhs = self.parse_expr_res(restrictions);
2711               let aop = match op {
2712                   token::Plus =>    BiAdd,
2713                   token::Minus =>   BiSub,
2714                   token::Star =>    BiMul,
2715                   token::Slash =>   BiDiv,
2716                   token::Percent => BiRem,
2717                   token::Caret =>   BiBitXor,
2718                   token::And =>     BiBitAnd,
2719                   token::Or =>      BiBitOr,
2720                   token::Shl =>     BiShl,
2721                   token::Shr =>     BiShr
2722               };
2723               let rhs_span = rhs.span;
2724               let span = lhs.span;
2725               let assign_op = self.mk_assign_op(codemap::respan(op_span, aop), lhs, rhs);
2726               self.mk_expr(span.lo, rhs_span.hi, assign_op)
2727           }
2728           // A range expression, either `expr..expr` or `expr..`.
2729           token::DotDot => {
2730             self.bump();
2731
2732             let opt_end = if self.is_at_start_of_range_notation_rhs() {
2733                 let end = self.parse_binops();
2734                 Some(end)
2735             } else {
2736                 None
2737             };
2738
2739             let lo = lhs.span.lo;
2740             let hi = self.span.hi;
2741             let range = self.mk_range(Some(lhs), opt_end);
2742             return self.mk_expr(lo, hi, range);
2743           }
2744
2745           _ => {
2746               lhs
2747           }
2748         }
2749     }
2750
2751     fn is_at_start_of_range_notation_rhs(&self) -> bool {
2752         if self.token.can_begin_expr() {
2753             // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
2754             if self.token == token::OpenDelim(token::Brace) {
2755                 return !self.restrictions.contains(RESTRICTION_NO_STRUCT_LITERAL);
2756             }
2757             true
2758         } else {
2759             false
2760         }
2761     }
2762
2763     /// Parse an 'if' or 'if let' expression ('if' token already eaten)
2764     pub fn parse_if_expr(&mut self) -> P<Expr> {
2765         if self.check_keyword(keywords::Let) {
2766             return self.parse_if_let_expr();
2767         }
2768         let lo = self.last_span.lo;
2769         let cond = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
2770         let thn = self.parse_block();
2771         let mut els: Option<P<Expr>> = None;
2772         let mut hi = thn.span.hi;
2773         if self.eat_keyword(keywords::Else) {
2774             let elexpr = self.parse_else_expr();
2775             hi = elexpr.span.hi;
2776             els = Some(elexpr);
2777         }
2778         self.mk_expr(lo, hi, ExprIf(cond, thn, els))
2779     }
2780
2781     /// Parse an 'if let' expression ('if' token already eaten)
2782     pub fn parse_if_let_expr(&mut self) -> P<Expr> {
2783         let lo = self.last_span.lo;
2784         self.expect_keyword(keywords::Let);
2785         let pat = self.parse_pat();
2786         self.expect(&token::Eq);
2787         let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
2788         let thn = self.parse_block();
2789         let (hi, els) = if self.eat_keyword(keywords::Else) {
2790             let expr = self.parse_else_expr();
2791             (expr.span.hi, Some(expr))
2792         } else {
2793             (thn.span.hi, None)
2794         };
2795         self.mk_expr(lo, hi, ExprIfLet(pat, expr, thn, els))
2796     }
2797
2798     // `|args| expr`
2799     pub fn parse_lambda_expr(&mut self, capture_clause: CaptureClause)
2800                              -> P<Expr>
2801     {
2802         let lo = self.span.lo;
2803         let decl = self.parse_fn_block_decl();
2804         let body = match decl.output {
2805             DefaultReturn(_) => {
2806                 // If no explicit return type is given, parse any
2807                 // expr and wrap it up in a dummy block:
2808                 let body_expr = self.parse_expr();
2809                 P(ast::Block {
2810                     id: ast::DUMMY_NODE_ID,
2811                     stmts: vec![],
2812                     span: body_expr.span,
2813                     expr: Some(body_expr),
2814                     rules: DefaultBlock,
2815                 })
2816             }
2817             _ => {
2818                 // If an explicit return type is given, require a
2819                 // block to appear (RFC 968).
2820                 self.parse_block()
2821             }
2822         };
2823
2824         self.mk_expr(
2825             lo,
2826             body.span.hi,
2827             ExprClosure(capture_clause, decl, body))
2828     }
2829
2830     pub fn parse_else_expr(&mut self) -> P<Expr> {
2831         if self.eat_keyword(keywords::If) {
2832             return self.parse_if_expr();
2833         } else {
2834             let blk = self.parse_block();
2835             return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk));
2836         }
2837     }
2838
2839     /// Parse a 'for' .. 'in' expression ('for' token already eaten)
2840     pub fn parse_for_expr(&mut self, opt_ident: Option<ast::Ident>) -> P<Expr> {
2841         // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
2842
2843         let lo = self.last_span.lo;
2844         let pat = self.parse_pat();
2845         self.expect_keyword(keywords::In);
2846         let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
2847         let loop_block = self.parse_block();
2848         let hi = self.span.hi;
2849
2850         self.mk_expr(lo, hi, ExprForLoop(pat, expr, loop_block, opt_ident))
2851     }
2852
2853     /// Parse a 'while' or 'while let' expression ('while' token already eaten)
2854     pub fn parse_while_expr(&mut self, opt_ident: Option<ast::Ident>) -> P<Expr> {
2855         if self.token.is_keyword(keywords::Let) {
2856             return self.parse_while_let_expr(opt_ident);
2857         }
2858         let lo = self.last_span.lo;
2859         let cond = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
2860         let body = self.parse_block();
2861         let hi = body.span.hi;
2862         return self.mk_expr(lo, hi, ExprWhile(cond, body, opt_ident));
2863     }
2864
2865     /// Parse a 'while let' expression ('while' token already eaten)
2866     pub fn parse_while_let_expr(&mut self, opt_ident: Option<ast::Ident>) -> P<Expr> {
2867         let lo = self.last_span.lo;
2868         self.expect_keyword(keywords::Let);
2869         let pat = self.parse_pat();
2870         self.expect(&token::Eq);
2871         let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
2872         let body = self.parse_block();
2873         let hi = body.span.hi;
2874         return self.mk_expr(lo, hi, ExprWhileLet(pat, expr, body, opt_ident));
2875     }
2876
2877     pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::Ident>) -> P<Expr> {
2878         let lo = self.last_span.lo;
2879         let body = self.parse_block();
2880         let hi = body.span.hi;
2881         self.mk_expr(lo, hi, ExprLoop(body, opt_ident))
2882     }
2883
2884     fn parse_match_expr(&mut self) -> P<Expr> {
2885         let lo = self.last_span.lo;
2886         let discriminant = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
2887         self.commit_expr_expecting(&*discriminant, token::OpenDelim(token::Brace));
2888         let mut arms: Vec<Arm> = Vec::new();
2889         while self.token != token::CloseDelim(token::Brace) {
2890             arms.push(self.parse_arm());
2891         }
2892         let hi = self.span.hi;
2893         self.bump();
2894         return self.mk_expr(lo, hi, ExprMatch(discriminant, arms, MatchSource::Normal));
2895     }
2896
2897     pub fn parse_arm(&mut self) -> Arm {
2898         let attrs = self.parse_outer_attributes();
2899         let pats = self.parse_pats();
2900         let mut guard = None;
2901         if self.eat_keyword(keywords::If) {
2902             guard = Some(self.parse_expr());
2903         }
2904         self.expect(&token::FatArrow);
2905         let expr = self.parse_expr_res(RESTRICTION_STMT_EXPR);
2906
2907         let require_comma =
2908             !classify::expr_is_simple_block(&*expr)
2909             && self.token != token::CloseDelim(token::Brace);
2910
2911         if require_comma {
2912             self.commit_expr(&*expr, &[token::Comma], &[token::CloseDelim(token::Brace)]);
2913         } else {
2914             self.eat(&token::Comma);
2915         }
2916
2917         ast::Arm {
2918             attrs: attrs,
2919             pats: pats,
2920             guard: guard,
2921             body: expr,
2922         }
2923     }
2924
2925     /// Parse an expression
2926     pub fn parse_expr(&mut self) -> P<Expr> {
2927         return self.parse_expr_res(UNRESTRICTED);
2928     }
2929
2930     /// Parse an expression, subject to the given restrictions
2931     pub fn parse_expr_res(&mut self, r: Restrictions) -> P<Expr> {
2932         let old = self.restrictions;
2933         self.restrictions = r;
2934         let e = self.parse_assign_expr();
2935         self.restrictions = old;
2936         return e;
2937     }
2938
2939     /// Parse the RHS of a local variable declaration (e.g. '= 14;')
2940     fn parse_initializer(&mut self) -> Option<P<Expr>> {
2941         if self.check(&token::Eq) {
2942             self.bump();
2943             Some(self.parse_expr())
2944         } else {
2945             None
2946         }
2947     }
2948
2949     /// Parse patterns, separated by '|' s
2950     fn parse_pats(&mut self) -> Vec<P<Pat>> {
2951         let mut pats = Vec::new();
2952         loop {
2953             pats.push(self.parse_pat());
2954             if self.check(&token::BinOp(token::Or)) { self.bump(); }
2955             else { return pats; }
2956         };
2957     }
2958
2959     fn parse_pat_vec_elements(
2960         &mut self,
2961     ) -> (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>) {
2962         let mut before = Vec::new();
2963         let mut slice = None;
2964         let mut after = Vec::new();
2965         let mut first = true;
2966         let mut before_slice = true;
2967
2968         while self.token != token::CloseDelim(token::Bracket) {
2969             if first {
2970                 first = false;
2971             } else {
2972                 self.expect(&token::Comma);
2973
2974                 if self.token == token::CloseDelim(token::Bracket)
2975                         && (before_slice || after.len() != 0) {
2976                     break
2977                 }
2978             }
2979
2980             if before_slice {
2981                 if self.check(&token::DotDot) {
2982                     self.bump();
2983
2984                     if self.check(&token::Comma) ||
2985                             self.check(&token::CloseDelim(token::Bracket)) {
2986                         slice = Some(P(ast::Pat {
2987                             id: ast::DUMMY_NODE_ID,
2988                             node: PatWild(PatWildMulti),
2989                             span: self.span,
2990                         }));
2991                         before_slice = false;
2992                     }
2993                     continue
2994                 }
2995             }
2996
2997             let subpat = self.parse_pat();
2998             if before_slice && self.check(&token::DotDot) {
2999                 self.bump();
3000                 slice = Some(subpat);
3001                 before_slice = false;
3002             } else if before_slice {
3003                 before.push(subpat);
3004             } else {
3005                 after.push(subpat);
3006             }
3007         }
3008
3009         (before, slice, after)
3010     }
3011
3012     /// Parse the fields of a struct-like pattern
3013     fn parse_pat_fields(&mut self) -> (Vec<codemap::Spanned<ast::FieldPat>> , bool) {
3014         let mut fields = Vec::new();
3015         let mut etc = false;
3016         let mut first = true;
3017         while self.token != token::CloseDelim(token::Brace) {
3018             if first {
3019                 first = false;
3020             } else {
3021                 self.expect(&token::Comma);
3022                 // accept trailing commas
3023                 if self.check(&token::CloseDelim(token::Brace)) { break }
3024             }
3025
3026             let lo = self.span.lo;
3027             let hi;
3028
3029             if self.check(&token::DotDot) {
3030                 self.bump();
3031                 if self.token != token::CloseDelim(token::Brace) {
3032                     let token_str = self.this_token_to_string();
3033                     self.fatal(&format!("expected `{}`, found `{}`", "}",
3034                                        token_str))
3035                 }
3036                 etc = true;
3037                 break;
3038             }
3039
3040             // Check if a colon exists one ahead. This means we're parsing a fieldname.
3041             let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3042                 // Parsing a pattern of the form "fieldname: pat"
3043                 let fieldname = self.parse_ident();
3044                 self.bump();
3045                 let pat = self.parse_pat();
3046                 hi = pat.span.hi;
3047                 (pat, fieldname, false)
3048             } else {
3049                 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3050                 let is_box = self.eat_keyword(keywords::Box);
3051                 let boxed_span_lo = self.span.lo;
3052                 let is_ref = self.eat_keyword(keywords::Ref);
3053                 let is_mut = self.eat_keyword(keywords::Mut);
3054                 let fieldname = self.parse_ident();
3055                 hi = self.last_span.hi;
3056
3057                 let bind_type = match (is_ref, is_mut) {
3058                     (true, true) => BindByRef(MutMutable),
3059                     (true, false) => BindByRef(MutImmutable),
3060                     (false, true) => BindByValue(MutMutable),
3061                     (false, false) => BindByValue(MutImmutable),
3062                 };
3063                 let fieldpath = codemap::Spanned{span:self.last_span, node:fieldname};
3064                 let fieldpat = P(ast::Pat{
3065                     id: ast::DUMMY_NODE_ID,
3066                     node: PatIdent(bind_type, fieldpath, None),
3067                     span: mk_sp(boxed_span_lo, hi),
3068                 });
3069
3070                 let subpat = if is_box {
3071                     P(ast::Pat{
3072                         id: ast::DUMMY_NODE_ID,
3073                         node: PatBox(fieldpat),
3074                         span: mk_sp(lo, hi),
3075                     })
3076                 } else {
3077                     fieldpat
3078                 };
3079                 (subpat, fieldname, true)
3080             };
3081
3082             fields.push(codemap::Spanned { span: mk_sp(lo, hi),
3083                                            node: ast::FieldPat { ident: fieldname,
3084                                                                  pat: subpat,
3085                                                                  is_shorthand: is_shorthand }});
3086         }
3087         return (fields, etc);
3088     }
3089
3090     /// Parse a pattern.
3091     pub fn parse_pat(&mut self) -> P<Pat> {
3092         maybe_whole!(self, NtPat);
3093
3094         let lo = self.span.lo;
3095         let mut hi;
3096         let pat;
3097         match self.token {
3098             // parse _
3099           token::Underscore => {
3100             self.bump();
3101             pat = PatWild(PatWildSingle);
3102             hi = self.last_span.hi;
3103             return P(ast::Pat {
3104                 id: ast::DUMMY_NODE_ID,
3105                 node: pat,
3106                 span: mk_sp(lo, hi)
3107             })
3108           }
3109           token::BinOp(token::And) | token::AndAnd => {
3110             // parse &pat and &mut pat
3111             let lo = self.span.lo;
3112             self.expect_and();
3113             let mutability = if self.eat_keyword(keywords::Mut) {
3114                 ast::MutMutable
3115             } else {
3116                 ast::MutImmutable
3117             };
3118             let sub = self.parse_pat();
3119             pat = PatRegion(sub, mutability);
3120             hi = self.last_span.hi;
3121             return P(ast::Pat {
3122                 id: ast::DUMMY_NODE_ID,
3123                 node: pat,
3124                 span: mk_sp(lo, hi)
3125             })
3126           }
3127           token::OpenDelim(token::Paren) => {
3128             // parse (pat,pat,pat,...) as tuple
3129             self.bump();
3130             if self.check(&token::CloseDelim(token::Paren)) {
3131                 self.bump();
3132                 pat = PatTup(vec![]);
3133             } else {
3134                 let mut fields = vec!(self.parse_pat());
3135                 if self.look_ahead(1, |t| *t != token::CloseDelim(token::Paren)) {
3136                     while self.check(&token::Comma) {
3137                         self.bump();
3138                         if self.check(&token::CloseDelim(token::Paren)) { break; }
3139                         fields.push(self.parse_pat());
3140                     }
3141                 }
3142                 if fields.len() == 1 { self.expect(&token::Comma); }
3143                 self.expect(&token::CloseDelim(token::Paren));
3144                 pat = PatTup(fields);
3145             }
3146             hi = self.last_span.hi;
3147             return P(ast::Pat {
3148                 id: ast::DUMMY_NODE_ID,
3149                 node: pat,
3150                 span: mk_sp(lo, hi)
3151             })
3152           }
3153           token::OpenDelim(token::Bracket) => {
3154             // parse [pat,pat,...] as vector pattern
3155             self.bump();
3156             let (before, slice, after) =
3157                 self.parse_pat_vec_elements();
3158
3159             self.expect(&token::CloseDelim(token::Bracket));
3160             pat = ast::PatVec(before, slice, after);
3161             hi = self.last_span.hi;
3162             return P(ast::Pat {
3163                 id: ast::DUMMY_NODE_ID,
3164                 node: pat,
3165                 span: mk_sp(lo, hi)
3166             })
3167           }
3168           _ => {}
3169         }
3170         // at this point, token != _, ~, &, &&, (, [
3171
3172         if (!(self.token.is_ident() || self.token.is_path())
3173               && self.token != token::ModSep)
3174                 || self.token.is_keyword(keywords::True)
3175                 || self.token.is_keyword(keywords::False) {
3176             // Parse an expression pattern or exp ... exp.
3177             //
3178             // These expressions are limited to literals (possibly
3179             // preceded by unary-minus) or identifiers.
3180             let val = self.parse_literal_maybe_minus();
3181             if (self.check(&token::DotDotDot)) &&
3182                     self.look_ahead(1, |t| {
3183                         *t != token::Comma && *t != token::CloseDelim(token::Bracket)
3184                     }) {
3185                 self.bump();
3186                 let end = if self.token.is_ident() || self.token.is_path() {
3187                     let path = self.parse_path(LifetimeAndTypesWithColons);
3188                     let hi = self.span.hi;
3189                     self.mk_expr(lo, hi, ExprPath(None, path))
3190                 } else {
3191                     self.parse_literal_maybe_minus()
3192                 };
3193                 pat = PatRange(val, end);
3194             } else {
3195                 pat = PatLit(val);
3196             }
3197         } else if self.eat_keyword(keywords::Mut) {
3198             pat = self.parse_pat_ident(BindByValue(MutMutable));
3199         } else if self.eat_keyword(keywords::Ref) {
3200             // parse ref pat
3201             let mutbl = self.parse_mutability();
3202             pat = self.parse_pat_ident(BindByRef(mutbl));
3203         } else if self.eat_keyword(keywords::Box) {
3204             // `box PAT`
3205             //
3206             // FIXME(#13910): Rename to `PatBox` and extend to full DST
3207             // support.
3208             let sub = self.parse_pat();
3209             pat = PatBox(sub);
3210             hi = self.last_span.hi;
3211             return P(ast::Pat {
3212                 id: ast::DUMMY_NODE_ID,
3213                 node: pat,
3214                 span: mk_sp(lo, hi)
3215             })
3216         } else {
3217             let can_be_enum_or_struct = self.look_ahead(1, |t| {
3218                 match *t {
3219                     token::OpenDelim(_) | token::Lt | token::ModSep => true,
3220                     _ => false,
3221                 }
3222             });
3223
3224             if self.look_ahead(1, |t| *t == token::DotDotDot) &&
3225                     self.look_ahead(2, |t| {
3226                         *t != token::Comma && *t != token::CloseDelim(token::Bracket)
3227                     }) {
3228                 let start = self.parse_expr_res(RESTRICTION_NO_BAR_OP);
3229                 self.eat(&token::DotDotDot);
3230                 let end = self.parse_expr_res(RESTRICTION_NO_BAR_OP);
3231                 pat = PatRange(start, end);
3232             } else if self.token.is_plain_ident() && !can_be_enum_or_struct {
3233                 let id = self.parse_ident();
3234                 let id_span = self.last_span;
3235                 let pth1 = codemap::Spanned{span:id_span, node: id};
3236                 if self.eat(&token::Not) {
3237                     // macro invocation
3238                     let delim = self.expect_open_delim();
3239                     let tts = self.parse_seq_to_end(&token::CloseDelim(delim),
3240                                                     seq_sep_none(),
3241                                                     |p| p.parse_token_tree());
3242
3243                     let mac = MacInvocTT(ident_to_path(id_span,id), tts, EMPTY_CTXT);
3244                     pat = ast::PatMac(codemap::Spanned {node: mac, span: self.span});
3245                 } else {
3246                     let sub = if self.eat(&token::At) {
3247                         // parse foo @ pat
3248                         Some(self.parse_pat())
3249                     } else {
3250                         // or just foo
3251                         None
3252                     };
3253                     pat = PatIdent(BindByValue(MutImmutable), pth1, sub);
3254                 }
3255             } else if self.look_ahead(1, |t| *t == token::Lt) {
3256                 self.bump();
3257                 self.unexpected()
3258             } else {
3259                 // parse an enum pat
3260                 let enum_path = self.parse_path(LifetimeAndTypesWithColons);
3261                 match self.token {
3262                     token::OpenDelim(token::Brace) => {
3263                         self.bump();
3264                         let (fields, etc) =
3265                             self.parse_pat_fields();
3266                         self.bump();
3267                         pat = PatStruct(enum_path, fields, etc);
3268                     }
3269                     token::DotDotDot => {
3270                         let hi = self.last_span.hi;
3271                         let start = self.mk_expr(lo, hi, ExprPath(None, enum_path));
3272                         self.eat(&token::DotDotDot);
3273                         let end = if self.token.is_ident() || self.token.is_path() {
3274                             let path = self.parse_path(LifetimeAndTypesWithColons);
3275                             let hi = self.span.hi;
3276                             self.mk_expr(lo, hi, ExprPath(None, path))
3277                         } else {
3278                             self.parse_literal_maybe_minus()
3279                         };
3280                         pat = PatRange(start, end);
3281                     }
3282                     _ => {
3283                         let mut args: Vec<P<Pat>> = Vec::new();
3284                         match self.token {
3285                           token::OpenDelim(token::Paren) => {
3286                             let is_dotdot = self.look_ahead(1, |t| {
3287                                 match *t {
3288                                     token::DotDot => true,
3289                                     _ => false,
3290                                 }
3291                             });
3292                             if is_dotdot {
3293                                 // This is a "top constructor only" pat
3294                                 self.bump();
3295                                 self.bump();
3296                                 self.expect(&token::CloseDelim(token::Paren));
3297                                 pat = PatEnum(enum_path, None);
3298                             } else {
3299                                 args = self.parse_enum_variant_seq(
3300                                     &token::OpenDelim(token::Paren),
3301                                     &token::CloseDelim(token::Paren),
3302                                     seq_sep_trailing_allowed(token::Comma),
3303                                     |p| p.parse_pat()
3304                                 );
3305                                 pat = PatEnum(enum_path, Some(args));
3306                             }
3307                           },
3308                           _ => {
3309                               if !enum_path.global &&
3310                                   enum_path.segments.len() == 1 &&
3311                                   enum_path.segments[0].parameters.is_empty()
3312                               {
3313                                 // NB: If enum_path is a single identifier,
3314                                 // this should not be reachable due to special
3315                                 // handling further above.
3316                                 //
3317                                 // However, previously a PatIdent got emitted
3318                                 // here, so we preserve the branch just in case.
3319                                 //
3320                                 // A rewrite of the logic in this function
3321                                 // would probably make this obvious.
3322                                 self.span_bug(enum_path.span,
3323                                               "ident only path should have been covered already");
3324                               } else {
3325                                   pat = PatEnum(enum_path, Some(args));
3326                               }
3327                           }
3328                         }
3329                     }
3330                 }
3331             }
3332         }
3333         hi = self.last_span.hi;
3334         P(ast::Pat {
3335             id: ast::DUMMY_NODE_ID,
3336             node: pat,
3337             span: mk_sp(lo, hi),
3338         })
3339     }
3340
3341     /// Parse ident or ident @ pat
3342     /// used by the copy foo and ref foo patterns to give a good
3343     /// error message when parsing mistakes like ref foo(a,b)
3344     fn parse_pat_ident(&mut self,
3345                        binding_mode: ast::BindingMode)
3346                        -> ast::Pat_ {
3347         if !self.token.is_plain_ident() {
3348             let span = self.span;
3349             let tok_str = self.this_token_to_string();
3350             self.span_fatal(span,
3351                             &format!("expected identifier, found `{}`", tok_str));
3352         }
3353         let ident = self.parse_ident();
3354         let last_span = self.last_span;
3355         let name = codemap::Spanned{span: last_span, node: ident};
3356         let sub = if self.eat(&token::At) {
3357             Some(self.parse_pat())
3358         } else {
3359             None
3360         };
3361
3362         // just to be friendly, if they write something like
3363         //   ref Some(i)
3364         // we end up here with ( as the current token.  This shortly
3365         // leads to a parse error.  Note that if there is no explicit
3366         // binding mode then we do not end up here, because the lookahead
3367         // will direct us over to parse_enum_variant()
3368         if self.token == token::OpenDelim(token::Paren) {
3369             let last_span = self.last_span;
3370             self.span_fatal(
3371                 last_span,
3372                 "expected identifier, found enum pattern");
3373         }
3374
3375         PatIdent(binding_mode, name, sub)
3376     }
3377
3378     /// Parse a local variable declaration
3379     fn parse_local(&mut self) -> P<Local> {
3380         let lo = self.span.lo;
3381         let pat = self.parse_pat();
3382
3383         let mut ty = None;
3384         if self.eat(&token::Colon) {
3385             ty = Some(self.parse_ty_sum());
3386         }
3387         let init = self.parse_initializer();
3388         P(ast::Local {
3389             ty: ty,
3390             pat: pat,
3391             init: init,
3392             id: ast::DUMMY_NODE_ID,
3393             span: mk_sp(lo, self.last_span.hi),
3394             source: LocalLet,
3395         })
3396     }
3397
3398     /// Parse a "let" stmt
3399     fn parse_let(&mut self) -> P<Decl> {
3400         let lo = self.span.lo;
3401         let local = self.parse_local();
3402         P(spanned(lo, self.last_span.hi, DeclLocal(local)))
3403     }
3404
3405     /// Parse a structure field
3406     fn parse_name_and_ty(&mut self, pr: Visibility,
3407                          attrs: Vec<Attribute> ) -> StructField {
3408         let lo = self.span.lo;
3409         if !self.token.is_plain_ident() {
3410             self.fatal("expected ident");
3411         }
3412         let name = self.parse_ident();
3413         self.expect(&token::Colon);
3414         let ty = self.parse_ty_sum();
3415         spanned(lo, self.last_span.hi, ast::StructField_ {
3416             kind: NamedField(name, pr),
3417             id: ast::DUMMY_NODE_ID,
3418             ty: ty,
3419             attrs: attrs,
3420         })
3421     }
3422
3423     /// Emit an expected item after attributes error.
3424     fn expected_item_err(&self, attrs: &[Attribute]) {
3425         let message = match attrs.last() {
3426             Some(&Attribute { node: ast::Attribute_ { is_sugared_doc: true, .. }, .. }) => {
3427                 "expected item after doc comment"
3428             }
3429             _ => "expected item after attributes",
3430         };
3431
3432         self.span_err(self.last_span, message);
3433     }
3434
3435     /// Parse a statement. may include decl.
3436     pub fn parse_stmt(&mut self) -> Option<P<Stmt>> {
3437         self.parse_stmt_().map(P)
3438     }
3439
3440     fn parse_stmt_(&mut self) -> Option<Stmt> {
3441         maybe_whole!(Some deref self, NtStmt);
3442
3443         fn check_expected_item(p: &mut Parser, attrs: &[Attribute]) {
3444             // If we have attributes then we should have an item
3445             if !attrs.is_empty() {
3446                 p.expected_item_err(attrs);
3447             }
3448         }
3449
3450         let lo = self.span.lo;
3451         let attrs = self.parse_outer_attributes();
3452
3453         Some(if self.check_keyword(keywords::Let) {
3454             check_expected_item(self, &attrs);
3455             self.expect_keyword(keywords::Let);
3456             let decl = self.parse_let();
3457             spanned(lo, decl.span.hi, StmtDecl(decl, ast::DUMMY_NODE_ID))
3458         } else if self.token.is_ident()
3459             && !self.token.is_any_keyword()
3460             && self.look_ahead(1, |t| *t == token::Not) {
3461             // it's a macro invocation:
3462
3463             check_expected_item(self, &attrs);
3464
3465             // Potential trouble: if we allow macros with paths instead of
3466             // idents, we'd need to look ahead past the whole path here...
3467             let pth = self.parse_path(NoTypesAllowed);
3468             self.bump();
3469
3470             let id = match self.token {
3471                 token::OpenDelim(_) => token::special_idents::invalid, // no special identifier
3472                 _ => self.parse_ident(),
3473             };
3474
3475             // check that we're pointing at delimiters (need to check
3476             // again after the `if`, because of `parse_ident`
3477             // consuming more tokens).
3478             let delim = match self.token {
3479                 token::OpenDelim(delim) => delim,
3480                 _ => {
3481                     // we only expect an ident if we didn't parse one
3482                     // above.
3483                     let ident_str = if id.name == token::special_idents::invalid.name {
3484                         "identifier, "
3485                     } else {
3486                         ""
3487                     };
3488                     let tok_str = self.this_token_to_string();
3489                     self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
3490                                        ident_str,
3491                                        tok_str))
3492                 },
3493             };
3494
3495             let tts = self.parse_unspanned_seq(
3496                 &token::OpenDelim(delim),
3497                 &token::CloseDelim(delim),
3498                 seq_sep_none(),
3499                 |p| p.parse_token_tree()
3500             );
3501             let hi = self.span.hi;
3502
3503             let style = if delim == token::Brace {
3504                 MacStmtWithBraces
3505             } else {
3506                 MacStmtWithoutBraces
3507             };
3508
3509             if id.name == token::special_idents::invalid.name {
3510                 spanned(lo, hi,
3511                         StmtMac(P(spanned(lo,
3512                                           hi,
3513                                           MacInvocTT(pth, tts, EMPTY_CTXT))),
3514                                   style))
3515             } else {
3516                 // if it has a special ident, it's definitely an item
3517                 //
3518                 // Require a semicolon or braces.
3519                 if style != MacStmtWithBraces {
3520                     if !self.eat(&token::Semi) {
3521                         let last_span = self.last_span;
3522                         self.span_err(last_span,
3523                                       "macros that expand to items must \
3524                                        either be surrounded with braces or \
3525                                        followed by a semicolon");
3526                     }
3527                 }
3528                 spanned(lo, hi, StmtDecl(
3529                     P(spanned(lo, hi, DeclItem(
3530                         self.mk_item(
3531                             lo, hi, id /*id is good here*/,
3532                             ItemMac(spanned(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT))),
3533                             Inherited, Vec::new(/*no attrs*/))))),
3534                     ast::DUMMY_NODE_ID))
3535             }
3536         } else {
3537             match self.parse_item_(attrs, false) {
3538                 Some(i) => {
3539                     let hi = i.span.hi;
3540                     let decl = P(spanned(lo, hi, DeclItem(i)));
3541                     spanned(lo, hi, StmtDecl(decl, ast::DUMMY_NODE_ID))
3542                 }
3543                 None => {
3544                     // Do not attempt to parse an expression if we're done here.
3545                     if self.token == token::Semi {
3546                         self.bump();
3547                         return None;
3548                     }
3549
3550                     if self.token == token::CloseDelim(token::Brace) {
3551                         return None;
3552                     }
3553
3554                     // Remainder are line-expr stmts.
3555                     let e = self.parse_expr_res(RESTRICTION_STMT_EXPR);
3556                     spanned(lo, e.span.hi, StmtExpr(e, ast::DUMMY_NODE_ID))
3557                 }
3558             }
3559         })
3560     }
3561
3562     /// Is this expression a successfully-parsed statement?
3563     fn expr_is_complete(&mut self, e: &Expr) -> bool {
3564         self.restrictions.contains(RESTRICTION_STMT_EXPR) &&
3565             !classify::expr_requires_semi_to_be_stmt(e)
3566     }
3567
3568     /// Parse a block. No inner attrs are allowed.
3569     pub fn parse_block(&mut self) -> P<Block> {
3570         maybe_whole!(no_clone self, NtBlock);
3571
3572         let lo = self.span.lo;
3573
3574         if !self.eat(&token::OpenDelim(token::Brace)) {
3575             let sp = self.span;
3576             let tok = self.this_token_to_string();
3577             self.span_fatal_help(sp,
3578                                  &format!("expected `{{`, found `{}`", tok),
3579                                  "place this code inside a block");
3580         }
3581
3582         self.parse_block_tail(lo, DefaultBlock)
3583     }
3584
3585     /// Parse a block. Inner attrs are allowed.
3586     fn parse_inner_attrs_and_block(&mut self) -> (Vec<Attribute>, P<Block>) {
3587         maybe_whole!(pair_empty self, NtBlock);
3588
3589         let lo = self.span.lo;
3590         self.expect(&token::OpenDelim(token::Brace));
3591         (self.parse_inner_attributes(),
3592          self.parse_block_tail(lo, DefaultBlock))
3593     }
3594
3595     /// Parse the rest of a block expression or function body
3596     /// Precondition: already parsed the '{'.
3597     fn parse_block_tail(&mut self, lo: BytePos, s: BlockCheckMode) -> P<Block> {
3598         let mut stmts = vec![];
3599         let mut expr = None;
3600
3601         while !self.eat(&token::CloseDelim(token::Brace)) {
3602             let Spanned {node, span} = if let Some(s) = self.parse_stmt_() {
3603                 s
3604             } else {
3605                 // Found only `;` or `}`.
3606                 continue;
3607             };
3608             match node {
3609                 StmtExpr(e, _) => {
3610                     self.handle_expression_like_statement(e, span, &mut stmts, &mut expr);
3611                 }
3612                 StmtMac(mac, MacStmtWithoutBraces) => {
3613                     // statement macro without braces; might be an
3614                     // expr depending on whether a semicolon follows
3615                     match self.token {
3616                         token::Semi => {
3617                             stmts.push(P(Spanned {
3618                                 node: StmtMac(mac, MacStmtWithSemicolon),
3619                                 span: span,
3620                             }));
3621                             self.bump();
3622                         }
3623                         _ => {
3624                             let e = self.mk_mac_expr(span.lo, span.hi,
3625                                                      mac.and_then(|m| m.node));
3626                             let e = self.parse_dot_or_call_expr_with(e);
3627                             let e = self.parse_more_binops(e, 0);
3628                             let e = self.parse_assign_expr_with(e);
3629                             self.handle_expression_like_statement(
3630                                 e,
3631                                 span,
3632                                 &mut stmts,
3633                                 &mut expr);
3634                         }
3635                     }
3636                 }
3637                 StmtMac(m, style) => {
3638                     // statement macro; might be an expr
3639                     match self.token {
3640                         token::Semi => {
3641                             stmts.push(P(Spanned {
3642                                 node: StmtMac(m, MacStmtWithSemicolon),
3643                                 span: span,
3644                             }));
3645                             self.bump();
3646                         }
3647                         token::CloseDelim(token::Brace) => {
3648                             // if a block ends in `m!(arg)` without
3649                             // a `;`, it must be an expr
3650                             expr = Some(self.mk_mac_expr(span.lo, span.hi,
3651                                                          m.and_then(|x| x.node)));
3652                         }
3653                         _ => {
3654                             stmts.push(P(Spanned {
3655                                 node: StmtMac(m, style),
3656                                 span: span
3657                             }));
3658                         }
3659                     }
3660                 }
3661                 _ => { // all other kinds of statements:
3662                     if classify::stmt_ends_with_semi(&node) {
3663                         self.commit_stmt_expecting(token::Semi);
3664                     }
3665
3666                     stmts.push(P(Spanned {
3667                         node: node,
3668                         span: span
3669                     }));
3670                 }
3671             }
3672         }
3673
3674         P(ast::Block {
3675             stmts: stmts,
3676             expr: expr,
3677             id: ast::DUMMY_NODE_ID,
3678             rules: s,
3679             span: mk_sp(lo, self.last_span.hi),
3680         })
3681     }
3682
3683     fn handle_expression_like_statement(
3684             &mut self,
3685             e: P<Expr>,
3686             span: Span,
3687             stmts: &mut Vec<P<Stmt>>,
3688             last_block_expr: &mut Option<P<Expr>>) {
3689         // expression without semicolon
3690         if classify::expr_requires_semi_to_be_stmt(&*e) {
3691             // Just check for errors and recover; do not eat semicolon yet.
3692             self.commit_stmt(&[],
3693                              &[token::Semi, token::CloseDelim(token::Brace)]);
3694         }
3695
3696         match self.token {
3697             token::Semi => {
3698                 self.bump();
3699                 let span_with_semi = Span {
3700                     lo: span.lo,
3701                     hi: self.last_span.hi,
3702                     expn_id: span.expn_id,
3703                 };
3704                 stmts.push(P(Spanned {
3705                     node: StmtSemi(e, ast::DUMMY_NODE_ID),
3706                     span: span_with_semi,
3707                 }));
3708             }
3709             token::CloseDelim(token::Brace) => *last_block_expr = Some(e),
3710             _ => {
3711                 stmts.push(P(Spanned {
3712                     node: StmtExpr(e, ast::DUMMY_NODE_ID),
3713                     span: span
3714                 }));
3715             }
3716         }
3717     }
3718
3719     // Parses a sequence of bounds if a `:` is found,
3720     // otherwise returns empty list.
3721     fn parse_colon_then_ty_param_bounds(&mut self,
3722                                         mode: BoundParsingMode)
3723                                         -> OwnedSlice<TyParamBound>
3724     {
3725         if !self.eat(&token::Colon) {
3726             OwnedSlice::empty()
3727         } else {
3728             self.parse_ty_param_bounds(mode)
3729         }
3730     }
3731
3732     // matches bounds    = ( boundseq )?
3733     // where   boundseq  = ( polybound + boundseq ) | polybound
3734     // and     polybound = ( 'for' '<' 'region '>' )? bound
3735     // and     bound     = 'region | trait_ref
3736     fn parse_ty_param_bounds(&mut self,
3737                              mode: BoundParsingMode)
3738                              -> OwnedSlice<TyParamBound>
3739     {
3740         let mut result = vec!();
3741         loop {
3742             let question_span = self.span;
3743             let ate_question = self.eat(&token::Question);
3744             match self.token {
3745                 token::Lifetime(lifetime) => {
3746                     if ate_question {
3747                         self.span_err(question_span,
3748                                       "`?` may only modify trait bounds, not lifetime bounds");
3749                     }
3750                     result.push(RegionTyParamBound(ast::Lifetime {
3751                         id: ast::DUMMY_NODE_ID,
3752                         span: self.span,
3753                         name: lifetime.name
3754                     }));
3755                     self.bump();
3756                 }
3757                 token::ModSep | token::Ident(..) => {
3758                     let poly_trait_ref = self.parse_poly_trait_ref();
3759                     let modifier = if ate_question {
3760                         if mode == BoundParsingMode::Modified {
3761                             TraitBoundModifier::Maybe
3762                         } else {
3763                             self.span_err(question_span,
3764                                           "unexpected `?`");
3765                             TraitBoundModifier::None
3766                         }
3767                     } else {
3768                         TraitBoundModifier::None
3769                     };
3770                     result.push(TraitTyParamBound(poly_trait_ref, modifier))
3771                 }
3772                 _ => break,
3773             }
3774
3775             if !self.eat(&token::BinOp(token::Plus)) {
3776                 break;
3777             }
3778         }
3779
3780         return OwnedSlice::from_vec(result);
3781     }
3782
3783     /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
3784     fn parse_ty_param(&mut self) -> TyParam {
3785         let span = self.span;
3786         let ident = self.parse_ident();
3787
3788         let bounds = self.parse_colon_then_ty_param_bounds(BoundParsingMode::Modified);
3789
3790         let default = if self.check(&token::Eq) {
3791             self.bump();
3792             Some(self.parse_ty_sum())
3793         } else {
3794             None
3795         };
3796
3797         TyParam {
3798             ident: ident,
3799             id: ast::DUMMY_NODE_ID,
3800             bounds: bounds,
3801             default: default,
3802             span: span,
3803         }
3804     }
3805
3806     /// Parse a set of optional generic type parameter declarations. Where
3807     /// clauses are not parsed here, and must be added later via
3808     /// `parse_where_clause()`.
3809     ///
3810     /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
3811     ///                  | ( < lifetimes , typaramseq ( , )? > )
3812     /// where   typaramseq = ( typaram ) | ( typaram , typaramseq )
3813     pub fn parse_generics(&mut self) -> ast::Generics {
3814         if self.eat(&token::Lt) {
3815             let lifetime_defs = self.parse_lifetime_defs();
3816             let mut seen_default = false;
3817             let ty_params = self.parse_seq_to_gt(Some(token::Comma), |p| {
3818                 p.forbid_lifetime();
3819                 let ty_param = p.parse_ty_param();
3820                 if ty_param.default.is_some() {
3821                     seen_default = true;
3822                 } else if seen_default {
3823                     let last_span = p.last_span;
3824                     p.span_err(last_span,
3825                                "type parameters with a default must be trailing");
3826                 }
3827                 ty_param
3828             });
3829             ast::Generics {
3830                 lifetimes: lifetime_defs,
3831                 ty_params: ty_params,
3832                 where_clause: WhereClause {
3833                     id: ast::DUMMY_NODE_ID,
3834                     predicates: Vec::new(),
3835                 }
3836             }
3837         } else {
3838             ast_util::empty_generics()
3839         }
3840     }
3841
3842     fn parse_generic_values_after_lt(&mut self)
3843                                      -> (Vec<ast::Lifetime>, Vec<P<Ty>>, Vec<P<TypeBinding>>) {
3844         let lifetimes = self.parse_lifetimes(token::Comma);
3845
3846         // First parse types.
3847         let (types, returned) = self.parse_seq_to_gt_or_return(
3848             Some(token::Comma),
3849             |p| {
3850                 p.forbid_lifetime();
3851                 if p.look_ahead(1, |t| t == &token::Eq) {
3852                     None
3853                 } else {
3854                     Some(p.parse_ty_sum())
3855                 }
3856             }
3857         );
3858
3859         // If we found the `>`, don't continue.
3860         if !returned {
3861             return (lifetimes, types.into_vec(), Vec::new());
3862         }
3863
3864         // Then parse type bindings.
3865         let bindings = self.parse_seq_to_gt(
3866             Some(token::Comma),
3867             |p| {
3868                 p.forbid_lifetime();
3869                 let lo = p.span.lo;
3870                 let ident = p.parse_ident();
3871                 let found_eq = p.eat(&token::Eq);
3872                 if !found_eq {
3873                     let span = p.span;
3874                     p.span_warn(span, "whoops, no =?");
3875                 }
3876                 let ty = p.parse_ty();
3877                 let hi = p.span.hi;
3878                 let span = mk_sp(lo, hi);
3879                 return P(TypeBinding{id: ast::DUMMY_NODE_ID,
3880                     ident: ident,
3881                     ty: ty,
3882                     span: span,
3883                 });
3884             }
3885         );
3886         (lifetimes, types.into_vec(), bindings.into_vec())
3887     }
3888
3889     fn forbid_lifetime(&mut self) {
3890         if self.token.is_lifetime() {
3891             let span = self.span;
3892             self.span_fatal(span, "lifetime parameters must be declared \
3893                                         prior to type parameters");
3894         }
3895     }
3896
3897     /// Parses an optional `where` clause and places it in `generics`.
3898     ///
3899     /// ```
3900     /// where T : Trait<U, V> + 'b, 'a : 'b
3901     /// ```
3902     fn parse_where_clause(&mut self) -> ast::WhereClause {
3903         let mut where_clause = WhereClause {
3904             id: ast::DUMMY_NODE_ID,
3905             predicates: Vec::new(),
3906         };
3907
3908         if !self.eat_keyword(keywords::Where) {
3909             return where_clause;
3910         }
3911
3912         let mut parsed_something = false;
3913         loop {
3914             let lo = self.span.lo;
3915             match self.token {
3916                 token::OpenDelim(token::Brace) => {
3917                     break
3918                 }
3919
3920                 token::Lifetime(..) => {
3921                     let bounded_lifetime =
3922                         self.parse_lifetime();
3923
3924                     self.eat(&token::Colon);
3925
3926                     let bounds =
3927                         self.parse_lifetimes(token::BinOp(token::Plus));
3928
3929                     let hi = self.span.hi;
3930                     let span = mk_sp(lo, hi);
3931
3932                     where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
3933                         ast::WhereRegionPredicate {
3934                             span: span,
3935                             lifetime: bounded_lifetime,
3936                             bounds: bounds
3937                         }
3938                     ));
3939
3940                     parsed_something = true;
3941                 }
3942
3943                 _ => {
3944                     let bound_lifetimes = if self.eat_keyword(keywords::For) {
3945                         // Higher ranked constraint.
3946                         self.expect(&token::Lt);
3947                         let lifetime_defs = self.parse_lifetime_defs();
3948                         self.expect_gt();
3949                         lifetime_defs
3950                     } else {
3951                         vec![]
3952                     };
3953
3954                     let bounded_ty = self.parse_ty();
3955
3956                     if self.eat(&token::Colon) {
3957                         let bounds = self.parse_ty_param_bounds(BoundParsingMode::Bare);
3958                         let hi = self.span.hi;
3959                         let span = mk_sp(lo, hi);
3960
3961                         if bounds.len() == 0 {
3962                             self.span_err(span,
3963                                           "each predicate in a `where` clause must have \
3964                                            at least one bound in it");
3965                         }
3966
3967                         where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
3968                                 ast::WhereBoundPredicate {
3969                                     span: span,
3970                                     bound_lifetimes: bound_lifetimes,
3971                                     bounded_ty: bounded_ty,
3972                                     bounds: bounds,
3973                         }));
3974
3975                         parsed_something = true;
3976                     } else if self.eat(&token::Eq) {
3977                         // let ty = self.parse_ty();
3978                         let hi = self.span.hi;
3979                         let span = mk_sp(lo, hi);
3980                         // where_clause.predicates.push(
3981                         //     ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
3982                         //         id: ast::DUMMY_NODE_ID,
3983                         //         span: span,
3984                         //         path: panic!("NYI"), //bounded_ty,
3985                         //         ty: ty,
3986                         // }));
3987                         // parsed_something = true;
3988                         // // FIXME(#18433)
3989                         self.span_err(span,
3990                                      "equality constraints are not yet supported \
3991                                      in where clauses (#20041)");
3992                     } else {
3993                         let last_span = self.last_span;
3994                         self.span_err(last_span,
3995                               "unexpected token in `where` clause");
3996                     }
3997                 }
3998             };
3999
4000             if !self.eat(&token::Comma) {
4001                 break
4002             }
4003         }
4004
4005         if !parsed_something {
4006             let last_span = self.last_span;
4007             self.span_err(last_span,
4008                           "a `where` clause must have at least one predicate \
4009                            in it");
4010         }
4011
4012         where_clause
4013     }
4014
4015     fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
4016                      -> (Vec<Arg> , bool) {
4017         let sp = self.span;
4018         let mut args: Vec<Option<Arg>> =
4019             self.parse_unspanned_seq(
4020                 &token::OpenDelim(token::Paren),
4021                 &token::CloseDelim(token::Paren),
4022                 seq_sep_trailing_allowed(token::Comma),
4023                 |p| {
4024                     if p.token == token::DotDotDot {
4025                         p.bump();
4026                         if allow_variadic {
4027                             if p.token != token::CloseDelim(token::Paren) {
4028                                 let span = p.span;
4029                                 p.span_fatal(span,
4030                                     "`...` must be last in argument list for variadic function");
4031                             }
4032                         } else {
4033                             let span = p.span;
4034                             p.span_fatal(span,
4035                                          "only foreign functions are allowed to be variadic");
4036                         }
4037                         None
4038                     } else {
4039                         Some(p.parse_arg_general(named_args))
4040                     }
4041                 }
4042             );
4043
4044         let variadic = match args.pop() {
4045             Some(None) => true,
4046             Some(x) => {
4047                 // Need to put back that last arg
4048                 args.push(x);
4049                 false
4050             }
4051             None => false
4052         };
4053
4054         if variadic && args.is_empty() {
4055             self.span_err(sp,
4056                           "variadic function must be declared with at least one named argument");
4057         }
4058
4059         let args = args.into_iter().map(|x| x.unwrap()).collect();
4060
4061         (args, variadic)
4062     }
4063
4064     /// Parse the argument list and result type of a function declaration
4065     pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> P<FnDecl> {
4066
4067         let (args, variadic) = self.parse_fn_args(true, allow_variadic);
4068         let ret_ty = self.parse_ret_ty();
4069
4070         P(FnDecl {
4071             inputs: args,
4072             output: ret_ty,
4073             variadic: variadic
4074         })
4075     }
4076
4077     fn is_self_ident(&mut self) -> bool {
4078         match self.token {
4079           token::Ident(id, token::Plain) => id.name == special_idents::self_.name,
4080           _ => false
4081         }
4082     }
4083
4084     fn expect_self_ident(&mut self) -> ast::Ident {
4085         match self.token {
4086             token::Ident(id, token::Plain) if id.name == special_idents::self_.name => {
4087                 self.bump();
4088                 id
4089             },
4090             _ => {
4091                 let token_str = self.this_token_to_string();
4092                 self.fatal(&format!("expected `self`, found `{}`",
4093                                    token_str))
4094             }
4095         }
4096     }
4097
4098     fn is_self_type_ident(&mut self) -> bool {
4099         match self.token {
4100           token::Ident(id, token::Plain) => id.name == special_idents::type_self.name,
4101           _ => false
4102         }
4103     }
4104
4105     fn expect_self_type_ident(&mut self) -> ast::Ident {
4106         match self.token {
4107             token::Ident(id, token::Plain) if id.name == special_idents::type_self.name => {
4108                 self.bump();
4109                 id
4110             },
4111             _ => {
4112                 let token_str = self.this_token_to_string();
4113                 self.fatal(&format!("expected `Self`, found `{}`",
4114                                    token_str))
4115             }
4116         }
4117     }
4118
4119     /// Parse the argument list and result type of a function
4120     /// that may have a self type.
4121     fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> (ExplicitSelf, P<FnDecl>) where
4122         F: FnMut(&mut Parser) -> Arg,
4123     {
4124         fn maybe_parse_borrowed_explicit_self(this: &mut Parser)
4125                                               -> ast::ExplicitSelf_ {
4126             // The following things are possible to see here:
4127             //
4128             //     fn(&mut self)
4129             //     fn(&mut self)
4130             //     fn(&'lt self)
4131             //     fn(&'lt mut self)
4132             //
4133             // We already know that the current token is `&`.
4134
4135             if this.look_ahead(1, |t| t.is_keyword(keywords::SelfValue)) {
4136                 this.bump();
4137                 SelfRegion(None, MutImmutable, this.expect_self_ident())
4138             } else if this.look_ahead(1, |t| t.is_mutability()) &&
4139                       this.look_ahead(2, |t| t.is_keyword(keywords::SelfValue)) {
4140                 this.bump();
4141                 let mutability = this.parse_mutability();
4142                 SelfRegion(None, mutability, this.expect_self_ident())
4143             } else if this.look_ahead(1, |t| t.is_lifetime()) &&
4144                       this.look_ahead(2, |t| t.is_keyword(keywords::SelfValue)) {
4145                 this.bump();
4146                 let lifetime = this.parse_lifetime();
4147                 SelfRegion(Some(lifetime), MutImmutable, this.expect_self_ident())
4148             } else if this.look_ahead(1, |t| t.is_lifetime()) &&
4149                       this.look_ahead(2, |t| t.is_mutability()) &&
4150                       this.look_ahead(3, |t| t.is_keyword(keywords::SelfValue)) {
4151                 this.bump();
4152                 let lifetime = this.parse_lifetime();
4153                 let mutability = this.parse_mutability();
4154                 SelfRegion(Some(lifetime), mutability, this.expect_self_ident())
4155             } else {
4156                 SelfStatic
4157             }
4158         }
4159
4160         self.expect(&token::OpenDelim(token::Paren));
4161
4162         // A bit of complexity and lookahead is needed here in order to be
4163         // backwards compatible.
4164         let lo = self.span.lo;
4165         let mut self_ident_lo = self.span.lo;
4166         let mut self_ident_hi = self.span.hi;
4167
4168         let mut mutbl_self = MutImmutable;
4169         let explicit_self = match self.token {
4170             token::BinOp(token::And) => {
4171                 let eself = maybe_parse_borrowed_explicit_self(self);
4172                 self_ident_lo = self.last_span.lo;
4173                 self_ident_hi = self.last_span.hi;
4174                 eself
4175             }
4176             token::BinOp(token::Star) => {
4177                 // Possibly "*self" or "*mut self" -- not supported. Try to avoid
4178                 // emitting cryptic "unexpected token" errors.
4179                 self.bump();
4180                 let _mutability = if self.token.is_mutability() {
4181                     self.parse_mutability()
4182                 } else {
4183                     MutImmutable
4184                 };
4185                 if self.is_self_ident() {
4186                     let span = self.span;
4187                     self.span_err(span, "cannot pass self by unsafe pointer");
4188                     self.bump();
4189                 }
4190                 // error case, making bogus self ident:
4191                 SelfValue(special_idents::self_)
4192             }
4193             token::Ident(..) => {
4194                 if self.is_self_ident() {
4195                     let self_ident = self.expect_self_ident();
4196
4197                     // Determine whether this is the fully explicit form, `self:
4198                     // TYPE`.
4199                     if self.eat(&token::Colon) {
4200                         SelfExplicit(self.parse_ty_sum(), self_ident)
4201                     } else {
4202                         SelfValue(self_ident)
4203                     }
4204                 } else if self.token.is_mutability() &&
4205                         self.look_ahead(1, |t| t.is_keyword(keywords::SelfValue)) {
4206                     mutbl_self = self.parse_mutability();
4207                     let self_ident = self.expect_self_ident();
4208
4209                     // Determine whether this is the fully explicit form,
4210                     // `self: TYPE`.
4211                     if self.eat(&token::Colon) {
4212                         SelfExplicit(self.parse_ty_sum(), self_ident)
4213                     } else {
4214                         SelfValue(self_ident)
4215                     }
4216                 } else {
4217                     SelfStatic
4218                 }
4219             }
4220             _ => SelfStatic,
4221         };
4222
4223         let explicit_self_sp = mk_sp(self_ident_lo, self_ident_hi);
4224
4225         // shared fall-through for the three cases below. borrowing prevents simply
4226         // writing this as a closure
4227         macro_rules! parse_remaining_arguments {
4228             ($self_id:ident) =>
4229             {
4230             // If we parsed a self type, expect a comma before the argument list.
4231             match self.token {
4232                 token::Comma => {
4233                     self.bump();
4234                     let sep = seq_sep_trailing_allowed(token::Comma);
4235                     let mut fn_inputs = self.parse_seq_to_before_end(
4236                         &token::CloseDelim(token::Paren),
4237                         sep,
4238                         parse_arg_fn
4239                     );
4240                     fn_inputs.insert(0, Arg::new_self(explicit_self_sp, mutbl_self, $self_id));
4241                     fn_inputs
4242                 }
4243                 token::CloseDelim(token::Paren) => {
4244                     vec!(Arg::new_self(explicit_self_sp, mutbl_self, $self_id))
4245                 }
4246                 _ => {
4247                     let token_str = self.this_token_to_string();
4248                     self.fatal(&format!("expected `,` or `)`, found `{}`",
4249                                        token_str))
4250                 }
4251             }
4252             }
4253         }
4254
4255         let fn_inputs = match explicit_self {
4256             SelfStatic =>  {
4257                 let sep = seq_sep_trailing_allowed(token::Comma);
4258                 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)
4259             }
4260             SelfValue(id) => parse_remaining_arguments!(id),
4261             SelfRegion(_,_,id) => parse_remaining_arguments!(id),
4262             SelfExplicit(_,id) => parse_remaining_arguments!(id),
4263         };
4264
4265
4266         self.expect(&token::CloseDelim(token::Paren));
4267
4268         let hi = self.span.hi;
4269
4270         let ret_ty = self.parse_ret_ty();
4271
4272         let fn_decl = P(FnDecl {
4273             inputs: fn_inputs,
4274             output: ret_ty,
4275             variadic: false
4276         });
4277
4278         (spanned(lo, hi, explicit_self), fn_decl)
4279     }
4280
4281     // parse the |arg, arg| header on a lambda
4282     fn parse_fn_block_decl(&mut self) -> P<FnDecl> {
4283         let inputs_captures = {
4284             if self.eat(&token::OrOr) {
4285                 Vec::new()
4286             } else {
4287                 self.expect(&token::BinOp(token::Or));
4288                 self.parse_obsolete_closure_kind();
4289                 let args = self.parse_seq_to_before_end(
4290                     &token::BinOp(token::Or),
4291                     seq_sep_trailing_allowed(token::Comma),
4292                     |p| p.parse_fn_block_arg()
4293                 );
4294                 self.bump();
4295                 args
4296             }
4297         };
4298         let output = self.parse_ret_ty();
4299
4300         P(FnDecl {
4301             inputs: inputs_captures,
4302             output: output,
4303             variadic: false
4304         })
4305     }
4306
4307     /// Parse the name and optional generic types of a function header.
4308     fn parse_fn_header(&mut self) -> (Ident, ast::Generics) {
4309         let id = self.parse_ident();
4310         let generics = self.parse_generics();
4311         (id, generics)
4312     }
4313
4314     fn mk_item(&mut self, lo: BytePos, hi: BytePos, ident: Ident,
4315                node: Item_, vis: Visibility,
4316                attrs: Vec<Attribute>) -> P<Item> {
4317         P(Item {
4318             ident: ident,
4319             attrs: attrs,
4320             id: ast::DUMMY_NODE_ID,
4321             node: node,
4322             vis: vis,
4323             span: mk_sp(lo, hi)
4324         })
4325     }
4326
4327     /// Parse an item-position function declaration.
4328     fn parse_item_fn(&mut self, unsafety: Unsafety, abi: abi::Abi) -> ItemInfo {
4329         let (ident, mut generics) = self.parse_fn_header();
4330         let decl = self.parse_fn_decl(false);
4331         generics.where_clause = self.parse_where_clause();
4332         let (inner_attrs, body) = self.parse_inner_attrs_and_block();
4333         (ident, ItemFn(decl, unsafety, abi, generics, body), Some(inner_attrs))
4334     }
4335
4336     /// Parse an impl item.
4337     pub fn parse_impl_item(&mut self) -> P<ImplItem> {
4338         let lo = self.span.lo;
4339         let mut attrs = self.parse_outer_attributes();
4340         let vis = self.parse_visibility();
4341         let (name, node) = if self.eat_keyword(keywords::Type) {
4342             let name = self.parse_ident();
4343             self.expect(&token::Eq);
4344             let typ = self.parse_ty_sum();
4345             self.expect(&token::Semi);
4346             (name, TypeImplItem(typ))
4347         } else {
4348             let (name, inner_attrs, node) = self.parse_impl_method(vis);
4349             attrs.extend(inner_attrs.into_iter());
4350             (name, node)
4351         };
4352
4353         P(ImplItem {
4354             id: ast::DUMMY_NODE_ID,
4355             span: mk_sp(lo, self.last_span.hi),
4356             ident: name,
4357             vis: vis,
4358             attrs: attrs,
4359             node: node
4360         })
4361     }
4362
4363     fn complain_if_pub_macro(&mut self, visa: Visibility, span: Span) {
4364         match visa {
4365             Public => {
4366                 self.span_err(span, "can't qualify macro invocation with `pub`");
4367                 self.fileline_help(span, "try adjusting the macro to put `pub` inside \
4368                                       the invocation");
4369             }
4370             Inherited => (),
4371         }
4372     }
4373
4374     /// Parse a method or a macro invocation in a trait impl.
4375     fn parse_impl_method(&mut self, vis: Visibility)
4376                          -> (Ident, Vec<ast::Attribute>, ast::ImplItem_) {
4377         // code copied from parse_macro_use_or_failure... abstraction!
4378         if !self.token.is_any_keyword()
4379             && self.look_ahead(1, |t| *t == token::Not)
4380             && (self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren))
4381                 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) {
4382             // method macro.
4383
4384             let last_span = self.last_span;
4385             self.complain_if_pub_macro(vis, last_span);
4386
4387             let pth = self.parse_path(NoTypesAllowed);
4388             self.expect(&token::Not);
4389
4390             // eat a matched-delimiter token tree:
4391             let delim = self.expect_open_delim();
4392             let tts = self.parse_seq_to_end(&token::CloseDelim(delim),
4393                                             seq_sep_none(),
4394                                             |p| p.parse_token_tree());
4395             let m_ = ast::MacInvocTT(pth, tts, EMPTY_CTXT);
4396             let m: ast::Mac = codemap::Spanned { node: m_,
4397                                                 span: mk_sp(self.span.lo,
4398                                                             self.span.hi) };
4399             if delim != token::Brace {
4400                 self.expect(&token::Semi)
4401             }
4402             (token::special_idents::invalid, vec![], ast::MacImplItem(m))
4403         } else {
4404             let unsafety = self.parse_unsafety();
4405             let abi = if self.eat_keyword(keywords::Extern) {
4406                 self.parse_opt_abi().unwrap_or(abi::C)
4407             } else {
4408                 abi::Rust
4409             };
4410             self.expect_keyword(keywords::Fn);
4411             let ident = self.parse_ident();
4412             let mut generics = self.parse_generics();
4413             let (explicit_self, decl) = self.parse_fn_decl_with_self(|p| {
4414                     p.parse_arg()
4415                 });
4416             generics.where_clause = self.parse_where_clause();
4417             let (inner_attrs, body) = self.parse_inner_attrs_and_block();
4418             (ident, inner_attrs, MethodImplItem(ast::MethodSig {
4419                 generics: generics,
4420                 abi: abi,
4421                 explicit_self: explicit_self,
4422                 unsafety: unsafety,
4423                 decl: decl
4424              }, body))
4425         }
4426     }
4427
4428     /// Parse trait Foo { ... }
4429     fn parse_item_trait(&mut self, unsafety: Unsafety) -> ItemInfo {
4430
4431         let ident = self.parse_ident();
4432         let mut tps = self.parse_generics();
4433
4434         // Parse supertrait bounds.
4435         let bounds = self.parse_colon_then_ty_param_bounds(BoundParsingMode::Bare);
4436
4437         tps.where_clause = self.parse_where_clause();
4438
4439         let meths = self.parse_trait_items();
4440         (ident, ItemTrait(unsafety, tps, bounds, meths), None)
4441     }
4442
4443     /// Parses items implementations variants
4444     ///    impl<T> Foo { ... }
4445     ///    impl<T> ToString for &'static T { ... }
4446     ///    impl Send for .. {}
4447     fn parse_item_impl(&mut self, unsafety: ast::Unsafety) -> ItemInfo {
4448         let impl_span = self.span;
4449
4450         // First, parse type parameters if necessary.
4451         let mut generics = self.parse_generics();
4452
4453         // Special case: if the next identifier that follows is '(', don't
4454         // allow this to be parsed as a trait.
4455         let could_be_trait = self.token != token::OpenDelim(token::Paren);
4456
4457         let neg_span = self.span;
4458         let polarity = if self.eat(&token::Not) {
4459             ast::ImplPolarity::Negative
4460         } else {
4461             ast::ImplPolarity::Positive
4462         };
4463
4464         // Parse the trait.
4465         let mut ty = self.parse_ty_sum();
4466
4467         // Parse traits, if necessary.
4468         let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) {
4469             // New-style trait. Reinterpret the type as a trait.
4470             match ty.node {
4471                 TyPath(None, ref path) => {
4472                     Some(TraitRef {
4473                         path: (*path).clone(),
4474                         ref_id: ty.id,
4475                     })
4476                 }
4477                 _ => {
4478                     self.span_err(ty.span, "not a trait");
4479                     None
4480                 }
4481             }
4482         } else {
4483             match polarity {
4484                 ast::ImplPolarity::Negative => {
4485                     // This is a negated type implementation
4486                     // `impl !MyType {}`, which is not allowed.
4487                     self.span_err(neg_span, "inherent implementation can't be negated");
4488                 },
4489                 _ => {}
4490             }
4491             None
4492         };
4493
4494         if self.eat(&token::DotDot) {
4495             if generics.is_parameterized() {
4496                 self.span_err(impl_span, "default trait implementations are not \
4497                                           allowed to have genercis");
4498             }
4499
4500             self.expect(&token::OpenDelim(token::Brace));
4501             self.expect(&token::CloseDelim(token::Brace));
4502             (ast_util::impl_pretty_name(&opt_trait, None),
4503              ItemDefaultImpl(unsafety, opt_trait.unwrap()), None)
4504         } else {
4505             if opt_trait.is_some() {
4506                 ty = self.parse_ty_sum();
4507             }
4508             generics.where_clause = self.parse_where_clause();
4509
4510             self.expect(&token::OpenDelim(token::Brace));
4511             let attrs = self.parse_inner_attributes();
4512
4513             let mut impl_items = vec![];
4514             while !self.eat(&token::CloseDelim(token::Brace)) {
4515                 impl_items.push(self.parse_impl_item());
4516             }
4517
4518             (ast_util::impl_pretty_name(&opt_trait, Some(&*ty)),
4519              ItemImpl(unsafety, polarity, generics, opt_trait, ty, impl_items),
4520              Some(attrs))
4521         }
4522     }
4523
4524     /// Parse a::B<String,i32>
4525     fn parse_trait_ref(&mut self) -> TraitRef {
4526         ast::TraitRef {
4527             path: self.parse_path(LifetimeAndTypesWithoutColons),
4528             ref_id: ast::DUMMY_NODE_ID,
4529         }
4530     }
4531
4532     fn parse_late_bound_lifetime_defs(&mut self) -> Vec<ast::LifetimeDef> {
4533         if self.eat_keyword(keywords::For) {
4534             self.expect(&token::Lt);
4535             let lifetime_defs = self.parse_lifetime_defs();
4536             self.expect_gt();
4537             lifetime_defs
4538         } else {
4539             Vec::new()
4540         }
4541     }
4542
4543     /// Parse for<'l> a::B<String,i32>
4544     fn parse_poly_trait_ref(&mut self) -> PolyTraitRef {
4545         let lo = self.span.lo;
4546         let lifetime_defs = self.parse_late_bound_lifetime_defs();
4547
4548         ast::PolyTraitRef {
4549             bound_lifetimes: lifetime_defs,
4550             trait_ref: self.parse_trait_ref(),
4551             span: mk_sp(lo, self.last_span.hi),
4552         }
4553     }
4554
4555     /// Parse struct Foo { ... }
4556     fn parse_item_struct(&mut self) -> ItemInfo {
4557         let class_name = self.parse_ident();
4558         let mut generics = self.parse_generics();
4559
4560         if self.eat(&token::Colon) {
4561             let ty = self.parse_ty_sum();
4562             self.span_err(ty.span, "`virtual` structs have been removed from the language");
4563         }
4564
4565         // There is a special case worth noting here, as reported in issue #17904.
4566         // If we are parsing a tuple struct it is the case that the where clause
4567         // should follow the field list. Like so:
4568         //
4569         // struct Foo<T>(T) where T: Copy;
4570         //
4571         // If we are parsing a normal record-style struct it is the case
4572         // that the where clause comes before the body, and after the generics.
4573         // So if we look ahead and see a brace or a where-clause we begin
4574         // parsing a record style struct.
4575         //
4576         // Otherwise if we look ahead and see a paren we parse a tuple-style
4577         // struct.
4578
4579         let (fields, ctor_id) = if self.token.is_keyword(keywords::Where) {
4580             generics.where_clause = self.parse_where_clause();
4581             if self.eat(&token::Semi) {
4582                 // If we see a: `struct Foo<T> where T: Copy;` style decl.
4583                 (Vec::new(), Some(ast::DUMMY_NODE_ID))
4584             } else {
4585                 // If we see: `struct Foo<T> where T: Copy { ... }`
4586                 (self.parse_record_struct_body(&class_name), None)
4587             }
4588         // No `where` so: `struct Foo<T>;`
4589         } else if self.eat(&token::Semi) {
4590             (Vec::new(), Some(ast::DUMMY_NODE_ID))
4591         // Record-style struct definition
4592         } else if self.token == token::OpenDelim(token::Brace) {
4593             let fields = self.parse_record_struct_body(&class_name);
4594             (fields, None)
4595         // Tuple-style struct definition with optional where-clause.
4596         } else {
4597             let fields = self.parse_tuple_struct_body(&class_name, &mut generics);
4598             (fields, Some(ast::DUMMY_NODE_ID))
4599         };
4600
4601         (class_name,
4602          ItemStruct(P(ast::StructDef {
4603              fields: fields,
4604              ctor_id: ctor_id,
4605          }), generics),
4606          None)
4607     }
4608
4609     pub fn parse_record_struct_body(&mut self, class_name: &ast::Ident) -> Vec<StructField> {
4610         let mut fields = Vec::new();
4611         if self.eat(&token::OpenDelim(token::Brace)) {
4612             while self.token != token::CloseDelim(token::Brace) {
4613                 fields.push(self.parse_struct_decl_field(true));
4614             }
4615
4616             if fields.len() == 0 {
4617                 self.fatal(&format!("unit-like struct definition should be \
4618                     written as `struct {};`",
4619                     token::get_ident(class_name.clone())));
4620             }
4621
4622             self.bump();
4623         } else {
4624             let token_str = self.this_token_to_string();
4625             self.fatal(&format!("expected `where`, or `{}` after struct \
4626                                 name, found `{}`", "{",
4627                                 token_str));
4628         }
4629
4630         fields
4631     }
4632
4633     pub fn parse_tuple_struct_body(&mut self,
4634                                    class_name: &ast::Ident,
4635                                    generics: &mut ast::Generics)
4636                                    -> Vec<StructField> {
4637         // This is the case where we find `struct Foo<T>(T) where T: Copy;`
4638         if self.check(&token::OpenDelim(token::Paren)) {
4639             let fields = self.parse_unspanned_seq(
4640                 &token::OpenDelim(token::Paren),
4641                 &token::CloseDelim(token::Paren),
4642                 seq_sep_trailing_allowed(token::Comma),
4643                 |p| {
4644                     let attrs = p.parse_outer_attributes();
4645                     let lo = p.span.lo;
4646                     let struct_field_ = ast::StructField_ {
4647                         kind: UnnamedField(p.parse_visibility()),
4648                         id: ast::DUMMY_NODE_ID,
4649                         ty: p.parse_ty_sum(),
4650                         attrs: attrs,
4651                     };
4652                     spanned(lo, p.span.hi, struct_field_)
4653                 });
4654
4655             if fields.len() == 0 {
4656                 self.fatal(&format!("unit-like struct definition should be \
4657                     written as `struct {};`",
4658                     token::get_ident(class_name.clone())));
4659             }
4660
4661             generics.where_clause = self.parse_where_clause();
4662             self.expect(&token::Semi);
4663             fields
4664         // This is the case where we just see struct Foo<T> where T: Copy;
4665         } else if self.token.is_keyword(keywords::Where) {
4666             generics.where_clause = self.parse_where_clause();
4667             self.expect(&token::Semi);
4668             Vec::new()
4669         // This case is where we see: `struct Foo<T>;`
4670         } else {
4671             let token_str = self.this_token_to_string();
4672             self.fatal(&format!("expected `where`, `{}`, `(`, or `;` after struct \
4673                 name, found `{}`", "{", token_str));
4674         }
4675     }
4676
4677     /// Parse a structure field declaration
4678     pub fn parse_single_struct_field(&mut self,
4679                                      vis: Visibility,
4680                                      attrs: Vec<Attribute> )
4681                                      -> StructField {
4682         let a_var = self.parse_name_and_ty(vis, attrs);
4683         match self.token {
4684             token::Comma => {
4685                 self.bump();
4686             }
4687             token::CloseDelim(token::Brace) => {}
4688             _ => {
4689                 let span = self.span;
4690                 let token_str = self.this_token_to_string();
4691                 self.span_fatal_help(span,
4692                                      &format!("expected `,`, or `}}`, found `{}`",
4693                                              token_str),
4694                                      "struct fields should be separated by commas")
4695             }
4696         }
4697         a_var
4698     }
4699
4700     /// Parse an element of a struct definition
4701     fn parse_struct_decl_field(&mut self, allow_pub: bool) -> StructField {
4702
4703         let attrs = self.parse_outer_attributes();
4704
4705         if self.eat_keyword(keywords::Pub) {
4706             if !allow_pub {
4707                 let span = self.last_span;
4708                 self.span_err(span, "`pub` is not allowed here");
4709             }
4710             return self.parse_single_struct_field(Public, attrs);
4711         }
4712
4713         return self.parse_single_struct_field(Inherited, attrs);
4714     }
4715
4716     /// Parse visibility: PUB, PRIV, or nothing
4717     fn parse_visibility(&mut self) -> Visibility {
4718         if self.eat_keyword(keywords::Pub) { Public }
4719         else { Inherited }
4720     }
4721
4722     /// Given a termination token, parse all of the items in a module
4723     fn parse_mod_items(&mut self, term: &token::Token, inner_lo: BytePos) -> Mod {
4724         let mut items = vec![];
4725         while let Some(item) = self.parse_item() {
4726             items.push(item);
4727         }
4728
4729         if !self.eat(term) {
4730             let token_str = self.this_token_to_string();
4731             self.fatal(&format!("expected item, found `{}`", token_str))
4732         }
4733
4734         ast::Mod {
4735             inner: mk_sp(inner_lo, self.span.lo),
4736             items: items
4737         }
4738     }
4739
4740     fn parse_item_const(&mut self, m: Option<Mutability>) -> ItemInfo {
4741         let id = self.parse_ident();
4742         self.expect(&token::Colon);
4743         let ty = self.parse_ty_sum();
4744         self.expect(&token::Eq);
4745         let e = self.parse_expr();
4746         self.commit_expr_expecting(&*e, token::Semi);
4747         let item = match m {
4748             Some(m) => ItemStatic(ty, m, e),
4749             None => ItemConst(ty, e),
4750         };
4751         (id, item, None)
4752     }
4753
4754     /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
4755     fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> ItemInfo {
4756         let id_span = self.span;
4757         let id = self.parse_ident();
4758         if self.check(&token::Semi) {
4759             self.bump();
4760             // This mod is in an external file. Let's go get it!
4761             let (m, attrs) = self.eval_src_mod(id, outer_attrs, id_span);
4762             (id, m, Some(attrs))
4763         } else {
4764             self.push_mod_path(id, outer_attrs);
4765             self.expect(&token::OpenDelim(token::Brace));
4766             let mod_inner_lo = self.span.lo;
4767             let old_owns_directory = self.owns_directory;
4768             self.owns_directory = true;
4769             let attrs = self.parse_inner_attributes();
4770             let m = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo);
4771             self.owns_directory = old_owns_directory;
4772             self.pop_mod_path();
4773             (id, ItemMod(m), Some(attrs))
4774         }
4775     }
4776
4777     fn push_mod_path(&mut self, id: Ident, attrs: &[Attribute]) {
4778         let default_path = self.id_to_interned_str(id);
4779         let file_path = match ::attr::first_attr_value_str_by_name(attrs,
4780                                                                    "path") {
4781             Some(d) => d,
4782             None => default_path,
4783         };
4784         self.mod_path_stack.push(file_path)
4785     }
4786
4787     fn pop_mod_path(&mut self) {
4788         self.mod_path_stack.pop().unwrap();
4789     }
4790
4791     /// Read a module from a source file.
4792     fn eval_src_mod(&mut self,
4793                     id: ast::Ident,
4794                     outer_attrs: &[ast::Attribute],
4795                     id_sp: Span)
4796                     -> (ast::Item_, Vec<ast::Attribute> ) {
4797         let mut prefix = PathBuf::from(&self.sess.span_diagnostic.cm
4798                                             .span_to_filename(self.span));
4799         prefix.pop();
4800         let mut dir_path = prefix;
4801         for part in &self.mod_path_stack {
4802             dir_path.push(&**part);
4803         }
4804         let mod_string = token::get_ident(id);
4805         let (file_path, owns_directory) = match ::attr::first_attr_value_str_by_name(
4806                 outer_attrs, "path") {
4807             Some(d) => (dir_path.join(&*d), true),
4808             None => {
4809                 let mod_name = mod_string.to_string();
4810                 let default_path_str = format!("{}.rs", mod_name);
4811                 let secondary_path_str = format!("{}/mod.rs", mod_name);
4812                 let default_path = dir_path.join(&default_path_str[..]);
4813                 let secondary_path = dir_path.join(&secondary_path_str[..]);
4814                 let default_exists = default_path.exists();
4815                 let secondary_exists = secondary_path.exists();
4816
4817                 if !self.owns_directory {
4818                     self.span_err(id_sp,
4819                                   "cannot declare a new module at this location");
4820                     let this_module = match self.mod_path_stack.last() {
4821                         Some(name) => name.to_string(),
4822                         None => self.root_module_name.as_ref().unwrap().clone(),
4823                     };
4824                     self.span_note(id_sp,
4825                                    &format!("maybe move this module `{0}` \
4826                                             to its own directory via \
4827                                             `{0}/mod.rs`",
4828                                            this_module));
4829                     if default_exists || secondary_exists {
4830                         self.span_note(id_sp,
4831                                        &format!("... or maybe `use` the module \
4832                                                 `{}` instead of possibly \
4833                                                 redeclaring it",
4834                                                mod_name));
4835                     }
4836                     self.abort_if_errors();
4837                 }
4838
4839                 match (default_exists, secondary_exists) {
4840                     (true, false) => (default_path, false),
4841                     (false, true) => (secondary_path, true),
4842                     (false, false) => {
4843                         self.span_fatal_help(id_sp,
4844                                              &format!("file not found for module `{}`",
4845                                                      mod_name),
4846                                              &format!("name the file either {} or {} inside \
4847                                                      the directory {:?}",
4848                                                      default_path_str,
4849                                                      secondary_path_str,
4850                                                      dir_path.display()));
4851                     }
4852                     (true, true) => {
4853                         self.span_fatal_help(
4854                             id_sp,
4855                             &format!("file for module `{}` found at both {} \
4856                                      and {}",
4857                                     mod_name,
4858                                     default_path_str,
4859                                     secondary_path_str),
4860                             "delete or rename one of them to remove the ambiguity");
4861                     }
4862                 }
4863             }
4864         };
4865
4866         self.eval_src_mod_from_path(file_path, owns_directory,
4867                                     mod_string.to_string(), id_sp)
4868     }
4869
4870     fn eval_src_mod_from_path(&mut self,
4871                               path: PathBuf,
4872                               owns_directory: bool,
4873                               name: String,
4874                               id_sp: Span) -> (ast::Item_, Vec<ast::Attribute> ) {
4875         let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
4876         match included_mod_stack.iter().position(|p| *p == path) {
4877             Some(i) => {
4878                 let mut err = String::from_str("circular modules: ");
4879                 let len = included_mod_stack.len();
4880                 for p in &included_mod_stack[i.. len] {
4881                     err.push_str(&p.to_string_lossy());
4882                     err.push_str(" -> ");
4883                 }
4884                 err.push_str(&path.to_string_lossy());
4885                 self.span_fatal(id_sp, &err[..]);
4886             }
4887             None => ()
4888         }
4889         included_mod_stack.push(path.clone());
4890         drop(included_mod_stack);
4891
4892         let mut p0 =
4893             new_sub_parser_from_file(self.sess,
4894                                      self.cfg.clone(),
4895                                      &path,
4896                                      owns_directory,
4897                                      Some(name),
4898                                      id_sp);
4899         let mod_inner_lo = p0.span.lo;
4900         let mod_attrs = p0.parse_inner_attributes();
4901         let m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo);
4902         self.sess.included_mod_stack.borrow_mut().pop();
4903         (ast::ItemMod(m0), mod_attrs)
4904     }
4905
4906     /// Parse a function declaration from a foreign module
4907     fn parse_item_foreign_fn(&mut self, vis: ast::Visibility,
4908                              attrs: Vec<Attribute>) -> P<ForeignItem> {
4909         let lo = self.span.lo;
4910         self.expect_keyword(keywords::Fn);
4911
4912         let (ident, mut generics) = self.parse_fn_header();
4913         let decl = self.parse_fn_decl(true);
4914         generics.where_clause = self.parse_where_clause();
4915         let hi = self.span.hi;
4916         self.expect(&token::Semi);
4917         P(ast::ForeignItem {
4918             ident: ident,
4919             attrs: attrs,
4920             node: ForeignItemFn(decl, generics),
4921             id: ast::DUMMY_NODE_ID,
4922             span: mk_sp(lo, hi),
4923             vis: vis
4924         })
4925     }
4926
4927     /// Parse a static item from a foreign module
4928     fn parse_item_foreign_static(&mut self, vis: ast::Visibility,
4929                                  attrs: Vec<Attribute>) -> P<ForeignItem> {
4930         let lo = self.span.lo;
4931
4932         self.expect_keyword(keywords::Static);
4933         let mutbl = self.eat_keyword(keywords::Mut);
4934
4935         let ident = self.parse_ident();
4936         self.expect(&token::Colon);
4937         let ty = self.parse_ty_sum();
4938         let hi = self.span.hi;
4939         self.expect(&token::Semi);
4940         P(ForeignItem {
4941             ident: ident,
4942             attrs: attrs,
4943             node: ForeignItemStatic(ty, mutbl),
4944             id: ast::DUMMY_NODE_ID,
4945             span: mk_sp(lo, hi),
4946             vis: vis
4947         })
4948     }
4949
4950     /// Parse extern crate links
4951     ///
4952     /// # Examples
4953     ///
4954     /// extern crate foo;
4955     /// extern crate bar as foo;
4956     fn parse_item_extern_crate(&mut self,
4957                                lo: BytePos,
4958                                visibility: Visibility,
4959                                attrs: Vec<Attribute>)
4960                                 -> P<Item> {
4961
4962         let crate_name = self.parse_ident();
4963         let (maybe_path, ident) = if self.eat_keyword(keywords::As) {
4964             (Some(crate_name.name), self.parse_ident())
4965         } else {
4966             (None, crate_name)
4967         };
4968         self.expect(&token::Semi);
4969
4970         let last_span = self.last_span;
4971         self.mk_item(lo,
4972                      last_span.hi,
4973                      ident,
4974                      ItemExternCrate(maybe_path),
4975                      visibility,
4976                      attrs)
4977     }
4978
4979     /// Parse `extern` for foreign ABIs
4980     /// modules.
4981     ///
4982     /// `extern` is expected to have been
4983     /// consumed before calling this method
4984     ///
4985     /// # Examples:
4986     ///
4987     /// extern "C" {}
4988     /// extern {}
4989     fn parse_item_foreign_mod(&mut self,
4990                               lo: BytePos,
4991                               opt_abi: Option<abi::Abi>,
4992                               visibility: Visibility,
4993                               mut attrs: Vec<Attribute>)
4994                               -> P<Item> {
4995         self.expect(&token::OpenDelim(token::Brace));
4996
4997         let abi = opt_abi.unwrap_or(abi::C);
4998
4999         attrs.extend(self.parse_inner_attributes().into_iter());
5000
5001         let mut foreign_items = vec![];
5002         while let Some(item) = self.parse_foreign_item() {
5003             foreign_items.push(item);
5004         }
5005         self.expect(&token::CloseDelim(token::Brace));
5006
5007         let last_span = self.last_span;
5008         let m = ast::ForeignMod {
5009             abi: abi,
5010             items: foreign_items
5011         };
5012         self.mk_item(lo,
5013                      last_span.hi,
5014                      special_idents::invalid,
5015                      ItemForeignMod(m),
5016                      visibility,
5017                      attrs)
5018     }
5019
5020     /// Parse type Foo = Bar;
5021     fn parse_item_type(&mut self) -> ItemInfo {
5022         let ident = self.parse_ident();
5023         let mut tps = self.parse_generics();
5024         tps.where_clause = self.parse_where_clause();
5025         self.expect(&token::Eq);
5026         let ty = self.parse_ty_sum();
5027         self.expect(&token::Semi);
5028         (ident, ItemTy(ty, tps), None)
5029     }
5030
5031     /// Parse a structure-like enum variant definition
5032     /// this should probably be renamed or refactored...
5033     fn parse_struct_def(&mut self) -> P<StructDef> {
5034         let mut fields: Vec<StructField> = Vec::new();
5035         while self.token != token::CloseDelim(token::Brace) {
5036             fields.push(self.parse_struct_decl_field(false));
5037         }
5038         self.bump();
5039
5040         P(StructDef {
5041             fields: fields,
5042             ctor_id: None,
5043         })
5044     }
5045
5046     /// Parse the part of an "enum" decl following the '{'
5047     fn parse_enum_def(&mut self, _generics: &ast::Generics) -> EnumDef {
5048         let mut variants = Vec::new();
5049         let mut all_nullary = true;
5050         let mut any_disr = None;
5051         while self.token != token::CloseDelim(token::Brace) {
5052             let variant_attrs = self.parse_outer_attributes();
5053             let vlo = self.span.lo;
5054
5055             let vis = self.parse_visibility();
5056
5057             let ident;
5058             let kind;
5059             let mut args = Vec::new();
5060             let mut disr_expr = None;
5061             ident = self.parse_ident();
5062             if self.eat(&token::OpenDelim(token::Brace)) {
5063                 // Parse a struct variant.
5064                 all_nullary = false;
5065                 let start_span = self.span;
5066                 let struct_def = self.parse_struct_def();
5067                 if struct_def.fields.len() == 0 {
5068                     self.span_err(start_span,
5069                         &format!("unit-like struct variant should be written \
5070                                  without braces, as `{},`",
5071                                 token::get_ident(ident)));
5072                 }
5073                 kind = StructVariantKind(struct_def);
5074             } else if self.check(&token::OpenDelim(token::Paren)) {
5075                 all_nullary = false;
5076                 let arg_tys = self.parse_enum_variant_seq(
5077                     &token::OpenDelim(token::Paren),
5078                     &token::CloseDelim(token::Paren),
5079                     seq_sep_trailing_allowed(token::Comma),
5080                     |p| p.parse_ty_sum()
5081                 );
5082                 for ty in arg_tys {
5083                     args.push(ast::VariantArg {
5084                         ty: ty,
5085                         id: ast::DUMMY_NODE_ID,
5086                     });
5087                 }
5088                 kind = TupleVariantKind(args);
5089             } else if self.eat(&token::Eq) {
5090                 disr_expr = Some(self.parse_expr());
5091                 any_disr = disr_expr.as_ref().map(|expr| expr.span);
5092                 kind = TupleVariantKind(args);
5093             } else {
5094                 kind = TupleVariantKind(Vec::new());
5095             }
5096
5097             let vr = ast::Variant_ {
5098                 name: ident,
5099                 attrs: variant_attrs,
5100                 kind: kind,
5101                 id: ast::DUMMY_NODE_ID,
5102                 disr_expr: disr_expr,
5103                 vis: vis,
5104             };
5105             variants.push(P(spanned(vlo, self.last_span.hi, vr)));
5106
5107             if !self.eat(&token::Comma) { break; }
5108         }
5109         self.expect(&token::CloseDelim(token::Brace));
5110         match any_disr {
5111             Some(disr_span) if !all_nullary =>
5112                 self.span_err(disr_span,
5113                     "discriminator values can only be used with a c-like enum"),
5114             _ => ()
5115         }
5116
5117         ast::EnumDef { variants: variants }
5118     }
5119
5120     /// Parse an "enum" declaration
5121     fn parse_item_enum(&mut self) -> ItemInfo {
5122         let id = self.parse_ident();
5123         let mut generics = self.parse_generics();
5124         generics.where_clause = self.parse_where_clause();
5125         self.expect(&token::OpenDelim(token::Brace));
5126
5127         let enum_definition = self.parse_enum_def(&generics);
5128         (id, ItemEnum(enum_definition, generics), None)
5129     }
5130
5131     /// Parses a string as an ABI spec on an extern type or module. Consumes
5132     /// the `extern` keyword, if one is found.
5133     fn parse_opt_abi(&mut self) -> Option<abi::Abi> {
5134         match self.token {
5135             token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
5136                 let sp = self.span;
5137                 self.expect_no_suffix(sp, "ABI spec", suf);
5138                 self.bump();
5139                 let the_string = s.as_str();
5140                 match abi::lookup(the_string) {
5141                     Some(abi) => Some(abi),
5142                     None => {
5143                         let last_span = self.last_span;
5144                         self.span_err(
5145                             last_span,
5146                             &format!("illegal ABI: expected one of [{}], \
5147                                      found `{}`",
5148                                     abi::all_names().connect(", "),
5149                                     the_string));
5150                         None
5151                     }
5152                 }
5153             }
5154
5155             _ => None,
5156         }
5157     }
5158
5159     /// Parse one of the items allowed by the flags.
5160     /// NB: this function no longer parses the items inside an
5161     /// extern crate.
5162     fn parse_item_(&mut self, attrs: Vec<Attribute>,
5163                    macros_allowed: bool) -> Option<P<Item>> {
5164         let nt_item = match self.token {
5165             token::Interpolated(token::NtItem(ref item)) => {
5166                 Some((**item).clone())
5167             }
5168             _ => None
5169         };
5170         match nt_item {
5171             Some(mut item) => {
5172                 self.bump();
5173                 let mut attrs = attrs;
5174                 mem::swap(&mut item.attrs, &mut attrs);
5175                 item.attrs.extend(attrs.into_iter());
5176                 return Some(P(item));
5177             }
5178             None => {}
5179         }
5180
5181         let lo = self.span.lo;
5182
5183         let visibility = self.parse_visibility();
5184
5185         if self.eat_keyword(keywords::Use) {
5186             // USE ITEM
5187             let item_ = ItemUse(self.parse_view_path());
5188             self.expect(&token::Semi);
5189
5190             let last_span = self.last_span;
5191             let item = self.mk_item(lo,
5192                                     last_span.hi,
5193                                     token::special_idents::invalid,
5194                                     item_,
5195                                     visibility,
5196                                     attrs);
5197             return Some(item);
5198         }
5199
5200         if self.eat_keyword(keywords::Extern) {
5201             if self.eat_keyword(keywords::Crate) {
5202                 return Some(self.parse_item_extern_crate(lo, visibility, attrs));
5203             }
5204
5205             let opt_abi = self.parse_opt_abi();
5206
5207             if self.eat_keyword(keywords::Fn) {
5208                 // EXTERN FUNCTION ITEM
5209                 let abi = opt_abi.unwrap_or(abi::C);
5210                 let (ident, item_, extra_attrs) =
5211                     self.parse_item_fn(Unsafety::Normal, abi);
5212                 let last_span = self.last_span;
5213                 let item = self.mk_item(lo,
5214                                         last_span.hi,
5215                                         ident,
5216                                         item_,
5217                                         visibility,
5218                                         maybe_append(attrs, extra_attrs));
5219                 return Some(item);
5220             } else if self.check(&token::OpenDelim(token::Brace)) {
5221                 return Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs));
5222             }
5223
5224             let span = self.span;
5225             let token_str = self.this_token_to_string();
5226             self.span_fatal(span,
5227                             &format!("expected `{}` or `fn`, found `{}`", "{",
5228                                     token_str));
5229         }
5230
5231         if self.eat_keyword_noexpect(keywords::Virtual) {
5232             let span = self.span;
5233             self.span_err(span, "`virtual` structs have been removed from the language");
5234         }
5235
5236         if self.eat_keyword(keywords::Static) {
5237             // STATIC ITEM
5238             let m = if self.eat_keyword(keywords::Mut) {MutMutable} else {MutImmutable};
5239             let (ident, item_, extra_attrs) = self.parse_item_const(Some(m));
5240             let last_span = self.last_span;
5241             let item = self.mk_item(lo,
5242                                     last_span.hi,
5243                                     ident,
5244                                     item_,
5245                                     visibility,
5246                                     maybe_append(attrs, extra_attrs));
5247             return Some(item);
5248         }
5249         if self.eat_keyword(keywords::Const) {
5250             // CONST ITEM
5251             if self.eat_keyword(keywords::Mut) {
5252                 let last_span = self.last_span;
5253                 self.span_err(last_span, "const globals cannot be mutable");
5254                 self.fileline_help(last_span, "did you mean to declare a static?");
5255             }
5256             let (ident, item_, extra_attrs) = self.parse_item_const(None);
5257             let last_span = self.last_span;
5258             let item = self.mk_item(lo,
5259                                     last_span.hi,
5260                                     ident,
5261                                     item_,
5262                                     visibility,
5263                                     maybe_append(attrs, extra_attrs));
5264             return Some(item);
5265         }
5266         if self.check_keyword(keywords::Unsafe) &&
5267             self.look_ahead(1, |t| t.is_keyword(keywords::Trait))
5268         {
5269             // UNSAFE TRAIT ITEM
5270             self.expect_keyword(keywords::Unsafe);
5271             self.expect_keyword(keywords::Trait);
5272             let (ident, item_, extra_attrs) =
5273                 self.parse_item_trait(ast::Unsafety::Unsafe);
5274             let last_span = self.last_span;
5275             let item = self.mk_item(lo,
5276                                     last_span.hi,
5277                                     ident,
5278                                     item_,
5279                                     visibility,
5280                                     maybe_append(attrs, extra_attrs));
5281             return Some(item);
5282         }
5283         if self.check_keyword(keywords::Unsafe) &&
5284             self.look_ahead(1, |t| t.is_keyword(keywords::Impl))
5285         {
5286             // IMPL ITEM
5287             self.expect_keyword(keywords::Unsafe);
5288             self.expect_keyword(keywords::Impl);
5289             let (ident, item_, extra_attrs) = self.parse_item_impl(ast::Unsafety::Unsafe);
5290             let last_span = self.last_span;
5291             let item = self.mk_item(lo,
5292                                     last_span.hi,
5293                                     ident,
5294                                     item_,
5295                                     visibility,
5296                                     maybe_append(attrs, extra_attrs));
5297             return Some(item);
5298         }
5299         if self.check_keyword(keywords::Fn) {
5300             // FUNCTION ITEM
5301             self.bump();
5302             let (ident, item_, extra_attrs) =
5303                 self.parse_item_fn(Unsafety::Normal, abi::Rust);
5304             let last_span = self.last_span;
5305             let item = self.mk_item(lo,
5306                                     last_span.hi,
5307                                     ident,
5308                                     item_,
5309                                     visibility,
5310                                     maybe_append(attrs, extra_attrs));
5311             return Some(item);
5312         }
5313         if self.check_keyword(keywords::Unsafe)
5314             && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
5315             // UNSAFE FUNCTION ITEM
5316             self.bump();
5317             let abi = if self.eat_keyword(keywords::Extern) {
5318                 self.parse_opt_abi().unwrap_or(abi::C)
5319             } else {
5320                 abi::Rust
5321             };
5322             self.expect_keyword(keywords::Fn);
5323             let (ident, item_, extra_attrs) =
5324                 self.parse_item_fn(Unsafety::Unsafe, abi);
5325             let last_span = self.last_span;
5326             let item = self.mk_item(lo,
5327                                     last_span.hi,
5328                                     ident,
5329                                     item_,
5330                                     visibility,
5331                                     maybe_append(attrs, extra_attrs));
5332             return Some(item);
5333         }
5334         if self.eat_keyword(keywords::Mod) {
5335             // MODULE ITEM
5336             let (ident, item_, extra_attrs) =
5337                 self.parse_item_mod(&attrs[..]);
5338             let last_span = self.last_span;
5339             let item = self.mk_item(lo,
5340                                     last_span.hi,
5341                                     ident,
5342                                     item_,
5343                                     visibility,
5344                                     maybe_append(attrs, extra_attrs));
5345             return Some(item);
5346         }
5347         if self.eat_keyword(keywords::Type) {
5348             // TYPE ITEM
5349             let (ident, item_, extra_attrs) = self.parse_item_type();
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.eat_keyword(keywords::Enum) {
5360             // ENUM ITEM
5361             let (ident, item_, extra_attrs) = self.parse_item_enum();
5362             let last_span = self.last_span;
5363             let item = self.mk_item(lo,
5364                                     last_span.hi,
5365                                     ident,
5366                                     item_,
5367                                     visibility,
5368                                     maybe_append(attrs, extra_attrs));
5369             return Some(item);
5370         }
5371         if self.eat_keyword(keywords::Trait) {
5372             // TRAIT ITEM
5373             let (ident, item_, extra_attrs) =
5374                 self.parse_item_trait(ast::Unsafety::Normal);
5375             let last_span = self.last_span;
5376             let item = self.mk_item(lo,
5377                                     last_span.hi,
5378                                     ident,
5379                                     item_,
5380                                     visibility,
5381                                     maybe_append(attrs, extra_attrs));
5382             return Some(item);
5383         }
5384         if self.eat_keyword(keywords::Impl) {
5385             // IMPL ITEM
5386             let (ident, item_, extra_attrs) = self.parse_item_impl(ast::Unsafety::Normal);
5387             let last_span = self.last_span;
5388             let item = self.mk_item(lo,
5389                                     last_span.hi,
5390                                     ident,
5391                                     item_,
5392                                     visibility,
5393                                     maybe_append(attrs, extra_attrs));
5394             return Some(item);
5395         }
5396         if self.eat_keyword(keywords::Struct) {
5397             // STRUCT ITEM
5398             let (ident, item_, extra_attrs) = self.parse_item_struct();
5399             let last_span = self.last_span;
5400             let item = self.mk_item(lo,
5401                                     last_span.hi,
5402                                     ident,
5403                                     item_,
5404                                     visibility,
5405                                     maybe_append(attrs, extra_attrs));
5406             return Some(item);
5407         }
5408         self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility)
5409     }
5410
5411     /// Parse a foreign item.
5412     fn parse_foreign_item(&mut self) -> Option<P<ForeignItem>> {
5413         let lo = self.span.lo;
5414
5415         let attrs = self.parse_outer_attributes();
5416         let visibility = self.parse_visibility();
5417
5418         if self.check_keyword(keywords::Static) {
5419             // FOREIGN STATIC ITEM
5420             return Some(self.parse_item_foreign_static(visibility, attrs));
5421         }
5422         if self.check_keyword(keywords::Fn) || self.check_keyword(keywords::Unsafe) {
5423             // FOREIGN FUNCTION ITEM
5424             return Some(self.parse_item_foreign_fn(visibility, attrs));
5425         }
5426
5427         // FIXME #5668: this will occur for a macro invocation:
5428         match self.parse_macro_use_or_failure(attrs, true, lo, visibility) {
5429             Some(item) => {
5430                 self.span_fatal(item.span, "macros cannot expand to foreign items");
5431             }
5432             None => None
5433         }
5434     }
5435
5436     /// This is the fall-through for parsing items.
5437     fn parse_macro_use_or_failure(
5438         &mut self,
5439         attrs: Vec<Attribute> ,
5440         macros_allowed: bool,
5441         lo: BytePos,
5442         visibility: Visibility
5443     ) -> Option<P<Item>> {
5444         if macros_allowed && !self.token.is_any_keyword()
5445                 && self.look_ahead(1, |t| *t == token::Not)
5446                 && (self.look_ahead(2, |t| t.is_plain_ident())
5447                     || self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren))
5448                     || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) {
5449             // MACRO INVOCATION ITEM
5450
5451             let last_span = self.last_span;
5452             self.complain_if_pub_macro(visibility, last_span);
5453
5454             // item macro.
5455             let pth = self.parse_path(NoTypesAllowed);
5456             self.expect(&token::Not);
5457
5458             // a 'special' identifier (like what `macro_rules!` uses)
5459             // is optional. We should eventually unify invoc syntax
5460             // and remove this.
5461             let id = if self.token.is_plain_ident() {
5462                 self.parse_ident()
5463             } else {
5464                 token::special_idents::invalid // no special identifier
5465             };
5466             // eat a matched-delimiter token tree:
5467             let delim = self.expect_open_delim();
5468             let tts = self.parse_seq_to_end(&token::CloseDelim(delim),
5469                                             seq_sep_none(),
5470                                             |p| p.parse_token_tree());
5471             // single-variant-enum... :
5472             let m = ast::MacInvocTT(pth, tts, EMPTY_CTXT);
5473             let m: ast::Mac = codemap::Spanned { node: m,
5474                                              span: mk_sp(self.span.lo,
5475                                                          self.span.hi) };
5476
5477             if delim != token::Brace {
5478                 if !self.eat(&token::Semi) {
5479                     let last_span = self.last_span;
5480                     self.span_err(last_span,
5481                                   "macros that expand to items must either \
5482                                    be surrounded with braces or followed by \
5483                                    a semicolon");
5484                 }
5485             }
5486
5487             let item_ = ItemMac(m);
5488             let last_span = self.last_span;
5489             let item = self.mk_item(lo,
5490                                     last_span.hi,
5491                                     id,
5492                                     item_,
5493                                     visibility,
5494                                     attrs);
5495             return Some(item);
5496         }
5497
5498         // FAILURE TO PARSE ITEM
5499         match visibility {
5500             Inherited => {}
5501             Public => {
5502                 let last_span = self.last_span;
5503                 self.span_fatal(last_span, "unmatched visibility `pub`");
5504             }
5505         }
5506
5507         if !attrs.is_empty() {
5508             self.expected_item_err(&attrs);
5509         }
5510         None
5511     }
5512
5513     pub fn parse_item(&mut self) -> Option<P<Item>> {
5514         let attrs = self.parse_outer_attributes();
5515         self.parse_item_(attrs, true)
5516     }
5517
5518     /// Matches view_path : MOD? non_global_path as IDENT
5519     /// | MOD? non_global_path MOD_SEP LBRACE RBRACE
5520     /// | MOD? non_global_path MOD_SEP LBRACE ident_seq RBRACE
5521     /// | MOD? non_global_path MOD_SEP STAR
5522     /// | MOD? non_global_path
5523     fn parse_view_path(&mut self) -> P<ViewPath> {
5524         let lo = self.span.lo;
5525
5526         // Allow a leading :: because the paths are absolute either way.
5527         // This occurs with "use $crate::..." in macros.
5528         self.eat(&token::ModSep);
5529
5530         if self.check(&token::OpenDelim(token::Brace)) {
5531             // use {foo,bar}
5532             let idents = self.parse_unspanned_seq(
5533                 &token::OpenDelim(token::Brace),
5534                 &token::CloseDelim(token::Brace),
5535                 seq_sep_trailing_allowed(token::Comma),
5536                 |p| p.parse_path_list_item());
5537             let path = ast::Path {
5538                 span: mk_sp(lo, self.span.hi),
5539                 global: false,
5540                 segments: Vec::new()
5541             };
5542             return P(spanned(lo, self.span.hi, ViewPathList(path, idents)));
5543         }
5544
5545         let first_ident = self.parse_ident();
5546         let mut path = vec!(first_ident);
5547         if let token::ModSep = self.token {
5548             // foo::bar or foo::{a,b,c} or foo::*
5549             while self.check(&token::ModSep) {
5550                 self.bump();
5551
5552                 match self.token {
5553                   token::Ident(..) => {
5554                     let ident = self.parse_ident();
5555                     path.push(ident);
5556                   }
5557
5558                   // foo::bar::{a,b,c}
5559                   token::OpenDelim(token::Brace) => {
5560                     let idents = self.parse_unspanned_seq(
5561                         &token::OpenDelim(token::Brace),
5562                         &token::CloseDelim(token::Brace),
5563                         seq_sep_trailing_allowed(token::Comma),
5564                         |p| p.parse_path_list_item()
5565                     );
5566                     let path = ast::Path {
5567                         span: mk_sp(lo, self.span.hi),
5568                         global: false,
5569                         segments: path.into_iter().map(|identifier| {
5570                             ast::PathSegment {
5571                                 identifier: identifier,
5572                                 parameters: ast::PathParameters::none(),
5573                             }
5574                         }).collect()
5575                     };
5576                     return P(spanned(lo, self.span.hi, ViewPathList(path, idents)));
5577                   }
5578
5579                   // foo::bar::*
5580                   token::BinOp(token::Star) => {
5581                     self.bump();
5582                     let path = ast::Path {
5583                         span: mk_sp(lo, self.span.hi),
5584                         global: false,
5585                         segments: path.into_iter().map(|identifier| {
5586                             ast::PathSegment {
5587                                 identifier: identifier,
5588                                 parameters: ast::PathParameters::none(),
5589                             }
5590                         }).collect()
5591                     };
5592                     return P(spanned(lo, self.span.hi, ViewPathGlob(path)));
5593                   }
5594
5595                   // fall-through for case foo::bar::;
5596                   token::Semi => {
5597                     self.span_err(self.span, "expected identifier or `{` or `*`, found `;`");
5598                   }
5599
5600                   _ => break
5601                 }
5602             }
5603         }
5604         let mut rename_to = path[path.len() - 1];
5605         let path = ast::Path {
5606             span: mk_sp(lo, self.last_span.hi),
5607             global: false,
5608             segments: path.into_iter().map(|identifier| {
5609                 ast::PathSegment {
5610                     identifier: identifier,
5611                     parameters: ast::PathParameters::none(),
5612                 }
5613             }).collect()
5614         };
5615         if self.eat_keyword(keywords::As) {
5616             rename_to = self.parse_ident()
5617         }
5618         P(spanned(lo, self.last_span.hi, ViewPathSimple(rename_to, path)))
5619     }
5620
5621     /// Parses a source module as a crate. This is the main
5622     /// entry point for the parser.
5623     pub fn parse_crate_mod(&mut self) -> Crate {
5624         let lo = self.span.lo;
5625         ast::Crate {
5626             attrs: self.parse_inner_attributes(),
5627             module: self.parse_mod_items(&token::Eof, lo),
5628             config: self.cfg.clone(),
5629             span: mk_sp(lo, self.span.lo),
5630             exported_macros: Vec::new(),
5631         }
5632     }
5633
5634     pub fn parse_optional_str(&mut self)
5635                               -> Option<(InternedString, ast::StrStyle, Option<ast::Name>)> {
5636         let ret = match self.token {
5637             token::Literal(token::Str_(s), suf) => {
5638                 (self.id_to_interned_str(s.ident()), ast::CookedStr, suf)
5639             }
5640             token::Literal(token::StrRaw(s, n), suf) => {
5641                 (self.id_to_interned_str(s.ident()), ast::RawStr(n), suf)
5642             }
5643             _ => return None
5644         };
5645         self.bump();
5646         Some(ret)
5647     }
5648
5649     pub fn parse_str(&mut self) -> (InternedString, StrStyle) {
5650         match self.parse_optional_str() {
5651             Some((s, style, suf)) => {
5652                 let sp = self.last_span;
5653                 self.expect_no_suffix(sp, "str literal", suf);
5654                 (s, style)
5655             }
5656             _ =>  self.fatal("expected string literal")
5657         }
5658     }
5659 }