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.
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.
11 pub use self::PathParsingMode::*;
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, LitByteStr};
38 use ast::{LitStr, LitInt, Local};
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};
55 use ast::{TyFixedLengthVec, TyBareFn, TyTypeof, TyInfer};
56 use ast::{TyParam, TyParamBound, TyParen, TyPath, TyPolyTraitRef, TyPtr};
57 use ast::{TyRptr, TyTup, TyU32, TyVec, UnUniq};
58 use ast::{TypeImplItem, TypeTraitItem};
59 use ast::{UnnamedField, UnsafeBlock};
60 use ast::{ViewPath, ViewPathGlob, ViewPathList, ViewPathSimple};
61 use ast::{Visibility, WhereClause};
63 use ast_util::{self, AS_PREC, ident_to_path, operator_prec};
64 use codemap::{self, Span, BytePos, Spanned, spanned, mk_sp, CodeMap};
66 use ext::tt::macro_parser;
68 use parse::attr::ParserAttr;
70 use parse::common::{SeqSep, seq_sep_none, seq_sep_trailing_allowed};
71 use parse::lexer::{Reader, TokenAndSpan};
72 use parse::obsolete::{ParserObsoleteMethods, ObsoleteSyntax};
73 use parse::token::{self, MatchNt, SubstNt, SpecialVarNt, InternedString};
74 use parse::token::{keywords, special_idents, SpecialMacroVar};
75 use parse::{new_sub_parser_from_file, ParseSess};
78 use owned_slice::OwnedSlice;
80 use diagnostic::FatalError;
82 use std::collections::HashSet;
83 use std::io::prelude::*;
85 use std::path::{Path, PathBuf};
90 flags Restrictions: u8 {
91 const RESTRICTION_STMT_EXPR = 1 << 0,
92 const RESTRICTION_NO_STRUCT_LITERAL = 1 << 1,
96 type ItemInfo = (Ident, Item_, Option<Vec<Attribute> >);
98 /// How to parse a path. There are four different kinds of paths, all of which
99 /// are parsed somewhat differently.
100 #[derive(Copy, Clone, PartialEq)]
101 pub enum PathParsingMode {
102 /// A path with no type parameters; e.g. `foo::bar::Baz`
104 /// A path with a lifetime and type parameters, with no double colons
105 /// before the type parameters; e.g. `foo::bar<'a>::Baz<T>`
106 LifetimeAndTypesWithoutColons,
107 /// A path with a lifetime and type parameters with double colons before
108 /// the type parameters; e.g. `foo::bar::<'a>::Baz::<T>`
109 LifetimeAndTypesWithColons,
112 /// How to parse a bound, whether to allow bound modifiers such as `?`.
113 #[derive(Copy, Clone, PartialEq)]
114 pub enum BoundParsingMode {
119 /// Possibly accept an `token::Interpolated` expression (a pre-parsed expression
120 /// dropped into the token stream, which happens while parsing the result of
121 /// macro expansion). Placement of these is not as complex as I feared it would
122 /// be. The important thing is to make sure that lookahead doesn't balk at
123 /// `token::Interpolated` tokens.
124 macro_rules! maybe_whole_expr {
127 let found = match $p.token {
128 token::Interpolated(token::NtExpr(ref e)) => {
131 token::Interpolated(token::NtPath(_)) => {
132 // FIXME: The following avoids an issue with lexical borrowck scopes,
133 // but the clone is unfortunate.
134 let pt = match $p.token {
135 token::Interpolated(token::NtPath(ref pt)) => (**pt).clone(),
139 Some($p.mk_expr(span.lo, span.hi, ExprPath(None, pt)))
141 token::Interpolated(token::NtBlock(_)) => {
142 // FIXME: The following avoids an issue with lexical borrowck scopes,
143 // but the clone is unfortunate.
144 let b = match $p.token {
145 token::Interpolated(token::NtBlock(ref b)) => (*b).clone(),
149 Some($p.mk_expr(span.lo, span.hi, ExprBlock(b)))
164 /// As maybe_whole_expr, but for things other than expressions
165 macro_rules! maybe_whole {
166 ($p:expr, $constructor:ident) => (
168 let found = match ($p).token {
169 token::Interpolated(token::$constructor(_)) => {
170 Some(try!(($p).bump_and_get()))
174 if let Some(token::Interpolated(token::$constructor(x))) = found {
175 return Ok(x.clone());
179 (no_clone $p:expr, $constructor:ident) => (
181 let found = match ($p).token {
182 token::Interpolated(token::$constructor(_)) => {
183 Some(try!(($p).bump_and_get()))
187 if let Some(token::Interpolated(token::$constructor(x))) = found {
192 (deref $p:expr, $constructor:ident) => (
194 let found = match ($p).token {
195 token::Interpolated(token::$constructor(_)) => {
196 Some(try!(($p).bump_and_get()))
200 if let Some(token::Interpolated(token::$constructor(x))) = found {
201 return Ok((*x).clone());
205 (Some deref $p:expr, $constructor:ident) => (
207 let found = match ($p).token {
208 token::Interpolated(token::$constructor(_)) => {
209 Some(try!(($p).bump_and_get()))
213 if let Some(token::Interpolated(token::$constructor(x))) = found {
214 return Ok(Some((*x).clone()));
218 (pair_empty $p:expr, $constructor:ident) => (
220 let found = match ($p).token {
221 token::Interpolated(token::$constructor(_)) => {
222 Some(try!(($p).bump_and_get()))
226 if let Some(token::Interpolated(token::$constructor(x))) = found {
227 return Ok((Vec::new(), x));
234 fn maybe_append(mut lhs: Vec<Attribute>, rhs: Option<Vec<Attribute>>)
236 if let Some(ref attrs) = rhs {
237 lhs.extend(attrs.iter().cloned())
242 /* ident is handled by common.rs */
244 pub struct Parser<'a> {
245 pub sess: &'a ParseSess,
246 /// the current token:
247 pub token: token::Token,
248 /// the span of the current token:
250 /// the span of the prior token:
252 pub cfg: CrateConfig,
253 /// the previous token or None (only stashed sometimes).
254 pub last_token: Option<Box<token::Token>>,
255 pub buffer: [TokenAndSpan; 4],
256 pub buffer_start: isize,
257 pub buffer_end: isize,
258 pub tokens_consumed: usize,
259 pub restrictions: Restrictions,
260 pub quote_depth: usize, // not (yet) related to the quasiquoter
261 pub reader: Box<Reader+'a>,
262 pub interner: Rc<token::IdentInterner>,
263 /// The set of seen errors about obsolete syntax. Used to suppress
264 /// extra detail when the same error is seen twice
265 pub obsolete_set: HashSet<ObsoleteSyntax>,
266 /// Used to determine the path to externally loaded source files
267 pub mod_path_stack: Vec<InternedString>,
268 /// Stack of spans of open delimiters. Used for error message.
269 pub open_braces: Vec<Span>,
270 /// Flag if this parser "owns" the directory that it is currently parsing
271 /// in. This will affect how nested files are looked up.
272 pub owns_directory: bool,
273 /// Name of the root module this parser originated from. If `None`, then the
274 /// name is not known. This does not change while the parser is descending
275 /// into modules, and sub-parsers have new values for this name.
276 pub root_module_name: Option<String>,
277 pub expected_tokens: Vec<TokenType>,
280 #[derive(PartialEq, Eq, Clone)]
283 Keyword(keywords::Keyword),
288 fn to_string(&self) -> String {
290 TokenType::Token(ref t) => format!("`{}`", Parser::token_to_string(t)),
291 TokenType::Operator => "an operator".to_string(),
292 TokenType::Keyword(kw) => format!("`{}`", kw.to_name()),
297 fn is_plain_ident_or_underscore(t: &token::Token) -> bool {
298 t.is_plain_ident() || *t == token::Underscore
301 /// Information about the path to a module.
302 pub struct ModulePath {
304 pub path_exists: bool,
305 pub result: Result<ModulePathSuccess, ModulePathError>,
308 pub struct ModulePathSuccess {
309 pub path: ::std::path::PathBuf,
310 pub owns_directory: bool,
313 pub struct ModulePathError {
315 pub help_msg: String,
319 impl<'a> Parser<'a> {
320 pub fn new(sess: &'a ParseSess,
321 cfg: ast::CrateConfig,
322 mut rdr: Box<Reader+'a>)
325 let tok0 = rdr.real_token();
327 let placeholder = TokenAndSpan {
328 tok: token::Underscore,
334 interner: token::get_ident_interner(),
350 restrictions: Restrictions::empty(),
352 obsolete_set: HashSet::new(),
353 mod_path_stack: Vec::new(),
354 open_braces: Vec::new(),
355 owns_directory: true,
356 root_module_name: None,
357 expected_tokens: Vec::new(),
361 // Panicing fns (for now!)
362 // This is so that the quote_*!() syntax extensions
363 pub fn parse_expr(&mut self) -> P<Expr> {
364 panictry!(self.parse_expr_nopanic())
367 pub fn parse_item(&mut self) -> Option<P<Item>> {
368 panictry!(self.parse_item_nopanic())
371 pub fn parse_pat(&mut self) -> P<Pat> {
372 panictry!(self.parse_pat_nopanic())
375 pub fn parse_arm(&mut self) -> Arm {
376 panictry!(self.parse_arm_nopanic())
379 pub fn parse_ty(&mut self) -> P<Ty> {
380 panictry!(self.parse_ty_nopanic())
383 pub fn parse_stmt(&mut self) -> Option<P<Stmt>> {
384 panictry!(self.parse_stmt_nopanic())
387 /// Convert a token to a string using self's reader
388 pub fn token_to_string(token: &token::Token) -> String {
389 pprust::token_to_string(token)
392 /// Convert the current token to a string using self's reader
393 pub fn this_token_to_string(&self) -> String {
394 Parser::token_to_string(&self.token)
397 pub fn unexpected_last(&self, t: &token::Token) -> FatalError {
398 let token_str = Parser::token_to_string(t);
399 let last_span = self.last_span;
400 self.span_fatal(last_span, &format!("unexpected token: `{}`",
404 pub fn unexpected(&mut self) -> FatalError {
405 match self.expect_one_of(&[], &[]) {
407 Ok(_) => unreachable!()
411 /// Expect and consume the token t. Signal an error if
412 /// the next token is not t.
413 pub fn expect(&mut self, t: &token::Token) -> PResult<()> {
414 if self.expected_tokens.is_empty() {
415 if self.token == *t {
418 let token_str = Parser::token_to_string(t);
419 let this_token_str = self.this_token_to_string();
420 Err(self.fatal(&format!("expected `{}`, found `{}`",
425 self.expect_one_of(slice::ref_slice(t), &[])
429 /// Expect next token to be edible or inedible token. If edible,
430 /// then consume it; if inedible, then return without consuming
431 /// anything. Signal a fatal error if next token is unexpected.
432 pub fn expect_one_of(&mut self,
433 edible: &[token::Token],
434 inedible: &[token::Token]) -> PResult<()>{
435 fn tokens_to_string(tokens: &[TokenType]) -> String {
436 let mut i = tokens.iter();
437 // This might be a sign we need a connect method on Iterator.
439 .map_or("".to_string(), |t| t.to_string());
440 i.enumerate().fold(b, |mut b, (i, ref a)| {
441 if tokens.len() > 2 && i == tokens.len() - 2 {
443 } else if tokens.len() == 2 && i == tokens.len() - 2 {
448 b.push_str(&*a.to_string());
452 if edible.contains(&self.token) {
454 } else if inedible.contains(&self.token) {
455 // leave it in the input
458 let mut expected = edible.iter()
459 .map(|x| TokenType::Token(x.clone()))
460 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
461 .chain(self.expected_tokens.iter().cloned())
462 .collect::<Vec<_>>();
463 expected.sort_by(|a, b| a.to_string().cmp(&b.to_string()));
465 let expect = tokens_to_string(&expected[..]);
466 let actual = self.this_token_to_string();
468 &(if expected.len() > 1 {
469 (format!("expected one of {}, found `{}`",
472 } else if expected.is_empty() {
473 (format!("unexpected token: `{}`",
476 (format!("expected {}, found `{}`",
484 /// Check for erroneous `ident { }`; if matches, signal error and
485 /// recover (without consuming any expected input token). Returns
486 /// true if and only if input was consumed for recovery.
487 pub fn check_for_erroneous_unit_struct_expecting(&mut self,
488 expected: &[token::Token])
490 if self.token == token::OpenDelim(token::Brace)
491 && expected.iter().all(|t| *t != token::OpenDelim(token::Brace))
492 && self.look_ahead(1, |t| *t == token::CloseDelim(token::Brace)) {
493 // matched; signal non-fatal error and recover.
494 let span = self.span;
496 "unit-like struct construction is written with no trailing `{ }`");
497 try!(self.eat(&token::OpenDelim(token::Brace)));
498 try!(self.eat(&token::CloseDelim(token::Brace)));
505 /// Commit to parsing a complete expression `e` expected to be
506 /// followed by some token from the set edible + inedible. Recover
507 /// from anticipated input errors, discarding erroneous characters.
508 pub fn commit_expr(&mut self, e: &Expr, edible: &[token::Token],
509 inedible: &[token::Token]) -> PResult<()> {
510 debug!("commit_expr {:?}", e);
511 if let ExprPath(..) = e.node {
512 // might be unit-struct construction; check for recoverableinput error.
513 let expected = edible.iter()
515 .chain(inedible.iter().cloned())
516 .collect::<Vec<_>>();
517 try!(self.check_for_erroneous_unit_struct_expecting(&expected[..]));
519 self.expect_one_of(edible, inedible)
522 pub fn commit_expr_expecting(&mut self, e: &Expr, edible: token::Token) -> PResult<()> {
523 self.commit_expr(e, &[edible], &[])
526 /// Commit to parsing a complete statement `s`, which expects to be
527 /// followed by some token from the set edible + inedible. Check
528 /// for recoverable input errors, discarding erroneous characters.
529 pub fn commit_stmt(&mut self, edible: &[token::Token],
530 inedible: &[token::Token]) -> PResult<()> {
533 .map_or(false, |t| t.is_ident() || t.is_path()) {
534 let expected = edible.iter()
536 .chain(inedible.iter().cloned())
537 .collect::<Vec<_>>();
538 try!(self.check_for_erroneous_unit_struct_expecting(&expected));
540 self.expect_one_of(edible, inedible)
543 pub fn commit_stmt_expecting(&mut self, edible: token::Token) -> PResult<()> {
544 self.commit_stmt(&[edible], &[])
547 pub fn parse_ident(&mut self) -> PResult<ast::Ident> {
548 self.check_strict_keywords();
549 try!(self.check_reserved_keywords());
551 token::Ident(i, _) => {
555 token::Interpolated(token::NtIdent(..)) => {
556 self.bug("ident interpolation not converted to real token");
559 let token_str = self.this_token_to_string();
560 Err(self.fatal(&format!("expected ident, found `{}`",
566 pub fn parse_ident_or_self_type(&mut self) -> PResult<ast::Ident> {
567 if self.is_self_type_ident() {
568 self.expect_self_type_ident()
574 pub fn parse_path_list_item(&mut self) -> PResult<ast::PathListItem> {
575 let lo = self.span.lo;
576 let node = if try!(self.eat_keyword(keywords::SelfValue)) {
577 let rename = try!(self.parse_rename());
578 ast::PathListMod { id: ast::DUMMY_NODE_ID, rename: rename }
580 let ident = try!(self.parse_ident());
581 let rename = try!(self.parse_rename());
582 ast::PathListIdent { name: ident, rename: rename, id: ast::DUMMY_NODE_ID }
584 let hi = self.last_span.hi;
585 Ok(spanned(lo, hi, node))
588 /// Check if the next token is `tok`, and return `true` if so.
590 /// This method is will automatically add `tok` to `expected_tokens` if `tok` is not
592 pub fn check(&mut self, tok: &token::Token) -> bool {
593 let is_present = self.token == *tok;
594 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
598 /// Consume token 'tok' if it exists. Returns true if the given
599 /// token was present, false otherwise.
600 pub fn eat(&mut self, tok: &token::Token) -> PResult<bool> {
601 let is_present = self.check(tok);
602 if is_present { try!(self.bump())}
606 pub fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
607 self.expected_tokens.push(TokenType::Keyword(kw));
608 self.token.is_keyword(kw)
611 /// If the next token is the given keyword, eat it and return
612 /// true. Otherwise, return false.
613 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> PResult<bool> {
614 if self.check_keyword(kw) {
622 pub fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> PResult<bool> {
623 if self.token.is_keyword(kw) {
631 /// If the given word is not a keyword, signal an error.
632 /// If the next token is not the given word, signal an error.
633 /// Otherwise, eat it.
634 pub fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<()> {
635 if !try!(self.eat_keyword(kw) ){
636 self.expect_one_of(&[], &[])
642 /// Signal an error if the given string is a strict keyword
643 pub fn check_strict_keywords(&mut self) {
644 if self.token.is_strict_keyword() {
645 let token_str = self.this_token_to_string();
646 let span = self.span;
648 &format!("expected identifier, found keyword `{}`",
653 /// Signal an error if the current token is a reserved keyword
654 pub fn check_reserved_keywords(&mut self) -> PResult<()>{
655 if self.token.is_reserved_keyword() {
656 let token_str = self.this_token_to_string();
657 Err(self.fatal(&format!("`{}` is a reserved keyword",
664 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
665 /// `&` and continue. If an `&` is not seen, signal an error.
666 fn expect_and(&mut self) -> PResult<()> {
667 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
669 token::BinOp(token::And) => self.bump(),
671 let span = self.span;
672 let lo = span.lo + BytePos(1);
673 Ok(self.replace_token(token::BinOp(token::And), lo, span.hi))
675 _ => self.expect_one_of(&[], &[])
679 pub fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
681 None => {/* everything ok */}
683 let text = suf.as_str();
685 self.span_bug(sp, "found empty literal suffix in Some")
687 self.span_err(sp, &*format!("{} with a suffix is invalid", kind));
693 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
694 /// `<` and continue. If a `<` is not seen, return false.
696 /// This is meant to be used when parsing generics on a path to get the
698 fn eat_lt(&mut self) -> PResult<bool> {
699 self.expected_tokens.push(TokenType::Token(token::Lt));
701 token::Lt => { try!(self.bump()); Ok(true)}
702 token::BinOp(token::Shl) => {
703 let span = self.span;
704 let lo = span.lo + BytePos(1);
705 self.replace_token(token::Lt, lo, span.hi);
712 fn expect_lt(&mut self) -> PResult<()> {
713 if !try!(self.eat_lt()) {
714 self.expect_one_of(&[], &[])
720 /// Expect and consume a GT. if a >> is seen, replace it
721 /// with a single > and continue. If a GT is not seen,
723 pub fn expect_gt(&mut self) -> PResult<()> {
724 self.expected_tokens.push(TokenType::Token(token::Gt));
726 token::Gt => self.bump(),
727 token::BinOp(token::Shr) => {
728 let span = self.span;
729 let lo = span.lo + BytePos(1);
730 Ok(self.replace_token(token::Gt, lo, span.hi))
732 token::BinOpEq(token::Shr) => {
733 let span = self.span;
734 let lo = span.lo + BytePos(1);
735 Ok(self.replace_token(token::Ge, lo, span.hi))
738 let span = self.span;
739 let lo = span.lo + BytePos(1);
740 Ok(self.replace_token(token::Eq, lo, span.hi))
743 let gt_str = Parser::token_to_string(&token::Gt);
744 let this_token_str = self.this_token_to_string();
745 Err(self.fatal(&format!("expected `{}`, found `{}`",
752 pub fn parse_seq_to_before_gt_or_return<T, F>(&mut self,
753 sep: Option<token::Token>,
755 -> PResult<(OwnedSlice<T>, bool)> where
756 F: FnMut(&mut Parser) -> PResult<Option<T>>,
758 let mut v = Vec::new();
759 // This loop works by alternating back and forth between parsing types
760 // and commas. For example, given a string `A, B,>`, the parser would
761 // first parse `A`, then a comma, then `B`, then a comma. After that it
762 // would encounter a `>` and stop. This lets the parser handle trailing
763 // commas in generic parameters, because it can stop either after
764 // parsing a type or after parsing a comma.
766 if self.check(&token::Gt)
767 || self.token == token::BinOp(token::Shr)
768 || self.token == token::Ge
769 || self.token == token::BinOpEq(token::Shr) {
774 match try!(f(self)) {
775 Some(result) => v.push(result),
776 None => return Ok((OwnedSlice::from_vec(v), true))
779 if let Some(t) = sep.as_ref() {
780 try!(self.expect(t));
785 return Ok((OwnedSlice::from_vec(v), false));
788 /// Parse a sequence bracketed by '<' and '>', stopping
790 pub fn parse_seq_to_before_gt<T, F>(&mut self,
791 sep: Option<token::Token>,
793 -> PResult<OwnedSlice<T>> where
794 F: FnMut(&mut Parser) -> PResult<T>,
796 let (result, returned) = try!(self.parse_seq_to_before_gt_or_return(sep,
797 |p| Ok(Some(try!(f(p))))));
802 pub fn parse_seq_to_gt<T, F>(&mut self,
803 sep: Option<token::Token>,
805 -> PResult<OwnedSlice<T>> where
806 F: FnMut(&mut Parser) -> PResult<T>,
808 let v = try!(self.parse_seq_to_before_gt(sep, f));
809 try!(self.expect_gt());
813 pub fn parse_seq_to_gt_or_return<T, F>(&mut self,
814 sep: Option<token::Token>,
816 -> PResult<(OwnedSlice<T>, bool)> where
817 F: FnMut(&mut Parser) -> PResult<Option<T>>,
819 let (v, returned) = try!(self.parse_seq_to_before_gt_or_return(sep, f));
821 try!(self.expect_gt());
823 return Ok((v, returned));
826 /// Parse a sequence, including the closing delimiter. The function
827 /// f must consume tokens until reaching the next separator or
829 pub fn parse_seq_to_end<T, F>(&mut self,
833 -> PResult<Vec<T>> where
834 F: FnMut(&mut Parser) -> PResult<T>,
836 let val = try!(self.parse_seq_to_before_end(ket, sep, f));
841 /// Parse a sequence, not including the closing delimiter. The function
842 /// f must consume tokens until reaching the next separator or
844 pub fn parse_seq_to_before_end<T, F>(&mut self,
848 -> PResult<Vec<T>> where
849 F: FnMut(&mut Parser) -> PResult<T>,
851 let mut first: bool = true;
853 while self.token != *ket {
856 if first { first = false; }
857 else { try!(self.expect(t)); }
861 if sep.trailing_sep_allowed && self.check(ket) { break; }
862 v.push(try!(f(self)));
867 /// Parse a sequence, including the closing delimiter. The function
868 /// f must consume tokens until reaching the next separator or
870 pub fn parse_unspanned_seq<T, F>(&mut self,
875 -> PResult<Vec<T>> where
876 F: FnMut(&mut Parser) -> PResult<T>,
878 try!(self.expect(bra));
879 let result = try!(self.parse_seq_to_before_end(ket, sep, f));
884 /// Parse a sequence parameter of enum variant. For consistency purposes,
885 /// these should not be empty.
886 pub fn parse_enum_variant_seq<T, F>(&mut self,
891 -> PResult<Vec<T>> where
892 F: FnMut(&mut Parser) -> PResult<T>,
894 let result = try!(self.parse_unspanned_seq(bra, ket, sep, f));
895 if result.is_empty() {
896 let last_span = self.last_span;
897 self.span_err(last_span,
898 "nullary enum variants are written with no trailing `( )`");
903 // NB: Do not use this function unless you actually plan to place the
904 // spanned list in the AST.
905 pub fn parse_seq<T, F>(&mut self,
910 -> PResult<Spanned<Vec<T>>> where
911 F: FnMut(&mut Parser) -> PResult<T>,
913 let lo = self.span.lo;
914 try!(self.expect(bra));
915 let result = try!(self.parse_seq_to_before_end(ket, sep, f));
916 let hi = self.span.hi;
918 Ok(spanned(lo, hi, result))
921 /// Advance the parser by one token
922 pub fn bump(&mut self) -> PResult<()> {
923 self.last_span = self.span;
924 // Stash token for error recovery (sometimes; clone is not necessarily cheap).
925 self.last_token = if self.token.is_ident() ||
926 self.token.is_path() ||
927 self.token == token::Comma {
928 Some(Box::new(self.token.clone()))
932 let next = if self.buffer_start == self.buffer_end {
933 self.reader.real_token()
935 // Avoid token copies with `replace`.
936 let buffer_start = self.buffer_start as usize;
937 let next_index = (buffer_start + 1) & 3;
938 self.buffer_start = next_index as isize;
940 let placeholder = TokenAndSpan {
941 tok: token::Underscore,
944 mem::replace(&mut self.buffer[buffer_start], placeholder)
947 self.token = next.tok;
948 self.tokens_consumed += 1;
949 self.expected_tokens.clear();
950 // check after each token
951 self.check_unknown_macro_variable()
954 /// Advance the parser by one token and return the bumped token.
955 pub fn bump_and_get(&mut self) -> PResult<token::Token> {
956 let old_token = mem::replace(&mut self.token, token::Underscore);
961 /// EFFECT: replace the current token and span with the given one
962 pub fn replace_token(&mut self,
966 self.last_span = mk_sp(self.span.lo, lo);
968 self.span = mk_sp(lo, hi);
970 pub fn buffer_length(&mut self) -> isize {
971 if self.buffer_start <= self.buffer_end {
972 return self.buffer_end - self.buffer_start;
974 return (4 - self.buffer_start) + self.buffer_end;
976 pub fn look_ahead<R, F>(&mut self, distance: usize, f: F) -> R where
977 F: FnOnce(&token::Token) -> R,
979 let dist = distance as isize;
980 while self.buffer_length() < dist {
981 self.buffer[self.buffer_end as usize] = self.reader.real_token();
982 self.buffer_end = (self.buffer_end + 1) & 3;
984 f(&self.buffer[((self.buffer_start + dist - 1) & 3) as usize].tok)
986 pub fn fatal(&self, m: &str) -> diagnostic::FatalError {
987 self.sess.span_diagnostic.span_fatal(self.span, m)
989 pub fn span_fatal(&self, sp: Span, m: &str) -> diagnostic::FatalError {
990 self.sess.span_diagnostic.span_fatal(sp, m)
992 pub fn span_fatal_help(&self, sp: Span, m: &str, help: &str) -> diagnostic::FatalError {
993 self.span_err(sp, m);
994 self.fileline_help(sp, help);
995 diagnostic::FatalError
997 pub fn span_note(&self, sp: Span, m: &str) {
998 self.sess.span_diagnostic.span_note(sp, m)
1000 pub fn span_help(&self, sp: Span, m: &str) {
1001 self.sess.span_diagnostic.span_help(sp, m)
1003 pub fn span_suggestion(&self, sp: Span, m: &str, n: String) {
1004 self.sess.span_diagnostic.span_suggestion(sp, m, n)
1006 pub fn fileline_help(&self, sp: Span, m: &str) {
1007 self.sess.span_diagnostic.fileline_help(sp, m)
1009 pub fn bug(&self, m: &str) -> ! {
1010 self.sess.span_diagnostic.span_bug(self.span, m)
1012 pub fn warn(&self, m: &str) {
1013 self.sess.span_diagnostic.span_warn(self.span, m)
1015 pub fn span_warn(&self, sp: Span, m: &str) {
1016 self.sess.span_diagnostic.span_warn(sp, m)
1018 pub fn span_err(&self, sp: Span, m: &str) {
1019 self.sess.span_diagnostic.span_err(sp, m)
1021 pub fn span_bug(&self, sp: Span, m: &str) -> ! {
1022 self.sess.span_diagnostic.span_bug(sp, m)
1024 pub fn abort_if_errors(&self) {
1025 self.sess.span_diagnostic.handler().abort_if_errors();
1028 pub fn id_to_interned_str(&mut self, id: Ident) -> InternedString {
1032 /// Is the current token one of the keywords that signals a bare function
1034 pub fn token_is_bare_fn_keyword(&mut self) -> bool {
1035 self.check_keyword(keywords::Fn) ||
1036 self.check_keyword(keywords::Unsafe) ||
1037 self.check_keyword(keywords::Extern)
1040 pub fn get_lifetime(&mut self) -> ast::Ident {
1042 token::Lifetime(ref ident) => *ident,
1043 _ => self.bug("not a lifetime"),
1047 pub fn parse_for_in_type(&mut self) -> PResult<Ty_> {
1049 Parses whatever can come after a `for` keyword in a type.
1050 The `for` has already been consumed.
1054 - for <'lt> |S| -> T
1058 - for <'lt> [unsafe] [extern "ABI"] fn (S) -> T
1059 - for <'lt> path::foo(a, b)
1064 let lo = self.span.lo;
1066 let lifetime_defs = try!(self.parse_late_bound_lifetime_defs());
1068 // examine next token to decide to do
1069 if self.token_is_bare_fn_keyword() {
1070 self.parse_ty_bare_fn(lifetime_defs)
1072 let hi = self.span.hi;
1073 let trait_ref = try!(self.parse_trait_ref());
1074 let poly_trait_ref = ast::PolyTraitRef { bound_lifetimes: lifetime_defs,
1075 trait_ref: trait_ref,
1076 span: mk_sp(lo, hi)};
1077 let other_bounds = if try!(self.eat(&token::BinOp(token::Plus)) ){
1078 try!(self.parse_ty_param_bounds(BoundParsingMode::Bare))
1083 Some(TraitTyParamBound(poly_trait_ref, TraitBoundModifier::None)).into_iter()
1084 .chain(other_bounds.into_vec())
1086 Ok(ast::TyPolyTraitRef(all_bounds))
1090 pub fn parse_ty_path(&mut self) -> PResult<Ty_> {
1091 Ok(TyPath(None, try!(self.parse_path(LifetimeAndTypesWithoutColons))))
1094 /// parse a TyBareFn type:
1095 pub fn parse_ty_bare_fn(&mut self, lifetime_defs: Vec<ast::LifetimeDef>) -> PResult<Ty_> {
1098 [unsafe] [extern "ABI"] fn <'lt> (S) -> T
1099 ^~~~^ ^~~~^ ^~~~^ ^~^ ^
1102 | | | Argument types
1108 let unsafety = try!(self.parse_unsafety());
1109 let abi = if try!(self.eat_keyword(keywords::Extern) ){
1110 try!(self.parse_opt_abi()).unwrap_or(abi::C)
1115 try!(self.expect_keyword(keywords::Fn));
1116 let (inputs, variadic) = try!(self.parse_fn_args(false, true));
1117 let ret_ty = try!(self.parse_ret_ty());
1118 let decl = P(FnDecl {
1123 Ok(TyBareFn(P(BareFnTy {
1126 lifetimes: lifetime_defs,
1131 /// Parses an obsolete closure kind (`&:`, `&mut:`, or `:`).
1132 pub fn parse_obsolete_closure_kind(&mut self) -> PResult<()> {
1133 let lo = self.span.lo;
1135 self.check(&token::BinOp(token::And)) &&
1136 self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
1137 self.look_ahead(2, |t| *t == token::Colon)
1143 self.token == token::BinOp(token::And) &&
1144 self.look_ahead(1, |t| *t == token::Colon)
1149 try!(self.eat(&token::Colon))
1156 let span = mk_sp(lo, self.span.hi);
1157 self.obsolete(span, ObsoleteSyntax::ClosureKind);
1161 pub fn parse_unsafety(&mut self) -> PResult<Unsafety> {
1162 if try!(self.eat_keyword(keywords::Unsafe)) {
1163 return Ok(Unsafety::Unsafe);
1165 return Ok(Unsafety::Normal);
1169 /// Parse the items in a trait declaration
1170 pub fn parse_trait_items(&mut self) -> PResult<Vec<P<TraitItem>>> {
1171 self.parse_unspanned_seq(
1172 &token::OpenDelim(token::Brace),
1173 &token::CloseDelim(token::Brace),
1175 |p| -> PResult<P<TraitItem>> {
1176 maybe_whole!(no_clone p, NtTraitItem);
1177 let mut attrs = p.parse_outer_attributes();
1180 let (name, node) = if try!(p.eat_keyword(keywords::Type)) {
1181 let TyParam {ident, bounds, default, ..} = try!(p.parse_ty_param());
1182 try!(p.expect(&token::Semi));
1183 (ident, TypeTraitItem(bounds, default))
1184 } else if p.is_const_item() {
1185 try!(p.expect_keyword(keywords::Const));
1186 let ident = try!(p.parse_ident());
1187 try!(p.expect(&token::Colon));
1188 let ty = try!(p.parse_ty_sum());
1189 let default = if p.check(&token::Eq) {
1191 let expr = try!(p.parse_expr_nopanic());
1192 try!(p.commit_expr_expecting(&expr, token::Semi));
1195 try!(p.expect(&token::Semi));
1198 (ident, ConstTraitItem(ty, default))
1200 let (constness, unsafety, abi) = try!(p.parse_fn_front_matter());
1202 let ident = try!(p.parse_ident());
1203 let mut generics = try!(p.parse_generics());
1205 let (explicit_self, d) = try!(p.parse_fn_decl_with_self(|p|{
1206 // This is somewhat dubious; We don't want to allow
1207 // argument names to be left off if there is a
1209 p.parse_arg_general(false)
1212 generics.where_clause = try!(p.parse_where_clause());
1213 let sig = ast::MethodSig {
1215 constness: constness,
1219 explicit_self: explicit_self,
1222 let body = match p.token {
1225 debug!("parse_trait_methods(): parsing required method");
1228 token::OpenDelim(token::Brace) => {
1229 debug!("parse_trait_methods(): parsing provided method");
1230 let (inner_attrs, body) =
1231 try!(p.parse_inner_attrs_and_block());
1232 attrs.extend(inner_attrs.iter().cloned());
1237 let token_str = p.this_token_to_string();
1238 return Err(p.fatal(&format!("expected `;` or `{{`, found `{}`",
1242 (ident, ast::MethodTraitItem(sig, body))
1246 id: ast::DUMMY_NODE_ID,
1250 span: mk_sp(lo, p.last_span.hi),
1255 /// Parse a possibly mutable type
1256 pub fn parse_mt(&mut self) -> PResult<MutTy> {
1257 let mutbl = try!(self.parse_mutability());
1258 let t = try!(self.parse_ty_nopanic());
1259 Ok(MutTy { ty: t, mutbl: mutbl })
1262 /// Parse optional return type [ -> TY ] in function decl
1263 pub fn parse_ret_ty(&mut self) -> PResult<FunctionRetTy> {
1264 if try!(self.eat(&token::RArrow) ){
1265 if try!(self.eat(&token::Not) ){
1266 Ok(NoReturn(self.span))
1268 Ok(Return(try!(self.parse_ty_nopanic())))
1271 let pos = self.span.lo;
1272 Ok(DefaultReturn(mk_sp(pos, pos)))
1276 /// Parse a type in a context where `T1+T2` is allowed.
1277 pub fn parse_ty_sum(&mut self) -> PResult<P<Ty>> {
1278 let lo = self.span.lo;
1279 let lhs = try!(self.parse_ty_nopanic());
1281 if !try!(self.eat(&token::BinOp(token::Plus)) ){
1285 let bounds = try!(self.parse_ty_param_bounds(BoundParsingMode::Bare));
1287 // In type grammar, `+` is treated like a binary operator,
1288 // and hence both L and R side are required.
1289 if bounds.is_empty() {
1290 let last_span = self.last_span;
1291 self.span_err(last_span,
1292 "at least one type parameter bound \
1293 must be specified");
1296 let sp = mk_sp(lo, self.last_span.hi);
1297 let sum = ast::TyObjectSum(lhs, bounds);
1298 Ok(P(Ty {id: ast::DUMMY_NODE_ID, node: sum, span: sp}))
1302 pub fn parse_ty_nopanic(&mut self) -> PResult<P<Ty>> {
1303 maybe_whole!(no_clone self, NtTy);
1305 let lo = self.span.lo;
1307 let t = if self.check(&token::OpenDelim(token::Paren)) {
1310 // (t) is a parenthesized ty
1311 // (t,) is the type of a tuple with only one field,
1313 let mut ts = vec![];
1314 let mut last_comma = false;
1315 while self.token != token::CloseDelim(token::Paren) {
1316 ts.push(try!(self.parse_ty_sum()));
1317 if self.check(&token::Comma) {
1326 try!(self.expect(&token::CloseDelim(token::Paren)));
1327 if ts.len() == 1 && !last_comma {
1328 TyParen(ts.into_iter().nth(0).unwrap())
1332 } else if self.check(&token::BinOp(token::Star)) {
1333 // STAR POINTER (bare pointer?)
1335 TyPtr(try!(self.parse_ptr()))
1336 } else if self.check(&token::OpenDelim(token::Bracket)) {
1338 try!(self.expect(&token::OpenDelim(token::Bracket)));
1339 let t = try!(self.parse_ty_sum());
1341 // Parse the `; e` in `[ i32; e ]`
1342 // where `e` is a const expression
1343 let t = match try!(self.maybe_parse_fixed_length_of_vec()) {
1345 Some(suffix) => TyFixedLengthVec(t, suffix)
1347 try!(self.expect(&token::CloseDelim(token::Bracket)));
1349 } else if self.check(&token::BinOp(token::And)) ||
1350 self.token == token::AndAnd {
1352 try!(self.expect_and());
1353 try!(self.parse_borrowed_pointee())
1354 } else if self.check_keyword(keywords::For) {
1355 try!(self.parse_for_in_type())
1356 } else if self.token_is_bare_fn_keyword() {
1358 try!(self.parse_ty_bare_fn(Vec::new()))
1359 } else if try!(self.eat_keyword_noexpect(keywords::Typeof)) {
1361 // In order to not be ambiguous, the type must be surrounded by parens.
1362 try!(self.expect(&token::OpenDelim(token::Paren)));
1363 let e = try!(self.parse_expr_nopanic());
1364 try!(self.expect(&token::CloseDelim(token::Paren)));
1366 } else if try!(self.eat_lt()) {
1369 try!(self.parse_qualified_path(NoTypesAllowed));
1371 TyPath(Some(qself), path)
1372 } else if self.check(&token::ModSep) ||
1373 self.token.is_ident() ||
1374 self.token.is_path() {
1375 let path = try!(self.parse_path(LifetimeAndTypesWithoutColons));
1376 if self.check(&token::Not) {
1379 let delim = try!(self.expect_open_delim());
1380 let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
1382 |p| p.parse_token_tree()));
1383 let hi = self.span.hi;
1384 TyMac(spanned(lo, hi, MacInvocTT(path, tts, EMPTY_CTXT)))
1389 } else if try!(self.eat(&token::Underscore) ){
1390 // TYPE TO BE INFERRED
1393 let this_token_str = self.this_token_to_string();
1394 let msg = format!("expected type, found `{}`", this_token_str);
1395 return Err(self.fatal(&msg[..]));
1398 let sp = mk_sp(lo, self.last_span.hi);
1399 Ok(P(Ty {id: ast::DUMMY_NODE_ID, node: t, span: sp}))
1402 pub fn parse_borrowed_pointee(&mut self) -> PResult<Ty_> {
1403 // look for `&'lt` or `&'foo ` and interpret `foo` as the region name:
1404 let opt_lifetime = try!(self.parse_opt_lifetime());
1406 let mt = try!(self.parse_mt());
1407 return Ok(TyRptr(opt_lifetime, mt));
1410 pub fn parse_ptr(&mut self) -> PResult<MutTy> {
1411 let mutbl = if try!(self.eat_keyword(keywords::Mut) ){
1413 } else if try!(self.eat_keyword(keywords::Const) ){
1416 let span = self.last_span;
1418 "bare raw pointers are no longer allowed, you should \
1419 likely use `*mut T`, but otherwise `*T` is now \
1420 known as `*const T`");
1423 let t = try!(self.parse_ty_nopanic());
1424 Ok(MutTy { ty: t, mutbl: mutbl })
1427 pub fn is_named_argument(&mut self) -> bool {
1428 let offset = match self.token {
1429 token::BinOp(token::And) => 1,
1431 _ if self.token.is_keyword(keywords::Mut) => 1,
1435 debug!("parser is_named_argument offset:{}", offset);
1438 is_plain_ident_or_underscore(&self.token)
1439 && self.look_ahead(1, |t| *t == token::Colon)
1441 self.look_ahead(offset, |t| is_plain_ident_or_underscore(t))
1442 && self.look_ahead(offset + 1, |t| *t == token::Colon)
1446 /// This version of parse arg doesn't necessarily require
1447 /// identifier names.
1448 pub fn parse_arg_general(&mut self, require_name: bool) -> PResult<Arg> {
1449 let pat = if require_name || self.is_named_argument() {
1450 debug!("parse_arg_general parse_pat (require_name:{})",
1452 let pat = try!(self.parse_pat_nopanic());
1454 try!(self.expect(&token::Colon));
1457 debug!("parse_arg_general ident_to_pat");
1458 ast_util::ident_to_pat(ast::DUMMY_NODE_ID,
1460 special_idents::invalid)
1463 let t = try!(self.parse_ty_sum());
1468 id: ast::DUMMY_NODE_ID,
1472 /// Parse a single function argument
1473 pub fn parse_arg(&mut self) -> PResult<Arg> {
1474 self.parse_arg_general(true)
1477 /// Parse an argument in a lambda header e.g. |arg, arg|
1478 pub fn parse_fn_block_arg(&mut self) -> PResult<Arg> {
1479 let pat = try!(self.parse_pat_nopanic());
1480 let t = if try!(self.eat(&token::Colon) ){
1481 try!(self.parse_ty_sum())
1484 id: ast::DUMMY_NODE_ID,
1486 span: mk_sp(self.span.lo, self.span.hi),
1492 id: ast::DUMMY_NODE_ID
1496 pub fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<Option<P<ast::Expr>>> {
1497 if self.check(&token::Semi) {
1499 Ok(Some(try!(self.parse_expr_nopanic())))
1505 /// Matches token_lit = LIT_INTEGER | ...
1506 pub fn lit_from_token(&self, tok: &token::Token) -> PResult<Lit_> {
1508 token::Interpolated(token::NtExpr(ref v)) => {
1510 ExprLit(ref lit) => { Ok(lit.node.clone()) }
1511 _ => { return Err(self.unexpected_last(tok)); }
1514 token::Literal(lit, suf) => {
1515 let (suffix_illegal, out) = match lit {
1516 token::Byte(i) => (true, LitByte(parse::byte_lit(&i.as_str()).0)),
1517 token::Char(i) => (true, LitChar(parse::char_lit(&i.as_str()).0)),
1519 // there are some valid suffixes for integer and
1520 // float literals, so all the handling is done
1522 token::Integer(s) => {
1523 (false, parse::integer_lit(&s.as_str(),
1524 suf.as_ref().map(|s| s.as_str()),
1525 &self.sess.span_diagnostic,
1528 token::Float(s) => {
1529 (false, parse::float_lit(&s.as_str(),
1530 suf.as_ref().map(|s| s.as_str()),
1531 &self.sess.span_diagnostic,
1537 LitStr(token::intern_and_get_ident(&parse::str_lit(&s.as_str())),
1540 token::StrRaw(s, n) => {
1543 token::intern_and_get_ident(&parse::raw_str_lit(&s.as_str())),
1546 token::ByteStr(i) =>
1547 (true, LitByteStr(parse::byte_str_lit(&i.as_str()))),
1548 token::ByteStrRaw(i, _) =>
1550 LitByteStr(Rc::new(i.to_string().into_bytes()))),
1554 let sp = self.last_span;
1555 self.expect_no_suffix(sp, &*format!("{} literal", lit.short_name()), suf)
1560 _ => { return Err(self.unexpected_last(tok)); }
1564 /// Matches lit = true | false | token_lit
1565 pub fn parse_lit(&mut self) -> PResult<Lit> {
1566 let lo = self.span.lo;
1567 let lit = if try!(self.eat_keyword(keywords::True) ){
1569 } else if try!(self.eat_keyword(keywords::False) ){
1572 let token = try!(self.bump_and_get());
1573 let lit = try!(self.lit_from_token(&token));
1576 Ok(codemap::Spanned { node: lit, span: mk_sp(lo, self.last_span.hi) })
1579 /// matches '-' lit | lit
1580 pub fn parse_literal_maybe_minus(&mut self) -> PResult<P<Expr>> {
1581 let minus_lo = self.span.lo;
1582 let minus_present = try!(self.eat(&token::BinOp(token::Minus)));
1584 let lo = self.span.lo;
1585 let literal = P(try!(self.parse_lit()));
1586 let hi = self.span.hi;
1587 let expr = self.mk_expr(lo, hi, ExprLit(literal));
1590 let minus_hi = self.span.hi;
1591 let unary = self.mk_unary(UnNeg, expr);
1592 Ok(self.mk_expr(minus_lo, minus_hi, unary))
1598 // QUALIFIED PATH `<TYPE [as TRAIT_REF]>::IDENT[::<PARAMS>]`
1599 // Assumes that the leading `<` has been parsed already.
1600 pub fn parse_qualified_path(&mut self, mode: PathParsingMode)
1601 -> PResult<(QSelf, ast::Path)> {
1602 let span = self.last_span;
1603 let self_type = try!(self.parse_ty_sum());
1604 let mut path = if try!(self.eat_keyword(keywords::As)) {
1605 try!(self.parse_path(LifetimeAndTypesWithoutColons))
1616 position: path.segments.len()
1619 try!(self.expect(&token::Gt));
1620 try!(self.expect(&token::ModSep));
1622 let segments = match mode {
1623 LifetimeAndTypesWithoutColons => {
1624 try!(self.parse_path_segments_without_colons())
1626 LifetimeAndTypesWithColons => {
1627 try!(self.parse_path_segments_with_colons())
1630 try!(self.parse_path_segments_without_types())
1633 path.segments.extend(segments);
1635 path.span.hi = self.last_span.hi;
1640 /// Parses a path and optional type parameter bounds, depending on the
1641 /// mode. The `mode` parameter determines whether lifetimes, types, and/or
1642 /// bounds are permitted and whether `::` must precede type parameter
1644 pub fn parse_path(&mut self, mode: PathParsingMode) -> PResult<ast::Path> {
1645 // Check for a whole path...
1646 let found = match self.token {
1647 token::Interpolated(token::NtPath(_)) => Some(try!(self.bump_and_get())),
1650 if let Some(token::Interpolated(token::NtPath(path))) = found {
1654 let lo = self.span.lo;
1655 let is_global = try!(self.eat(&token::ModSep));
1657 // Parse any number of segments and bound sets. A segment is an
1658 // identifier followed by an optional lifetime and a set of types.
1659 // A bound set is a set of type parameter bounds.
1660 let segments = match mode {
1661 LifetimeAndTypesWithoutColons => {
1662 try!(self.parse_path_segments_without_colons())
1664 LifetimeAndTypesWithColons => {
1665 try!(self.parse_path_segments_with_colons())
1668 try!(self.parse_path_segments_without_types())
1672 // Assemble the span.
1673 let span = mk_sp(lo, self.last_span.hi);
1675 // Assemble the result.
1684 /// - `a::b<T,U>::c<V,W>`
1685 /// - `a::b<T,U>::c(V) -> W`
1686 /// - `a::b<T,U>::c(V)`
1687 pub fn parse_path_segments_without_colons(&mut self) -> PResult<Vec<ast::PathSegment>> {
1688 let mut segments = Vec::new();
1690 // First, parse an identifier.
1691 let identifier = try!(self.parse_ident_or_self_type());
1693 // Parse types, optionally.
1694 let parameters = if try!(self.eat_lt() ){
1695 let (lifetimes, types, bindings) = try!(self.parse_generic_values_after_lt());
1697 ast::AngleBracketedParameters(ast::AngleBracketedParameterData {
1698 lifetimes: lifetimes,
1699 types: OwnedSlice::from_vec(types),
1700 bindings: OwnedSlice::from_vec(bindings),
1702 } else if try!(self.eat(&token::OpenDelim(token::Paren)) ){
1703 let lo = self.last_span.lo;
1705 let inputs = try!(self.parse_seq_to_end(
1706 &token::CloseDelim(token::Paren),
1707 seq_sep_trailing_allowed(token::Comma),
1708 |p| p.parse_ty_sum()));
1710 let output_ty = if try!(self.eat(&token::RArrow) ){
1711 Some(try!(self.parse_ty_nopanic()))
1716 let hi = self.last_span.hi;
1718 ast::ParenthesizedParameters(ast::ParenthesizedParameterData {
1719 span: mk_sp(lo, hi),
1724 ast::PathParameters::none()
1727 // Assemble and push the result.
1728 segments.push(ast::PathSegment { identifier: identifier,
1729 parameters: parameters });
1731 // Continue only if we see a `::`
1732 if !try!(self.eat(&token::ModSep) ){
1733 return Ok(segments);
1739 /// - `a::b::<T,U>::c`
1740 pub fn parse_path_segments_with_colons(&mut self) -> PResult<Vec<ast::PathSegment>> {
1741 let mut segments = Vec::new();
1743 // First, parse an identifier.
1744 let identifier = try!(self.parse_ident_or_self_type());
1746 // If we do not see a `::`, stop.
1747 if !try!(self.eat(&token::ModSep) ){
1748 segments.push(ast::PathSegment {
1749 identifier: identifier,
1750 parameters: ast::PathParameters::none()
1752 return Ok(segments);
1755 // Check for a type segment.
1756 if try!(self.eat_lt() ){
1757 // Consumed `a::b::<`, go look for types
1758 let (lifetimes, types, bindings) = try!(self.parse_generic_values_after_lt());
1759 segments.push(ast::PathSegment {
1760 identifier: identifier,
1761 parameters: ast::AngleBracketedParameters(ast::AngleBracketedParameterData {
1762 lifetimes: lifetimes,
1763 types: OwnedSlice::from_vec(types),
1764 bindings: OwnedSlice::from_vec(bindings),
1768 // Consumed `a::b::<T,U>`, check for `::` before proceeding
1769 if !try!(self.eat(&token::ModSep) ){
1770 return Ok(segments);
1773 // Consumed `a::`, go look for `b`
1774 segments.push(ast::PathSegment {
1775 identifier: identifier,
1776 parameters: ast::PathParameters::none(),
1785 pub fn parse_path_segments_without_types(&mut self) -> PResult<Vec<ast::PathSegment>> {
1786 let mut segments = Vec::new();
1788 // First, parse an identifier.
1789 let identifier = try!(self.parse_ident_or_self_type());
1791 // Assemble and push the result.
1792 segments.push(ast::PathSegment {
1793 identifier: identifier,
1794 parameters: ast::PathParameters::none()
1797 // If we do not see a `::`, stop.
1798 if !try!(self.eat(&token::ModSep) ){
1799 return Ok(segments);
1804 /// parses 0 or 1 lifetime
1805 pub fn parse_opt_lifetime(&mut self) -> PResult<Option<ast::Lifetime>> {
1807 token::Lifetime(..) => {
1808 Ok(Some(try!(self.parse_lifetime())))
1816 /// Parses a single lifetime
1817 /// Matches lifetime = LIFETIME
1818 pub fn parse_lifetime(&mut self) -> PResult<ast::Lifetime> {
1820 token::Lifetime(i) => {
1821 let span = self.span;
1823 return Ok(ast::Lifetime {
1824 id: ast::DUMMY_NODE_ID,
1830 return Err(self.fatal(&format!("expected a lifetime name")));
1835 /// Parses `lifetime_defs = [ lifetime_defs { ',' lifetime_defs } ]` where `lifetime_def =
1836 /// lifetime [':' lifetimes]`
1837 pub fn parse_lifetime_defs(&mut self) -> PResult<Vec<ast::LifetimeDef>> {
1839 let mut res = Vec::new();
1842 token::Lifetime(_) => {
1843 let lifetime = try!(self.parse_lifetime());
1845 if try!(self.eat(&token::Colon) ){
1846 try!(self.parse_lifetimes(token::BinOp(token::Plus)))
1850 res.push(ast::LifetimeDef { lifetime: lifetime,
1860 token::Comma => { try!(self.bump());}
1861 token::Gt => { return Ok(res); }
1862 token::BinOp(token::Shr) => { return Ok(res); }
1864 let this_token_str = self.this_token_to_string();
1865 let msg = format!("expected `,` or `>` after lifetime \
1868 return Err(self.fatal(&msg[..]));
1874 /// matches lifetimes = ( lifetime ) | ( lifetime , lifetimes ) actually, it matches the empty
1875 /// one too, but putting that in there messes up the grammar....
1877 /// Parses zero or more comma separated lifetimes. Expects each lifetime to be followed by
1878 /// either a comma or `>`. Used when parsing type parameter lists, where we expect something
1879 /// like `<'a, 'b, T>`.
1880 pub fn parse_lifetimes(&mut self, sep: token::Token) -> PResult<Vec<ast::Lifetime>> {
1882 let mut res = Vec::new();
1885 token::Lifetime(_) => {
1886 res.push(try!(self.parse_lifetime()));
1893 if self.token != sep {
1901 /// Parse mutability declaration (mut/const/imm)
1902 pub fn parse_mutability(&mut self) -> PResult<Mutability> {
1903 if try!(self.eat_keyword(keywords::Mut) ){
1910 /// Parse ident COLON expr
1911 pub fn parse_field(&mut self) -> PResult<Field> {
1912 let lo = self.span.lo;
1913 let i = try!(self.parse_ident());
1914 let hi = self.last_span.hi;
1915 try!(self.expect(&token::Colon));
1916 let e = try!(self.parse_expr_nopanic());
1918 ident: spanned(lo, hi, i),
1919 span: mk_sp(lo, e.span.hi),
1924 pub fn mk_expr(&mut self, lo: BytePos, hi: BytePos, node: Expr_) -> P<Expr> {
1926 id: ast::DUMMY_NODE_ID,
1928 span: mk_sp(lo, hi),
1932 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::Expr_ {
1933 ExprUnary(unop, expr)
1936 pub fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::Expr_ {
1937 ExprBinary(binop, lhs, rhs)
1940 pub fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::Expr_ {
1944 fn mk_method_call(&mut self,
1945 ident: ast::SpannedIdent,
1949 ExprMethodCall(ident, tps, args)
1952 pub fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::Expr_ {
1953 ExprIndex(expr, idx)
1956 pub fn mk_range(&mut self,
1957 start: Option<P<Expr>>,
1958 end: Option<P<Expr>>)
1960 ExprRange(start, end)
1963 pub fn mk_field(&mut self, expr: P<Expr>, ident: ast::SpannedIdent) -> ast::Expr_ {
1964 ExprField(expr, ident)
1967 pub fn mk_tup_field(&mut self, expr: P<Expr>, idx: codemap::Spanned<usize>) -> ast::Expr_ {
1968 ExprTupField(expr, idx)
1971 pub fn mk_assign_op(&mut self, binop: ast::BinOp,
1972 lhs: P<Expr>, rhs: P<Expr>) -> ast::Expr_ {
1973 ExprAssignOp(binop, lhs, rhs)
1976 pub fn mk_mac_expr(&mut self, lo: BytePos, hi: BytePos, m: Mac_) -> P<Expr> {
1978 id: ast::DUMMY_NODE_ID,
1979 node: ExprMac(codemap::Spanned {node: m, span: mk_sp(lo, hi)}),
1980 span: mk_sp(lo, hi),
1984 pub fn mk_lit_u32(&mut self, i: u32) -> P<Expr> {
1985 let span = &self.span;
1986 let lv_lit = P(codemap::Spanned {
1987 node: LitInt(i as u64, ast::UnsignedIntLit(TyU32)),
1992 id: ast::DUMMY_NODE_ID,
1993 node: ExprLit(lv_lit),
1998 fn expect_open_delim(&mut self) -> PResult<token::DelimToken> {
1999 self.expected_tokens.push(TokenType::Token(token::Gt));
2001 token::OpenDelim(delim) => {
2005 _ => Err(self.fatal("expected open delimiter")),
2009 /// At the bottom (top?) of the precedence hierarchy,
2010 /// parse things like parenthesized exprs,
2011 /// macros, return, etc.
2012 pub fn parse_bottom_expr(&mut self) -> PResult<P<Expr>> {
2013 maybe_whole_expr!(self);
2015 let lo = self.span.lo;
2016 let mut hi = self.span.hi;
2020 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2022 token::OpenDelim(token::Paren) => {
2025 // (e) is parenthesized e
2026 // (e,) is a tuple with only one field, e
2027 let mut es = vec![];
2028 let mut trailing_comma = false;
2029 while self.token != token::CloseDelim(token::Paren) {
2030 es.push(try!(self.parse_expr_nopanic()));
2031 try!(self.commit_expr(&**es.last().unwrap(), &[],
2032 &[token::Comma, token::CloseDelim(token::Paren)]));
2033 if self.check(&token::Comma) {
2034 trailing_comma = true;
2038 trailing_comma = false;
2044 hi = self.last_span.hi;
2045 return if es.len() == 1 && !trailing_comma {
2046 Ok(self.mk_expr(lo, hi, ExprParen(es.into_iter().nth(0).unwrap())))
2048 Ok(self.mk_expr(lo, hi, ExprTup(es)))
2051 token::OpenDelim(token::Brace) => {
2052 return self.parse_block_expr(lo, DefaultBlock);
2054 token::BinOp(token::Or) | token::OrOr => {
2055 let lo = self.span.lo;
2056 return self.parse_lambda_expr(lo, CaptureByRef);
2058 token::Ident(id @ ast::Ident {
2059 name: token::SELF_KEYWORD_NAME,
2061 }, token::Plain) => {
2063 let path = ast_util::ident_to_path(mk_sp(lo, hi), id);
2064 ex = ExprPath(None, path);
2065 hi = self.last_span.hi;
2067 token::OpenDelim(token::Bracket) => {
2070 if self.check(&token::CloseDelim(token::Bracket)) {
2073 ex = ExprVec(Vec::new());
2076 let first_expr = try!(self.parse_expr_nopanic());
2077 if self.check(&token::Semi) {
2078 // Repeating array syntax: [ 0; 512 ]
2080 let count = try!(self.parse_expr_nopanic());
2081 try!(self.expect(&token::CloseDelim(token::Bracket)));
2082 ex = ExprRepeat(first_expr, count);
2083 } else if self.check(&token::Comma) {
2084 // Vector with two or more elements.
2086 let remaining_exprs = try!(self.parse_seq_to_end(
2087 &token::CloseDelim(token::Bracket),
2088 seq_sep_trailing_allowed(token::Comma),
2089 |p| Ok(try!(p.parse_expr_nopanic()))
2091 let mut exprs = vec!(first_expr);
2092 exprs.extend(remaining_exprs);
2093 ex = ExprVec(exprs);
2095 // Vector with one element.
2096 try!(self.expect(&token::CloseDelim(token::Bracket)));
2097 ex = ExprVec(vec!(first_expr));
2100 hi = self.last_span.hi;
2103 if try!(self.eat_lt()){
2105 try!(self.parse_qualified_path(LifetimeAndTypesWithColons));
2107 return Ok(self.mk_expr(lo, hi, ExprPath(Some(qself), path)));
2109 if try!(self.eat_keyword(keywords::Move) ){
2110 let lo = self.last_span.lo;
2111 return self.parse_lambda_expr(lo, CaptureByValue);
2113 if try!(self.eat_keyword(keywords::If)) {
2114 return self.parse_if_expr();
2116 if try!(self.eat_keyword(keywords::For) ){
2117 let lo = self.last_span.lo;
2118 return self.parse_for_expr(None, lo);
2120 if try!(self.eat_keyword(keywords::While) ){
2121 let lo = self.last_span.lo;
2122 return self.parse_while_expr(None, lo);
2124 if self.token.is_lifetime() {
2125 let lifetime = self.get_lifetime();
2126 let lo = self.span.lo;
2128 try!(self.expect(&token::Colon));
2129 if try!(self.eat_keyword(keywords::While) ){
2130 return self.parse_while_expr(Some(lifetime), lo)
2132 if try!(self.eat_keyword(keywords::For) ){
2133 return self.parse_for_expr(Some(lifetime), lo)
2135 if try!(self.eat_keyword(keywords::Loop) ){
2136 return self.parse_loop_expr(Some(lifetime), lo)
2138 return Err(self.fatal("expected `while`, `for`, or `loop` after a label"))
2140 if try!(self.eat_keyword(keywords::Loop) ){
2141 let lo = self.last_span.lo;
2142 return self.parse_loop_expr(None, lo);
2144 if try!(self.eat_keyword(keywords::Continue) ){
2145 let ex = if self.token.is_lifetime() {
2146 let ex = ExprAgain(Some(Spanned{
2147 node: self.get_lifetime(),
2155 let hi = self.last_span.hi;
2156 return Ok(self.mk_expr(lo, hi, ex));
2158 if try!(self.eat_keyword(keywords::Match) ){
2159 return self.parse_match_expr();
2161 if try!(self.eat_keyword(keywords::Unsafe) ){
2162 return self.parse_block_expr(
2164 UnsafeBlock(ast::UserProvided));
2166 if try!(self.eat_keyword(keywords::Return) ){
2167 if self.token.can_begin_expr() {
2168 let e = try!(self.parse_expr_nopanic());
2170 ex = ExprRet(Some(e));
2174 } else if try!(self.eat_keyword(keywords::Break) ){
2175 if self.token.is_lifetime() {
2176 ex = ExprBreak(Some(Spanned {
2177 node: self.get_lifetime(),
2182 ex = ExprBreak(None);
2184 hi = self.last_span.hi;
2185 } else if self.check(&token::ModSep) ||
2186 self.token.is_ident() &&
2187 !self.check_keyword(keywords::True) &&
2188 !self.check_keyword(keywords::False) {
2190 try!(self.parse_path(LifetimeAndTypesWithColons));
2192 // `!`, as an operator, is prefix, so we know this isn't that
2193 if self.check(&token::Not) {
2194 // MACRO INVOCATION expression
2197 let delim = try!(self.expect_open_delim());
2198 let tts = try!(self.parse_seq_to_end(
2199 &token::CloseDelim(delim),
2201 |p| p.parse_token_tree()));
2202 let hi = self.last_span.hi;
2204 return Ok(self.mk_mac_expr(lo,
2210 if self.check(&token::OpenDelim(token::Brace)) {
2211 // This is a struct literal, unless we're prohibited
2212 // from parsing struct literals here.
2213 let prohibited = self.restrictions.contains(
2214 Restrictions::RESTRICTION_NO_STRUCT_LITERAL
2217 // It's a struct literal.
2219 let mut fields = Vec::new();
2220 let mut base = None;
2222 while self.token != token::CloseDelim(token::Brace) {
2223 if try!(self.eat(&token::DotDot) ){
2224 base = Some(try!(self.parse_expr_nopanic()));
2228 fields.push(try!(self.parse_field()));
2229 try!(self.commit_expr(&*fields.last().unwrap().expr,
2231 &[token::CloseDelim(token::Brace)]));
2234 if fields.is_empty() && base.is_none() {
2235 let last_span = self.last_span;
2236 self.span_err(last_span,
2237 "structure literal must either \
2238 have at least one field or use \
2239 structure update syntax");
2243 try!(self.expect(&token::CloseDelim(token::Brace)));
2244 ex = ExprStruct(pth, fields, base);
2245 return Ok(self.mk_expr(lo, hi, ex));
2250 ex = ExprPath(None, pth);
2252 // other literal expression
2253 let lit = try!(self.parse_lit());
2255 ex = ExprLit(P(lit));
2260 return Ok(self.mk_expr(lo, hi, ex));
2263 /// Parse a block or unsafe block
2264 pub fn parse_block_expr(&mut self, lo: BytePos, blk_mode: BlockCheckMode)
2265 -> PResult<P<Expr>> {
2266 try!(self.expect(&token::OpenDelim(token::Brace)));
2267 let blk = try!(self.parse_block_tail(lo, blk_mode));
2268 return Ok(self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk)));
2271 /// parse a.b or a(13) or a[4] or just a
2272 pub fn parse_dot_or_call_expr(&mut self) -> PResult<P<Expr>> {
2273 let b = try!(self.parse_bottom_expr());
2274 self.parse_dot_or_call_expr_with(b)
2277 pub fn parse_dot_or_call_expr_with(&mut self, e0: P<Expr>) -> PResult<P<Expr>> {
2283 if try!(self.eat(&token::Dot) ){
2285 token::Ident(i, _) => {
2286 let dot = self.last_span.hi;
2289 let (_, tys, bindings) = if try!(self.eat(&token::ModSep) ){
2290 try!(self.expect_lt());
2291 try!(self.parse_generic_values_after_lt())
2293 (Vec::new(), Vec::new(), Vec::new())
2296 if !bindings.is_empty() {
2297 let last_span = self.last_span;
2298 self.span_err(last_span, "type bindings are only permitted on trait paths");
2301 // expr.f() method call
2303 token::OpenDelim(token::Paren) => {
2304 let mut es = try!(self.parse_unspanned_seq(
2305 &token::OpenDelim(token::Paren),
2306 &token::CloseDelim(token::Paren),
2307 seq_sep_trailing_allowed(token::Comma),
2308 |p| Ok(try!(p.parse_expr_nopanic()))
2310 hi = self.last_span.hi;
2313 let id = spanned(dot, hi, i);
2314 let nd = self.mk_method_call(id, tys, es);
2315 e = self.mk_expr(lo, hi, nd);
2318 if !tys.is_empty() {
2319 let last_span = self.last_span;
2320 self.span_err(last_span,
2321 "field expressions may not \
2322 have type parameters");
2325 let id = spanned(dot, hi, i);
2326 let field = self.mk_field(e, id);
2327 e = self.mk_expr(lo, hi, field);
2331 token::Literal(token::Integer(n), suf) => {
2334 // A tuple index may not have a suffix
2335 self.expect_no_suffix(sp, "tuple index", suf);
2337 let dot = self.last_span.hi;
2341 let index = n.as_str().parse::<usize>().ok();
2344 let id = spanned(dot, hi, n);
2345 let field = self.mk_tup_field(e, id);
2346 e = self.mk_expr(lo, hi, field);
2349 let last_span = self.last_span;
2350 self.span_err(last_span, "invalid tuple or tuple struct index");
2354 token::Literal(token::Float(n), _suf) => {
2356 let last_span = self.last_span;
2357 let fstr = n.as_str();
2358 self.span_err(last_span,
2359 &format!("unexpected token: `{}`", n.as_str()));
2360 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2361 let float = match fstr.parse::<f64>().ok() {
2365 self.fileline_help(last_span,
2366 &format!("try parenthesizing the first index; e.g., `(foo.{}){}`",
2367 float.trunc() as usize,
2368 format!(".{}", fstr.splitn(2, ".").last().unwrap())));
2370 self.abort_if_errors();
2373 _ => return Err(self.unexpected())
2377 if self.expr_is_complete(&*e) { break; }
2380 token::OpenDelim(token::Paren) => {
2381 let es = try!(self.parse_unspanned_seq(
2382 &token::OpenDelim(token::Paren),
2383 &token::CloseDelim(token::Paren),
2384 seq_sep_trailing_allowed(token::Comma),
2385 |p| Ok(try!(p.parse_expr_nopanic()))
2387 hi = self.last_span.hi;
2389 let nd = self.mk_call(e, es);
2390 e = self.mk_expr(lo, hi, nd);
2394 // Could be either an index expression or a slicing expression.
2395 token::OpenDelim(token::Bracket) => {
2397 let ix = try!(self.parse_expr_nopanic());
2399 try!(self.commit_expr_expecting(&*ix, token::CloseDelim(token::Bracket)));
2400 let index = self.mk_index(e, ix);
2401 e = self.mk_expr(lo, hi, index)
2409 // Parse unquoted tokens after a `$` in a token tree
2410 fn parse_unquoted(&mut self) -> PResult<TokenTree> {
2411 let mut sp = self.span;
2412 let (name, namep) = match self.token {
2416 if self.token == token::OpenDelim(token::Paren) {
2417 let Spanned { node: seq, span: seq_span } = try!(self.parse_seq(
2418 &token::OpenDelim(token::Paren),
2419 &token::CloseDelim(token::Paren),
2421 |p| p.parse_token_tree()
2423 let (sep, repeat) = try!(self.parse_sep_and_kleene_op());
2424 let name_num = macro_parser::count_names(&seq);
2425 return Ok(TtSequence(mk_sp(sp.lo, seq_span.hi),
2426 Rc::new(SequenceRepetition {
2430 num_captures: name_num
2432 } else if self.token.is_keyword_allow_following_colon(keywords::Crate) {
2434 return Ok(TtToken(sp, SpecialVarNt(SpecialMacroVar::CrateMacroVar)));
2436 sp = mk_sp(sp.lo, self.span.hi);
2437 let namep = match self.token { token::Ident(_, p) => p, _ => token::Plain };
2438 let name = try!(self.parse_ident());
2442 token::SubstNt(name, namep) => {
2448 // continue by trying to parse the `:ident` after `$name`
2449 if self.token == token::Colon && self.look_ahead(1, |t| t.is_ident() &&
2450 !t.is_strict_keyword() &&
2451 !t.is_reserved_keyword()) {
2453 sp = mk_sp(sp.lo, self.span.hi);
2454 let kindp = match self.token { token::Ident(_, p) => p, _ => token::Plain };
2455 let nt_kind = try!(self.parse_ident());
2456 Ok(TtToken(sp, MatchNt(name, nt_kind, namep, kindp)))
2458 Ok(TtToken(sp, SubstNt(name, namep)))
2462 pub fn check_unknown_macro_variable(&mut self) -> PResult<()> {
2463 if self.quote_depth == 0 {
2465 token::SubstNt(name, _) =>
2466 return Err(self.fatal(&format!("unknown macro variable `{}`",
2474 /// Parse an optional separator followed by a Kleene-style
2475 /// repetition token (+ or *).
2476 pub fn parse_sep_and_kleene_op(&mut self) -> PResult<(Option<token::Token>, ast::KleeneOp)> {
2477 fn parse_kleene_op(parser: &mut Parser) -> PResult<Option<ast::KleeneOp>> {
2478 match parser.token {
2479 token::BinOp(token::Star) => {
2480 try!(parser.bump());
2481 Ok(Some(ast::ZeroOrMore))
2483 token::BinOp(token::Plus) => {
2484 try!(parser.bump());
2485 Ok(Some(ast::OneOrMore))
2491 match try!(parse_kleene_op(self)) {
2492 Some(kleene_op) => return Ok((None, kleene_op)),
2496 let separator = try!(self.bump_and_get());
2497 match try!(parse_kleene_op(self)) {
2498 Some(zerok) => Ok((Some(separator), zerok)),
2499 None => return Err(self.fatal("expected `*` or `+`"))
2503 /// parse a single token tree from the input.
2504 pub fn parse_token_tree(&mut self) -> PResult<TokenTree> {
2505 // FIXME #6994: currently, this is too eager. It
2506 // parses token trees but also identifies TtSequence's
2507 // and token::SubstNt's; it's too early to know yet
2508 // whether something will be a nonterminal or a seq
2510 maybe_whole!(deref self, NtTT);
2512 // this is the fall-through for the 'match' below.
2513 // invariants: the current token is not a left-delimiter,
2514 // not an EOF, and not the desired right-delimiter (if
2515 // it were, parse_seq_to_before_end would have prevented
2516 // reaching this point.
2517 fn parse_non_delim_tt_tok(p: &mut Parser) -> PResult<TokenTree> {
2518 maybe_whole!(deref p, NtTT);
2520 token::CloseDelim(_) => {
2521 // This is a conservative error: only report the last unclosed delimiter. The
2522 // previous unclosed delimiters could actually be closed! The parser just hasn't
2523 // gotten to them yet.
2524 match p.open_braces.last() {
2526 Some(&sp) => p.span_note(sp, "unclosed delimiter"),
2528 let token_str = p.this_token_to_string();
2529 Err(p.fatal(&format!("incorrect close delimiter: `{}`",
2532 /* we ought to allow different depths of unquotation */
2533 token::Dollar | token::SubstNt(..) if p.quote_depth > 0 => {
2537 Ok(TtToken(p.span, try!(p.bump_and_get())))
2544 let open_braces = self.open_braces.clone();
2545 for sp in &open_braces {
2546 self.span_help(*sp, "did you mean to close this delimiter?");
2548 // There shouldn't really be a span, but it's easier for the test runner
2549 // if we give it one
2550 return Err(self.fatal("this file contains an un-closed delimiter "));
2552 token::OpenDelim(delim) => {
2553 // The span for beginning of the delimited section
2554 let pre_span = self.span;
2556 // Parse the open delimiter.
2557 self.open_braces.push(self.span);
2558 let open_span = self.span;
2561 // Parse the token trees within the delimiters
2562 let tts = try!(self.parse_seq_to_before_end(
2563 &token::CloseDelim(delim),
2565 |p| p.parse_token_tree()
2568 // Parse the close delimiter.
2569 let close_span = self.span;
2571 self.open_braces.pop().unwrap();
2573 // Expand to cover the entire delimited token tree
2574 let span = Span { hi: close_span.hi, ..pre_span };
2576 Ok(TtDelimited(span, Rc::new(Delimited {
2578 open_span: open_span,
2580 close_span: close_span,
2583 _ => parse_non_delim_tt_tok(self),
2587 // parse a stream of tokens into a list of TokenTree's,
2589 pub fn parse_all_token_trees(&mut self) -> PResult<Vec<TokenTree>> {
2590 let mut tts = Vec::new();
2591 while self.token != token::Eof {
2592 tts.push(try!(self.parse_token_tree()));
2597 /// Parse a prefix-operator expr
2598 pub fn parse_prefix_expr(&mut self) -> PResult<P<Expr>> {
2599 let lo = self.span.lo;
2602 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2607 let e = try!(self.parse_prefix_expr());
2609 ex = self.mk_unary(UnNot, e);
2611 token::BinOp(token::Minus) => {
2613 let e = try!(self.parse_prefix_expr());
2615 ex = self.mk_unary(UnNeg, e);
2617 token::BinOp(token::Star) => {
2619 let e = try!(self.parse_prefix_expr());
2621 ex = self.mk_unary(UnDeref, e);
2623 token::BinOp(token::And) | token::AndAnd => {
2624 try!(self.expect_and());
2625 let m = try!(self.parse_mutability());
2626 let e = try!(self.parse_prefix_expr());
2628 ex = ExprAddrOf(m, e);
2630 token::Ident(_, _) => {
2631 if !self.check_keyword(keywords::Box) && !self.check_keyword(keywords::In) {
2632 return self.parse_dot_or_call_expr();
2635 let lo = self.span.lo;
2636 let keyword_hi = self.span.hi;
2638 let is_in = self.token.is_keyword(keywords::In);
2642 let place = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL));
2643 let blk = try!(self.parse_block());
2645 let blk_expr = self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk));
2646 ex = ExprBox(Some(place), blk_expr);
2647 return Ok(self.mk_expr(lo, hi, ex));
2650 // FIXME (#22181) Remove `box (PLACE) EXPR` support
2651 // entirely after next release (enabling `(box (EXPR))`),
2652 // since it will be replaced by `in PLACE { EXPR }`, ...
2654 // ... but for now: check for a place: `box(PLACE) EXPR`.
2656 if try!(self.eat(&token::OpenDelim(token::Paren))) {
2657 let box_span = mk_sp(lo, self.last_span.hi);
2658 self.span_warn(box_span,
2659 "deprecated syntax; use the `in` keyword now \
2660 (e.g. change `box (<expr>) <expr>` to \
2661 `in <expr> { <expr> }`)");
2663 // Continue supporting `box () EXPR` (temporarily)
2664 if !try!(self.eat(&token::CloseDelim(token::Paren))) {
2665 let place = try!(self.parse_expr_nopanic());
2666 try!(self.expect(&token::CloseDelim(token::Paren)));
2667 // Give a suggestion to use `box()` when a parenthesised expression is used
2668 if !self.token.can_begin_expr() {
2669 let span = self.span;
2670 let this_token_to_string = self.this_token_to_string();
2672 &format!("expected expression, found `{}`",
2673 this_token_to_string));
2675 // Spanning just keyword avoids constructing
2676 // printout of arg expression (which starts
2677 // with parenthesis, as established above).
2679 let box_span = mk_sp(lo, keyword_hi);
2680 self.span_suggestion(box_span,
2681 "try using `box ()` instead:",
2683 self.abort_if_errors();
2685 let subexpression = try!(self.parse_prefix_expr());
2686 hi = subexpression.span.hi;
2687 ex = ExprBox(Some(place), subexpression);
2688 return Ok(self.mk_expr(lo, hi, ex));
2692 // Otherwise, we use the unique pointer default.
2693 let subexpression = try!(self.parse_prefix_expr());
2694 hi = subexpression.span.hi;
2696 // FIXME (pnkfelix): After working out kinks with box
2697 // desugaring, should be `ExprBox(None, subexpression)`
2699 ex = self.mk_unary(UnUniq, subexpression);
2701 _ => return self.parse_dot_or_call_expr()
2703 return Ok(self.mk_expr(lo, hi, ex));
2706 /// Parse an expression of binops
2707 pub fn parse_binops(&mut self) -> PResult<P<Expr>> {
2708 let prefix_expr = try!(self.parse_prefix_expr());
2709 self.parse_more_binops(prefix_expr, 0)
2712 /// Parse an expression of binops of at least min_prec precedence
2713 pub fn parse_more_binops(&mut self, lhs: P<Expr>, min_prec: usize) -> PResult<P<Expr>> {
2714 if self.expr_is_complete(&*lhs) { return Ok(lhs); }
2716 self.expected_tokens.push(TokenType::Operator);
2718 let cur_op_span = self.span;
2719 let cur_opt = self.token.to_binop();
2722 if ast_util::is_comparison_binop(cur_op) {
2723 self.check_no_chained_comparison(&*lhs, cur_op)
2725 let cur_prec = operator_prec(cur_op);
2726 if cur_prec >= min_prec {
2728 let expr = try!(self.parse_prefix_expr());
2729 let rhs = try!(self.parse_more_binops(expr, cur_prec + 1));
2730 let lhs_span = lhs.span;
2731 let rhs_span = rhs.span;
2732 let binary = self.mk_binary(codemap::respan(cur_op_span, cur_op), lhs, rhs);
2733 let bin = self.mk_expr(lhs_span.lo, rhs_span.hi, binary);
2734 self.parse_more_binops(bin, min_prec)
2740 if AS_PREC >= min_prec && try!(self.eat_keyword_noexpect(keywords::As) ){
2741 let rhs = try!(self.parse_ty_nopanic());
2742 let _as = self.mk_expr(lhs.span.lo,
2744 ExprCast(lhs, rhs));
2745 self.parse_more_binops(_as, min_prec)
2753 /// Produce an error if comparison operators are chained (RFC #558).
2754 /// We only need to check lhs, not rhs, because all comparison ops
2755 /// have same precedence and are left-associative
2756 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: ast::BinOp_) {
2757 debug_assert!(ast_util::is_comparison_binop(outer_op));
2759 ExprBinary(op, _, _) if ast_util::is_comparison_binop(op.node) => {
2760 // respan to include both operators
2761 let op_span = mk_sp(op.span.lo, self.span.hi);
2762 self.span_err(op_span,
2763 "chained comparison operators require parentheses");
2764 if op.node == BiLt && outer_op == BiGt {
2765 self.fileline_help(op_span,
2766 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
2773 /// Parse an assignment expression....
2774 /// actually, this seems to be the main entry point for
2775 /// parsing an arbitrary expression.
2776 pub fn parse_assign_expr(&mut self) -> PResult<P<Expr>> {
2779 // prefix-form of range notation '..expr'
2780 // This has the same precedence as assignment expressions
2781 // (much lower than other prefix expressions) to be consistent
2782 // with the postfix-form 'expr..'
2783 let lo = self.span.lo;
2784 let mut hi = self.span.hi;
2786 let opt_end = if self.is_at_start_of_range_notation_rhs() {
2787 let end = try!(self.parse_binops());
2793 let ex = self.mk_range(None, opt_end);
2794 Ok(self.mk_expr(lo, hi, ex))
2797 let lhs = try!(self.parse_binops());
2798 self.parse_assign_expr_with(lhs)
2803 pub fn parse_assign_expr_with(&mut self, lhs: P<Expr>) -> PResult<P<Expr>> {
2804 let restrictions = self.restrictions & Restrictions::RESTRICTION_NO_STRUCT_LITERAL;
2805 let op_span = self.span;
2809 let rhs = try!(self.parse_expr_res(restrictions));
2810 Ok(self.mk_expr(lhs.span.lo, rhs.span.hi, ExprAssign(lhs, rhs)))
2812 token::BinOpEq(op) => {
2814 let rhs = try!(self.parse_expr_res(restrictions));
2815 let aop = match op {
2816 token::Plus => BiAdd,
2817 token::Minus => BiSub,
2818 token::Star => BiMul,
2819 token::Slash => BiDiv,
2820 token::Percent => BiRem,
2821 token::Caret => BiBitXor,
2822 token::And => BiBitAnd,
2823 token::Or => BiBitOr,
2824 token::Shl => BiShl,
2827 let rhs_span = rhs.span;
2828 let span = lhs.span;
2829 let assign_op = self.mk_assign_op(codemap::respan(op_span, aop), lhs, rhs);
2830 Ok(self.mk_expr(span.lo, rhs_span.hi, assign_op))
2832 // A range expression, either `expr..expr` or `expr..`.
2834 let lo = lhs.span.lo;
2835 let mut hi = self.span.hi;
2838 let opt_end = if self.is_at_start_of_range_notation_rhs() {
2839 let end = try!(self.parse_binops());
2845 let range = self.mk_range(Some(lhs), opt_end);
2846 return Ok(self.mk_expr(lo, hi, range));
2855 fn is_at_start_of_range_notation_rhs(&self) -> bool {
2856 if self.token.can_begin_expr() {
2857 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
2858 if self.token == token::OpenDelim(token::Brace) {
2859 return !self.restrictions.contains(Restrictions::RESTRICTION_NO_STRUCT_LITERAL);
2867 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
2868 pub fn parse_if_expr(&mut self) -> PResult<P<Expr>> {
2869 if self.check_keyword(keywords::Let) {
2870 return self.parse_if_let_expr();
2872 let lo = self.last_span.lo;
2873 let cond = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL));
2874 let thn = try!(self.parse_block());
2875 let mut els: Option<P<Expr>> = None;
2876 let mut hi = thn.span.hi;
2877 if try!(self.eat_keyword(keywords::Else) ){
2878 let elexpr = try!(self.parse_else_expr());
2879 hi = elexpr.span.hi;
2882 Ok(self.mk_expr(lo, hi, ExprIf(cond, thn, els)))
2885 /// Parse an 'if let' expression ('if' token already eaten)
2886 pub fn parse_if_let_expr(&mut self) -> PResult<P<Expr>> {
2887 let lo = self.last_span.lo;
2888 try!(self.expect_keyword(keywords::Let));
2889 let pat = try!(self.parse_pat_nopanic());
2890 try!(self.expect(&token::Eq));
2891 let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL));
2892 let thn = try!(self.parse_block());
2893 let (hi, els) = if try!(self.eat_keyword(keywords::Else) ){
2894 let expr = try!(self.parse_else_expr());
2895 (expr.span.hi, Some(expr))
2899 Ok(self.mk_expr(lo, hi, ExprIfLet(pat, expr, thn, els)))
2903 pub fn parse_lambda_expr(&mut self, lo: BytePos, capture_clause: CaptureClause)
2906 let decl = try!(self.parse_fn_block_decl());
2907 let body = match decl.output {
2908 DefaultReturn(_) => {
2909 // If no explicit return type is given, parse any
2910 // expr and wrap it up in a dummy block:
2911 let body_expr = try!(self.parse_expr_nopanic());
2913 id: ast::DUMMY_NODE_ID,
2915 span: body_expr.span,
2916 expr: Some(body_expr),
2917 rules: DefaultBlock,
2921 // If an explicit return type is given, require a
2922 // block to appear (RFC 968).
2923 try!(self.parse_block())
2930 ExprClosure(capture_clause, decl, body)))
2933 pub fn parse_else_expr(&mut self) -> PResult<P<Expr>> {
2934 if try!(self.eat_keyword(keywords::If) ){
2935 return self.parse_if_expr();
2937 let blk = try!(self.parse_block());
2938 return Ok(self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk)));
2942 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
2943 pub fn parse_for_expr(&mut self, opt_ident: Option<ast::Ident>,
2944 span_lo: BytePos) -> PResult<P<Expr>> {
2945 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
2947 let pat = try!(self.parse_pat_nopanic());
2948 try!(self.expect_keyword(keywords::In));
2949 let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL));
2950 let loop_block = try!(self.parse_block());
2951 let hi = self.last_span.hi;
2953 Ok(self.mk_expr(span_lo, hi, ExprForLoop(pat, expr, loop_block, opt_ident)))
2956 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
2957 pub fn parse_while_expr(&mut self, opt_ident: Option<ast::Ident>,
2958 span_lo: BytePos) -> PResult<P<Expr>> {
2959 if self.token.is_keyword(keywords::Let) {
2960 return self.parse_while_let_expr(opt_ident, span_lo);
2962 let cond = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL));
2963 let body = try!(self.parse_block());
2964 let hi = body.span.hi;
2965 return Ok(self.mk_expr(span_lo, hi, ExprWhile(cond, body, opt_ident)));
2968 /// Parse a 'while let' expression ('while' token already eaten)
2969 pub fn parse_while_let_expr(&mut self, opt_ident: Option<ast::Ident>,
2970 span_lo: BytePos) -> PResult<P<Expr>> {
2971 try!(self.expect_keyword(keywords::Let));
2972 let pat = try!(self.parse_pat_nopanic());
2973 try!(self.expect(&token::Eq));
2974 let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL));
2975 let body = try!(self.parse_block());
2976 let hi = body.span.hi;
2977 return Ok(self.mk_expr(span_lo, hi, ExprWhileLet(pat, expr, body, opt_ident)));
2980 pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::Ident>,
2981 span_lo: BytePos) -> PResult<P<Expr>> {
2982 let body = try!(self.parse_block());
2983 let hi = body.span.hi;
2984 Ok(self.mk_expr(span_lo, hi, ExprLoop(body, opt_ident)))
2987 fn parse_match_expr(&mut self) -> PResult<P<Expr>> {
2988 let lo = self.last_span.lo;
2989 let discriminant = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL));
2990 try!(self.commit_expr_expecting(&*discriminant, token::OpenDelim(token::Brace)));
2991 let mut arms: Vec<Arm> = Vec::new();
2992 while self.token != token::CloseDelim(token::Brace) {
2993 arms.push(try!(self.parse_arm_nopanic()));
2995 let hi = self.span.hi;
2997 return Ok(self.mk_expr(lo, hi, ExprMatch(discriminant, arms, MatchSource::Normal)));
3000 pub fn parse_arm_nopanic(&mut self) -> PResult<Arm> {
3001 maybe_whole!(no_clone self, NtArm);
3003 let attrs = self.parse_outer_attributes();
3004 let pats = try!(self.parse_pats());
3005 let mut guard = None;
3006 if try!(self.eat_keyword(keywords::If) ){
3007 guard = Some(try!(self.parse_expr_nopanic()));
3009 try!(self.expect(&token::FatArrow));
3010 let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_STMT_EXPR));
3013 !classify::expr_is_simple_block(&*expr)
3014 && self.token != token::CloseDelim(token::Brace);
3017 try!(self.commit_expr(&*expr, &[token::Comma], &[token::CloseDelim(token::Brace)]));
3019 try!(self.eat(&token::Comma));
3030 /// Parse an expression
3031 pub fn parse_expr_nopanic(&mut self) -> PResult<P<Expr>> {
3032 self.parse_expr_res(Restrictions::empty())
3035 /// Parse an expression, subject to the given restrictions
3036 pub fn parse_expr_res(&mut self, r: Restrictions) -> PResult<P<Expr>> {
3037 let old = self.restrictions;
3038 self.restrictions = r;
3039 let e = try!(self.parse_assign_expr());
3040 self.restrictions = old;
3044 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3045 fn parse_initializer(&mut self) -> PResult<Option<P<Expr>>> {
3046 if self.check(&token::Eq) {
3048 Ok(Some(try!(self.parse_expr_nopanic())))
3054 /// Parse patterns, separated by '|' s
3055 fn parse_pats(&mut self) -> PResult<Vec<P<Pat>>> {
3056 let mut pats = Vec::new();
3058 pats.push(try!(self.parse_pat_nopanic()));
3059 if self.check(&token::BinOp(token::Or)) { try!(self.bump());}
3060 else { return Ok(pats); }
3064 fn parse_pat_tuple_elements(&mut self) -> PResult<Vec<P<Pat>>> {
3065 let mut fields = vec![];
3066 if !self.check(&token::CloseDelim(token::Paren)) {
3067 fields.push(try!(self.parse_pat_nopanic()));
3068 if self.look_ahead(1, |t| *t != token::CloseDelim(token::Paren)) {
3069 while try!(self.eat(&token::Comma)) &&
3070 !self.check(&token::CloseDelim(token::Paren)) {
3071 fields.push(try!(self.parse_pat_nopanic()));
3074 if fields.len() == 1 {
3075 try!(self.expect(&token::Comma));
3081 fn parse_pat_vec_elements(
3083 ) -> PResult<(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3084 let mut before = Vec::new();
3085 let mut slice = None;
3086 let mut after = Vec::new();
3087 let mut first = true;
3088 let mut before_slice = true;
3090 while self.token != token::CloseDelim(token::Bracket) {
3094 try!(self.expect(&token::Comma));
3096 if self.token == token::CloseDelim(token::Bracket)
3097 && (before_slice || !after.is_empty()) {
3103 if self.check(&token::DotDot) {
3106 if self.check(&token::Comma) ||
3107 self.check(&token::CloseDelim(token::Bracket)) {
3108 slice = Some(P(ast::Pat {
3109 id: ast::DUMMY_NODE_ID,
3110 node: PatWild(PatWildMulti),
3113 before_slice = false;
3119 let subpat = try!(self.parse_pat_nopanic());
3120 if before_slice && self.check(&token::DotDot) {
3122 slice = Some(subpat);
3123 before_slice = false;
3124 } else if before_slice {
3125 before.push(subpat);
3131 Ok((before, slice, after))
3134 /// Parse the fields of a struct-like pattern
3135 fn parse_pat_fields(&mut self) -> PResult<(Vec<codemap::Spanned<ast::FieldPat>> , bool)> {
3136 let mut fields = Vec::new();
3137 let mut etc = false;
3138 let mut first = true;
3139 while self.token != token::CloseDelim(token::Brace) {
3143 try!(self.expect(&token::Comma));
3144 // accept trailing commas
3145 if self.check(&token::CloseDelim(token::Brace)) { break }
3148 let lo = self.span.lo;
3151 if self.check(&token::DotDot) {
3153 if self.token != token::CloseDelim(token::Brace) {
3154 let token_str = self.this_token_to_string();
3155 return Err(self.fatal(&format!("expected `{}`, found `{}`", "}",
3162 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3163 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3164 // Parsing a pattern of the form "fieldname: pat"
3165 let fieldname = try!(self.parse_ident());
3167 let pat = try!(self.parse_pat_nopanic());
3169 (pat, fieldname, false)
3171 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3172 let is_box = try!(self.eat_keyword(keywords::Box));
3173 let boxed_span_lo = self.span.lo;
3174 let is_ref = try!(self.eat_keyword(keywords::Ref));
3175 let is_mut = try!(self.eat_keyword(keywords::Mut));
3176 let fieldname = try!(self.parse_ident());
3177 hi = self.last_span.hi;
3179 let bind_type = match (is_ref, is_mut) {
3180 (true, true) => BindByRef(MutMutable),
3181 (true, false) => BindByRef(MutImmutable),
3182 (false, true) => BindByValue(MutMutable),
3183 (false, false) => BindByValue(MutImmutable),
3185 let fieldpath = codemap::Spanned{span:self.last_span, node:fieldname};
3186 let fieldpat = P(ast::Pat{
3187 id: ast::DUMMY_NODE_ID,
3188 node: PatIdent(bind_type, fieldpath, None),
3189 span: mk_sp(boxed_span_lo, hi),
3192 let subpat = if is_box {
3194 id: ast::DUMMY_NODE_ID,
3195 node: PatBox(fieldpat),
3196 span: mk_sp(lo, hi),
3201 (subpat, fieldname, true)
3204 fields.push(codemap::Spanned { span: mk_sp(lo, hi),
3205 node: ast::FieldPat { ident: fieldname,
3207 is_shorthand: is_shorthand }});
3209 return Ok((fields, etc));
3212 fn parse_pat_range_end(&mut self) -> PResult<P<Expr>> {
3213 if self.is_path_start() {
3214 let lo = self.span.lo;
3215 let (qself, path) = if try!(self.eat_lt()) {
3216 // Parse a qualified path
3218 try!(self.parse_qualified_path(NoTypesAllowed));
3221 // Parse an unqualified path
3222 (None, try!(self.parse_path(LifetimeAndTypesWithColons)))
3224 let hi = self.last_span.hi;
3225 Ok(self.mk_expr(lo, hi, ExprPath(qself, path)))
3227 self.parse_literal_maybe_minus()
3231 fn is_path_start(&self) -> bool {
3232 (self.token == token::Lt || self.token == token::ModSep
3233 || self.token.is_ident() || self.token.is_path())
3234 && !self.token.is_keyword(keywords::True) && !self.token.is_keyword(keywords::False)
3237 /// Parse a pattern.
3238 pub fn parse_pat_nopanic(&mut self) -> PResult<P<Pat>> {
3239 maybe_whole!(self, NtPat);
3241 let lo = self.span.lo;
3244 token::Underscore => {
3247 pat = PatWild(PatWildSingle);
3249 token::BinOp(token::And) | token::AndAnd => {
3250 // Parse &pat / &mut pat
3251 try!(self.expect_and());
3252 let mutbl = try!(self.parse_mutability());
3253 let subpat = try!(self.parse_pat_nopanic());
3254 pat = PatRegion(subpat, mutbl);
3256 token::OpenDelim(token::Paren) => {
3257 // Parse (pat,pat,pat,...) as tuple pattern
3259 let fields = try!(self.parse_pat_tuple_elements());
3260 try!(self.expect(&token::CloseDelim(token::Paren)));
3261 pat = PatTup(fields);
3263 token::OpenDelim(token::Bracket) => {
3264 // Parse [pat,pat,...] as slice pattern
3266 let (before, slice, after) = try!(self.parse_pat_vec_elements());
3267 try!(self.expect(&token::CloseDelim(token::Bracket)));
3268 pat = PatVec(before, slice, after);
3271 // At this point, token != _, &, &&, (, [
3272 if try!(self.eat_keyword(keywords::Mut)) {
3273 // Parse mut ident @ pat
3274 pat = try!(self.parse_pat_ident(BindByValue(MutMutable)));
3275 } else if try!(self.eat_keyword(keywords::Ref)) {
3276 // Parse ref ident @ pat / ref mut ident @ pat
3277 let mutbl = try!(self.parse_mutability());
3278 pat = try!(self.parse_pat_ident(BindByRef(mutbl)));
3279 } else if try!(self.eat_keyword(keywords::Box)) {
3281 let subpat = try!(self.parse_pat_nopanic());
3282 pat = PatBox(subpat);
3283 } else if self.is_path_start() {
3284 // Parse pattern starting with a path
3285 if self.token.is_plain_ident() && self.look_ahead(1, |t| *t != token::DotDotDot &&
3286 *t != token::OpenDelim(token::Brace) &&
3287 *t != token::OpenDelim(token::Paren) &&
3288 // Contrary to its definition, a plain ident can be followed by :: in macros
3289 *t != token::ModSep) {
3290 // Plain idents have some extra abilities here compared to general paths
3291 if self.look_ahead(1, |t| *t == token::Not) {
3292 // Parse macro invocation
3293 let ident = try!(self.parse_ident());
3294 let ident_span = self.last_span;
3295 let path = ident_to_path(ident_span, ident);
3297 let delim = try!(self.expect_open_delim());
3298 let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
3299 seq_sep_none(), |p| p.parse_token_tree()));
3300 let mac = MacInvocTT(path, tts, EMPTY_CTXT);
3301 pat = PatMac(codemap::Spanned {node: mac, span: self.span});
3303 // Parse ident @ pat
3304 // This can give false positives and parse nullary enums,
3305 // they are dealt with later in resolve
3306 pat = try!(self.parse_pat_ident(BindByValue(MutImmutable)));
3309 let (qself, path) = if try!(self.eat_lt()) {
3310 // Parse a qualified path
3312 try!(self.parse_qualified_path(NoTypesAllowed));
3315 // Parse an unqualified path
3316 (None, try!(self.parse_path(LifetimeAndTypesWithColons)))
3319 token::DotDotDot => {
3321 let hi = self.last_span.hi;
3322 let begin = self.mk_expr(lo, hi, ExprPath(qself, path));
3324 let end = try!(self.parse_pat_range_end());
3325 pat = PatRange(begin, end);
3327 token::OpenDelim(token::Brace) => {
3328 if qself.is_some() {
3329 let span = self.span;
3331 "unexpected `{` after qualified path");
3332 self.abort_if_errors();
3334 // Parse struct pattern
3336 let (fields, etc) = try!(self.parse_pat_fields());
3338 pat = PatStruct(path, fields, etc);
3340 token::OpenDelim(token::Paren) => {
3341 if qself.is_some() {
3342 let span = self.span;
3344 "unexpected `(` after qualified path");
3345 self.abort_if_errors();
3347 // Parse tuple struct or enum pattern
3348 if self.look_ahead(1, |t| *t == token::DotDot) {
3349 // This is a "top constructor only" pat
3352 try!(self.expect(&token::CloseDelim(token::Paren)));
3353 pat = PatEnum(path, None);
3355 let args = try!(self.parse_enum_variant_seq(
3356 &token::OpenDelim(token::Paren),
3357 &token::CloseDelim(token::Paren),
3358 seq_sep_trailing_allowed(token::Comma),
3359 |p| p.parse_pat_nopanic()));
3360 pat = PatEnum(path, Some(args));
3363 _ if qself.is_some() => {
3364 // Parse qualified path
3365 pat = PatQPath(qself.unwrap(), path);
3368 // Parse nullary enum
3369 pat = PatEnum(path, Some(vec![]));
3374 // Try to parse everything else as literal with optional minus
3375 let begin = try!(self.parse_literal_maybe_minus());
3376 if try!(self.eat(&token::DotDotDot)) {
3377 let end = try!(self.parse_pat_range_end());
3378 pat = PatRange(begin, end);
3380 pat = PatLit(begin);
3386 let hi = self.last_span.hi;
3388 id: ast::DUMMY_NODE_ID,
3390 span: mk_sp(lo, hi),
3394 /// Parse ident or ident @ pat
3395 /// used by the copy foo and ref foo patterns to give a good
3396 /// error message when parsing mistakes like ref foo(a,b)
3397 fn parse_pat_ident(&mut self,
3398 binding_mode: ast::BindingMode)
3399 -> PResult<ast::Pat_> {
3400 if !self.token.is_plain_ident() {
3401 let span = self.span;
3402 let tok_str = self.this_token_to_string();
3403 return Err(self.span_fatal(span,
3404 &format!("expected identifier, found `{}`", tok_str)))
3406 let ident = try!(self.parse_ident());
3407 let last_span = self.last_span;
3408 let name = codemap::Spanned{span: last_span, node: ident};
3409 let sub = if try!(self.eat(&token::At) ){
3410 Some(try!(self.parse_pat_nopanic()))
3415 // just to be friendly, if they write something like
3417 // we end up here with ( as the current token. This shortly
3418 // leads to a parse error. Note that if there is no explicit
3419 // binding mode then we do not end up here, because the lookahead
3420 // will direct us over to parse_enum_variant()
3421 if self.token == token::OpenDelim(token::Paren) {
3422 let last_span = self.last_span;
3423 return Err(self.span_fatal(
3425 "expected identifier, found enum pattern"))
3428 Ok(PatIdent(binding_mode, name, sub))
3431 /// Parse a local variable declaration
3432 fn parse_local(&mut self) -> PResult<P<Local>> {
3433 let lo = self.span.lo;
3434 let pat = try!(self.parse_pat_nopanic());
3437 if try!(self.eat(&token::Colon) ){
3438 ty = Some(try!(self.parse_ty_sum()));
3440 let init = try!(self.parse_initializer());
3445 id: ast::DUMMY_NODE_ID,
3446 span: mk_sp(lo, self.last_span.hi),
3450 /// Parse a "let" stmt
3451 fn parse_let(&mut self) -> PResult<P<Decl>> {
3452 let lo = self.span.lo;
3453 let local = try!(self.parse_local());
3454 Ok(P(spanned(lo, self.last_span.hi, DeclLocal(local))))
3457 /// Parse a structure field
3458 fn parse_name_and_ty(&mut self, pr: Visibility,
3459 attrs: Vec<Attribute> ) -> PResult<StructField> {
3461 Inherited => self.span.lo,
3462 Public => self.last_span.lo,
3464 if !self.token.is_plain_ident() {
3465 return Err(self.fatal("expected ident"));
3467 let name = try!(self.parse_ident());
3468 try!(self.expect(&token::Colon));
3469 let ty = try!(self.parse_ty_sum());
3470 Ok(spanned(lo, self.last_span.hi, ast::StructField_ {
3471 kind: NamedField(name, pr),
3472 id: ast::DUMMY_NODE_ID,
3478 /// Emit an expected item after attributes error.
3479 fn expected_item_err(&self, attrs: &[Attribute]) {
3480 let message = match attrs.last() {
3481 Some(&Attribute { node: ast::Attribute_ { is_sugared_doc: true, .. }, .. }) => {
3482 "expected item after doc comment"
3484 _ => "expected item after attributes",
3487 self.span_err(self.last_span, message);
3490 /// Parse a statement. may include decl.
3491 pub fn parse_stmt_nopanic(&mut self) -> PResult<Option<P<Stmt>>> {
3492 Ok(try!(self.parse_stmt_()).map(P))
3495 fn parse_stmt_(&mut self) -> PResult<Option<Stmt>> {
3496 maybe_whole!(Some deref self, NtStmt);
3498 fn check_expected_item(p: &mut Parser, attrs: &[Attribute]) {
3499 // If we have attributes then we should have an item
3500 if !attrs.is_empty() {
3501 p.expected_item_err(attrs);
3505 let attrs = self.parse_outer_attributes();
3506 let lo = self.span.lo;
3508 Ok(Some(if self.check_keyword(keywords::Let) {
3509 check_expected_item(self, &attrs);
3510 try!(self.expect_keyword(keywords::Let));
3511 let decl = try!(self.parse_let());
3512 spanned(lo, decl.span.hi, StmtDecl(decl, ast::DUMMY_NODE_ID))
3513 } else if self.token.is_ident()
3514 && !self.token.is_any_keyword()
3515 && self.look_ahead(1, |t| *t == token::Not) {
3516 // it's a macro invocation:
3518 check_expected_item(self, &attrs);
3520 // Potential trouble: if we allow macros with paths instead of
3521 // idents, we'd need to look ahead past the whole path here...
3522 let pth = try!(self.parse_path(NoTypesAllowed));
3525 let id = match self.token {
3526 token::OpenDelim(_) => token::special_idents::invalid, // no special identifier
3527 _ => try!(self.parse_ident()),
3530 // check that we're pointing at delimiters (need to check
3531 // again after the `if`, because of `parse_ident`
3532 // consuming more tokens).
3533 let delim = match self.token {
3534 token::OpenDelim(delim) => delim,
3536 // we only expect an ident if we didn't parse one
3538 let ident_str = if id.name == token::special_idents::invalid.name {
3543 let tok_str = self.this_token_to_string();
3544 return Err(self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
3550 let tts = try!(self.parse_unspanned_seq(
3551 &token::OpenDelim(delim),
3552 &token::CloseDelim(delim),
3554 |p| p.parse_token_tree()
3556 let hi = self.last_span.hi;
3558 let style = if delim == token::Brace {
3561 MacStmtWithoutBraces
3564 if id.name == token::special_idents::invalid.name {
3566 StmtMac(P(spanned(lo,
3568 MacInvocTT(pth, tts, EMPTY_CTXT))),
3571 // if it has a special ident, it's definitely an item
3573 // Require a semicolon or braces.
3574 if style != MacStmtWithBraces {
3575 if !try!(self.eat(&token::Semi) ){
3576 let last_span = self.last_span;
3577 self.span_err(last_span,
3578 "macros that expand to items must \
3579 either be surrounded with braces or \
3580 followed by a semicolon");
3583 spanned(lo, hi, StmtDecl(
3584 P(spanned(lo, hi, DeclItem(
3586 lo, hi, id /*id is good here*/,
3587 ItemMac(spanned(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT))),
3588 Inherited, Vec::new(/*no attrs*/))))),
3589 ast::DUMMY_NODE_ID))
3592 match try!(self.parse_item_(attrs, false)) {
3595 let decl = P(spanned(lo, hi, DeclItem(i)));
3596 spanned(lo, hi, StmtDecl(decl, ast::DUMMY_NODE_ID))
3599 // Do not attempt to parse an expression if we're done here.
3600 if self.token == token::Semi {
3605 if self.token == token::CloseDelim(token::Brace) {
3609 // Remainder are line-expr stmts.
3610 let e = try!(self.parse_expr_res(Restrictions::RESTRICTION_STMT_EXPR));
3611 spanned(lo, e.span.hi, StmtExpr(e, ast::DUMMY_NODE_ID))
3617 /// Is this expression a successfully-parsed statement?
3618 fn expr_is_complete(&mut self, e: &Expr) -> bool {
3619 self.restrictions.contains(Restrictions::RESTRICTION_STMT_EXPR) &&
3620 !classify::expr_requires_semi_to_be_stmt(e)
3623 /// Parse a block. No inner attrs are allowed.
3624 pub fn parse_block(&mut self) -> PResult<P<Block>> {
3625 maybe_whole!(no_clone self, NtBlock);
3627 let lo = self.span.lo;
3629 if !try!(self.eat(&token::OpenDelim(token::Brace)) ){
3631 let tok = self.this_token_to_string();
3632 return Err(self.span_fatal_help(sp,
3633 &format!("expected `{{`, found `{}`", tok),
3634 "place this code inside a block"));
3637 self.parse_block_tail(lo, DefaultBlock)
3640 /// Parse a block. Inner attrs are allowed.
3641 fn parse_inner_attrs_and_block(&mut self) -> PResult<(Vec<Attribute>, P<Block>)> {
3642 maybe_whole!(pair_empty self, NtBlock);
3644 let lo = self.span.lo;
3645 try!(self.expect(&token::OpenDelim(token::Brace)));
3646 Ok((self.parse_inner_attributes(),
3647 try!(self.parse_block_tail(lo, DefaultBlock))))
3650 /// Parse the rest of a block expression or function body
3651 /// Precondition: already parsed the '{'.
3652 fn parse_block_tail(&mut self, lo: BytePos, s: BlockCheckMode) -> PResult<P<Block>> {
3653 let mut stmts = vec![];
3654 let mut expr = None;
3656 while !try!(self.eat(&token::CloseDelim(token::Brace))) {
3657 let Spanned {node, span} = if let Some(s) = try!(self.parse_stmt_()) {
3660 // Found only `;` or `}`.
3665 try!(self.handle_expression_like_statement(e, span, &mut stmts, &mut expr));
3667 StmtMac(mac, MacStmtWithoutBraces) => {
3668 // statement macro without braces; might be an
3669 // expr depending on whether a semicolon follows
3672 stmts.push(P(Spanned {
3673 node: StmtMac(mac, MacStmtWithSemicolon),
3674 span: mk_sp(span.lo, self.span.hi),
3679 let e = self.mk_mac_expr(span.lo, span.hi,
3680 mac.and_then(|m| m.node));
3681 let e = try!(self.parse_dot_or_call_expr_with(e));
3682 let e = try!(self.parse_more_binops(e, 0));
3683 let e = try!(self.parse_assign_expr_with(e));
3684 try!(self.handle_expression_like_statement(
3692 StmtMac(m, style) => {
3693 // statement macro; might be an expr
3696 stmts.push(P(Spanned {
3697 node: StmtMac(m, MacStmtWithSemicolon),
3698 span: mk_sp(span.lo, self.span.hi),
3702 token::CloseDelim(token::Brace) => {
3703 // if a block ends in `m!(arg)` without
3704 // a `;`, it must be an expr
3705 expr = Some(self.mk_mac_expr(span.lo, span.hi,
3706 m.and_then(|x| x.node)));
3709 stmts.push(P(Spanned {
3710 node: StmtMac(m, style),
3716 _ => { // all other kinds of statements:
3717 let mut hi = span.hi;
3718 if classify::stmt_ends_with_semi(&node) {
3719 try!(self.commit_stmt_expecting(token::Semi));
3720 hi = self.last_span.hi;
3723 stmts.push(P(Spanned {
3725 span: mk_sp(span.lo, hi)
3734 id: ast::DUMMY_NODE_ID,
3736 span: mk_sp(lo, self.last_span.hi),
3740 fn handle_expression_like_statement(
3744 stmts: &mut Vec<P<Stmt>>,
3745 last_block_expr: &mut Option<P<Expr>>) -> PResult<()> {
3746 // expression without semicolon
3747 if classify::expr_requires_semi_to_be_stmt(&*e) {
3748 // Just check for errors and recover; do not eat semicolon yet.
3749 try!(self.commit_stmt(&[],
3750 &[token::Semi, token::CloseDelim(token::Brace)]));
3756 let span_with_semi = Span {
3758 hi: self.last_span.hi,
3759 expn_id: span.expn_id,
3761 stmts.push(P(Spanned {
3762 node: StmtSemi(e, ast::DUMMY_NODE_ID),
3763 span: span_with_semi,
3766 token::CloseDelim(token::Brace) => *last_block_expr = Some(e),
3768 stmts.push(P(Spanned {
3769 node: StmtExpr(e, ast::DUMMY_NODE_ID),
3777 // Parses a sequence of bounds if a `:` is found,
3778 // otherwise returns empty list.
3779 fn parse_colon_then_ty_param_bounds(&mut self,
3780 mode: BoundParsingMode)
3781 -> PResult<OwnedSlice<TyParamBound>>
3783 if !try!(self.eat(&token::Colon) ){
3784 Ok(OwnedSlice::empty())
3786 self.parse_ty_param_bounds(mode)
3790 // matches bounds = ( boundseq )?
3791 // where boundseq = ( polybound + boundseq ) | polybound
3792 // and polybound = ( 'for' '<' 'region '>' )? bound
3793 // and bound = 'region | trait_ref
3794 fn parse_ty_param_bounds(&mut self,
3795 mode: BoundParsingMode)
3796 -> PResult<OwnedSlice<TyParamBound>>
3798 let mut result = vec!();
3800 let question_span = self.span;
3801 let ate_question = try!(self.eat(&token::Question));
3803 token::Lifetime(lifetime) => {
3805 self.span_err(question_span,
3806 "`?` may only modify trait bounds, not lifetime bounds");
3808 result.push(RegionTyParamBound(ast::Lifetime {
3809 id: ast::DUMMY_NODE_ID,
3815 token::ModSep | token::Ident(..) => {
3816 let poly_trait_ref = try!(self.parse_poly_trait_ref());
3817 let modifier = if ate_question {
3818 if mode == BoundParsingMode::Modified {
3819 TraitBoundModifier::Maybe
3821 self.span_err(question_span,
3823 TraitBoundModifier::None
3826 TraitBoundModifier::None
3828 result.push(TraitTyParamBound(poly_trait_ref, modifier))
3833 if !try!(self.eat(&token::BinOp(token::Plus)) ){
3838 return Ok(OwnedSlice::from_vec(result));
3841 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
3842 fn parse_ty_param(&mut self) -> PResult<TyParam> {
3843 let span = self.span;
3844 let ident = try!(self.parse_ident());
3846 let bounds = try!(self.parse_colon_then_ty_param_bounds(BoundParsingMode::Modified));
3848 let default = if self.check(&token::Eq) {
3850 Some(try!(self.parse_ty_sum()))
3857 id: ast::DUMMY_NODE_ID,
3864 /// Parse a set of optional generic type parameter declarations. Where
3865 /// clauses are not parsed here, and must be added later via
3866 /// `parse_where_clause()`.
3868 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
3869 /// | ( < lifetimes , typaramseq ( , )? > )
3870 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
3871 pub fn parse_generics(&mut self) -> PResult<ast::Generics> {
3872 maybe_whole!(self, NtGenerics);
3874 if try!(self.eat(&token::Lt) ){
3875 let lifetime_defs = try!(self.parse_lifetime_defs());
3876 let mut seen_default = false;
3877 let ty_params = try!(self.parse_seq_to_gt(Some(token::Comma), |p| {
3878 try!(p.forbid_lifetime());
3879 let ty_param = try!(p.parse_ty_param());
3880 if ty_param.default.is_some() {
3881 seen_default = true;
3882 } else if seen_default {
3883 let last_span = p.last_span;
3884 p.span_err(last_span,
3885 "type parameters with a default must be trailing");
3890 lifetimes: lifetime_defs,
3891 ty_params: ty_params,
3892 where_clause: WhereClause {
3893 id: ast::DUMMY_NODE_ID,
3894 predicates: Vec::new(),
3898 Ok(ast_util::empty_generics())
3902 fn parse_generic_values_after_lt(&mut self) -> PResult<(Vec<ast::Lifetime>,
3904 Vec<P<TypeBinding>>)> {
3905 let span_lo = self.span.lo;
3906 let lifetimes = try!(self.parse_lifetimes(token::Comma));
3908 let missing_comma = !lifetimes.is_empty() &&
3909 !self.token.is_like_gt() &&
3911 .as_ref().map_or(true,
3912 |x| &**x != &token::Comma);
3916 let msg = format!("expected `,` or `>` after lifetime \
3918 self.this_token_to_string());
3919 self.span_err(self.span, &msg);
3921 let span_hi = self.span.hi;
3922 let span_hi = if self.parse_ty_nopanic().is_ok() {
3928 let msg = format!("did you mean a single argument type &'a Type, \
3929 or did you mean the comma-separated arguments \
3931 self.span_note(mk_sp(span_lo, span_hi), &msg);
3933 self.abort_if_errors()
3936 // First parse types.
3937 let (types, returned) = try!(self.parse_seq_to_gt_or_return(
3940 try!(p.forbid_lifetime());
3941 if p.look_ahead(1, |t| t == &token::Eq) {
3944 Ok(Some(try!(p.parse_ty_sum())))
3949 // If we found the `>`, don't continue.
3951 return Ok((lifetimes, types.into_vec(), Vec::new()));
3954 // Then parse type bindings.
3955 let bindings = try!(self.parse_seq_to_gt(
3958 try!(p.forbid_lifetime());
3960 let ident = try!(p.parse_ident());
3961 let found_eq = try!(p.eat(&token::Eq));
3964 p.span_warn(span, "whoops, no =?");
3966 let ty = try!(p.parse_ty_nopanic());
3967 let hi = ty.span.hi;
3968 let span = mk_sp(lo, hi);
3969 return Ok(P(TypeBinding{id: ast::DUMMY_NODE_ID,
3976 Ok((lifetimes, types.into_vec(), bindings.into_vec()))
3979 fn forbid_lifetime(&mut self) -> PResult<()> {
3980 if self.token.is_lifetime() {
3981 let span = self.span;
3982 return Err(self.span_fatal(span, "lifetime parameters must be declared \
3983 prior to type parameters"))
3988 /// Parses an optional `where` clause and places it in `generics`.
3991 /// where T : Trait<U, V> + 'b, 'a : 'b
3993 pub fn parse_where_clause(&mut self) -> PResult<ast::WhereClause> {
3994 maybe_whole!(self, NtWhereClause);
3996 let mut where_clause = WhereClause {
3997 id: ast::DUMMY_NODE_ID,
3998 predicates: Vec::new(),
4001 if !try!(self.eat_keyword(keywords::Where)) {
4002 return Ok(where_clause);
4005 let mut parsed_something = false;
4007 let lo = self.span.lo;
4009 token::OpenDelim(token::Brace) => {
4013 token::Lifetime(..) => {
4014 let bounded_lifetime =
4015 try!(self.parse_lifetime());
4017 try!(self.eat(&token::Colon));
4020 try!(self.parse_lifetimes(token::BinOp(token::Plus)));
4022 let hi = self.last_span.hi;
4023 let span = mk_sp(lo, hi);
4025 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
4026 ast::WhereRegionPredicate {
4028 lifetime: bounded_lifetime,
4033 parsed_something = true;
4037 let bound_lifetimes = if try!(self.eat_keyword(keywords::For) ){
4038 // Higher ranked constraint.
4039 try!(self.expect(&token::Lt));
4040 let lifetime_defs = try!(self.parse_lifetime_defs());
4041 try!(self.expect_gt());
4047 let bounded_ty = try!(self.parse_ty_nopanic());
4049 if try!(self.eat(&token::Colon) ){
4050 let bounds = try!(self.parse_ty_param_bounds(BoundParsingMode::Bare));
4051 let hi = self.last_span.hi;
4052 let span = mk_sp(lo, hi);
4054 if bounds.is_empty() {
4056 "each predicate in a `where` clause must have \
4057 at least one bound in it");
4060 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
4061 ast::WhereBoundPredicate {
4063 bound_lifetimes: bound_lifetimes,
4064 bounded_ty: bounded_ty,
4068 parsed_something = true;
4069 } else if try!(self.eat(&token::Eq) ){
4070 // let ty = try!(self.parse_ty_nopanic());
4071 let hi = self.last_span.hi;
4072 let span = mk_sp(lo, hi);
4073 // where_clause.predicates.push(
4074 // ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
4075 // id: ast::DUMMY_NODE_ID,
4077 // path: panic!("NYI"), //bounded_ty,
4080 // parsed_something = true;
4083 "equality constraints are not yet supported \
4084 in where clauses (#20041)");
4086 let last_span = self.last_span;
4087 self.span_err(last_span,
4088 "unexpected token in `where` clause");
4093 if !try!(self.eat(&token::Comma) ){
4098 if !parsed_something {
4099 let last_span = self.last_span;
4100 self.span_err(last_span,
4101 "a `where` clause must have at least one predicate \
4108 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
4109 -> PResult<(Vec<Arg> , bool)> {
4111 let mut args: Vec<Option<Arg>> =
4112 try!(self.parse_unspanned_seq(
4113 &token::OpenDelim(token::Paren),
4114 &token::CloseDelim(token::Paren),
4115 seq_sep_trailing_allowed(token::Comma),
4117 if p.token == token::DotDotDot {
4120 if p.token != token::CloseDelim(token::Paren) {
4122 return Err(p.span_fatal(span,
4123 "`...` must be last in argument list for variadic function"))
4127 return Err(p.span_fatal(span,
4128 "only foreign functions are allowed to be variadic"))
4132 Ok(Some(try!(p.parse_arg_general(named_args))))
4137 let variadic = match args.pop() {
4140 // Need to put back that last arg
4147 if variadic && args.is_empty() {
4149 "variadic function must be declared with at least one named argument");
4152 let args = args.into_iter().map(|x| x.unwrap()).collect();
4154 Ok((args, variadic))
4157 /// Parse the argument list and result type of a function declaration
4158 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<P<FnDecl>> {
4160 let (args, variadic) = try!(self.parse_fn_args(true, allow_variadic));
4161 let ret_ty = try!(self.parse_ret_ty());
4170 fn is_self_ident(&mut self) -> bool {
4172 token::Ident(id, token::Plain) => id.name == special_idents::self_.name,
4177 fn expect_self_ident(&mut self) -> PResult<ast::Ident> {
4179 token::Ident(id, token::Plain) if id.name == special_idents::self_.name => {
4184 let token_str = self.this_token_to_string();
4185 return Err(self.fatal(&format!("expected `self`, found `{}`",
4191 fn is_self_type_ident(&mut self) -> bool {
4193 token::Ident(id, token::Plain) => id.name == special_idents::type_self.name,
4198 fn expect_self_type_ident(&mut self) -> PResult<ast::Ident> {
4200 token::Ident(id, token::Plain) if id.name == special_idents::type_self.name => {
4205 let token_str = self.this_token_to_string();
4206 Err(self.fatal(&format!("expected `Self`, found `{}`",
4212 /// Parse the argument list and result type of a function
4213 /// that may have a self type.
4214 fn parse_fn_decl_with_self<F>(&mut self,
4215 parse_arg_fn: F) -> PResult<(ExplicitSelf, P<FnDecl>)> where
4216 F: FnMut(&mut Parser) -> PResult<Arg>,
4218 fn maybe_parse_borrowed_explicit_self(this: &mut Parser)
4219 -> PResult<ast::ExplicitSelf_> {
4220 // The following things are possible to see here:
4225 // fn(&'lt mut self)
4227 // We already know that the current token is `&`.
4229 if this.look_ahead(1, |t| t.is_keyword(keywords::SelfValue)) {
4231 Ok(SelfRegion(None, MutImmutable, try!(this.expect_self_ident())))
4232 } else if this.look_ahead(1, |t| t.is_mutability()) &&
4233 this.look_ahead(2, |t| t.is_keyword(keywords::SelfValue)) {
4235 let mutability = try!(this.parse_mutability());
4236 Ok(SelfRegion(None, mutability, try!(this.expect_self_ident())))
4237 } else if this.look_ahead(1, |t| t.is_lifetime()) &&
4238 this.look_ahead(2, |t| t.is_keyword(keywords::SelfValue)) {
4240 let lifetime = try!(this.parse_lifetime());
4241 Ok(SelfRegion(Some(lifetime), MutImmutable, try!(this.expect_self_ident())))
4242 } else if this.look_ahead(1, |t| t.is_lifetime()) &&
4243 this.look_ahead(2, |t| t.is_mutability()) &&
4244 this.look_ahead(3, |t| t.is_keyword(keywords::SelfValue)) {
4246 let lifetime = try!(this.parse_lifetime());
4247 let mutability = try!(this.parse_mutability());
4248 Ok(SelfRegion(Some(lifetime), mutability, try!(this.expect_self_ident())))
4254 try!(self.expect(&token::OpenDelim(token::Paren)));
4256 // A bit of complexity and lookahead is needed here in order to be
4257 // backwards compatible.
4258 let lo = self.span.lo;
4259 let mut self_ident_lo = self.span.lo;
4260 let mut self_ident_hi = self.span.hi;
4262 let mut mutbl_self = MutImmutable;
4263 let explicit_self = match self.token {
4264 token::BinOp(token::And) => {
4265 let eself = try!(maybe_parse_borrowed_explicit_self(self));
4266 self_ident_lo = self.last_span.lo;
4267 self_ident_hi = self.last_span.hi;
4270 token::BinOp(token::Star) => {
4271 // Possibly "*self" or "*mut self" -- not supported. Try to avoid
4272 // emitting cryptic "unexpected token" errors.
4274 let _mutability = if self.token.is_mutability() {
4275 try!(self.parse_mutability())
4279 if self.is_self_ident() {
4280 let span = self.span;
4281 self.span_err(span, "cannot pass self by raw pointer");
4284 // error case, making bogus self ident:
4285 SelfValue(special_idents::self_)
4287 token::Ident(..) => {
4288 if self.is_self_ident() {
4289 let self_ident = try!(self.expect_self_ident());
4291 // Determine whether this is the fully explicit form, `self:
4293 if try!(self.eat(&token::Colon) ){
4294 SelfExplicit(try!(self.parse_ty_sum()), self_ident)
4296 SelfValue(self_ident)
4298 } else if self.token.is_mutability() &&
4299 self.look_ahead(1, |t| t.is_keyword(keywords::SelfValue)) {
4300 mutbl_self = try!(self.parse_mutability());
4301 let self_ident = try!(self.expect_self_ident());
4303 // Determine whether this is the fully explicit form,
4305 if try!(self.eat(&token::Colon) ){
4306 SelfExplicit(try!(self.parse_ty_sum()), self_ident)
4308 SelfValue(self_ident)
4317 let explicit_self_sp = mk_sp(self_ident_lo, self_ident_hi);
4319 // shared fall-through for the three cases below. borrowing prevents simply
4320 // writing this as a closure
4321 macro_rules! parse_remaining_arguments {
4324 // If we parsed a self type, expect a comma before the argument list.
4328 let sep = seq_sep_trailing_allowed(token::Comma);
4329 let mut fn_inputs = try!(self.parse_seq_to_before_end(
4330 &token::CloseDelim(token::Paren),
4334 fn_inputs.insert(0, Arg::new_self(explicit_self_sp, mutbl_self, $self_id));
4337 token::CloseDelim(token::Paren) => {
4338 vec!(Arg::new_self(explicit_self_sp, mutbl_self, $self_id))
4341 let token_str = self.this_token_to_string();
4342 return Err(self.fatal(&format!("expected `,` or `)`, found `{}`",
4349 let fn_inputs = match explicit_self {
4351 let sep = seq_sep_trailing_allowed(token::Comma);
4352 try!(self.parse_seq_to_before_end(&token::CloseDelim(token::Paren),
4355 SelfValue(id) => parse_remaining_arguments!(id),
4356 SelfRegion(_,_,id) => parse_remaining_arguments!(id),
4357 SelfExplicit(_,id) => parse_remaining_arguments!(id),
4361 try!(self.expect(&token::CloseDelim(token::Paren)));
4363 let hi = self.span.hi;
4365 let ret_ty = try!(self.parse_ret_ty());
4367 let fn_decl = P(FnDecl {
4373 Ok((spanned(lo, hi, explicit_self), fn_decl))
4376 // parse the |arg, arg| header on a lambda
4377 fn parse_fn_block_decl(&mut self) -> PResult<P<FnDecl>> {
4378 let inputs_captures = {
4379 if try!(self.eat(&token::OrOr) ){
4382 try!(self.expect(&token::BinOp(token::Or)));
4383 try!(self.parse_obsolete_closure_kind());
4384 let args = try!(self.parse_seq_to_before_end(
4385 &token::BinOp(token::Or),
4386 seq_sep_trailing_allowed(token::Comma),
4387 |p| p.parse_fn_block_arg()
4393 let output = try!(self.parse_ret_ty());
4396 inputs: inputs_captures,
4402 /// Parse the name and optional generic types of a function header.
4403 fn parse_fn_header(&mut self) -> PResult<(Ident, ast::Generics)> {
4404 let id = try!(self.parse_ident());
4405 let generics = try!(self.parse_generics());
4409 fn mk_item(&mut self, lo: BytePos, hi: BytePos, ident: Ident,
4410 node: Item_, vis: Visibility,
4411 attrs: Vec<Attribute>) -> P<Item> {
4415 id: ast::DUMMY_NODE_ID,
4422 /// Parse an item-position function declaration.
4423 fn parse_item_fn(&mut self,
4425 constness: Constness,
4427 -> PResult<ItemInfo> {
4428 let (ident, mut generics) = try!(self.parse_fn_header());
4429 let decl = try!(self.parse_fn_decl(false));
4430 generics.where_clause = try!(self.parse_where_clause());
4431 let (inner_attrs, body) = try!(self.parse_inner_attrs_and_block());
4432 Ok((ident, ItemFn(decl, unsafety, constness, abi, generics, body), Some(inner_attrs)))
4435 /// true if we are looking at `const ID`, false for things like `const fn` etc
4436 pub fn is_const_item(&mut self) -> bool {
4437 self.token.is_keyword(keywords::Const) &&
4438 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn))
4441 /// parses all the "front matter" for a `fn` declaration, up to
4442 /// and including the `fn` keyword:
4448 pub fn parse_fn_front_matter(&mut self) -> PResult<(ast::Constness, ast::Unsafety, abi::Abi)> {
4449 let is_const_fn = try!(self.eat_keyword(keywords::Const));
4450 let (constness, unsafety, abi) = if is_const_fn {
4451 (Constness::Const, Unsafety::Normal, abi::Rust)
4453 let unsafety = try!(self.parse_unsafety());
4454 let abi = if try!(self.eat_keyword(keywords::Extern)) {
4455 try!(self.parse_opt_abi()).unwrap_or(abi::C)
4459 (Constness::NotConst, unsafety, abi)
4461 try!(self.expect_keyword(keywords::Fn));
4462 Ok((constness, unsafety, abi))
4465 /// Parse an impl item.
4466 pub fn parse_impl_item(&mut self) -> PResult<P<ImplItem>> {
4467 maybe_whole!(no_clone self, NtImplItem);
4469 let mut attrs = self.parse_outer_attributes();
4470 let lo = self.span.lo;
4471 let vis = try!(self.parse_visibility());
4472 let (name, node) = if try!(self.eat_keyword(keywords::Type)) {
4473 let name = try!(self.parse_ident());
4474 try!(self.expect(&token::Eq));
4475 let typ = try!(self.parse_ty_sum());
4476 try!(self.expect(&token::Semi));
4477 (name, TypeImplItem(typ))
4478 } else if self.is_const_item() {
4479 try!(self.expect_keyword(keywords::Const));
4480 let name = try!(self.parse_ident());
4481 try!(self.expect(&token::Colon));
4482 let typ = try!(self.parse_ty_sum());
4483 try!(self.expect(&token::Eq));
4484 let expr = try!(self.parse_expr_nopanic());
4485 try!(self.commit_expr_expecting(&expr, token::Semi));
4486 (name, ConstImplItem(typ, expr))
4488 let (name, inner_attrs, node) = try!(self.parse_impl_method(vis));
4489 attrs.extend(inner_attrs);
4494 id: ast::DUMMY_NODE_ID,
4495 span: mk_sp(lo, self.last_span.hi),
4503 fn complain_if_pub_macro(&mut self, visa: Visibility, span: Span) {
4506 self.span_err(span, "can't qualify macro invocation with `pub`");
4507 self.fileline_help(span, "try adjusting the macro to put `pub` inside \
4514 /// Parse a method or a macro invocation in a trait impl.
4515 fn parse_impl_method(&mut self, vis: Visibility)
4516 -> PResult<(Ident, Vec<ast::Attribute>, ast::ImplItem_)> {
4517 // code copied from parse_macro_use_or_failure... abstraction!
4518 if !self.token.is_any_keyword()
4519 && self.look_ahead(1, |t| *t == token::Not)
4520 && (self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren))
4521 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) {
4524 let last_span = self.last_span;
4525 self.complain_if_pub_macro(vis, last_span);
4527 let pth = try!(self.parse_path(NoTypesAllowed));
4528 try!(self.expect(&token::Not));
4530 // eat a matched-delimiter token tree:
4531 let delim = try!(self.expect_open_delim());
4532 let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
4534 |p| p.parse_token_tree()));
4535 let m_ = ast::MacInvocTT(pth, tts, EMPTY_CTXT);
4536 let m: ast::Mac = codemap::Spanned { node: m_,
4537 span: mk_sp(self.span.lo,
4539 if delim != token::Brace {
4540 try!(self.expect(&token::Semi))
4542 Ok((token::special_idents::invalid, vec![], ast::MacImplItem(m)))
4544 let (constness, unsafety, abi) = try!(self.parse_fn_front_matter());
4545 let ident = try!(self.parse_ident());
4546 let mut generics = try!(self.parse_generics());
4547 let (explicit_self, decl) = try!(self.parse_fn_decl_with_self(|p| {
4550 generics.where_clause = try!(self.parse_where_clause());
4551 let (inner_attrs, body) = try!(self.parse_inner_attrs_and_block());
4552 Ok((ident, inner_attrs, MethodImplItem(ast::MethodSig {
4555 explicit_self: explicit_self,
4557 constness: constness,
4563 /// Parse trait Foo { ... }
4564 fn parse_item_trait(&mut self, unsafety: Unsafety) -> PResult<ItemInfo> {
4566 let ident = try!(self.parse_ident());
4567 let mut tps = try!(self.parse_generics());
4569 // Parse supertrait bounds.
4570 let bounds = try!(self.parse_colon_then_ty_param_bounds(BoundParsingMode::Bare));
4572 tps.where_clause = try!(self.parse_where_clause());
4574 let meths = try!(self.parse_trait_items());
4575 Ok((ident, ItemTrait(unsafety, tps, bounds, meths), None))
4578 /// Parses items implementations variants
4579 /// impl<T> Foo { ... }
4580 /// impl<T> ToString for &'static T { ... }
4581 /// impl Send for .. {}
4582 fn parse_item_impl(&mut self, unsafety: ast::Unsafety) -> PResult<ItemInfo> {
4583 let impl_span = self.span;
4585 // First, parse type parameters if necessary.
4586 let mut generics = try!(self.parse_generics());
4588 // Special case: if the next identifier that follows is '(', don't
4589 // allow this to be parsed as a trait.
4590 let could_be_trait = self.token != token::OpenDelim(token::Paren);
4592 let neg_span = self.span;
4593 let polarity = if try!(self.eat(&token::Not) ){
4594 ast::ImplPolarity::Negative
4596 ast::ImplPolarity::Positive
4600 let mut ty = try!(self.parse_ty_sum());
4602 // Parse traits, if necessary.
4603 let opt_trait = if could_be_trait && try!(self.eat_keyword(keywords::For) ){
4604 // New-style trait. Reinterpret the type as a trait.
4606 TyPath(None, ref path) => {
4608 path: (*path).clone(),
4613 self.span_err(ty.span, "not a trait");
4619 ast::ImplPolarity::Negative => {
4620 // This is a negated type implementation
4621 // `impl !MyType {}`, which is not allowed.
4622 self.span_err(neg_span, "inherent implementation can't be negated");
4629 if opt_trait.is_some() && try!(self.eat(&token::DotDot) ){
4630 if generics.is_parameterized() {
4631 self.span_err(impl_span, "default trait implementations are not \
4632 allowed to have generics");
4635 try!(self.expect(&token::OpenDelim(token::Brace)));
4636 try!(self.expect(&token::CloseDelim(token::Brace)));
4637 Ok((ast_util::impl_pretty_name(&opt_trait, None),
4638 ItemDefaultImpl(unsafety, opt_trait.unwrap()), None))
4640 if opt_trait.is_some() {
4641 ty = try!(self.parse_ty_sum());
4643 generics.where_clause = try!(self.parse_where_clause());
4645 try!(self.expect(&token::OpenDelim(token::Brace)));
4646 let attrs = self.parse_inner_attributes();
4648 let mut impl_items = vec![];
4649 while !try!(self.eat(&token::CloseDelim(token::Brace))) {
4650 impl_items.push(try!(self.parse_impl_item()));
4653 Ok((ast_util::impl_pretty_name(&opt_trait, Some(&*ty)),
4654 ItemImpl(unsafety, polarity, generics, opt_trait, ty, impl_items),
4659 /// Parse a::B<String,i32>
4660 fn parse_trait_ref(&mut self) -> PResult<TraitRef> {
4662 path: try!(self.parse_path(LifetimeAndTypesWithoutColons)),
4663 ref_id: ast::DUMMY_NODE_ID,
4667 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<Vec<ast::LifetimeDef>> {
4668 if try!(self.eat_keyword(keywords::For) ){
4669 try!(self.expect(&token::Lt));
4670 let lifetime_defs = try!(self.parse_lifetime_defs());
4671 try!(self.expect_gt());
4678 /// Parse for<'l> a::B<String,i32>
4679 fn parse_poly_trait_ref(&mut self) -> PResult<PolyTraitRef> {
4680 let lo = self.span.lo;
4681 let lifetime_defs = try!(self.parse_late_bound_lifetime_defs());
4683 Ok(ast::PolyTraitRef {
4684 bound_lifetimes: lifetime_defs,
4685 trait_ref: try!(self.parse_trait_ref()),
4686 span: mk_sp(lo, self.last_span.hi),
4690 /// Parse struct Foo { ... }
4691 fn parse_item_struct(&mut self) -> PResult<ItemInfo> {
4692 let class_name = try!(self.parse_ident());
4693 let mut generics = try!(self.parse_generics());
4695 // There is a special case worth noting here, as reported in issue #17904.
4696 // If we are parsing a tuple struct it is the case that the where clause
4697 // should follow the field list. Like so:
4699 // struct Foo<T>(T) where T: Copy;
4701 // If we are parsing a normal record-style struct it is the case
4702 // that the where clause comes before the body, and after the generics.
4703 // So if we look ahead and see a brace or a where-clause we begin
4704 // parsing a record style struct.
4706 // Otherwise if we look ahead and see a paren we parse a tuple-style
4709 let (fields, ctor_id) = if self.token.is_keyword(keywords::Where) {
4710 generics.where_clause = try!(self.parse_where_clause());
4711 if try!(self.eat(&token::Semi)) {
4712 // If we see a: `struct Foo<T> where T: Copy;` style decl.
4713 (Vec::new(), Some(ast::DUMMY_NODE_ID))
4715 // If we see: `struct Foo<T> where T: Copy { ... }`
4716 (try!(self.parse_record_struct_body(&class_name)), None)
4718 // No `where` so: `struct Foo<T>;`
4719 } else if try!(self.eat(&token::Semi) ){
4720 (Vec::new(), Some(ast::DUMMY_NODE_ID))
4721 // Record-style struct definition
4722 } else if self.token == token::OpenDelim(token::Brace) {
4723 let fields = try!(self.parse_record_struct_body(&class_name));
4725 // Tuple-style struct definition with optional where-clause.
4726 } else if self.token == token::OpenDelim(token::Paren) {
4727 let fields = try!(self.parse_tuple_struct_body(&class_name, &mut generics));
4728 (fields, Some(ast::DUMMY_NODE_ID))
4730 let token_str = self.this_token_to_string();
4731 return Err(self.fatal(&format!("expected `where`, `{{`, `(`, or `;` after struct \
4732 name, found `{}`", token_str)))
4736 ItemStruct(P(ast::StructDef {
4743 pub fn parse_record_struct_body(&mut self,
4744 class_name: &ast::Ident) -> PResult<Vec<StructField>> {
4745 let mut fields = Vec::new();
4746 if try!(self.eat(&token::OpenDelim(token::Brace)) ){
4747 while self.token != token::CloseDelim(token::Brace) {
4748 fields.push(try!(self.parse_struct_decl_field(true)));
4751 if fields.is_empty() {
4752 return Err(self.fatal(&format!("unit-like struct definition should be \
4753 written as `struct {};`",
4759 let token_str = self.this_token_to_string();
4760 return Err(self.fatal(&format!("expected `where`, or `{{` after struct \
4768 pub fn parse_tuple_struct_body(&mut self,
4769 class_name: &ast::Ident,
4770 generics: &mut ast::Generics)
4771 -> PResult<Vec<StructField>> {
4772 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
4773 // Unit like structs are handled in parse_item_struct function
4774 let fields = try!(self.parse_unspanned_seq(
4775 &token::OpenDelim(token::Paren),
4776 &token::CloseDelim(token::Paren),
4777 seq_sep_trailing_allowed(token::Comma),
4779 let attrs = p.parse_outer_attributes();
4781 let struct_field_ = ast::StructField_ {
4782 kind: UnnamedField(try!(p.parse_visibility())),
4783 id: ast::DUMMY_NODE_ID,
4784 ty: try!(p.parse_ty_sum()),
4787 Ok(spanned(lo, p.span.hi, struct_field_))
4790 if fields.is_empty() {
4791 return Err(self.fatal(&format!("unit-like struct definition should be \
4792 written as `struct {};`",
4796 generics.where_clause = try!(self.parse_where_clause());
4797 try!(self.expect(&token::Semi));
4801 /// Parse a structure field declaration
4802 pub fn parse_single_struct_field(&mut self,
4804 attrs: Vec<Attribute> )
4805 -> PResult<StructField> {
4806 let a_var = try!(self.parse_name_and_ty(vis, attrs));
4811 token::CloseDelim(token::Brace) => {}
4813 let span = self.span;
4814 let token_str = self.this_token_to_string();
4815 return Err(self.span_fatal_help(span,
4816 &format!("expected `,`, or `}}`, found `{}`",
4818 "struct fields should be separated by commas"))
4824 /// Parse an element of a struct definition
4825 fn parse_struct_decl_field(&mut self, allow_pub: bool) -> PResult<StructField> {
4827 let attrs = self.parse_outer_attributes();
4829 if try!(self.eat_keyword(keywords::Pub) ){
4831 let span = self.last_span;
4832 self.span_err(span, "`pub` is not allowed here");
4834 return self.parse_single_struct_field(Public, attrs);
4837 return self.parse_single_struct_field(Inherited, attrs);
4840 /// Parse visibility: PUB or nothing
4841 fn parse_visibility(&mut self) -> PResult<Visibility> {
4842 if try!(self.eat_keyword(keywords::Pub)) { Ok(Public) }
4843 else { Ok(Inherited) }
4846 /// Given a termination token, parse all of the items in a module
4847 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: BytePos) -> PResult<Mod> {
4848 let mut items = vec![];
4849 while let Some(item) = try!(self.parse_item_nopanic()) {
4853 if !try!(self.eat(term)) {
4854 let token_str = self.this_token_to_string();
4855 return Err(self.fatal(&format!("expected item, found `{}`", token_str)));
4858 let hi = if self.span == codemap::DUMMY_SP {
4865 inner: mk_sp(inner_lo, hi),
4870 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<ItemInfo> {
4871 let id = try!(self.parse_ident());
4872 try!(self.expect(&token::Colon));
4873 let ty = try!(self.parse_ty_sum());
4874 try!(self.expect(&token::Eq));
4875 let e = try!(self.parse_expr_nopanic());
4876 try!(self.commit_expr_expecting(&*e, token::Semi));
4877 let item = match m {
4878 Some(m) => ItemStatic(ty, m, e),
4879 None => ItemConst(ty, e),
4881 Ok((id, item, None))
4884 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
4885 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<ItemInfo> {
4886 let id_span = self.span;
4887 let id = try!(self.parse_ident());
4888 if self.check(&token::Semi) {
4890 // This mod is in an external file. Let's go get it!
4891 let (m, attrs) = try!(self.eval_src_mod(id, outer_attrs, id_span));
4892 Ok((id, m, Some(attrs)))
4894 self.push_mod_path(id, outer_attrs);
4895 try!(self.expect(&token::OpenDelim(token::Brace)));
4896 let mod_inner_lo = self.span.lo;
4897 let old_owns_directory = self.owns_directory;
4898 self.owns_directory = true;
4899 let attrs = self.parse_inner_attributes();
4900 let m = try!(self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo));
4901 self.owns_directory = old_owns_directory;
4902 self.pop_mod_path();
4903 Ok((id, ItemMod(m), Some(attrs)))
4907 fn push_mod_path(&mut self, id: Ident, attrs: &[Attribute]) {
4908 let default_path = self.id_to_interned_str(id);
4909 let file_path = match ::attr::first_attr_value_str_by_name(attrs, "path") {
4911 None => default_path,
4913 self.mod_path_stack.push(file_path)
4916 fn pop_mod_path(&mut self) {
4917 self.mod_path_stack.pop().unwrap();
4920 pub fn submod_path_from_attr(attrs: &[ast::Attribute], dir_path: &Path) -> Option<PathBuf> {
4921 ::attr::first_attr_value_str_by_name(attrs, "path").map(|d| dir_path.join(&*d))
4924 /// Returns either a path to a module, or .
4925 pub fn default_submod_path(id: ast::Ident, dir_path: &Path, codemap: &CodeMap) -> ModulePath
4927 let mod_name = id.to_string();
4928 let default_path_str = format!("{}.rs", mod_name);
4929 let secondary_path_str = format!("{}/mod.rs", mod_name);
4930 let default_path = dir_path.join(&default_path_str);
4931 let secondary_path = dir_path.join(&secondary_path_str);
4932 let default_exists = codemap.file_exists(&default_path);
4933 let secondary_exists = codemap.file_exists(&secondary_path);
4935 let result = match (default_exists, secondary_exists) {
4936 (true, false) => Ok(ModulePathSuccess { path: default_path, owns_directory: false }),
4937 (false, true) => Ok(ModulePathSuccess { path: secondary_path, owns_directory: true }),
4938 (false, false) => Err(ModulePathError {
4939 err_msg: format!("file not found for module `{}`", mod_name),
4940 help_msg: format!("name the file either {} or {} inside the directory {:?}",
4943 dir_path.display()),
4945 (true, true) => Err(ModulePathError {
4946 err_msg: format!("file for module `{}` found at both {} and {}",
4949 secondary_path_str),
4950 help_msg: "delete or rename one of them to remove the ambiguity".to_owned(),
4956 path_exists: default_exists || secondary_exists,
4961 fn submod_path(&mut self,
4963 outer_attrs: &[ast::Attribute],
4964 id_sp: Span) -> PResult<ModulePathSuccess> {
4965 let mut prefix = PathBuf::from(&self.sess.codemap().span_to_filename(self.span));
4967 let mut dir_path = prefix;
4968 for part in &self.mod_path_stack {
4969 dir_path.push(&**part);
4972 if let Some(p) = Parser::submod_path_from_attr(outer_attrs, &dir_path) {
4973 return Ok(ModulePathSuccess { path: p, owns_directory: true });
4976 let paths = Parser::default_submod_path(id, &dir_path, self.sess.codemap());
4978 if !self.owns_directory {
4979 self.span_err(id_sp, "cannot declare a new module at this location");
4980 let this_module = match self.mod_path_stack.last() {
4981 Some(name) => name.to_string(),
4982 None => self.root_module_name.as_ref().unwrap().clone(),
4984 self.span_note(id_sp,
4985 &format!("maybe move this module `{0}` to its own directory \
4988 if paths.path_exists {
4989 self.span_note(id_sp,
4990 &format!("... or maybe `use` the module `{}` instead \
4991 of possibly redeclaring it",
4994 self.abort_if_errors();
4997 match paths.result {
4998 Ok(succ) => Ok(succ),
4999 Err(err) => Err(self.span_fatal_help(id_sp, &err.err_msg, &err.help_msg)),
5003 /// Read a module from a source file.
5004 fn eval_src_mod(&mut self,
5006 outer_attrs: &[ast::Attribute],
5008 -> PResult<(ast::Item_, Vec<ast::Attribute> )> {
5009 let ModulePathSuccess { path, owns_directory } = try!(self.submod_path(id,
5013 self.eval_src_mod_from_path(path,
5019 fn eval_src_mod_from_path(&mut self,
5021 owns_directory: bool,
5023 id_sp: Span) -> PResult<(ast::Item_, Vec<ast::Attribute> )> {
5024 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
5025 match included_mod_stack.iter().position(|p| *p == path) {
5027 let mut err = String::from("circular modules: ");
5028 let len = included_mod_stack.len();
5029 for p in &included_mod_stack[i.. len] {
5030 err.push_str(&p.to_string_lossy());
5031 err.push_str(" -> ");
5033 err.push_str(&path.to_string_lossy());
5034 return Err(self.span_fatal(id_sp, &err[..]));
5038 included_mod_stack.push(path.clone());
5039 drop(included_mod_stack);
5041 let mut p0 = new_sub_parser_from_file(self.sess,
5047 let mod_inner_lo = p0.span.lo;
5048 let mod_attrs = p0.parse_inner_attributes();
5049 let m0 = try!(p0.parse_mod_items(&token::Eof, mod_inner_lo));
5050 self.sess.included_mod_stack.borrow_mut().pop();
5051 Ok((ast::ItemMod(m0), mod_attrs))
5054 /// Parse a function declaration from a foreign module
5055 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility,
5056 attrs: Vec<Attribute>) -> PResult<P<ForeignItem>> {
5057 let lo = self.span.lo;
5058 try!(self.expect_keyword(keywords::Fn));
5060 let (ident, mut generics) = try!(self.parse_fn_header());
5061 let decl = try!(self.parse_fn_decl(true));
5062 generics.where_clause = try!(self.parse_where_clause());
5063 let hi = self.span.hi;
5064 try!(self.expect(&token::Semi));
5065 Ok(P(ast::ForeignItem {
5068 node: ForeignItemFn(decl, generics),
5069 id: ast::DUMMY_NODE_ID,
5070 span: mk_sp(lo, hi),
5075 /// Parse a static item from a foreign module
5076 fn parse_item_foreign_static(&mut self, vis: ast::Visibility,
5077 attrs: Vec<Attribute>) -> PResult<P<ForeignItem>> {
5078 let lo = self.span.lo;
5080 try!(self.expect_keyword(keywords::Static));
5081 let mutbl = try!(self.eat_keyword(keywords::Mut));
5083 let ident = try!(self.parse_ident());
5084 try!(self.expect(&token::Colon));
5085 let ty = try!(self.parse_ty_sum());
5086 let hi = self.span.hi;
5087 try!(self.expect(&token::Semi));
5091 node: ForeignItemStatic(ty, mutbl),
5092 id: ast::DUMMY_NODE_ID,
5093 span: mk_sp(lo, hi),
5098 /// Parse extern crate links
5102 /// extern crate foo;
5103 /// extern crate bar as foo;
5104 fn parse_item_extern_crate(&mut self,
5106 visibility: Visibility,
5107 attrs: Vec<Attribute>)
5108 -> PResult<P<Item>> {
5110 let crate_name = try!(self.parse_ident());
5111 let (maybe_path, ident) = if let Some(ident) = try!(self.parse_rename()) {
5112 (Some(crate_name.name), ident)
5116 try!(self.expect(&token::Semi));
5118 let last_span = self.last_span;
5122 ItemExternCrate(maybe_path),
5127 /// Parse `extern` for foreign ABIs
5130 /// `extern` is expected to have been
5131 /// consumed before calling this method
5137 fn parse_item_foreign_mod(&mut self,
5139 opt_abi: Option<abi::Abi>,
5140 visibility: Visibility,
5141 mut attrs: Vec<Attribute>)
5142 -> PResult<P<Item>> {
5143 try!(self.expect(&token::OpenDelim(token::Brace)));
5145 let abi = opt_abi.unwrap_or(abi::C);
5147 attrs.extend(self.parse_inner_attributes());
5149 let mut foreign_items = vec![];
5150 while let Some(item) = try!(self.parse_foreign_item()) {
5151 foreign_items.push(item);
5153 try!(self.expect(&token::CloseDelim(token::Brace)));
5155 let last_span = self.last_span;
5156 let m = ast::ForeignMod {
5158 items: foreign_items
5162 special_idents::invalid,
5168 /// Parse type Foo = Bar;
5169 fn parse_item_type(&mut self) -> PResult<ItemInfo> {
5170 let ident = try!(self.parse_ident());
5171 let mut tps = try!(self.parse_generics());
5172 tps.where_clause = try!(self.parse_where_clause());
5173 try!(self.expect(&token::Eq));
5174 let ty = try!(self.parse_ty_sum());
5175 try!(self.expect(&token::Semi));
5176 Ok((ident, ItemTy(ty, tps), None))
5179 /// Parse a structure-like enum variant definition
5180 /// this should probably be renamed or refactored...
5181 fn parse_struct_def(&mut self) -> PResult<P<StructDef>> {
5182 let mut fields: Vec<StructField> = Vec::new();
5183 while self.token != token::CloseDelim(token::Brace) {
5184 fields.push(try!(self.parse_struct_decl_field(false)));
5194 /// Parse the part of an "enum" decl following the '{'
5195 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<EnumDef> {
5196 let mut variants = Vec::new();
5197 let mut all_nullary = true;
5198 let mut any_disr = None;
5199 while self.token != token::CloseDelim(token::Brace) {
5200 let variant_attrs = self.parse_outer_attributes();
5201 let vlo = self.span.lo;
5203 let vis = try!(self.parse_visibility());
5207 let mut args = Vec::new();
5208 let mut disr_expr = None;
5209 ident = try!(self.parse_ident());
5210 if try!(self.eat(&token::OpenDelim(token::Brace)) ){
5211 // Parse a struct variant.
5212 all_nullary = false;
5213 let start_span = self.span;
5214 let struct_def = try!(self.parse_struct_def());
5215 if struct_def.fields.is_empty() {
5216 self.span_err(start_span,
5217 &format!("unit-like struct variant should be written \
5218 without braces, as `{},`",
5221 kind = StructVariantKind(struct_def);
5222 } else if self.check(&token::OpenDelim(token::Paren)) {
5223 all_nullary = false;
5224 let arg_tys = try!(self.parse_enum_variant_seq(
5225 &token::OpenDelim(token::Paren),
5226 &token::CloseDelim(token::Paren),
5227 seq_sep_trailing_allowed(token::Comma),
5228 |p| p.parse_ty_sum()
5231 args.push(ast::VariantArg {
5233 id: ast::DUMMY_NODE_ID,
5236 kind = TupleVariantKind(args);
5237 } else if try!(self.eat(&token::Eq) ){
5238 disr_expr = Some(try!(self.parse_expr_nopanic()));
5239 any_disr = disr_expr.as_ref().map(|expr| expr.span);
5240 kind = TupleVariantKind(args);
5242 kind = TupleVariantKind(Vec::new());
5245 let vr = ast::Variant_ {
5247 attrs: variant_attrs,
5249 id: ast::DUMMY_NODE_ID,
5250 disr_expr: disr_expr,
5253 variants.push(P(spanned(vlo, self.last_span.hi, vr)));
5255 if !try!(self.eat(&token::Comma)) { break; }
5257 try!(self.expect(&token::CloseDelim(token::Brace)));
5259 Some(disr_span) if !all_nullary =>
5260 self.span_err(disr_span,
5261 "discriminator values can only be used with a c-like enum"),
5265 Ok(ast::EnumDef { variants: variants })
5268 /// Parse an "enum" declaration
5269 fn parse_item_enum(&mut self) -> PResult<ItemInfo> {
5270 let id = try!(self.parse_ident());
5271 let mut generics = try!(self.parse_generics());
5272 generics.where_clause = try!(self.parse_where_clause());
5273 try!(self.expect(&token::OpenDelim(token::Brace)));
5275 let enum_definition = try!(self.parse_enum_def(&generics));
5276 Ok((id, ItemEnum(enum_definition, generics), None))
5279 /// Parses a string as an ABI spec on an extern type or module. Consumes
5280 /// the `extern` keyword, if one is found.
5281 fn parse_opt_abi(&mut self) -> PResult<Option<abi::Abi>> {
5283 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
5285 self.expect_no_suffix(sp, "ABI spec", suf);
5287 match abi::lookup(&s.as_str()) {
5288 Some(abi) => Ok(Some(abi)),
5290 let last_span = self.last_span;
5293 &format!("invalid ABI: expected one of [{}], \
5295 abi::all_names().join(", "),
5306 /// Parse one of the items allowed by the flags.
5307 /// NB: this function no longer parses the items inside an
5309 fn parse_item_(&mut self, attrs: Vec<Attribute>,
5310 macros_allowed: bool) -> PResult<Option<P<Item>>> {
5311 let nt_item = match self.token {
5312 token::Interpolated(token::NtItem(ref item)) => {
5313 Some((**item).clone())
5320 let mut attrs = attrs;
5321 mem::swap(&mut item.attrs, &mut attrs);
5322 item.attrs.extend(attrs);
5323 return Ok(Some(P(item)));
5328 let lo = self.span.lo;
5330 let visibility = try!(self.parse_visibility());
5332 if try!(self.eat_keyword(keywords::Use) ){
5334 let item_ = ItemUse(try!(self.parse_view_path()));
5335 try!(self.expect(&token::Semi));
5337 let last_span = self.last_span;
5338 let item = self.mk_item(lo,
5340 token::special_idents::invalid,
5344 return Ok(Some(item));
5347 if try!(self.eat_keyword(keywords::Extern)) {
5348 if try!(self.eat_keyword(keywords::Crate)) {
5349 return Ok(Some(try!(self.parse_item_extern_crate(lo, visibility, attrs))));
5352 let opt_abi = try!(self.parse_opt_abi());
5354 if try!(self.eat_keyword(keywords::Fn) ){
5355 // EXTERN FUNCTION ITEM
5356 let abi = opt_abi.unwrap_or(abi::C);
5357 let (ident, item_, extra_attrs) =
5358 try!(self.parse_item_fn(Unsafety::Normal, Constness::NotConst, abi));
5359 let last_span = self.last_span;
5360 let item = self.mk_item(lo,
5365 maybe_append(attrs, extra_attrs));
5366 return Ok(Some(item));
5367 } else if self.check(&token::OpenDelim(token::Brace)) {
5368 return Ok(Some(try!(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs))));
5371 try!(self.expect_one_of(&[], &[]));
5374 if try!(self.eat_keyword(keywords::Static) ){
5376 let m = if try!(self.eat_keyword(keywords::Mut)) {MutMutable} else {MutImmutable};
5377 let (ident, item_, extra_attrs) = try!(self.parse_item_const(Some(m)));
5378 let last_span = self.last_span;
5379 let item = self.mk_item(lo,
5384 maybe_append(attrs, extra_attrs));
5385 return Ok(Some(item));
5387 if try!(self.eat_keyword(keywords::Const) ){
5388 if self.check_keyword(keywords::Fn) {
5389 // CONST FUNCTION ITEM
5391 let (ident, item_, extra_attrs) =
5392 try!(self.parse_item_fn(Unsafety::Normal, Constness::Const, abi::Rust));
5393 let last_span = self.last_span;
5394 let item = self.mk_item(lo,
5399 maybe_append(attrs, extra_attrs));
5400 return Ok(Some(item));
5404 if try!(self.eat_keyword(keywords::Mut) ){
5405 let last_span = self.last_span;
5406 self.span_err(last_span, "const globals cannot be mutable");
5407 self.fileline_help(last_span, "did you mean to declare a static?");
5409 let (ident, item_, extra_attrs) = try!(self.parse_item_const(None));
5410 let last_span = self.last_span;
5411 let item = self.mk_item(lo,
5416 maybe_append(attrs, extra_attrs));
5417 return Ok(Some(item));
5419 if self.check_keyword(keywords::Unsafe) &&
5420 self.look_ahead(1, |t| t.is_keyword(keywords::Trait))
5422 // UNSAFE TRAIT ITEM
5423 try!(self.expect_keyword(keywords::Unsafe));
5424 try!(self.expect_keyword(keywords::Trait));
5425 let (ident, item_, extra_attrs) =
5426 try!(self.parse_item_trait(ast::Unsafety::Unsafe));
5427 let last_span = self.last_span;
5428 let item = self.mk_item(lo,
5433 maybe_append(attrs, extra_attrs));
5434 return Ok(Some(item));
5436 if self.check_keyword(keywords::Unsafe) &&
5437 self.look_ahead(1, |t| t.is_keyword(keywords::Impl))
5440 try!(self.expect_keyword(keywords::Unsafe));
5441 try!(self.expect_keyword(keywords::Impl));
5442 let (ident, item_, extra_attrs) = try!(self.parse_item_impl(ast::Unsafety::Unsafe));
5443 let last_span = self.last_span;
5444 let item = self.mk_item(lo,
5449 maybe_append(attrs, extra_attrs));
5450 return Ok(Some(item));
5452 if self.check_keyword(keywords::Fn) {
5455 let (ident, item_, extra_attrs) =
5456 try!(self.parse_item_fn(Unsafety::Normal, Constness::NotConst, abi::Rust));
5457 let last_span = self.last_span;
5458 let item = self.mk_item(lo,
5463 maybe_append(attrs, extra_attrs));
5464 return Ok(Some(item));
5466 if self.check_keyword(keywords::Unsafe)
5467 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
5468 // UNSAFE FUNCTION ITEM
5470 let abi = if try!(self.eat_keyword(keywords::Extern) ){
5471 try!(self.parse_opt_abi()).unwrap_or(abi::C)
5475 try!(self.expect_keyword(keywords::Fn));
5476 let (ident, item_, extra_attrs) =
5477 try!(self.parse_item_fn(Unsafety::Unsafe, Constness::NotConst, abi));
5478 let last_span = self.last_span;
5479 let item = self.mk_item(lo,
5484 maybe_append(attrs, extra_attrs));
5485 return Ok(Some(item));
5487 if try!(self.eat_keyword(keywords::Mod) ){
5489 let (ident, item_, extra_attrs) =
5490 try!(self.parse_item_mod(&attrs[..]));
5491 let last_span = self.last_span;
5492 let item = self.mk_item(lo,
5497 maybe_append(attrs, extra_attrs));
5498 return Ok(Some(item));
5500 if try!(self.eat_keyword(keywords::Type) ){
5502 let (ident, item_, extra_attrs) = try!(self.parse_item_type());
5503 let last_span = self.last_span;
5504 let item = self.mk_item(lo,
5509 maybe_append(attrs, extra_attrs));
5510 return Ok(Some(item));
5512 if try!(self.eat_keyword(keywords::Enum) ){
5514 let (ident, item_, extra_attrs) = try!(self.parse_item_enum());
5515 let last_span = self.last_span;
5516 let item = self.mk_item(lo,
5521 maybe_append(attrs, extra_attrs));
5522 return Ok(Some(item));
5524 if try!(self.eat_keyword(keywords::Trait) ){
5526 let (ident, item_, extra_attrs) =
5527 try!(self.parse_item_trait(ast::Unsafety::Normal));
5528 let last_span = self.last_span;
5529 let item = self.mk_item(lo,
5534 maybe_append(attrs, extra_attrs));
5535 return Ok(Some(item));
5537 if try!(self.eat_keyword(keywords::Impl) ){
5539 let (ident, item_, extra_attrs) = try!(self.parse_item_impl(ast::Unsafety::Normal));
5540 let last_span = self.last_span;
5541 let item = self.mk_item(lo,
5546 maybe_append(attrs, extra_attrs));
5547 return Ok(Some(item));
5549 if try!(self.eat_keyword(keywords::Struct) ){
5551 let (ident, item_, extra_attrs) = try!(self.parse_item_struct());
5552 let last_span = self.last_span;
5553 let item = self.mk_item(lo,
5558 maybe_append(attrs, extra_attrs));
5559 return Ok(Some(item));
5561 self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility)
5564 /// Parse a foreign item.
5565 fn parse_foreign_item(&mut self) -> PResult<Option<P<ForeignItem>>> {
5566 let attrs = self.parse_outer_attributes();
5567 let lo = self.span.lo;
5568 let visibility = try!(self.parse_visibility());
5570 if self.check_keyword(keywords::Static) {
5571 // FOREIGN STATIC ITEM
5572 return Ok(Some(try!(self.parse_item_foreign_static(visibility, attrs))));
5574 if self.check_keyword(keywords::Fn) || self.check_keyword(keywords::Unsafe) {
5575 // FOREIGN FUNCTION ITEM
5576 return Ok(Some(try!(self.parse_item_foreign_fn(visibility, attrs))));
5579 // FIXME #5668: this will occur for a macro invocation:
5580 match try!(self.parse_macro_use_or_failure(attrs, true, lo, visibility)) {
5582 return Err(self.span_fatal(item.span, "macros cannot expand to foreign items"));
5588 /// This is the fall-through for parsing items.
5589 fn parse_macro_use_or_failure(
5591 attrs: Vec<Attribute> ,
5592 macros_allowed: bool,
5594 visibility: Visibility
5595 ) -> PResult<Option<P<Item>>> {
5596 if macros_allowed && !self.token.is_any_keyword()
5597 && self.look_ahead(1, |t| *t == token::Not)
5598 && (self.look_ahead(2, |t| t.is_plain_ident())
5599 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren))
5600 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) {
5601 // MACRO INVOCATION ITEM
5603 let last_span = self.last_span;
5604 self.complain_if_pub_macro(visibility, last_span);
5607 let pth = try!(self.parse_path(NoTypesAllowed));
5608 try!(self.expect(&token::Not));
5610 // a 'special' identifier (like what `macro_rules!` uses)
5611 // is optional. We should eventually unify invoc syntax
5613 let id = if self.token.is_plain_ident() {
5614 try!(self.parse_ident())
5616 token::special_idents::invalid // no special identifier
5618 // eat a matched-delimiter token tree:
5619 let delim = try!(self.expect_open_delim());
5620 let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
5622 |p| p.parse_token_tree()));
5623 // single-variant-enum... :
5624 let m = ast::MacInvocTT(pth, tts, EMPTY_CTXT);
5625 let m: ast::Mac = codemap::Spanned { node: m,
5626 span: mk_sp(self.span.lo,
5629 if delim != token::Brace {
5630 if !try!(self.eat(&token::Semi) ){
5631 let last_span = self.last_span;
5632 self.span_err(last_span,
5633 "macros that expand to items must either \
5634 be surrounded with braces or followed by \
5639 let item_ = ItemMac(m);
5640 let last_span = self.last_span;
5641 let item = self.mk_item(lo,
5647 return Ok(Some(item));
5650 // FAILURE TO PARSE ITEM
5654 let last_span = self.last_span;
5655 return Err(self.span_fatal(last_span, "unmatched visibility `pub`"));
5659 if !attrs.is_empty() {
5660 self.expected_item_err(&attrs);
5665 pub fn parse_item_nopanic(&mut self) -> PResult<Option<P<Item>>> {
5666 let attrs = self.parse_outer_attributes();
5667 self.parse_item_(attrs, true)
5671 /// Matches view_path : MOD? non_global_path as IDENT
5672 /// | MOD? non_global_path MOD_SEP LBRACE RBRACE
5673 /// | MOD? non_global_path MOD_SEP LBRACE ident_seq RBRACE
5674 /// | MOD? non_global_path MOD_SEP STAR
5675 /// | MOD? non_global_path
5676 fn parse_view_path(&mut self) -> PResult<P<ViewPath>> {
5677 let lo = self.span.lo;
5679 // Allow a leading :: because the paths are absolute either way.
5680 // This occurs with "use $crate::..." in macros.
5681 try!(self.eat(&token::ModSep));
5683 if self.check(&token::OpenDelim(token::Brace)) {
5685 let idents = try!(self.parse_unspanned_seq(
5686 &token::OpenDelim(token::Brace),
5687 &token::CloseDelim(token::Brace),
5688 seq_sep_trailing_allowed(token::Comma),
5689 |p| p.parse_path_list_item()));
5690 let path = ast::Path {
5691 span: mk_sp(lo, self.span.hi),
5693 segments: Vec::new()
5695 return Ok(P(spanned(lo, self.span.hi, ViewPathList(path, idents))));
5698 let first_ident = try!(self.parse_ident());
5699 let mut path = vec!(first_ident);
5700 if let token::ModSep = self.token {
5701 // foo::bar or foo::{a,b,c} or foo::*
5702 while self.check(&token::ModSep) {
5706 token::Ident(..) => {
5707 let ident = try!(self.parse_ident());
5711 // foo::bar::{a,b,c}
5712 token::OpenDelim(token::Brace) => {
5713 let idents = try!(self.parse_unspanned_seq(
5714 &token::OpenDelim(token::Brace),
5715 &token::CloseDelim(token::Brace),
5716 seq_sep_trailing_allowed(token::Comma),
5717 |p| p.parse_path_list_item()
5719 let path = ast::Path {
5720 span: mk_sp(lo, self.span.hi),
5722 segments: path.into_iter().map(|identifier| {
5724 identifier: identifier,
5725 parameters: ast::PathParameters::none(),
5729 return Ok(P(spanned(lo, self.span.hi, ViewPathList(path, idents))));
5733 token::BinOp(token::Star) => {
5735 let path = ast::Path {
5736 span: mk_sp(lo, self.span.hi),
5738 segments: path.into_iter().map(|identifier| {
5740 identifier: identifier,
5741 parameters: ast::PathParameters::none(),
5745 return Ok(P(spanned(lo, self.span.hi, ViewPathGlob(path))));
5748 // fall-through for case foo::bar::;
5750 self.span_err(self.span, "expected identifier or `{` or `*`, found `;`");
5757 let mut rename_to = path[path.len() - 1];
5758 let path = ast::Path {
5759 span: mk_sp(lo, self.last_span.hi),
5761 segments: path.into_iter().map(|identifier| {
5763 identifier: identifier,
5764 parameters: ast::PathParameters::none(),
5768 rename_to = try!(self.parse_rename()).unwrap_or(rename_to);
5769 Ok(P(spanned(lo, self.last_span.hi, ViewPathSimple(rename_to, path))))
5772 fn parse_rename(&mut self) -> PResult<Option<Ident>> {
5773 if try!(self.eat_keyword(keywords::As)) {
5774 self.parse_ident().map(Some)
5780 /// Parses a source module as a crate. This is the main
5781 /// entry point for the parser.
5782 pub fn parse_crate_mod(&mut self) -> PResult<Crate> {
5783 let lo = self.span.lo;
5785 attrs: self.parse_inner_attributes(),
5786 module: try!(self.parse_mod_items(&token::Eof, lo)),
5787 config: self.cfg.clone(),
5788 span: mk_sp(lo, self.span.lo),
5789 exported_macros: Vec::new(),
5793 pub fn parse_optional_str(&mut self)
5794 -> PResult<Option<(InternedString,
5796 Option<ast::Name>)>> {
5797 let ret = match self.token {
5798 token::Literal(token::Str_(s), suf) => {
5799 (self.id_to_interned_str(s.ident()), ast::CookedStr, suf)
5801 token::Literal(token::StrRaw(s, n), suf) => {
5802 (self.id_to_interned_str(s.ident()), ast::RawStr(n), suf)
5804 _ => return Ok(None)
5810 pub fn parse_str(&mut self) -> PResult<(InternedString, StrStyle)> {
5811 match try!(self.parse_optional_str()) {
5812 Some((s, style, suf)) => {
5813 let sp = self.last_span;
5814 self.expect_no_suffix(sp, "string literal", suf);
5817 _ => Err(self.fatal("expected string literal"))