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