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