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::{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;
83 use std::io::prelude::*;
85 use std::path::{Path, PathBuf};
90 flags Restrictions: u8 {
91 const UNRESTRICTED = 0b0000,
92 const RESTRICTION_STMT_EXPR = 0b0001,
93 const RESTRICTION_NO_STRUCT_LITERAL = 0b0010,
97 type ItemInfo = (Ident, Item_, Option<Vec<Attribute> >);
99 /// How to parse a path. There are four different kinds of paths, all of which
100 /// are parsed somewhat differently.
101 #[derive(Copy, Clone, PartialEq)]
102 pub enum PathParsingMode {
103 /// A path with no type parameters; e.g. `foo::bar::Baz`
105 /// A path with a lifetime and type parameters, with no double colons
106 /// before the type parameters; e.g. `foo::bar<'a>::Baz<T>`
107 LifetimeAndTypesWithoutColons,
108 /// A path with a lifetime and type parameters with double colons before
109 /// the type parameters; e.g. `foo::bar::<'a>::Baz::<T>`
110 LifetimeAndTypesWithColons,
113 /// How to parse a qualified path, whether to allow trailing parameters.
114 #[derive(Copy, Clone, PartialEq)]
115 pub enum QPathParsingMode {
116 /// No trailing parameters, e.g. `<T as Trait>::Item`
118 /// Optional parameters, e.g. `<T as Trait>::item::<'a, U>`
122 /// How to parse a bound, whether to allow bound modifiers such as `?`.
123 #[derive(Copy, Clone, PartialEq)]
124 pub enum BoundParsingMode {
129 /// Possibly accept an `token::Interpolated` expression (a pre-parsed expression
130 /// dropped into the token stream, which happens while parsing the result of
131 /// macro expansion). Placement of these is not as complex as I feared it would
132 /// be. The important thing is to make sure that lookahead doesn't balk at
133 /// `token::Interpolated` tokens.
134 macro_rules! maybe_whole_expr {
137 let found = match $p.token {
138 token::Interpolated(token::NtExpr(ref e)) => {
141 token::Interpolated(token::NtPath(_)) => {
142 // FIXME: The following avoids an issue with lexical borrowck scopes,
143 // but the clone is unfortunate.
144 let pt = match $p.token {
145 token::Interpolated(token::NtPath(ref pt)) => (**pt).clone(),
149 Some($p.mk_expr(span.lo, span.hi, ExprPath(None, pt)))
151 token::Interpolated(token::NtBlock(_)) => {
152 // FIXME: The following avoids an issue with lexical borrowck scopes,
153 // but the clone is unfortunate.
154 let b = match $p.token {
155 token::Interpolated(token::NtBlock(ref b)) => (*b).clone(),
159 Some($p.mk_expr(span.lo, span.hi, ExprBlock(b)))
174 /// As maybe_whole_expr, but for things other than expressions
175 macro_rules! maybe_whole {
176 ($p:expr, $constructor:ident) => (
178 let found = match ($p).token {
179 token::Interpolated(token::$constructor(_)) => {
180 Some(try!(($p).bump_and_get()))
184 if let Some(token::Interpolated(token::$constructor(x))) = found {
185 return Ok(x.clone());
189 (no_clone $p:expr, $constructor:ident) => (
191 let found = match ($p).token {
192 token::Interpolated(token::$constructor(_)) => {
193 Some(try!(($p).bump_and_get()))
197 if let Some(token::Interpolated(token::$constructor(x))) = found {
202 (deref $p:expr, $constructor:ident) => (
204 let found = match ($p).token {
205 token::Interpolated(token::$constructor(_)) => {
206 Some(try!(($p).bump_and_get()))
210 if let Some(token::Interpolated(token::$constructor(x))) = found {
211 return Ok((*x).clone());
215 (Some deref $p:expr, $constructor:ident) => (
217 let found = match ($p).token {
218 token::Interpolated(token::$constructor(_)) => {
219 Some(try!(($p).bump_and_get()))
223 if let Some(token::Interpolated(token::$constructor(x))) = found {
224 return Ok(Some((*x).clone()));
228 (pair_empty $p:expr, $constructor:ident) => (
230 let found = match ($p).token {
231 token::Interpolated(token::$constructor(_)) => {
232 Some(try!(($p).bump_and_get()))
236 if let Some(token::Interpolated(token::$constructor(x))) = found {
237 return Ok((Vec::new(), x));
244 fn maybe_append(mut lhs: Vec<Attribute>, rhs: Option<Vec<Attribute>>)
246 if let Some(ref attrs) = rhs {
247 lhs.extend(attrs.iter().cloned())
252 /* ident is handled by common.rs */
254 pub struct Parser<'a> {
255 pub sess: &'a ParseSess,
256 /// the current token:
257 pub token: token::Token,
258 /// the span of the current token:
260 /// the span of the prior token:
262 pub cfg: CrateConfig,
263 /// the previous token or None (only stashed sometimes).
264 pub last_token: Option<Box<token::Token>>,
265 pub buffer: [TokenAndSpan; 4],
266 pub buffer_start: isize,
267 pub buffer_end: isize,
268 pub tokens_consumed: usize,
269 pub restrictions: Restrictions,
270 pub quote_depth: usize, // not (yet) related to the quasiquoter
271 pub reader: Box<Reader+'a>,
272 pub interner: Rc<token::IdentInterner>,
273 /// The set of seen errors about obsolete syntax. Used to suppress
274 /// extra detail when the same error is seen twice
275 pub obsolete_set: HashSet<ObsoleteSyntax>,
276 /// Used to determine the path to externally loaded source files
277 pub mod_path_stack: Vec<InternedString>,
278 /// Stack of spans of open delimiters. Used for error message.
279 pub open_braces: Vec<Span>,
280 /// Flag if this parser "owns" the directory that it is currently parsing
281 /// in. This will affect how nested files are looked up.
282 pub owns_directory: bool,
283 /// Name of the root module this parser originated from. If `None`, then the
284 /// name is not known. This does not change while the parser is descending
285 /// into modules, and sub-parsers have new values for this name.
286 pub root_module_name: Option<String>,
287 pub expected_tokens: Vec<TokenType>,
290 #[derive(PartialEq, Eq, Clone)]
293 Keyword(keywords::Keyword),
298 fn to_string(&self) -> String {
300 TokenType::Token(ref t) => format!("`{}`", Parser::token_to_string(t)),
301 TokenType::Operator => "an operator".to_string(),
302 TokenType::Keyword(kw) => format!("`{}`", token::get_name(kw.to_name())),
307 fn is_plain_ident_or_underscore(t: &token::Token) -> bool {
308 t.is_plain_ident() || *t == token::Underscore
311 impl<'a> Parser<'a> {
312 pub fn new(sess: &'a ParseSess,
313 cfg: ast::CrateConfig,
314 mut rdr: Box<Reader+'a>)
317 let tok0 = rdr.real_token();
319 let placeholder = TokenAndSpan {
320 tok: token::Underscore,
326 interner: token::get_ident_interner(),
342 restrictions: UNRESTRICTED,
344 obsolete_set: HashSet::new(),
345 mod_path_stack: Vec::new(),
346 open_braces: Vec::new(),
347 owns_directory: true,
348 root_module_name: None,
349 expected_tokens: Vec::new(),
353 // Panicing fns (for now!)
354 // This is so that the quote_*!() syntax extensions
355 pub fn parse_expr(&mut self) -> P<Expr> {
356 panictry!(self.parse_expr_nopanic())
359 pub fn parse_item(&mut self) -> Option<P<Item>> {
360 panictry!(self.parse_item_nopanic())
363 pub fn parse_pat(&mut self) -> P<Pat> {
364 panictry!(self.parse_pat_nopanic())
367 pub fn parse_arm(&mut self) -> Arm {
368 panictry!(self.parse_arm_nopanic())
371 pub fn parse_ty(&mut self) -> P<Ty> {
372 panictry!(self.parse_ty_nopanic())
375 pub fn parse_stmt(&mut self) -> Option<P<Stmt>> {
376 panictry!(self.parse_stmt_nopanic())
379 /// Convert a token to a string using self's reader
380 pub fn token_to_string(token: &token::Token) -> String {
381 pprust::token_to_string(token)
384 /// Convert the current token to a string using self's reader
385 pub fn this_token_to_string(&self) -> String {
386 Parser::token_to_string(&self.token)
389 pub fn unexpected_last(&self, t: &token::Token) -> FatalError {
390 let token_str = Parser::token_to_string(t);
391 let last_span = self.last_span;
392 self.span_fatal(last_span, &format!("unexpected token: `{}`",
396 pub fn unexpected(&mut self) -> FatalError {
397 match self.expect_one_of(&[], &[]) {
399 Ok(_) => unreachable!()
403 /// Expect and consume the token t. Signal an error if
404 /// the next token is not t.
405 pub fn expect(&mut self, t: &token::Token) -> PResult<()> {
406 if self.expected_tokens.is_empty() {
407 if self.token == *t {
410 let token_str = Parser::token_to_string(t);
411 let this_token_str = self.this_token_to_string();
412 Err(self.fatal(&format!("expected `{}`, found `{}`",
417 self.expect_one_of(slice::ref_slice(t), &[])
421 /// Expect next token to be edible or inedible token. If edible,
422 /// then consume it; if inedible, then return without consuming
423 /// anything. Signal a fatal error if next token is unexpected.
424 pub fn expect_one_of(&mut self,
425 edible: &[token::Token],
426 inedible: &[token::Token]) -> PResult<()>{
427 fn tokens_to_string(tokens: &[TokenType]) -> String {
428 let mut i = tokens.iter();
429 // This might be a sign we need a connect method on Iterator.
431 .map_or("".to_string(), |t| t.to_string());
432 i.enumerate().fold(b, |mut b, (i, ref a)| {
433 if tokens.len() > 2 && i == tokens.len() - 2 {
435 } else if tokens.len() == 2 && i == tokens.len() - 2 {
440 b.push_str(&*a.to_string());
444 if edible.contains(&self.token) {
446 } else if inedible.contains(&self.token) {
447 // leave it in the input
450 let mut expected = edible.iter()
451 .map(|x| TokenType::Token(x.clone()))
452 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
453 .chain(self.expected_tokens.iter().cloned())
454 .collect::<Vec<_>>();
455 expected.sort_by(|a, b| a.to_string().cmp(&b.to_string()));
457 let expect = tokens_to_string(&expected[..]);
458 let actual = self.this_token_to_string();
460 &(if expected.len() > 1 {
461 (format!("expected one of {}, found `{}`",
464 } else if expected.is_empty() {
465 (format!("unexpected token: `{}`",
468 (format!("expected {}, found `{}`",
476 /// Check for erroneous `ident { }`; if matches, signal error and
477 /// recover (without consuming any expected input token). Returns
478 /// true if and only if input was consumed for recovery.
479 pub fn check_for_erroneous_unit_struct_expecting(&mut self,
480 expected: &[token::Token])
482 if self.token == token::OpenDelim(token::Brace)
483 && expected.iter().all(|t| *t != token::OpenDelim(token::Brace))
484 && self.look_ahead(1, |t| *t == token::CloseDelim(token::Brace)) {
485 // matched; signal non-fatal error and recover.
486 let span = self.span;
488 "unit-like struct construction is written with no trailing `{ }`");
489 try!(self.eat(&token::OpenDelim(token::Brace)));
490 try!(self.eat(&token::CloseDelim(token::Brace)));
497 /// Commit to parsing a complete expression `e` expected to be
498 /// followed by some token from the set edible + inedible. Recover
499 /// from anticipated input errors, discarding erroneous characters.
500 pub fn commit_expr(&mut self, e: &Expr, edible: &[token::Token],
501 inedible: &[token::Token]) -> PResult<()> {
502 debug!("commit_expr {:?}", e);
503 if let ExprPath(..) = e.node {
504 // might be unit-struct construction; check for recoverableinput error.
505 let expected = edible.iter()
507 .chain(inedible.iter().cloned())
508 .collect::<Vec<_>>();
509 try!(self.check_for_erroneous_unit_struct_expecting(&expected[..]));
511 self.expect_one_of(edible, inedible)
514 pub fn commit_expr_expecting(&mut self, e: &Expr, edible: token::Token) -> PResult<()> {
515 self.commit_expr(e, &[edible], &[])
518 /// Commit to parsing a complete statement `s`, which expects to be
519 /// followed by some token from the set edible + inedible. Check
520 /// for recoverable input errors, discarding erroneous characters.
521 pub fn commit_stmt(&mut self, edible: &[token::Token],
522 inedible: &[token::Token]) -> PResult<()> {
525 .map_or(false, |t| t.is_ident() || t.is_path()) {
526 let expected = edible.iter()
528 .chain(inedible.iter().cloned())
529 .collect::<Vec<_>>();
530 try!(self.check_for_erroneous_unit_struct_expecting(&expected));
532 self.expect_one_of(edible, inedible)
535 pub fn commit_stmt_expecting(&mut self, edible: token::Token) -> PResult<()> {
536 self.commit_stmt(&[edible], &[])
539 pub fn parse_ident(&mut self) -> PResult<ast::Ident> {
540 self.check_strict_keywords();
541 try!(self.check_reserved_keywords());
543 token::Ident(i, _) => {
547 token::Interpolated(token::NtIdent(..)) => {
548 self.bug("ident interpolation not converted to real token");
551 let token_str = self.this_token_to_string();
552 Err(self.fatal(&format!("expected ident, found `{}`",
558 pub fn parse_ident_or_self_type(&mut self) -> PResult<ast::Ident> {
559 if self.is_self_type_ident() {
560 self.expect_self_type_ident()
566 pub fn parse_path_list_item(&mut self) -> PResult<ast::PathListItem> {
567 let lo = self.span.lo;
568 let node = if try!(self.eat_keyword(keywords::SelfValue)) {
569 ast::PathListMod { id: ast::DUMMY_NODE_ID }
571 let ident = try!(self.parse_ident());
572 ast::PathListIdent { name: ident, id: ast::DUMMY_NODE_ID }
574 let hi = self.last_span.hi;
575 Ok(spanned(lo, hi, node))
578 /// Check if the next token is `tok`, and return `true` if so.
580 /// This method is will automatically add `tok` to `expected_tokens` if `tok` is not
582 pub fn check(&mut self, tok: &token::Token) -> bool {
583 let is_present = self.token == *tok;
584 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
588 /// Consume token 'tok' if it exists. Returns true if the given
589 /// token was present, false otherwise.
590 pub fn eat(&mut self, tok: &token::Token) -> PResult<bool> {
591 let is_present = self.check(tok);
592 if is_present { try!(self.bump())}
596 pub fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
597 self.expected_tokens.push(TokenType::Keyword(kw));
598 self.token.is_keyword(kw)
601 /// If the next token is the given keyword, eat it and return
602 /// true. Otherwise, return false.
603 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> PResult<bool> {
604 if self.check_keyword(kw) {
612 pub fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> PResult<bool> {
613 if self.token.is_keyword(kw) {
621 /// If the given word is not a keyword, signal an error.
622 /// If the next token is not the given word, signal an error.
623 /// Otherwise, eat it.
624 pub fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<()> {
625 if !try!(self.eat_keyword(kw) ){
626 self.expect_one_of(&[], &[])
632 /// Signal an error if the given string is a strict keyword
633 pub fn check_strict_keywords(&mut self) {
634 if self.token.is_strict_keyword() {
635 let token_str = self.this_token_to_string();
636 let span = self.span;
638 &format!("expected identifier, found keyword `{}`",
643 /// Signal an error if the current token is a reserved keyword
644 pub fn check_reserved_keywords(&mut self) -> PResult<()>{
645 if self.token.is_reserved_keyword() {
646 let token_str = self.this_token_to_string();
647 Err(self.fatal(&format!("`{}` is a reserved keyword",
654 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
655 /// `&` and continue. If an `&` is not seen, signal an error.
656 fn expect_and(&mut self) -> PResult<()> {
657 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
659 token::BinOp(token::And) => self.bump(),
661 let span = self.span;
662 let lo = span.lo + BytePos(1);
663 Ok(self.replace_token(token::BinOp(token::And), lo, span.hi))
665 _ => self.expect_one_of(&[], &[])
669 pub fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
671 None => {/* everything ok */}
673 let text = suf.as_str();
675 self.span_bug(sp, "found empty literal suffix in Some")
677 self.span_err(sp, &*format!("{} with a suffix is illegal", kind));
683 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
684 /// `<` and continue. If a `<` is not seen, return false.
686 /// This is meant to be used when parsing generics on a path to get the
688 fn eat_lt(&mut self) -> PResult<bool> {
689 self.expected_tokens.push(TokenType::Token(token::Lt));
691 token::Lt => { try!(self.bump()); Ok(true)}
692 token::BinOp(token::Shl) => {
693 let span = self.span;
694 let lo = span.lo + BytePos(1);
695 self.replace_token(token::Lt, lo, span.hi);
702 fn expect_lt(&mut self) -> PResult<()> {
703 if !try!(self.eat_lt()) {
704 self.expect_one_of(&[], &[])
710 /// Expect and consume a GT. if a >> is seen, replace it
711 /// with a single > and continue. If a GT is not seen,
713 pub fn expect_gt(&mut self) -> PResult<()> {
714 self.expected_tokens.push(TokenType::Token(token::Gt));
716 token::Gt => self.bump(),
717 token::BinOp(token::Shr) => {
718 let span = self.span;
719 let lo = span.lo + BytePos(1);
720 Ok(self.replace_token(token::Gt, lo, span.hi))
722 token::BinOpEq(token::Shr) => {
723 let span = self.span;
724 let lo = span.lo + BytePos(1);
725 Ok(self.replace_token(token::Ge, lo, span.hi))
728 let span = self.span;
729 let lo = span.lo + BytePos(1);
730 Ok(self.replace_token(token::Eq, lo, span.hi))
733 let gt_str = Parser::token_to_string(&token::Gt);
734 let this_token_str = self.this_token_to_string();
735 Err(self.fatal(&format!("expected `{}`, found `{}`",
742 pub fn parse_seq_to_before_gt_or_return<T, F>(&mut self,
743 sep: Option<token::Token>,
745 -> PResult<(OwnedSlice<T>, bool)> where
746 F: FnMut(&mut Parser) -> PResult<Option<T>>,
748 let mut v = Vec::new();
749 // This loop works by alternating back and forth between parsing types
750 // and commas. For example, given a string `A, B,>`, the parser would
751 // first parse `A`, then a comma, then `B`, then a comma. After that it
752 // would encounter a `>` and stop. This lets the parser handle trailing
753 // commas in generic parameters, because it can stop either after
754 // parsing a type or after parsing a comma.
756 if self.check(&token::Gt)
757 || self.token == token::BinOp(token::Shr)
758 || self.token == token::Ge
759 || self.token == token::BinOpEq(token::Shr) {
764 match try!(f(self)) {
765 Some(result) => v.push(result),
766 None => return Ok((OwnedSlice::from_vec(v), true))
769 if let Some(t) = sep.as_ref() {
770 try!(self.expect(t));
775 return Ok((OwnedSlice::from_vec(v), false));
778 /// Parse a sequence bracketed by '<' and '>', stopping
780 pub fn parse_seq_to_before_gt<T, F>(&mut self,
781 sep: Option<token::Token>,
783 -> PResult<OwnedSlice<T>> where
784 F: FnMut(&mut Parser) -> PResult<T>,
786 let (result, returned) = try!(self.parse_seq_to_before_gt_or_return(sep,
787 |p| Ok(Some(try!(f(p))))));
792 pub fn parse_seq_to_gt<T, F>(&mut self,
793 sep: Option<token::Token>,
795 -> PResult<OwnedSlice<T>> where
796 F: FnMut(&mut Parser) -> PResult<T>,
798 let v = try!(self.parse_seq_to_before_gt(sep, f));
799 try!(self.expect_gt());
803 pub fn parse_seq_to_gt_or_return<T, F>(&mut self,
804 sep: Option<token::Token>,
806 -> PResult<(OwnedSlice<T>, bool)> where
807 F: FnMut(&mut Parser) -> PResult<Option<T>>,
809 let (v, returned) = try!(self.parse_seq_to_before_gt_or_return(sep, f));
811 try!(self.expect_gt());
813 return Ok((v, returned));
816 /// Parse a sequence, including the closing delimiter. The function
817 /// f must consume tokens until reaching the next separator or
819 pub fn parse_seq_to_end<T, F>(&mut self,
823 -> PResult<Vec<T>> where
824 F: FnMut(&mut Parser) -> PResult<T>,
826 let val = try!(self.parse_seq_to_before_end(ket, sep, f));
831 /// Parse a sequence, not including the closing delimiter. The function
832 /// f must consume tokens until reaching the next separator or
834 pub fn parse_seq_to_before_end<T, F>(&mut self,
838 -> PResult<Vec<T>> where
839 F: FnMut(&mut Parser) -> PResult<T>,
841 let mut first: bool = true;
843 while self.token != *ket {
846 if first { first = false; }
847 else { try!(self.expect(t)); }
851 if sep.trailing_sep_allowed && self.check(ket) { break; }
852 v.push(try!(f(self)));
857 /// Parse a sequence, including the closing delimiter. The function
858 /// f must consume tokens until reaching the next separator or
860 pub fn parse_unspanned_seq<T, F>(&mut self,
865 -> PResult<Vec<T>> where
866 F: FnMut(&mut Parser) -> PResult<T>,
868 try!(self.expect(bra));
869 let result = try!(self.parse_seq_to_before_end(ket, sep, f));
874 /// Parse a sequence parameter of enum variant. For consistency purposes,
875 /// these should not be empty.
876 pub fn parse_enum_variant_seq<T, F>(&mut self,
881 -> PResult<Vec<T>> where
882 F: FnMut(&mut Parser) -> PResult<T>,
884 let result = try!(self.parse_unspanned_seq(bra, ket, sep, f));
885 if result.is_empty() {
886 let last_span = self.last_span;
887 self.span_err(last_span,
888 "nullary enum variants are written with no trailing `( )`");
893 // NB: Do not use this function unless you actually plan to place the
894 // spanned list in the AST.
895 pub fn parse_seq<T, F>(&mut self,
900 -> PResult<Spanned<Vec<T>>> where
901 F: FnMut(&mut Parser) -> PResult<T>,
903 let lo = self.span.lo;
904 try!(self.expect(bra));
905 let result = try!(self.parse_seq_to_before_end(ket, sep, f));
906 let hi = self.span.hi;
908 Ok(spanned(lo, hi, result))
911 /// Advance the parser by one token
912 pub fn bump(&mut self) -> PResult<()> {
913 self.last_span = self.span;
914 // Stash token for error recovery (sometimes; clone is not necessarily cheap).
915 self.last_token = if self.token.is_ident() ||
916 self.token.is_path() ||
917 self.token == token::Comma {
918 Some(Box::new(self.token.clone()))
922 let next = if self.buffer_start == self.buffer_end {
923 self.reader.real_token()
925 // Avoid token copies with `replace`.
926 let buffer_start = self.buffer_start as usize;
927 let next_index = (buffer_start + 1) & 3;
928 self.buffer_start = next_index as isize;
930 let placeholder = TokenAndSpan {
931 tok: token::Underscore,
934 mem::replace(&mut self.buffer[buffer_start], placeholder)
937 self.token = next.tok;
938 self.tokens_consumed += 1;
939 self.expected_tokens.clear();
940 // check after each token
941 self.check_unknown_macro_variable()
944 /// Advance the parser by one token and return the bumped token.
945 pub fn bump_and_get(&mut self) -> PResult<token::Token> {
946 let old_token = mem::replace(&mut self.token, token::Underscore);
951 /// EFFECT: replace the current token and span with the given one
952 pub fn replace_token(&mut self,
956 self.last_span = mk_sp(self.span.lo, lo);
958 self.span = mk_sp(lo, hi);
960 pub fn buffer_length(&mut self) -> isize {
961 if self.buffer_start <= self.buffer_end {
962 return self.buffer_end - self.buffer_start;
964 return (4 - self.buffer_start) + self.buffer_end;
966 pub fn look_ahead<R, F>(&mut self, distance: usize, f: F) -> R where
967 F: FnOnce(&token::Token) -> R,
969 let dist = distance as isize;
970 while self.buffer_length() < dist {
971 self.buffer[self.buffer_end as usize] = self.reader.real_token();
972 self.buffer_end = (self.buffer_end + 1) & 3;
974 f(&self.buffer[((self.buffer_start + dist - 1) & 3) as usize].tok)
976 pub fn fatal(&self, m: &str) -> diagnostic::FatalError {
977 self.sess.span_diagnostic.span_fatal(self.span, m)
979 pub fn span_fatal(&self, sp: Span, m: &str) -> diagnostic::FatalError {
980 self.sess.span_diagnostic.span_fatal(sp, m)
982 pub fn span_fatal_help(&self, sp: Span, m: &str, help: &str) -> diagnostic::FatalError {
983 self.span_err(sp, m);
984 self.fileline_help(sp, help);
985 diagnostic::FatalError
987 pub fn span_note(&self, sp: Span, m: &str) {
988 self.sess.span_diagnostic.span_note(sp, m)
990 pub fn span_help(&self, sp: Span, m: &str) {
991 self.sess.span_diagnostic.span_help(sp, m)
993 pub fn span_suggestion(&self, sp: Span, m: &str, n: String) {
994 self.sess.span_diagnostic.span_suggestion(sp, m, n)
996 pub fn fileline_help(&self, sp: Span, m: &str) {
997 self.sess.span_diagnostic.fileline_help(sp, m)
999 pub fn bug(&self, m: &str) -> ! {
1000 self.sess.span_diagnostic.span_bug(self.span, m)
1002 pub fn warn(&self, m: &str) {
1003 self.sess.span_diagnostic.span_warn(self.span, m)
1005 pub fn span_warn(&self, sp: Span, m: &str) {
1006 self.sess.span_diagnostic.span_warn(sp, m)
1008 pub fn span_err(&self, sp: Span, m: &str) {
1009 self.sess.span_diagnostic.span_err(sp, m)
1011 pub fn span_bug(&self, sp: Span, m: &str) -> ! {
1012 self.sess.span_diagnostic.span_bug(sp, m)
1014 pub fn abort_if_errors(&self) {
1015 self.sess.span_diagnostic.handler().abort_if_errors();
1018 pub fn id_to_interned_str(&mut self, id: Ident) -> InternedString {
1019 token::get_ident(id)
1022 /// Is the current token one of the keywords that signals a bare function
1024 pub fn token_is_bare_fn_keyword(&mut self) -> bool {
1025 self.check_keyword(keywords::Fn) ||
1026 self.check_keyword(keywords::Unsafe) ||
1027 self.check_keyword(keywords::Extern)
1030 pub fn get_lifetime(&mut self) -> ast::Ident {
1032 token::Lifetime(ref ident) => *ident,
1033 _ => self.bug("not a lifetime"),
1037 pub fn parse_for_in_type(&mut self) -> PResult<Ty_> {
1039 Parses whatever can come after a `for` keyword in a type.
1040 The `for` has already been consumed.
1044 - for <'lt> |S| -> T
1048 - for <'lt> [unsafe] [extern "ABI"] fn (S) -> T
1049 - for <'lt> path::foo(a, b)
1054 let lo = self.span.lo;
1056 let lifetime_defs = try!(self.parse_late_bound_lifetime_defs());
1058 // examine next token to decide to do
1059 if self.token_is_bare_fn_keyword() {
1060 self.parse_ty_bare_fn(lifetime_defs)
1062 let hi = self.span.hi;
1063 let trait_ref = try!(self.parse_trait_ref());
1064 let poly_trait_ref = ast::PolyTraitRef { bound_lifetimes: lifetime_defs,
1065 trait_ref: trait_ref,
1066 span: mk_sp(lo, hi)};
1067 let other_bounds = if try!(self.eat(&token::BinOp(token::Plus)) ){
1068 try!(self.parse_ty_param_bounds(BoundParsingMode::Bare))
1073 Some(TraitTyParamBound(poly_trait_ref, TraitBoundModifier::None)).into_iter()
1074 .chain(other_bounds.into_vec().into_iter())
1076 Ok(ast::TyPolyTraitRef(all_bounds))
1080 pub fn parse_ty_path(&mut self) -> PResult<Ty_> {
1081 Ok(TyPath(None, try!(self.parse_path(LifetimeAndTypesWithoutColons))))
1084 /// parse a TyBareFn type:
1085 pub fn parse_ty_bare_fn(&mut self, lifetime_defs: Vec<ast::LifetimeDef>) -> PResult<Ty_> {
1088 [unsafe] [extern "ABI"] fn <'lt> (S) -> T
1089 ^~~~^ ^~~~^ ^~~~^ ^~^ ^
1092 | | | Argument types
1098 let unsafety = try!(self.parse_unsafety());
1099 let abi = if try!(self.eat_keyword(keywords::Extern) ){
1100 try!(self.parse_opt_abi()).unwrap_or(abi::C)
1105 try!(self.expect_keyword(keywords::Fn));
1106 let (inputs, variadic) = try!(self.parse_fn_args(false, true));
1107 let ret_ty = try!(self.parse_ret_ty());
1108 let decl = P(FnDecl {
1113 Ok(TyBareFn(P(BareFnTy {
1116 lifetimes: lifetime_defs,
1121 /// Parses an obsolete closure kind (`&:`, `&mut:`, or `:`).
1122 pub fn parse_obsolete_closure_kind(&mut self) -> PResult<()> {
1123 let lo = self.span.lo;
1125 self.check(&token::BinOp(token::And)) &&
1126 self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
1127 self.look_ahead(2, |t| *t == token::Colon)
1133 self.token == token::BinOp(token::And) &&
1134 self.look_ahead(1, |t| *t == token::Colon)
1139 try!(self.eat(&token::Colon))
1146 let span = mk_sp(lo, self.span.hi);
1147 self.obsolete(span, ObsoleteSyntax::ClosureKind);
1151 pub fn parse_unsafety(&mut self) -> PResult<Unsafety> {
1152 if try!(self.eat_keyword(keywords::Unsafe)) {
1153 return Ok(Unsafety::Unsafe);
1155 return Ok(Unsafety::Normal);
1159 /// Parse the items in a trait declaration
1160 pub fn parse_trait_items(&mut self) -> PResult<Vec<P<TraitItem>>> {
1161 self.parse_unspanned_seq(
1162 &token::OpenDelim(token::Brace),
1163 &token::CloseDelim(token::Brace),
1165 |p| -> PResult<P<TraitItem>> {
1166 maybe_whole!(no_clone p, NtTraitItem);
1167 let mut attrs = p.parse_outer_attributes();
1170 let (name, node) = if try!(p.eat_keyword(keywords::Type)) {
1171 let TyParam {ident, bounds, default, ..} = try!(p.parse_ty_param());
1172 try!(p.expect(&token::Semi));
1173 (ident, TypeTraitItem(bounds, default))
1174 } else if try!(p.eat_keyword(keywords::Const)) {
1175 let ident = try!(p.parse_ident());
1176 try!(p.expect(&token::Colon));
1177 let ty = try!(p.parse_ty_sum());
1178 let default = if p.check(&token::Eq) {
1180 let expr = try!(p.parse_expr_nopanic());
1181 try!(p.commit_expr_expecting(&expr, token::Semi));
1184 try!(p.expect(&token::Semi));
1187 (ident, ConstTraitItem(ty, default))
1189 let style = try!(p.parse_unsafety());
1190 let abi = if try!(p.eat_keyword(keywords::Extern)) {
1191 try!(p.parse_opt_abi()).unwrap_or(abi::C)
1195 try!(p.expect_keyword(keywords::Fn));
1197 let ident = try!(p.parse_ident());
1198 let mut generics = try!(p.parse_generics());
1200 let (explicit_self, d) = try!(p.parse_fn_decl_with_self(|p|{
1201 // This is somewhat dubious; We don't want to allow
1202 // argument names to be left off if there is a
1204 p.parse_arg_general(false)
1207 generics.where_clause = try!(p.parse_where_clause());
1208 let sig = ast::MethodSig {
1213 explicit_self: explicit_self,
1216 let body = match p.token {
1219 debug!("parse_trait_methods(): parsing required method");
1222 token::OpenDelim(token::Brace) => {
1223 debug!("parse_trait_methods(): parsing provided method");
1224 let (inner_attrs, body) =
1225 try!(p.parse_inner_attrs_and_block());
1226 attrs.extend(inner_attrs.iter().cloned());
1231 let token_str = p.this_token_to_string();
1232 return Err(p.fatal(&format!("expected `;` or `{{`, found `{}`",
1236 (ident, ast::MethodTraitItem(sig, body))
1240 id: ast::DUMMY_NODE_ID,
1244 span: mk_sp(lo, p.last_span.hi),
1249 /// Parse a possibly mutable type
1250 pub fn parse_mt(&mut self) -> PResult<MutTy> {
1251 let mutbl = try!(self.parse_mutability());
1252 let t = try!(self.parse_ty_nopanic());
1253 Ok(MutTy { ty: t, mutbl: mutbl })
1256 /// Parse optional return type [ -> TY ] in function decl
1257 pub fn parse_ret_ty(&mut self) -> PResult<FunctionRetTy> {
1258 if try!(self.eat(&token::RArrow) ){
1259 if try!(self.eat(&token::Not) ){
1260 Ok(NoReturn(self.span))
1262 Ok(Return(try!(self.parse_ty_nopanic())))
1265 let pos = self.span.lo;
1266 Ok(DefaultReturn(mk_sp(pos, pos)))
1270 /// Parse a type in a context where `T1+T2` is allowed.
1271 pub fn parse_ty_sum(&mut self) -> PResult<P<Ty>> {
1272 let lo = self.span.lo;
1273 let lhs = try!(self.parse_ty_nopanic());
1275 if !try!(self.eat(&token::BinOp(token::Plus)) ){
1279 let bounds = try!(self.parse_ty_param_bounds(BoundParsingMode::Bare));
1281 // In type grammar, `+` is treated like a binary operator,
1282 // and hence both L and R side are required.
1283 if bounds.is_empty() {
1284 let last_span = self.last_span;
1285 self.span_err(last_span,
1286 "at least one type parameter bound \
1287 must be specified");
1290 let sp = mk_sp(lo, self.last_span.hi);
1291 let sum = ast::TyObjectSum(lhs, bounds);
1292 Ok(P(Ty {id: ast::DUMMY_NODE_ID, node: sum, span: sp}))
1296 pub fn parse_ty_nopanic(&mut self) -> PResult<P<Ty>> {
1297 maybe_whole!(no_clone self, NtTy);
1299 let lo = self.span.lo;
1301 let t = if self.check(&token::OpenDelim(token::Paren)) {
1304 // (t) is a parenthesized ty
1305 // (t,) is the type of a tuple with only one field,
1307 let mut ts = vec![];
1308 let mut last_comma = false;
1309 while self.token != token::CloseDelim(token::Paren) {
1310 ts.push(try!(self.parse_ty_sum()));
1311 if self.check(&token::Comma) {
1320 try!(self.expect(&token::CloseDelim(token::Paren)));
1321 if ts.len() == 1 && !last_comma {
1322 TyParen(ts.into_iter().nth(0).unwrap())
1326 } else if self.check(&token::BinOp(token::Star)) {
1327 // STAR POINTER (bare pointer?)
1329 TyPtr(try!(self.parse_ptr()))
1330 } else if self.check(&token::OpenDelim(token::Bracket)) {
1332 try!(self.expect(&token::OpenDelim(token::Bracket)));
1333 let t = try!(self.parse_ty_sum());
1335 // Parse the `; e` in `[ i32; e ]`
1336 // where `e` is a const expression
1337 let t = match try!(self.maybe_parse_fixed_length_of_vec()) {
1339 Some(suffix) => TyFixedLengthVec(t, suffix)
1341 try!(self.expect(&token::CloseDelim(token::Bracket)));
1343 } else if self.check(&token::BinOp(token::And)) ||
1344 self.token == token::AndAnd {
1346 try!(self.expect_and());
1347 try!(self.parse_borrowed_pointee())
1348 } else if self.check_keyword(keywords::For) {
1349 try!(self.parse_for_in_type())
1350 } else if self.token_is_bare_fn_keyword() {
1352 try!(self.parse_ty_bare_fn(Vec::new()))
1353 } else if try!(self.eat_keyword_noexpect(keywords::Typeof)) {
1355 // In order to not be ambiguous, the type must be surrounded by parens.
1356 try!(self.expect(&token::OpenDelim(token::Paren)));
1357 let e = try!(self.parse_expr_nopanic());
1358 try!(self.expect(&token::CloseDelim(token::Paren)));
1360 } else if try!(self.eat_lt()) {
1363 try!(self.parse_qualified_path(QPathParsingMode::NoParameters));
1365 TyPath(Some(qself), path)
1366 } else if self.check(&token::ModSep) ||
1367 self.token.is_ident() ||
1368 self.token.is_path() {
1370 try!(self.parse_ty_path())
1371 } else if try!(self.eat(&token::Underscore) ){
1372 // TYPE TO BE INFERRED
1375 let this_token_str = self.this_token_to_string();
1376 let msg = format!("expected type, found `{}`", this_token_str);
1377 return Err(self.fatal(&msg[..]));
1380 let sp = mk_sp(lo, self.last_span.hi);
1381 Ok(P(Ty {id: ast::DUMMY_NODE_ID, node: t, span: sp}))
1384 pub fn parse_borrowed_pointee(&mut self) -> PResult<Ty_> {
1385 // look for `&'lt` or `&'foo ` and interpret `foo` as the region name:
1386 let opt_lifetime = try!(self.parse_opt_lifetime());
1388 let mt = try!(self.parse_mt());
1389 return Ok(TyRptr(opt_lifetime, mt));
1392 pub fn parse_ptr(&mut self) -> PResult<MutTy> {
1393 let mutbl = if try!(self.eat_keyword(keywords::Mut) ){
1395 } else if try!(self.eat_keyword(keywords::Const) ){
1398 let span = self.last_span;
1400 "bare raw pointers are no longer allowed, you should \
1401 likely use `*mut T`, but otherwise `*T` is now \
1402 known as `*const T`");
1405 let t = try!(self.parse_ty_nopanic());
1406 Ok(MutTy { ty: t, mutbl: mutbl })
1409 pub fn is_named_argument(&mut self) -> bool {
1410 let offset = match self.token {
1411 token::BinOp(token::And) => 1,
1413 _ if self.token.is_keyword(keywords::Mut) => 1,
1417 debug!("parser is_named_argument offset:{}", offset);
1420 is_plain_ident_or_underscore(&self.token)
1421 && self.look_ahead(1, |t| *t == token::Colon)
1423 self.look_ahead(offset, |t| is_plain_ident_or_underscore(t))
1424 && self.look_ahead(offset + 1, |t| *t == token::Colon)
1428 /// This version of parse arg doesn't necessarily require
1429 /// identifier names.
1430 pub fn parse_arg_general(&mut self, require_name: bool) -> PResult<Arg> {
1431 let pat = if require_name || self.is_named_argument() {
1432 debug!("parse_arg_general parse_pat (require_name:{})",
1434 let pat = try!(self.parse_pat_nopanic());
1436 try!(self.expect(&token::Colon));
1439 debug!("parse_arg_general ident_to_pat");
1440 ast_util::ident_to_pat(ast::DUMMY_NODE_ID,
1442 special_idents::invalid)
1445 let t = try!(self.parse_ty_sum());
1450 id: ast::DUMMY_NODE_ID,
1454 /// Parse a single function argument
1455 pub fn parse_arg(&mut self) -> PResult<Arg> {
1456 self.parse_arg_general(true)
1459 /// Parse an argument in a lambda header e.g. |arg, arg|
1460 pub fn parse_fn_block_arg(&mut self) -> PResult<Arg> {
1461 let pat = try!(self.parse_pat_nopanic());
1462 let t = if try!(self.eat(&token::Colon) ){
1463 try!(self.parse_ty_sum())
1466 id: ast::DUMMY_NODE_ID,
1468 span: mk_sp(self.span.lo, self.span.hi),
1474 id: ast::DUMMY_NODE_ID
1478 pub fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<Option<P<ast::Expr>>> {
1479 if self.check(&token::Semi) {
1481 Ok(Some(try!(self.parse_expr_nopanic())))
1487 /// Matches token_lit = LIT_INTEGER | ...
1488 pub fn lit_from_token(&self, tok: &token::Token) -> PResult<Lit_> {
1490 token::Interpolated(token::NtExpr(ref v)) => {
1492 ExprLit(ref lit) => { Ok(lit.node.clone()) }
1493 _ => { return Err(self.unexpected_last(tok)); }
1496 token::Literal(lit, suf) => {
1497 let (suffix_illegal, out) = match lit {
1498 token::Byte(i) => (true, LitByte(parse::byte_lit(i.as_str()).0)),
1499 token::Char(i) => (true, LitChar(parse::char_lit(i.as_str()).0)),
1501 // there are some valid suffixes for integer and
1502 // float literals, so all the handling is done
1504 token::Integer(s) => {
1505 (false, parse::integer_lit(s.as_str(),
1506 suf.as_ref().map(|s| s.as_str()),
1507 &self.sess.span_diagnostic,
1510 token::Float(s) => {
1511 (false, parse::float_lit(s.as_str(),
1512 suf.as_ref().map(|s| s.as_str()),
1513 &self.sess.span_diagnostic,
1519 LitStr(token::intern_and_get_ident(&parse::str_lit(s.as_str())),
1522 token::StrRaw(s, n) => {
1525 token::intern_and_get_ident(&parse::raw_str_lit(s.as_str())),
1529 (true, LitBinary(parse::binary_lit(i.as_str()))),
1530 token::BinaryRaw(i, _) =>
1532 LitBinary(Rc::new(i.as_str().as_bytes().iter().cloned().collect()))),
1536 let sp = self.last_span;
1537 self.expect_no_suffix(sp, &*format!("{} literal", lit.short_name()), suf)
1542 _ => { return Err(self.unexpected_last(tok)); }
1546 /// Matches lit = true | false | token_lit
1547 pub fn parse_lit(&mut self) -> PResult<Lit> {
1548 let lo = self.span.lo;
1549 let lit = if try!(self.eat_keyword(keywords::True) ){
1551 } else if try!(self.eat_keyword(keywords::False) ){
1554 let token = try!(self.bump_and_get());
1555 let lit = try!(self.lit_from_token(&token));
1558 Ok(codemap::Spanned { node: lit, span: mk_sp(lo, self.last_span.hi) })
1561 /// matches '-' lit | lit
1562 pub fn parse_literal_maybe_minus(&mut self) -> PResult<P<Expr>> {
1563 let minus_lo = self.span.lo;
1564 let minus_present = try!(self.eat(&token::BinOp(token::Minus)));
1566 let lo = self.span.lo;
1567 let literal = P(try!(self.parse_lit()));
1568 let hi = self.span.hi;
1569 let expr = self.mk_expr(lo, hi, ExprLit(literal));
1572 let minus_hi = self.span.hi;
1573 let unary = self.mk_unary(UnNeg, expr);
1574 Ok(self.mk_expr(minus_lo, minus_hi, unary))
1580 // QUALIFIED PATH `<TYPE [as TRAIT_REF]>::IDENT[::<PARAMS>]`
1581 // Assumes that the leading `<` has been parsed already.
1582 pub fn parse_qualified_path(&mut self, mode: QPathParsingMode)
1583 -> PResult<(QSelf, ast::Path)> {
1584 let self_type = try!(self.parse_ty_sum());
1585 let mut path = if try!(self.eat_keyword(keywords::As)) {
1586 try!(self.parse_path(LifetimeAndTypesWithoutColons))
1597 position: path.segments.len()
1600 try!(self.expect(&token::Gt));
1601 try!(self.expect(&token::ModSep));
1603 let item_name = try!(self.parse_ident());
1604 let parameters = match mode {
1605 QPathParsingMode::NoParameters => ast::PathParameters::none(),
1606 QPathParsingMode::MaybeParameters => {
1607 if try!(self.eat(&token::ModSep)) {
1608 try!(self.expect_lt());
1609 // Consumed `item::<`, go look for types
1610 let (lifetimes, types, bindings) =
1611 try!(self.parse_generic_values_after_lt());
1612 ast::AngleBracketedParameters(ast::AngleBracketedParameterData {
1613 lifetimes: lifetimes,
1614 types: OwnedSlice::from_vec(types),
1615 bindings: OwnedSlice::from_vec(bindings),
1618 ast::PathParameters::none()
1622 path.segments.push(ast::PathSegment {
1623 identifier: item_name,
1624 parameters: parameters
1627 if path.segments.len() == 1 {
1628 path.span.lo = self.last_span.lo;
1630 path.span.hi = self.last_span.hi;
1635 /// Parses a path and optional type parameter bounds, depending on the
1636 /// mode. The `mode` parameter determines whether lifetimes, types, and/or
1637 /// bounds are permitted and whether `::` must precede type parameter
1639 pub fn parse_path(&mut self, mode: PathParsingMode) -> PResult<ast::Path> {
1640 // Check for a whole path...
1641 let found = match self.token {
1642 token::Interpolated(token::NtPath(_)) => Some(try!(self.bump_and_get())),
1645 if let Some(token::Interpolated(token::NtPath(path))) = found {
1649 let lo = self.span.lo;
1650 let is_global = try!(self.eat(&token::ModSep));
1652 // Parse any number of segments and bound sets. A segment is an
1653 // identifier followed by an optional lifetime and a set of types.
1654 // A bound set is a set of type parameter bounds.
1655 let segments = match mode {
1656 LifetimeAndTypesWithoutColons => {
1657 try!(self.parse_path_segments_without_colons())
1659 LifetimeAndTypesWithColons => {
1660 try!(self.parse_path_segments_with_colons())
1663 try!(self.parse_path_segments_without_types())
1667 // Assemble the span.
1668 let span = mk_sp(lo, self.last_span.hi);
1670 // Assemble the result.
1679 /// - `a::b<T,U>::c<V,W>`
1680 /// - `a::b<T,U>::c(V) -> W`
1681 /// - `a::b<T,U>::c(V)`
1682 pub fn parse_path_segments_without_colons(&mut self) -> PResult<Vec<ast::PathSegment>> {
1683 let mut segments = Vec::new();
1685 // First, parse an identifier.
1686 let identifier = try!(self.parse_ident_or_self_type());
1688 // Parse types, optionally.
1689 let parameters = if try!(self.eat_lt() ){
1690 let (lifetimes, types, bindings) = try!(self.parse_generic_values_after_lt());
1692 ast::AngleBracketedParameters(ast::AngleBracketedParameterData {
1693 lifetimes: lifetimes,
1694 types: OwnedSlice::from_vec(types),
1695 bindings: OwnedSlice::from_vec(bindings),
1697 } else if try!(self.eat(&token::OpenDelim(token::Paren)) ){
1698 let lo = self.last_span.lo;
1700 let inputs = try!(self.parse_seq_to_end(
1701 &token::CloseDelim(token::Paren),
1702 seq_sep_trailing_allowed(token::Comma),
1703 |p| p.parse_ty_sum()));
1705 let output_ty = if try!(self.eat(&token::RArrow) ){
1706 Some(try!(self.parse_ty_nopanic()))
1711 let hi = self.last_span.hi;
1713 ast::ParenthesizedParameters(ast::ParenthesizedParameterData {
1714 span: mk_sp(lo, hi),
1719 ast::PathParameters::none()
1722 // Assemble and push the result.
1723 segments.push(ast::PathSegment { identifier: identifier,
1724 parameters: parameters });
1726 // Continue only if we see a `::`
1727 if !try!(self.eat(&token::ModSep) ){
1728 return Ok(segments);
1734 /// - `a::b::<T,U>::c`
1735 pub fn parse_path_segments_with_colons(&mut self) -> PResult<Vec<ast::PathSegment>> {
1736 let mut segments = Vec::new();
1738 // First, parse an identifier.
1739 let identifier = try!(self.parse_ident_or_self_type());
1741 // If we do not see a `::`, stop.
1742 if !try!(self.eat(&token::ModSep) ){
1743 segments.push(ast::PathSegment {
1744 identifier: identifier,
1745 parameters: ast::PathParameters::none()
1747 return Ok(segments);
1750 // Check for a type segment.
1751 if try!(self.eat_lt() ){
1752 // Consumed `a::b::<`, go look for types
1753 let (lifetimes, types, bindings) = try!(self.parse_generic_values_after_lt());
1754 segments.push(ast::PathSegment {
1755 identifier: identifier,
1756 parameters: ast::AngleBracketedParameters(ast::AngleBracketedParameterData {
1757 lifetimes: lifetimes,
1758 types: OwnedSlice::from_vec(types),
1759 bindings: OwnedSlice::from_vec(bindings),
1763 // Consumed `a::b::<T,U>`, check for `::` before proceeding
1764 if !try!(self.eat(&token::ModSep) ){
1765 return Ok(segments);
1768 // Consumed `a::`, go look for `b`
1769 segments.push(ast::PathSegment {
1770 identifier: identifier,
1771 parameters: ast::PathParameters::none(),
1780 pub fn parse_path_segments_without_types(&mut self) -> PResult<Vec<ast::PathSegment>> {
1781 let mut segments = Vec::new();
1783 // First, parse an identifier.
1784 let identifier = try!(self.parse_ident_or_self_type());
1786 // Assemble and push the result.
1787 segments.push(ast::PathSegment {
1788 identifier: identifier,
1789 parameters: ast::PathParameters::none()
1792 // If we do not see a `::`, stop.
1793 if !try!(self.eat(&token::ModSep) ){
1794 return Ok(segments);
1799 /// parses 0 or 1 lifetime
1800 pub fn parse_opt_lifetime(&mut self) -> PResult<Option<ast::Lifetime>> {
1802 token::Lifetime(..) => {
1803 Ok(Some(try!(self.parse_lifetime())))
1811 /// Parses a single lifetime
1812 /// Matches lifetime = LIFETIME
1813 pub fn parse_lifetime(&mut self) -> PResult<ast::Lifetime> {
1815 token::Lifetime(i) => {
1816 let span = self.span;
1818 return Ok(ast::Lifetime {
1819 id: ast::DUMMY_NODE_ID,
1825 return Err(self.fatal(&format!("expected a lifetime name")));
1830 /// Parses `lifetime_defs = [ lifetime_defs { ',' lifetime_defs } ]` where `lifetime_def =
1831 /// lifetime [':' lifetimes]`
1832 pub fn parse_lifetime_defs(&mut self) -> PResult<Vec<ast::LifetimeDef>> {
1834 let mut res = Vec::new();
1837 token::Lifetime(_) => {
1838 let lifetime = try!(self.parse_lifetime());
1840 if try!(self.eat(&token::Colon) ){
1841 try!(self.parse_lifetimes(token::BinOp(token::Plus)))
1845 res.push(ast::LifetimeDef { lifetime: lifetime,
1855 token::Comma => { try!(self.bump());}
1856 token::Gt => { return Ok(res); }
1857 token::BinOp(token::Shr) => { return Ok(res); }
1859 let this_token_str = self.this_token_to_string();
1860 let msg = format!("expected `,` or `>` after lifetime \
1863 return Err(self.fatal(&msg[..]));
1869 /// matches lifetimes = ( lifetime ) | ( lifetime , lifetimes ) actually, it matches the empty
1870 /// one too, but putting that in there messes up the grammar....
1872 /// Parses zero or more comma separated lifetimes. Expects each lifetime to be followed by
1873 /// either a comma or `>`. Used when parsing type parameter lists, where we expect something
1874 /// like `<'a, 'b, T>`.
1875 pub fn parse_lifetimes(&mut self, sep: token::Token) -> PResult<Vec<ast::Lifetime>> {
1877 let mut res = Vec::new();
1880 token::Lifetime(_) => {
1881 res.push(try!(self.parse_lifetime()));
1888 if self.token != sep {
1896 /// Parse mutability declaration (mut/const/imm)
1897 pub fn parse_mutability(&mut self) -> PResult<Mutability> {
1898 if try!(self.eat_keyword(keywords::Mut) ){
1905 /// Parse ident COLON expr
1906 pub fn parse_field(&mut self) -> PResult<Field> {
1907 let lo = self.span.lo;
1908 let i = try!(self.parse_ident());
1909 let hi = self.last_span.hi;
1910 try!(self.expect(&token::Colon));
1911 let e = try!(self.parse_expr_nopanic());
1913 ident: spanned(lo, hi, i),
1914 span: mk_sp(lo, e.span.hi),
1919 pub fn mk_expr(&mut self, lo: BytePos, hi: BytePos, node: Expr_) -> P<Expr> {
1921 id: ast::DUMMY_NODE_ID,
1923 span: mk_sp(lo, hi),
1927 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::Expr_ {
1928 ExprUnary(unop, expr)
1931 pub fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::Expr_ {
1932 ExprBinary(binop, lhs, rhs)
1935 pub fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::Expr_ {
1939 fn mk_method_call(&mut self,
1940 ident: ast::SpannedIdent,
1944 ExprMethodCall(ident, tps, args)
1947 pub fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::Expr_ {
1948 ExprIndex(expr, idx)
1951 pub fn mk_range(&mut self,
1952 start: Option<P<Expr>>,
1953 end: Option<P<Expr>>)
1955 ExprRange(start, end)
1958 pub fn mk_field(&mut self, expr: P<Expr>, ident: ast::SpannedIdent) -> ast::Expr_ {
1959 ExprField(expr, ident)
1962 pub fn mk_tup_field(&mut self, expr: P<Expr>, idx: codemap::Spanned<usize>) -> ast::Expr_ {
1963 ExprTupField(expr, idx)
1966 pub fn mk_assign_op(&mut self, binop: ast::BinOp,
1967 lhs: P<Expr>, rhs: P<Expr>) -> ast::Expr_ {
1968 ExprAssignOp(binop, lhs, rhs)
1971 pub fn mk_mac_expr(&mut self, lo: BytePos, hi: BytePos, m: Mac_) -> P<Expr> {
1973 id: ast::DUMMY_NODE_ID,
1974 node: ExprMac(codemap::Spanned {node: m, span: mk_sp(lo, hi)}),
1975 span: mk_sp(lo, hi),
1979 pub fn mk_lit_u32(&mut self, i: u32) -> P<Expr> {
1980 let span = &self.span;
1981 let lv_lit = P(codemap::Spanned {
1982 node: LitInt(i as u64, ast::UnsignedIntLit(TyU32)),
1987 id: ast::DUMMY_NODE_ID,
1988 node: ExprLit(lv_lit),
1993 fn expect_open_delim(&mut self) -> PResult<token::DelimToken> {
1994 self.expected_tokens.push(TokenType::Token(token::Gt));
1996 token::OpenDelim(delim) => {
2000 _ => Err(self.fatal("expected open delimiter")),
2004 /// At the bottom (top?) of the precedence hierarchy,
2005 /// parse things like parenthesized exprs,
2006 /// macros, return, etc.
2007 pub fn parse_bottom_expr(&mut self) -> PResult<P<Expr>> {
2008 maybe_whole_expr!(self);
2010 let lo = self.span.lo;
2011 let mut hi = self.span.hi;
2015 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2017 token::OpenDelim(token::Paren) => {
2020 // (e) is parenthesized e
2021 // (e,) is a tuple with only one field, e
2022 let mut es = vec![];
2023 let mut trailing_comma = false;
2024 while self.token != token::CloseDelim(token::Paren) {
2025 es.push(try!(self.parse_expr_nopanic()));
2026 try!(self.commit_expr(&**es.last().unwrap(), &[],
2027 &[token::Comma, token::CloseDelim(token::Paren)]));
2028 if self.check(&token::Comma) {
2029 trailing_comma = true;
2033 trailing_comma = false;
2039 hi = self.last_span.hi;
2040 return if es.len() == 1 && !trailing_comma {
2041 Ok(self.mk_expr(lo, hi, ExprParen(es.into_iter().nth(0).unwrap())))
2043 Ok(self.mk_expr(lo, hi, ExprTup(es)))
2046 token::OpenDelim(token::Brace) => {
2047 return self.parse_block_expr(lo, DefaultBlock);
2049 token::BinOp(token::Or) | token::OrOr => {
2050 return self.parse_lambda_expr(CaptureByRef);
2052 token::Ident(id @ ast::Ident {
2053 name: token::SELF_KEYWORD_NAME,
2055 }, token::Plain) => {
2057 let path = ast_util::ident_to_path(mk_sp(lo, hi), id);
2058 ex = ExprPath(None, path);
2059 hi = self.last_span.hi;
2061 token::OpenDelim(token::Bracket) => {
2064 if self.check(&token::CloseDelim(token::Bracket)) {
2067 ex = ExprVec(Vec::new());
2070 let first_expr = try!(self.parse_expr_nopanic());
2071 if self.check(&token::Semi) {
2072 // Repeating vector syntax: [ 0; 512 ]
2074 let count = try!(self.parse_expr_nopanic());
2075 try!(self.expect(&token::CloseDelim(token::Bracket)));
2076 ex = ExprRepeat(first_expr, count);
2077 } else if self.check(&token::Comma) {
2078 // Vector with two or more elements.
2080 let remaining_exprs = try!(self.parse_seq_to_end(
2081 &token::CloseDelim(token::Bracket),
2082 seq_sep_trailing_allowed(token::Comma),
2083 |p| Ok(try!(p.parse_expr_nopanic()))
2085 let mut exprs = vec!(first_expr);
2086 exprs.extend(remaining_exprs.into_iter());
2087 ex = ExprVec(exprs);
2089 // Vector with one element.
2090 try!(self.expect(&token::CloseDelim(token::Bracket)));
2091 ex = ExprVec(vec!(first_expr));
2094 hi = self.last_span.hi;
2097 if try!(self.eat_lt()){
2100 try!(self.parse_qualified_path(QPathParsingMode::MaybeParameters));
2102 return Ok(self.mk_expr(lo, hi, ExprPath(Some(qself), path)));
2104 if try!(self.eat_keyword(keywords::Move) ){
2105 return self.parse_lambda_expr(CaptureByValue);
2107 if try!(self.eat_keyword(keywords::If)) {
2108 return self.parse_if_expr();
2110 if try!(self.eat_keyword(keywords::For) ){
2111 return self.parse_for_expr(None);
2113 if try!(self.eat_keyword(keywords::While) ){
2114 return self.parse_while_expr(None);
2116 if self.token.is_lifetime() {
2117 let lifetime = self.get_lifetime();
2119 try!(self.expect(&token::Colon));
2120 if try!(self.eat_keyword(keywords::While) ){
2121 return self.parse_while_expr(Some(lifetime))
2123 if try!(self.eat_keyword(keywords::For) ){
2124 return self.parse_for_expr(Some(lifetime))
2126 if try!(self.eat_keyword(keywords::Loop) ){
2127 return self.parse_loop_expr(Some(lifetime))
2129 return Err(self.fatal("expected `while`, `for`, or `loop` after a label"))
2131 if try!(self.eat_keyword(keywords::Loop) ){
2132 return self.parse_loop_expr(None);
2134 if try!(self.eat_keyword(keywords::Continue) ){
2135 let lo = self.span.lo;
2136 let ex = if self.token.is_lifetime() {
2137 let lifetime = self.get_lifetime();
2139 ExprAgain(Some(lifetime))
2143 let hi = self.span.hi;
2144 return Ok(self.mk_expr(lo, hi, ex));
2146 if try!(self.eat_keyword(keywords::Match) ){
2147 return self.parse_match_expr();
2149 if try!(self.eat_keyword(keywords::Unsafe) ){
2150 return self.parse_block_expr(
2152 UnsafeBlock(ast::UserProvided));
2154 if try!(self.eat_keyword(keywords::Return) ){
2155 // RETURN expression
2156 if self.token.can_begin_expr() {
2157 let e = try!(self.parse_expr_nopanic());
2159 ex = ExprRet(Some(e));
2163 } else if try!(self.eat_keyword(keywords::Break) ){
2165 if self.token.is_lifetime() {
2166 let lifetime = self.get_lifetime();
2168 ex = ExprBreak(Some(lifetime));
2170 ex = ExprBreak(None);
2173 } else if self.check(&token::ModSep) ||
2174 self.token.is_ident() &&
2175 !self.check_keyword(keywords::True) &&
2176 !self.check_keyword(keywords::False) {
2178 try!(self.parse_path(LifetimeAndTypesWithColons));
2180 // `!`, as an operator, is prefix, so we know this isn't that
2181 if self.check(&token::Not) {
2182 // MACRO INVOCATION expression
2185 let delim = try!(self.expect_open_delim());
2186 let tts = try!(self.parse_seq_to_end(
2187 &token::CloseDelim(delim),
2189 |p| p.parse_token_tree()));
2190 let hi = self.last_span.hi;
2192 return Ok(self.mk_mac_expr(lo,
2198 if self.check(&token::OpenDelim(token::Brace)) {
2199 // This is a struct literal, unless we're prohibited
2200 // from parsing struct literals here.
2201 if !self.restrictions.contains(RESTRICTION_NO_STRUCT_LITERAL) {
2202 // It's a struct literal.
2204 let mut fields = Vec::new();
2205 let mut base = None;
2207 while self.token != token::CloseDelim(token::Brace) {
2208 if try!(self.eat(&token::DotDot) ){
2209 base = Some(try!(self.parse_expr_nopanic()));
2213 fields.push(try!(self.parse_field()));
2214 try!(self.commit_expr(&*fields.last().unwrap().expr,
2216 &[token::CloseDelim(token::Brace)]));
2219 if fields.is_empty() && base.is_none() {
2220 let last_span = self.last_span;
2221 self.span_err(last_span,
2222 "structure literal must either \
2223 have at least one field or use \
2224 functional structure update \
2229 try!(self.expect(&token::CloseDelim(token::Brace)));
2230 ex = ExprStruct(pth, fields, base);
2231 return Ok(self.mk_expr(lo, hi, ex));
2236 ex = ExprPath(None, pth);
2238 // other literal expression
2239 let lit = try!(self.parse_lit());
2241 ex = ExprLit(P(lit));
2246 return Ok(self.mk_expr(lo, hi, ex));
2249 /// Parse a block or unsafe block
2250 pub fn parse_block_expr(&mut self, lo: BytePos, blk_mode: BlockCheckMode)
2251 -> PResult<P<Expr>> {
2252 try!(self.expect(&token::OpenDelim(token::Brace)));
2253 let blk = try!(self.parse_block_tail(lo, blk_mode));
2254 return Ok(self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk)));
2257 /// parse a.b or a(13) or a[4] or just a
2258 pub fn parse_dot_or_call_expr(&mut self) -> PResult<P<Expr>> {
2259 let b = try!(self.parse_bottom_expr());
2260 self.parse_dot_or_call_expr_with(b)
2263 pub fn parse_dot_or_call_expr_with(&mut self, e0: P<Expr>) -> PResult<P<Expr>> {
2269 if try!(self.eat(&token::Dot) ){
2271 token::Ident(i, _) => {
2272 let dot = self.last_span.hi;
2275 let (_, tys, bindings) = if try!(self.eat(&token::ModSep) ){
2276 try!(self.expect_lt());
2277 try!(self.parse_generic_values_after_lt())
2279 (Vec::new(), Vec::new(), Vec::new())
2282 if !bindings.is_empty() {
2283 let last_span = self.last_span;
2284 self.span_err(last_span, "type bindings are only permitted on trait paths");
2287 // expr.f() method call
2289 token::OpenDelim(token::Paren) => {
2290 let mut es = try!(self.parse_unspanned_seq(
2291 &token::OpenDelim(token::Paren),
2292 &token::CloseDelim(token::Paren),
2293 seq_sep_trailing_allowed(token::Comma),
2294 |p| Ok(try!(p.parse_expr_nopanic()))
2296 hi = self.last_span.hi;
2299 let id = spanned(dot, hi, i);
2300 let nd = self.mk_method_call(id, tys, es);
2301 e = self.mk_expr(lo, hi, nd);
2304 if !tys.is_empty() {
2305 let last_span = self.last_span;
2306 self.span_err(last_span,
2307 "field expressions may not \
2308 have type parameters");
2311 let id = spanned(dot, hi, i);
2312 let field = self.mk_field(e, id);
2313 e = self.mk_expr(lo, hi, field);
2317 token::Literal(token::Integer(n), suf) => {
2320 // A tuple index may not have a suffix
2321 self.expect_no_suffix(sp, "tuple index", suf);
2323 let dot = self.last_span.hi;
2327 let index = n.as_str().parse::<usize>().ok();
2330 let id = spanned(dot, hi, n);
2331 let field = self.mk_tup_field(e, id);
2332 e = self.mk_expr(lo, hi, field);
2335 let last_span = self.last_span;
2336 self.span_err(last_span, "invalid tuple or tuple struct index");
2340 token::Literal(token::Float(n), _suf) => {
2342 let last_span = self.last_span;
2343 let fstr = n.as_str();
2344 self.span_err(last_span,
2345 &format!("unexpected token: `{}`", n.as_str()));
2346 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2347 let float = match fstr.parse::<f64>().ok() {
2351 self.fileline_help(last_span,
2352 &format!("try parenthesizing the first index; e.g., `(foo.{}){}`",
2353 float.trunc() as usize,
2354 &float.fract().to_string()[1..]));
2356 self.abort_if_errors();
2359 _ => return Err(self.unexpected())
2363 if self.expr_is_complete(&*e) { break; }
2366 token::OpenDelim(token::Paren) => {
2367 let es = try!(self.parse_unspanned_seq(
2368 &token::OpenDelim(token::Paren),
2369 &token::CloseDelim(token::Paren),
2370 seq_sep_trailing_allowed(token::Comma),
2371 |p| Ok(try!(p.parse_expr_nopanic()))
2373 hi = self.last_span.hi;
2375 let nd = self.mk_call(e, es);
2376 e = self.mk_expr(lo, hi, nd);
2380 // Could be either an index expression or a slicing expression.
2381 token::OpenDelim(token::Bracket) => {
2383 let ix = try!(self.parse_expr_nopanic());
2385 try!(self.commit_expr_expecting(&*ix, token::CloseDelim(token::Bracket)));
2386 let index = self.mk_index(e, ix);
2387 e = self.mk_expr(lo, hi, index)
2395 // Parse unquoted tokens after a `$` in a token tree
2396 fn parse_unquoted(&mut self) -> PResult<TokenTree> {
2397 let mut sp = self.span;
2398 let (name, namep) = match self.token {
2402 if self.token == token::OpenDelim(token::Paren) {
2403 let Spanned { node: seq, span: seq_span } = try!(self.parse_seq(
2404 &token::OpenDelim(token::Paren),
2405 &token::CloseDelim(token::Paren),
2407 |p| p.parse_token_tree()
2409 let (sep, repeat) = try!(self.parse_sep_and_kleene_op());
2410 let name_num = macro_parser::count_names(&seq);
2411 return Ok(TtSequence(mk_sp(sp.lo, seq_span.hi),
2412 Rc::new(SequenceRepetition {
2416 num_captures: name_num
2418 } else if self.token.is_keyword_allow_following_colon(keywords::Crate) {
2420 return Ok(TtToken(sp, SpecialVarNt(SpecialMacroVar::CrateMacroVar)));
2422 sp = mk_sp(sp.lo, self.span.hi);
2423 let namep = match self.token { token::Ident(_, p) => p, _ => token::Plain };
2424 let name = try!(self.parse_ident());
2428 token::SubstNt(name, namep) => {
2434 // continue by trying to parse the `:ident` after `$name`
2435 if self.token == token::Colon && self.look_ahead(1, |t| t.is_ident() &&
2436 !t.is_strict_keyword() &&
2437 !t.is_reserved_keyword()) {
2439 sp = mk_sp(sp.lo, self.span.hi);
2440 let kindp = match self.token { token::Ident(_, p) => p, _ => token::Plain };
2441 let nt_kind = try!(self.parse_ident());
2442 Ok(TtToken(sp, MatchNt(name, nt_kind, namep, kindp)))
2444 Ok(TtToken(sp, SubstNt(name, namep)))
2448 pub fn check_unknown_macro_variable(&mut self) -> PResult<()> {
2449 if self.quote_depth == 0 {
2451 token::SubstNt(name, _) =>
2452 return Err(self.fatal(&format!("unknown macro variable `{}`",
2453 token::get_ident(name)))),
2460 /// Parse an optional separator followed by a Kleene-style
2461 /// repetition token (+ or *).
2462 pub fn parse_sep_and_kleene_op(&mut self) -> PResult<(Option<token::Token>, ast::KleeneOp)> {
2463 fn parse_kleene_op(parser: &mut Parser) -> PResult<Option<ast::KleeneOp>> {
2464 match parser.token {
2465 token::BinOp(token::Star) => {
2466 try!(parser.bump());
2467 Ok(Some(ast::ZeroOrMore))
2469 token::BinOp(token::Plus) => {
2470 try!(parser.bump());
2471 Ok(Some(ast::OneOrMore))
2477 match try!(parse_kleene_op(self)) {
2478 Some(kleene_op) => return Ok((None, kleene_op)),
2482 let separator = try!(self.bump_and_get());
2483 match try!(parse_kleene_op(self)) {
2484 Some(zerok) => Ok((Some(separator), zerok)),
2485 None => return Err(self.fatal("expected `*` or `+`"))
2489 /// parse a single token tree from the input.
2490 pub fn parse_token_tree(&mut self) -> PResult<TokenTree> {
2491 // FIXME #6994: currently, this is too eager. It
2492 // parses token trees but also identifies TtSequence's
2493 // and token::SubstNt's; it's too early to know yet
2494 // whether something will be a nonterminal or a seq
2496 maybe_whole!(deref self, NtTT);
2498 // this is the fall-through for the 'match' below.
2499 // invariants: the current token is not a left-delimiter,
2500 // not an EOF, and not the desired right-delimiter (if
2501 // it were, parse_seq_to_before_end would have prevented
2502 // reaching this point.
2503 fn parse_non_delim_tt_tok(p: &mut Parser) -> PResult<TokenTree> {
2504 maybe_whole!(deref p, NtTT);
2506 token::CloseDelim(_) => {
2507 // This is a conservative error: only report the last unclosed delimiter. The
2508 // previous unclosed delimiters could actually be closed! The parser just hasn't
2509 // gotten to them yet.
2510 match p.open_braces.last() {
2512 Some(&sp) => p.span_note(sp, "unclosed delimiter"),
2514 let token_str = p.this_token_to_string();
2515 Err(p.fatal(&format!("incorrect close delimiter: `{}`",
2518 /* we ought to allow different depths of unquotation */
2519 token::Dollar | token::SubstNt(..) if p.quote_depth > 0 => {
2523 Ok(TtToken(p.span, try!(p.bump_and_get())))
2530 let open_braces = self.open_braces.clone();
2531 for sp in &open_braces {
2532 self.span_help(*sp, "did you mean to close this delimiter?");
2534 // There shouldn't really be a span, but it's easier for the test runner
2535 // if we give it one
2536 return Err(self.fatal("this file contains an un-closed delimiter "));
2538 token::OpenDelim(delim) => {
2539 // The span for beginning of the delimited section
2540 let pre_span = self.span;
2542 // Parse the open delimiter.
2543 self.open_braces.push(self.span);
2544 let open_span = self.span;
2547 // Parse the token trees within the delimiters
2548 let tts = try!(self.parse_seq_to_before_end(
2549 &token::CloseDelim(delim),
2551 |p| p.parse_token_tree()
2554 // Parse the close delimiter.
2555 let close_span = self.span;
2557 self.open_braces.pop().unwrap();
2559 // Expand to cover the entire delimited token tree
2560 let span = Span { hi: close_span.hi, ..pre_span };
2562 Ok(TtDelimited(span, Rc::new(Delimited {
2564 open_span: open_span,
2566 close_span: close_span,
2569 _ => parse_non_delim_tt_tok(self),
2573 // parse a stream of tokens into a list of TokenTree's,
2575 pub fn parse_all_token_trees(&mut self) -> PResult<Vec<TokenTree>> {
2576 let mut tts = Vec::new();
2577 while self.token != token::Eof {
2578 tts.push(try!(self.parse_token_tree()));
2583 /// Parse a prefix-operator expr
2584 pub fn parse_prefix_expr(&mut self) -> PResult<P<Expr>> {
2585 let lo = self.span.lo;
2588 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2593 let e = try!(self.parse_prefix_expr());
2595 ex = self.mk_unary(UnNot, e);
2597 token::BinOp(token::Minus) => {
2599 let e = try!(self.parse_prefix_expr());
2601 ex = self.mk_unary(UnNeg, e);
2603 token::BinOp(token::Star) => {
2605 let e = try!(self.parse_prefix_expr());
2607 ex = self.mk_unary(UnDeref, e);
2609 token::BinOp(token::And) | token::AndAnd => {
2610 try!(self.expect_and());
2611 let m = try!(self.parse_mutability());
2612 let e = try!(self.parse_prefix_expr());
2614 ex = ExprAddrOf(m, e);
2616 token::Ident(_, _) => {
2617 if !self.check_keyword(keywords::Box) {
2618 return self.parse_dot_or_call_expr();
2621 let lo = self.span.lo;
2622 let box_hi = self.span.hi;
2626 // Check for a place: `box(PLACE) EXPR`.
2627 if try!(self.eat(&token::OpenDelim(token::Paren)) ){
2628 // Support `box() EXPR` as the default.
2629 if !try!(self.eat(&token::CloseDelim(token::Paren)) ){
2630 let place = try!(self.parse_expr_nopanic());
2631 try!(self.expect(&token::CloseDelim(token::Paren)));
2632 // Give a suggestion to use `box()` when a parenthesised expression is used
2633 if !self.token.can_begin_expr() {
2634 let span = self.span;
2635 let this_token_to_string = self.this_token_to_string();
2637 &format!("expected expression, found `{}`",
2638 this_token_to_string));
2639 let box_span = mk_sp(lo, box_hi);
2640 self.span_suggestion(box_span,
2641 "try using `box()` instead:",
2642 "box()".to_string());
2643 self.abort_if_errors();
2645 let subexpression = try!(self.parse_prefix_expr());
2646 hi = subexpression.span.hi;
2647 ex = ExprBox(Some(place), subexpression);
2648 return Ok(self.mk_expr(lo, hi, ex));
2652 // Otherwise, we use the unique pointer default.
2653 let subexpression = try!(self.parse_prefix_expr());
2654 hi = subexpression.span.hi;
2655 // FIXME (pnkfelix): After working out kinks with box
2656 // desugaring, should be `ExprBox(None, subexpression)`
2658 ex = self.mk_unary(UnUniq, subexpression);
2660 _ => return self.parse_dot_or_call_expr()
2662 return Ok(self.mk_expr(lo, hi, ex));
2665 /// Parse an expression of binops
2666 pub fn parse_binops(&mut self) -> PResult<P<Expr>> {
2667 let prefix_expr = try!(self.parse_prefix_expr());
2668 self.parse_more_binops(prefix_expr, 0)
2671 /// Parse an expression of binops of at least min_prec precedence
2672 pub fn parse_more_binops(&mut self, lhs: P<Expr>, min_prec: usize) -> PResult<P<Expr>> {
2673 if self.expr_is_complete(&*lhs) { return Ok(lhs); }
2675 self.expected_tokens.push(TokenType::Operator);
2677 let cur_op_span = self.span;
2678 let cur_opt = self.token.to_binop();
2681 if ast_util::is_comparison_binop(cur_op) {
2682 self.check_no_chained_comparison(&*lhs, cur_op)
2684 let cur_prec = operator_prec(cur_op);
2685 if cur_prec >= min_prec {
2687 let expr = try!(self.parse_prefix_expr());
2688 let rhs = try!(self.parse_more_binops(expr, cur_prec + 1));
2689 let lhs_span = lhs.span;
2690 let rhs_span = rhs.span;
2691 let binary = self.mk_binary(codemap::respan(cur_op_span, cur_op), lhs, rhs);
2692 let bin = self.mk_expr(lhs_span.lo, rhs_span.hi, binary);
2693 self.parse_more_binops(bin, min_prec)
2699 if AS_PREC >= min_prec && try!(self.eat_keyword_noexpect(keywords::As) ){
2700 let rhs = try!(self.parse_ty_nopanic());
2701 let _as = self.mk_expr(lhs.span.lo,
2703 ExprCast(lhs, rhs));
2704 self.parse_more_binops(_as, min_prec)
2712 /// Produce an error if comparison operators are chained (RFC #558).
2713 /// We only need to check lhs, not rhs, because all comparison ops
2714 /// have same precedence and are left-associative
2715 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: ast::BinOp_) {
2716 debug_assert!(ast_util::is_comparison_binop(outer_op));
2718 ExprBinary(op, _, _) if ast_util::is_comparison_binop(op.node) => {
2719 // respan to include both operators
2720 let op_span = mk_sp(op.span.lo, self.span.hi);
2721 self.span_err(op_span,
2722 "chained comparison operators require parentheses");
2723 if op.node == BiLt && outer_op == BiGt {
2724 self.fileline_help(op_span,
2725 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
2732 /// Parse an assignment expression....
2733 /// actually, this seems to be the main entry point for
2734 /// parsing an arbitrary expression.
2735 pub fn parse_assign_expr(&mut self) -> PResult<P<Expr>> {
2738 // prefix-form of range notation '..expr'
2739 // This has the same precedence as assignment expressions
2740 // (much lower than other prefix expressions) to be consistent
2741 // with the postfix-form 'expr..'
2742 let lo = self.span.lo;
2744 let opt_end = if self.is_at_start_of_range_notation_rhs() {
2745 let end = try!(self.parse_binops());
2750 let hi = self.span.hi;
2751 let ex = self.mk_range(None, opt_end);
2752 Ok(self.mk_expr(lo, hi, ex))
2755 let lhs = try!(self.parse_binops());
2756 self.parse_assign_expr_with(lhs)
2761 pub fn parse_assign_expr_with(&mut self, lhs: P<Expr>) -> PResult<P<Expr>> {
2762 let restrictions = self.restrictions & RESTRICTION_NO_STRUCT_LITERAL;
2763 let op_span = self.span;
2767 let rhs = try!(self.parse_expr_res(restrictions));
2768 Ok(self.mk_expr(lhs.span.lo, rhs.span.hi, ExprAssign(lhs, rhs)))
2770 token::BinOpEq(op) => {
2772 let rhs = try!(self.parse_expr_res(restrictions));
2773 let aop = match op {
2774 token::Plus => BiAdd,
2775 token::Minus => BiSub,
2776 token::Star => BiMul,
2777 token::Slash => BiDiv,
2778 token::Percent => BiRem,
2779 token::Caret => BiBitXor,
2780 token::And => BiBitAnd,
2781 token::Or => BiBitOr,
2782 token::Shl => BiShl,
2785 let rhs_span = rhs.span;
2786 let span = lhs.span;
2787 let assign_op = self.mk_assign_op(codemap::respan(op_span, aop), lhs, rhs);
2788 Ok(self.mk_expr(span.lo, rhs_span.hi, assign_op))
2790 // A range expression, either `expr..expr` or `expr..`.
2794 let opt_end = if self.is_at_start_of_range_notation_rhs() {
2795 let end = try!(self.parse_binops());
2801 let lo = lhs.span.lo;
2802 let hi = self.span.hi;
2803 let range = self.mk_range(Some(lhs), opt_end);
2804 return Ok(self.mk_expr(lo, hi, range));
2813 fn is_at_start_of_range_notation_rhs(&self) -> bool {
2814 if self.token.can_begin_expr() {
2815 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
2816 if self.token == token::OpenDelim(token::Brace) {
2817 return !self.restrictions.contains(RESTRICTION_NO_STRUCT_LITERAL);
2825 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
2826 pub fn parse_if_expr(&mut self) -> PResult<P<Expr>> {
2827 if self.check_keyword(keywords::Let) {
2828 return self.parse_if_let_expr();
2830 let lo = self.last_span.lo;
2831 let cond = try!(self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL));
2832 let thn = try!(self.parse_block());
2833 let mut els: Option<P<Expr>> = None;
2834 let mut hi = thn.span.hi;
2835 if try!(self.eat_keyword(keywords::Else) ){
2836 let elexpr = try!(self.parse_else_expr());
2837 hi = elexpr.span.hi;
2840 Ok(self.mk_expr(lo, hi, ExprIf(cond, thn, els)))
2843 /// Parse an 'if let' expression ('if' token already eaten)
2844 pub fn parse_if_let_expr(&mut self) -> PResult<P<Expr>> {
2845 let lo = self.last_span.lo;
2846 try!(self.expect_keyword(keywords::Let));
2847 let pat = try!(self.parse_pat_nopanic());
2848 try!(self.expect(&token::Eq));
2849 let expr = try!(self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL));
2850 let thn = try!(self.parse_block());
2851 let (hi, els) = if try!(self.eat_keyword(keywords::Else) ){
2852 let expr = try!(self.parse_else_expr());
2853 (expr.span.hi, Some(expr))
2857 Ok(self.mk_expr(lo, hi, ExprIfLet(pat, expr, thn, els)))
2861 pub fn parse_lambda_expr(&mut self, capture_clause: CaptureClause)
2864 let lo = self.span.lo;
2865 let decl = try!(self.parse_fn_block_decl());
2866 let body = match decl.output {
2867 DefaultReturn(_) => {
2868 // If no explicit return type is given, parse any
2869 // expr and wrap it up in a dummy block:
2870 let body_expr = try!(self.parse_expr_nopanic());
2872 id: ast::DUMMY_NODE_ID,
2874 span: body_expr.span,
2875 expr: Some(body_expr),
2876 rules: DefaultBlock,
2880 // If an explicit return type is given, require a
2881 // block to appear (RFC 968).
2882 try!(self.parse_block())
2889 ExprClosure(capture_clause, decl, body)))
2892 pub fn parse_else_expr(&mut self) -> PResult<P<Expr>> {
2893 if try!(self.eat_keyword(keywords::If) ){
2894 return self.parse_if_expr();
2896 let blk = try!(self.parse_block());
2897 return Ok(self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk)));
2901 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
2902 pub fn parse_for_expr(&mut self, opt_ident: Option<ast::Ident>) -> PResult<P<Expr>> {
2903 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
2905 let lo = self.last_span.lo;
2906 let pat = try!(self.parse_pat_nopanic());
2907 try!(self.expect_keyword(keywords::In));
2908 let expr = try!(self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL));
2909 let loop_block = try!(self.parse_block());
2910 let hi = self.last_span.hi;
2912 Ok(self.mk_expr(lo, hi, ExprForLoop(pat, expr, loop_block, opt_ident)))
2915 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
2916 pub fn parse_while_expr(&mut self, opt_ident: Option<ast::Ident>) -> PResult<P<Expr>> {
2917 if self.token.is_keyword(keywords::Let) {
2918 return self.parse_while_let_expr(opt_ident);
2920 let lo = self.last_span.lo;
2921 let cond = try!(self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL));
2922 let body = try!(self.parse_block());
2923 let hi = body.span.hi;
2924 return Ok(self.mk_expr(lo, hi, ExprWhile(cond, body, opt_ident)));
2927 /// Parse a 'while let' expression ('while' token already eaten)
2928 pub fn parse_while_let_expr(&mut self, opt_ident: Option<ast::Ident>) -> PResult<P<Expr>> {
2929 let lo = self.last_span.lo;
2930 try!(self.expect_keyword(keywords::Let));
2931 let pat = try!(self.parse_pat_nopanic());
2932 try!(self.expect(&token::Eq));
2933 let expr = try!(self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL));
2934 let body = try!(self.parse_block());
2935 let hi = body.span.hi;
2936 return Ok(self.mk_expr(lo, hi, ExprWhileLet(pat, expr, body, opt_ident)));
2939 pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::Ident>) -> PResult<P<Expr>> {
2940 let lo = self.last_span.lo;
2941 let body = try!(self.parse_block());
2942 let hi = body.span.hi;
2943 Ok(self.mk_expr(lo, hi, ExprLoop(body, opt_ident)))
2946 fn parse_match_expr(&mut self) -> PResult<P<Expr>> {
2947 let lo = self.last_span.lo;
2948 let discriminant = try!(self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL));
2949 try!(self.commit_expr_expecting(&*discriminant, token::OpenDelim(token::Brace)));
2950 let mut arms: Vec<Arm> = Vec::new();
2951 while self.token != token::CloseDelim(token::Brace) {
2952 arms.push(try!(self.parse_arm_nopanic()));
2954 let hi = self.span.hi;
2956 return Ok(self.mk_expr(lo, hi, ExprMatch(discriminant, arms, MatchSource::Normal)));
2959 pub fn parse_arm_nopanic(&mut self) -> PResult<Arm> {
2960 maybe_whole!(no_clone self, NtArm);
2962 let attrs = self.parse_outer_attributes();
2963 let pats = try!(self.parse_pats());
2964 let mut guard = None;
2965 if try!(self.eat_keyword(keywords::If) ){
2966 guard = Some(try!(self.parse_expr_nopanic()));
2968 try!(self.expect(&token::FatArrow));
2969 let expr = try!(self.parse_expr_res(RESTRICTION_STMT_EXPR));
2972 !classify::expr_is_simple_block(&*expr)
2973 && self.token != token::CloseDelim(token::Brace);
2976 try!(self.commit_expr(&*expr, &[token::Comma], &[token::CloseDelim(token::Brace)]));
2978 try!(self.eat(&token::Comma));
2989 /// Parse an expression
2990 pub fn parse_expr_nopanic(&mut self) -> PResult<P<Expr>> {
2991 return self.parse_expr_res(UNRESTRICTED);
2994 /// Parse an expression, subject to the given restrictions
2995 pub fn parse_expr_res(&mut self, r: Restrictions) -> PResult<P<Expr>> {
2996 let old = self.restrictions;
2997 self.restrictions = r;
2998 let e = try!(self.parse_assign_expr());
2999 self.restrictions = old;
3003 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3004 fn parse_initializer(&mut self) -> PResult<Option<P<Expr>>> {
3005 if self.check(&token::Eq) {
3007 Ok(Some(try!(self.parse_expr_nopanic())))
3013 /// Parse patterns, separated by '|' s
3014 fn parse_pats(&mut self) -> PResult<Vec<P<Pat>>> {
3015 let mut pats = Vec::new();
3017 pats.push(try!(self.parse_pat_nopanic()));
3018 if self.check(&token::BinOp(token::Or)) { try!(self.bump());}
3019 else { return Ok(pats); }
3023 fn parse_pat_tuple_elements(&mut self) -> PResult<Vec<P<Pat>>> {
3024 let mut fields = vec![];
3025 if !self.check(&token::CloseDelim(token::Paren)) {
3026 fields.push(try!(self.parse_pat_nopanic()));
3027 if self.look_ahead(1, |t| *t != token::CloseDelim(token::Paren)) {
3028 while try!(self.eat(&token::Comma)) &&
3029 !self.check(&token::CloseDelim(token::Paren)) {
3030 fields.push(try!(self.parse_pat_nopanic()));
3033 if fields.len() == 1 {
3034 try!(self.expect(&token::Comma));
3040 fn parse_pat_vec_elements(
3042 ) -> PResult<(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3043 let mut before = Vec::new();
3044 let mut slice = None;
3045 let mut after = Vec::new();
3046 let mut first = true;
3047 let mut before_slice = true;
3049 while self.token != token::CloseDelim(token::Bracket) {
3053 try!(self.expect(&token::Comma));
3055 if self.token == token::CloseDelim(token::Bracket)
3056 && (before_slice || !after.is_empty()) {
3062 if self.check(&token::DotDot) {
3065 if self.check(&token::Comma) ||
3066 self.check(&token::CloseDelim(token::Bracket)) {
3067 slice = Some(P(ast::Pat {
3068 id: ast::DUMMY_NODE_ID,
3069 node: PatWild(PatWildMulti),
3072 before_slice = false;
3078 let subpat = try!(self.parse_pat_nopanic());
3079 if before_slice && self.check(&token::DotDot) {
3081 slice = Some(subpat);
3082 before_slice = false;
3083 } else if before_slice {
3084 before.push(subpat);
3090 Ok((before, slice, after))
3093 /// Parse the fields of a struct-like pattern
3094 fn parse_pat_fields(&mut self) -> PResult<(Vec<codemap::Spanned<ast::FieldPat>> , bool)> {
3095 let mut fields = Vec::new();
3096 let mut etc = false;
3097 let mut first = true;
3098 while self.token != token::CloseDelim(token::Brace) {
3102 try!(self.expect(&token::Comma));
3103 // accept trailing commas
3104 if self.check(&token::CloseDelim(token::Brace)) { break }
3107 let lo = self.span.lo;
3110 if self.check(&token::DotDot) {
3112 if self.token != token::CloseDelim(token::Brace) {
3113 let token_str = self.this_token_to_string();
3114 return Err(self.fatal(&format!("expected `{}`, found `{}`", "}",
3121 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3122 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3123 // Parsing a pattern of the form "fieldname: pat"
3124 let fieldname = try!(self.parse_ident());
3126 let pat = try!(self.parse_pat_nopanic());
3128 (pat, fieldname, false)
3130 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3131 let is_box = try!(self.eat_keyword(keywords::Box));
3132 let boxed_span_lo = self.span.lo;
3133 let is_ref = try!(self.eat_keyword(keywords::Ref));
3134 let is_mut = try!(self.eat_keyword(keywords::Mut));
3135 let fieldname = try!(self.parse_ident());
3136 hi = self.last_span.hi;
3138 let bind_type = match (is_ref, is_mut) {
3139 (true, true) => BindByRef(MutMutable),
3140 (true, false) => BindByRef(MutImmutable),
3141 (false, true) => BindByValue(MutMutable),
3142 (false, false) => BindByValue(MutImmutable),
3144 let fieldpath = codemap::Spanned{span:self.last_span, node:fieldname};
3145 let fieldpat = P(ast::Pat{
3146 id: ast::DUMMY_NODE_ID,
3147 node: PatIdent(bind_type, fieldpath, None),
3148 span: mk_sp(boxed_span_lo, hi),
3151 let subpat = if is_box {
3153 id: ast::DUMMY_NODE_ID,
3154 node: PatBox(fieldpat),
3155 span: mk_sp(lo, hi),
3160 (subpat, fieldname, true)
3163 fields.push(codemap::Spanned { span: mk_sp(lo, hi),
3164 node: ast::FieldPat { ident: fieldname,
3166 is_shorthand: is_shorthand }});
3168 return Ok((fields, etc));
3171 fn parse_pat_range_end(&mut self) -> PResult<P<Expr>> {
3172 if self.is_path_start() {
3173 let lo = self.span.lo;
3174 let (qself, path) = if try!(self.eat_lt()) {
3175 // Parse a qualified path
3177 try!(self.parse_qualified_path(QPathParsingMode::NoParameters));
3180 // Parse an unqualified path
3181 (None, try!(self.parse_path(LifetimeAndTypesWithColons)))
3183 let hi = self.last_span.hi;
3184 Ok(self.mk_expr(lo, hi, ExprPath(qself, path)))
3186 self.parse_literal_maybe_minus()
3190 fn is_path_start(&self) -> bool {
3191 (self.token == token::Lt || self.token == token::ModSep
3192 || self.token.is_ident() || self.token.is_path())
3193 && !self.token.is_keyword(keywords::True) && !self.token.is_keyword(keywords::False)
3196 /// Parse a pattern.
3197 pub fn parse_pat_nopanic(&mut self) -> PResult<P<Pat>> {
3198 maybe_whole!(self, NtPat);
3200 let lo = self.span.lo;
3203 token::Underscore => {
3206 pat = PatWild(PatWildSingle);
3208 token::BinOp(token::And) | token::AndAnd => {
3209 // Parse &pat / &mut pat
3210 try!(self.expect_and());
3211 let mutbl = try!(self.parse_mutability());
3212 let subpat = try!(self.parse_pat_nopanic());
3213 pat = PatRegion(subpat, mutbl);
3215 token::OpenDelim(token::Paren) => {
3216 // Parse (pat,pat,pat,...) as tuple pattern
3218 let fields = try!(self.parse_pat_tuple_elements());
3219 try!(self.expect(&token::CloseDelim(token::Paren)));
3220 pat = PatTup(fields);
3222 token::OpenDelim(token::Bracket) => {
3223 // Parse [pat,pat,...] as vector pattern
3225 let (before, slice, after) = try!(self.parse_pat_vec_elements());
3226 try!(self.expect(&token::CloseDelim(token::Bracket)));
3227 pat = PatVec(before, slice, after);
3230 // At this point, token != _, &, &&, (, [
3231 if try!(self.eat_keyword(keywords::Mut)) {
3232 // Parse mut ident @ pat
3233 pat = try!(self.parse_pat_ident(BindByValue(MutMutable)));
3234 } else if try!(self.eat_keyword(keywords::Ref)) {
3235 // Parse ref ident @ pat / ref mut ident @ pat
3236 let mutbl = try!(self.parse_mutability());
3237 pat = try!(self.parse_pat_ident(BindByRef(mutbl)));
3238 } else if try!(self.eat_keyword(keywords::Box)) {
3240 let subpat = try!(self.parse_pat_nopanic());
3241 pat = PatBox(subpat);
3242 } else if self.is_path_start() {
3243 // Parse pattern starting with a path
3244 if self.token.is_plain_ident() && self.look_ahead(1, |t| *t != token::DotDotDot &&
3245 *t != token::OpenDelim(token::Brace) &&
3246 *t != token::OpenDelim(token::Paren) &&
3247 // Contrary to its definition, a plain ident can be followed by :: in macros
3248 *t != token::ModSep) {
3249 // Plain idents have some extra abilities here compared to general paths
3250 if self.look_ahead(1, |t| *t == token::Not) {
3251 // Parse macro invocation
3252 let ident = try!(self.parse_ident());
3253 let ident_span = self.last_span;
3254 let path = ident_to_path(ident_span, ident);
3256 let delim = try!(self.expect_open_delim());
3257 let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
3258 seq_sep_none(), |p| p.parse_token_tree()));
3259 let mac = MacInvocTT(path, tts, EMPTY_CTXT);
3260 pat = PatMac(codemap::Spanned {node: mac, span: self.span});
3262 // Parse ident @ pat
3263 // This can give false positives and parse nullary enums,
3264 // they are dealt with later in resolve
3265 pat = try!(self.parse_pat_ident(BindByValue(MutImmutable)));
3268 let (qself, path) = if try!(self.eat_lt()) {
3269 // Parse a qualified path
3271 try!(self.parse_qualified_path(QPathParsingMode::NoParameters));
3274 // Parse an unqualified path
3275 (None, try!(self.parse_path(LifetimeAndTypesWithColons)))
3278 token::DotDotDot => {
3280 let hi = self.last_span.hi;
3281 let begin = self.mk_expr(lo, hi, ExprPath(qself, path));
3283 let end = try!(self.parse_pat_range_end());
3284 pat = PatRange(begin, end);
3286 token::OpenDelim(token::Brace) => {
3287 if qself.is_some() {
3288 let span = self.span;
3290 "unexpected `{` after qualified path");
3291 self.abort_if_errors();
3293 // Parse struct pattern
3295 let (fields, etc) = try!(self.parse_pat_fields());
3297 pat = PatStruct(path, fields, etc);
3299 token::OpenDelim(token::Paren) => {
3300 if qself.is_some() {
3301 let span = self.span;
3303 "unexpected `(` after qualified path");
3304 self.abort_if_errors();
3306 // Parse tuple struct or enum pattern
3307 if self.look_ahead(1, |t| *t == token::DotDot) {
3308 // This is a "top constructor only" pat
3311 try!(self.expect(&token::CloseDelim(token::Paren)));
3312 pat = PatEnum(path, None);
3314 let args = try!(self.parse_enum_variant_seq(
3315 &token::OpenDelim(token::Paren),
3316 &token::CloseDelim(token::Paren),
3317 seq_sep_trailing_allowed(token::Comma),
3318 |p| p.parse_pat_nopanic()));
3319 pat = PatEnum(path, Some(args));
3322 _ if qself.is_some() => {
3323 // Parse qualified path
3324 pat = PatQPath(qself.unwrap(), path);
3327 // Parse nullary enum
3328 pat = PatEnum(path, Some(vec![]));
3333 // Try to parse everything else as literal with optional minus
3334 let begin = try!(self.parse_literal_maybe_minus());
3335 if try!(self.eat(&token::DotDotDot)) {
3336 let end = try!(self.parse_pat_range_end());
3337 pat = PatRange(begin, end);
3339 pat = PatLit(begin);
3345 let hi = self.last_span.hi;
3347 id: ast::DUMMY_NODE_ID,
3349 span: mk_sp(lo, hi),
3353 /// Parse ident or ident @ pat
3354 /// used by the copy foo and ref foo patterns to give a good
3355 /// error message when parsing mistakes like ref foo(a,b)
3356 fn parse_pat_ident(&mut self,
3357 binding_mode: ast::BindingMode)
3358 -> PResult<ast::Pat_> {
3359 if !self.token.is_plain_ident() {
3360 let span = self.span;
3361 let tok_str = self.this_token_to_string();
3362 return Err(self.span_fatal(span,
3363 &format!("expected identifier, found `{}`", tok_str)))
3365 let ident = try!(self.parse_ident());
3366 let last_span = self.last_span;
3367 let name = codemap::Spanned{span: last_span, node: ident};
3368 let sub = if try!(self.eat(&token::At) ){
3369 Some(try!(self.parse_pat_nopanic()))
3374 // just to be friendly, if they write something like
3376 // we end up here with ( as the current token. This shortly
3377 // leads to a parse error. Note that if there is no explicit
3378 // binding mode then we do not end up here, because the lookahead
3379 // will direct us over to parse_enum_variant()
3380 if self.token == token::OpenDelim(token::Paren) {
3381 let last_span = self.last_span;
3382 return Err(self.span_fatal(
3384 "expected identifier, found enum pattern"))
3387 Ok(PatIdent(binding_mode, name, sub))
3390 /// Parse a local variable declaration
3391 fn parse_local(&mut self) -> PResult<P<Local>> {
3392 let lo = self.span.lo;
3393 let pat = try!(self.parse_pat_nopanic());
3396 if try!(self.eat(&token::Colon) ){
3397 ty = Some(try!(self.parse_ty_sum()));
3399 let init = try!(self.parse_initializer());
3404 id: ast::DUMMY_NODE_ID,
3405 span: mk_sp(lo, self.last_span.hi),
3410 /// Parse a "let" stmt
3411 fn parse_let(&mut self) -> PResult<P<Decl>> {
3412 let lo = self.span.lo;
3413 let local = try!(self.parse_local());
3414 Ok(P(spanned(lo, self.last_span.hi, DeclLocal(local))))
3417 /// Parse a structure field
3418 fn parse_name_and_ty(&mut self, pr: Visibility,
3419 attrs: Vec<Attribute> ) -> PResult<StructField> {
3420 let lo = self.span.lo;
3421 if !self.token.is_plain_ident() {
3422 return Err(self.fatal("expected ident"));
3424 let name = try!(self.parse_ident());
3425 try!(self.expect(&token::Colon));
3426 let ty = try!(self.parse_ty_sum());
3427 Ok(spanned(lo, self.last_span.hi, ast::StructField_ {
3428 kind: NamedField(name, pr),
3429 id: ast::DUMMY_NODE_ID,
3435 /// Emit an expected item after attributes error.
3436 fn expected_item_err(&self, attrs: &[Attribute]) {
3437 let message = match attrs.last() {
3438 Some(&Attribute { node: ast::Attribute_ { is_sugared_doc: true, .. }, .. }) => {
3439 "expected item after doc comment"
3441 _ => "expected item after attributes",
3444 self.span_err(self.last_span, message);
3447 /// Parse a statement. may include decl.
3448 pub fn parse_stmt_nopanic(&mut self) -> PResult<Option<P<Stmt>>> {
3449 Ok(try!(self.parse_stmt_()).map(P))
3452 fn parse_stmt_(&mut self) -> PResult<Option<Stmt>> {
3453 maybe_whole!(Some deref self, NtStmt);
3455 fn check_expected_item(p: &mut Parser, attrs: &[Attribute]) {
3456 // If we have attributes then we should have an item
3457 if !attrs.is_empty() {
3458 p.expected_item_err(attrs);
3462 let attrs = self.parse_outer_attributes();
3463 let lo = self.span.lo;
3465 Ok(Some(if self.check_keyword(keywords::Let) {
3466 check_expected_item(self, &attrs);
3467 try!(self.expect_keyword(keywords::Let));
3468 let decl = try!(self.parse_let());
3469 spanned(lo, decl.span.hi, StmtDecl(decl, ast::DUMMY_NODE_ID))
3470 } else if self.token.is_ident()
3471 && !self.token.is_any_keyword()
3472 && self.look_ahead(1, |t| *t == token::Not) {
3473 // it's a macro invocation:
3475 check_expected_item(self, &attrs);
3477 // Potential trouble: if we allow macros with paths instead of
3478 // idents, we'd need to look ahead past the whole path here...
3479 let pth = try!(self.parse_path(NoTypesAllowed));
3482 let id = match self.token {
3483 token::OpenDelim(_) => token::special_idents::invalid, // no special identifier
3484 _ => try!(self.parse_ident()),
3487 // check that we're pointing at delimiters (need to check
3488 // again after the `if`, because of `parse_ident`
3489 // consuming more tokens).
3490 let delim = match self.token {
3491 token::OpenDelim(delim) => delim,
3493 // we only expect an ident if we didn't parse one
3495 let ident_str = if id.name == token::special_idents::invalid.name {
3500 let tok_str = self.this_token_to_string();
3501 return Err(self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
3507 let tts = try!(self.parse_unspanned_seq(
3508 &token::OpenDelim(delim),
3509 &token::CloseDelim(delim),
3511 |p| p.parse_token_tree()
3513 let hi = self.last_span.hi;
3515 let style = if delim == token::Brace {
3518 MacStmtWithoutBraces
3521 if id.name == token::special_idents::invalid.name {
3523 StmtMac(P(spanned(lo,
3525 MacInvocTT(pth, tts, EMPTY_CTXT))),
3528 // if it has a special ident, it's definitely an item
3530 // Require a semicolon or braces.
3531 if style != MacStmtWithBraces {
3532 if !try!(self.eat(&token::Semi) ){
3533 let last_span = self.last_span;
3534 self.span_err(last_span,
3535 "macros that expand to items must \
3536 either be surrounded with braces or \
3537 followed by a semicolon");
3540 spanned(lo, hi, StmtDecl(
3541 P(spanned(lo, hi, DeclItem(
3543 lo, hi, id /*id is good here*/,
3544 ItemMac(spanned(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT))),
3545 Inherited, Vec::new(/*no attrs*/))))),
3546 ast::DUMMY_NODE_ID))
3549 match try!(self.parse_item_(attrs, false)) {
3552 let decl = P(spanned(lo, hi, DeclItem(i)));
3553 spanned(lo, hi, StmtDecl(decl, ast::DUMMY_NODE_ID))
3556 // Do not attempt to parse an expression if we're done here.
3557 if self.token == token::Semi {
3562 if self.token == token::CloseDelim(token::Brace) {
3566 // Remainder are line-expr stmts.
3567 let e = try!(self.parse_expr_res(RESTRICTION_STMT_EXPR));
3568 spanned(lo, e.span.hi, StmtExpr(e, ast::DUMMY_NODE_ID))
3574 /// Is this expression a successfully-parsed statement?
3575 fn expr_is_complete(&mut self, e: &Expr) -> bool {
3576 self.restrictions.contains(RESTRICTION_STMT_EXPR) &&
3577 !classify::expr_requires_semi_to_be_stmt(e)
3580 /// Parse a block. No inner attrs are allowed.
3581 pub fn parse_block(&mut self) -> PResult<P<Block>> {
3582 maybe_whole!(no_clone self, NtBlock);
3584 let lo = self.span.lo;
3586 if !try!(self.eat(&token::OpenDelim(token::Brace)) ){
3588 let tok = self.this_token_to_string();
3589 return Err(self.span_fatal_help(sp,
3590 &format!("expected `{{`, found `{}`", tok),
3591 "place this code inside a block"));
3594 self.parse_block_tail(lo, DefaultBlock)
3597 /// Parse a block. Inner attrs are allowed.
3598 fn parse_inner_attrs_and_block(&mut self) -> PResult<(Vec<Attribute>, P<Block>)> {
3599 maybe_whole!(pair_empty self, NtBlock);
3601 let lo = self.span.lo;
3602 try!(self.expect(&token::OpenDelim(token::Brace)));
3603 Ok((self.parse_inner_attributes(),
3604 try!(self.parse_block_tail(lo, DefaultBlock))))
3607 /// Parse the rest of a block expression or function body
3608 /// Precondition: already parsed the '{'.
3609 fn parse_block_tail(&mut self, lo: BytePos, s: BlockCheckMode) -> PResult<P<Block>> {
3610 let mut stmts = vec![];
3611 let mut expr = None;
3613 while !try!(self.eat(&token::CloseDelim(token::Brace))) {
3614 let Spanned {node, span} = if let Some(s) = try!(self.parse_stmt_()) {
3617 // Found only `;` or `}`.
3622 try!(self.handle_expression_like_statement(e, span, &mut stmts, &mut expr));
3624 StmtMac(mac, MacStmtWithoutBraces) => {
3625 // statement macro without braces; might be an
3626 // expr depending on whether a semicolon follows
3629 stmts.push(P(Spanned {
3630 node: StmtMac(mac, MacStmtWithSemicolon),
3631 span: mk_sp(span.lo, self.span.hi),
3636 let e = self.mk_mac_expr(span.lo, span.hi,
3637 mac.and_then(|m| m.node));
3638 let e = try!(self.parse_dot_or_call_expr_with(e));
3639 let e = try!(self.parse_more_binops(e, 0));
3640 let e = try!(self.parse_assign_expr_with(e));
3641 try!(self.handle_expression_like_statement(
3649 StmtMac(m, style) => {
3650 // statement macro; might be an expr
3653 stmts.push(P(Spanned {
3654 node: StmtMac(m, MacStmtWithSemicolon),
3655 span: mk_sp(span.lo, self.span.hi),
3659 token::CloseDelim(token::Brace) => {
3660 // if a block ends in `m!(arg)` without
3661 // a `;`, it must be an expr
3662 expr = Some(self.mk_mac_expr(span.lo, span.hi,
3663 m.and_then(|x| x.node)));
3666 stmts.push(P(Spanned {
3667 node: StmtMac(m, style),
3673 _ => { // all other kinds of statements:
3674 let mut hi = span.hi;
3675 if classify::stmt_ends_with_semi(&node) {
3676 try!(self.commit_stmt_expecting(token::Semi));
3677 hi = self.last_span.hi;
3680 stmts.push(P(Spanned {
3682 span: mk_sp(span.lo, hi)
3691 id: ast::DUMMY_NODE_ID,
3693 span: mk_sp(lo, self.last_span.hi),
3697 fn handle_expression_like_statement(
3701 stmts: &mut Vec<P<Stmt>>,
3702 last_block_expr: &mut Option<P<Expr>>) -> PResult<()> {
3703 // expression without semicolon
3704 if classify::expr_requires_semi_to_be_stmt(&*e) {
3705 // Just check for errors and recover; do not eat semicolon yet.
3706 try!(self.commit_stmt(&[],
3707 &[token::Semi, token::CloseDelim(token::Brace)]));
3713 let span_with_semi = Span {
3715 hi: self.last_span.hi,
3716 expn_id: span.expn_id,
3718 stmts.push(P(Spanned {
3719 node: StmtSemi(e, ast::DUMMY_NODE_ID),
3720 span: span_with_semi,
3723 token::CloseDelim(token::Brace) => *last_block_expr = Some(e),
3725 stmts.push(P(Spanned {
3726 node: StmtExpr(e, ast::DUMMY_NODE_ID),
3734 // Parses a sequence of bounds if a `:` is found,
3735 // otherwise returns empty list.
3736 fn parse_colon_then_ty_param_bounds(&mut self,
3737 mode: BoundParsingMode)
3738 -> PResult<OwnedSlice<TyParamBound>>
3740 if !try!(self.eat(&token::Colon) ){
3741 Ok(OwnedSlice::empty())
3743 self.parse_ty_param_bounds(mode)
3747 // matches bounds = ( boundseq )?
3748 // where boundseq = ( polybound + boundseq ) | polybound
3749 // and polybound = ( 'for' '<' 'region '>' )? bound
3750 // and bound = 'region | trait_ref
3751 fn parse_ty_param_bounds(&mut self,
3752 mode: BoundParsingMode)
3753 -> PResult<OwnedSlice<TyParamBound>>
3755 let mut result = vec!();
3757 let question_span = self.span;
3758 let ate_question = try!(self.eat(&token::Question));
3760 token::Lifetime(lifetime) => {
3762 self.span_err(question_span,
3763 "`?` may only modify trait bounds, not lifetime bounds");
3765 result.push(RegionTyParamBound(ast::Lifetime {
3766 id: ast::DUMMY_NODE_ID,
3772 token::ModSep | token::Ident(..) => {
3773 let poly_trait_ref = try!(self.parse_poly_trait_ref());
3774 let modifier = if ate_question {
3775 if mode == BoundParsingMode::Modified {
3776 TraitBoundModifier::Maybe
3778 self.span_err(question_span,
3780 TraitBoundModifier::None
3783 TraitBoundModifier::None
3785 result.push(TraitTyParamBound(poly_trait_ref, modifier))
3790 if !try!(self.eat(&token::BinOp(token::Plus)) ){
3795 return Ok(OwnedSlice::from_vec(result));
3798 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
3799 fn parse_ty_param(&mut self) -> PResult<TyParam> {
3800 let span = self.span;
3801 let ident = try!(self.parse_ident());
3803 let bounds = try!(self.parse_colon_then_ty_param_bounds(BoundParsingMode::Modified));
3805 let default = if self.check(&token::Eq) {
3807 Some(try!(self.parse_ty_sum()))
3814 id: ast::DUMMY_NODE_ID,
3821 /// Parse a set of optional generic type parameter declarations. Where
3822 /// clauses are not parsed here, and must be added later via
3823 /// `parse_where_clause()`.
3825 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
3826 /// | ( < lifetimes , typaramseq ( , )? > )
3827 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
3828 pub fn parse_generics(&mut self) -> PResult<ast::Generics> {
3829 if try!(self.eat(&token::Lt) ){
3830 let lifetime_defs = try!(self.parse_lifetime_defs());
3831 let mut seen_default = false;
3832 let ty_params = try!(self.parse_seq_to_gt(Some(token::Comma), |p| {
3833 try!(p.forbid_lifetime());
3834 let ty_param = try!(p.parse_ty_param());
3835 if ty_param.default.is_some() {
3836 seen_default = true;
3837 } else if seen_default {
3838 let last_span = p.last_span;
3839 p.span_err(last_span,
3840 "type parameters with a default must be trailing");
3845 lifetimes: lifetime_defs,
3846 ty_params: ty_params,
3847 where_clause: WhereClause {
3848 id: ast::DUMMY_NODE_ID,
3849 predicates: Vec::new(),
3853 Ok(ast_util::empty_generics())
3857 fn parse_generic_values_after_lt(&mut self) -> PResult<(Vec<ast::Lifetime>,
3859 Vec<P<TypeBinding>>)> {
3860 let span_lo = self.span.lo;
3861 let lifetimes = try!(self.parse_lifetimes(token::Comma));
3863 let missing_comma = !lifetimes.is_empty() &&
3864 !self.token.is_like_gt() &&
3866 .as_ref().map_or(true,
3867 |x| &**x != &token::Comma);
3871 let msg = format!("expected `,` or `>` after lifetime \
3873 self.this_token_to_string());
3874 self.span_err(self.span, &msg);
3876 let span_hi = self.span.hi;
3877 let span_hi = if self.parse_ty_nopanic().is_ok() {
3883 let msg = format!("did you mean a single argument type &'a Type, \
3884 or did you mean the comma-separated arguments \
3886 self.span_note(mk_sp(span_lo, span_hi), &msg);
3888 self.abort_if_errors()
3891 // First parse types.
3892 let (types, returned) = try!(self.parse_seq_to_gt_or_return(
3895 try!(p.forbid_lifetime());
3896 if p.look_ahead(1, |t| t == &token::Eq) {
3899 Ok(Some(try!(p.parse_ty_sum())))
3904 // If we found the `>`, don't continue.
3906 return Ok((lifetimes, types.into_vec(), Vec::new()));
3909 // Then parse type bindings.
3910 let bindings = try!(self.parse_seq_to_gt(
3913 try!(p.forbid_lifetime());
3915 let ident = try!(p.parse_ident());
3916 let found_eq = try!(p.eat(&token::Eq));
3919 p.span_warn(span, "whoops, no =?");
3921 let ty = try!(p.parse_ty_nopanic());
3923 let span = mk_sp(lo, hi);
3924 return Ok(P(TypeBinding{id: ast::DUMMY_NODE_ID,
3931 Ok((lifetimes, types.into_vec(), bindings.into_vec()))
3934 fn forbid_lifetime(&mut self) -> PResult<()> {
3935 if self.token.is_lifetime() {
3936 let span = self.span;
3937 return Err(self.span_fatal(span, "lifetime parameters must be declared \
3938 prior to type parameters"))
3943 /// Parses an optional `where` clause and places it in `generics`.
3946 /// where T : Trait<U, V> + 'b, 'a : 'b
3948 pub fn parse_where_clause(&mut self) -> PResult<ast::WhereClause> {
3949 let mut where_clause = WhereClause {
3950 id: ast::DUMMY_NODE_ID,
3951 predicates: Vec::new(),
3954 if !try!(self.eat_keyword(keywords::Where)) {
3955 return Ok(where_clause);
3958 let mut parsed_something = false;
3960 let lo = self.span.lo;
3962 token::OpenDelim(token::Brace) => {
3966 token::Lifetime(..) => {
3967 let bounded_lifetime =
3968 try!(self.parse_lifetime());
3970 try!(self.eat(&token::Colon));
3973 try!(self.parse_lifetimes(token::BinOp(token::Plus)));
3975 let hi = self.last_span.hi;
3976 let span = mk_sp(lo, hi);
3978 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
3979 ast::WhereRegionPredicate {
3981 lifetime: bounded_lifetime,
3986 parsed_something = true;
3990 let bound_lifetimes = if try!(self.eat_keyword(keywords::For) ){
3991 // Higher ranked constraint.
3992 try!(self.expect(&token::Lt));
3993 let lifetime_defs = try!(self.parse_lifetime_defs());
3994 try!(self.expect_gt());
4000 let bounded_ty = try!(self.parse_ty_nopanic());
4002 if try!(self.eat(&token::Colon) ){
4003 let bounds = try!(self.parse_ty_param_bounds(BoundParsingMode::Bare));
4004 let hi = self.last_span.hi;
4005 let span = mk_sp(lo, hi);
4007 if bounds.is_empty() {
4009 "each predicate in a `where` clause must have \
4010 at least one bound in it");
4013 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
4014 ast::WhereBoundPredicate {
4016 bound_lifetimes: bound_lifetimes,
4017 bounded_ty: bounded_ty,
4021 parsed_something = true;
4022 } else if try!(self.eat(&token::Eq) ){
4023 // let ty = try!(self.parse_ty_nopanic());
4024 let hi = self.last_span.hi;
4025 let span = mk_sp(lo, hi);
4026 // where_clause.predicates.push(
4027 // ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
4028 // id: ast::DUMMY_NODE_ID,
4030 // path: panic!("NYI"), //bounded_ty,
4033 // parsed_something = true;
4036 "equality constraints are not yet supported \
4037 in where clauses (#20041)");
4039 let last_span = self.last_span;
4040 self.span_err(last_span,
4041 "unexpected token in `where` clause");
4046 if !try!(self.eat(&token::Comma) ){
4051 if !parsed_something {
4052 let last_span = self.last_span;
4053 self.span_err(last_span,
4054 "a `where` clause must have at least one predicate \
4061 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
4062 -> PResult<(Vec<Arg> , bool)> {
4064 let mut args: Vec<Option<Arg>> =
4065 try!(self.parse_unspanned_seq(
4066 &token::OpenDelim(token::Paren),
4067 &token::CloseDelim(token::Paren),
4068 seq_sep_trailing_allowed(token::Comma),
4070 if p.token == token::DotDotDot {
4073 if p.token != token::CloseDelim(token::Paren) {
4075 return Err(p.span_fatal(span,
4076 "`...` must be last in argument list for variadic function"))
4080 return Err(p.span_fatal(span,
4081 "only foreign functions are allowed to be variadic"))
4085 Ok(Some(try!(p.parse_arg_general(named_args))))
4090 let variadic = match args.pop() {
4093 // Need to put back that last arg
4100 if variadic && args.is_empty() {
4102 "variadic function must be declared with at least one named argument");
4105 let args = args.into_iter().map(|x| x.unwrap()).collect();
4107 Ok((args, variadic))
4110 /// Parse the argument list and result type of a function declaration
4111 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<P<FnDecl>> {
4113 let (args, variadic) = try!(self.parse_fn_args(true, allow_variadic));
4114 let ret_ty = try!(self.parse_ret_ty());
4123 fn is_self_ident(&mut self) -> bool {
4125 token::Ident(id, token::Plain) => id.name == special_idents::self_.name,
4130 fn expect_self_ident(&mut self) -> PResult<ast::Ident> {
4132 token::Ident(id, token::Plain) if id.name == special_idents::self_.name => {
4137 let token_str = self.this_token_to_string();
4138 return Err(self.fatal(&format!("expected `self`, found `{}`",
4144 fn is_self_type_ident(&mut self) -> bool {
4146 token::Ident(id, token::Plain) => id.name == special_idents::type_self.name,
4151 fn expect_self_type_ident(&mut self) -> PResult<ast::Ident> {
4153 token::Ident(id, token::Plain) if id.name == special_idents::type_self.name => {
4158 let token_str = self.this_token_to_string();
4159 Err(self.fatal(&format!("expected `Self`, found `{}`",
4165 /// Parse the argument list and result type of a function
4166 /// that may have a self type.
4167 fn parse_fn_decl_with_self<F>(&mut self,
4168 parse_arg_fn: F) -> PResult<(ExplicitSelf, P<FnDecl>)> where
4169 F: FnMut(&mut Parser) -> PResult<Arg>,
4171 fn maybe_parse_borrowed_explicit_self(this: &mut Parser)
4172 -> PResult<ast::ExplicitSelf_> {
4173 // The following things are possible to see here:
4178 // fn(&'lt mut self)
4180 // We already know that the current token is `&`.
4182 if this.look_ahead(1, |t| t.is_keyword(keywords::SelfValue)) {
4184 Ok(SelfRegion(None, MutImmutable, try!(this.expect_self_ident())))
4185 } else if this.look_ahead(1, |t| t.is_mutability()) &&
4186 this.look_ahead(2, |t| t.is_keyword(keywords::SelfValue)) {
4188 let mutability = try!(this.parse_mutability());
4189 Ok(SelfRegion(None, mutability, try!(this.expect_self_ident())))
4190 } else if this.look_ahead(1, |t| t.is_lifetime()) &&
4191 this.look_ahead(2, |t| t.is_keyword(keywords::SelfValue)) {
4193 let lifetime = try!(this.parse_lifetime());
4194 Ok(SelfRegion(Some(lifetime), MutImmutable, try!(this.expect_self_ident())))
4195 } else if this.look_ahead(1, |t| t.is_lifetime()) &&
4196 this.look_ahead(2, |t| t.is_mutability()) &&
4197 this.look_ahead(3, |t| t.is_keyword(keywords::SelfValue)) {
4199 let lifetime = try!(this.parse_lifetime());
4200 let mutability = try!(this.parse_mutability());
4201 Ok(SelfRegion(Some(lifetime), mutability, try!(this.expect_self_ident())))
4207 try!(self.expect(&token::OpenDelim(token::Paren)));
4209 // A bit of complexity and lookahead is needed here in order to be
4210 // backwards compatible.
4211 let lo = self.span.lo;
4212 let mut self_ident_lo = self.span.lo;
4213 let mut self_ident_hi = self.span.hi;
4215 let mut mutbl_self = MutImmutable;
4216 let explicit_self = match self.token {
4217 token::BinOp(token::And) => {
4218 let eself = try!(maybe_parse_borrowed_explicit_self(self));
4219 self_ident_lo = self.last_span.lo;
4220 self_ident_hi = self.last_span.hi;
4223 token::BinOp(token::Star) => {
4224 // Possibly "*self" or "*mut self" -- not supported. Try to avoid
4225 // emitting cryptic "unexpected token" errors.
4227 let _mutability = if self.token.is_mutability() {
4228 try!(self.parse_mutability())
4232 if self.is_self_ident() {
4233 let span = self.span;
4234 self.span_err(span, "cannot pass self by unsafe pointer");
4237 // error case, making bogus self ident:
4238 SelfValue(special_idents::self_)
4240 token::Ident(..) => {
4241 if self.is_self_ident() {
4242 let self_ident = try!(self.expect_self_ident());
4244 // Determine whether this is the fully explicit form, `self:
4246 if try!(self.eat(&token::Colon) ){
4247 SelfExplicit(try!(self.parse_ty_sum()), self_ident)
4249 SelfValue(self_ident)
4251 } else if self.token.is_mutability() &&
4252 self.look_ahead(1, |t| t.is_keyword(keywords::SelfValue)) {
4253 mutbl_self = try!(self.parse_mutability());
4254 let self_ident = try!(self.expect_self_ident());
4256 // Determine whether this is the fully explicit form,
4258 if try!(self.eat(&token::Colon) ){
4259 SelfExplicit(try!(self.parse_ty_sum()), self_ident)
4261 SelfValue(self_ident)
4270 let explicit_self_sp = mk_sp(self_ident_lo, self_ident_hi);
4272 // shared fall-through for the three cases below. borrowing prevents simply
4273 // writing this as a closure
4274 macro_rules! parse_remaining_arguments {
4277 // If we parsed a self type, expect a comma before the argument list.
4281 let sep = seq_sep_trailing_allowed(token::Comma);
4282 let mut fn_inputs = try!(self.parse_seq_to_before_end(
4283 &token::CloseDelim(token::Paren),
4287 fn_inputs.insert(0, Arg::new_self(explicit_self_sp, mutbl_self, $self_id));
4290 token::CloseDelim(token::Paren) => {
4291 vec!(Arg::new_self(explicit_self_sp, mutbl_self, $self_id))
4294 let token_str = self.this_token_to_string();
4295 return Err(self.fatal(&format!("expected `,` or `)`, found `{}`",
4302 let fn_inputs = match explicit_self {
4304 let sep = seq_sep_trailing_allowed(token::Comma);
4305 try!(self.parse_seq_to_before_end(&token::CloseDelim(token::Paren),
4308 SelfValue(id) => parse_remaining_arguments!(id),
4309 SelfRegion(_,_,id) => parse_remaining_arguments!(id),
4310 SelfExplicit(_,id) => parse_remaining_arguments!(id),
4314 try!(self.expect(&token::CloseDelim(token::Paren)));
4316 let hi = self.span.hi;
4318 let ret_ty = try!(self.parse_ret_ty());
4320 let fn_decl = P(FnDecl {
4326 Ok((spanned(lo, hi, explicit_self), fn_decl))
4329 // parse the |arg, arg| header on a lambda
4330 fn parse_fn_block_decl(&mut self) -> PResult<P<FnDecl>> {
4331 let inputs_captures = {
4332 if try!(self.eat(&token::OrOr) ){
4335 try!(self.expect(&token::BinOp(token::Or)));
4336 try!(self.parse_obsolete_closure_kind());
4337 let args = try!(self.parse_seq_to_before_end(
4338 &token::BinOp(token::Or),
4339 seq_sep_trailing_allowed(token::Comma),
4340 |p| p.parse_fn_block_arg()
4346 let output = try!(self.parse_ret_ty());
4349 inputs: inputs_captures,
4355 /// Parse the name and optional generic types of a function header.
4356 fn parse_fn_header(&mut self) -> PResult<(Ident, ast::Generics)> {
4357 let id = try!(self.parse_ident());
4358 let generics = try!(self.parse_generics());
4362 fn mk_item(&mut self, lo: BytePos, hi: BytePos, ident: Ident,
4363 node: Item_, vis: Visibility,
4364 attrs: Vec<Attribute>) -> P<Item> {
4368 id: ast::DUMMY_NODE_ID,
4375 /// Parse an item-position function declaration.
4376 fn parse_item_fn(&mut self, unsafety: Unsafety, abi: abi::Abi) -> PResult<ItemInfo> {
4377 let (ident, mut generics) = try!(self.parse_fn_header());
4378 let decl = try!(self.parse_fn_decl(false));
4379 generics.where_clause = try!(self.parse_where_clause());
4380 let (inner_attrs, body) = try!(self.parse_inner_attrs_and_block());
4381 Ok((ident, ItemFn(decl, unsafety, abi, generics, body), Some(inner_attrs)))
4384 /// Parse an impl item.
4385 pub fn parse_impl_item(&mut self) -> PResult<P<ImplItem>> {
4386 maybe_whole!(no_clone self, NtImplItem);
4388 let mut attrs = self.parse_outer_attributes();
4389 let lo = self.span.lo;
4390 let vis = try!(self.parse_visibility());
4391 let (name, node) = if try!(self.eat_keyword(keywords::Type)) {
4392 let name = try!(self.parse_ident());
4393 try!(self.expect(&token::Eq));
4394 let typ = try!(self.parse_ty_sum());
4395 try!(self.expect(&token::Semi));
4396 (name, TypeImplItem(typ))
4397 } else if try!(self.eat_keyword(keywords::Const)) {
4398 let name = try!(self.parse_ident());
4399 try!(self.expect(&token::Colon));
4400 let typ = try!(self.parse_ty_sum());
4401 try!(self.expect(&token::Eq));
4402 let expr = try!(self.parse_expr_nopanic());
4403 try!(self.commit_expr_expecting(&expr, token::Semi));
4404 (name, ConstImplItem(typ, expr))
4406 let (name, inner_attrs, node) = try!(self.parse_impl_method(vis));
4407 attrs.extend(inner_attrs.into_iter());
4412 id: ast::DUMMY_NODE_ID,
4413 span: mk_sp(lo, self.last_span.hi),
4421 fn complain_if_pub_macro(&mut self, visa: Visibility, span: Span) {
4424 self.span_err(span, "can't qualify macro invocation with `pub`");
4425 self.fileline_help(span, "try adjusting the macro to put `pub` inside \
4432 /// Parse a method or a macro invocation in a trait impl.
4433 fn parse_impl_method(&mut self, vis: Visibility)
4434 -> PResult<(Ident, Vec<ast::Attribute>, ast::ImplItem_)> {
4435 // code copied from parse_macro_use_or_failure... abstraction!
4436 if !self.token.is_any_keyword()
4437 && self.look_ahead(1, |t| *t == token::Not)
4438 && (self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren))
4439 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) {
4442 let last_span = self.last_span;
4443 self.complain_if_pub_macro(vis, last_span);
4445 let pth = try!(self.parse_path(NoTypesAllowed));
4446 try!(self.expect(&token::Not));
4448 // eat a matched-delimiter token tree:
4449 let delim = try!(self.expect_open_delim());
4450 let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
4452 |p| p.parse_token_tree()));
4453 let m_ = ast::MacInvocTT(pth, tts, EMPTY_CTXT);
4454 let m: ast::Mac = codemap::Spanned { node: m_,
4455 span: mk_sp(self.span.lo,
4457 if delim != token::Brace {
4458 try!(self.expect(&token::Semi))
4460 Ok((token::special_idents::invalid, vec![], ast::MacImplItem(m)))
4462 let unsafety = try!(self.parse_unsafety());
4463 let abi = if try!(self.eat_keyword(keywords::Extern)) {
4464 try!(self.parse_opt_abi()).unwrap_or(abi::C)
4468 try!(self.expect_keyword(keywords::Fn));
4469 let ident = try!(self.parse_ident());
4470 let mut generics = try!(self.parse_generics());
4471 let (explicit_self, decl) = try!(self.parse_fn_decl_with_self(|p| {
4474 generics.where_clause = try!(self.parse_where_clause());
4475 let (inner_attrs, body) = try!(self.parse_inner_attrs_and_block());
4476 Ok((ident, inner_attrs, MethodImplItem(ast::MethodSig {
4479 explicit_self: explicit_self,
4486 /// Parse trait Foo { ... }
4487 fn parse_item_trait(&mut self, unsafety: Unsafety) -> PResult<ItemInfo> {
4489 let ident = try!(self.parse_ident());
4490 let mut tps = try!(self.parse_generics());
4492 // Parse supertrait bounds.
4493 let bounds = try!(self.parse_colon_then_ty_param_bounds(BoundParsingMode::Bare));
4495 tps.where_clause = try!(self.parse_where_clause());
4497 let meths = try!(self.parse_trait_items());
4498 Ok((ident, ItemTrait(unsafety, tps, bounds, meths), None))
4501 /// Parses items implementations variants
4502 /// impl<T> Foo { ... }
4503 /// impl<T> ToString for &'static T { ... }
4504 /// impl Send for .. {}
4505 fn parse_item_impl(&mut self, unsafety: ast::Unsafety) -> PResult<ItemInfo> {
4506 let impl_span = self.span;
4508 // First, parse type parameters if necessary.
4509 let mut generics = try!(self.parse_generics());
4511 // Special case: if the next identifier that follows is '(', don't
4512 // allow this to be parsed as a trait.
4513 let could_be_trait = self.token != token::OpenDelim(token::Paren);
4515 let neg_span = self.span;
4516 let polarity = if try!(self.eat(&token::Not) ){
4517 ast::ImplPolarity::Negative
4519 ast::ImplPolarity::Positive
4523 let mut ty = try!(self.parse_ty_sum());
4525 // Parse traits, if necessary.
4526 let opt_trait = if could_be_trait && try!(self.eat_keyword(keywords::For) ){
4527 // New-style trait. Reinterpret the type as a trait.
4529 TyPath(None, ref path) => {
4531 path: (*path).clone(),
4536 self.span_err(ty.span, "not a trait");
4542 ast::ImplPolarity::Negative => {
4543 // This is a negated type implementation
4544 // `impl !MyType {}`, which is not allowed.
4545 self.span_err(neg_span, "inherent implementation can't be negated");
4552 if try!(self.eat(&token::DotDot) ){
4553 if generics.is_parameterized() {
4554 self.span_err(impl_span, "default trait implementations are not \
4555 allowed to have genercis");
4558 try!(self.expect(&token::OpenDelim(token::Brace)));
4559 try!(self.expect(&token::CloseDelim(token::Brace)));
4560 Ok((ast_util::impl_pretty_name(&opt_trait, None),
4561 ItemDefaultImpl(unsafety, opt_trait.unwrap()), None))
4563 if opt_trait.is_some() {
4564 ty = try!(self.parse_ty_sum());
4566 generics.where_clause = try!(self.parse_where_clause());
4568 try!(self.expect(&token::OpenDelim(token::Brace)));
4569 let attrs = self.parse_inner_attributes();
4571 let mut impl_items = vec![];
4572 while !try!(self.eat(&token::CloseDelim(token::Brace))) {
4573 impl_items.push(try!(self.parse_impl_item()));
4576 Ok((ast_util::impl_pretty_name(&opt_trait, Some(&*ty)),
4577 ItemImpl(unsafety, polarity, generics, opt_trait, ty, impl_items),
4582 /// Parse a::B<String,i32>
4583 fn parse_trait_ref(&mut self) -> PResult<TraitRef> {
4585 path: try!(self.parse_path(LifetimeAndTypesWithoutColons)),
4586 ref_id: ast::DUMMY_NODE_ID,
4590 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<Vec<ast::LifetimeDef>> {
4591 if try!(self.eat_keyword(keywords::For) ){
4592 try!(self.expect(&token::Lt));
4593 let lifetime_defs = try!(self.parse_lifetime_defs());
4594 try!(self.expect_gt());
4601 /// Parse for<'l> a::B<String,i32>
4602 fn parse_poly_trait_ref(&mut self) -> PResult<PolyTraitRef> {
4603 let lo = self.span.lo;
4604 let lifetime_defs = try!(self.parse_late_bound_lifetime_defs());
4606 Ok(ast::PolyTraitRef {
4607 bound_lifetimes: lifetime_defs,
4608 trait_ref: try!(self.parse_trait_ref()),
4609 span: mk_sp(lo, self.last_span.hi),
4613 /// Parse struct Foo { ... }
4614 fn parse_item_struct(&mut self) -> PResult<ItemInfo> {
4615 let class_name = try!(self.parse_ident());
4616 let mut generics = try!(self.parse_generics());
4618 if try!(self.eat(&token::Colon) ){
4619 let ty = try!(self.parse_ty_sum());
4620 self.span_err(ty.span, "`virtual` structs have been removed from the language");
4623 // There is a special case worth noting here, as reported in issue #17904.
4624 // If we are parsing a tuple struct it is the case that the where clause
4625 // should follow the field list. Like so:
4627 // struct Foo<T>(T) where T: Copy;
4629 // If we are parsing a normal record-style struct it is the case
4630 // that the where clause comes before the body, and after the generics.
4631 // So if we look ahead and see a brace or a where-clause we begin
4632 // parsing a record style struct.
4634 // Otherwise if we look ahead and see a paren we parse a tuple-style
4637 let (fields, ctor_id) = if self.token.is_keyword(keywords::Where) {
4638 generics.where_clause = try!(self.parse_where_clause());
4639 if try!(self.eat(&token::Semi)) {
4640 // If we see a: `struct Foo<T> where T: Copy;` style decl.
4641 (Vec::new(), Some(ast::DUMMY_NODE_ID))
4643 // If we see: `struct Foo<T> where T: Copy { ... }`
4644 (try!(self.parse_record_struct_body(&class_name)), None)
4646 // No `where` so: `struct Foo<T>;`
4647 } else if try!(self.eat(&token::Semi) ){
4648 (Vec::new(), Some(ast::DUMMY_NODE_ID))
4649 // Record-style struct definition
4650 } else if self.token == token::OpenDelim(token::Brace) {
4651 let fields = try!(self.parse_record_struct_body(&class_name));
4653 // Tuple-style struct definition with optional where-clause.
4655 let fields = try!(self.parse_tuple_struct_body(&class_name, &mut generics));
4656 (fields, Some(ast::DUMMY_NODE_ID))
4660 ItemStruct(P(ast::StructDef {
4667 pub fn parse_record_struct_body(&mut self,
4668 class_name: &ast::Ident) -> PResult<Vec<StructField>> {
4669 let mut fields = Vec::new();
4670 if try!(self.eat(&token::OpenDelim(token::Brace)) ){
4671 while self.token != token::CloseDelim(token::Brace) {
4672 fields.push(try!(self.parse_struct_decl_field(true)));
4675 if fields.is_empty() {
4676 return Err(self.fatal(&format!("unit-like struct definition should be \
4677 written as `struct {};`",
4678 token::get_ident(class_name.clone()))));
4683 let token_str = self.this_token_to_string();
4684 return Err(self.fatal(&format!("expected `where`, or `{}` after struct \
4685 name, found `{}`", "{",
4692 pub fn parse_tuple_struct_body(&mut self,
4693 class_name: &ast::Ident,
4694 generics: &mut ast::Generics)
4695 -> PResult<Vec<StructField>> {
4696 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
4697 if self.check(&token::OpenDelim(token::Paren)) {
4698 let fields = try!(self.parse_unspanned_seq(
4699 &token::OpenDelim(token::Paren),
4700 &token::CloseDelim(token::Paren),
4701 seq_sep_trailing_allowed(token::Comma),
4703 let attrs = p.parse_outer_attributes();
4705 let struct_field_ = ast::StructField_ {
4706 kind: UnnamedField(try!(p.parse_visibility())),
4707 id: ast::DUMMY_NODE_ID,
4708 ty: try!(p.parse_ty_sum()),
4711 Ok(spanned(lo, p.span.hi, struct_field_))
4714 if fields.is_empty() {
4715 return Err(self.fatal(&format!("unit-like struct definition should be \
4716 written as `struct {};`",
4717 token::get_ident(class_name.clone()))));
4720 generics.where_clause = try!(self.parse_where_clause());
4721 try!(self.expect(&token::Semi));
4723 // This is the case where we just see struct Foo<T> where T: Copy;
4724 } else if self.token.is_keyword(keywords::Where) {
4725 generics.where_clause = try!(self.parse_where_clause());
4726 try!(self.expect(&token::Semi));
4728 // This case is where we see: `struct Foo<T>;`
4730 let token_str = self.this_token_to_string();
4731 Err(self.fatal(&format!("expected `where`, `{}`, `(`, or `;` after struct \
4732 name, found `{}`", "{", token_str)))
4736 /// Parse a structure field declaration
4737 pub fn parse_single_struct_field(&mut self,
4739 attrs: Vec<Attribute> )
4740 -> PResult<StructField> {
4741 let a_var = try!(self.parse_name_and_ty(vis, attrs));
4746 token::CloseDelim(token::Brace) => {}
4748 let span = self.span;
4749 let token_str = self.this_token_to_string();
4750 return Err(self.span_fatal_help(span,
4751 &format!("expected `,`, or `}}`, found `{}`",
4753 "struct fields should be separated by commas"))
4759 /// Parse an element of a struct definition
4760 fn parse_struct_decl_field(&mut self, allow_pub: bool) -> PResult<StructField> {
4762 let attrs = self.parse_outer_attributes();
4764 if try!(self.eat_keyword(keywords::Pub) ){
4766 let span = self.last_span;
4767 self.span_err(span, "`pub` is not allowed here");
4769 return self.parse_single_struct_field(Public, attrs);
4772 return self.parse_single_struct_field(Inherited, attrs);
4775 /// Parse visibility: PUB, PRIV, or nothing
4776 fn parse_visibility(&mut self) -> PResult<Visibility> {
4777 if try!(self.eat_keyword(keywords::Pub)) { Ok(Public) }
4778 else { Ok(Inherited) }
4781 /// Given a termination token, parse all of the items in a module
4782 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: BytePos) -> PResult<Mod> {
4783 let mut items = vec![];
4784 while let Some(item) = try!(self.parse_item_nopanic()) {
4788 if !try!(self.eat(term)) {
4789 let token_str = self.this_token_to_string();
4790 return Err(self.fatal(&format!("expected item, found `{}`", token_str)));
4794 inner: mk_sp(inner_lo, self.span.lo),
4799 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<ItemInfo> {
4800 let id = try!(self.parse_ident());
4801 try!(self.expect(&token::Colon));
4802 let ty = try!(self.parse_ty_sum());
4803 try!(self.expect(&token::Eq));
4804 let e = try!(self.parse_expr_nopanic());
4805 try!(self.commit_expr_expecting(&*e, token::Semi));
4806 let item = match m {
4807 Some(m) => ItemStatic(ty, m, e),
4808 None => ItemConst(ty, e),
4810 Ok((id, item, None))
4813 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
4814 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<ItemInfo> {
4815 let id_span = self.span;
4816 let id = try!(self.parse_ident());
4817 if self.check(&token::Semi) {
4819 // This mod is in an external file. Let's go get it!
4820 let (m, attrs) = try!(self.eval_src_mod(id, outer_attrs, id_span));
4821 Ok((id, m, Some(attrs)))
4823 self.push_mod_path(id, outer_attrs);
4824 try!(self.expect(&token::OpenDelim(token::Brace)));
4825 let mod_inner_lo = self.span.lo;
4826 let old_owns_directory = self.owns_directory;
4827 self.owns_directory = true;
4828 let attrs = self.parse_inner_attributes();
4829 let m = try!(self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo));
4830 self.owns_directory = old_owns_directory;
4831 self.pop_mod_path();
4832 Ok((id, ItemMod(m), Some(attrs)))
4836 fn push_mod_path(&mut self, id: Ident, attrs: &[Attribute]) {
4837 let default_path = self.id_to_interned_str(id);
4838 let file_path = match ::attr::first_attr_value_str_by_name(attrs,
4841 None => default_path,
4843 self.mod_path_stack.push(file_path)
4846 fn pop_mod_path(&mut self) {
4847 self.mod_path_stack.pop().unwrap();
4850 /// Read a module from a source file.
4851 fn eval_src_mod(&mut self,
4853 outer_attrs: &[ast::Attribute],
4855 -> PResult<(ast::Item_, Vec<ast::Attribute> )> {
4856 let mut prefix = PathBuf::from(&self.sess.span_diagnostic.cm
4857 .span_to_filename(self.span));
4859 let mut dir_path = prefix;
4860 for part in &self.mod_path_stack {
4861 dir_path.push(&**part);
4863 let mod_string = token::get_ident(id);
4864 let (file_path, owns_directory) = match ::attr::first_attr_value_str_by_name(
4865 outer_attrs, "path") {
4866 Some(d) => (dir_path.join(&*d), true),
4868 let mod_name = mod_string.to_string();
4869 let default_path_str = format!("{}.rs", mod_name);
4870 let secondary_path_str = format!("{}/mod.rs", mod_name);
4871 let default_path = dir_path.join(&default_path_str[..]);
4872 let secondary_path = dir_path.join(&secondary_path_str[..]);
4873 let default_exists = fs::metadata(&default_path).is_ok();
4874 let secondary_exists = fs::metadata(&secondary_path).is_ok();
4876 if !self.owns_directory {
4877 self.span_err(id_sp,
4878 "cannot declare a new module at this location");
4879 let this_module = match self.mod_path_stack.last() {
4880 Some(name) => name.to_string(),
4881 None => self.root_module_name.as_ref().unwrap().clone(),
4883 self.span_note(id_sp,
4884 &format!("maybe move this module `{0}` \
4885 to its own directory via \
4888 if default_exists || secondary_exists {
4889 self.span_note(id_sp,
4890 &format!("... or maybe `use` the module \
4891 `{}` instead of possibly \
4895 self.abort_if_errors();
4898 match (default_exists, secondary_exists) {
4899 (true, false) => (default_path, false),
4900 (false, true) => (secondary_path, true),
4902 return Err(self.span_fatal_help(id_sp,
4903 &format!("file not found for module `{}`",
4905 &format!("name the file either {} or {} inside \
4906 the directory {:?}",
4909 dir_path.display())));
4912 return Err(self.span_fatal_help(
4914 &format!("file for module `{}` found at both {} \
4918 secondary_path_str),
4919 "delete or rename one of them to remove the ambiguity"));
4925 self.eval_src_mod_from_path(file_path, owns_directory,
4926 mod_string.to_string(), id_sp)
4929 fn eval_src_mod_from_path(&mut self,
4931 owns_directory: bool,
4933 id_sp: Span) -> PResult<(ast::Item_, Vec<ast::Attribute> )> {
4934 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
4935 match included_mod_stack.iter().position(|p| *p == path) {
4937 let mut err = String::from("circular modules: ");
4938 let len = included_mod_stack.len();
4939 for p in &included_mod_stack[i.. len] {
4940 err.push_str(&p.to_string_lossy());
4941 err.push_str(" -> ");
4943 err.push_str(&path.to_string_lossy());
4944 return Err(self.span_fatal(id_sp, &err[..]));
4948 included_mod_stack.push(path.clone());
4949 drop(included_mod_stack);
4952 new_sub_parser_from_file(self.sess,
4958 let mod_inner_lo = p0.span.lo;
4959 let mod_attrs = p0.parse_inner_attributes();
4960 let m0 = try!(p0.parse_mod_items(&token::Eof, mod_inner_lo));
4961 self.sess.included_mod_stack.borrow_mut().pop();
4962 Ok((ast::ItemMod(m0), mod_attrs))
4965 /// Parse a function declaration from a foreign module
4966 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility,
4967 attrs: Vec<Attribute>) -> PResult<P<ForeignItem>> {
4968 let lo = self.span.lo;
4969 try!(self.expect_keyword(keywords::Fn));
4971 let (ident, mut generics) = try!(self.parse_fn_header());
4972 let decl = try!(self.parse_fn_decl(true));
4973 generics.where_clause = try!(self.parse_where_clause());
4974 let hi = self.span.hi;
4975 try!(self.expect(&token::Semi));
4976 Ok(P(ast::ForeignItem {
4979 node: ForeignItemFn(decl, generics),
4980 id: ast::DUMMY_NODE_ID,
4981 span: mk_sp(lo, hi),
4986 /// Parse a static item from a foreign module
4987 fn parse_item_foreign_static(&mut self, vis: ast::Visibility,
4988 attrs: Vec<Attribute>) -> PResult<P<ForeignItem>> {
4989 let lo = self.span.lo;
4991 try!(self.expect_keyword(keywords::Static));
4992 let mutbl = try!(self.eat_keyword(keywords::Mut));
4994 let ident = try!(self.parse_ident());
4995 try!(self.expect(&token::Colon));
4996 let ty = try!(self.parse_ty_sum());
4997 let hi = self.span.hi;
4998 try!(self.expect(&token::Semi));
5002 node: ForeignItemStatic(ty, mutbl),
5003 id: ast::DUMMY_NODE_ID,
5004 span: mk_sp(lo, hi),
5009 /// Parse extern crate links
5013 /// extern crate foo;
5014 /// extern crate bar as foo;
5015 fn parse_item_extern_crate(&mut self,
5017 visibility: Visibility,
5018 attrs: Vec<Attribute>)
5019 -> PResult<P<Item>> {
5021 let crate_name = try!(self.parse_ident());
5022 let (maybe_path, ident) = if try!(self.eat_keyword(keywords::As)) {
5023 (Some(crate_name.name), try!(self.parse_ident()))
5027 try!(self.expect(&token::Semi));
5029 let last_span = self.last_span;
5033 ItemExternCrate(maybe_path),
5038 /// Parse `extern` for foreign ABIs
5041 /// `extern` is expected to have been
5042 /// consumed before calling this method
5048 fn parse_item_foreign_mod(&mut self,
5050 opt_abi: Option<abi::Abi>,
5051 visibility: Visibility,
5052 mut attrs: Vec<Attribute>)
5053 -> PResult<P<Item>> {
5054 try!(self.expect(&token::OpenDelim(token::Brace)));
5056 let abi = opt_abi.unwrap_or(abi::C);
5058 attrs.extend(self.parse_inner_attributes().into_iter());
5060 let mut foreign_items = vec![];
5061 while let Some(item) = try!(self.parse_foreign_item()) {
5062 foreign_items.push(item);
5064 try!(self.expect(&token::CloseDelim(token::Brace)));
5066 let last_span = self.last_span;
5067 let m = ast::ForeignMod {
5069 items: foreign_items
5073 special_idents::invalid,
5079 /// Parse type Foo = Bar;
5080 fn parse_item_type(&mut self) -> PResult<ItemInfo> {
5081 let ident = try!(self.parse_ident());
5082 let mut tps = try!(self.parse_generics());
5083 tps.where_clause = try!(self.parse_where_clause());
5084 try!(self.expect(&token::Eq));
5085 let ty = try!(self.parse_ty_sum());
5086 try!(self.expect(&token::Semi));
5087 Ok((ident, ItemTy(ty, tps), None))
5090 /// Parse a structure-like enum variant definition
5091 /// this should probably be renamed or refactored...
5092 fn parse_struct_def(&mut self) -> PResult<P<StructDef>> {
5093 let mut fields: Vec<StructField> = Vec::new();
5094 while self.token != token::CloseDelim(token::Brace) {
5095 fields.push(try!(self.parse_struct_decl_field(false)));
5105 /// Parse the part of an "enum" decl following the '{'
5106 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<EnumDef> {
5107 let mut variants = Vec::new();
5108 let mut all_nullary = true;
5109 let mut any_disr = None;
5110 while self.token != token::CloseDelim(token::Brace) {
5111 let variant_attrs = self.parse_outer_attributes();
5112 let vlo = self.span.lo;
5114 let vis = try!(self.parse_visibility());
5118 let mut args = Vec::new();
5119 let mut disr_expr = None;
5120 ident = try!(self.parse_ident());
5121 if try!(self.eat(&token::OpenDelim(token::Brace)) ){
5122 // Parse a struct variant.
5123 all_nullary = false;
5124 let start_span = self.span;
5125 let struct_def = try!(self.parse_struct_def());
5126 if struct_def.fields.is_empty() {
5127 self.span_err(start_span,
5128 &format!("unit-like struct variant should be written \
5129 without braces, as `{},`",
5130 token::get_ident(ident)));
5132 kind = StructVariantKind(struct_def);
5133 } else if self.check(&token::OpenDelim(token::Paren)) {
5134 all_nullary = false;
5135 let arg_tys = try!(self.parse_enum_variant_seq(
5136 &token::OpenDelim(token::Paren),
5137 &token::CloseDelim(token::Paren),
5138 seq_sep_trailing_allowed(token::Comma),
5139 |p| p.parse_ty_sum()
5142 args.push(ast::VariantArg {
5144 id: ast::DUMMY_NODE_ID,
5147 kind = TupleVariantKind(args);
5148 } else if try!(self.eat(&token::Eq) ){
5149 disr_expr = Some(try!(self.parse_expr_nopanic()));
5150 any_disr = disr_expr.as_ref().map(|expr| expr.span);
5151 kind = TupleVariantKind(args);
5153 kind = TupleVariantKind(Vec::new());
5156 let vr = ast::Variant_ {
5158 attrs: variant_attrs,
5160 id: ast::DUMMY_NODE_ID,
5161 disr_expr: disr_expr,
5164 variants.push(P(spanned(vlo, self.last_span.hi, vr)));
5166 if !try!(self.eat(&token::Comma)) { break; }
5168 try!(self.expect(&token::CloseDelim(token::Brace)));
5170 Some(disr_span) if !all_nullary =>
5171 self.span_err(disr_span,
5172 "discriminator values can only be used with a c-like enum"),
5176 Ok(ast::EnumDef { variants: variants })
5179 /// Parse an "enum" declaration
5180 fn parse_item_enum(&mut self) -> PResult<ItemInfo> {
5181 let id = try!(self.parse_ident());
5182 let mut generics = try!(self.parse_generics());
5183 generics.where_clause = try!(self.parse_where_clause());
5184 try!(self.expect(&token::OpenDelim(token::Brace)));
5186 let enum_definition = try!(self.parse_enum_def(&generics));
5187 Ok((id, ItemEnum(enum_definition, generics), None))
5190 /// Parses a string as an ABI spec on an extern type or module. Consumes
5191 /// the `extern` keyword, if one is found.
5192 fn parse_opt_abi(&mut self) -> PResult<Option<abi::Abi>> {
5194 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
5196 self.expect_no_suffix(sp, "ABI spec", suf);
5198 let the_string = s.as_str();
5199 match abi::lookup(the_string) {
5200 Some(abi) => Ok(Some(abi)),
5202 let last_span = self.last_span;
5205 &format!("illegal ABI: expected one of [{}], \
5207 abi::all_names().connect(", "),
5218 /// Parse one of the items allowed by the flags.
5219 /// NB: this function no longer parses the items inside an
5221 fn parse_item_(&mut self, attrs: Vec<Attribute>,
5222 macros_allowed: bool) -> PResult<Option<P<Item>>> {
5223 let nt_item = match self.token {
5224 token::Interpolated(token::NtItem(ref item)) => {
5225 Some((**item).clone())
5232 let mut attrs = attrs;
5233 mem::swap(&mut item.attrs, &mut attrs);
5234 item.attrs.extend(attrs.into_iter());
5235 return Ok(Some(P(item)));
5240 let lo = self.span.lo;
5242 let visibility = try!(self.parse_visibility());
5244 if try!(self.eat_keyword(keywords::Use) ){
5246 let item_ = ItemUse(try!(self.parse_view_path()));
5247 try!(self.expect(&token::Semi));
5249 let last_span = self.last_span;
5250 let item = self.mk_item(lo,
5252 token::special_idents::invalid,
5256 return Ok(Some(item));
5259 if try!(self.eat_keyword(keywords::Extern)) {
5260 if try!(self.eat_keyword(keywords::Crate)) {
5261 return Ok(Some(try!(self.parse_item_extern_crate(lo, visibility, attrs))));
5264 let opt_abi = try!(self.parse_opt_abi());
5266 if try!(self.eat_keyword(keywords::Fn) ){
5267 // EXTERN FUNCTION ITEM
5268 let abi = opt_abi.unwrap_or(abi::C);
5269 let (ident, item_, extra_attrs) =
5270 try!(self.parse_item_fn(Unsafety::Normal, abi));
5271 let last_span = self.last_span;
5272 let item = self.mk_item(lo,
5277 maybe_append(attrs, extra_attrs));
5278 return Ok(Some(item));
5279 } else if self.check(&token::OpenDelim(token::Brace)) {
5280 return Ok(Some(try!(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs))));
5283 let span = self.span;
5284 let token_str = self.this_token_to_string();
5285 return Err(self.span_fatal(span,
5286 &format!("expected `{}` or `fn`, found `{}`", "{",
5290 if try!(self.eat_keyword_noexpect(keywords::Virtual) ){
5291 let span = self.span;
5292 self.span_err(span, "`virtual` structs have been removed from the language");
5295 if try!(self.eat_keyword(keywords::Static) ){
5297 let m = if try!(self.eat_keyword(keywords::Mut)) {MutMutable} else {MutImmutable};
5298 let (ident, item_, extra_attrs) = try!(self.parse_item_const(Some(m)));
5299 let last_span = self.last_span;
5300 let item = self.mk_item(lo,
5305 maybe_append(attrs, extra_attrs));
5306 return Ok(Some(item));
5308 if try!(self.eat_keyword(keywords::Const) ){
5310 if try!(self.eat_keyword(keywords::Mut) ){
5311 let last_span = self.last_span;
5312 self.span_err(last_span, "const globals cannot be mutable");
5313 self.fileline_help(last_span, "did you mean to declare a static?");
5315 let (ident, item_, extra_attrs) = try!(self.parse_item_const(None));
5316 let last_span = self.last_span;
5317 let item = self.mk_item(lo,
5322 maybe_append(attrs, extra_attrs));
5323 return Ok(Some(item));
5325 if self.check_keyword(keywords::Unsafe) &&
5326 self.look_ahead(1, |t| t.is_keyword(keywords::Trait))
5328 // UNSAFE TRAIT ITEM
5329 try!(self.expect_keyword(keywords::Unsafe));
5330 try!(self.expect_keyword(keywords::Trait));
5331 let (ident, item_, extra_attrs) =
5332 try!(self.parse_item_trait(ast::Unsafety::Unsafe));
5333 let last_span = self.last_span;
5334 let item = self.mk_item(lo,
5339 maybe_append(attrs, extra_attrs));
5340 return Ok(Some(item));
5342 if self.check_keyword(keywords::Unsafe) &&
5343 self.look_ahead(1, |t| t.is_keyword(keywords::Impl))
5346 try!(self.expect_keyword(keywords::Unsafe));
5347 try!(self.expect_keyword(keywords::Impl));
5348 let (ident, item_, extra_attrs) = try!(self.parse_item_impl(ast::Unsafety::Unsafe));
5349 let last_span = self.last_span;
5350 let item = self.mk_item(lo,
5355 maybe_append(attrs, extra_attrs));
5356 return Ok(Some(item));
5358 if self.check_keyword(keywords::Fn) {
5361 let (ident, item_, extra_attrs) =
5362 try!(self.parse_item_fn(Unsafety::Normal, abi::Rust));
5363 let last_span = self.last_span;
5364 let item = self.mk_item(lo,
5369 maybe_append(attrs, extra_attrs));
5370 return Ok(Some(item));
5372 if self.check_keyword(keywords::Unsafe)
5373 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
5374 // UNSAFE FUNCTION ITEM
5376 let abi = if try!(self.eat_keyword(keywords::Extern) ){
5377 try!(self.parse_opt_abi()).unwrap_or(abi::C)
5381 try!(self.expect_keyword(keywords::Fn));
5382 let (ident, item_, extra_attrs) =
5383 try!(self.parse_item_fn(Unsafety::Unsafe, abi));
5384 let last_span = self.last_span;
5385 let item = self.mk_item(lo,
5390 maybe_append(attrs, extra_attrs));
5391 return Ok(Some(item));
5393 if try!(self.eat_keyword(keywords::Mod) ){
5395 let (ident, item_, extra_attrs) =
5396 try!(self.parse_item_mod(&attrs[..]));
5397 let last_span = self.last_span;
5398 let item = self.mk_item(lo,
5403 maybe_append(attrs, extra_attrs));
5404 return Ok(Some(item));
5406 if try!(self.eat_keyword(keywords::Type) ){
5408 let (ident, item_, extra_attrs) = try!(self.parse_item_type());
5409 let last_span = self.last_span;
5410 let item = self.mk_item(lo,
5415 maybe_append(attrs, extra_attrs));
5416 return Ok(Some(item));
5418 if try!(self.eat_keyword(keywords::Enum) ){
5420 let (ident, item_, extra_attrs) = try!(self.parse_item_enum());
5421 let last_span = self.last_span;
5422 let item = self.mk_item(lo,
5427 maybe_append(attrs, extra_attrs));
5428 return Ok(Some(item));
5430 if try!(self.eat_keyword(keywords::Trait) ){
5432 let (ident, item_, extra_attrs) =
5433 try!(self.parse_item_trait(ast::Unsafety::Normal));
5434 let last_span = self.last_span;
5435 let item = self.mk_item(lo,
5440 maybe_append(attrs, extra_attrs));
5441 return Ok(Some(item));
5443 if try!(self.eat_keyword(keywords::Impl) ){
5445 let (ident, item_, extra_attrs) = try!(self.parse_item_impl(ast::Unsafety::Normal));
5446 let last_span = self.last_span;
5447 let item = self.mk_item(lo,
5452 maybe_append(attrs, extra_attrs));
5453 return Ok(Some(item));
5455 if try!(self.eat_keyword(keywords::Struct) ){
5457 let (ident, item_, extra_attrs) = try!(self.parse_item_struct());
5458 let last_span = self.last_span;
5459 let item = self.mk_item(lo,
5464 maybe_append(attrs, extra_attrs));
5465 return Ok(Some(item));
5467 self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility)
5470 /// Parse a foreign item.
5471 fn parse_foreign_item(&mut self) -> PResult<Option<P<ForeignItem>>> {
5472 let attrs = self.parse_outer_attributes();
5473 let lo = self.span.lo;
5474 let visibility = try!(self.parse_visibility());
5476 if self.check_keyword(keywords::Static) {
5477 // FOREIGN STATIC ITEM
5478 return Ok(Some(try!(self.parse_item_foreign_static(visibility, attrs))));
5480 if self.check_keyword(keywords::Fn) || self.check_keyword(keywords::Unsafe) {
5481 // FOREIGN FUNCTION ITEM
5482 return Ok(Some(try!(self.parse_item_foreign_fn(visibility, attrs))));
5485 // FIXME #5668: this will occur for a macro invocation:
5486 match try!(self.parse_macro_use_or_failure(attrs, true, lo, visibility)) {
5488 return Err(self.span_fatal(item.span, "macros cannot expand to foreign items"));
5494 /// This is the fall-through for parsing items.
5495 fn parse_macro_use_or_failure(
5497 attrs: Vec<Attribute> ,
5498 macros_allowed: bool,
5500 visibility: Visibility
5501 ) -> PResult<Option<P<Item>>> {
5502 if macros_allowed && !self.token.is_any_keyword()
5503 && self.look_ahead(1, |t| *t == token::Not)
5504 && (self.look_ahead(2, |t| t.is_plain_ident())
5505 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren))
5506 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) {
5507 // MACRO INVOCATION ITEM
5509 let last_span = self.last_span;
5510 self.complain_if_pub_macro(visibility, last_span);
5513 let pth = try!(self.parse_path(NoTypesAllowed));
5514 try!(self.expect(&token::Not));
5516 // a 'special' identifier (like what `macro_rules!` uses)
5517 // is optional. We should eventually unify invoc syntax
5519 let id = if self.token.is_plain_ident() {
5520 try!(self.parse_ident())
5522 token::special_idents::invalid // no special identifier
5524 // eat a matched-delimiter token tree:
5525 let delim = try!(self.expect_open_delim());
5526 let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
5528 |p| p.parse_token_tree()));
5529 // single-variant-enum... :
5530 let m = ast::MacInvocTT(pth, tts, EMPTY_CTXT);
5531 let m: ast::Mac = codemap::Spanned { node: m,
5532 span: mk_sp(self.span.lo,
5535 if delim != token::Brace {
5536 if !try!(self.eat(&token::Semi) ){
5537 let last_span = self.last_span;
5538 self.span_err(last_span,
5539 "macros that expand to items must either \
5540 be surrounded with braces or followed by \
5545 let item_ = ItemMac(m);
5546 let last_span = self.last_span;
5547 let item = self.mk_item(lo,
5553 return Ok(Some(item));
5556 // FAILURE TO PARSE ITEM
5560 let last_span = self.last_span;
5561 return Err(self.span_fatal(last_span, "unmatched visibility `pub`"));
5565 if !attrs.is_empty() {
5566 self.expected_item_err(&attrs);
5571 pub fn parse_item_nopanic(&mut self) -> PResult<Option<P<Item>>> {
5572 let attrs = self.parse_outer_attributes();
5573 self.parse_item_(attrs, true)
5577 /// Matches view_path : MOD? non_global_path as IDENT
5578 /// | MOD? non_global_path MOD_SEP LBRACE RBRACE
5579 /// | MOD? non_global_path MOD_SEP LBRACE ident_seq RBRACE
5580 /// | MOD? non_global_path MOD_SEP STAR
5581 /// | MOD? non_global_path
5582 fn parse_view_path(&mut self) -> PResult<P<ViewPath>> {
5583 let lo = self.span.lo;
5585 // Allow a leading :: because the paths are absolute either way.
5586 // This occurs with "use $crate::..." in macros.
5587 try!(self.eat(&token::ModSep));
5589 if self.check(&token::OpenDelim(token::Brace)) {
5591 let idents = try!(self.parse_unspanned_seq(
5592 &token::OpenDelim(token::Brace),
5593 &token::CloseDelim(token::Brace),
5594 seq_sep_trailing_allowed(token::Comma),
5595 |p| p.parse_path_list_item()));
5596 let path = ast::Path {
5597 span: mk_sp(lo, self.span.hi),
5599 segments: Vec::new()
5601 return Ok(P(spanned(lo, self.span.hi, ViewPathList(path, idents))));
5604 let first_ident = try!(self.parse_ident());
5605 let mut path = vec!(first_ident);
5606 if let token::ModSep = self.token {
5607 // foo::bar or foo::{a,b,c} or foo::*
5608 while self.check(&token::ModSep) {
5612 token::Ident(..) => {
5613 let ident = try!(self.parse_ident());
5617 // foo::bar::{a,b,c}
5618 token::OpenDelim(token::Brace) => {
5619 let idents = try!(self.parse_unspanned_seq(
5620 &token::OpenDelim(token::Brace),
5621 &token::CloseDelim(token::Brace),
5622 seq_sep_trailing_allowed(token::Comma),
5623 |p| p.parse_path_list_item()
5625 let path = ast::Path {
5626 span: mk_sp(lo, self.span.hi),
5628 segments: path.into_iter().map(|identifier| {
5630 identifier: identifier,
5631 parameters: ast::PathParameters::none(),
5635 return Ok(P(spanned(lo, self.span.hi, ViewPathList(path, idents))));
5639 token::BinOp(token::Star) => {
5641 let path = ast::Path {
5642 span: mk_sp(lo, self.span.hi),
5644 segments: path.into_iter().map(|identifier| {
5646 identifier: identifier,
5647 parameters: ast::PathParameters::none(),
5651 return Ok(P(spanned(lo, self.span.hi, ViewPathGlob(path))));
5654 // fall-through for case foo::bar::;
5656 self.span_err(self.span, "expected identifier or `{` or `*`, found `;`");
5663 let mut rename_to = path[path.len() - 1];
5664 let path = ast::Path {
5665 span: mk_sp(lo, self.last_span.hi),
5667 segments: path.into_iter().map(|identifier| {
5669 identifier: identifier,
5670 parameters: ast::PathParameters::none(),
5674 if try!(self.eat_keyword(keywords::As)) {
5675 rename_to = try!(self.parse_ident())
5677 Ok(P(spanned(lo, self.last_span.hi, ViewPathSimple(rename_to, path))))
5680 /// Parses a source module as a crate. This is the main
5681 /// entry point for the parser.
5682 pub fn parse_crate_mod(&mut self) -> PResult<Crate> {
5683 let lo = self.span.lo;
5685 attrs: self.parse_inner_attributes(),
5686 module: try!(self.parse_mod_items(&token::Eof, lo)),
5687 config: self.cfg.clone(),
5688 span: mk_sp(lo, self.span.lo),
5689 exported_macros: Vec::new(),
5693 pub fn parse_optional_str(&mut self)
5694 -> PResult<Option<(InternedString,
5696 Option<ast::Name>)>> {
5697 let ret = match self.token {
5698 token::Literal(token::Str_(s), suf) => {
5699 (self.id_to_interned_str(s.ident()), ast::CookedStr, suf)
5701 token::Literal(token::StrRaw(s, n), suf) => {
5702 (self.id_to_interned_str(s.ident()), ast::RawStr(n), suf)
5704 _ => return Ok(None)
5710 pub fn parse_str(&mut self) -> PResult<(InternedString, StrStyle)> {
5711 match try!(self.parse_optional_str()) {
5712 Some((s, style, suf)) => {
5713 let sp = self.last_span;
5714 self.expect_no_suffix(sp, "str literal", suf);
5717 _ => Err(self.fatal("expected string literal"))