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