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, LitBinary};
38 use ast::{LitStr, LitInt, Local, LocalLet};
39 use ast::{MacStmtWithBraces, MacStmtWithSemicolon, MacStmtWithoutBraces};
40 use ast::{MutImmutable, MutMutable, Mac_, MacInvocTT, MatchSource};
41 use ast::{MutTy, BiMul, Mutability};
42 use ast::{MethodImplItem, NamedField, UnNeg, NoReturn, UnNot};
43 use ast::{Pat, PatBox, PatEnum, PatIdent, PatLit, PatQPath, PatMac, PatRange};
44 use ast::{PatRegion, PatStruct, PatTup, PatVec, PatWild, PatWildMulti};
45 use ast::PatWildSingle;
46 use ast::{PolyTraitRef, QSelf};
47 use ast::{Return, BiShl, BiShr, Stmt, StmtDecl};
48 use ast::{StmtExpr, StmtSemi, StmtMac, StructDef, StructField};
49 use ast::{StructVariantKind, BiSub, StrStyle};
50 use ast::{SelfExplicit, SelfRegion, SelfStatic, SelfValue};
51 use ast::{Delimited, SequenceRepetition, TokenTree, TraitItem, TraitRef};
52 use ast::{TtDelimited, TtSequence, TtToken};
53 use ast::{TupleVariantKind, Ty, Ty_, TypeBinding};
54 use ast::{TyFixedLengthVec, TyBareFn, TyTypeof, TyInfer};
55 use ast::{TyParam, TyParamBound, TyParen, TyPath, TyPolyTraitRef, TyPtr};
56 use ast::{TyRptr, TyTup, TyU32, TyVec, UnUniq};
57 use ast::{TypeImplItem, TypeTraitItem};
58 use ast::{UnnamedField, UnsafeBlock};
59 use ast::{ViewPath, ViewPathGlob, ViewPathList, ViewPathSimple};
60 use ast::{Visibility, WhereClause};
62 use ast_util::{self, AS_PREC, ident_to_path, operator_prec};
63 use codemap::{self, Span, BytePos, Spanned, spanned, mk_sp};
65 use ext::tt::macro_parser;
67 use parse::attr::ParserAttr;
69 use parse::common::{SeqSep, seq_sep_none, seq_sep_trailing_allowed};
70 use parse::lexer::{Reader, TokenAndSpan};
71 use parse::obsolete::{ParserObsoleteMethods, ObsoleteSyntax};
72 use parse::token::{self, MatchNt, SubstNt, SpecialVarNt, InternedString};
73 use parse::token::{keywords, special_idents, SpecialMacroVar};
74 use parse::{new_sub_parser_from_file, ParseSess};
77 use owned_slice::OwnedSlice;
79 use diagnostic::FatalError;
81 use std::collections::HashSet;
82 use std::io::prelude::*;
84 use std::path::{Path, PathBuf};
89 flags Restrictions: u8 {
90 const RESTRICTION_STMT_EXPR = 1 << 0,
91 const RESTRICTION_NO_STRUCT_LITERAL = 1 << 1,
95 type ItemInfo = (Ident, Item_, Option<Vec<Attribute> >);
97 /// How to parse a path. There are four different kinds of paths, all of which
98 /// are parsed somewhat differently.
99 #[derive(Copy, Clone, PartialEq)]
100 pub enum PathParsingMode {
101 /// A path with no type parameters; e.g. `foo::bar::Baz`
103 /// A path with a lifetime and type parameters, with no double colons
104 /// before the type parameters; e.g. `foo::bar<'a>::Baz<T>`
105 LifetimeAndTypesWithoutColons,
106 /// A path with a lifetime and type parameters with double colons before
107 /// the type parameters; e.g. `foo::bar::<'a>::Baz::<T>`
108 LifetimeAndTypesWithColons,
111 /// How to parse a bound, whether to allow bound modifiers such as `?`.
112 #[derive(Copy, Clone, PartialEq)]
113 pub enum BoundParsingMode {
118 /// Possibly accept an `token::Interpolated` expression (a pre-parsed expression
119 /// dropped into the token stream, which happens while parsing the result of
120 /// macro expansion). Placement of these is not as complex as I feared it would
121 /// be. The important thing is to make sure that lookahead doesn't balk at
122 /// `token::Interpolated` tokens.
123 macro_rules! maybe_whole_expr {
126 let found = match $p.token {
127 token::Interpolated(token::NtExpr(ref e)) => {
130 token::Interpolated(token::NtPath(_)) => {
131 // FIXME: The following avoids an issue with lexical borrowck scopes,
132 // but the clone is unfortunate.
133 let pt = match $p.token {
134 token::Interpolated(token::NtPath(ref pt)) => (**pt).clone(),
138 Some($p.mk_expr(span.lo, span.hi, ExprPath(None, pt)))
140 token::Interpolated(token::NtBlock(_)) => {
141 // FIXME: The following avoids an issue with lexical borrowck scopes,
142 // but the clone is unfortunate.
143 let b = match $p.token {
144 token::Interpolated(token::NtBlock(ref b)) => (*b).clone(),
148 Some($p.mk_expr(span.lo, span.hi, ExprBlock(b)))
163 /// As maybe_whole_expr, but for things other than expressions
164 macro_rules! maybe_whole {
165 ($p:expr, $constructor:ident) => (
167 let found = match ($p).token {
168 token::Interpolated(token::$constructor(_)) => {
169 Some(try!(($p).bump_and_get()))
173 if let Some(token::Interpolated(token::$constructor(x))) = found {
174 return Ok(x.clone());
178 (no_clone $p:expr, $constructor:ident) => (
180 let found = match ($p).token {
181 token::Interpolated(token::$constructor(_)) => {
182 Some(try!(($p).bump_and_get()))
186 if let Some(token::Interpolated(token::$constructor(x))) = found {
191 (deref $p:expr, $constructor:ident) => (
193 let found = match ($p).token {
194 token::Interpolated(token::$constructor(_)) => {
195 Some(try!(($p).bump_and_get()))
199 if let Some(token::Interpolated(token::$constructor(x))) = found {
200 return Ok((*x).clone());
204 (Some deref $p:expr, $constructor:ident) => (
206 let found = match ($p).token {
207 token::Interpolated(token::$constructor(_)) => {
208 Some(try!(($p).bump_and_get()))
212 if let Some(token::Interpolated(token::$constructor(x))) = found {
213 return Ok(Some((*x).clone()));
217 (pair_empty $p:expr, $constructor:ident) => (
219 let found = match ($p).token {
220 token::Interpolated(token::$constructor(_)) => {
221 Some(try!(($p).bump_and_get()))
225 if let Some(token::Interpolated(token::$constructor(x))) = found {
226 return Ok((Vec::new(), x));
233 fn maybe_append(mut lhs: Vec<Attribute>, rhs: Option<Vec<Attribute>>)
235 if let Some(ref attrs) = rhs {
236 lhs.extend(attrs.iter().cloned())
241 /* ident is handled by common.rs */
243 pub struct Parser<'a> {
244 pub sess: &'a ParseSess,
245 /// the current token:
246 pub token: token::Token,
247 /// the span of the current token:
249 /// the span of the prior token:
251 pub cfg: CrateConfig,
252 /// the previous token or None (only stashed sometimes).
253 pub last_token: Option<Box<token::Token>>,
254 pub buffer: [TokenAndSpan; 4],
255 pub buffer_start: isize,
256 pub buffer_end: isize,
257 pub tokens_consumed: usize,
258 pub restrictions: Restrictions,
259 pub quote_depth: usize, // not (yet) related to the quasiquoter
260 pub reader: Box<Reader+'a>,
261 pub interner: Rc<token::IdentInterner>,
262 /// The set of seen errors about obsolete syntax. Used to suppress
263 /// extra detail when the same error is seen twice
264 pub obsolete_set: HashSet<ObsoleteSyntax>,
265 /// Used to determine the path to externally loaded source files
266 pub mod_path_stack: Vec<InternedString>,
267 /// Stack of spans of open delimiters. Used for error message.
268 pub open_braces: Vec<Span>,
269 /// Flag if this parser "owns" the directory that it is currently parsing
270 /// in. This will affect how nested files are looked up.
271 pub owns_directory: bool,
272 /// Name of the root module this parser originated from. If `None`, then the
273 /// name is not known. This does not change while the parser is descending
274 /// into modules, and sub-parsers have new values for this name.
275 pub root_module_name: Option<String>,
276 pub expected_tokens: Vec<TokenType>,
279 #[derive(PartialEq, Eq, Clone)]
282 Keyword(keywords::Keyword),
287 fn to_string(&self) -> String {
289 TokenType::Token(ref t) => format!("`{}`", Parser::token_to_string(t)),
290 TokenType::Operator => "an operator".to_string(),
291 TokenType::Keyword(kw) => format!("`{}`", token::get_name(kw.to_name())),
296 fn is_plain_ident_or_underscore(t: &token::Token) -> bool {
297 t.is_plain_ident() || *t == token::Underscore
300 impl<'a> Parser<'a> {
301 pub fn new(sess: &'a ParseSess,
302 cfg: ast::CrateConfig,
303 mut rdr: Box<Reader+'a>)
306 let tok0 = rdr.real_token();
308 let placeholder = TokenAndSpan {
309 tok: token::Underscore,
315 interner: token::get_ident_interner(),
331 restrictions: Restrictions::empty(),
333 obsolete_set: HashSet::new(),
334 mod_path_stack: Vec::new(),
335 open_braces: Vec::new(),
336 owns_directory: true,
337 root_module_name: None,
338 expected_tokens: Vec::new(),
342 // Panicing fns (for now!)
343 // This is so that the quote_*!() syntax extensions
344 pub fn parse_expr(&mut self) -> P<Expr> {
345 panictry!(self.parse_expr_nopanic())
348 pub fn parse_item(&mut self) -> Option<P<Item>> {
349 panictry!(self.parse_item_nopanic())
352 pub fn parse_pat(&mut self) -> P<Pat> {
353 panictry!(self.parse_pat_nopanic())
356 pub fn parse_arm(&mut self) -> Arm {
357 panictry!(self.parse_arm_nopanic())
360 pub fn parse_ty(&mut self) -> P<Ty> {
361 panictry!(self.parse_ty_nopanic())
364 pub fn parse_stmt(&mut self) -> Option<P<Stmt>> {
365 panictry!(self.parse_stmt_nopanic())
368 /// Convert a token to a string using self's reader
369 pub fn token_to_string(token: &token::Token) -> String {
370 pprust::token_to_string(token)
373 /// Convert the current token to a string using self's reader
374 pub fn this_token_to_string(&self) -> String {
375 Parser::token_to_string(&self.token)
378 pub fn unexpected_last(&self, t: &token::Token) -> FatalError {
379 let token_str = Parser::token_to_string(t);
380 let last_span = self.last_span;
381 self.span_fatal(last_span, &format!("unexpected token: `{}`",
385 pub fn unexpected(&mut self) -> FatalError {
386 match self.expect_one_of(&[], &[]) {
388 Ok(_) => unreachable!()
392 /// Expect and consume the token t. Signal an error if
393 /// the next token is not t.
394 pub fn expect(&mut self, t: &token::Token) -> PResult<()> {
395 if self.expected_tokens.is_empty() {
396 if self.token == *t {
399 let token_str = Parser::token_to_string(t);
400 let this_token_str = self.this_token_to_string();
401 Err(self.fatal(&format!("expected `{}`, found `{}`",
406 self.expect_one_of(slice::ref_slice(t), &[])
410 /// Expect next token to be edible or inedible token. If edible,
411 /// then consume it; if inedible, then return without consuming
412 /// anything. Signal a fatal error if next token is unexpected.
413 pub fn expect_one_of(&mut self,
414 edible: &[token::Token],
415 inedible: &[token::Token]) -> PResult<()>{
416 fn tokens_to_string(tokens: &[TokenType]) -> String {
417 let mut i = tokens.iter();
418 // This might be a sign we need a connect method on Iterator.
420 .map_or("".to_string(), |t| t.to_string());
421 i.enumerate().fold(b, |mut b, (i, ref a)| {
422 if tokens.len() > 2 && i == tokens.len() - 2 {
424 } else if tokens.len() == 2 && i == tokens.len() - 2 {
429 b.push_str(&*a.to_string());
433 if edible.contains(&self.token) {
435 } else if inedible.contains(&self.token) {
436 // leave it in the input
439 let mut expected = edible.iter()
440 .map(|x| TokenType::Token(x.clone()))
441 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
442 .chain(self.expected_tokens.iter().cloned())
443 .collect::<Vec<_>>();
444 expected.sort_by(|a, b| a.to_string().cmp(&b.to_string()));
446 let expect = tokens_to_string(&expected[..]);
447 let actual = self.this_token_to_string();
449 &(if expected.len() > 1 {
450 (format!("expected one of {}, found `{}`",
453 } else if expected.is_empty() {
454 (format!("unexpected token: `{}`",
457 (format!("expected {}, found `{}`",
465 /// Check for erroneous `ident { }`; if matches, signal error and
466 /// recover (without consuming any expected input token). Returns
467 /// true if and only if input was consumed for recovery.
468 pub fn check_for_erroneous_unit_struct_expecting(&mut self,
469 expected: &[token::Token])
471 if self.token == token::OpenDelim(token::Brace)
472 && expected.iter().all(|t| *t != token::OpenDelim(token::Brace))
473 && self.look_ahead(1, |t| *t == token::CloseDelim(token::Brace)) {
474 // matched; signal non-fatal error and recover.
475 let span = self.span;
477 "unit-like struct construction is written with no trailing `{ }`");
478 try!(self.eat(&token::OpenDelim(token::Brace)));
479 try!(self.eat(&token::CloseDelim(token::Brace)));
486 /// Commit to parsing a complete expression `e` expected to be
487 /// followed by some token from the set edible + inedible. Recover
488 /// from anticipated input errors, discarding erroneous characters.
489 pub fn commit_expr(&mut self, e: &Expr, edible: &[token::Token],
490 inedible: &[token::Token]) -> PResult<()> {
491 debug!("commit_expr {:?}", e);
492 if let ExprPath(..) = e.node {
493 // might be unit-struct construction; check for recoverableinput error.
494 let expected = edible.iter()
496 .chain(inedible.iter().cloned())
497 .collect::<Vec<_>>();
498 try!(self.check_for_erroneous_unit_struct_expecting(&expected[..]));
500 self.expect_one_of(edible, inedible)
503 pub fn commit_expr_expecting(&mut self, e: &Expr, edible: token::Token) -> PResult<()> {
504 self.commit_expr(e, &[edible], &[])
507 /// Commit to parsing a complete statement `s`, which expects to be
508 /// followed by some token from the set edible + inedible. Check
509 /// for recoverable input errors, discarding erroneous characters.
510 pub fn commit_stmt(&mut self, edible: &[token::Token],
511 inedible: &[token::Token]) -> PResult<()> {
514 .map_or(false, |t| t.is_ident() || t.is_path()) {
515 let expected = edible.iter()
517 .chain(inedible.iter().cloned())
518 .collect::<Vec<_>>();
519 try!(self.check_for_erroneous_unit_struct_expecting(&expected));
521 self.expect_one_of(edible, inedible)
524 pub fn commit_stmt_expecting(&mut self, edible: token::Token) -> PResult<()> {
525 self.commit_stmt(&[edible], &[])
528 pub fn parse_ident(&mut self) -> PResult<ast::Ident> {
529 self.check_strict_keywords();
530 try!(self.check_reserved_keywords());
532 token::Ident(i, _) => {
536 token::Interpolated(token::NtIdent(..)) => {
537 self.bug("ident interpolation not converted to real token");
540 let token_str = self.this_token_to_string();
541 Err(self.fatal(&format!("expected ident, found `{}`",
547 pub fn parse_ident_or_self_type(&mut self) -> PResult<ast::Ident> {
548 if self.is_self_type_ident() {
549 self.expect_self_type_ident()
555 pub fn parse_path_list_item(&mut self) -> PResult<ast::PathListItem> {
556 let lo = self.span.lo;
557 let node = if try!(self.eat_keyword(keywords::SelfValue)) {
558 ast::PathListMod { id: ast::DUMMY_NODE_ID }
560 let ident = try!(self.parse_ident());
561 ast::PathListIdent { name: ident, id: ast::DUMMY_NODE_ID }
563 let hi = self.last_span.hi;
564 Ok(spanned(lo, hi, node))
567 /// Check if the next token is `tok`, and return `true` if so.
569 /// This method is will automatically add `tok` to `expected_tokens` if `tok` is not
571 pub fn check(&mut self, tok: &token::Token) -> bool {
572 let is_present = self.token == *tok;
573 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
577 /// Consume token 'tok' if it exists. Returns true if the given
578 /// token was present, false otherwise.
579 pub fn eat(&mut self, tok: &token::Token) -> PResult<bool> {
580 let is_present = self.check(tok);
581 if is_present { try!(self.bump())}
585 pub fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
586 self.expected_tokens.push(TokenType::Keyword(kw));
587 self.token.is_keyword(kw)
590 /// If the next token is the given keyword, eat it and return
591 /// true. Otherwise, return false.
592 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> PResult<bool> {
593 if self.check_keyword(kw) {
601 pub fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> PResult<bool> {
602 if self.token.is_keyword(kw) {
610 /// If the given word is not a keyword, signal an error.
611 /// If the next token is not the given word, signal an error.
612 /// Otherwise, eat it.
613 pub fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<()> {
614 if !try!(self.eat_keyword(kw) ){
615 self.expect_one_of(&[], &[])
621 /// Signal an error if the given string is a strict keyword
622 pub fn check_strict_keywords(&mut self) {
623 if self.token.is_strict_keyword() {
624 let token_str = self.this_token_to_string();
625 let span = self.span;
627 &format!("expected identifier, found keyword `{}`",
632 /// Signal an error if the current token is a reserved keyword
633 pub fn check_reserved_keywords(&mut self) -> PResult<()>{
634 if self.token.is_reserved_keyword() {
635 let token_str = self.this_token_to_string();
636 Err(self.fatal(&format!("`{}` is a reserved keyword",
643 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
644 /// `&` and continue. If an `&` is not seen, signal an error.
645 fn expect_and(&mut self) -> PResult<()> {
646 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
648 token::BinOp(token::And) => self.bump(),
650 let span = self.span;
651 let lo = span.lo + BytePos(1);
652 Ok(self.replace_token(token::BinOp(token::And), lo, span.hi))
654 _ => self.expect_one_of(&[], &[])
658 pub fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
660 None => {/* everything ok */}
662 let text = suf.as_str();
664 self.span_bug(sp, "found empty literal suffix in Some")
666 self.span_err(sp, &*format!("{} with a suffix is illegal", kind));
672 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
673 /// `<` and continue. If a `<` is not seen, return false.
675 /// This is meant to be used when parsing generics on a path to get the
677 fn eat_lt(&mut self) -> PResult<bool> {
678 self.expected_tokens.push(TokenType::Token(token::Lt));
680 token::Lt => { try!(self.bump()); Ok(true)}
681 token::BinOp(token::Shl) => {
682 let span = self.span;
683 let lo = span.lo + BytePos(1);
684 self.replace_token(token::Lt, lo, span.hi);
691 fn expect_lt(&mut self) -> PResult<()> {
692 if !try!(self.eat_lt()) {
693 self.expect_one_of(&[], &[])
699 /// Expect and consume a GT. if a >> is seen, replace it
700 /// with a single > and continue. If a GT is not seen,
702 pub fn expect_gt(&mut self) -> PResult<()> {
703 self.expected_tokens.push(TokenType::Token(token::Gt));
705 token::Gt => self.bump(),
706 token::BinOp(token::Shr) => {
707 let span = self.span;
708 let lo = span.lo + BytePos(1);
709 Ok(self.replace_token(token::Gt, lo, span.hi))
711 token::BinOpEq(token::Shr) => {
712 let span = self.span;
713 let lo = span.lo + BytePos(1);
714 Ok(self.replace_token(token::Ge, lo, span.hi))
717 let span = self.span;
718 let lo = span.lo + BytePos(1);
719 Ok(self.replace_token(token::Eq, lo, span.hi))
722 let gt_str = Parser::token_to_string(&token::Gt);
723 let this_token_str = self.this_token_to_string();
724 Err(self.fatal(&format!("expected `{}`, found `{}`",
731 pub fn parse_seq_to_before_gt_or_return<T, F>(&mut self,
732 sep: Option<token::Token>,
734 -> PResult<(OwnedSlice<T>, bool)> where
735 F: FnMut(&mut Parser) -> PResult<Option<T>>,
737 let mut v = Vec::new();
738 // This loop works by alternating back and forth between parsing types
739 // and commas. For example, given a string `A, B,>`, the parser would
740 // first parse `A`, then a comma, then `B`, then a comma. After that it
741 // would encounter a `>` and stop. This lets the parser handle trailing
742 // commas in generic parameters, because it can stop either after
743 // parsing a type or after parsing a comma.
745 if self.check(&token::Gt)
746 || self.token == token::BinOp(token::Shr)
747 || self.token == token::Ge
748 || self.token == token::BinOpEq(token::Shr) {
753 match try!(f(self)) {
754 Some(result) => v.push(result),
755 None => return Ok((OwnedSlice::from_vec(v), true))
758 if let Some(t) = sep.as_ref() {
759 try!(self.expect(t));
764 return Ok((OwnedSlice::from_vec(v), false));
767 /// Parse a sequence bracketed by '<' and '>', stopping
769 pub fn parse_seq_to_before_gt<T, F>(&mut self,
770 sep: Option<token::Token>,
772 -> PResult<OwnedSlice<T>> where
773 F: FnMut(&mut Parser) -> PResult<T>,
775 let (result, returned) = try!(self.parse_seq_to_before_gt_or_return(sep,
776 |p| Ok(Some(try!(f(p))))));
781 pub fn parse_seq_to_gt<T, F>(&mut self,
782 sep: Option<token::Token>,
784 -> PResult<OwnedSlice<T>> where
785 F: FnMut(&mut Parser) -> PResult<T>,
787 let v = try!(self.parse_seq_to_before_gt(sep, f));
788 try!(self.expect_gt());
792 pub fn parse_seq_to_gt_or_return<T, F>(&mut self,
793 sep: Option<token::Token>,
795 -> PResult<(OwnedSlice<T>, bool)> where
796 F: FnMut(&mut Parser) -> PResult<Option<T>>,
798 let (v, returned) = try!(self.parse_seq_to_before_gt_or_return(sep, f));
800 try!(self.expect_gt());
802 return Ok((v, returned));
805 /// Parse a sequence, including the closing delimiter. The function
806 /// f must consume tokens until reaching the next separator or
808 pub fn parse_seq_to_end<T, F>(&mut self,
812 -> PResult<Vec<T>> where
813 F: FnMut(&mut Parser) -> PResult<T>,
815 let val = try!(self.parse_seq_to_before_end(ket, sep, f));
820 /// Parse a sequence, not including the closing delimiter. The function
821 /// f must consume tokens until reaching the next separator or
823 pub fn parse_seq_to_before_end<T, F>(&mut self,
827 -> PResult<Vec<T>> where
828 F: FnMut(&mut Parser) -> PResult<T>,
830 let mut first: bool = true;
832 while self.token != *ket {
835 if first { first = false; }
836 else { try!(self.expect(t)); }
840 if sep.trailing_sep_allowed && self.check(ket) { break; }
841 v.push(try!(f(self)));
846 /// Parse a sequence, including the closing delimiter. The function
847 /// f must consume tokens until reaching the next separator or
849 pub fn parse_unspanned_seq<T, F>(&mut self,
854 -> PResult<Vec<T>> where
855 F: FnMut(&mut Parser) -> PResult<T>,
857 try!(self.expect(bra));
858 let result = try!(self.parse_seq_to_before_end(ket, sep, f));
863 /// Parse a sequence parameter of enum variant. For consistency purposes,
864 /// these should not be empty.
865 pub fn parse_enum_variant_seq<T, F>(&mut self,
870 -> PResult<Vec<T>> where
871 F: FnMut(&mut Parser) -> PResult<T>,
873 let result = try!(self.parse_unspanned_seq(bra, ket, sep, f));
874 if result.is_empty() {
875 let last_span = self.last_span;
876 self.span_err(last_span,
877 "nullary enum variants are written with no trailing `( )`");
882 // NB: Do not use this function unless you actually plan to place the
883 // spanned list in the AST.
884 pub fn parse_seq<T, F>(&mut self,
889 -> PResult<Spanned<Vec<T>>> where
890 F: FnMut(&mut Parser) -> PResult<T>,
892 let lo = self.span.lo;
893 try!(self.expect(bra));
894 let result = try!(self.parse_seq_to_before_end(ket, sep, f));
895 let hi = self.span.hi;
897 Ok(spanned(lo, hi, result))
900 /// Advance the parser by one token
901 pub fn bump(&mut self) -> PResult<()> {
902 self.last_span = self.span;
903 // Stash token for error recovery (sometimes; clone is not necessarily cheap).
904 self.last_token = if self.token.is_ident() ||
905 self.token.is_path() ||
906 self.token == token::Comma {
907 Some(Box::new(self.token.clone()))
911 let next = if self.buffer_start == self.buffer_end {
912 self.reader.real_token()
914 // Avoid token copies with `replace`.
915 let buffer_start = self.buffer_start as usize;
916 let next_index = (buffer_start + 1) & 3;
917 self.buffer_start = next_index as isize;
919 let placeholder = TokenAndSpan {
920 tok: token::Underscore,
923 mem::replace(&mut self.buffer[buffer_start], placeholder)
926 self.token = next.tok;
927 self.tokens_consumed += 1;
928 self.expected_tokens.clear();
929 // check after each token
930 self.check_unknown_macro_variable()
933 /// Advance the parser by one token and return the bumped token.
934 pub fn bump_and_get(&mut self) -> PResult<token::Token> {
935 let old_token = mem::replace(&mut self.token, token::Underscore);
940 /// EFFECT: replace the current token and span with the given one
941 pub fn replace_token(&mut self,
945 self.last_span = mk_sp(self.span.lo, lo);
947 self.span = mk_sp(lo, hi);
949 pub fn buffer_length(&mut self) -> isize {
950 if self.buffer_start <= self.buffer_end {
951 return self.buffer_end - self.buffer_start;
953 return (4 - self.buffer_start) + self.buffer_end;
955 pub fn look_ahead<R, F>(&mut self, distance: usize, f: F) -> R where
956 F: FnOnce(&token::Token) -> R,
958 let dist = distance as isize;
959 while self.buffer_length() < dist {
960 self.buffer[self.buffer_end as usize] = self.reader.real_token();
961 self.buffer_end = (self.buffer_end + 1) & 3;
963 f(&self.buffer[((self.buffer_start + dist - 1) & 3) as usize].tok)
965 pub fn fatal(&self, m: &str) -> diagnostic::FatalError {
966 self.sess.span_diagnostic.span_fatal(self.span, m)
968 pub fn span_fatal(&self, sp: Span, m: &str) -> diagnostic::FatalError {
969 self.sess.span_diagnostic.span_fatal(sp, m)
971 pub fn span_fatal_help(&self, sp: Span, m: &str, help: &str) -> diagnostic::FatalError {
972 self.span_err(sp, m);
973 self.fileline_help(sp, help);
974 diagnostic::FatalError
976 pub fn span_note(&self, sp: Span, m: &str) {
977 self.sess.span_diagnostic.span_note(sp, m)
979 pub fn span_help(&self, sp: Span, m: &str) {
980 self.sess.span_diagnostic.span_help(sp, m)
982 pub fn span_suggestion(&self, sp: Span, m: &str, n: String) {
983 self.sess.span_diagnostic.span_suggestion(sp, m, n)
985 pub fn fileline_help(&self, sp: Span, m: &str) {
986 self.sess.span_diagnostic.fileline_help(sp, m)
988 pub fn bug(&self, m: &str) -> ! {
989 self.sess.span_diagnostic.span_bug(self.span, m)
991 pub fn warn(&self, m: &str) {
992 self.sess.span_diagnostic.span_warn(self.span, m)
994 pub fn span_warn(&self, sp: Span, m: &str) {
995 self.sess.span_diagnostic.span_warn(sp, m)
997 pub fn span_err(&self, sp: Span, m: &str) {
998 self.sess.span_diagnostic.span_err(sp, m)
1000 pub fn span_bug(&self, sp: Span, m: &str) -> ! {
1001 self.sess.span_diagnostic.span_bug(sp, m)
1003 pub fn abort_if_errors(&self) {
1004 self.sess.span_diagnostic.handler().abort_if_errors();
1007 pub fn id_to_interned_str(&mut self, id: Ident) -> InternedString {
1008 token::get_ident(id)
1011 /// Is the current token one of the keywords that signals a bare function
1013 pub fn token_is_bare_fn_keyword(&mut self) -> bool {
1014 self.check_keyword(keywords::Fn) ||
1015 self.check_keyword(keywords::Unsafe) ||
1016 self.check_keyword(keywords::Extern)
1019 pub fn get_lifetime(&mut self) -> ast::Ident {
1021 token::Lifetime(ref ident) => *ident,
1022 _ => self.bug("not a lifetime"),
1026 pub fn parse_for_in_type(&mut self) -> PResult<Ty_> {
1028 Parses whatever can come after a `for` keyword in a type.
1029 The `for` has already been consumed.
1033 - for <'lt> |S| -> T
1037 - for <'lt> [unsafe] [extern "ABI"] fn (S) -> T
1038 - for <'lt> path::foo(a, b)
1043 let lo = self.span.lo;
1045 let lifetime_defs = try!(self.parse_late_bound_lifetime_defs());
1047 // examine next token to decide to do
1048 if self.token_is_bare_fn_keyword() {
1049 self.parse_ty_bare_fn(lifetime_defs)
1051 let hi = self.span.hi;
1052 let trait_ref = try!(self.parse_trait_ref());
1053 let poly_trait_ref = ast::PolyTraitRef { bound_lifetimes: lifetime_defs,
1054 trait_ref: trait_ref,
1055 span: mk_sp(lo, hi)};
1056 let other_bounds = if try!(self.eat(&token::BinOp(token::Plus)) ){
1057 try!(self.parse_ty_param_bounds(BoundParsingMode::Bare))
1062 Some(TraitTyParamBound(poly_trait_ref, TraitBoundModifier::None)).into_iter()
1063 .chain(other_bounds.into_vec())
1065 Ok(ast::TyPolyTraitRef(all_bounds))
1069 pub fn parse_ty_path(&mut self) -> PResult<Ty_> {
1070 Ok(TyPath(None, try!(self.parse_path(LifetimeAndTypesWithoutColons))))
1073 /// parse a TyBareFn type:
1074 pub fn parse_ty_bare_fn(&mut self, lifetime_defs: Vec<ast::LifetimeDef>) -> PResult<Ty_> {
1077 [unsafe] [extern "ABI"] fn <'lt> (S) -> T
1078 ^~~~^ ^~~~^ ^~~~^ ^~^ ^
1081 | | | Argument types
1087 let unsafety = try!(self.parse_unsafety());
1088 let abi = if try!(self.eat_keyword(keywords::Extern) ){
1089 try!(self.parse_opt_abi()).unwrap_or(abi::C)
1094 try!(self.expect_keyword(keywords::Fn));
1095 let (inputs, variadic) = try!(self.parse_fn_args(false, true));
1096 let ret_ty = try!(self.parse_ret_ty());
1097 let decl = P(FnDecl {
1102 Ok(TyBareFn(P(BareFnTy {
1105 lifetimes: lifetime_defs,
1110 /// Parses an obsolete closure kind (`&:`, `&mut:`, or `:`).
1111 pub fn parse_obsolete_closure_kind(&mut self) -> PResult<()> {
1112 let lo = self.span.lo;
1114 self.check(&token::BinOp(token::And)) &&
1115 self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
1116 self.look_ahead(2, |t| *t == token::Colon)
1122 self.token == token::BinOp(token::And) &&
1123 self.look_ahead(1, |t| *t == token::Colon)
1128 try!(self.eat(&token::Colon))
1135 let span = mk_sp(lo, self.span.hi);
1136 self.obsolete(span, ObsoleteSyntax::ClosureKind);
1140 pub fn parse_unsafety(&mut self) -> PResult<Unsafety> {
1141 if try!(self.eat_keyword(keywords::Unsafe)) {
1142 return Ok(Unsafety::Unsafe);
1144 return Ok(Unsafety::Normal);
1148 /// Parse the items in a trait declaration
1149 pub fn parse_trait_items(&mut self) -> PResult<Vec<P<TraitItem>>> {
1150 self.parse_unspanned_seq(
1151 &token::OpenDelim(token::Brace),
1152 &token::CloseDelim(token::Brace),
1154 |p| -> PResult<P<TraitItem>> {
1155 maybe_whole!(no_clone p, NtTraitItem);
1156 let mut attrs = p.parse_outer_attributes();
1159 let (name, node) = if try!(p.eat_keyword(keywords::Type)) {
1160 let TyParam {ident, bounds, default, ..} = try!(p.parse_ty_param());
1161 try!(p.expect(&token::Semi));
1162 (ident, TypeTraitItem(bounds, default))
1163 } else if p.is_const_item() {
1164 try!(p.expect_keyword(keywords::Const));
1165 let ident = try!(p.parse_ident());
1166 try!(p.expect(&token::Colon));
1167 let ty = try!(p.parse_ty_sum());
1168 let default = if p.check(&token::Eq) {
1170 let expr = try!(p.parse_expr_nopanic());
1171 try!(p.commit_expr_expecting(&expr, token::Semi));
1174 try!(p.expect(&token::Semi));
1177 (ident, ConstTraitItem(ty, default))
1179 let (constness, unsafety, abi) = try!(p.parse_fn_front_matter());
1181 let ident = try!(p.parse_ident());
1182 let mut generics = try!(p.parse_generics());
1184 let (explicit_self, d) = try!(p.parse_fn_decl_with_self(|p|{
1185 // This is somewhat dubious; We don't want to allow
1186 // argument names to be left off if there is a
1188 p.parse_arg_general(false)
1191 generics.where_clause = try!(p.parse_where_clause());
1192 let sig = ast::MethodSig {
1194 constness: constness,
1198 explicit_self: explicit_self,
1201 let body = match p.token {
1204 debug!("parse_trait_methods(): parsing required method");
1207 token::OpenDelim(token::Brace) => {
1208 debug!("parse_trait_methods(): parsing provided method");
1209 let (inner_attrs, body) =
1210 try!(p.parse_inner_attrs_and_block());
1211 attrs.extend(inner_attrs.iter().cloned());
1216 let token_str = p.this_token_to_string();
1217 return Err(p.fatal(&format!("expected `;` or `{{`, found `{}`",
1221 (ident, ast::MethodTraitItem(sig, body))
1225 id: ast::DUMMY_NODE_ID,
1229 span: mk_sp(lo, p.last_span.hi),
1234 /// Parse a possibly mutable type
1235 pub fn parse_mt(&mut self) -> PResult<MutTy> {
1236 let mutbl = try!(self.parse_mutability());
1237 let t = try!(self.parse_ty_nopanic());
1238 Ok(MutTy { ty: t, mutbl: mutbl })
1241 /// Parse optional return type [ -> TY ] in function decl
1242 pub fn parse_ret_ty(&mut self) -> PResult<FunctionRetTy> {
1243 if try!(self.eat(&token::RArrow) ){
1244 if try!(self.eat(&token::Not) ){
1245 Ok(NoReturn(self.span))
1247 Ok(Return(try!(self.parse_ty_nopanic())))
1250 let pos = self.span.lo;
1251 Ok(DefaultReturn(mk_sp(pos, pos)))
1255 /// Parse a type in a context where `T1+T2` is allowed.
1256 pub fn parse_ty_sum(&mut self) -> PResult<P<Ty>> {
1257 let lo = self.span.lo;
1258 let lhs = try!(self.parse_ty_nopanic());
1260 if !try!(self.eat(&token::BinOp(token::Plus)) ){
1264 let bounds = try!(self.parse_ty_param_bounds(BoundParsingMode::Bare));
1266 // In type grammar, `+` is treated like a binary operator,
1267 // and hence both L and R side are required.
1268 if bounds.is_empty() {
1269 let last_span = self.last_span;
1270 self.span_err(last_span,
1271 "at least one type parameter bound \
1272 must be specified");
1275 let sp = mk_sp(lo, self.last_span.hi);
1276 let sum = ast::TyObjectSum(lhs, bounds);
1277 Ok(P(Ty {id: ast::DUMMY_NODE_ID, node: sum, span: sp}))
1281 pub fn parse_ty_nopanic(&mut self) -> PResult<P<Ty>> {
1282 maybe_whole!(no_clone self, NtTy);
1284 let lo = self.span.lo;
1286 let t = if self.check(&token::OpenDelim(token::Paren)) {
1289 // (t) is a parenthesized ty
1290 // (t,) is the type of a tuple with only one field,
1292 let mut ts = vec![];
1293 let mut last_comma = false;
1294 while self.token != token::CloseDelim(token::Paren) {
1295 ts.push(try!(self.parse_ty_sum()));
1296 if self.check(&token::Comma) {
1305 try!(self.expect(&token::CloseDelim(token::Paren)));
1306 if ts.len() == 1 && !last_comma {
1307 TyParen(ts.into_iter().nth(0).unwrap())
1311 } else if self.check(&token::BinOp(token::Star)) {
1312 // STAR POINTER (bare pointer?)
1314 TyPtr(try!(self.parse_ptr()))
1315 } else if self.check(&token::OpenDelim(token::Bracket)) {
1317 try!(self.expect(&token::OpenDelim(token::Bracket)));
1318 let t = try!(self.parse_ty_sum());
1320 // Parse the `; e` in `[ i32; e ]`
1321 // where `e` is a const expression
1322 let t = match try!(self.maybe_parse_fixed_length_of_vec()) {
1324 Some(suffix) => TyFixedLengthVec(t, suffix)
1326 try!(self.expect(&token::CloseDelim(token::Bracket)));
1328 } else if self.check(&token::BinOp(token::And)) ||
1329 self.token == token::AndAnd {
1331 try!(self.expect_and());
1332 try!(self.parse_borrowed_pointee())
1333 } else if self.check_keyword(keywords::For) {
1334 try!(self.parse_for_in_type())
1335 } else if self.token_is_bare_fn_keyword() {
1337 try!(self.parse_ty_bare_fn(Vec::new()))
1338 } else if try!(self.eat_keyword_noexpect(keywords::Typeof)) {
1340 // In order to not be ambiguous, the type must be surrounded by parens.
1341 try!(self.expect(&token::OpenDelim(token::Paren)));
1342 let e = try!(self.parse_expr_nopanic());
1343 try!(self.expect(&token::CloseDelim(token::Paren)));
1345 } else if try!(self.eat_lt()) {
1348 try!(self.parse_qualified_path(NoTypesAllowed));
1350 TyPath(Some(qself), path)
1351 } else if self.check(&token::ModSep) ||
1352 self.token.is_ident() ||
1353 self.token.is_path() {
1355 try!(self.parse_ty_path())
1356 } else if try!(self.eat(&token::Underscore) ){
1357 // TYPE TO BE INFERRED
1360 let this_token_str = self.this_token_to_string();
1361 let msg = format!("expected type, found `{}`", this_token_str);
1362 return Err(self.fatal(&msg[..]));
1365 let sp = mk_sp(lo, self.last_span.hi);
1366 Ok(P(Ty {id: ast::DUMMY_NODE_ID, node: t, span: sp}))
1369 pub fn parse_borrowed_pointee(&mut self) -> PResult<Ty_> {
1370 // look for `&'lt` or `&'foo ` and interpret `foo` as the region name:
1371 let opt_lifetime = try!(self.parse_opt_lifetime());
1373 let mt = try!(self.parse_mt());
1374 return Ok(TyRptr(opt_lifetime, mt));
1377 pub fn parse_ptr(&mut self) -> PResult<MutTy> {
1378 let mutbl = if try!(self.eat_keyword(keywords::Mut) ){
1380 } else if try!(self.eat_keyword(keywords::Const) ){
1383 let span = self.last_span;
1385 "bare raw pointers are no longer allowed, you should \
1386 likely use `*mut T`, but otherwise `*T` is now \
1387 known as `*const T`");
1390 let t = try!(self.parse_ty_nopanic());
1391 Ok(MutTy { ty: t, mutbl: mutbl })
1394 pub fn is_named_argument(&mut self) -> bool {
1395 let offset = match self.token {
1396 token::BinOp(token::And) => 1,
1398 _ if self.token.is_keyword(keywords::Mut) => 1,
1402 debug!("parser is_named_argument offset:{}", offset);
1405 is_plain_ident_or_underscore(&self.token)
1406 && self.look_ahead(1, |t| *t == token::Colon)
1408 self.look_ahead(offset, |t| is_plain_ident_or_underscore(t))
1409 && self.look_ahead(offset + 1, |t| *t == token::Colon)
1413 /// This version of parse arg doesn't necessarily require
1414 /// identifier names.
1415 pub fn parse_arg_general(&mut self, require_name: bool) -> PResult<Arg> {
1416 let pat = if require_name || self.is_named_argument() {
1417 debug!("parse_arg_general parse_pat (require_name:{})",
1419 let pat = try!(self.parse_pat_nopanic());
1421 try!(self.expect(&token::Colon));
1424 debug!("parse_arg_general ident_to_pat");
1425 ast_util::ident_to_pat(ast::DUMMY_NODE_ID,
1427 special_idents::invalid)
1430 let t = try!(self.parse_ty_sum());
1435 id: ast::DUMMY_NODE_ID,
1439 /// Parse a single function argument
1440 pub fn parse_arg(&mut self) -> PResult<Arg> {
1441 self.parse_arg_general(true)
1444 /// Parse an argument in a lambda header e.g. |arg, arg|
1445 pub fn parse_fn_block_arg(&mut self) -> PResult<Arg> {
1446 let pat = try!(self.parse_pat_nopanic());
1447 let t = if try!(self.eat(&token::Colon) ){
1448 try!(self.parse_ty_sum())
1451 id: ast::DUMMY_NODE_ID,
1453 span: mk_sp(self.span.lo, self.span.hi),
1459 id: ast::DUMMY_NODE_ID
1463 pub fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<Option<P<ast::Expr>>> {
1464 if self.check(&token::Semi) {
1466 Ok(Some(try!(self.parse_expr_nopanic())))
1472 /// Matches token_lit = LIT_INTEGER | ...
1473 pub fn lit_from_token(&self, tok: &token::Token) -> PResult<Lit_> {
1475 token::Interpolated(token::NtExpr(ref v)) => {
1477 ExprLit(ref lit) => { Ok(lit.node.clone()) }
1478 _ => { return Err(self.unexpected_last(tok)); }
1481 token::Literal(lit, suf) => {
1482 let (suffix_illegal, out) = match lit {
1483 token::Byte(i) => (true, LitByte(parse::byte_lit(i.as_str()).0)),
1484 token::Char(i) => (true, LitChar(parse::char_lit(i.as_str()).0)),
1486 // there are some valid suffixes for integer and
1487 // float literals, so all the handling is done
1489 token::Integer(s) => {
1490 (false, parse::integer_lit(s.as_str(),
1491 suf.as_ref().map(|s| s.as_str()),
1492 &self.sess.span_diagnostic,
1495 token::Float(s) => {
1496 (false, parse::float_lit(s.as_str(),
1497 suf.as_ref().map(|s| s.as_str()),
1498 &self.sess.span_diagnostic,
1504 LitStr(token::intern_and_get_ident(&parse::str_lit(s.as_str())),
1507 token::StrRaw(s, n) => {
1510 token::intern_and_get_ident(&parse::raw_str_lit(s.as_str())),
1514 (true, LitBinary(parse::binary_lit(i.as_str()))),
1515 token::BinaryRaw(i, _) =>
1517 LitBinary(Rc::new(i.as_str().as_bytes().iter().cloned().collect()))),
1521 let sp = self.last_span;
1522 self.expect_no_suffix(sp, &*format!("{} literal", lit.short_name()), suf)
1527 _ => { return Err(self.unexpected_last(tok)); }
1531 /// Matches lit = true | false | token_lit
1532 pub fn parse_lit(&mut self) -> PResult<Lit> {
1533 let lo = self.span.lo;
1534 let lit = if try!(self.eat_keyword(keywords::True) ){
1536 } else if try!(self.eat_keyword(keywords::False) ){
1539 let token = try!(self.bump_and_get());
1540 let lit = try!(self.lit_from_token(&token));
1543 Ok(codemap::Spanned { node: lit, span: mk_sp(lo, self.last_span.hi) })
1546 /// matches '-' lit | lit
1547 pub fn parse_literal_maybe_minus(&mut self) -> PResult<P<Expr>> {
1548 let minus_lo = self.span.lo;
1549 let minus_present = try!(self.eat(&token::BinOp(token::Minus)));
1551 let lo = self.span.lo;
1552 let literal = P(try!(self.parse_lit()));
1553 let hi = self.span.hi;
1554 let expr = self.mk_expr(lo, hi, ExprLit(literal));
1557 let minus_hi = self.span.hi;
1558 let unary = self.mk_unary(UnNeg, expr);
1559 Ok(self.mk_expr(minus_lo, minus_hi, unary))
1565 // QUALIFIED PATH `<TYPE [as TRAIT_REF]>::IDENT[::<PARAMS>]`
1566 // Assumes that the leading `<` has been parsed already.
1567 pub fn parse_qualified_path(&mut self, mode: PathParsingMode)
1568 -> PResult<(QSelf, ast::Path)> {
1569 let span = self.last_span;
1570 let self_type = try!(self.parse_ty_sum());
1571 let mut path = if try!(self.eat_keyword(keywords::As)) {
1572 try!(self.parse_path(LifetimeAndTypesWithoutColons))
1583 position: path.segments.len()
1586 try!(self.expect(&token::Gt));
1587 try!(self.expect(&token::ModSep));
1589 let segments = match mode {
1590 LifetimeAndTypesWithoutColons => {
1591 try!(self.parse_path_segments_without_colons())
1593 LifetimeAndTypesWithColons => {
1594 try!(self.parse_path_segments_with_colons())
1597 try!(self.parse_path_segments_without_types())
1600 path.segments.extend(segments);
1602 path.span.hi = self.last_span.hi;
1607 /// Parses a path and optional type parameter bounds, depending on the
1608 /// mode. The `mode` parameter determines whether lifetimes, types, and/or
1609 /// bounds are permitted and whether `::` must precede type parameter
1611 pub fn parse_path(&mut self, mode: PathParsingMode) -> PResult<ast::Path> {
1612 // Check for a whole path...
1613 let found = match self.token {
1614 token::Interpolated(token::NtPath(_)) => Some(try!(self.bump_and_get())),
1617 if let Some(token::Interpolated(token::NtPath(path))) = found {
1621 let lo = self.span.lo;
1622 let is_global = try!(self.eat(&token::ModSep));
1624 // Parse any number of segments and bound sets. A segment is an
1625 // identifier followed by an optional lifetime and a set of types.
1626 // A bound set is a set of type parameter bounds.
1627 let segments = match mode {
1628 LifetimeAndTypesWithoutColons => {
1629 try!(self.parse_path_segments_without_colons())
1631 LifetimeAndTypesWithColons => {
1632 try!(self.parse_path_segments_with_colons())
1635 try!(self.parse_path_segments_without_types())
1639 // Assemble the span.
1640 let span = mk_sp(lo, self.last_span.hi);
1642 // Assemble the result.
1651 /// - `a::b<T,U>::c<V,W>`
1652 /// - `a::b<T,U>::c(V) -> W`
1653 /// - `a::b<T,U>::c(V)`
1654 pub fn parse_path_segments_without_colons(&mut self) -> PResult<Vec<ast::PathSegment>> {
1655 let mut segments = Vec::new();
1657 // First, parse an identifier.
1658 let identifier = try!(self.parse_ident_or_self_type());
1660 // Parse types, optionally.
1661 let parameters = if try!(self.eat_lt() ){
1662 let (lifetimes, types, bindings) = try!(self.parse_generic_values_after_lt());
1664 ast::AngleBracketedParameters(ast::AngleBracketedParameterData {
1665 lifetimes: lifetimes,
1666 types: OwnedSlice::from_vec(types),
1667 bindings: OwnedSlice::from_vec(bindings),
1669 } else if try!(self.eat(&token::OpenDelim(token::Paren)) ){
1670 let lo = self.last_span.lo;
1672 let inputs = try!(self.parse_seq_to_end(
1673 &token::CloseDelim(token::Paren),
1674 seq_sep_trailing_allowed(token::Comma),
1675 |p| p.parse_ty_sum()));
1677 let output_ty = if try!(self.eat(&token::RArrow) ){
1678 Some(try!(self.parse_ty_nopanic()))
1683 let hi = self.last_span.hi;
1685 ast::ParenthesizedParameters(ast::ParenthesizedParameterData {
1686 span: mk_sp(lo, hi),
1691 ast::PathParameters::none()
1694 // Assemble and push the result.
1695 segments.push(ast::PathSegment { identifier: identifier,
1696 parameters: parameters });
1698 // Continue only if we see a `::`
1699 if !try!(self.eat(&token::ModSep) ){
1700 return Ok(segments);
1706 /// - `a::b::<T,U>::c`
1707 pub fn parse_path_segments_with_colons(&mut self) -> PResult<Vec<ast::PathSegment>> {
1708 let mut segments = Vec::new();
1710 // First, parse an identifier.
1711 let identifier = try!(self.parse_ident_or_self_type());
1713 // If we do not see a `::`, stop.
1714 if !try!(self.eat(&token::ModSep) ){
1715 segments.push(ast::PathSegment {
1716 identifier: identifier,
1717 parameters: ast::PathParameters::none()
1719 return Ok(segments);
1722 // Check for a type segment.
1723 if try!(self.eat_lt() ){
1724 // Consumed `a::b::<`, go look for types
1725 let (lifetimes, types, bindings) = try!(self.parse_generic_values_after_lt());
1726 segments.push(ast::PathSegment {
1727 identifier: identifier,
1728 parameters: ast::AngleBracketedParameters(ast::AngleBracketedParameterData {
1729 lifetimes: lifetimes,
1730 types: OwnedSlice::from_vec(types),
1731 bindings: OwnedSlice::from_vec(bindings),
1735 // Consumed `a::b::<T,U>`, check for `::` before proceeding
1736 if !try!(self.eat(&token::ModSep) ){
1737 return Ok(segments);
1740 // Consumed `a::`, go look for `b`
1741 segments.push(ast::PathSegment {
1742 identifier: identifier,
1743 parameters: ast::PathParameters::none(),
1752 pub fn parse_path_segments_without_types(&mut self) -> PResult<Vec<ast::PathSegment>> {
1753 let mut segments = Vec::new();
1755 // First, parse an identifier.
1756 let identifier = try!(self.parse_ident_or_self_type());
1758 // Assemble and push the result.
1759 segments.push(ast::PathSegment {
1760 identifier: identifier,
1761 parameters: ast::PathParameters::none()
1764 // If we do not see a `::`, stop.
1765 if !try!(self.eat(&token::ModSep) ){
1766 return Ok(segments);
1771 /// parses 0 or 1 lifetime
1772 pub fn parse_opt_lifetime(&mut self) -> PResult<Option<ast::Lifetime>> {
1774 token::Lifetime(..) => {
1775 Ok(Some(try!(self.parse_lifetime())))
1783 /// Parses a single lifetime
1784 /// Matches lifetime = LIFETIME
1785 pub fn parse_lifetime(&mut self) -> PResult<ast::Lifetime> {
1787 token::Lifetime(i) => {
1788 let span = self.span;
1790 return Ok(ast::Lifetime {
1791 id: ast::DUMMY_NODE_ID,
1797 return Err(self.fatal(&format!("expected a lifetime name")));
1802 /// Parses `lifetime_defs = [ lifetime_defs { ',' lifetime_defs } ]` where `lifetime_def =
1803 /// lifetime [':' lifetimes]`
1804 pub fn parse_lifetime_defs(&mut self) -> PResult<Vec<ast::LifetimeDef>> {
1806 let mut res = Vec::new();
1809 token::Lifetime(_) => {
1810 let lifetime = try!(self.parse_lifetime());
1812 if try!(self.eat(&token::Colon) ){
1813 try!(self.parse_lifetimes(token::BinOp(token::Plus)))
1817 res.push(ast::LifetimeDef { lifetime: lifetime,
1827 token::Comma => { try!(self.bump());}
1828 token::Gt => { return Ok(res); }
1829 token::BinOp(token::Shr) => { return Ok(res); }
1831 let this_token_str = self.this_token_to_string();
1832 let msg = format!("expected `,` or `>` after lifetime \
1835 return Err(self.fatal(&msg[..]));
1841 /// matches lifetimes = ( lifetime ) | ( lifetime , lifetimes ) actually, it matches the empty
1842 /// one too, but putting that in there messes up the grammar....
1844 /// Parses zero or more comma separated lifetimes. Expects each lifetime to be followed by
1845 /// either a comma or `>`. Used when parsing type parameter lists, where we expect something
1846 /// like `<'a, 'b, T>`.
1847 pub fn parse_lifetimes(&mut self, sep: token::Token) -> PResult<Vec<ast::Lifetime>> {
1849 let mut res = Vec::new();
1852 token::Lifetime(_) => {
1853 res.push(try!(self.parse_lifetime()));
1860 if self.token != sep {
1868 /// Parse mutability declaration (mut/const/imm)
1869 pub fn parse_mutability(&mut self) -> PResult<Mutability> {
1870 if try!(self.eat_keyword(keywords::Mut) ){
1877 /// Parse ident COLON expr
1878 pub fn parse_field(&mut self) -> PResult<Field> {
1879 let lo = self.span.lo;
1880 let i = try!(self.parse_ident());
1881 let hi = self.last_span.hi;
1882 try!(self.expect(&token::Colon));
1883 let e = try!(self.parse_expr_nopanic());
1885 ident: spanned(lo, hi, i),
1886 span: mk_sp(lo, e.span.hi),
1891 pub fn mk_expr(&mut self, lo: BytePos, hi: BytePos, node: Expr_) -> P<Expr> {
1893 id: ast::DUMMY_NODE_ID,
1895 span: mk_sp(lo, hi),
1899 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::Expr_ {
1900 ExprUnary(unop, expr)
1903 pub fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::Expr_ {
1904 ExprBinary(binop, lhs, rhs)
1907 pub fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::Expr_ {
1911 fn mk_method_call(&mut self,
1912 ident: ast::SpannedIdent,
1916 ExprMethodCall(ident, tps, args)
1919 pub fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::Expr_ {
1920 ExprIndex(expr, idx)
1923 pub fn mk_range(&mut self,
1924 start: Option<P<Expr>>,
1925 end: Option<P<Expr>>)
1927 ExprRange(start, end)
1930 pub fn mk_field(&mut self, expr: P<Expr>, ident: ast::SpannedIdent) -> ast::Expr_ {
1931 ExprField(expr, ident)
1934 pub fn mk_tup_field(&mut self, expr: P<Expr>, idx: codemap::Spanned<usize>) -> ast::Expr_ {
1935 ExprTupField(expr, idx)
1938 pub fn mk_assign_op(&mut self, binop: ast::BinOp,
1939 lhs: P<Expr>, rhs: P<Expr>) -> ast::Expr_ {
1940 ExprAssignOp(binop, lhs, rhs)
1943 pub fn mk_mac_expr(&mut self, lo: BytePos, hi: BytePos, m: Mac_) -> P<Expr> {
1945 id: ast::DUMMY_NODE_ID,
1946 node: ExprMac(codemap::Spanned {node: m, span: mk_sp(lo, hi)}),
1947 span: mk_sp(lo, hi),
1951 pub fn mk_lit_u32(&mut self, i: u32) -> P<Expr> {
1952 let span = &self.span;
1953 let lv_lit = P(codemap::Spanned {
1954 node: LitInt(i as u64, ast::UnsignedIntLit(TyU32)),
1959 id: ast::DUMMY_NODE_ID,
1960 node: ExprLit(lv_lit),
1965 fn expect_open_delim(&mut self) -> PResult<token::DelimToken> {
1966 self.expected_tokens.push(TokenType::Token(token::Gt));
1968 token::OpenDelim(delim) => {
1972 _ => Err(self.fatal("expected open delimiter")),
1976 /// At the bottom (top?) of the precedence hierarchy,
1977 /// parse things like parenthesized exprs,
1978 /// macros, return, etc.
1979 pub fn parse_bottom_expr(&mut self) -> PResult<P<Expr>> {
1980 maybe_whole_expr!(self);
1982 let lo = self.span.lo;
1983 let mut hi = self.span.hi;
1987 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
1989 token::OpenDelim(token::Paren) => {
1992 // (e) is parenthesized e
1993 // (e,) is a tuple with only one field, e
1994 let mut es = vec![];
1995 let mut trailing_comma = false;
1996 while self.token != token::CloseDelim(token::Paren) {
1997 es.push(try!(self.parse_expr_nopanic()));
1998 try!(self.commit_expr(&**es.last().unwrap(), &[],
1999 &[token::Comma, token::CloseDelim(token::Paren)]));
2000 if self.check(&token::Comma) {
2001 trailing_comma = true;
2005 trailing_comma = false;
2011 hi = self.last_span.hi;
2012 return if es.len() == 1 && !trailing_comma {
2013 Ok(self.mk_expr(lo, hi, ExprParen(es.into_iter().nth(0).unwrap())))
2015 Ok(self.mk_expr(lo, hi, ExprTup(es)))
2018 token::OpenDelim(token::Brace) => {
2019 return self.parse_block_expr(lo, DefaultBlock);
2021 token::BinOp(token::Or) | token::OrOr => {
2022 let lo = self.span.lo;
2023 return self.parse_lambda_expr(lo, CaptureByRef);
2025 token::Ident(id @ ast::Ident {
2026 name: token::SELF_KEYWORD_NAME,
2028 }, token::Plain) => {
2030 let path = ast_util::ident_to_path(mk_sp(lo, hi), id);
2031 ex = ExprPath(None, path);
2032 hi = self.last_span.hi;
2034 token::OpenDelim(token::Bracket) => {
2037 if self.check(&token::CloseDelim(token::Bracket)) {
2040 ex = ExprVec(Vec::new());
2043 let first_expr = try!(self.parse_expr_nopanic());
2044 if self.check(&token::Semi) {
2045 // Repeating vector syntax: [ 0; 512 ]
2047 let count = try!(self.parse_expr_nopanic());
2048 try!(self.expect(&token::CloseDelim(token::Bracket)));
2049 ex = ExprRepeat(first_expr, count);
2050 } else if self.check(&token::Comma) {
2051 // Vector with two or more elements.
2053 let remaining_exprs = try!(self.parse_seq_to_end(
2054 &token::CloseDelim(token::Bracket),
2055 seq_sep_trailing_allowed(token::Comma),
2056 |p| Ok(try!(p.parse_expr_nopanic()))
2058 let mut exprs = vec!(first_expr);
2059 exprs.extend(remaining_exprs);
2060 ex = ExprVec(exprs);
2062 // Vector with one element.
2063 try!(self.expect(&token::CloseDelim(token::Bracket)));
2064 ex = ExprVec(vec!(first_expr));
2067 hi = self.last_span.hi;
2070 if try!(self.eat_lt()){
2072 try!(self.parse_qualified_path(LifetimeAndTypesWithColons));
2074 return Ok(self.mk_expr(lo, hi, ExprPath(Some(qself), path)));
2076 if try!(self.eat_keyword(keywords::Move) ){
2077 let lo = self.last_span.lo;
2078 return self.parse_lambda_expr(lo, CaptureByValue);
2080 if try!(self.eat_keyword(keywords::If)) {
2081 return self.parse_if_expr();
2083 if try!(self.eat_keyword(keywords::For) ){
2084 return self.parse_for_expr(None);
2086 if try!(self.eat_keyword(keywords::While) ){
2087 return self.parse_while_expr(None);
2089 if self.token.is_lifetime() {
2090 let lifetime = self.get_lifetime();
2092 try!(self.expect(&token::Colon));
2093 if try!(self.eat_keyword(keywords::While) ){
2094 return self.parse_while_expr(Some(lifetime))
2096 if try!(self.eat_keyword(keywords::For) ){
2097 return self.parse_for_expr(Some(lifetime))
2099 if try!(self.eat_keyword(keywords::Loop) ){
2100 return self.parse_loop_expr(Some(lifetime))
2102 return Err(self.fatal("expected `while`, `for`, or `loop` after a label"))
2104 if try!(self.eat_keyword(keywords::Loop) ){
2105 return self.parse_loop_expr(None);
2107 if try!(self.eat_keyword(keywords::Continue) ){
2108 let lo = self.span.lo;
2109 let ex = if self.token.is_lifetime() {
2110 let lifetime = self.get_lifetime();
2112 ExprAgain(Some(lifetime))
2116 let hi = self.span.hi;
2117 return Ok(self.mk_expr(lo, hi, ex));
2119 if try!(self.eat_keyword(keywords::Match) ){
2120 return self.parse_match_expr();
2122 if try!(self.eat_keyword(keywords::Unsafe) ){
2123 return self.parse_block_expr(
2125 UnsafeBlock(ast::UserProvided));
2127 if try!(self.eat_keyword(keywords::Return) ){
2128 // RETURN expression
2129 if self.token.can_begin_expr() {
2130 let e = try!(self.parse_expr_nopanic());
2132 ex = ExprRet(Some(e));
2136 } else if try!(self.eat_keyword(keywords::Break) ){
2138 if self.token.is_lifetime() {
2139 let lifetime = self.get_lifetime();
2141 ex = ExprBreak(Some(lifetime));
2143 ex = ExprBreak(None);
2146 } else if self.check(&token::ModSep) ||
2147 self.token.is_ident() &&
2148 !self.check_keyword(keywords::True) &&
2149 !self.check_keyword(keywords::False) {
2151 try!(self.parse_path(LifetimeAndTypesWithColons));
2153 // `!`, as an operator, is prefix, so we know this isn't that
2154 if self.check(&token::Not) {
2155 // MACRO INVOCATION expression
2158 let delim = try!(self.expect_open_delim());
2159 let tts = try!(self.parse_seq_to_end(
2160 &token::CloseDelim(delim),
2162 |p| p.parse_token_tree()));
2163 let hi = self.last_span.hi;
2165 return Ok(self.mk_mac_expr(lo,
2171 if self.check(&token::OpenDelim(token::Brace)) {
2172 // This is a struct literal, unless we're prohibited
2173 // from parsing struct literals here.
2174 let prohibited = self.restrictions.contains(
2175 Restrictions::RESTRICTION_NO_STRUCT_LITERAL
2178 // It's a struct literal.
2180 let mut fields = Vec::new();
2181 let mut base = None;
2183 while self.token != token::CloseDelim(token::Brace) {
2184 if try!(self.eat(&token::DotDot) ){
2185 base = Some(try!(self.parse_expr_nopanic()));
2189 fields.push(try!(self.parse_field()));
2190 try!(self.commit_expr(&*fields.last().unwrap().expr,
2192 &[token::CloseDelim(token::Brace)]));
2195 if fields.is_empty() && base.is_none() {
2196 let last_span = self.last_span;
2197 self.span_err(last_span,
2198 "structure literal must either \
2199 have at least one field or use \
2200 functional structure update \
2205 try!(self.expect(&token::CloseDelim(token::Brace)));
2206 ex = ExprStruct(pth, fields, base);
2207 return Ok(self.mk_expr(lo, hi, ex));
2212 ex = ExprPath(None, pth);
2214 // other literal expression
2215 let lit = try!(self.parse_lit());
2217 ex = ExprLit(P(lit));
2222 return Ok(self.mk_expr(lo, hi, ex));
2225 /// Parse a block or unsafe block
2226 pub fn parse_block_expr(&mut self, lo: BytePos, blk_mode: BlockCheckMode)
2227 -> PResult<P<Expr>> {
2228 try!(self.expect(&token::OpenDelim(token::Brace)));
2229 let blk = try!(self.parse_block_tail(lo, blk_mode));
2230 return Ok(self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk)));
2233 /// parse a.b or a(13) or a[4] or just a
2234 pub fn parse_dot_or_call_expr(&mut self) -> PResult<P<Expr>> {
2235 let b = try!(self.parse_bottom_expr());
2236 self.parse_dot_or_call_expr_with(b)
2239 pub fn parse_dot_or_call_expr_with(&mut self, e0: P<Expr>) -> PResult<P<Expr>> {
2245 if try!(self.eat(&token::Dot) ){
2247 token::Ident(i, _) => {
2248 let dot = self.last_span.hi;
2251 let (_, tys, bindings) = if try!(self.eat(&token::ModSep) ){
2252 try!(self.expect_lt());
2253 try!(self.parse_generic_values_after_lt())
2255 (Vec::new(), Vec::new(), Vec::new())
2258 if !bindings.is_empty() {
2259 let last_span = self.last_span;
2260 self.span_err(last_span, "type bindings are only permitted on trait paths");
2263 // expr.f() method call
2265 token::OpenDelim(token::Paren) => {
2266 let mut es = try!(self.parse_unspanned_seq(
2267 &token::OpenDelim(token::Paren),
2268 &token::CloseDelim(token::Paren),
2269 seq_sep_trailing_allowed(token::Comma),
2270 |p| Ok(try!(p.parse_expr_nopanic()))
2272 hi = self.last_span.hi;
2275 let id = spanned(dot, hi, i);
2276 let nd = self.mk_method_call(id, tys, es);
2277 e = self.mk_expr(lo, hi, nd);
2280 if !tys.is_empty() {
2281 let last_span = self.last_span;
2282 self.span_err(last_span,
2283 "field expressions may not \
2284 have type parameters");
2287 let id = spanned(dot, hi, i);
2288 let field = self.mk_field(e, id);
2289 e = self.mk_expr(lo, hi, field);
2293 token::Literal(token::Integer(n), suf) => {
2296 // A tuple index may not have a suffix
2297 self.expect_no_suffix(sp, "tuple index", suf);
2299 let dot = self.last_span.hi;
2303 let index = n.as_str().parse::<usize>().ok();
2306 let id = spanned(dot, hi, n);
2307 let field = self.mk_tup_field(e, id);
2308 e = self.mk_expr(lo, hi, field);
2311 let last_span = self.last_span;
2312 self.span_err(last_span, "invalid tuple or tuple struct index");
2316 token::Literal(token::Float(n), _suf) => {
2318 let last_span = self.last_span;
2319 let fstr = n.as_str();
2320 self.span_err(last_span,
2321 &format!("unexpected token: `{}`", n.as_str()));
2322 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2323 let float = match fstr.parse::<f64>().ok() {
2327 self.fileline_help(last_span,
2328 &format!("try parenthesizing the first index; e.g., `(foo.{}){}`",
2329 float.trunc() as usize,
2330 &float.fract().to_string()[1..]));
2332 self.abort_if_errors();
2335 _ => return Err(self.unexpected())
2339 if self.expr_is_complete(&*e) { break; }
2342 token::OpenDelim(token::Paren) => {
2343 let es = try!(self.parse_unspanned_seq(
2344 &token::OpenDelim(token::Paren),
2345 &token::CloseDelim(token::Paren),
2346 seq_sep_trailing_allowed(token::Comma),
2347 |p| Ok(try!(p.parse_expr_nopanic()))
2349 hi = self.last_span.hi;
2351 let nd = self.mk_call(e, es);
2352 e = self.mk_expr(lo, hi, nd);
2356 // Could be either an index expression or a slicing expression.
2357 token::OpenDelim(token::Bracket) => {
2359 let ix = try!(self.parse_expr_nopanic());
2361 try!(self.commit_expr_expecting(&*ix, token::CloseDelim(token::Bracket)));
2362 let index = self.mk_index(e, ix);
2363 e = self.mk_expr(lo, hi, index)
2371 // Parse unquoted tokens after a `$` in a token tree
2372 fn parse_unquoted(&mut self) -> PResult<TokenTree> {
2373 let mut sp = self.span;
2374 let (name, namep) = match self.token {
2378 if self.token == token::OpenDelim(token::Paren) {
2379 let Spanned { node: seq, span: seq_span } = try!(self.parse_seq(
2380 &token::OpenDelim(token::Paren),
2381 &token::CloseDelim(token::Paren),
2383 |p| p.parse_token_tree()
2385 let (sep, repeat) = try!(self.parse_sep_and_kleene_op());
2386 let name_num = macro_parser::count_names(&seq);
2387 return Ok(TtSequence(mk_sp(sp.lo, seq_span.hi),
2388 Rc::new(SequenceRepetition {
2392 num_captures: name_num
2394 } else if self.token.is_keyword_allow_following_colon(keywords::Crate) {
2396 return Ok(TtToken(sp, SpecialVarNt(SpecialMacroVar::CrateMacroVar)));
2398 sp = mk_sp(sp.lo, self.span.hi);
2399 let namep = match self.token { token::Ident(_, p) => p, _ => token::Plain };
2400 let name = try!(self.parse_ident());
2404 token::SubstNt(name, namep) => {
2410 // continue by trying to parse the `:ident` after `$name`
2411 if self.token == token::Colon && self.look_ahead(1, |t| t.is_ident() &&
2412 !t.is_strict_keyword() &&
2413 !t.is_reserved_keyword()) {
2415 sp = mk_sp(sp.lo, self.span.hi);
2416 let kindp = match self.token { token::Ident(_, p) => p, _ => token::Plain };
2417 let nt_kind = try!(self.parse_ident());
2418 Ok(TtToken(sp, MatchNt(name, nt_kind, namep, kindp)))
2420 Ok(TtToken(sp, SubstNt(name, namep)))
2424 pub fn check_unknown_macro_variable(&mut self) -> PResult<()> {
2425 if self.quote_depth == 0 {
2427 token::SubstNt(name, _) =>
2428 return Err(self.fatal(&format!("unknown macro variable `{}`",
2429 token::get_ident(name)))),
2436 /// Parse an optional separator followed by a Kleene-style
2437 /// repetition token (+ or *).
2438 pub fn parse_sep_and_kleene_op(&mut self) -> PResult<(Option<token::Token>, ast::KleeneOp)> {
2439 fn parse_kleene_op(parser: &mut Parser) -> PResult<Option<ast::KleeneOp>> {
2440 match parser.token {
2441 token::BinOp(token::Star) => {
2442 try!(parser.bump());
2443 Ok(Some(ast::ZeroOrMore))
2445 token::BinOp(token::Plus) => {
2446 try!(parser.bump());
2447 Ok(Some(ast::OneOrMore))
2453 match try!(parse_kleene_op(self)) {
2454 Some(kleene_op) => return Ok((None, kleene_op)),
2458 let separator = try!(self.bump_and_get());
2459 match try!(parse_kleene_op(self)) {
2460 Some(zerok) => Ok((Some(separator), zerok)),
2461 None => return Err(self.fatal("expected `*` or `+`"))
2465 /// parse a single token tree from the input.
2466 pub fn parse_token_tree(&mut self) -> PResult<TokenTree> {
2467 // FIXME #6994: currently, this is too eager. It
2468 // parses token trees but also identifies TtSequence's
2469 // and token::SubstNt's; it's too early to know yet
2470 // whether something will be a nonterminal or a seq
2472 maybe_whole!(deref self, NtTT);
2474 // this is the fall-through for the 'match' below.
2475 // invariants: the current token is not a left-delimiter,
2476 // not an EOF, and not the desired right-delimiter (if
2477 // it were, parse_seq_to_before_end would have prevented
2478 // reaching this point.
2479 fn parse_non_delim_tt_tok(p: &mut Parser) -> PResult<TokenTree> {
2480 maybe_whole!(deref p, NtTT);
2482 token::CloseDelim(_) => {
2483 // This is a conservative error: only report the last unclosed delimiter. The
2484 // previous unclosed delimiters could actually be closed! The parser just hasn't
2485 // gotten to them yet.
2486 match p.open_braces.last() {
2488 Some(&sp) => p.span_note(sp, "unclosed delimiter"),
2490 let token_str = p.this_token_to_string();
2491 Err(p.fatal(&format!("incorrect close delimiter: `{}`",
2494 /* we ought to allow different depths of unquotation */
2495 token::Dollar | token::SubstNt(..) if p.quote_depth > 0 => {
2499 Ok(TtToken(p.span, try!(p.bump_and_get())))
2506 let open_braces = self.open_braces.clone();
2507 for sp in &open_braces {
2508 self.span_help(*sp, "did you mean to close this delimiter?");
2510 // There shouldn't really be a span, but it's easier for the test runner
2511 // if we give it one
2512 return Err(self.fatal("this file contains an un-closed delimiter "));
2514 token::OpenDelim(delim) => {
2515 // The span for beginning of the delimited section
2516 let pre_span = self.span;
2518 // Parse the open delimiter.
2519 self.open_braces.push(self.span);
2520 let open_span = self.span;
2523 // Parse the token trees within the delimiters
2524 let tts = try!(self.parse_seq_to_before_end(
2525 &token::CloseDelim(delim),
2527 |p| p.parse_token_tree()
2530 // Parse the close delimiter.
2531 let close_span = self.span;
2533 self.open_braces.pop().unwrap();
2535 // Expand to cover the entire delimited token tree
2536 let span = Span { hi: close_span.hi, ..pre_span };
2538 Ok(TtDelimited(span, Rc::new(Delimited {
2540 open_span: open_span,
2542 close_span: close_span,
2545 _ => parse_non_delim_tt_tok(self),
2549 // parse a stream of tokens into a list of TokenTree's,
2551 pub fn parse_all_token_trees(&mut self) -> PResult<Vec<TokenTree>> {
2552 let mut tts = Vec::new();
2553 while self.token != token::Eof {
2554 tts.push(try!(self.parse_token_tree()));
2559 /// Parse a prefix-operator expr
2560 pub fn parse_prefix_expr(&mut self) -> PResult<P<Expr>> {
2561 let lo = self.span.lo;
2564 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2569 let e = try!(self.parse_prefix_expr());
2571 ex = self.mk_unary(UnNot, e);
2573 token::BinOp(token::Minus) => {
2575 let e = try!(self.parse_prefix_expr());
2577 ex = self.mk_unary(UnNeg, e);
2579 token::BinOp(token::Star) => {
2581 let e = try!(self.parse_prefix_expr());
2583 ex = self.mk_unary(UnDeref, e);
2585 token::BinOp(token::And) | token::AndAnd => {
2586 try!(self.expect_and());
2587 let m = try!(self.parse_mutability());
2588 let e = try!(self.parse_prefix_expr());
2590 ex = ExprAddrOf(m, e);
2592 token::Ident(_, _) => {
2593 if !self.check_keyword(keywords::Box) {
2594 return self.parse_dot_or_call_expr();
2597 let lo = self.span.lo;
2598 let box_hi = self.span.hi;
2602 // Check for a place: `box(PLACE) EXPR`.
2603 if try!(self.eat(&token::OpenDelim(token::Paren)) ){
2604 // Support `box() EXPR` as the default.
2605 if !try!(self.eat(&token::CloseDelim(token::Paren)) ){
2606 let place = try!(self.parse_expr_nopanic());
2607 try!(self.expect(&token::CloseDelim(token::Paren)));
2608 // Give a suggestion to use `box()` when a parenthesised expression is used
2609 if !self.token.can_begin_expr() {
2610 let span = self.span;
2611 let this_token_to_string = self.this_token_to_string();
2613 &format!("expected expression, found `{}`",
2614 this_token_to_string));
2615 let box_span = mk_sp(lo, box_hi);
2616 self.span_suggestion(box_span,
2617 "try using `box()` instead:",
2618 "box()".to_string());
2619 self.abort_if_errors();
2621 let subexpression = try!(self.parse_prefix_expr());
2622 hi = subexpression.span.hi;
2623 ex = ExprBox(Some(place), subexpression);
2624 return Ok(self.mk_expr(lo, hi, ex));
2628 // Otherwise, we use the unique pointer default.
2629 let subexpression = try!(self.parse_prefix_expr());
2630 hi = subexpression.span.hi;
2631 // FIXME (pnkfelix): After working out kinks with box
2632 // desugaring, should be `ExprBox(None, subexpression)`
2634 ex = self.mk_unary(UnUniq, subexpression);
2636 _ => return self.parse_dot_or_call_expr()
2638 return Ok(self.mk_expr(lo, hi, ex));
2641 /// Parse an expression of binops
2642 pub fn parse_binops(&mut self) -> PResult<P<Expr>> {
2643 let prefix_expr = try!(self.parse_prefix_expr());
2644 self.parse_more_binops(prefix_expr, 0)
2647 /// Parse an expression of binops of at least min_prec precedence
2648 pub fn parse_more_binops(&mut self, lhs: P<Expr>, min_prec: usize) -> PResult<P<Expr>> {
2649 if self.expr_is_complete(&*lhs) { return Ok(lhs); }
2651 self.expected_tokens.push(TokenType::Operator);
2653 let cur_op_span = self.span;
2654 let cur_opt = self.token.to_binop();
2657 if ast_util::is_comparison_binop(cur_op) {
2658 self.check_no_chained_comparison(&*lhs, cur_op)
2660 let cur_prec = operator_prec(cur_op);
2661 if cur_prec >= min_prec {
2663 let expr = try!(self.parse_prefix_expr());
2664 let rhs = try!(self.parse_more_binops(expr, cur_prec + 1));
2665 let lhs_span = lhs.span;
2666 let rhs_span = rhs.span;
2667 let binary = self.mk_binary(codemap::respan(cur_op_span, cur_op), lhs, rhs);
2668 let bin = self.mk_expr(lhs_span.lo, rhs_span.hi, binary);
2669 self.parse_more_binops(bin, min_prec)
2675 if AS_PREC >= min_prec && try!(self.eat_keyword_noexpect(keywords::As) ){
2676 let rhs = try!(self.parse_ty_nopanic());
2677 let _as = self.mk_expr(lhs.span.lo,
2679 ExprCast(lhs, rhs));
2680 self.parse_more_binops(_as, min_prec)
2688 /// Produce an error if comparison operators are chained (RFC #558).
2689 /// We only need to check lhs, not rhs, because all comparison ops
2690 /// have same precedence and are left-associative
2691 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: ast::BinOp_) {
2692 debug_assert!(ast_util::is_comparison_binop(outer_op));
2694 ExprBinary(op, _, _) if ast_util::is_comparison_binop(op.node) => {
2695 // respan to include both operators
2696 let op_span = mk_sp(op.span.lo, self.span.hi);
2697 self.span_err(op_span,
2698 "chained comparison operators require parentheses");
2699 if op.node == BiLt && outer_op == BiGt {
2700 self.fileline_help(op_span,
2701 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
2708 /// Parse an assignment expression....
2709 /// actually, this seems to be the main entry point for
2710 /// parsing an arbitrary expression.
2711 pub fn parse_assign_expr(&mut self) -> PResult<P<Expr>> {
2714 // prefix-form of range notation '..expr'
2715 // This has the same precedence as assignment expressions
2716 // (much lower than other prefix expressions) to be consistent
2717 // with the postfix-form 'expr..'
2718 let lo = self.span.lo;
2720 let opt_end = if self.is_at_start_of_range_notation_rhs() {
2721 let end = try!(self.parse_binops());
2726 let hi = self.span.hi;
2727 let ex = self.mk_range(None, opt_end);
2728 Ok(self.mk_expr(lo, hi, ex))
2731 let lhs = try!(self.parse_binops());
2732 self.parse_assign_expr_with(lhs)
2737 pub fn parse_assign_expr_with(&mut self, lhs: P<Expr>) -> PResult<P<Expr>> {
2738 let restrictions = self.restrictions & Restrictions::RESTRICTION_NO_STRUCT_LITERAL;
2739 let op_span = self.span;
2743 let rhs = try!(self.parse_expr_res(restrictions));
2744 Ok(self.mk_expr(lhs.span.lo, rhs.span.hi, ExprAssign(lhs, rhs)))
2746 token::BinOpEq(op) => {
2748 let rhs = try!(self.parse_expr_res(restrictions));
2749 let aop = match op {
2750 token::Plus => BiAdd,
2751 token::Minus => BiSub,
2752 token::Star => BiMul,
2753 token::Slash => BiDiv,
2754 token::Percent => BiRem,
2755 token::Caret => BiBitXor,
2756 token::And => BiBitAnd,
2757 token::Or => BiBitOr,
2758 token::Shl => BiShl,
2761 let rhs_span = rhs.span;
2762 let span = lhs.span;
2763 let assign_op = self.mk_assign_op(codemap::respan(op_span, aop), lhs, rhs);
2764 Ok(self.mk_expr(span.lo, rhs_span.hi, assign_op))
2766 // A range expression, either `expr..expr` or `expr..`.
2770 let opt_end = if self.is_at_start_of_range_notation_rhs() {
2771 let end = try!(self.parse_binops());
2777 let lo = lhs.span.lo;
2778 let hi = self.span.hi;
2779 let range = self.mk_range(Some(lhs), opt_end);
2780 return Ok(self.mk_expr(lo, hi, range));
2789 fn is_at_start_of_range_notation_rhs(&self) -> bool {
2790 if self.token.can_begin_expr() {
2791 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
2792 if self.token == token::OpenDelim(token::Brace) {
2793 return !self.restrictions.contains(Restrictions::RESTRICTION_NO_STRUCT_LITERAL);
2801 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
2802 pub fn parse_if_expr(&mut self) -> PResult<P<Expr>> {
2803 if self.check_keyword(keywords::Let) {
2804 return self.parse_if_let_expr();
2806 let lo = self.last_span.lo;
2807 let cond = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL));
2808 let thn = try!(self.parse_block());
2809 let mut els: Option<P<Expr>> = None;
2810 let mut hi = thn.span.hi;
2811 if try!(self.eat_keyword(keywords::Else) ){
2812 let elexpr = try!(self.parse_else_expr());
2813 hi = elexpr.span.hi;
2816 Ok(self.mk_expr(lo, hi, ExprIf(cond, thn, els)))
2819 /// Parse an 'if let' expression ('if' token already eaten)
2820 pub fn parse_if_let_expr(&mut self) -> PResult<P<Expr>> {
2821 let lo = self.last_span.lo;
2822 try!(self.expect_keyword(keywords::Let));
2823 let pat = try!(self.parse_pat_nopanic());
2824 try!(self.expect(&token::Eq));
2825 let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL));
2826 let thn = try!(self.parse_block());
2827 let (hi, els) = if try!(self.eat_keyword(keywords::Else) ){
2828 let expr = try!(self.parse_else_expr());
2829 (expr.span.hi, Some(expr))
2833 Ok(self.mk_expr(lo, hi, ExprIfLet(pat, expr, thn, els)))
2837 pub fn parse_lambda_expr(&mut self, lo: BytePos, capture_clause: CaptureClause)
2840 let decl = try!(self.parse_fn_block_decl());
2841 let body = match decl.output {
2842 DefaultReturn(_) => {
2843 // If no explicit return type is given, parse any
2844 // expr and wrap it up in a dummy block:
2845 let body_expr = try!(self.parse_expr_nopanic());
2847 id: ast::DUMMY_NODE_ID,
2849 span: body_expr.span,
2850 expr: Some(body_expr),
2851 rules: DefaultBlock,
2855 // If an explicit return type is given, require a
2856 // block to appear (RFC 968).
2857 try!(self.parse_block())
2864 ExprClosure(capture_clause, decl, body)))
2867 pub fn parse_else_expr(&mut self) -> PResult<P<Expr>> {
2868 if try!(self.eat_keyword(keywords::If) ){
2869 return self.parse_if_expr();
2871 let blk = try!(self.parse_block());
2872 return Ok(self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk)));
2876 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
2877 pub fn parse_for_expr(&mut self, opt_ident: Option<ast::Ident>) -> PResult<P<Expr>> {
2878 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
2880 let lo = self.last_span.lo;
2881 let pat = try!(self.parse_pat_nopanic());
2882 try!(self.expect_keyword(keywords::In));
2883 let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL));
2884 let loop_block = try!(self.parse_block());
2885 let hi = self.last_span.hi;
2887 Ok(self.mk_expr(lo, hi, ExprForLoop(pat, expr, loop_block, opt_ident)))
2890 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
2891 pub fn parse_while_expr(&mut self, opt_ident: Option<ast::Ident>) -> PResult<P<Expr>> {
2892 if self.token.is_keyword(keywords::Let) {
2893 return self.parse_while_let_expr(opt_ident);
2895 let lo = self.last_span.lo;
2896 let cond = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL));
2897 let body = try!(self.parse_block());
2898 let hi = body.span.hi;
2899 return Ok(self.mk_expr(lo, hi, ExprWhile(cond, body, opt_ident)));
2902 /// Parse a 'while let' expression ('while' token already eaten)
2903 pub fn parse_while_let_expr(&mut self, opt_ident: Option<ast::Ident>) -> PResult<P<Expr>> {
2904 let lo = self.last_span.lo;
2905 try!(self.expect_keyword(keywords::Let));
2906 let pat = try!(self.parse_pat_nopanic());
2907 try!(self.expect(&token::Eq));
2908 let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL));
2909 let body = try!(self.parse_block());
2910 let hi = body.span.hi;
2911 return Ok(self.mk_expr(lo, hi, ExprWhileLet(pat, expr, body, opt_ident)));
2914 pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::Ident>) -> PResult<P<Expr>> {
2915 let lo = self.last_span.lo;
2916 let body = try!(self.parse_block());
2917 let hi = body.span.hi;
2918 Ok(self.mk_expr(lo, hi, ExprLoop(body, opt_ident)))
2921 fn parse_match_expr(&mut self) -> PResult<P<Expr>> {
2922 let lo = self.last_span.lo;
2923 let discriminant = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL));
2924 try!(self.commit_expr_expecting(&*discriminant, token::OpenDelim(token::Brace)));
2925 let mut arms: Vec<Arm> = Vec::new();
2926 while self.token != token::CloseDelim(token::Brace) {
2927 arms.push(try!(self.parse_arm_nopanic()));
2929 let hi = self.span.hi;
2931 return Ok(self.mk_expr(lo, hi, ExprMatch(discriminant, arms, MatchSource::Normal)));
2934 pub fn parse_arm_nopanic(&mut self) -> PResult<Arm> {
2935 maybe_whole!(no_clone self, NtArm);
2937 let attrs = self.parse_outer_attributes();
2938 let pats = try!(self.parse_pats());
2939 let mut guard = None;
2940 if try!(self.eat_keyword(keywords::If) ){
2941 guard = Some(try!(self.parse_expr_nopanic()));
2943 try!(self.expect(&token::FatArrow));
2944 let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_STMT_EXPR));
2947 !classify::expr_is_simple_block(&*expr)
2948 && self.token != token::CloseDelim(token::Brace);
2951 try!(self.commit_expr(&*expr, &[token::Comma], &[token::CloseDelim(token::Brace)]));
2953 try!(self.eat(&token::Comma));
2964 /// Parse an expression
2965 pub fn parse_expr_nopanic(&mut self) -> PResult<P<Expr>> {
2966 self.parse_expr_res(Restrictions::empty())
2969 /// Parse an expression, subject to the given restrictions
2970 pub fn parse_expr_res(&mut self, r: Restrictions) -> PResult<P<Expr>> {
2971 let old = self.restrictions;
2972 self.restrictions = r;
2973 let e = try!(self.parse_assign_expr());
2974 self.restrictions = old;
2978 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
2979 fn parse_initializer(&mut self) -> PResult<Option<P<Expr>>> {
2980 if self.check(&token::Eq) {
2982 Ok(Some(try!(self.parse_expr_nopanic())))
2988 /// Parse patterns, separated by '|' s
2989 fn parse_pats(&mut self) -> PResult<Vec<P<Pat>>> {
2990 let mut pats = Vec::new();
2992 pats.push(try!(self.parse_pat_nopanic()));
2993 if self.check(&token::BinOp(token::Or)) { try!(self.bump());}
2994 else { return Ok(pats); }
2998 fn parse_pat_tuple_elements(&mut self) -> PResult<Vec<P<Pat>>> {
2999 let mut fields = vec![];
3000 if !self.check(&token::CloseDelim(token::Paren)) {
3001 fields.push(try!(self.parse_pat_nopanic()));
3002 if self.look_ahead(1, |t| *t != token::CloseDelim(token::Paren)) {
3003 while try!(self.eat(&token::Comma)) &&
3004 !self.check(&token::CloseDelim(token::Paren)) {
3005 fields.push(try!(self.parse_pat_nopanic()));
3008 if fields.len() == 1 {
3009 try!(self.expect(&token::Comma));
3015 fn parse_pat_vec_elements(
3017 ) -> PResult<(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3018 let mut before = Vec::new();
3019 let mut slice = None;
3020 let mut after = Vec::new();
3021 let mut first = true;
3022 let mut before_slice = true;
3024 while self.token != token::CloseDelim(token::Bracket) {
3028 try!(self.expect(&token::Comma));
3030 if self.token == token::CloseDelim(token::Bracket)
3031 && (before_slice || !after.is_empty()) {
3037 if self.check(&token::DotDot) {
3040 if self.check(&token::Comma) ||
3041 self.check(&token::CloseDelim(token::Bracket)) {
3042 slice = Some(P(ast::Pat {
3043 id: ast::DUMMY_NODE_ID,
3044 node: PatWild(PatWildMulti),
3047 before_slice = false;
3053 let subpat = try!(self.parse_pat_nopanic());
3054 if before_slice && self.check(&token::DotDot) {
3056 slice = Some(subpat);
3057 before_slice = false;
3058 } else if before_slice {
3059 before.push(subpat);
3065 Ok((before, slice, after))
3068 /// Parse the fields of a struct-like pattern
3069 fn parse_pat_fields(&mut self) -> PResult<(Vec<codemap::Spanned<ast::FieldPat>> , bool)> {
3070 let mut fields = Vec::new();
3071 let mut etc = false;
3072 let mut first = true;
3073 while self.token != token::CloseDelim(token::Brace) {
3077 try!(self.expect(&token::Comma));
3078 // accept trailing commas
3079 if self.check(&token::CloseDelim(token::Brace)) { break }
3082 let lo = self.span.lo;
3085 if self.check(&token::DotDot) {
3087 if self.token != token::CloseDelim(token::Brace) {
3088 let token_str = self.this_token_to_string();
3089 return Err(self.fatal(&format!("expected `{}`, found `{}`", "}",
3096 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3097 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3098 // Parsing a pattern of the form "fieldname: pat"
3099 let fieldname = try!(self.parse_ident());
3101 let pat = try!(self.parse_pat_nopanic());
3103 (pat, fieldname, false)
3105 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3106 let is_box = try!(self.eat_keyword(keywords::Box));
3107 let boxed_span_lo = self.span.lo;
3108 let is_ref = try!(self.eat_keyword(keywords::Ref));
3109 let is_mut = try!(self.eat_keyword(keywords::Mut));
3110 let fieldname = try!(self.parse_ident());
3111 hi = self.last_span.hi;
3113 let bind_type = match (is_ref, is_mut) {
3114 (true, true) => BindByRef(MutMutable),
3115 (true, false) => BindByRef(MutImmutable),
3116 (false, true) => BindByValue(MutMutable),
3117 (false, false) => BindByValue(MutImmutable),
3119 let fieldpath = codemap::Spanned{span:self.last_span, node:fieldname};
3120 let fieldpat = P(ast::Pat{
3121 id: ast::DUMMY_NODE_ID,
3122 node: PatIdent(bind_type, fieldpath, None),
3123 span: mk_sp(boxed_span_lo, hi),
3126 let subpat = if is_box {
3128 id: ast::DUMMY_NODE_ID,
3129 node: PatBox(fieldpat),
3130 span: mk_sp(lo, hi),
3135 (subpat, fieldname, true)
3138 fields.push(codemap::Spanned { span: mk_sp(lo, hi),
3139 node: ast::FieldPat { ident: fieldname,
3141 is_shorthand: is_shorthand }});
3143 return Ok((fields, etc));
3146 fn parse_pat_range_end(&mut self) -> PResult<P<Expr>> {
3147 if self.is_path_start() {
3148 let lo = self.span.lo;
3149 let (qself, path) = if try!(self.eat_lt()) {
3150 // Parse a qualified path
3152 try!(self.parse_qualified_path(NoTypesAllowed));
3155 // Parse an unqualified path
3156 (None, try!(self.parse_path(LifetimeAndTypesWithColons)))
3158 let hi = self.last_span.hi;
3159 Ok(self.mk_expr(lo, hi, ExprPath(qself, path)))
3161 self.parse_literal_maybe_minus()
3165 fn is_path_start(&self) -> bool {
3166 (self.token == token::Lt || self.token == token::ModSep
3167 || self.token.is_ident() || self.token.is_path())
3168 && !self.token.is_keyword(keywords::True) && !self.token.is_keyword(keywords::False)
3171 /// Parse a pattern.
3172 pub fn parse_pat_nopanic(&mut self) -> PResult<P<Pat>> {
3173 maybe_whole!(self, NtPat);
3175 let lo = self.span.lo;
3178 token::Underscore => {
3181 pat = PatWild(PatWildSingle);
3183 token::BinOp(token::And) | token::AndAnd => {
3184 // Parse &pat / &mut pat
3185 try!(self.expect_and());
3186 let mutbl = try!(self.parse_mutability());
3187 let subpat = try!(self.parse_pat_nopanic());
3188 pat = PatRegion(subpat, mutbl);
3190 token::OpenDelim(token::Paren) => {
3191 // Parse (pat,pat,pat,...) as tuple pattern
3193 let fields = try!(self.parse_pat_tuple_elements());
3194 try!(self.expect(&token::CloseDelim(token::Paren)));
3195 pat = PatTup(fields);
3197 token::OpenDelim(token::Bracket) => {
3198 // Parse [pat,pat,...] as vector pattern
3200 let (before, slice, after) = try!(self.parse_pat_vec_elements());
3201 try!(self.expect(&token::CloseDelim(token::Bracket)));
3202 pat = PatVec(before, slice, after);
3205 // At this point, token != _, &, &&, (, [
3206 if try!(self.eat_keyword(keywords::Mut)) {
3207 // Parse mut ident @ pat
3208 pat = try!(self.parse_pat_ident(BindByValue(MutMutable)));
3209 } else if try!(self.eat_keyword(keywords::Ref)) {
3210 // Parse ref ident @ pat / ref mut ident @ pat
3211 let mutbl = try!(self.parse_mutability());
3212 pat = try!(self.parse_pat_ident(BindByRef(mutbl)));
3213 } else if try!(self.eat_keyword(keywords::Box)) {
3215 let subpat = try!(self.parse_pat_nopanic());
3216 pat = PatBox(subpat);
3217 } else if self.is_path_start() {
3218 // Parse pattern starting with a path
3219 if self.token.is_plain_ident() && self.look_ahead(1, |t| *t != token::DotDotDot &&
3220 *t != token::OpenDelim(token::Brace) &&
3221 *t != token::OpenDelim(token::Paren) &&
3222 // Contrary to its definition, a plain ident can be followed by :: in macros
3223 *t != token::ModSep) {
3224 // Plain idents have some extra abilities here compared to general paths
3225 if self.look_ahead(1, |t| *t == token::Not) {
3226 // Parse macro invocation
3227 let ident = try!(self.parse_ident());
3228 let ident_span = self.last_span;
3229 let path = ident_to_path(ident_span, ident);
3231 let delim = try!(self.expect_open_delim());
3232 let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
3233 seq_sep_none(), |p| p.parse_token_tree()));
3234 let mac = MacInvocTT(path, tts, EMPTY_CTXT);
3235 pat = PatMac(codemap::Spanned {node: mac, span: self.span});
3237 // Parse ident @ pat
3238 // This can give false positives and parse nullary enums,
3239 // they are dealt with later in resolve
3240 pat = try!(self.parse_pat_ident(BindByValue(MutImmutable)));
3243 let (qself, path) = if try!(self.eat_lt()) {
3244 // Parse a qualified path
3246 try!(self.parse_qualified_path(NoTypesAllowed));
3249 // Parse an unqualified path
3250 (None, try!(self.parse_path(LifetimeAndTypesWithColons)))
3253 token::DotDotDot => {
3255 let hi = self.last_span.hi;
3256 let begin = self.mk_expr(lo, hi, ExprPath(qself, path));
3258 let end = try!(self.parse_pat_range_end());
3259 pat = PatRange(begin, end);
3261 token::OpenDelim(token::Brace) => {
3262 if qself.is_some() {
3263 let span = self.span;
3265 "unexpected `{` after qualified path");
3266 self.abort_if_errors();
3268 // Parse struct pattern
3270 let (fields, etc) = try!(self.parse_pat_fields());
3272 pat = PatStruct(path, fields, etc);
3274 token::OpenDelim(token::Paren) => {
3275 if qself.is_some() {
3276 let span = self.span;
3278 "unexpected `(` after qualified path");
3279 self.abort_if_errors();
3281 // Parse tuple struct or enum pattern
3282 if self.look_ahead(1, |t| *t == token::DotDot) {
3283 // This is a "top constructor only" pat
3286 try!(self.expect(&token::CloseDelim(token::Paren)));
3287 pat = PatEnum(path, None);
3289 let args = try!(self.parse_enum_variant_seq(
3290 &token::OpenDelim(token::Paren),
3291 &token::CloseDelim(token::Paren),
3292 seq_sep_trailing_allowed(token::Comma),
3293 |p| p.parse_pat_nopanic()));
3294 pat = PatEnum(path, Some(args));
3297 _ if qself.is_some() => {
3298 // Parse qualified path
3299 pat = PatQPath(qself.unwrap(), path);
3302 // Parse nullary enum
3303 pat = PatEnum(path, Some(vec![]));
3308 // Try to parse everything else as literal with optional minus
3309 let begin = try!(self.parse_literal_maybe_minus());
3310 if try!(self.eat(&token::DotDotDot)) {
3311 let end = try!(self.parse_pat_range_end());
3312 pat = PatRange(begin, end);
3314 pat = PatLit(begin);
3320 let hi = self.last_span.hi;
3322 id: ast::DUMMY_NODE_ID,
3324 span: mk_sp(lo, hi),
3328 /// Parse ident or ident @ pat
3329 /// used by the copy foo and ref foo patterns to give a good
3330 /// error message when parsing mistakes like ref foo(a,b)
3331 fn parse_pat_ident(&mut self,
3332 binding_mode: ast::BindingMode)
3333 -> PResult<ast::Pat_> {
3334 if !self.token.is_plain_ident() {
3335 let span = self.span;
3336 let tok_str = self.this_token_to_string();
3337 return Err(self.span_fatal(span,
3338 &format!("expected identifier, found `{}`", tok_str)))
3340 let ident = try!(self.parse_ident());
3341 let last_span = self.last_span;
3342 let name = codemap::Spanned{span: last_span, node: ident};
3343 let sub = if try!(self.eat(&token::At) ){
3344 Some(try!(self.parse_pat_nopanic()))
3349 // just to be friendly, if they write something like
3351 // we end up here with ( as the current token. This shortly
3352 // leads to a parse error. Note that if there is no explicit
3353 // binding mode then we do not end up here, because the lookahead
3354 // will direct us over to parse_enum_variant()
3355 if self.token == token::OpenDelim(token::Paren) {
3356 let last_span = self.last_span;
3357 return Err(self.span_fatal(
3359 "expected identifier, found enum pattern"))
3362 Ok(PatIdent(binding_mode, name, sub))
3365 /// Parse a local variable declaration
3366 fn parse_local(&mut self) -> PResult<P<Local>> {
3367 let lo = self.span.lo;
3368 let pat = try!(self.parse_pat_nopanic());
3371 if try!(self.eat(&token::Colon) ){
3372 ty = Some(try!(self.parse_ty_sum()));
3374 let init = try!(self.parse_initializer());
3379 id: ast::DUMMY_NODE_ID,
3380 span: mk_sp(lo, self.last_span.hi),
3385 /// Parse a "let" stmt
3386 fn parse_let(&mut self) -> PResult<P<Decl>> {
3387 let lo = self.span.lo;
3388 let local = try!(self.parse_local());
3389 Ok(P(spanned(lo, self.last_span.hi, DeclLocal(local))))
3392 /// Parse a structure field
3393 fn parse_name_and_ty(&mut self, pr: Visibility,
3394 attrs: Vec<Attribute> ) -> PResult<StructField> {
3396 Inherited => self.span.lo,
3397 Public => self.last_span.lo,
3399 if !self.token.is_plain_ident() {
3400 return Err(self.fatal("expected ident"));
3402 let name = try!(self.parse_ident());
3403 try!(self.expect(&token::Colon));
3404 let ty = try!(self.parse_ty_sum());
3405 Ok(spanned(lo, self.last_span.hi, ast::StructField_ {
3406 kind: NamedField(name, pr),
3407 id: ast::DUMMY_NODE_ID,
3413 /// Emit an expected item after attributes error.
3414 fn expected_item_err(&self, attrs: &[Attribute]) {
3415 let message = match attrs.last() {
3416 Some(&Attribute { node: ast::Attribute_ { is_sugared_doc: true, .. }, .. }) => {
3417 "expected item after doc comment"
3419 _ => "expected item after attributes",
3422 self.span_err(self.last_span, message);
3425 /// Parse a statement. may include decl.
3426 pub fn parse_stmt_nopanic(&mut self) -> PResult<Option<P<Stmt>>> {
3427 Ok(try!(self.parse_stmt_()).map(P))
3430 fn parse_stmt_(&mut self) -> PResult<Option<Stmt>> {
3431 maybe_whole!(Some deref self, NtStmt);
3433 fn check_expected_item(p: &mut Parser, attrs: &[Attribute]) {
3434 // If we have attributes then we should have an item
3435 if !attrs.is_empty() {
3436 p.expected_item_err(attrs);
3440 let attrs = self.parse_outer_attributes();
3441 let lo = self.span.lo;
3443 Ok(Some(if self.check_keyword(keywords::Let) {
3444 check_expected_item(self, &attrs);
3445 try!(self.expect_keyword(keywords::Let));
3446 let decl = try!(self.parse_let());
3447 spanned(lo, decl.span.hi, StmtDecl(decl, ast::DUMMY_NODE_ID))
3448 } else if self.token.is_ident()
3449 && !self.token.is_any_keyword()
3450 && self.look_ahead(1, |t| *t == token::Not) {
3451 // it's a macro invocation:
3453 check_expected_item(self, &attrs);
3455 // Potential trouble: if we allow macros with paths instead of
3456 // idents, we'd need to look ahead past the whole path here...
3457 let pth = try!(self.parse_path(NoTypesAllowed));
3460 let id = match self.token {
3461 token::OpenDelim(_) => token::special_idents::invalid, // no special identifier
3462 _ => try!(self.parse_ident()),
3465 // check that we're pointing at delimiters (need to check
3466 // again after the `if`, because of `parse_ident`
3467 // consuming more tokens).
3468 let delim = match self.token {
3469 token::OpenDelim(delim) => delim,
3471 // we only expect an ident if we didn't parse one
3473 let ident_str = if id.name == token::special_idents::invalid.name {
3478 let tok_str = self.this_token_to_string();
3479 return Err(self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
3485 let tts = try!(self.parse_unspanned_seq(
3486 &token::OpenDelim(delim),
3487 &token::CloseDelim(delim),
3489 |p| p.parse_token_tree()
3491 let hi = self.last_span.hi;
3493 let style = if delim == token::Brace {
3496 MacStmtWithoutBraces
3499 if id.name == token::special_idents::invalid.name {
3501 StmtMac(P(spanned(lo,
3503 MacInvocTT(pth, tts, EMPTY_CTXT))),
3506 // if it has a special ident, it's definitely an item
3508 // Require a semicolon or braces.
3509 if style != MacStmtWithBraces {
3510 if !try!(self.eat(&token::Semi) ){
3511 let last_span = self.last_span;
3512 self.span_err(last_span,
3513 "macros that expand to items must \
3514 either be surrounded with braces or \
3515 followed by a semicolon");
3518 spanned(lo, hi, StmtDecl(
3519 P(spanned(lo, hi, DeclItem(
3521 lo, hi, id /*id is good here*/,
3522 ItemMac(spanned(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT))),
3523 Inherited, Vec::new(/*no attrs*/))))),
3524 ast::DUMMY_NODE_ID))
3527 match try!(self.parse_item_(attrs, false)) {
3530 let decl = P(spanned(lo, hi, DeclItem(i)));
3531 spanned(lo, hi, StmtDecl(decl, ast::DUMMY_NODE_ID))
3534 // Do not attempt to parse an expression if we're done here.
3535 if self.token == token::Semi {
3540 if self.token == token::CloseDelim(token::Brace) {
3544 // Remainder are line-expr stmts.
3545 let e = try!(self.parse_expr_res(Restrictions::RESTRICTION_STMT_EXPR));
3546 spanned(lo, e.span.hi, StmtExpr(e, ast::DUMMY_NODE_ID))
3552 /// Is this expression a successfully-parsed statement?
3553 fn expr_is_complete(&mut self, e: &Expr) -> bool {
3554 self.restrictions.contains(Restrictions::RESTRICTION_STMT_EXPR) &&
3555 !classify::expr_requires_semi_to_be_stmt(e)
3558 /// Parse a block. No inner attrs are allowed.
3559 pub fn parse_block(&mut self) -> PResult<P<Block>> {
3560 maybe_whole!(no_clone self, NtBlock);
3562 let lo = self.span.lo;
3564 if !try!(self.eat(&token::OpenDelim(token::Brace)) ){
3566 let tok = self.this_token_to_string();
3567 return Err(self.span_fatal_help(sp,
3568 &format!("expected `{{`, found `{}`", tok),
3569 "place this code inside a block"));
3572 self.parse_block_tail(lo, DefaultBlock)
3575 /// Parse a block. Inner attrs are allowed.
3576 fn parse_inner_attrs_and_block(&mut self) -> PResult<(Vec<Attribute>, P<Block>)> {
3577 maybe_whole!(pair_empty self, NtBlock);
3579 let lo = self.span.lo;
3580 try!(self.expect(&token::OpenDelim(token::Brace)));
3581 Ok((self.parse_inner_attributes(),
3582 try!(self.parse_block_tail(lo, DefaultBlock))))
3585 /// Parse the rest of a block expression or function body
3586 /// Precondition: already parsed the '{'.
3587 fn parse_block_tail(&mut self, lo: BytePos, s: BlockCheckMode) -> PResult<P<Block>> {
3588 let mut stmts = vec![];
3589 let mut expr = None;
3591 while !try!(self.eat(&token::CloseDelim(token::Brace))) {
3592 let Spanned {node, span} = if let Some(s) = try!(self.parse_stmt_()) {
3595 // Found only `;` or `}`.
3600 try!(self.handle_expression_like_statement(e, span, &mut stmts, &mut expr));
3602 StmtMac(mac, MacStmtWithoutBraces) => {
3603 // statement macro without braces; might be an
3604 // expr depending on whether a semicolon follows
3607 stmts.push(P(Spanned {
3608 node: StmtMac(mac, MacStmtWithSemicolon),
3609 span: mk_sp(span.lo, self.span.hi),
3614 let e = self.mk_mac_expr(span.lo, span.hi,
3615 mac.and_then(|m| m.node));
3616 let e = try!(self.parse_dot_or_call_expr_with(e));
3617 let e = try!(self.parse_more_binops(e, 0));
3618 let e = try!(self.parse_assign_expr_with(e));
3619 try!(self.handle_expression_like_statement(
3627 StmtMac(m, style) => {
3628 // statement macro; might be an expr
3631 stmts.push(P(Spanned {
3632 node: StmtMac(m, MacStmtWithSemicolon),
3633 span: mk_sp(span.lo, self.span.hi),
3637 token::CloseDelim(token::Brace) => {
3638 // if a block ends in `m!(arg)` without
3639 // a `;`, it must be an expr
3640 expr = Some(self.mk_mac_expr(span.lo, span.hi,
3641 m.and_then(|x| x.node)));
3644 stmts.push(P(Spanned {
3645 node: StmtMac(m, style),
3651 _ => { // all other kinds of statements:
3652 let mut hi = span.hi;
3653 if classify::stmt_ends_with_semi(&node) {
3654 try!(self.commit_stmt_expecting(token::Semi));
3655 hi = self.last_span.hi;
3658 stmts.push(P(Spanned {
3660 span: mk_sp(span.lo, hi)
3669 id: ast::DUMMY_NODE_ID,
3671 span: mk_sp(lo, self.last_span.hi),
3675 fn handle_expression_like_statement(
3679 stmts: &mut Vec<P<Stmt>>,
3680 last_block_expr: &mut Option<P<Expr>>) -> PResult<()> {
3681 // expression without semicolon
3682 if classify::expr_requires_semi_to_be_stmt(&*e) {
3683 // Just check for errors and recover; do not eat semicolon yet.
3684 try!(self.commit_stmt(&[],
3685 &[token::Semi, token::CloseDelim(token::Brace)]));
3691 let span_with_semi = Span {
3693 hi: self.last_span.hi,
3694 expn_id: span.expn_id,
3696 stmts.push(P(Spanned {
3697 node: StmtSemi(e, ast::DUMMY_NODE_ID),
3698 span: span_with_semi,
3701 token::CloseDelim(token::Brace) => *last_block_expr = Some(e),
3703 stmts.push(P(Spanned {
3704 node: StmtExpr(e, ast::DUMMY_NODE_ID),
3712 // Parses a sequence of bounds if a `:` is found,
3713 // otherwise returns empty list.
3714 fn parse_colon_then_ty_param_bounds(&mut self,
3715 mode: BoundParsingMode)
3716 -> PResult<OwnedSlice<TyParamBound>>
3718 if !try!(self.eat(&token::Colon) ){
3719 Ok(OwnedSlice::empty())
3721 self.parse_ty_param_bounds(mode)
3725 // matches bounds = ( boundseq )?
3726 // where boundseq = ( polybound + boundseq ) | polybound
3727 // and polybound = ( 'for' '<' 'region '>' )? bound
3728 // and bound = 'region | trait_ref
3729 fn parse_ty_param_bounds(&mut self,
3730 mode: BoundParsingMode)
3731 -> PResult<OwnedSlice<TyParamBound>>
3733 let mut result = vec!();
3735 let question_span = self.span;
3736 let ate_question = try!(self.eat(&token::Question));
3738 token::Lifetime(lifetime) => {
3740 self.span_err(question_span,
3741 "`?` may only modify trait bounds, not lifetime bounds");
3743 result.push(RegionTyParamBound(ast::Lifetime {
3744 id: ast::DUMMY_NODE_ID,
3750 token::ModSep | token::Ident(..) => {
3751 let poly_trait_ref = try!(self.parse_poly_trait_ref());
3752 let modifier = if ate_question {
3753 if mode == BoundParsingMode::Modified {
3754 TraitBoundModifier::Maybe
3756 self.span_err(question_span,
3758 TraitBoundModifier::None
3761 TraitBoundModifier::None
3763 result.push(TraitTyParamBound(poly_trait_ref, modifier))
3768 if !try!(self.eat(&token::BinOp(token::Plus)) ){
3773 return Ok(OwnedSlice::from_vec(result));
3776 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
3777 fn parse_ty_param(&mut self) -> PResult<TyParam> {
3778 let span = self.span;
3779 let ident = try!(self.parse_ident());
3781 let bounds = try!(self.parse_colon_then_ty_param_bounds(BoundParsingMode::Modified));
3783 let default = if self.check(&token::Eq) {
3785 Some(try!(self.parse_ty_sum()))
3792 id: ast::DUMMY_NODE_ID,
3799 /// Parse a set of optional generic type parameter declarations. Where
3800 /// clauses are not parsed here, and must be added later via
3801 /// `parse_where_clause()`.
3803 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
3804 /// | ( < lifetimes , typaramseq ( , )? > )
3805 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
3806 pub fn parse_generics(&mut self) -> PResult<ast::Generics> {
3807 maybe_whole!(self, NtGenerics);
3809 if try!(self.eat(&token::Lt) ){
3810 let lifetime_defs = try!(self.parse_lifetime_defs());
3811 let mut seen_default = false;
3812 let ty_params = try!(self.parse_seq_to_gt(Some(token::Comma), |p| {
3813 try!(p.forbid_lifetime());
3814 let ty_param = try!(p.parse_ty_param());
3815 if ty_param.default.is_some() {
3816 seen_default = true;
3817 } else if seen_default {
3818 let last_span = p.last_span;
3819 p.span_err(last_span,
3820 "type parameters with a default must be trailing");
3825 lifetimes: lifetime_defs,
3826 ty_params: ty_params,
3827 where_clause: WhereClause {
3828 id: ast::DUMMY_NODE_ID,
3829 predicates: Vec::new(),
3833 Ok(ast_util::empty_generics())
3837 fn parse_generic_values_after_lt(&mut self) -> PResult<(Vec<ast::Lifetime>,
3839 Vec<P<TypeBinding>>)> {
3840 let span_lo = self.span.lo;
3841 let lifetimes = try!(self.parse_lifetimes(token::Comma));
3843 let missing_comma = !lifetimes.is_empty() &&
3844 !self.token.is_like_gt() &&
3846 .as_ref().map_or(true,
3847 |x| &**x != &token::Comma);
3851 let msg = format!("expected `,` or `>` after lifetime \
3853 self.this_token_to_string());
3854 self.span_err(self.span, &msg);
3856 let span_hi = self.span.hi;
3857 let span_hi = if self.parse_ty_nopanic().is_ok() {
3863 let msg = format!("did you mean a single argument type &'a Type, \
3864 or did you mean the comma-separated arguments \
3866 self.span_note(mk_sp(span_lo, span_hi), &msg);
3868 self.abort_if_errors()
3871 // First parse types.
3872 let (types, returned) = try!(self.parse_seq_to_gt_or_return(
3875 try!(p.forbid_lifetime());
3876 if p.look_ahead(1, |t| t == &token::Eq) {
3879 Ok(Some(try!(p.parse_ty_sum())))
3884 // If we found the `>`, don't continue.
3886 return Ok((lifetimes, types.into_vec(), Vec::new()));
3889 // Then parse type bindings.
3890 let bindings = try!(self.parse_seq_to_gt(
3893 try!(p.forbid_lifetime());
3895 let ident = try!(p.parse_ident());
3896 let found_eq = try!(p.eat(&token::Eq));
3899 p.span_warn(span, "whoops, no =?");
3901 let ty = try!(p.parse_ty_nopanic());
3903 let span = mk_sp(lo, hi);
3904 return Ok(P(TypeBinding{id: ast::DUMMY_NODE_ID,
3911 Ok((lifetimes, types.into_vec(), bindings.into_vec()))
3914 fn forbid_lifetime(&mut self) -> PResult<()> {
3915 if self.token.is_lifetime() {
3916 let span = self.span;
3917 return Err(self.span_fatal(span, "lifetime parameters must be declared \
3918 prior to type parameters"))
3923 /// Parses an optional `where` clause and places it in `generics`.
3926 /// where T : Trait<U, V> + 'b, 'a : 'b
3928 pub fn parse_where_clause(&mut self) -> PResult<ast::WhereClause> {
3929 maybe_whole!(self, NtWhereClause);
3931 let mut where_clause = WhereClause {
3932 id: ast::DUMMY_NODE_ID,
3933 predicates: Vec::new(),
3936 if !try!(self.eat_keyword(keywords::Where)) {
3937 return Ok(where_clause);
3940 let mut parsed_something = false;
3942 let lo = self.span.lo;
3944 token::OpenDelim(token::Brace) => {
3948 token::Lifetime(..) => {
3949 let bounded_lifetime =
3950 try!(self.parse_lifetime());
3952 try!(self.eat(&token::Colon));
3955 try!(self.parse_lifetimes(token::BinOp(token::Plus)));
3957 let hi = self.last_span.hi;
3958 let span = mk_sp(lo, hi);
3960 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
3961 ast::WhereRegionPredicate {
3963 lifetime: bounded_lifetime,
3968 parsed_something = true;
3972 let bound_lifetimes = if try!(self.eat_keyword(keywords::For) ){
3973 // Higher ranked constraint.
3974 try!(self.expect(&token::Lt));
3975 let lifetime_defs = try!(self.parse_lifetime_defs());
3976 try!(self.expect_gt());
3982 let bounded_ty = try!(self.parse_ty_nopanic());
3984 if try!(self.eat(&token::Colon) ){
3985 let bounds = try!(self.parse_ty_param_bounds(BoundParsingMode::Bare));
3986 let hi = self.last_span.hi;
3987 let span = mk_sp(lo, hi);
3989 if bounds.is_empty() {
3991 "each predicate in a `where` clause must have \
3992 at least one bound in it");
3995 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
3996 ast::WhereBoundPredicate {
3998 bound_lifetimes: bound_lifetimes,
3999 bounded_ty: bounded_ty,
4003 parsed_something = true;
4004 } else if try!(self.eat(&token::Eq) ){
4005 // let ty = try!(self.parse_ty_nopanic());
4006 let hi = self.last_span.hi;
4007 let span = mk_sp(lo, hi);
4008 // where_clause.predicates.push(
4009 // ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
4010 // id: ast::DUMMY_NODE_ID,
4012 // path: panic!("NYI"), //bounded_ty,
4015 // parsed_something = true;
4018 "equality constraints are not yet supported \
4019 in where clauses (#20041)");
4021 let last_span = self.last_span;
4022 self.span_err(last_span,
4023 "unexpected token in `where` clause");
4028 if !try!(self.eat(&token::Comma) ){
4033 if !parsed_something {
4034 let last_span = self.last_span;
4035 self.span_err(last_span,
4036 "a `where` clause must have at least one predicate \
4043 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
4044 -> PResult<(Vec<Arg> , bool)> {
4046 let mut args: Vec<Option<Arg>> =
4047 try!(self.parse_unspanned_seq(
4048 &token::OpenDelim(token::Paren),
4049 &token::CloseDelim(token::Paren),
4050 seq_sep_trailing_allowed(token::Comma),
4052 if p.token == token::DotDotDot {
4055 if p.token != token::CloseDelim(token::Paren) {
4057 return Err(p.span_fatal(span,
4058 "`...` must be last in argument list for variadic function"))
4062 return Err(p.span_fatal(span,
4063 "only foreign functions are allowed to be variadic"))
4067 Ok(Some(try!(p.parse_arg_general(named_args))))
4072 let variadic = match args.pop() {
4075 // Need to put back that last arg
4082 if variadic && args.is_empty() {
4084 "variadic function must be declared with at least one named argument");
4087 let args = args.into_iter().map(|x| x.unwrap()).collect();
4089 Ok((args, variadic))
4092 /// Parse the argument list and result type of a function declaration
4093 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<P<FnDecl>> {
4095 let (args, variadic) = try!(self.parse_fn_args(true, allow_variadic));
4096 let ret_ty = try!(self.parse_ret_ty());
4105 fn is_self_ident(&mut self) -> bool {
4107 token::Ident(id, token::Plain) => id.name == special_idents::self_.name,
4112 fn expect_self_ident(&mut self) -> PResult<ast::Ident> {
4114 token::Ident(id, token::Plain) if id.name == special_idents::self_.name => {
4119 let token_str = self.this_token_to_string();
4120 return Err(self.fatal(&format!("expected `self`, found `{}`",
4126 fn is_self_type_ident(&mut self) -> bool {
4128 token::Ident(id, token::Plain) => id.name == special_idents::type_self.name,
4133 fn expect_self_type_ident(&mut self) -> PResult<ast::Ident> {
4135 token::Ident(id, token::Plain) if id.name == special_idents::type_self.name => {
4140 let token_str = self.this_token_to_string();
4141 Err(self.fatal(&format!("expected `Self`, found `{}`",
4147 /// Parse the argument list and result type of a function
4148 /// that may have a self type.
4149 fn parse_fn_decl_with_self<F>(&mut self,
4150 parse_arg_fn: F) -> PResult<(ExplicitSelf, P<FnDecl>)> where
4151 F: FnMut(&mut Parser) -> PResult<Arg>,
4153 fn maybe_parse_borrowed_explicit_self(this: &mut Parser)
4154 -> PResult<ast::ExplicitSelf_> {
4155 // The following things are possible to see here:
4160 // fn(&'lt mut self)
4162 // We already know that the current token is `&`.
4164 if this.look_ahead(1, |t| t.is_keyword(keywords::SelfValue)) {
4166 Ok(SelfRegion(None, MutImmutable, try!(this.expect_self_ident())))
4167 } else if this.look_ahead(1, |t| t.is_mutability()) &&
4168 this.look_ahead(2, |t| t.is_keyword(keywords::SelfValue)) {
4170 let mutability = try!(this.parse_mutability());
4171 Ok(SelfRegion(None, mutability, try!(this.expect_self_ident())))
4172 } else if this.look_ahead(1, |t| t.is_lifetime()) &&
4173 this.look_ahead(2, |t| t.is_keyword(keywords::SelfValue)) {
4175 let lifetime = try!(this.parse_lifetime());
4176 Ok(SelfRegion(Some(lifetime), MutImmutable, try!(this.expect_self_ident())))
4177 } else if this.look_ahead(1, |t| t.is_lifetime()) &&
4178 this.look_ahead(2, |t| t.is_mutability()) &&
4179 this.look_ahead(3, |t| t.is_keyword(keywords::SelfValue)) {
4181 let lifetime = try!(this.parse_lifetime());
4182 let mutability = try!(this.parse_mutability());
4183 Ok(SelfRegion(Some(lifetime), mutability, try!(this.expect_self_ident())))
4189 try!(self.expect(&token::OpenDelim(token::Paren)));
4191 // A bit of complexity and lookahead is needed here in order to be
4192 // backwards compatible.
4193 let lo = self.span.lo;
4194 let mut self_ident_lo = self.span.lo;
4195 let mut self_ident_hi = self.span.hi;
4197 let mut mutbl_self = MutImmutable;
4198 let explicit_self = match self.token {
4199 token::BinOp(token::And) => {
4200 let eself = try!(maybe_parse_borrowed_explicit_self(self));
4201 self_ident_lo = self.last_span.lo;
4202 self_ident_hi = self.last_span.hi;
4205 token::BinOp(token::Star) => {
4206 // Possibly "*self" or "*mut self" -- not supported. Try to avoid
4207 // emitting cryptic "unexpected token" errors.
4209 let _mutability = if self.token.is_mutability() {
4210 try!(self.parse_mutability())
4214 if self.is_self_ident() {
4215 let span = self.span;
4216 self.span_err(span, "cannot pass self by raw pointer");
4219 // error case, making bogus self ident:
4220 SelfValue(special_idents::self_)
4222 token::Ident(..) => {
4223 if self.is_self_ident() {
4224 let self_ident = try!(self.expect_self_ident());
4226 // Determine whether this is the fully explicit form, `self:
4228 if try!(self.eat(&token::Colon) ){
4229 SelfExplicit(try!(self.parse_ty_sum()), self_ident)
4231 SelfValue(self_ident)
4233 } else if self.token.is_mutability() &&
4234 self.look_ahead(1, |t| t.is_keyword(keywords::SelfValue)) {
4235 mutbl_self = try!(self.parse_mutability());
4236 let self_ident = try!(self.expect_self_ident());
4238 // Determine whether this is the fully explicit form,
4240 if try!(self.eat(&token::Colon) ){
4241 SelfExplicit(try!(self.parse_ty_sum()), self_ident)
4243 SelfValue(self_ident)
4252 let explicit_self_sp = mk_sp(self_ident_lo, self_ident_hi);
4254 // shared fall-through for the three cases below. borrowing prevents simply
4255 // writing this as a closure
4256 macro_rules! parse_remaining_arguments {
4259 // If we parsed a self type, expect a comma before the argument list.
4263 let sep = seq_sep_trailing_allowed(token::Comma);
4264 let mut fn_inputs = try!(self.parse_seq_to_before_end(
4265 &token::CloseDelim(token::Paren),
4269 fn_inputs.insert(0, Arg::new_self(explicit_self_sp, mutbl_self, $self_id));
4272 token::CloseDelim(token::Paren) => {
4273 vec!(Arg::new_self(explicit_self_sp, mutbl_self, $self_id))
4276 let token_str = self.this_token_to_string();
4277 return Err(self.fatal(&format!("expected `,` or `)`, found `{}`",
4284 let fn_inputs = match explicit_self {
4286 let sep = seq_sep_trailing_allowed(token::Comma);
4287 try!(self.parse_seq_to_before_end(&token::CloseDelim(token::Paren),
4290 SelfValue(id) => parse_remaining_arguments!(id),
4291 SelfRegion(_,_,id) => parse_remaining_arguments!(id),
4292 SelfExplicit(_,id) => parse_remaining_arguments!(id),
4296 try!(self.expect(&token::CloseDelim(token::Paren)));
4298 let hi = self.span.hi;
4300 let ret_ty = try!(self.parse_ret_ty());
4302 let fn_decl = P(FnDecl {
4308 Ok((spanned(lo, hi, explicit_self), fn_decl))
4311 // parse the |arg, arg| header on a lambda
4312 fn parse_fn_block_decl(&mut self) -> PResult<P<FnDecl>> {
4313 let inputs_captures = {
4314 if try!(self.eat(&token::OrOr) ){
4317 try!(self.expect(&token::BinOp(token::Or)));
4318 try!(self.parse_obsolete_closure_kind());
4319 let args = try!(self.parse_seq_to_before_end(
4320 &token::BinOp(token::Or),
4321 seq_sep_trailing_allowed(token::Comma),
4322 |p| p.parse_fn_block_arg()
4328 let output = try!(self.parse_ret_ty());
4331 inputs: inputs_captures,
4337 /// Parse the name and optional generic types of a function header.
4338 fn parse_fn_header(&mut self) -> PResult<(Ident, ast::Generics)> {
4339 let id = try!(self.parse_ident());
4340 let generics = try!(self.parse_generics());
4344 fn mk_item(&mut self, lo: BytePos, hi: BytePos, ident: Ident,
4345 node: Item_, vis: Visibility,
4346 attrs: Vec<Attribute>) -> P<Item> {
4350 id: ast::DUMMY_NODE_ID,
4357 /// Parse an item-position function declaration.
4358 fn parse_item_fn(&mut self,
4360 constness: Constness,
4362 -> PResult<ItemInfo> {
4363 let (ident, mut generics) = try!(self.parse_fn_header());
4364 let decl = try!(self.parse_fn_decl(false));
4365 generics.where_clause = try!(self.parse_where_clause());
4366 let (inner_attrs, body) = try!(self.parse_inner_attrs_and_block());
4367 Ok((ident, ItemFn(decl, unsafety, constness, abi, generics, body), Some(inner_attrs)))
4370 /// true if we are looking at `const ID`, false for things like `const fn` etc
4371 pub fn is_const_item(&mut self) -> bool {
4372 self.token.is_keyword(keywords::Const) &&
4373 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn))
4376 /// parses all the "front matter" for a `fn` declaration, up to
4377 /// and including the `fn` keyword:
4383 pub fn parse_fn_front_matter(&mut self) -> PResult<(ast::Constness, ast::Unsafety, abi::Abi)> {
4384 let is_const_fn = try!(self.eat_keyword(keywords::Const));
4385 let (constness, unsafety, abi) = if is_const_fn {
4386 (Constness::Const, Unsafety::Normal, abi::Rust)
4388 let unsafety = try!(self.parse_unsafety());
4389 let abi = if try!(self.eat_keyword(keywords::Extern)) {
4390 try!(self.parse_opt_abi()).unwrap_or(abi::C)
4394 (Constness::NotConst, unsafety, abi)
4396 try!(self.expect_keyword(keywords::Fn));
4397 Ok((constness, unsafety, abi))
4400 /// Parse an impl item.
4401 pub fn parse_impl_item(&mut self) -> PResult<P<ImplItem>> {
4402 maybe_whole!(no_clone self, NtImplItem);
4404 let mut attrs = self.parse_outer_attributes();
4405 let lo = self.span.lo;
4406 let vis = try!(self.parse_visibility());
4407 let (name, node) = if try!(self.eat_keyword(keywords::Type)) {
4408 let name = try!(self.parse_ident());
4409 try!(self.expect(&token::Eq));
4410 let typ = try!(self.parse_ty_sum());
4411 try!(self.expect(&token::Semi));
4412 (name, TypeImplItem(typ))
4413 } else if self.is_const_item() {
4414 try!(self.expect_keyword(keywords::Const));
4415 let name = try!(self.parse_ident());
4416 try!(self.expect(&token::Colon));
4417 let typ = try!(self.parse_ty_sum());
4418 try!(self.expect(&token::Eq));
4419 let expr = try!(self.parse_expr_nopanic());
4420 try!(self.commit_expr_expecting(&expr, token::Semi));
4421 (name, ConstImplItem(typ, expr))
4423 let (name, inner_attrs, node) = try!(self.parse_impl_method(vis));
4424 attrs.extend(inner_attrs);
4429 id: ast::DUMMY_NODE_ID,
4430 span: mk_sp(lo, self.last_span.hi),
4438 fn complain_if_pub_macro(&mut self, visa: Visibility, span: Span) {
4441 self.span_err(span, "can't qualify macro invocation with `pub`");
4442 self.fileline_help(span, "try adjusting the macro to put `pub` inside \
4449 /// Parse a method or a macro invocation in a trait impl.
4450 fn parse_impl_method(&mut self, vis: Visibility)
4451 -> PResult<(Ident, Vec<ast::Attribute>, ast::ImplItem_)> {
4452 // code copied from parse_macro_use_or_failure... abstraction!
4453 if !self.token.is_any_keyword()
4454 && self.look_ahead(1, |t| *t == token::Not)
4455 && (self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren))
4456 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) {
4459 let last_span = self.last_span;
4460 self.complain_if_pub_macro(vis, last_span);
4462 let pth = try!(self.parse_path(NoTypesAllowed));
4463 try!(self.expect(&token::Not));
4465 // eat a matched-delimiter token tree:
4466 let delim = try!(self.expect_open_delim());
4467 let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
4469 |p| p.parse_token_tree()));
4470 let m_ = ast::MacInvocTT(pth, tts, EMPTY_CTXT);
4471 let m: ast::Mac = codemap::Spanned { node: m_,
4472 span: mk_sp(self.span.lo,
4474 if delim != token::Brace {
4475 try!(self.expect(&token::Semi))
4477 Ok((token::special_idents::invalid, vec![], ast::MacImplItem(m)))
4479 let (constness, unsafety, abi) = try!(self.parse_fn_front_matter());
4480 let ident = try!(self.parse_ident());
4481 let mut generics = try!(self.parse_generics());
4482 let (explicit_self, decl) = try!(self.parse_fn_decl_with_self(|p| {
4485 generics.where_clause = try!(self.parse_where_clause());
4486 let (inner_attrs, body) = try!(self.parse_inner_attrs_and_block());
4487 Ok((ident, inner_attrs, MethodImplItem(ast::MethodSig {
4490 explicit_self: explicit_self,
4492 constness: constness,
4498 /// Parse trait Foo { ... }
4499 fn parse_item_trait(&mut self, unsafety: Unsafety) -> PResult<ItemInfo> {
4501 let ident = try!(self.parse_ident());
4502 let mut tps = try!(self.parse_generics());
4504 // Parse supertrait bounds.
4505 let bounds = try!(self.parse_colon_then_ty_param_bounds(BoundParsingMode::Bare));
4507 tps.where_clause = try!(self.parse_where_clause());
4509 let meths = try!(self.parse_trait_items());
4510 Ok((ident, ItemTrait(unsafety, tps, bounds, meths), None))
4513 /// Parses items implementations variants
4514 /// impl<T> Foo { ... }
4515 /// impl<T> ToString for &'static T { ... }
4516 /// impl Send for .. {}
4517 fn parse_item_impl(&mut self, unsafety: ast::Unsafety) -> PResult<ItemInfo> {
4518 let impl_span = self.span;
4520 // First, parse type parameters if necessary.
4521 let mut generics = try!(self.parse_generics());
4523 // Special case: if the next identifier that follows is '(', don't
4524 // allow this to be parsed as a trait.
4525 let could_be_trait = self.token != token::OpenDelim(token::Paren);
4527 let neg_span = self.span;
4528 let polarity = if try!(self.eat(&token::Not) ){
4529 ast::ImplPolarity::Negative
4531 ast::ImplPolarity::Positive
4535 let mut ty = try!(self.parse_ty_sum());
4537 // Parse traits, if necessary.
4538 let opt_trait = if could_be_trait && try!(self.eat_keyword(keywords::For) ){
4539 // New-style trait. Reinterpret the type as a trait.
4541 TyPath(None, ref path) => {
4543 path: (*path).clone(),
4548 self.span_err(ty.span, "not a trait");
4554 ast::ImplPolarity::Negative => {
4555 // This is a negated type implementation
4556 // `impl !MyType {}`, which is not allowed.
4557 self.span_err(neg_span, "inherent implementation can't be negated");
4564 if try!(self.eat(&token::DotDot) ){
4565 if generics.is_parameterized() {
4566 self.span_err(impl_span, "default trait implementations are not \
4567 allowed to have generics");
4570 try!(self.expect(&token::OpenDelim(token::Brace)));
4571 try!(self.expect(&token::CloseDelim(token::Brace)));
4572 Ok((ast_util::impl_pretty_name(&opt_trait, None),
4573 ItemDefaultImpl(unsafety, opt_trait.unwrap()), None))
4575 if opt_trait.is_some() {
4576 ty = try!(self.parse_ty_sum());
4578 generics.where_clause = try!(self.parse_where_clause());
4580 try!(self.expect(&token::OpenDelim(token::Brace)));
4581 let attrs = self.parse_inner_attributes();
4583 let mut impl_items = vec![];
4584 while !try!(self.eat(&token::CloseDelim(token::Brace))) {
4585 impl_items.push(try!(self.parse_impl_item()));
4588 Ok((ast_util::impl_pretty_name(&opt_trait, Some(&*ty)),
4589 ItemImpl(unsafety, polarity, generics, opt_trait, ty, impl_items),
4594 /// Parse a::B<String,i32>
4595 fn parse_trait_ref(&mut self) -> PResult<TraitRef> {
4597 path: try!(self.parse_path(LifetimeAndTypesWithoutColons)),
4598 ref_id: ast::DUMMY_NODE_ID,
4602 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<Vec<ast::LifetimeDef>> {
4603 if try!(self.eat_keyword(keywords::For) ){
4604 try!(self.expect(&token::Lt));
4605 let lifetime_defs = try!(self.parse_lifetime_defs());
4606 try!(self.expect_gt());
4613 /// Parse for<'l> a::B<String,i32>
4614 fn parse_poly_trait_ref(&mut self) -> PResult<PolyTraitRef> {
4615 let lo = self.span.lo;
4616 let lifetime_defs = try!(self.parse_late_bound_lifetime_defs());
4618 Ok(ast::PolyTraitRef {
4619 bound_lifetimes: lifetime_defs,
4620 trait_ref: try!(self.parse_trait_ref()),
4621 span: mk_sp(lo, self.last_span.hi),
4625 /// Parse struct Foo { ... }
4626 fn parse_item_struct(&mut self) -> PResult<ItemInfo> {
4627 let class_name = try!(self.parse_ident());
4628 let mut generics = try!(self.parse_generics());
4630 if try!(self.eat(&token::Colon) ){
4631 let ty = try!(self.parse_ty_sum());
4632 self.span_err(ty.span, "`virtual` structs have been removed from the language");
4635 // There is a special case worth noting here, as reported in issue #17904.
4636 // If we are parsing a tuple struct it is the case that the where clause
4637 // should follow the field list. Like so:
4639 // struct Foo<T>(T) where T: Copy;
4641 // If we are parsing a normal record-style struct it is the case
4642 // that the where clause comes before the body, and after the generics.
4643 // So if we look ahead and see a brace or a where-clause we begin
4644 // parsing a record style struct.
4646 // Otherwise if we look ahead and see a paren we parse a tuple-style
4649 let (fields, ctor_id) = if self.token.is_keyword(keywords::Where) {
4650 generics.where_clause = try!(self.parse_where_clause());
4651 if try!(self.eat(&token::Semi)) {
4652 // If we see a: `struct Foo<T> where T: Copy;` style decl.
4653 (Vec::new(), Some(ast::DUMMY_NODE_ID))
4655 // If we see: `struct Foo<T> where T: Copy { ... }`
4656 (try!(self.parse_record_struct_body(&class_name)), None)
4658 // No `where` so: `struct Foo<T>;`
4659 } else if try!(self.eat(&token::Semi) ){
4660 (Vec::new(), Some(ast::DUMMY_NODE_ID))
4661 // Record-style struct definition
4662 } else if self.token == token::OpenDelim(token::Brace) {
4663 let fields = try!(self.parse_record_struct_body(&class_name));
4665 // Tuple-style struct definition with optional where-clause.
4667 let fields = try!(self.parse_tuple_struct_body(&class_name, &mut generics));
4668 (fields, Some(ast::DUMMY_NODE_ID))
4672 ItemStruct(P(ast::StructDef {
4679 pub fn parse_record_struct_body(&mut self,
4680 class_name: &ast::Ident) -> PResult<Vec<StructField>> {
4681 let mut fields = Vec::new();
4682 if try!(self.eat(&token::OpenDelim(token::Brace)) ){
4683 while self.token != token::CloseDelim(token::Brace) {
4684 fields.push(try!(self.parse_struct_decl_field(true)));
4687 if fields.is_empty() {
4688 return Err(self.fatal(&format!("unit-like struct definition should be \
4689 written as `struct {};`",
4690 token::get_ident(class_name.clone()))));
4695 let token_str = self.this_token_to_string();
4696 return Err(self.fatal(&format!("expected `where`, or `{}` after struct \
4697 name, found `{}`", "{",
4704 pub fn parse_tuple_struct_body(&mut self,
4705 class_name: &ast::Ident,
4706 generics: &mut ast::Generics)
4707 -> PResult<Vec<StructField>> {
4708 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
4709 if self.check(&token::OpenDelim(token::Paren)) {
4710 let fields = try!(self.parse_unspanned_seq(
4711 &token::OpenDelim(token::Paren),
4712 &token::CloseDelim(token::Paren),
4713 seq_sep_trailing_allowed(token::Comma),
4715 let attrs = p.parse_outer_attributes();
4717 let struct_field_ = ast::StructField_ {
4718 kind: UnnamedField(try!(p.parse_visibility())),
4719 id: ast::DUMMY_NODE_ID,
4720 ty: try!(p.parse_ty_sum()),
4723 Ok(spanned(lo, p.span.hi, struct_field_))
4726 if fields.is_empty() {
4727 return Err(self.fatal(&format!("unit-like struct definition should be \
4728 written as `struct {};`",
4729 token::get_ident(class_name.clone()))));
4732 generics.where_clause = try!(self.parse_where_clause());
4733 try!(self.expect(&token::Semi));
4735 // This is the case where we just see struct Foo<T> where T: Copy;
4736 } else if self.token.is_keyword(keywords::Where) {
4737 generics.where_clause = try!(self.parse_where_clause());
4738 try!(self.expect(&token::Semi));
4740 // This case is where we see: `struct Foo<T>;`
4742 let token_str = self.this_token_to_string();
4743 Err(self.fatal(&format!("expected `where`, `{}`, `(`, or `;` after struct \
4744 name, found `{}`", "{", token_str)))
4748 /// Parse a structure field declaration
4749 pub fn parse_single_struct_field(&mut self,
4751 attrs: Vec<Attribute> )
4752 -> PResult<StructField> {
4753 let a_var = try!(self.parse_name_and_ty(vis, attrs));
4758 token::CloseDelim(token::Brace) => {}
4760 let span = self.span;
4761 let token_str = self.this_token_to_string();
4762 return Err(self.span_fatal_help(span,
4763 &format!("expected `,`, or `}}`, found `{}`",
4765 "struct fields should be separated by commas"))
4771 /// Parse an element of a struct definition
4772 fn parse_struct_decl_field(&mut self, allow_pub: bool) -> PResult<StructField> {
4774 let attrs = self.parse_outer_attributes();
4776 if try!(self.eat_keyword(keywords::Pub) ){
4778 let span = self.last_span;
4779 self.span_err(span, "`pub` is not allowed here");
4781 return self.parse_single_struct_field(Public, attrs);
4784 return self.parse_single_struct_field(Inherited, attrs);
4787 /// Parse visibility: PUB or nothing
4788 fn parse_visibility(&mut self) -> PResult<Visibility> {
4789 if try!(self.eat_keyword(keywords::Pub)) { Ok(Public) }
4790 else { Ok(Inherited) }
4793 /// Given a termination token, parse all of the items in a module
4794 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: BytePos) -> PResult<Mod> {
4795 let mut items = vec![];
4796 while let Some(item) = try!(self.parse_item_nopanic()) {
4800 if !try!(self.eat(term)) {
4801 let token_str = self.this_token_to_string();
4802 return Err(self.fatal(&format!("expected item, found `{}`", token_str)));
4806 inner: mk_sp(inner_lo, self.span.lo),
4811 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<ItemInfo> {
4812 let id = try!(self.parse_ident());
4813 try!(self.expect(&token::Colon));
4814 let ty = try!(self.parse_ty_sum());
4815 try!(self.expect(&token::Eq));
4816 let e = try!(self.parse_expr_nopanic());
4817 try!(self.commit_expr_expecting(&*e, token::Semi));
4818 let item = match m {
4819 Some(m) => ItemStatic(ty, m, e),
4820 None => ItemConst(ty, e),
4822 Ok((id, item, None))
4825 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
4826 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<ItemInfo> {
4827 let id_span = self.span;
4828 let id = try!(self.parse_ident());
4829 if self.check(&token::Semi) {
4831 // This mod is in an external file. Let's go get it!
4832 let (m, attrs) = try!(self.eval_src_mod(id, outer_attrs, id_span));
4833 Ok((id, m, Some(attrs)))
4835 self.push_mod_path(id, outer_attrs);
4836 try!(self.expect(&token::OpenDelim(token::Brace)));
4837 let mod_inner_lo = self.span.lo;
4838 let old_owns_directory = self.owns_directory;
4839 self.owns_directory = true;
4840 let attrs = self.parse_inner_attributes();
4841 let m = try!(self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo));
4842 self.owns_directory = old_owns_directory;
4843 self.pop_mod_path();
4844 Ok((id, ItemMod(m), Some(attrs)))
4848 fn push_mod_path(&mut self, id: Ident, attrs: &[Attribute]) {
4849 let default_path = self.id_to_interned_str(id);
4850 let file_path = match ::attr::first_attr_value_str_by_name(attrs,
4853 None => default_path,
4855 self.mod_path_stack.push(file_path)
4858 fn pop_mod_path(&mut self) {
4859 self.mod_path_stack.pop().unwrap();
4862 /// Read a module from a source file.
4863 fn eval_src_mod(&mut self,
4865 outer_attrs: &[ast::Attribute],
4867 -> PResult<(ast::Item_, Vec<ast::Attribute> )> {
4868 let mut prefix = PathBuf::from(&self.sess.codemap().span_to_filename(self.span));
4870 let mut dir_path = prefix;
4871 for part in &self.mod_path_stack {
4872 dir_path.push(&**part);
4874 let mod_string = token::get_ident(id);
4875 let (file_path, owns_directory) = match ::attr::first_attr_value_str_by_name(
4876 outer_attrs, "path") {
4877 Some(d) => (dir_path.join(&*d), true),
4879 let mod_name = mod_string.to_string();
4880 let default_path_str = format!("{}.rs", mod_name);
4881 let secondary_path_str = format!("{}/mod.rs", mod_name);
4882 let default_path = dir_path.join(&default_path_str[..]);
4883 let secondary_path = dir_path.join(&secondary_path_str[..]);
4884 let default_exists = self.sess.codemap().file_exists(&default_path);
4885 let secondary_exists = self.sess.codemap().file_exists(&secondary_path);
4887 if !self.owns_directory {
4888 self.span_err(id_sp,
4889 "cannot declare a new module at this location");
4890 let this_module = match self.mod_path_stack.last() {
4891 Some(name) => name.to_string(),
4892 None => self.root_module_name.as_ref().unwrap().clone(),
4894 self.span_note(id_sp,
4895 &format!("maybe move this module `{0}` \
4896 to its own directory via \
4899 if default_exists || secondary_exists {
4900 self.span_note(id_sp,
4901 &format!("... or maybe `use` the module \
4902 `{}` instead of possibly \
4906 self.abort_if_errors();
4909 match (default_exists, secondary_exists) {
4910 (true, false) => (default_path, false),
4911 (false, true) => (secondary_path, true),
4913 return Err(self.span_fatal_help(id_sp,
4914 &format!("file not found for module `{}`",
4916 &format!("name the file either {} or {} inside \
4917 the directory {:?}",
4920 dir_path.display())));
4923 return Err(self.span_fatal_help(
4925 &format!("file for module `{}` found at both {} \
4929 secondary_path_str),
4930 "delete or rename one of them to remove the ambiguity"));
4936 self.eval_src_mod_from_path(file_path, owns_directory,
4937 mod_string.to_string(), id_sp)
4940 fn eval_src_mod_from_path(&mut self,
4942 owns_directory: bool,
4944 id_sp: Span) -> PResult<(ast::Item_, Vec<ast::Attribute> )> {
4945 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
4946 match included_mod_stack.iter().position(|p| *p == path) {
4948 let mut err = String::from("circular modules: ");
4949 let len = included_mod_stack.len();
4950 for p in &included_mod_stack[i.. len] {
4951 err.push_str(&p.to_string_lossy());
4952 err.push_str(" -> ");
4954 err.push_str(&path.to_string_lossy());
4955 return Err(self.span_fatal(id_sp, &err[..]));
4959 included_mod_stack.push(path.clone());
4960 drop(included_mod_stack);
4963 new_sub_parser_from_file(self.sess,
4969 let mod_inner_lo = p0.span.lo;
4970 let mod_attrs = p0.parse_inner_attributes();
4971 let m0 = try!(p0.parse_mod_items(&token::Eof, mod_inner_lo));
4972 self.sess.included_mod_stack.borrow_mut().pop();
4973 Ok((ast::ItemMod(m0), mod_attrs))
4976 /// Parse a function declaration from a foreign module
4977 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility,
4978 attrs: Vec<Attribute>) -> PResult<P<ForeignItem>> {
4979 let lo = self.span.lo;
4980 try!(self.expect_keyword(keywords::Fn));
4982 let (ident, mut generics) = try!(self.parse_fn_header());
4983 let decl = try!(self.parse_fn_decl(true));
4984 generics.where_clause = try!(self.parse_where_clause());
4985 let hi = self.span.hi;
4986 try!(self.expect(&token::Semi));
4987 Ok(P(ast::ForeignItem {
4990 node: ForeignItemFn(decl, generics),
4991 id: ast::DUMMY_NODE_ID,
4992 span: mk_sp(lo, hi),
4997 /// Parse a static item from a foreign module
4998 fn parse_item_foreign_static(&mut self, vis: ast::Visibility,
4999 attrs: Vec<Attribute>) -> PResult<P<ForeignItem>> {
5000 let lo = self.span.lo;
5002 try!(self.expect_keyword(keywords::Static));
5003 let mutbl = try!(self.eat_keyword(keywords::Mut));
5005 let ident = try!(self.parse_ident());
5006 try!(self.expect(&token::Colon));
5007 let ty = try!(self.parse_ty_sum());
5008 let hi = self.span.hi;
5009 try!(self.expect(&token::Semi));
5013 node: ForeignItemStatic(ty, mutbl),
5014 id: ast::DUMMY_NODE_ID,
5015 span: mk_sp(lo, hi),
5020 /// Parse extern crate links
5024 /// extern crate foo;
5025 /// extern crate bar as foo;
5026 fn parse_item_extern_crate(&mut self,
5028 visibility: Visibility,
5029 attrs: Vec<Attribute>)
5030 -> PResult<P<Item>> {
5032 let crate_name = try!(self.parse_ident());
5033 let (maybe_path, ident) = if try!(self.eat_keyword(keywords::As)) {
5034 (Some(crate_name.name), try!(self.parse_ident()))
5038 try!(self.expect(&token::Semi));
5040 let last_span = self.last_span;
5044 ItemExternCrate(maybe_path),
5049 /// Parse `extern` for foreign ABIs
5052 /// `extern` is expected to have been
5053 /// consumed before calling this method
5059 fn parse_item_foreign_mod(&mut self,
5061 opt_abi: Option<abi::Abi>,
5062 visibility: Visibility,
5063 mut attrs: Vec<Attribute>)
5064 -> PResult<P<Item>> {
5065 try!(self.expect(&token::OpenDelim(token::Brace)));
5067 let abi = opt_abi.unwrap_or(abi::C);
5069 attrs.extend(self.parse_inner_attributes());
5071 let mut foreign_items = vec![];
5072 while let Some(item) = try!(self.parse_foreign_item()) {
5073 foreign_items.push(item);
5075 try!(self.expect(&token::CloseDelim(token::Brace)));
5077 let last_span = self.last_span;
5078 let m = ast::ForeignMod {
5080 items: foreign_items
5084 special_idents::invalid,
5090 /// Parse type Foo = Bar;
5091 fn parse_item_type(&mut self) -> PResult<ItemInfo> {
5092 let ident = try!(self.parse_ident());
5093 let mut tps = try!(self.parse_generics());
5094 tps.where_clause = try!(self.parse_where_clause());
5095 try!(self.expect(&token::Eq));
5096 let ty = try!(self.parse_ty_sum());
5097 try!(self.expect(&token::Semi));
5098 Ok((ident, ItemTy(ty, tps), None))
5101 /// Parse a structure-like enum variant definition
5102 /// this should probably be renamed or refactored...
5103 fn parse_struct_def(&mut self) -> PResult<P<StructDef>> {
5104 let mut fields: Vec<StructField> = Vec::new();
5105 while self.token != token::CloseDelim(token::Brace) {
5106 fields.push(try!(self.parse_struct_decl_field(false)));
5116 /// Parse the part of an "enum" decl following the '{'
5117 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<EnumDef> {
5118 let mut variants = Vec::new();
5119 let mut all_nullary = true;
5120 let mut any_disr = None;
5121 while self.token != token::CloseDelim(token::Brace) {
5122 let variant_attrs = self.parse_outer_attributes();
5123 let vlo = self.span.lo;
5125 let vis = try!(self.parse_visibility());
5129 let mut args = Vec::new();
5130 let mut disr_expr = None;
5131 ident = try!(self.parse_ident());
5132 if try!(self.eat(&token::OpenDelim(token::Brace)) ){
5133 // Parse a struct variant.
5134 all_nullary = false;
5135 let start_span = self.span;
5136 let struct_def = try!(self.parse_struct_def());
5137 if struct_def.fields.is_empty() {
5138 self.span_err(start_span,
5139 &format!("unit-like struct variant should be written \
5140 without braces, as `{},`",
5141 token::get_ident(ident)));
5143 kind = StructVariantKind(struct_def);
5144 } else if self.check(&token::OpenDelim(token::Paren)) {
5145 all_nullary = false;
5146 let arg_tys = try!(self.parse_enum_variant_seq(
5147 &token::OpenDelim(token::Paren),
5148 &token::CloseDelim(token::Paren),
5149 seq_sep_trailing_allowed(token::Comma),
5150 |p| p.parse_ty_sum()
5153 args.push(ast::VariantArg {
5155 id: ast::DUMMY_NODE_ID,
5158 kind = TupleVariantKind(args);
5159 } else if try!(self.eat(&token::Eq) ){
5160 disr_expr = Some(try!(self.parse_expr_nopanic()));
5161 any_disr = disr_expr.as_ref().map(|expr| expr.span);
5162 kind = TupleVariantKind(args);
5164 kind = TupleVariantKind(Vec::new());
5167 let vr = ast::Variant_ {
5169 attrs: variant_attrs,
5171 id: ast::DUMMY_NODE_ID,
5172 disr_expr: disr_expr,
5175 variants.push(P(spanned(vlo, self.last_span.hi, vr)));
5177 if !try!(self.eat(&token::Comma)) { break; }
5179 try!(self.expect(&token::CloseDelim(token::Brace)));
5181 Some(disr_span) if !all_nullary =>
5182 self.span_err(disr_span,
5183 "discriminator values can only be used with a c-like enum"),
5187 Ok(ast::EnumDef { variants: variants })
5190 /// Parse an "enum" declaration
5191 fn parse_item_enum(&mut self) -> PResult<ItemInfo> {
5192 let id = try!(self.parse_ident());
5193 let mut generics = try!(self.parse_generics());
5194 generics.where_clause = try!(self.parse_where_clause());
5195 try!(self.expect(&token::OpenDelim(token::Brace)));
5197 let enum_definition = try!(self.parse_enum_def(&generics));
5198 Ok((id, ItemEnum(enum_definition, generics), None))
5201 /// Parses a string as an ABI spec on an extern type or module. Consumes
5202 /// the `extern` keyword, if one is found.
5203 fn parse_opt_abi(&mut self) -> PResult<Option<abi::Abi>> {
5205 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
5207 self.expect_no_suffix(sp, "ABI spec", suf);
5209 let the_string = s.as_str();
5210 match abi::lookup(the_string) {
5211 Some(abi) => Ok(Some(abi)),
5213 let last_span = self.last_span;
5216 &format!("illegal ABI: expected one of [{}], \
5218 abi::all_names().join(", "),
5229 /// Parse one of the items allowed by the flags.
5230 /// NB: this function no longer parses the items inside an
5232 fn parse_item_(&mut self, attrs: Vec<Attribute>,
5233 macros_allowed: bool) -> PResult<Option<P<Item>>> {
5234 let nt_item = match self.token {
5235 token::Interpolated(token::NtItem(ref item)) => {
5236 Some((**item).clone())
5243 let mut attrs = attrs;
5244 mem::swap(&mut item.attrs, &mut attrs);
5245 item.attrs.extend(attrs);
5246 return Ok(Some(P(item)));
5251 let lo = self.span.lo;
5253 let visibility = try!(self.parse_visibility());
5255 if try!(self.eat_keyword(keywords::Use) ){
5257 let item_ = ItemUse(try!(self.parse_view_path()));
5258 try!(self.expect(&token::Semi));
5260 let last_span = self.last_span;
5261 let item = self.mk_item(lo,
5263 token::special_idents::invalid,
5267 return Ok(Some(item));
5270 if try!(self.eat_keyword(keywords::Extern)) {
5271 if try!(self.eat_keyword(keywords::Crate)) {
5272 return Ok(Some(try!(self.parse_item_extern_crate(lo, visibility, attrs))));
5275 let opt_abi = try!(self.parse_opt_abi());
5277 if try!(self.eat_keyword(keywords::Fn) ){
5278 // EXTERN FUNCTION ITEM
5279 let abi = opt_abi.unwrap_or(abi::C);
5280 let (ident, item_, extra_attrs) =
5281 try!(self.parse_item_fn(Unsafety::Normal, Constness::NotConst, abi));
5282 let last_span = self.last_span;
5283 let item = self.mk_item(lo,
5288 maybe_append(attrs, extra_attrs));
5289 return Ok(Some(item));
5290 } else if self.check(&token::OpenDelim(token::Brace)) {
5291 return Ok(Some(try!(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs))));
5294 try!(self.expect_one_of(&[], &[]));
5297 if try!(self.eat_keyword_noexpect(keywords::Virtual) ){
5298 let span = self.span;
5299 self.span_err(span, "`virtual` structs have been removed from the language");
5302 if try!(self.eat_keyword(keywords::Static) ){
5304 let m = if try!(self.eat_keyword(keywords::Mut)) {MutMutable} else {MutImmutable};
5305 let (ident, item_, extra_attrs) = try!(self.parse_item_const(Some(m)));
5306 let last_span = self.last_span;
5307 let item = self.mk_item(lo,
5312 maybe_append(attrs, extra_attrs));
5313 return Ok(Some(item));
5315 if try!(self.eat_keyword(keywords::Const) ){
5316 if self.check_keyword(keywords::Fn) {
5317 // CONST FUNCTION ITEM
5319 let (ident, item_, extra_attrs) =
5320 try!(self.parse_item_fn(Unsafety::Normal, Constness::Const, abi::Rust));
5321 let last_span = self.last_span;
5322 let item = self.mk_item(lo,
5327 maybe_append(attrs, extra_attrs));
5328 return Ok(Some(item));
5332 if try!(self.eat_keyword(keywords::Mut) ){
5333 let last_span = self.last_span;
5334 self.span_err(last_span, "const globals cannot be mutable");
5335 self.fileline_help(last_span, "did you mean to declare a static?");
5337 let (ident, item_, extra_attrs) = try!(self.parse_item_const(None));
5338 let last_span = self.last_span;
5339 let item = self.mk_item(lo,
5344 maybe_append(attrs, extra_attrs));
5345 return Ok(Some(item));
5347 if self.check_keyword(keywords::Unsafe) &&
5348 self.look_ahead(1, |t| t.is_keyword(keywords::Trait))
5350 // UNSAFE TRAIT ITEM
5351 try!(self.expect_keyword(keywords::Unsafe));
5352 try!(self.expect_keyword(keywords::Trait));
5353 let (ident, item_, extra_attrs) =
5354 try!(self.parse_item_trait(ast::Unsafety::Unsafe));
5355 let last_span = self.last_span;
5356 let item = self.mk_item(lo,
5361 maybe_append(attrs, extra_attrs));
5362 return Ok(Some(item));
5364 if self.check_keyword(keywords::Unsafe) &&
5365 self.look_ahead(1, |t| t.is_keyword(keywords::Impl))
5368 try!(self.expect_keyword(keywords::Unsafe));
5369 try!(self.expect_keyword(keywords::Impl));
5370 let (ident, item_, extra_attrs) = try!(self.parse_item_impl(ast::Unsafety::Unsafe));
5371 let last_span = self.last_span;
5372 let item = self.mk_item(lo,
5377 maybe_append(attrs, extra_attrs));
5378 return Ok(Some(item));
5380 if self.check_keyword(keywords::Fn) {
5383 let (ident, item_, extra_attrs) =
5384 try!(self.parse_item_fn(Unsafety::Normal, Constness::NotConst, abi::Rust));
5385 let last_span = self.last_span;
5386 let item = self.mk_item(lo,
5391 maybe_append(attrs, extra_attrs));
5392 return Ok(Some(item));
5394 if self.check_keyword(keywords::Unsafe)
5395 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
5396 // UNSAFE FUNCTION ITEM
5398 let abi = if try!(self.eat_keyword(keywords::Extern) ){
5399 try!(self.parse_opt_abi()).unwrap_or(abi::C)
5403 try!(self.expect_keyword(keywords::Fn));
5404 let (ident, item_, extra_attrs) =
5405 try!(self.parse_item_fn(Unsafety::Unsafe, Constness::NotConst, abi));
5406 let last_span = self.last_span;
5407 let item = self.mk_item(lo,
5412 maybe_append(attrs, extra_attrs));
5413 return Ok(Some(item));
5415 if try!(self.eat_keyword(keywords::Mod) ){
5417 let (ident, item_, extra_attrs) =
5418 try!(self.parse_item_mod(&attrs[..]));
5419 let last_span = self.last_span;
5420 let item = self.mk_item(lo,
5425 maybe_append(attrs, extra_attrs));
5426 return Ok(Some(item));
5428 if try!(self.eat_keyword(keywords::Type) ){
5430 let (ident, item_, extra_attrs) = try!(self.parse_item_type());
5431 let last_span = self.last_span;
5432 let item = self.mk_item(lo,
5437 maybe_append(attrs, extra_attrs));
5438 return Ok(Some(item));
5440 if try!(self.eat_keyword(keywords::Enum) ){
5442 let (ident, item_, extra_attrs) = try!(self.parse_item_enum());
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 try!(self.eat_keyword(keywords::Trait) ){
5454 let (ident, item_, extra_attrs) =
5455 try!(self.parse_item_trait(ast::Unsafety::Normal));
5456 let last_span = self.last_span;
5457 let item = self.mk_item(lo,
5462 maybe_append(attrs, extra_attrs));
5463 return Ok(Some(item));
5465 if try!(self.eat_keyword(keywords::Impl) ){
5467 let (ident, item_, extra_attrs) = try!(self.parse_item_impl(ast::Unsafety::Normal));
5468 let last_span = self.last_span;
5469 let item = self.mk_item(lo,
5474 maybe_append(attrs, extra_attrs));
5475 return Ok(Some(item));
5477 if try!(self.eat_keyword(keywords::Struct) ){
5479 let (ident, item_, extra_attrs) = try!(self.parse_item_struct());
5480 let last_span = self.last_span;
5481 let item = self.mk_item(lo,
5486 maybe_append(attrs, extra_attrs));
5487 return Ok(Some(item));
5489 self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility)
5492 /// Parse a foreign item.
5493 fn parse_foreign_item(&mut self) -> PResult<Option<P<ForeignItem>>> {
5494 let attrs = self.parse_outer_attributes();
5495 let lo = self.span.lo;
5496 let visibility = try!(self.parse_visibility());
5498 if self.check_keyword(keywords::Static) {
5499 // FOREIGN STATIC ITEM
5500 return Ok(Some(try!(self.parse_item_foreign_static(visibility, attrs))));
5502 if self.check_keyword(keywords::Fn) || self.check_keyword(keywords::Unsafe) {
5503 // FOREIGN FUNCTION ITEM
5504 return Ok(Some(try!(self.parse_item_foreign_fn(visibility, attrs))));
5507 // FIXME #5668: this will occur for a macro invocation:
5508 match try!(self.parse_macro_use_or_failure(attrs, true, lo, visibility)) {
5510 return Err(self.span_fatal(item.span, "macros cannot expand to foreign items"));
5516 /// This is the fall-through for parsing items.
5517 fn parse_macro_use_or_failure(
5519 attrs: Vec<Attribute> ,
5520 macros_allowed: bool,
5522 visibility: Visibility
5523 ) -> PResult<Option<P<Item>>> {
5524 if macros_allowed && !self.token.is_any_keyword()
5525 && self.look_ahead(1, |t| *t == token::Not)
5526 && (self.look_ahead(2, |t| t.is_plain_ident())
5527 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren))
5528 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) {
5529 // MACRO INVOCATION ITEM
5531 let last_span = self.last_span;
5532 self.complain_if_pub_macro(visibility, last_span);
5535 let pth = try!(self.parse_path(NoTypesAllowed));
5536 try!(self.expect(&token::Not));
5538 // a 'special' identifier (like what `macro_rules!` uses)
5539 // is optional. We should eventually unify invoc syntax
5541 let id = if self.token.is_plain_ident() {
5542 try!(self.parse_ident())
5544 token::special_idents::invalid // no special identifier
5546 // eat a matched-delimiter token tree:
5547 let delim = try!(self.expect_open_delim());
5548 let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
5550 |p| p.parse_token_tree()));
5551 // single-variant-enum... :
5552 let m = ast::MacInvocTT(pth, tts, EMPTY_CTXT);
5553 let m: ast::Mac = codemap::Spanned { node: m,
5554 span: mk_sp(self.span.lo,
5557 if delim != token::Brace {
5558 if !try!(self.eat(&token::Semi) ){
5559 let last_span = self.last_span;
5560 self.span_err(last_span,
5561 "macros that expand to items must either \
5562 be surrounded with braces or followed by \
5567 let item_ = ItemMac(m);
5568 let last_span = self.last_span;
5569 let item = self.mk_item(lo,
5575 return Ok(Some(item));
5578 // FAILURE TO PARSE ITEM
5582 let last_span = self.last_span;
5583 return Err(self.span_fatal(last_span, "unmatched visibility `pub`"));
5587 if !attrs.is_empty() {
5588 self.expected_item_err(&attrs);
5593 pub fn parse_item_nopanic(&mut self) -> PResult<Option<P<Item>>> {
5594 let attrs = self.parse_outer_attributes();
5595 self.parse_item_(attrs, true)
5599 /// Matches view_path : MOD? non_global_path as IDENT
5600 /// | MOD? non_global_path MOD_SEP LBRACE RBRACE
5601 /// | MOD? non_global_path MOD_SEP LBRACE ident_seq RBRACE
5602 /// | MOD? non_global_path MOD_SEP STAR
5603 /// | MOD? non_global_path
5604 fn parse_view_path(&mut self) -> PResult<P<ViewPath>> {
5605 let lo = self.span.lo;
5607 // Allow a leading :: because the paths are absolute either way.
5608 // This occurs with "use $crate::..." in macros.
5609 try!(self.eat(&token::ModSep));
5611 if self.check(&token::OpenDelim(token::Brace)) {
5613 let idents = try!(self.parse_unspanned_seq(
5614 &token::OpenDelim(token::Brace),
5615 &token::CloseDelim(token::Brace),
5616 seq_sep_trailing_allowed(token::Comma),
5617 |p| p.parse_path_list_item()));
5618 let path = ast::Path {
5619 span: mk_sp(lo, self.span.hi),
5621 segments: Vec::new()
5623 return Ok(P(spanned(lo, self.span.hi, ViewPathList(path, idents))));
5626 let first_ident = try!(self.parse_ident());
5627 let mut path = vec!(first_ident);
5628 if let token::ModSep = self.token {
5629 // foo::bar or foo::{a,b,c} or foo::*
5630 while self.check(&token::ModSep) {
5634 token::Ident(..) => {
5635 let ident = try!(self.parse_ident());
5639 // foo::bar::{a,b,c}
5640 token::OpenDelim(token::Brace) => {
5641 let idents = try!(self.parse_unspanned_seq(
5642 &token::OpenDelim(token::Brace),
5643 &token::CloseDelim(token::Brace),
5644 seq_sep_trailing_allowed(token::Comma),
5645 |p| p.parse_path_list_item()
5647 let path = ast::Path {
5648 span: mk_sp(lo, self.span.hi),
5650 segments: path.into_iter().map(|identifier| {
5652 identifier: identifier,
5653 parameters: ast::PathParameters::none(),
5657 return Ok(P(spanned(lo, self.span.hi, ViewPathList(path, idents))));
5661 token::BinOp(token::Star) => {
5663 let path = ast::Path {
5664 span: mk_sp(lo, self.span.hi),
5666 segments: path.into_iter().map(|identifier| {
5668 identifier: identifier,
5669 parameters: ast::PathParameters::none(),
5673 return Ok(P(spanned(lo, self.span.hi, ViewPathGlob(path))));
5676 // fall-through for case foo::bar::;
5678 self.span_err(self.span, "expected identifier or `{` or `*`, found `;`");
5685 let mut rename_to = path[path.len() - 1];
5686 let path = ast::Path {
5687 span: mk_sp(lo, self.last_span.hi),
5689 segments: path.into_iter().map(|identifier| {
5691 identifier: identifier,
5692 parameters: ast::PathParameters::none(),
5696 if try!(self.eat_keyword(keywords::As)) {
5697 rename_to = try!(self.parse_ident())
5699 Ok(P(spanned(lo, self.last_span.hi, ViewPathSimple(rename_to, path))))
5702 /// Parses a source module as a crate. This is the main
5703 /// entry point for the parser.
5704 pub fn parse_crate_mod(&mut self) -> PResult<Crate> {
5705 let lo = self.span.lo;
5707 attrs: self.parse_inner_attributes(),
5708 module: try!(self.parse_mod_items(&token::Eof, lo)),
5709 config: self.cfg.clone(),
5710 span: mk_sp(lo, self.span.lo),
5711 exported_macros: Vec::new(),
5715 pub fn parse_optional_str(&mut self)
5716 -> PResult<Option<(InternedString,
5718 Option<ast::Name>)>> {
5719 let ret = match self.token {
5720 token::Literal(token::Str_(s), suf) => {
5721 (self.id_to_interned_str(s.ident()), ast::CookedStr, suf)
5723 token::Literal(token::StrRaw(s, n), suf) => {
5724 (self.id_to_interned_str(s.ident()), ast::RawStr(n), suf)
5726 _ => return Ok(None)
5732 pub fn parse_str(&mut self) -> PResult<(InternedString, StrStyle)> {
5733 match try!(self.parse_optional_str()) {
5734 Some((s, style, suf)) => {
5735 let sp = self.last_span;
5736 self.expect_no_suffix(sp, "str literal", suf);
5739 _ => Err(self.fatal("expected string literal"))