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