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