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