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, Block};
19 use ast::{BlockCheckMode, CaptureByRef, CaptureByValue, CaptureClause};
20 use ast::{Constness, 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, ExprInPlace};
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, 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};
37 use ast::{LitBool, LitChar, LitByte, LitByteStr};
38 use ast::{LitStr, LitInt, Local};
39 use ast::{MacStmtWithBraces, MacStmtWithSemicolon, MacStmtWithoutBraces};
40 use ast::{MutImmutable, MutMutable, Mac_};
41 use ast::{MutTy, BiMul, Mutability};
42 use ast::{NamedField, UnNeg, NoReturn, UnNot};
43 use ast::{Pat, PatBox, PatEnum, PatIdent, PatLit, PatQPath, PatMac, PatRange};
44 use ast::{PatRegion, PatStruct, PatTup, PatVec, PatWild};
45 use ast::{PolyTraitRef, QSelf};
46 use ast::{Return, BiShl, BiShr, Stmt, StmtDecl};
47 use ast::{StmtExpr, StmtSemi, StmtMac, VariantData, StructField};
48 use ast::{BiSub, StrStyle};
49 use ast::{SelfExplicit, SelfRegion, SelfStatic, SelfValue};
50 use ast::{Delimited, SequenceRepetition, TokenTree, TraitItem, TraitRef};
51 use ast::{Ty, Ty_, TypeBinding, TyMac};
52 use ast::{TyFixedLengthVec, TyBareFn, TyTypeof, TyInfer};
53 use ast::{TyParam, TyParamBound, TyParen, TyPath, TyPtr};
54 use ast::{TyRptr, TyTup, TyU32, TyVec};
55 use ast::TypeTraitItem;
56 use ast::{UnnamedField, UnsafeBlock};
57 use ast::{ViewPath, ViewPathGlob, ViewPathList, ViewPathSimple};
58 use ast::{Visibility, WhereClause};
59 use attr::{ThinAttributes, ThinAttributesExt, AttributesExt};
61 use ast_util::{self, ident_to_path};
62 use codemap::{self, Span, BytePos, Spanned, spanned, mk_sp, CodeMap};
64 use ext::tt::macro_parser;
67 use parse::common::{SeqSep, seq_sep_none, seq_sep_trailing_allowed};
68 use parse::lexer::{Reader, TokenAndSpan};
69 use parse::obsolete::{ParserObsoleteMethods, ObsoleteSyntax};
70 use parse::token::{self, MatchNt, SubstNt, SpecialVarNt, InternedString};
71 use parse::token::{keywords, special_idents, SpecialMacroVar};
72 use parse::{new_sub_parser_from_file, ParseSess};
73 use util::parser::{AssocOp, Fixity};
76 use owned_slice::OwnedSlice;
78 use diagnostic::FatalError;
80 use std::collections::HashSet;
81 use std::io::prelude::*;
83 use std::path::{Path, PathBuf};
88 flags Restrictions: u8 {
89 const RESTRICTION_STMT_EXPR = 1 << 0,
90 const RESTRICTION_NO_STRUCT_LITERAL = 1 << 1,
94 type ItemInfo = (Ident, Item_, Option<Vec<Attribute> >);
96 /// How to parse a path. There are four different kinds of paths, all of which
97 /// are parsed somewhat differently.
98 #[derive(Copy, Clone, PartialEq)]
99 pub enum PathParsingMode {
100 /// A path with no type parameters; e.g. `foo::bar::Baz`
102 /// A path with a lifetime and type parameters, with no double colons
103 /// before the type parameters; e.g. `foo::bar<'a>::Baz<T>`
104 LifetimeAndTypesWithoutColons,
105 /// A path with a lifetime and type parameters with double colons before
106 /// the type parameters; e.g. `foo::bar::<'a>::Baz::<T>`
107 LifetimeAndTypesWithColons,
110 /// How to parse a bound, whether to allow bound modifiers such as `?`.
111 #[derive(Copy, Clone, PartialEq)]
112 pub enum BoundParsingMode {
117 /// `pub` should be parsed in struct fields and not parsed in variant fields
118 #[derive(Clone, Copy, PartialEq)]
124 /// Possibly accept an `token::Interpolated` expression (a pre-parsed expression
125 /// dropped into the token stream, which happens while parsing the result of
126 /// macro expansion). Placement of these is not as complex as I feared it would
127 /// be. The important thing is to make sure that lookahead doesn't balk at
128 /// `token::Interpolated` tokens.
129 macro_rules! maybe_whole_expr {
132 let found = match $p.token {
133 token::Interpolated(token::NtExpr(ref e)) => {
136 token::Interpolated(token::NtPath(_)) => {
137 // FIXME: The following avoids an issue with lexical borrowck scopes,
138 // but the clone is unfortunate.
139 let pt = match $p.token {
140 token::Interpolated(token::NtPath(ref pt)) => (**pt).clone(),
144 Some($p.mk_expr(span.lo, span.hi, ExprPath(None, pt), None))
146 token::Interpolated(token::NtBlock(_)) => {
147 // FIXME: The following avoids an issue with lexical borrowck scopes,
148 // but the clone is unfortunate.
149 let b = match $p.token {
150 token::Interpolated(token::NtBlock(ref b)) => (*b).clone(),
154 Some($p.mk_expr(span.lo, span.hi, ExprBlock(b), None))
169 /// As maybe_whole_expr, but for things other than expressions
170 macro_rules! maybe_whole {
171 ($p:expr, $constructor:ident) => (
173 let found = match ($p).token {
174 token::Interpolated(token::$constructor(_)) => {
175 Some(try!(($p).bump_and_get()))
179 if let Some(token::Interpolated(token::$constructor(x))) = found {
180 return Ok(x.clone());
184 (no_clone $p:expr, $constructor:ident) => (
186 let found = match ($p).token {
187 token::Interpolated(token::$constructor(_)) => {
188 Some(try!(($p).bump_and_get()))
192 if let Some(token::Interpolated(token::$constructor(x))) = found {
197 (deref $p:expr, $constructor:ident) => (
199 let found = match ($p).token {
200 token::Interpolated(token::$constructor(_)) => {
201 Some(try!(($p).bump_and_get()))
205 if let Some(token::Interpolated(token::$constructor(x))) = found {
206 return Ok((*x).clone());
210 (Some deref $p:expr, $constructor:ident) => (
212 let found = match ($p).token {
213 token::Interpolated(token::$constructor(_)) => {
214 Some(try!(($p).bump_and_get()))
218 if let Some(token::Interpolated(token::$constructor(x))) = found {
219 return Ok(Some((*x).clone()));
223 (pair_empty $p:expr, $constructor:ident) => (
225 let found = match ($p).token {
226 token::Interpolated(token::$constructor(_)) => {
227 Some(try!(($p).bump_and_get()))
231 if let Some(token::Interpolated(token::$constructor(x))) = found {
232 return Ok((Vec::new(), x));
239 fn maybe_append(mut lhs: Vec<Attribute>, rhs: Option<Vec<Attribute>>)
241 if let Some(ref attrs) = rhs {
242 lhs.extend(attrs.iter().cloned())
247 /* ident is handled by common.rs */
249 pub struct Parser<'a> {
250 pub sess: &'a ParseSess,
251 /// the current token:
252 pub token: token::Token,
253 /// the span of the current token:
255 /// the span of the prior token:
257 pub cfg: CrateConfig,
258 /// the previous token or None (only stashed sometimes).
259 pub last_token: Option<Box<token::Token>>,
260 pub buffer: [TokenAndSpan; 4],
261 pub buffer_start: isize,
262 pub buffer_end: isize,
263 pub tokens_consumed: usize,
264 pub restrictions: Restrictions,
265 pub quote_depth: usize, // not (yet) related to the quasiquoter
266 pub reader: Box<Reader+'a>,
267 pub interner: Rc<token::IdentInterner>,
268 /// The set of seen errors about obsolete syntax. Used to suppress
269 /// extra detail when the same error is seen twice
270 pub obsolete_set: HashSet<ObsoleteSyntax>,
271 /// Used to determine the path to externally loaded source files
272 pub mod_path_stack: Vec<InternedString>,
273 /// Stack of spans of open delimiters. Used for error message.
274 pub open_braces: Vec<Span>,
275 /// Flag if this parser "owns" the directory that it is currently parsing
276 /// in. This will affect how nested files are looked up.
277 pub owns_directory: bool,
278 /// Name of the root module this parser originated from. If `None`, then the
279 /// name is not known. This does not change while the parser is descending
280 /// into modules, and sub-parsers have new values for this name.
281 pub root_module_name: Option<String>,
282 pub expected_tokens: Vec<TokenType>,
285 #[derive(PartialEq, Eq, Clone)]
288 Keyword(keywords::Keyword),
293 fn to_string(&self) -> String {
295 TokenType::Token(ref t) => format!("`{}`", Parser::token_to_string(t)),
296 TokenType::Operator => "an operator".to_string(),
297 TokenType::Keyword(kw) => format!("`{}`", kw.to_name()),
302 fn is_plain_ident_or_underscore(t: &token::Token) -> bool {
303 t.is_plain_ident() || *t == token::Underscore
306 /// Information about the path to a module.
307 pub struct ModulePath {
309 pub path_exists: bool,
310 pub result: Result<ModulePathSuccess, ModulePathError>,
313 pub struct ModulePathSuccess {
314 pub path: ::std::path::PathBuf,
315 pub owns_directory: bool,
318 pub struct ModulePathError {
320 pub help_msg: String,
325 AttributesParsed(ThinAttributes),
326 AlreadyParsed(P<Expr>),
329 impl From<Option<ThinAttributes>> for LhsExpr {
330 fn from(o: Option<ThinAttributes>) -> Self {
331 if let Some(attrs) = o {
332 LhsExpr::AttributesParsed(attrs)
334 LhsExpr::NotYetParsed
339 impl From<P<Expr>> for LhsExpr {
340 fn from(expr: P<Expr>) -> Self {
341 LhsExpr::AlreadyParsed(expr)
345 impl<'a> Parser<'a> {
346 pub fn new(sess: &'a ParseSess,
347 cfg: ast::CrateConfig,
348 mut rdr: Box<Reader+'a>)
351 let tok0 = rdr.real_token();
353 let placeholder = TokenAndSpan {
354 tok: token::Underscore,
360 interner: token::get_ident_interner(),
376 restrictions: Restrictions::empty(),
378 obsolete_set: HashSet::new(),
379 mod_path_stack: Vec::new(),
380 open_braces: Vec::new(),
381 owns_directory: true,
382 root_module_name: None,
383 expected_tokens: Vec::new(),
387 /// Convert a token to a string using self's reader
388 pub fn token_to_string(token: &token::Token) -> String {
389 pprust::token_to_string(token)
392 /// Convert the current token to a string using self's reader
393 pub fn this_token_to_string(&self) -> String {
394 Parser::token_to_string(&self.token)
397 pub fn unexpected_last(&self, t: &token::Token) -> FatalError {
398 let token_str = Parser::token_to_string(t);
399 let last_span = self.last_span;
400 self.span_fatal(last_span, &format!("unexpected token: `{}`",
404 pub fn unexpected(&mut self) -> FatalError {
405 match self.expect_one_of(&[], &[]) {
407 Ok(_) => unreachable!()
411 /// Expect and consume the token t. Signal an error if
412 /// the next token is not t.
413 pub fn expect(&mut self, t: &token::Token) -> PResult<()> {
414 if self.expected_tokens.is_empty() {
415 if self.token == *t {
418 let token_str = Parser::token_to_string(t);
419 let this_token_str = self.this_token_to_string();
420 Err(self.fatal(&format!("expected `{}`, found `{}`",
425 self.expect_one_of(unsafe { slice::from_raw_parts(t, 1) }, &[])
429 /// Expect next token to be edible or inedible token. If edible,
430 /// then consume it; if inedible, then return without consuming
431 /// anything. Signal a fatal error if next token is unexpected.
432 pub fn expect_one_of(&mut self,
433 edible: &[token::Token],
434 inedible: &[token::Token]) -> PResult<()>{
435 fn tokens_to_string(tokens: &[TokenType]) -> String {
436 let mut i = tokens.iter();
437 // This might be a sign we need a connect method on Iterator.
439 .map_or("".to_string(), |t| t.to_string());
440 i.enumerate().fold(b, |mut b, (i, ref a)| {
441 if tokens.len() > 2 && i == tokens.len() - 2 {
443 } else if tokens.len() == 2 && i == tokens.len() - 2 {
448 b.push_str(&*a.to_string());
452 if edible.contains(&self.token) {
454 } else if inedible.contains(&self.token) {
455 // leave it in the input
458 let mut expected = edible.iter()
459 .map(|x| TokenType::Token(x.clone()))
460 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
461 .chain(self.expected_tokens.iter().cloned())
462 .collect::<Vec<_>>();
463 expected.sort_by(|a, b| a.to_string().cmp(&b.to_string()));
465 let expect = tokens_to_string(&expected[..]);
466 let actual = self.this_token_to_string();
468 &(if expected.len() > 1 {
469 (format!("expected one of {}, found `{}`",
472 } else if expected.is_empty() {
473 (format!("unexpected token: `{}`",
476 (format!("expected {}, found `{}`",
484 /// Check for erroneous `ident { }`; if matches, signal error and
485 /// recover (without consuming any expected input token). Returns
486 /// true if and only if input was consumed for recovery.
487 pub fn check_for_erroneous_unit_struct_expecting(&mut self,
488 expected: &[token::Token])
490 if self.token == token::OpenDelim(token::Brace)
491 && expected.iter().all(|t| *t != token::OpenDelim(token::Brace))
492 && self.look_ahead(1, |t| *t == token::CloseDelim(token::Brace)) {
493 // matched; signal non-fatal error and recover.
494 let span = self.span;
496 "unit-like struct construction is written with no trailing `{ }`");
497 try!(self.eat(&token::OpenDelim(token::Brace)));
498 try!(self.eat(&token::CloseDelim(token::Brace)));
505 /// Commit to parsing a complete expression `e` expected to be
506 /// followed by some token from the set edible + inedible. Recover
507 /// from anticipated input errors, discarding erroneous characters.
508 pub fn commit_expr(&mut self, e: &Expr, edible: &[token::Token],
509 inedible: &[token::Token]) -> PResult<()> {
510 debug!("commit_expr {:?}", e);
511 if let ExprPath(..) = e.node {
512 // might be unit-struct construction; check for recoverableinput error.
513 let expected = edible.iter()
515 .chain(inedible.iter().cloned())
516 .collect::<Vec<_>>();
517 try!(self.check_for_erroneous_unit_struct_expecting(&expected[..]));
519 self.expect_one_of(edible, inedible)
522 pub fn commit_expr_expecting(&mut self, e: &Expr, edible: token::Token) -> PResult<()> {
523 self.commit_expr(e, &[edible], &[])
526 /// Commit to parsing a complete statement `s`, which expects to be
527 /// followed by some token from the set edible + inedible. Check
528 /// for recoverable input errors, discarding erroneous characters.
529 pub fn commit_stmt(&mut self, edible: &[token::Token],
530 inedible: &[token::Token]) -> PResult<()> {
533 .map_or(false, |t| t.is_ident() || t.is_path()) {
534 let expected = edible.iter()
536 .chain(inedible.iter().cloned())
537 .collect::<Vec<_>>();
538 try!(self.check_for_erroneous_unit_struct_expecting(&expected));
540 self.expect_one_of(edible, inedible)
543 pub fn commit_stmt_expecting(&mut self, edible: token::Token) -> PResult<()> {
544 self.commit_stmt(&[edible], &[])
547 pub fn parse_ident(&mut self) -> PResult<ast::Ident> {
548 self.check_strict_keywords();
549 try!(self.check_reserved_keywords());
551 token::Ident(i, _) => {
555 token::Interpolated(token::NtIdent(..)) => {
556 self.bug("ident interpolation not converted to real token");
559 let token_str = self.this_token_to_string();
560 Err(self.fatal(&format!("expected ident, found `{}`",
566 pub fn parse_ident_or_self_type(&mut self) -> PResult<ast::Ident> {
567 if self.is_self_type_ident() {
568 self.expect_self_type_ident()
574 pub fn parse_path_list_item(&mut self) -> PResult<ast::PathListItem> {
575 let lo = self.span.lo;
576 let node = if try!(self.eat_keyword(keywords::SelfValue)) {
577 let rename = try!(self.parse_rename());
578 ast::PathListMod { id: ast::DUMMY_NODE_ID, rename: rename }
580 let ident = try!(self.parse_ident());
581 let rename = try!(self.parse_rename());
582 ast::PathListIdent { name: ident, rename: rename, id: ast::DUMMY_NODE_ID }
584 let hi = self.last_span.hi;
585 Ok(spanned(lo, hi, node))
588 /// Check if the next token is `tok`, and return `true` if so.
590 /// This method is will automatically add `tok` to `expected_tokens` if `tok` is not
592 pub fn check(&mut self, tok: &token::Token) -> bool {
593 let is_present = self.token == *tok;
594 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
598 /// Consume token 'tok' if it exists. Returns true if the given
599 /// token was present, false otherwise.
600 pub fn eat(&mut self, tok: &token::Token) -> PResult<bool> {
601 let is_present = self.check(tok);
602 if is_present { try!(self.bump())}
606 pub fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
607 self.expected_tokens.push(TokenType::Keyword(kw));
608 self.token.is_keyword(kw)
611 /// If the next token is the given keyword, eat it and return
612 /// true. Otherwise, return false.
613 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> PResult<bool> {
614 if self.check_keyword(kw) {
622 pub fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> PResult<bool> {
623 if self.token.is_keyword(kw) {
631 /// If the given word is not a keyword, signal an error.
632 /// If the next token is not the given word, signal an error.
633 /// Otherwise, eat it.
634 pub fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<()> {
635 if !try!(self.eat_keyword(kw) ){
636 self.expect_one_of(&[], &[])
642 /// Signal an error if the given string is a strict keyword
643 pub fn check_strict_keywords(&mut self) {
644 if self.token.is_strict_keyword() {
645 let token_str = self.this_token_to_string();
646 let span = self.span;
648 &format!("expected identifier, found keyword `{}`",
653 /// Signal an error if the current token is a reserved keyword
654 pub fn check_reserved_keywords(&mut self) -> PResult<()>{
655 if self.token.is_reserved_keyword() {
656 let token_str = self.this_token_to_string();
657 Err(self.fatal(&format!("`{}` is a reserved keyword",
664 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
665 /// `&` and continue. If an `&` is not seen, signal an error.
666 fn expect_and(&mut self) -> PResult<()> {
667 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
669 token::BinOp(token::And) => self.bump(),
671 let span = self.span;
672 let lo = span.lo + BytePos(1);
673 Ok(self.replace_token(token::BinOp(token::And), lo, span.hi))
675 _ => self.expect_one_of(&[], &[])
679 pub fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
681 None => {/* everything ok */}
683 let text = suf.as_str();
685 self.span_bug(sp, "found empty literal suffix in Some")
687 self.span_err(sp, &*format!("{} with a suffix is invalid", kind));
693 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
694 /// `<` and continue. If a `<` is not seen, return false.
696 /// This is meant to be used when parsing generics on a path to get the
698 fn eat_lt(&mut self) -> PResult<bool> {
699 self.expected_tokens.push(TokenType::Token(token::Lt));
701 token::Lt => { try!(self.bump()); Ok(true)}
702 token::BinOp(token::Shl) => {
703 let span = self.span;
704 let lo = span.lo + BytePos(1);
705 self.replace_token(token::Lt, lo, span.hi);
712 fn expect_lt(&mut self) -> PResult<()> {
713 if !try!(self.eat_lt()) {
714 self.expect_one_of(&[], &[])
720 /// Expect and consume a GT. if a >> is seen, replace it
721 /// with a single > and continue. If a GT is not seen,
723 pub fn expect_gt(&mut self) -> PResult<()> {
724 self.expected_tokens.push(TokenType::Token(token::Gt));
726 token::Gt => self.bump(),
727 token::BinOp(token::Shr) => {
728 let span = self.span;
729 let lo = span.lo + BytePos(1);
730 Ok(self.replace_token(token::Gt, lo, span.hi))
732 token::BinOpEq(token::Shr) => {
733 let span = self.span;
734 let lo = span.lo + BytePos(1);
735 Ok(self.replace_token(token::Ge, lo, span.hi))
738 let span = self.span;
739 let lo = span.lo + BytePos(1);
740 Ok(self.replace_token(token::Eq, lo, span.hi))
743 let gt_str = Parser::token_to_string(&token::Gt);
744 let this_token_str = self.this_token_to_string();
745 Err(self.fatal(&format!("expected `{}`, found `{}`",
752 pub fn parse_seq_to_before_gt_or_return<T, F>(&mut self,
753 sep: Option<token::Token>,
755 -> PResult<(OwnedSlice<T>, bool)> where
756 F: FnMut(&mut Parser) -> PResult<Option<T>>,
758 let mut v = Vec::new();
759 // This loop works by alternating back and forth between parsing types
760 // and commas. For example, given a string `A, B,>`, the parser would
761 // first parse `A`, then a comma, then `B`, then a comma. After that it
762 // would encounter a `>` and stop. This lets the parser handle trailing
763 // commas in generic parameters, because it can stop either after
764 // parsing a type or after parsing a comma.
766 if self.check(&token::Gt)
767 || self.token == token::BinOp(token::Shr)
768 || self.token == token::Ge
769 || self.token == token::BinOpEq(token::Shr) {
774 match try!(f(self)) {
775 Some(result) => v.push(result),
776 None => return Ok((OwnedSlice::from_vec(v), true))
779 if let Some(t) = sep.as_ref() {
780 try!(self.expect(t));
785 return Ok((OwnedSlice::from_vec(v), false));
788 /// Parse a sequence bracketed by '<' and '>', stopping
790 pub fn parse_seq_to_before_gt<T, F>(&mut self,
791 sep: Option<token::Token>,
793 -> PResult<OwnedSlice<T>> where
794 F: FnMut(&mut Parser) -> PResult<T>,
796 let (result, returned) = try!(self.parse_seq_to_before_gt_or_return(sep,
797 |p| Ok(Some(try!(f(p))))));
802 pub fn parse_seq_to_gt<T, F>(&mut self,
803 sep: Option<token::Token>,
805 -> PResult<OwnedSlice<T>> where
806 F: FnMut(&mut Parser) -> PResult<T>,
808 let v = try!(self.parse_seq_to_before_gt(sep, f));
809 try!(self.expect_gt());
813 pub fn parse_seq_to_gt_or_return<T, F>(&mut self,
814 sep: Option<token::Token>,
816 -> PResult<(OwnedSlice<T>, bool)> where
817 F: FnMut(&mut Parser) -> PResult<Option<T>>,
819 let (v, returned) = try!(self.parse_seq_to_before_gt_or_return(sep, f));
821 try!(self.expect_gt());
823 return Ok((v, returned));
826 /// Parse a sequence, including the closing delimiter. The function
827 /// f must consume tokens until reaching the next separator or
829 pub fn parse_seq_to_end<T, F>(&mut self,
833 -> PResult<Vec<T>> where
834 F: FnMut(&mut Parser) -> PResult<T>,
836 let val = try!(self.parse_seq_to_before_end(ket, sep, f));
841 /// Parse a sequence, not including the closing delimiter. The function
842 /// f must consume tokens until reaching the next separator or
844 pub fn parse_seq_to_before_end<T, F>(&mut self,
848 -> PResult<Vec<T>> where
849 F: FnMut(&mut Parser) -> PResult<T>,
851 let mut first: bool = true;
853 while self.token != *ket {
856 if first { first = false; }
857 else { try!(self.expect(t)); }
861 if sep.trailing_sep_allowed && self.check(ket) { break; }
862 v.push(try!(f(self)));
867 /// Parse a sequence, including the closing delimiter. The function
868 /// f must consume tokens until reaching the next separator or
870 pub fn parse_unspanned_seq<T, F>(&mut self,
875 -> PResult<Vec<T>> where
876 F: FnMut(&mut Parser) -> PResult<T>,
878 try!(self.expect(bra));
879 let result = try!(self.parse_seq_to_before_end(ket, sep, f));
884 /// Parse a sequence parameter of enum variant. For consistency purposes,
885 /// these should not be empty.
886 pub fn parse_enum_variant_seq<T, F>(&mut self,
891 -> PResult<Vec<T>> where
892 F: FnMut(&mut Parser) -> PResult<T>,
894 let result = try!(self.parse_unspanned_seq(bra, ket, sep, f));
895 if result.is_empty() {
896 let last_span = self.last_span;
897 self.span_err(last_span,
898 "nullary enum variants are written with no trailing `( )`");
903 // NB: Do not use this function unless you actually plan to place the
904 // spanned list in the AST.
905 pub fn parse_seq<T, F>(&mut self,
910 -> PResult<Spanned<Vec<T>>> where
911 F: FnMut(&mut Parser) -> PResult<T>,
913 let lo = self.span.lo;
914 try!(self.expect(bra));
915 let result = try!(self.parse_seq_to_before_end(ket, sep, f));
916 let hi = self.span.hi;
918 Ok(spanned(lo, hi, result))
921 /// Advance the parser by one token
922 pub fn bump(&mut self) -> PResult<()> {
923 self.last_span = self.span;
924 // Stash token for error recovery (sometimes; clone is not necessarily cheap).
925 self.last_token = if self.token.is_ident() ||
926 self.token.is_path() ||
927 self.token == token::Comma {
928 Some(Box::new(self.token.clone()))
932 let next = if self.buffer_start == self.buffer_end {
933 self.reader.real_token()
935 // Avoid token copies with `replace`.
936 let buffer_start = self.buffer_start as usize;
937 let next_index = (buffer_start + 1) & 3;
938 self.buffer_start = next_index as isize;
940 let placeholder = TokenAndSpan {
941 tok: token::Underscore,
944 mem::replace(&mut self.buffer[buffer_start], placeholder)
947 self.token = next.tok;
948 self.tokens_consumed += 1;
949 self.expected_tokens.clear();
950 // check after each token
951 self.check_unknown_macro_variable()
954 /// Advance the parser by one token and return the bumped token.
955 pub fn bump_and_get(&mut self) -> PResult<token::Token> {
956 let old_token = mem::replace(&mut self.token, token::Underscore);
961 /// EFFECT: replace the current token and span with the given one
962 pub fn replace_token(&mut self,
966 self.last_span = mk_sp(self.span.lo, lo);
968 self.span = mk_sp(lo, hi);
970 pub fn buffer_length(&mut self) -> isize {
971 if self.buffer_start <= self.buffer_end {
972 return self.buffer_end - self.buffer_start;
974 return (4 - self.buffer_start) + self.buffer_end;
976 pub fn look_ahead<R, F>(&mut self, distance: usize, f: F) -> R where
977 F: FnOnce(&token::Token) -> R,
979 let dist = distance as isize;
980 while self.buffer_length() < dist {
981 self.buffer[self.buffer_end as usize] = self.reader.real_token();
982 self.buffer_end = (self.buffer_end + 1) & 3;
984 f(&self.buffer[((self.buffer_start + dist - 1) & 3) as usize].tok)
986 pub fn fatal(&self, m: &str) -> diagnostic::FatalError {
987 self.sess.span_diagnostic.span_fatal(self.span, m)
989 pub fn span_fatal(&self, sp: Span, m: &str) -> diagnostic::FatalError {
990 self.sess.span_diagnostic.span_fatal(sp, m)
992 pub fn span_fatal_help(&self, sp: Span, m: &str, help: &str) -> diagnostic::FatalError {
993 self.span_err(sp, m);
994 self.fileline_help(sp, help);
995 diagnostic::FatalError
997 pub fn span_note(&self, sp: Span, m: &str) {
998 self.sess.span_diagnostic.span_note(sp, m)
1000 pub fn span_help(&self, sp: Span, m: &str) {
1001 self.sess.span_diagnostic.span_help(sp, m)
1003 pub fn span_suggestion(&self, sp: Span, m: &str, n: String) {
1004 self.sess.span_diagnostic.span_suggestion(sp, m, n)
1006 pub fn fileline_help(&self, sp: Span, m: &str) {
1007 self.sess.span_diagnostic.fileline_help(sp, m)
1009 pub fn bug(&self, m: &str) -> ! {
1010 self.sess.span_diagnostic.span_bug(self.span, m)
1012 pub fn warn(&self, m: &str) {
1013 self.sess.span_diagnostic.span_warn(self.span, m)
1015 pub fn span_warn(&self, sp: Span, m: &str) {
1016 self.sess.span_diagnostic.span_warn(sp, m)
1018 pub fn span_err(&self, sp: Span, m: &str) {
1019 self.sess.span_diagnostic.span_err(sp, m)
1021 pub fn span_bug(&self, sp: Span, m: &str) -> ! {
1022 self.sess.span_diagnostic.span_bug(sp, m)
1024 pub fn abort_if_errors(&self) {
1025 self.sess.span_diagnostic.handler().abort_if_errors();
1028 pub fn id_to_interned_str(&mut self, id: Ident) -> InternedString {
1032 /// Is the current token one of the keywords that signals a bare function
1034 pub fn token_is_bare_fn_keyword(&mut self) -> bool {
1035 self.check_keyword(keywords::Fn) ||
1036 self.check_keyword(keywords::Unsafe) ||
1037 self.check_keyword(keywords::Extern)
1040 pub fn get_lifetime(&mut self) -> ast::Ident {
1042 token::Lifetime(ref ident) => *ident,
1043 _ => self.bug("not a lifetime"),
1047 pub fn parse_for_in_type(&mut self) -> PResult<Ty_> {
1049 Parses whatever can come after a `for` keyword in a type.
1050 The `for` has already been consumed.
1054 - for <'lt> |S| -> T
1058 - for <'lt> [unsafe] [extern "ABI"] fn (S) -> T
1059 - for <'lt> path::foo(a, b)
1064 let lo = self.span.lo;
1066 let lifetime_defs = try!(self.parse_late_bound_lifetime_defs());
1068 // examine next token to decide to do
1069 if self.token_is_bare_fn_keyword() {
1070 self.parse_ty_bare_fn(lifetime_defs)
1072 let hi = self.span.hi;
1073 let trait_ref = try!(self.parse_trait_ref());
1074 let poly_trait_ref = ast::PolyTraitRef { bound_lifetimes: lifetime_defs,
1075 trait_ref: trait_ref,
1076 span: mk_sp(lo, hi)};
1077 let other_bounds = if try!(self.eat(&token::BinOp(token::Plus)) ){
1078 try!(self.parse_ty_param_bounds(BoundParsingMode::Bare))
1083 Some(TraitTyParamBound(poly_trait_ref, TraitBoundModifier::None)).into_iter()
1084 .chain(other_bounds.into_vec())
1086 Ok(ast::TyPolyTraitRef(all_bounds))
1090 pub fn parse_ty_path(&mut self) -> PResult<Ty_> {
1091 Ok(TyPath(None, try!(self.parse_path(LifetimeAndTypesWithoutColons))))
1094 /// parse a TyBareFn type:
1095 pub fn parse_ty_bare_fn(&mut self, lifetime_defs: Vec<ast::LifetimeDef>) -> PResult<Ty_> {
1098 [unsafe] [extern "ABI"] fn <'lt> (S) -> T
1099 ^~~~^ ^~~~^ ^~~~^ ^~^ ^
1102 | | | Argument types
1108 let unsafety = try!(self.parse_unsafety());
1109 let abi = if try!(self.eat_keyword(keywords::Extern) ){
1110 try!(self.parse_opt_abi()).unwrap_or(abi::C)
1115 try!(self.expect_keyword(keywords::Fn));
1116 let (inputs, variadic) = try!(self.parse_fn_args(false, true));
1117 let ret_ty = try!(self.parse_ret_ty());
1118 let decl = P(FnDecl {
1123 Ok(TyBareFn(P(BareFnTy {
1126 lifetimes: lifetime_defs,
1131 /// Parses an obsolete closure kind (`&:`, `&mut:`, or `:`).
1132 pub fn parse_obsolete_closure_kind(&mut self) -> PResult<()> {
1133 let lo = self.span.lo;
1135 self.check(&token::BinOp(token::And)) &&
1136 self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
1137 self.look_ahead(2, |t| *t == token::Colon)
1143 self.token == token::BinOp(token::And) &&
1144 self.look_ahead(1, |t| *t == token::Colon)
1149 try!(self.eat(&token::Colon))
1156 let span = mk_sp(lo, self.span.hi);
1157 self.obsolete(span, ObsoleteSyntax::ClosureKind);
1161 pub fn parse_unsafety(&mut self) -> PResult<Unsafety> {
1162 if try!(self.eat_keyword(keywords::Unsafe)) {
1163 return Ok(Unsafety::Unsafe);
1165 return Ok(Unsafety::Normal);
1169 /// Parse the items in a trait declaration
1170 pub fn parse_trait_items(&mut self) -> PResult<Vec<P<TraitItem>>> {
1171 self.parse_unspanned_seq(
1172 &token::OpenDelim(token::Brace),
1173 &token::CloseDelim(token::Brace),
1175 |p| -> PResult<P<TraitItem>> {
1176 maybe_whole!(no_clone p, NtTraitItem);
1177 let mut attrs = try!(p.parse_outer_attributes());
1180 let (name, node) = if try!(p.eat_keyword(keywords::Type)) {
1181 let TyParam {ident, bounds, default, ..} = try!(p.parse_ty_param());
1182 try!(p.expect(&token::Semi));
1183 (ident, TypeTraitItem(bounds, default))
1184 } else if p.is_const_item() {
1185 try!(p.expect_keyword(keywords::Const));
1186 let ident = try!(p.parse_ident());
1187 try!(p.expect(&token::Colon));
1188 let ty = try!(p.parse_ty_sum());
1189 let default = if p.check(&token::Eq) {
1191 let expr = try!(p.parse_expr());
1192 try!(p.commit_expr_expecting(&expr, token::Semi));
1195 try!(p.expect(&token::Semi));
1198 (ident, ConstTraitItem(ty, default))
1200 let (constness, unsafety, abi) = try!(p.parse_fn_front_matter());
1202 let ident = try!(p.parse_ident());
1203 let mut generics = try!(p.parse_generics());
1205 let (explicit_self, d) = try!(p.parse_fn_decl_with_self(|p|{
1206 // This is somewhat dubious; We don't want to allow
1207 // argument names to be left off if there is a
1209 p.parse_arg_general(false)
1212 generics.where_clause = try!(p.parse_where_clause());
1213 let sig = ast::MethodSig {
1215 constness: constness,
1219 explicit_self: explicit_self,
1222 let body = match p.token {
1225 debug!("parse_trait_methods(): parsing required method");
1228 token::OpenDelim(token::Brace) => {
1229 debug!("parse_trait_methods(): parsing provided method");
1230 let (inner_attrs, body) =
1231 try!(p.parse_inner_attrs_and_block());
1232 attrs.extend(inner_attrs.iter().cloned());
1237 let token_str = p.this_token_to_string();
1238 return Err(p.fatal(&format!("expected `;` or `{{`, found `{}`",
1242 (ident, ast::MethodTraitItem(sig, body))
1246 id: ast::DUMMY_NODE_ID,
1250 span: mk_sp(lo, p.last_span.hi),
1255 /// Parse a possibly mutable type
1256 pub fn parse_mt(&mut self) -> PResult<MutTy> {
1257 let mutbl = try!(self.parse_mutability());
1258 let t = try!(self.parse_ty());
1259 Ok(MutTy { ty: t, mutbl: mutbl })
1262 /// Parse optional return type [ -> TY ] in function decl
1263 pub fn parse_ret_ty(&mut self) -> PResult<FunctionRetTy> {
1264 if try!(self.eat(&token::RArrow) ){
1265 if try!(self.eat(&token::Not) ){
1266 Ok(NoReturn(self.last_span))
1268 Ok(Return(try!(self.parse_ty())))
1271 let pos = self.span.lo;
1272 Ok(DefaultReturn(mk_sp(pos, pos)))
1276 /// Parse a type in a context where `T1+T2` is allowed.
1277 pub fn parse_ty_sum(&mut self) -> PResult<P<Ty>> {
1278 let lo = self.span.lo;
1279 let lhs = try!(self.parse_ty());
1281 if !try!(self.eat(&token::BinOp(token::Plus)) ){
1285 let bounds = try!(self.parse_ty_param_bounds(BoundParsingMode::Bare));
1287 // In type grammar, `+` is treated like a binary operator,
1288 // and hence both L and R side are required.
1289 if bounds.is_empty() {
1290 let last_span = self.last_span;
1291 self.span_err(last_span,
1292 "at least one type parameter bound \
1293 must be specified");
1296 let sp = mk_sp(lo, self.last_span.hi);
1297 let sum = ast::TyObjectSum(lhs, bounds);
1298 Ok(P(Ty {id: ast::DUMMY_NODE_ID, node: sum, span: sp}))
1302 pub fn parse_ty(&mut self) -> PResult<P<Ty>> {
1303 maybe_whole!(no_clone self, NtTy);
1305 let lo = self.span.lo;
1307 let t = if self.check(&token::OpenDelim(token::Paren)) {
1310 // (t) is a parenthesized ty
1311 // (t,) is the type of a tuple with only one field,
1313 let mut ts = vec![];
1314 let mut last_comma = false;
1315 while self.token != token::CloseDelim(token::Paren) {
1316 ts.push(try!(self.parse_ty_sum()));
1317 if self.check(&token::Comma) {
1326 try!(self.expect(&token::CloseDelim(token::Paren)));
1327 if ts.len() == 1 && !last_comma {
1328 TyParen(ts.into_iter().nth(0).unwrap())
1332 } else if self.check(&token::BinOp(token::Star)) {
1333 // STAR POINTER (bare pointer?)
1335 TyPtr(try!(self.parse_ptr()))
1336 } else if self.check(&token::OpenDelim(token::Bracket)) {
1338 try!(self.expect(&token::OpenDelim(token::Bracket)));
1339 let t = try!(self.parse_ty_sum());
1341 // Parse the `; e` in `[ i32; e ]`
1342 // where `e` is a const expression
1343 let t = match try!(self.maybe_parse_fixed_length_of_vec()) {
1345 Some(suffix) => TyFixedLengthVec(t, suffix)
1347 try!(self.expect(&token::CloseDelim(token::Bracket)));
1349 } else if self.check(&token::BinOp(token::And)) ||
1350 self.token == token::AndAnd {
1352 try!(self.expect_and());
1353 try!(self.parse_borrowed_pointee())
1354 } else if self.check_keyword(keywords::For) {
1355 try!(self.parse_for_in_type())
1356 } else if self.token_is_bare_fn_keyword() {
1358 try!(self.parse_ty_bare_fn(Vec::new()))
1359 } else if try!(self.eat_keyword_noexpect(keywords::Typeof)) {
1361 // In order to not be ambiguous, the type must be surrounded by parens.
1362 try!(self.expect(&token::OpenDelim(token::Paren)));
1363 let e = try!(self.parse_expr());
1364 try!(self.expect(&token::CloseDelim(token::Paren)));
1366 } else if try!(self.eat_lt()) {
1369 try!(self.parse_qualified_path(NoTypesAllowed));
1371 TyPath(Some(qself), path)
1372 } else if self.check(&token::ModSep) ||
1373 self.token.is_ident() ||
1374 self.token.is_path() {
1375 let path = try!(self.parse_path(LifetimeAndTypesWithoutColons));
1376 if self.check(&token::Not) {
1379 let delim = try!(self.expect_open_delim());
1380 let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
1382 |p| p.parse_token_tree()));
1383 let hi = self.span.hi;
1384 TyMac(spanned(lo, hi, Mac_ { path: path, tts: tts, ctxt: EMPTY_CTXT }))
1389 } else if try!(self.eat(&token::Underscore) ){
1390 // TYPE TO BE INFERRED
1393 let this_token_str = self.this_token_to_string();
1394 let msg = format!("expected type, found `{}`", this_token_str);
1395 return Err(self.fatal(&msg[..]));
1398 let sp = mk_sp(lo, self.last_span.hi);
1399 Ok(P(Ty {id: ast::DUMMY_NODE_ID, node: t, span: sp}))
1402 pub fn parse_borrowed_pointee(&mut self) -> PResult<Ty_> {
1403 // look for `&'lt` or `&'foo ` and interpret `foo` as the region name:
1404 let opt_lifetime = try!(self.parse_opt_lifetime());
1406 let mt = try!(self.parse_mt());
1407 return Ok(TyRptr(opt_lifetime, mt));
1410 pub fn parse_ptr(&mut self) -> PResult<MutTy> {
1411 let mutbl = if try!(self.eat_keyword(keywords::Mut) ){
1413 } else if try!(self.eat_keyword(keywords::Const) ){
1416 let span = self.last_span;
1418 "bare raw pointers are no longer allowed, you should \
1419 likely use `*mut T`, but otherwise `*T` is now \
1420 known as `*const T`");
1423 let t = try!(self.parse_ty());
1424 Ok(MutTy { ty: t, mutbl: mutbl })
1427 pub fn is_named_argument(&mut self) -> bool {
1428 let offset = match self.token {
1429 token::BinOp(token::And) => 1,
1431 _ if self.token.is_keyword(keywords::Mut) => 1,
1435 debug!("parser is_named_argument offset:{}", offset);
1438 is_plain_ident_or_underscore(&self.token)
1439 && self.look_ahead(1, |t| *t == token::Colon)
1441 self.look_ahead(offset, |t| is_plain_ident_or_underscore(t))
1442 && self.look_ahead(offset + 1, |t| *t == token::Colon)
1446 /// This version of parse arg doesn't necessarily require
1447 /// identifier names.
1448 pub fn parse_arg_general(&mut self, require_name: bool) -> PResult<Arg> {
1449 maybe_whole!(no_clone self, NtArg);
1451 let pat = if require_name || self.is_named_argument() {
1452 debug!("parse_arg_general parse_pat (require_name:{})",
1454 let pat = try!(self.parse_pat());
1456 try!(self.expect(&token::Colon));
1459 debug!("parse_arg_general ident_to_pat");
1460 ast_util::ident_to_pat(ast::DUMMY_NODE_ID,
1462 special_idents::invalid)
1465 let t = try!(self.parse_ty_sum());
1470 id: ast::DUMMY_NODE_ID,
1474 /// Parse a single function argument
1475 pub fn parse_arg(&mut self) -> PResult<Arg> {
1476 self.parse_arg_general(true)
1479 /// Parse an argument in a lambda header e.g. |arg, arg|
1480 pub fn parse_fn_block_arg(&mut self) -> PResult<Arg> {
1481 let pat = try!(self.parse_pat());
1482 let t = if try!(self.eat(&token::Colon) ){
1483 try!(self.parse_ty_sum())
1486 id: ast::DUMMY_NODE_ID,
1488 span: mk_sp(self.span.lo, self.span.hi),
1494 id: ast::DUMMY_NODE_ID
1498 pub fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<Option<P<ast::Expr>>> {
1499 if self.check(&token::Semi) {
1501 Ok(Some(try!(self.parse_expr())))
1507 /// Matches token_lit = LIT_INTEGER | ...
1508 pub fn lit_from_token(&self, tok: &token::Token) -> PResult<Lit_> {
1510 token::Interpolated(token::NtExpr(ref v)) => {
1512 ExprLit(ref lit) => { Ok(lit.node.clone()) }
1513 _ => { return Err(self.unexpected_last(tok)); }
1516 token::Literal(lit, suf) => {
1517 let (suffix_illegal, out) = match lit {
1518 token::Byte(i) => (true, LitByte(parse::byte_lit(&i.as_str()).0)),
1519 token::Char(i) => (true, LitChar(parse::char_lit(&i.as_str()).0)),
1521 // there are some valid suffixes for integer and
1522 // float literals, so all the handling is done
1524 token::Integer(s) => {
1525 (false, parse::integer_lit(&s.as_str(),
1526 suf.as_ref().map(|s| s.as_str()),
1527 &self.sess.span_diagnostic,
1530 token::Float(s) => {
1531 (false, parse::float_lit(&s.as_str(),
1532 suf.as_ref().map(|s| s.as_str()),
1533 &self.sess.span_diagnostic,
1539 LitStr(token::intern_and_get_ident(&parse::str_lit(&s.as_str())),
1542 token::StrRaw(s, n) => {
1545 token::intern_and_get_ident(&parse::raw_str_lit(&s.as_str())),
1548 token::ByteStr(i) =>
1549 (true, LitByteStr(parse::byte_str_lit(&i.as_str()))),
1550 token::ByteStrRaw(i, _) =>
1552 LitByteStr(Rc::new(i.to_string().into_bytes()))),
1556 let sp = self.last_span;
1557 self.expect_no_suffix(sp, &*format!("{} literal", lit.short_name()), suf)
1562 _ => { return Err(self.unexpected_last(tok)); }
1566 /// Matches lit = true | false | token_lit
1567 pub fn parse_lit(&mut self) -> PResult<Lit> {
1568 let lo = self.span.lo;
1569 let lit = if try!(self.eat_keyword(keywords::True) ){
1571 } else if try!(self.eat_keyword(keywords::False) ){
1574 let token = try!(self.bump_and_get());
1575 let lit = try!(self.lit_from_token(&token));
1578 Ok(codemap::Spanned { node: lit, span: mk_sp(lo, self.last_span.hi) })
1581 /// matches '-' lit | lit
1582 pub fn parse_pat_literal_maybe_minus(&mut self) -> PResult<P<Expr>> {
1583 let minus_lo = self.span.lo;
1584 let minus_present = try!(self.eat(&token::BinOp(token::Minus)));
1585 let lo = self.span.lo;
1586 let literal = P(try!(self.parse_lit()));
1587 let hi = self.last_span.hi;
1588 let expr = self.mk_expr(lo, hi, ExprLit(literal), None);
1591 let minus_hi = self.last_span.hi;
1592 let unary = self.mk_unary(UnNeg, expr);
1593 Ok(self.mk_expr(minus_lo, minus_hi, unary, None))
1599 /// Parses qualified path.
1601 /// Assumes that the leading `<` has been parsed already.
1603 /// Qualifed paths are a part of the universal function call
1606 /// `qualified_path = <type [as trait_ref]>::path`
1608 /// See `parse_path` for `mode` meaning.
1613 /// `<T as U>::F::a::<S>`
1614 pub fn parse_qualified_path(&mut self, mode: PathParsingMode)
1615 -> PResult<(QSelf, ast::Path)> {
1616 let span = self.last_span;
1617 let self_type = try!(self.parse_ty_sum());
1618 let mut path = if try!(self.eat_keyword(keywords::As)) {
1619 try!(self.parse_path(LifetimeAndTypesWithoutColons))
1630 position: path.segments.len()
1633 try!(self.expect(&token::Gt));
1634 try!(self.expect(&token::ModSep));
1636 let segments = match mode {
1637 LifetimeAndTypesWithoutColons => {
1638 try!(self.parse_path_segments_without_colons())
1640 LifetimeAndTypesWithColons => {
1641 try!(self.parse_path_segments_with_colons())
1644 try!(self.parse_path_segments_without_types())
1647 path.segments.extend(segments);
1649 path.span.hi = self.last_span.hi;
1654 /// Parses a path and optional type parameter bounds, depending on the
1655 /// mode. The `mode` parameter determines whether lifetimes, types, and/or
1656 /// bounds are permitted and whether `::` must precede type parameter
1658 pub fn parse_path(&mut self, mode: PathParsingMode) -> PResult<ast::Path> {
1659 // Check for a whole path...
1660 let found = match self.token {
1661 token::Interpolated(token::NtPath(_)) => Some(try!(self.bump_and_get())),
1664 if let Some(token::Interpolated(token::NtPath(path))) = found {
1668 let lo = self.span.lo;
1669 let is_global = try!(self.eat(&token::ModSep));
1671 // Parse any number of segments and bound sets. A segment is an
1672 // identifier followed by an optional lifetime and a set of types.
1673 // A bound set is a set of type parameter bounds.
1674 let segments = match mode {
1675 LifetimeAndTypesWithoutColons => {
1676 try!(self.parse_path_segments_without_colons())
1678 LifetimeAndTypesWithColons => {
1679 try!(self.parse_path_segments_with_colons())
1682 try!(self.parse_path_segments_without_types())
1686 // Assemble the span.
1687 let span = mk_sp(lo, self.last_span.hi);
1689 // Assemble the result.
1698 /// - `a::b<T,U>::c<V,W>`
1699 /// - `a::b<T,U>::c(V) -> W`
1700 /// - `a::b<T,U>::c(V)`
1701 pub fn parse_path_segments_without_colons(&mut self) -> PResult<Vec<ast::PathSegment>> {
1702 let mut segments = Vec::new();
1704 // First, parse an identifier.
1705 let identifier = try!(self.parse_ident_or_self_type());
1707 // Parse types, optionally.
1708 let parameters = if try!(self.eat_lt() ){
1709 let (lifetimes, types, bindings) = try!(self.parse_generic_values_after_lt());
1711 ast::AngleBracketedParameters(ast::AngleBracketedParameterData {
1712 lifetimes: lifetimes,
1713 types: OwnedSlice::from_vec(types),
1714 bindings: OwnedSlice::from_vec(bindings),
1716 } else if try!(self.eat(&token::OpenDelim(token::Paren)) ){
1717 let lo = self.last_span.lo;
1719 let inputs = try!(self.parse_seq_to_end(
1720 &token::CloseDelim(token::Paren),
1721 seq_sep_trailing_allowed(token::Comma),
1722 |p| p.parse_ty_sum()));
1724 let output_ty = if try!(self.eat(&token::RArrow) ){
1725 Some(try!(self.parse_ty()))
1730 let hi = self.last_span.hi;
1732 ast::ParenthesizedParameters(ast::ParenthesizedParameterData {
1733 span: mk_sp(lo, hi),
1738 ast::PathParameters::none()
1741 // Assemble and push the result.
1742 segments.push(ast::PathSegment { identifier: identifier,
1743 parameters: parameters });
1745 // Continue only if we see a `::`
1746 if !try!(self.eat(&token::ModSep) ){
1747 return Ok(segments);
1753 /// - `a::b::<T,U>::c`
1754 pub fn parse_path_segments_with_colons(&mut self) -> PResult<Vec<ast::PathSegment>> {
1755 let mut segments = Vec::new();
1757 // First, parse an identifier.
1758 let identifier = try!(self.parse_ident_or_self_type());
1760 // If we do not see a `::`, stop.
1761 if !try!(self.eat(&token::ModSep) ){
1762 segments.push(ast::PathSegment {
1763 identifier: identifier,
1764 parameters: ast::PathParameters::none()
1766 return Ok(segments);
1769 // Check for a type segment.
1770 if try!(self.eat_lt() ){
1771 // Consumed `a::b::<`, go look for types
1772 let (lifetimes, types, bindings) = try!(self.parse_generic_values_after_lt());
1773 segments.push(ast::PathSegment {
1774 identifier: identifier,
1775 parameters: ast::AngleBracketedParameters(ast::AngleBracketedParameterData {
1776 lifetimes: lifetimes,
1777 types: OwnedSlice::from_vec(types),
1778 bindings: OwnedSlice::from_vec(bindings),
1782 // Consumed `a::b::<T,U>`, check for `::` before proceeding
1783 if !try!(self.eat(&token::ModSep) ){
1784 return Ok(segments);
1787 // Consumed `a::`, go look for `b`
1788 segments.push(ast::PathSegment {
1789 identifier: identifier,
1790 parameters: ast::PathParameters::none(),
1799 pub fn parse_path_segments_without_types(&mut self) -> PResult<Vec<ast::PathSegment>> {
1800 let mut segments = Vec::new();
1802 // First, parse an identifier.
1803 let identifier = try!(self.parse_ident_or_self_type());
1805 // Assemble and push the result.
1806 segments.push(ast::PathSegment {
1807 identifier: identifier,
1808 parameters: ast::PathParameters::none()
1811 // If we do not see a `::`, stop.
1812 if !try!(self.eat(&token::ModSep) ){
1813 return Ok(segments);
1818 /// parses 0 or 1 lifetime
1819 pub fn parse_opt_lifetime(&mut self) -> PResult<Option<ast::Lifetime>> {
1821 token::Lifetime(..) => {
1822 Ok(Some(try!(self.parse_lifetime())))
1830 /// Parses a single lifetime
1831 /// Matches lifetime = LIFETIME
1832 pub fn parse_lifetime(&mut self) -> PResult<ast::Lifetime> {
1834 token::Lifetime(i) => {
1835 let span = self.span;
1837 return Ok(ast::Lifetime {
1838 id: ast::DUMMY_NODE_ID,
1844 return Err(self.fatal("expected a lifetime name"));
1849 /// Parses `lifetime_defs = [ lifetime_defs { ',' lifetime_defs } ]` where `lifetime_def =
1850 /// lifetime [':' lifetimes]`
1851 pub fn parse_lifetime_defs(&mut self) -> PResult<Vec<ast::LifetimeDef>> {
1853 let mut res = Vec::new();
1856 token::Lifetime(_) => {
1857 let lifetime = try!(self.parse_lifetime());
1859 if try!(self.eat(&token::Colon) ){
1860 try!(self.parse_lifetimes(token::BinOp(token::Plus)))
1864 res.push(ast::LifetimeDef { lifetime: lifetime,
1874 token::Comma => { try!(self.bump());}
1875 token::Gt => { return Ok(res); }
1876 token::BinOp(token::Shr) => { return Ok(res); }
1878 let this_token_str = self.this_token_to_string();
1879 let msg = format!("expected `,` or `>` after lifetime \
1882 return Err(self.fatal(&msg[..]));
1888 /// matches lifetimes = ( lifetime ) | ( lifetime , lifetimes ) actually, it matches the empty
1889 /// one too, but putting that in there messes up the grammar....
1891 /// Parses zero or more comma separated lifetimes. Expects each lifetime to be followed by
1892 /// either a comma or `>`. Used when parsing type parameter lists, where we expect something
1893 /// like `<'a, 'b, T>`.
1894 pub fn parse_lifetimes(&mut self, sep: token::Token) -> PResult<Vec<ast::Lifetime>> {
1896 let mut res = Vec::new();
1899 token::Lifetime(_) => {
1900 res.push(try!(self.parse_lifetime()));
1907 if self.token != sep {
1915 /// Parse mutability declaration (mut/const/imm)
1916 pub fn parse_mutability(&mut self) -> PResult<Mutability> {
1917 if try!(self.eat_keyword(keywords::Mut) ){
1924 /// Parse ident COLON expr
1925 pub fn parse_field(&mut self) -> PResult<Field> {
1926 let lo = self.span.lo;
1927 let i = try!(self.parse_ident());
1928 let hi = self.last_span.hi;
1929 try!(self.expect(&token::Colon));
1930 let e = try!(self.parse_expr());
1932 ident: spanned(lo, hi, i),
1933 span: mk_sp(lo, e.span.hi),
1938 pub fn mk_expr(&mut self, lo: BytePos, hi: BytePos,
1939 node: Expr_, attrs: ThinAttributes) -> P<Expr> {
1941 id: ast::DUMMY_NODE_ID,
1943 span: mk_sp(lo, hi),
1948 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::Expr_ {
1949 ExprUnary(unop, expr)
1952 pub fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::Expr_ {
1953 ExprBinary(binop, lhs, rhs)
1956 pub fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::Expr_ {
1960 fn mk_method_call(&mut self,
1961 ident: ast::SpannedIdent,
1965 ExprMethodCall(ident, tps, args)
1968 pub fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::Expr_ {
1969 ExprIndex(expr, idx)
1972 pub fn mk_range(&mut self,
1973 start: Option<P<Expr>>,
1974 end: Option<P<Expr>>)
1976 ExprRange(start, end)
1979 pub fn mk_field(&mut self, expr: P<Expr>, ident: ast::SpannedIdent) -> ast::Expr_ {
1980 ExprField(expr, ident)
1983 pub fn mk_tup_field(&mut self, expr: P<Expr>, idx: codemap::Spanned<usize>) -> ast::Expr_ {
1984 ExprTupField(expr, idx)
1987 pub fn mk_assign_op(&mut self, binop: ast::BinOp,
1988 lhs: P<Expr>, rhs: P<Expr>) -> ast::Expr_ {
1989 ExprAssignOp(binop, lhs, rhs)
1992 pub fn mk_mac_expr(&mut self, lo: BytePos, hi: BytePos,
1993 m: Mac_, attrs: ThinAttributes) -> P<Expr> {
1995 id: ast::DUMMY_NODE_ID,
1996 node: ExprMac(codemap::Spanned {node: m, span: mk_sp(lo, hi)}),
1997 span: mk_sp(lo, hi),
2002 pub fn mk_lit_u32(&mut self, i: u32, attrs: ThinAttributes) -> P<Expr> {
2003 let span = &self.span;
2004 let lv_lit = P(codemap::Spanned {
2005 node: LitInt(i as u64, ast::UnsignedIntLit(TyU32)),
2010 id: ast::DUMMY_NODE_ID,
2011 node: ExprLit(lv_lit),
2017 fn expect_open_delim(&mut self) -> PResult<token::DelimToken> {
2018 self.expected_tokens.push(TokenType::Token(token::Gt));
2020 token::OpenDelim(delim) => {
2024 _ => Err(self.fatal("expected open delimiter")),
2028 /// At the bottom (top?) of the precedence hierarchy,
2029 /// parse things like parenthesized exprs,
2030 /// macros, return, etc.
2032 /// NB: This does not parse outer attributes,
2033 /// and is private because it only works
2034 /// correctly if called from parse_dot_or_call_expr().
2035 fn parse_bottom_expr(&mut self) -> PResult<P<Expr>> {
2036 maybe_whole_expr!(self);
2038 // Outer attributes are already parsed and will be
2039 // added to the return value after the fact.
2041 // Therefore, prevent sub-parser from parsing
2042 // attributes by giving them a empty "already parsed" list.
2043 let mut attrs = None;
2045 let lo = self.span.lo;
2046 let mut hi = self.span.hi;
2050 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2052 token::OpenDelim(token::Paren) => {
2055 let attrs = try!(self.parse_inner_attributes())
2059 // (e) is parenthesized e
2060 // (e,) is a tuple with only one field, e
2061 let mut es = vec![];
2062 let mut trailing_comma = false;
2063 while self.token != token::CloseDelim(token::Paren) {
2064 es.push(try!(self.parse_expr()));
2065 try!(self.commit_expr(&**es.last().unwrap(), &[],
2066 &[token::Comma, token::CloseDelim(token::Paren)]));
2067 if self.check(&token::Comma) {
2068 trailing_comma = true;
2072 trailing_comma = false;
2078 hi = self.last_span.hi;
2079 return if es.len() == 1 && !trailing_comma {
2080 Ok(self.mk_expr(lo, hi, ExprParen(es.into_iter().nth(0).unwrap()), attrs))
2082 Ok(self.mk_expr(lo, hi, ExprTup(es), attrs))
2085 token::OpenDelim(token::Brace) => {
2086 return self.parse_block_expr(lo, DefaultBlock, attrs);
2088 token::BinOp(token::Or) | token::OrOr => {
2089 let lo = self.span.lo;
2090 return self.parse_lambda_expr(lo, CaptureByRef, attrs);
2092 token::Ident(id @ ast::Ident {
2093 name: token::SELF_KEYWORD_NAME,
2095 }, token::Plain) => {
2097 let path = ast_util::ident_to_path(mk_sp(lo, hi), id);
2098 ex = ExprPath(None, path);
2099 hi = self.last_span.hi;
2101 token::OpenDelim(token::Bracket) => {
2104 let inner_attrs = try!(self.parse_inner_attributes())
2106 attrs.update(|attrs| attrs.append(inner_attrs));
2108 if self.check(&token::CloseDelim(token::Bracket)) {
2111 ex = ExprVec(Vec::new());
2114 let first_expr = try!(self.parse_expr());
2115 if self.check(&token::Semi) {
2116 // Repeating array syntax: [ 0; 512 ]
2118 let count = try!(self.parse_expr());
2119 try!(self.expect(&token::CloseDelim(token::Bracket)));
2120 ex = ExprRepeat(first_expr, count);
2121 } else if self.check(&token::Comma) {
2122 // Vector with two or more elements.
2124 let remaining_exprs = try!(self.parse_seq_to_end(
2125 &token::CloseDelim(token::Bracket),
2126 seq_sep_trailing_allowed(token::Comma),
2127 |p| Ok(try!(p.parse_expr()))
2129 let mut exprs = vec!(first_expr);
2130 exprs.extend(remaining_exprs);
2131 ex = ExprVec(exprs);
2133 // Vector with one element.
2134 try!(self.expect(&token::CloseDelim(token::Bracket)));
2135 ex = ExprVec(vec!(first_expr));
2138 hi = self.last_span.hi;
2141 if try!(self.eat_lt()){
2143 try!(self.parse_qualified_path(LifetimeAndTypesWithColons));
2145 return Ok(self.mk_expr(lo, hi, ExprPath(Some(qself), path), attrs));
2147 if try!(self.eat_keyword(keywords::Move) ){
2148 let lo = self.last_span.lo;
2149 return self.parse_lambda_expr(lo, CaptureByValue, attrs);
2151 if try!(self.eat_keyword(keywords::If)) {
2152 return self.parse_if_expr(attrs);
2154 if try!(self.eat_keyword(keywords::For) ){
2155 let lo = self.last_span.lo;
2156 return self.parse_for_expr(None, lo, attrs);
2158 if try!(self.eat_keyword(keywords::While) ){
2159 let lo = self.last_span.lo;
2160 return self.parse_while_expr(None, lo, attrs);
2162 if self.token.is_lifetime() {
2163 let lifetime = self.get_lifetime();
2164 let lo = self.span.lo;
2166 try!(self.expect(&token::Colon));
2167 if try!(self.eat_keyword(keywords::While) ){
2168 return self.parse_while_expr(Some(lifetime), lo, attrs)
2170 if try!(self.eat_keyword(keywords::For) ){
2171 return self.parse_for_expr(Some(lifetime), lo, attrs)
2173 if try!(self.eat_keyword(keywords::Loop) ){
2174 return self.parse_loop_expr(Some(lifetime), lo, attrs)
2176 return Err(self.fatal("expected `while`, `for`, or `loop` after a label"))
2178 if try!(self.eat_keyword(keywords::Loop) ){
2179 let lo = self.last_span.lo;
2180 return self.parse_loop_expr(None, lo, attrs);
2182 if try!(self.eat_keyword(keywords::Continue) ){
2183 let ex = if self.token.is_lifetime() {
2184 let ex = ExprAgain(Some(Spanned{
2185 node: self.get_lifetime(),
2193 let hi = self.last_span.hi;
2194 return Ok(self.mk_expr(lo, hi, ex, attrs));
2196 if try!(self.eat_keyword(keywords::Match) ){
2197 return self.parse_match_expr(attrs);
2199 if try!(self.eat_keyword(keywords::Unsafe) ){
2200 return self.parse_block_expr(
2202 UnsafeBlock(ast::UserProvided),
2205 if try!(self.eat_keyword(keywords::Return) ){
2206 if self.token.can_begin_expr() {
2207 let e = try!(self.parse_expr());
2209 ex = ExprRet(Some(e));
2213 } else if try!(self.eat_keyword(keywords::Break) ){
2214 if self.token.is_lifetime() {
2215 ex = ExprBreak(Some(Spanned {
2216 node: self.get_lifetime(),
2221 ex = ExprBreak(None);
2223 hi = self.last_span.hi;
2224 } else if self.check(&token::ModSep) ||
2225 self.token.is_ident() &&
2226 !self.check_keyword(keywords::True) &&
2227 !self.check_keyword(keywords::False) {
2229 try!(self.parse_path(LifetimeAndTypesWithColons));
2231 // `!`, as an operator, is prefix, so we know this isn't that
2232 if self.check(&token::Not) {
2233 // MACRO INVOCATION expression
2236 let delim = try!(self.expect_open_delim());
2237 let tts = try!(self.parse_seq_to_end(
2238 &token::CloseDelim(delim),
2240 |p| p.parse_token_tree()));
2241 let hi = self.last_span.hi;
2243 return Ok(self.mk_mac_expr(lo,
2245 Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT },
2248 if self.check(&token::OpenDelim(token::Brace)) {
2249 // This is a struct literal, unless we're prohibited
2250 // from parsing struct literals here.
2251 let prohibited = self.restrictions.contains(
2252 Restrictions::RESTRICTION_NO_STRUCT_LITERAL
2255 // It's a struct literal.
2257 let mut fields = Vec::new();
2258 let mut base = None;
2260 let attrs = attrs.append(
2261 try!(self.parse_inner_attributes())
2262 .into_thin_attrs());
2264 while self.token != token::CloseDelim(token::Brace) {
2265 if try!(self.eat(&token::DotDot) ){
2266 base = Some(try!(self.parse_expr()));
2270 fields.push(try!(self.parse_field()));
2271 try!(self.commit_expr(&*fields.last().unwrap().expr,
2273 &[token::CloseDelim(token::Brace)]));
2277 try!(self.expect(&token::CloseDelim(token::Brace)));
2278 ex = ExprStruct(pth, fields, base);
2279 return Ok(self.mk_expr(lo, hi, ex, attrs));
2284 ex = ExprPath(None, pth);
2286 // other literal expression
2287 let lit = try!(self.parse_lit());
2289 ex = ExprLit(P(lit));
2294 return Ok(self.mk_expr(lo, hi, ex, attrs));
2297 fn parse_or_use_outer_attributes(&mut self,
2298 already_parsed_attrs: Option<ThinAttributes>)
2299 -> PResult<ThinAttributes> {
2300 if let Some(attrs) = already_parsed_attrs {
2303 self.parse_outer_attributes().map(|a| a.into_thin_attrs())
2307 /// Parse a block or unsafe block
2308 pub fn parse_block_expr(&mut self, lo: BytePos, blk_mode: BlockCheckMode,
2309 attrs: ThinAttributes)
2310 -> PResult<P<Expr>> {
2312 let outer_attrs = attrs;
2313 try!(self.expect(&token::OpenDelim(token::Brace)));
2315 let inner_attrs = try!(self.parse_inner_attributes()).into_thin_attrs();
2316 let attrs = outer_attrs.append(inner_attrs);
2318 let blk = try!(self.parse_block_tail(lo, blk_mode));
2319 return Ok(self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk), attrs));
2322 /// parse a.b or a(13) or a[4] or just a
2323 pub fn parse_dot_or_call_expr(&mut self,
2324 already_parsed_attrs: Option<ThinAttributes>)
2325 -> PResult<P<Expr>> {
2326 let attrs = try!(self.parse_or_use_outer_attributes(already_parsed_attrs));
2328 let b = try!(self.parse_bottom_expr());
2329 self.parse_dot_or_call_expr_with(b, attrs)
2332 pub fn parse_dot_or_call_expr_with(&mut self,
2334 attrs: ThinAttributes)
2335 -> PResult<P<Expr>> {
2336 // Stitch the list of outer attributes onto the return value.
2337 // A little bit ugly, but the best way given the current code
2339 self.parse_dot_or_call_expr_with_(e0)
2341 expr.map(|mut expr| {
2342 expr.attrs.update(|a| a.prepend(attrs));
2344 ExprIf(..) | ExprIfLet(..) => {
2345 if !expr.attrs.as_attr_slice().is_empty() {
2346 // Just point to the first attribute in there...
2347 let span = expr.attrs.as_attr_slice()[0].span;
2350 "attributes are not yet allowed on `if` \
2361 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>) -> PResult<P<Expr>> {
2367 if try!(self.eat(&token::Dot) ){
2369 token::Ident(i, _) => {
2370 let dot = self.last_span.hi;
2373 let (_, tys, bindings) = if try!(self.eat(&token::ModSep) ){
2374 try!(self.expect_lt());
2375 try!(self.parse_generic_values_after_lt())
2377 (Vec::new(), Vec::new(), Vec::new())
2380 if !bindings.is_empty() {
2381 let last_span = self.last_span;
2382 self.span_err(last_span, "type bindings are only permitted on trait paths");
2385 // expr.f() method call
2387 token::OpenDelim(token::Paren) => {
2388 let mut es = try!(self.parse_unspanned_seq(
2389 &token::OpenDelim(token::Paren),
2390 &token::CloseDelim(token::Paren),
2391 seq_sep_trailing_allowed(token::Comma),
2392 |p| Ok(try!(p.parse_expr()))
2394 hi = self.last_span.hi;
2397 let id = spanned(dot, hi, i);
2398 let nd = self.mk_method_call(id, tys, es);
2399 e = self.mk_expr(lo, hi, nd, None);
2402 if !tys.is_empty() {
2403 let last_span = self.last_span;
2404 self.span_err(last_span,
2405 "field expressions may not \
2406 have type parameters");
2409 let id = spanned(dot, hi, i);
2410 let field = self.mk_field(e, id);
2411 e = self.mk_expr(lo, hi, field, None);
2415 token::Literal(token::Integer(n), suf) => {
2418 // A tuple index may not have a suffix
2419 self.expect_no_suffix(sp, "tuple index", suf);
2421 let dot = self.last_span.hi;
2425 let index = n.as_str().parse::<usize>().ok();
2428 let id = spanned(dot, hi, n);
2429 let field = self.mk_tup_field(e, id);
2430 e = self.mk_expr(lo, hi, field, None);
2433 let last_span = self.last_span;
2434 self.span_err(last_span, "invalid tuple or tuple struct index");
2438 token::Literal(token::Float(n), _suf) => {
2440 let last_span = self.last_span;
2441 let fstr = n.as_str();
2442 self.span_err(last_span,
2443 &format!("unexpected token: `{}`", n.as_str()));
2444 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2445 let float = match fstr.parse::<f64>().ok() {
2449 self.fileline_help(last_span,
2450 &format!("try parenthesizing the first index; e.g., `(foo.{}){}`",
2451 float.trunc() as usize,
2452 format!(".{}", fstr.splitn(2, ".").last().unwrap())));
2454 self.abort_if_errors();
2457 _ => return Err(self.unexpected())
2461 if self.expr_is_complete(&*e) { break; }
2464 token::OpenDelim(token::Paren) => {
2465 let es = try!(self.parse_unspanned_seq(
2466 &token::OpenDelim(token::Paren),
2467 &token::CloseDelim(token::Paren),
2468 seq_sep_trailing_allowed(token::Comma),
2469 |p| Ok(try!(p.parse_expr()))
2471 hi = self.last_span.hi;
2473 let nd = self.mk_call(e, es);
2474 e = self.mk_expr(lo, hi, nd, None);
2478 // Could be either an index expression or a slicing expression.
2479 token::OpenDelim(token::Bracket) => {
2481 let ix = try!(self.parse_expr());
2483 try!(self.commit_expr_expecting(&*ix, token::CloseDelim(token::Bracket)));
2484 let index = self.mk_index(e, ix);
2485 e = self.mk_expr(lo, hi, index, None)
2493 // Parse unquoted tokens after a `$` in a token tree
2494 fn parse_unquoted(&mut self) -> PResult<TokenTree> {
2495 let mut sp = self.span;
2496 let (name, namep) = match self.token {
2500 if self.token == token::OpenDelim(token::Paren) {
2501 let Spanned { node: seq, span: seq_span } = try!(self.parse_seq(
2502 &token::OpenDelim(token::Paren),
2503 &token::CloseDelim(token::Paren),
2505 |p| p.parse_token_tree()
2507 let (sep, repeat) = try!(self.parse_sep_and_kleene_op());
2508 let name_num = macro_parser::count_names(&seq);
2509 return Ok(TokenTree::Sequence(mk_sp(sp.lo, seq_span.hi),
2510 Rc::new(SequenceRepetition {
2514 num_captures: name_num
2516 } else if self.token.is_keyword_allow_following_colon(keywords::Crate) {
2518 return Ok(TokenTree::Token(sp, SpecialVarNt(SpecialMacroVar::CrateMacroVar)));
2520 sp = mk_sp(sp.lo, self.span.hi);
2521 let namep = match self.token { token::Ident(_, p) => p, _ => token::Plain };
2522 let name = try!(self.parse_ident());
2526 token::SubstNt(name, namep) => {
2532 // continue by trying to parse the `:ident` after `$name`
2533 if self.token == token::Colon && self.look_ahead(1, |t| t.is_ident() &&
2534 !t.is_strict_keyword() &&
2535 !t.is_reserved_keyword()) {
2537 sp = mk_sp(sp.lo, self.span.hi);
2538 let kindp = match self.token { token::Ident(_, p) => p, _ => token::Plain };
2539 let nt_kind = try!(self.parse_ident());
2540 Ok(TokenTree::Token(sp, MatchNt(name, nt_kind, namep, kindp)))
2542 Ok(TokenTree::Token(sp, SubstNt(name, namep)))
2546 pub fn check_unknown_macro_variable(&mut self) -> PResult<()> {
2547 if self.quote_depth == 0 {
2549 token::SubstNt(name, _) =>
2550 return Err(self.fatal(&format!("unknown macro variable `{}`",
2558 /// Parse an optional separator followed by a Kleene-style
2559 /// repetition token (+ or *).
2560 pub fn parse_sep_and_kleene_op(&mut self) -> PResult<(Option<token::Token>, ast::KleeneOp)> {
2561 fn parse_kleene_op(parser: &mut Parser) -> PResult<Option<ast::KleeneOp>> {
2562 match parser.token {
2563 token::BinOp(token::Star) => {
2564 try!(parser.bump());
2565 Ok(Some(ast::ZeroOrMore))
2567 token::BinOp(token::Plus) => {
2568 try!(parser.bump());
2569 Ok(Some(ast::OneOrMore))
2575 match try!(parse_kleene_op(self)) {
2576 Some(kleene_op) => return Ok((None, kleene_op)),
2580 let separator = try!(self.bump_and_get());
2581 match try!(parse_kleene_op(self)) {
2582 Some(zerok) => Ok((Some(separator), zerok)),
2583 None => return Err(self.fatal("expected `*` or `+`"))
2587 /// parse a single token tree from the input.
2588 pub fn parse_token_tree(&mut self) -> PResult<TokenTree> {
2589 // FIXME #6994: currently, this is too eager. It
2590 // parses token trees but also identifies TokenType::Sequence's
2591 // and token::SubstNt's; it's too early to know yet
2592 // whether something will be a nonterminal or a seq
2594 maybe_whole!(deref self, NtTT);
2596 // this is the fall-through for the 'match' below.
2597 // invariants: the current token is not a left-delimiter,
2598 // not an EOF, and not the desired right-delimiter (if
2599 // it were, parse_seq_to_before_end would have prevented
2600 // reaching this point.
2601 fn parse_non_delim_tt_tok(p: &mut Parser) -> PResult<TokenTree> {
2602 maybe_whole!(deref p, NtTT);
2604 token::CloseDelim(_) => {
2605 // This is a conservative error: only report the last unclosed delimiter. The
2606 // previous unclosed delimiters could actually be closed! The parser just hasn't
2607 // gotten to them yet.
2608 match p.open_braces.last() {
2610 Some(&sp) => p.span_note(sp, "unclosed delimiter"),
2612 let token_str = p.this_token_to_string();
2613 Err(p.fatal(&format!("incorrect close delimiter: `{}`",
2616 /* we ought to allow different depths of unquotation */
2617 token::Dollar | token::SubstNt(..) if p.quote_depth > 0 => {
2621 Ok(TokenTree::Token(p.span, try!(p.bump_and_get())))
2628 let open_braces = self.open_braces.clone();
2629 for sp in &open_braces {
2630 self.span_help(*sp, "did you mean to close this delimiter?");
2632 // There shouldn't really be a span, but it's easier for the test runner
2633 // if we give it one
2634 return Err(self.fatal("this file contains an un-closed delimiter "));
2636 token::OpenDelim(delim) => {
2637 // The span for beginning of the delimited section
2638 let pre_span = self.span;
2640 // Parse the open delimiter.
2641 self.open_braces.push(self.span);
2642 let open_span = self.span;
2645 // Parse the token trees within the delimiters
2646 let tts = try!(self.parse_seq_to_before_end(
2647 &token::CloseDelim(delim),
2649 |p| p.parse_token_tree()
2652 // Parse the close delimiter.
2653 let close_span = self.span;
2655 self.open_braces.pop().unwrap();
2657 // Expand to cover the entire delimited token tree
2658 let span = Span { hi: close_span.hi, ..pre_span };
2660 Ok(TokenTree::Delimited(span, Rc::new(Delimited {
2662 open_span: open_span,
2664 close_span: close_span,
2667 _ => parse_non_delim_tt_tok(self),
2671 // parse a stream of tokens into a list of TokenTree's,
2673 pub fn parse_all_token_trees(&mut self) -> PResult<Vec<TokenTree>> {
2674 let mut tts = Vec::new();
2675 while self.token != token::Eof {
2676 tts.push(try!(self.parse_token_tree()));
2681 /// Parse a prefix-unary-operator expr
2682 pub fn parse_prefix_expr(&mut self,
2683 already_parsed_attrs: Option<ThinAttributes>)
2684 -> PResult<P<Expr>> {
2685 let attrs = try!(self.parse_or_use_outer_attributes(already_parsed_attrs));
2686 let lo = self.span.lo;
2688 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2689 let ex = match self.token {
2692 let e = try!(self.parse_prefix_expr(None));
2694 self.mk_unary(UnNot, e)
2696 token::BinOp(token::Minus) => {
2698 let e = try!(self.parse_prefix_expr(None));
2700 self.mk_unary(UnNeg, e)
2702 token::BinOp(token::Star) => {
2704 let e = try!(self.parse_prefix_expr(None));
2706 self.mk_unary(UnDeref, e)
2708 token::BinOp(token::And) | token::AndAnd => {
2709 try!(self.expect_and());
2710 let m = try!(self.parse_mutability());
2711 let e = try!(self.parse_prefix_expr(None));
2715 token::Ident(..) if self.token.is_keyword(keywords::In) => {
2717 let place = try!(self.parse_expr_res(
2718 Restrictions::RESTRICTION_NO_STRUCT_LITERAL,
2721 let blk = try!(self.parse_block());
2722 let span = blk.span;
2724 let blk_expr = self.mk_expr(span.lo, span.hi, ExprBlock(blk),
2726 ExprInPlace(place, blk_expr)
2728 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
2730 let subexpression = try!(self.parse_prefix_expr(None));
2731 hi = subexpression.span.hi;
2732 ExprBox(subexpression)
2734 _ => return self.parse_dot_or_call_expr(Some(attrs))
2736 return Ok(self.mk_expr(lo, hi, ex, attrs));
2739 /// Parse an associative expression
2741 /// This parses an expression accounting for associativity and precedence of the operators in
2743 pub fn parse_assoc_expr(&mut self,
2744 already_parsed_attrs: Option<ThinAttributes>)
2745 -> PResult<P<Expr>> {
2746 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
2749 /// Parse an associative expression with operators of at least `min_prec` precedence
2750 pub fn parse_assoc_expr_with(&mut self,
2753 -> PResult<P<Expr>> {
2754 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
2757 let attrs = match lhs {
2758 LhsExpr::AttributesParsed(attrs) => Some(attrs),
2761 if self.token == token::DotDot {
2762 return self.parse_prefix_range_expr(attrs);
2764 try!(self.parse_prefix_expr(attrs))
2767 if self.expr_is_complete(&*lhs) {
2768 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
2771 self.expected_tokens.push(TokenType::Operator);
2772 while let Some(op) = AssocOp::from_token(&self.token) {
2773 let cur_op_span = self.span;
2774 let restrictions = if op.is_assign_like() {
2775 self.restrictions & Restrictions::RESTRICTION_NO_STRUCT_LITERAL
2779 if op.precedence() < min_prec {
2783 if op.is_comparison() {
2784 self.check_no_chained_comparison(&*lhs, &op);
2787 if op == AssocOp::As {
2788 let rhs = try!(self.parse_ty());
2789 lhs = self.mk_expr(lhs.span.lo, rhs.span.hi,
2790 ExprCast(lhs, rhs), None);
2792 } else if op == AssocOp::DotDot {
2793 // If we didn’t have to handle `x..`, it would be pretty easy to generalise
2794 // it to the Fixity::None code.
2796 // We have 2 alternatives here: `x..y` and `x..` The other two variants are
2797 // handled with `parse_prefix_range_expr` call above.
2798 let rhs = if self.is_at_start_of_range_notation_rhs() {
2799 self.parse_assoc_expr_with(op.precedence() + 1,
2800 LhsExpr::NotYetParsed).ok()
2804 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
2809 let r = self.mk_range(Some(lhs), rhs);
2810 lhs = self.mk_expr(lhs_span.lo, rhs_span.hi, r, None);
2815 let rhs = try!(match op.fixity() {
2816 Fixity::Right => self.with_res(restrictions, |this|{
2817 this.parse_assoc_expr_with(op.precedence(), LhsExpr::NotYetParsed)
2819 Fixity::Left => self.with_res(restrictions, |this|{
2820 this.parse_assoc_expr_with(op.precedence() + 1, LhsExpr::NotYetParsed)
2822 // We currently have no non-associative operators that are not handled above by
2823 // the special cases. The code is here only for future convenience.
2824 Fixity::None => self.with_res(restrictions, |this|{
2825 this.parse_assoc_expr_with(op.precedence() + 1, LhsExpr::NotYetParsed)
2830 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
2831 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
2832 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
2833 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
2834 AssocOp::Greater | AssocOp::GreaterEqual => {
2835 let ast_op = op.to_ast_binop().unwrap();
2836 let (lhs_span, rhs_span) = (lhs.span, rhs.span);
2837 let binary = self.mk_binary(codemap::respan(cur_op_span, ast_op), lhs, rhs);
2838 self.mk_expr(lhs_span.lo, rhs_span.hi, binary, None)
2841 self.mk_expr(lhs.span.lo, rhs.span.hi, ExprAssign(lhs, rhs), None),
2843 self.mk_expr(lhs.span.lo, rhs.span.hi, ExprInPlace(lhs, rhs), None),
2844 AssocOp::AssignOp(k) => {
2846 token::Plus => BiAdd,
2847 token::Minus => BiSub,
2848 token::Star => BiMul,
2849 token::Slash => BiDiv,
2850 token::Percent => BiRem,
2851 token::Caret => BiBitXor,
2852 token::And => BiBitAnd,
2853 token::Or => BiBitOr,
2854 token::Shl => BiShl,
2857 let (lhs_span, rhs_span) = (lhs.span, rhs.span);
2858 let aopexpr = self.mk_assign_op(codemap::respan(cur_op_span, aop), lhs, rhs);
2859 self.mk_expr(lhs_span.lo, rhs_span.hi, aopexpr, None)
2861 AssocOp::As | AssocOp::DotDot => self.bug("As or DotDot branch reached")
2864 if op.fixity() == Fixity::None { break }
2869 /// Produce an error if comparison operators are chained (RFC #558).
2870 /// We only need to check lhs, not rhs, because all comparison ops
2871 /// have same precedence and are left-associative
2872 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
2873 debug_assert!(outer_op.is_comparison());
2875 ExprBinary(op, _, _) if op.node.is_comparison() => {
2876 // respan to include both operators
2877 let op_span = mk_sp(op.span.lo, self.span.hi);
2878 self.span_err(op_span,
2879 "chained comparison operators require parentheses");
2880 if op.node == BiLt && *outer_op == AssocOp::Greater {
2881 self.fileline_help(op_span,
2882 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
2889 /// Parse prefix-forms of range notation: `..expr` and `..`
2890 fn parse_prefix_range_expr(&mut self,
2891 already_parsed_attrs: Option<ThinAttributes>)
2892 -> PResult<P<Expr>> {
2893 debug_assert!(self.token == token::DotDot);
2894 let attrs = try!(self.parse_or_use_outer_attributes(already_parsed_attrs));
2895 let lo = self.span.lo;
2896 let mut hi = self.span.hi;
2898 let opt_end = if self.is_at_start_of_range_notation_rhs() {
2899 // RHS must be parsed with more associativity than DotDot.
2900 let next_prec = AssocOp::from_token(&token::DotDot).unwrap().precedence() + 1;
2901 Some(try!(self.parse_assoc_expr_with(next_prec,
2902 LhsExpr::NotYetParsed)
2910 let r = self.mk_range(None, opt_end);
2911 Ok(self.mk_expr(lo, hi, r, attrs))
2914 fn is_at_start_of_range_notation_rhs(&self) -> bool {
2915 if self.token.can_begin_expr() {
2916 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
2917 if self.token == token::OpenDelim(token::Brace) {
2918 return !self.restrictions.contains(Restrictions::RESTRICTION_NO_STRUCT_LITERAL);
2926 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
2927 pub fn parse_if_expr(&mut self, attrs: ThinAttributes) -> PResult<P<Expr>> {
2928 if self.check_keyword(keywords::Let) {
2929 return self.parse_if_let_expr(attrs);
2931 let lo = self.last_span.lo;
2932 let cond = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
2933 let thn = try!(self.parse_block());
2934 let mut els: Option<P<Expr>> = None;
2935 let mut hi = thn.span.hi;
2936 if try!(self.eat_keyword(keywords::Else) ){
2937 let elexpr = try!(self.parse_else_expr());
2938 hi = elexpr.span.hi;
2941 Ok(self.mk_expr(lo, hi, ExprIf(cond, thn, els), attrs))
2944 /// Parse an 'if let' expression ('if' token already eaten)
2945 pub fn parse_if_let_expr(&mut self, attrs: ThinAttributes)
2946 -> PResult<P<Expr>> {
2947 let lo = self.last_span.lo;
2948 try!(self.expect_keyword(keywords::Let));
2949 let pat = try!(self.parse_pat());
2950 try!(self.expect(&token::Eq));
2951 let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
2952 let thn = try!(self.parse_block());
2953 let (hi, els) = if try!(self.eat_keyword(keywords::Else) ){
2954 let expr = try!(self.parse_else_expr());
2955 (expr.span.hi, Some(expr))
2959 Ok(self.mk_expr(lo, hi, ExprIfLet(pat, expr, thn, els), attrs))
2963 pub fn parse_lambda_expr(&mut self, lo: BytePos,
2964 capture_clause: CaptureClause,
2965 attrs: ThinAttributes)
2968 let decl = try!(self.parse_fn_block_decl());
2969 let body = match decl.output {
2970 DefaultReturn(_) => {
2971 // If no explicit return type is given, parse any
2972 // expr and wrap it up in a dummy block:
2973 let body_expr = try!(self.parse_expr());
2975 id: ast::DUMMY_NODE_ID,
2977 span: body_expr.span,
2978 expr: Some(body_expr),
2979 rules: DefaultBlock,
2983 // If an explicit return type is given, require a
2984 // block to appear (RFC 968).
2985 try!(self.parse_block())
2992 ExprClosure(capture_clause, decl, body), attrs))
2995 // `else` token already eaten
2996 pub fn parse_else_expr(&mut self) -> PResult<P<Expr>> {
2997 if try!(self.eat_keyword(keywords::If) ){
2998 return self.parse_if_expr(None);
3000 let blk = try!(self.parse_block());
3001 return Ok(self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk), None));
3005 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3006 pub fn parse_for_expr(&mut self, opt_ident: Option<ast::Ident>,
3008 attrs: ThinAttributes) -> PResult<P<Expr>> {
3009 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3011 let pat = try!(self.parse_pat());
3012 try!(self.expect_keyword(keywords::In));
3013 let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3014 let (iattrs, loop_block) = try!(self.parse_inner_attrs_and_block());
3015 let attrs = attrs.append(iattrs.into_thin_attrs());
3017 let hi = self.last_span.hi;
3019 Ok(self.mk_expr(span_lo, hi,
3020 ExprForLoop(pat, expr, loop_block, opt_ident),
3024 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3025 pub fn parse_while_expr(&mut self, opt_ident: Option<ast::Ident>,
3027 attrs: ThinAttributes) -> PResult<P<Expr>> {
3028 if self.token.is_keyword(keywords::Let) {
3029 return self.parse_while_let_expr(opt_ident, span_lo, attrs);
3031 let cond = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3032 let (iattrs, body) = try!(self.parse_inner_attrs_and_block());
3033 let attrs = attrs.append(iattrs.into_thin_attrs());
3034 let hi = body.span.hi;
3035 return Ok(self.mk_expr(span_lo, hi, ExprWhile(cond, body, opt_ident),
3039 /// Parse a 'while let' expression ('while' token already eaten)
3040 pub fn parse_while_let_expr(&mut self, opt_ident: Option<ast::Ident>,
3042 attrs: ThinAttributes) -> PResult<P<Expr>> {
3043 try!(self.expect_keyword(keywords::Let));
3044 let pat = try!(self.parse_pat());
3045 try!(self.expect(&token::Eq));
3046 let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3047 let (iattrs, body) = try!(self.parse_inner_attrs_and_block());
3048 let attrs = attrs.append(iattrs.into_thin_attrs());
3049 let hi = body.span.hi;
3050 return Ok(self.mk_expr(span_lo, hi, ExprWhileLet(pat, expr, body, opt_ident), attrs));
3053 // parse `loop {...}`, `loop` token already eaten
3054 pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::Ident>,
3056 attrs: ThinAttributes) -> PResult<P<Expr>> {
3057 let (iattrs, body) = try!(self.parse_inner_attrs_and_block());
3058 let attrs = attrs.append(iattrs.into_thin_attrs());
3059 let hi = body.span.hi;
3060 Ok(self.mk_expr(span_lo, hi, ExprLoop(body, opt_ident), attrs))
3063 // `match` token already eaten
3064 fn parse_match_expr(&mut self, attrs: ThinAttributes) -> PResult<P<Expr>> {
3065 let match_span = self.last_span;
3066 let lo = self.last_span.lo;
3067 let discriminant = try!(self.parse_expr_res(
3068 Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3069 if let Err(e) = self.commit_expr_expecting(&*discriminant, token::OpenDelim(token::Brace)) {
3070 if self.token == token::Token::Semi {
3071 self.span_note(match_span, "did you mean to remove this `match` keyword?");
3075 let attrs = attrs.append(
3076 try!(self.parse_inner_attributes()).into_thin_attrs());
3077 let mut arms: Vec<Arm> = Vec::new();
3078 while self.token != token::CloseDelim(token::Brace) {
3079 arms.push(try!(self.parse_arm()));
3081 let hi = self.span.hi;
3083 return Ok(self.mk_expr(lo, hi, ExprMatch(discriminant, arms), attrs));
3086 pub fn parse_arm(&mut self) -> PResult<Arm> {
3087 maybe_whole!(no_clone self, NtArm);
3089 let attrs = try!(self.parse_outer_attributes());
3090 let pats = try!(self.parse_pats());
3091 let mut guard = None;
3092 if try!(self.eat_keyword(keywords::If) ){
3093 guard = Some(try!(self.parse_expr()));
3095 try!(self.expect(&token::FatArrow));
3096 let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_STMT_EXPR, None));
3099 !classify::expr_is_simple_block(&*expr)
3100 && self.token != token::CloseDelim(token::Brace);
3103 try!(self.commit_expr(&*expr, &[token::Comma], &[token::CloseDelim(token::Brace)]));
3105 try!(self.eat(&token::Comma));
3116 /// Parse an expression
3117 pub fn parse_expr(&mut self) -> PResult<P<Expr>> {
3118 self.parse_expr_res(Restrictions::empty(), None)
3121 /// Evaluate the closure with restrictions in place.
3123 /// After the closure is evaluated, restrictions are reset.
3124 pub fn with_res<F>(&mut self, r: Restrictions, f: F) -> PResult<P<Expr>>
3125 where F: FnOnce(&mut Self) -> PResult<P<Expr>> {
3126 let old = self.restrictions;
3127 self.restrictions = r;
3129 self.restrictions = old;
3134 /// Parse an expression, subject to the given restrictions
3135 pub fn parse_expr_res(&mut self, r: Restrictions,
3136 already_parsed_attrs: Option<ThinAttributes>)
3137 -> PResult<P<Expr>> {
3138 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3141 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3142 fn parse_initializer(&mut self) -> PResult<Option<P<Expr>>> {
3143 if self.check(&token::Eq) {
3145 Ok(Some(try!(self.parse_expr())))
3151 /// Parse patterns, separated by '|' s
3152 fn parse_pats(&mut self) -> PResult<Vec<P<Pat>>> {
3153 let mut pats = Vec::new();
3155 pats.push(try!(self.parse_pat()));
3156 if self.check(&token::BinOp(token::Or)) { try!(self.bump());}
3157 else { return Ok(pats); }
3161 fn parse_pat_tuple_elements(&mut self) -> PResult<Vec<P<Pat>>> {
3162 let mut fields = vec![];
3163 if !self.check(&token::CloseDelim(token::Paren)) {
3164 fields.push(try!(self.parse_pat()));
3165 if self.look_ahead(1, |t| *t != token::CloseDelim(token::Paren)) {
3166 while try!(self.eat(&token::Comma)) &&
3167 !self.check(&token::CloseDelim(token::Paren)) {
3168 fields.push(try!(self.parse_pat()));
3171 if fields.len() == 1 {
3172 try!(self.expect(&token::Comma));
3178 fn parse_pat_vec_elements(
3180 ) -> PResult<(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3181 let mut before = Vec::new();
3182 let mut slice = None;
3183 let mut after = Vec::new();
3184 let mut first = true;
3185 let mut before_slice = true;
3187 while self.token != token::CloseDelim(token::Bracket) {
3191 try!(self.expect(&token::Comma));
3193 if self.token == token::CloseDelim(token::Bracket)
3194 && (before_slice || !after.is_empty()) {
3200 if self.check(&token::DotDot) {
3203 if self.check(&token::Comma) ||
3204 self.check(&token::CloseDelim(token::Bracket)) {
3205 slice = Some(P(ast::Pat {
3206 id: ast::DUMMY_NODE_ID,
3210 before_slice = false;
3216 let subpat = try!(self.parse_pat());
3217 if before_slice && self.check(&token::DotDot) {
3219 slice = Some(subpat);
3220 before_slice = false;
3221 } else if before_slice {
3222 before.push(subpat);
3228 Ok((before, slice, after))
3231 /// Parse the fields of a struct-like pattern
3232 fn parse_pat_fields(&mut self) -> PResult<(Vec<codemap::Spanned<ast::FieldPat>> , bool)> {
3233 let mut fields = Vec::new();
3234 let mut etc = false;
3235 let mut first = true;
3236 while self.token != token::CloseDelim(token::Brace) {
3240 try!(self.expect(&token::Comma));
3241 // accept trailing commas
3242 if self.check(&token::CloseDelim(token::Brace)) { break }
3245 let lo = self.span.lo;
3248 if self.check(&token::DotDot) {
3250 if self.token != token::CloseDelim(token::Brace) {
3251 let token_str = self.this_token_to_string();
3252 return Err(self.fatal(&format!("expected `{}`, found `{}`", "}",
3259 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3260 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3261 // Parsing a pattern of the form "fieldname: pat"
3262 let fieldname = try!(self.parse_ident());
3264 let pat = try!(self.parse_pat());
3266 (pat, fieldname, false)
3268 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3269 let is_box = try!(self.eat_keyword(keywords::Box));
3270 let boxed_span_lo = self.span.lo;
3271 let is_ref = try!(self.eat_keyword(keywords::Ref));
3272 let is_mut = try!(self.eat_keyword(keywords::Mut));
3273 let fieldname = try!(self.parse_ident());
3274 hi = self.last_span.hi;
3276 let bind_type = match (is_ref, is_mut) {
3277 (true, true) => BindByRef(MutMutable),
3278 (true, false) => BindByRef(MutImmutable),
3279 (false, true) => BindByValue(MutMutable),
3280 (false, false) => BindByValue(MutImmutable),
3282 let fieldpath = codemap::Spanned{span:self.last_span, node:fieldname};
3283 let fieldpat = P(ast::Pat{
3284 id: ast::DUMMY_NODE_ID,
3285 node: PatIdent(bind_type, fieldpath, None),
3286 span: mk_sp(boxed_span_lo, hi),
3289 let subpat = if is_box {
3291 id: ast::DUMMY_NODE_ID,
3292 node: PatBox(fieldpat),
3293 span: mk_sp(lo, hi),
3298 (subpat, fieldname, true)
3301 fields.push(codemap::Spanned { span: mk_sp(lo, hi),
3302 node: ast::FieldPat { ident: fieldname,
3304 is_shorthand: is_shorthand }});
3306 return Ok((fields, etc));
3309 fn parse_pat_range_end(&mut self) -> PResult<P<Expr>> {
3310 if self.is_path_start() {
3311 let lo = self.span.lo;
3312 let (qself, path) = if try!(self.eat_lt()) {
3313 // Parse a qualified path
3315 try!(self.parse_qualified_path(NoTypesAllowed));
3318 // Parse an unqualified path
3319 (None, try!(self.parse_path(LifetimeAndTypesWithColons)))
3321 let hi = self.last_span.hi;
3322 Ok(self.mk_expr(lo, hi, ExprPath(qself, path), None))
3324 self.parse_pat_literal_maybe_minus()
3328 fn is_path_start(&self) -> bool {
3329 (self.token == token::Lt || self.token == token::ModSep
3330 || self.token.is_ident() || self.token.is_path())
3331 && !self.token.is_keyword(keywords::True) && !self.token.is_keyword(keywords::False)
3334 /// Parse a pattern.
3335 pub fn parse_pat(&mut self) -> PResult<P<Pat>> {
3336 maybe_whole!(self, NtPat);
3338 let lo = self.span.lo;
3341 token::Underscore => {
3346 token::BinOp(token::And) | token::AndAnd => {
3347 // Parse &pat / &mut pat
3348 try!(self.expect_and());
3349 let mutbl = try!(self.parse_mutability());
3350 if let token::Lifetime(ident) = self.token {
3351 return Err(self.fatal(&format!("unexpected lifetime `{}` in pattern", ident)));
3354 let subpat = try!(self.parse_pat());
3355 pat = PatRegion(subpat, mutbl);
3357 token::OpenDelim(token::Paren) => {
3358 // Parse (pat,pat,pat,...) as tuple pattern
3360 let fields = try!(self.parse_pat_tuple_elements());
3361 try!(self.expect(&token::CloseDelim(token::Paren)));
3362 pat = PatTup(fields);
3364 token::OpenDelim(token::Bracket) => {
3365 // Parse [pat,pat,...] as slice pattern
3367 let (before, slice, after) = try!(self.parse_pat_vec_elements());
3368 try!(self.expect(&token::CloseDelim(token::Bracket)));
3369 pat = PatVec(before, slice, after);
3372 // At this point, token != _, &, &&, (, [
3373 if try!(self.eat_keyword(keywords::Mut)) {
3374 // Parse mut ident @ pat
3375 pat = try!(self.parse_pat_ident(BindByValue(MutMutable)));
3376 } else if try!(self.eat_keyword(keywords::Ref)) {
3377 // Parse ref ident @ pat / ref mut ident @ pat
3378 let mutbl = try!(self.parse_mutability());
3379 pat = try!(self.parse_pat_ident(BindByRef(mutbl)));
3380 } else if try!(self.eat_keyword(keywords::Box)) {
3382 let subpat = try!(self.parse_pat());
3383 pat = PatBox(subpat);
3384 } else if self.is_path_start() {
3385 // Parse pattern starting with a path
3386 if self.token.is_plain_ident() && self.look_ahead(1, |t| *t != token::DotDotDot &&
3387 *t != token::OpenDelim(token::Brace) &&
3388 *t != token::OpenDelim(token::Paren) &&
3389 // Contrary to its definition, a plain ident can be followed by :: in macros
3390 *t != token::ModSep) {
3391 // Plain idents have some extra abilities here compared to general paths
3392 if self.look_ahead(1, |t| *t == token::Not) {
3393 // Parse macro invocation
3394 let ident = try!(self.parse_ident());
3395 let ident_span = self.last_span;
3396 let path = ident_to_path(ident_span, ident);
3398 let delim = try!(self.expect_open_delim());
3399 let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
3400 seq_sep_none(), |p| p.parse_token_tree()));
3401 let mac = Mac_ { path: path, tts: tts, ctxt: EMPTY_CTXT };
3402 pat = PatMac(codemap::Spanned {node: mac,
3403 span: mk_sp(lo, self.last_span.hi)});
3405 // Parse ident @ pat
3406 // This can give false positives and parse nullary enums,
3407 // they are dealt with later in resolve
3408 pat = try!(self.parse_pat_ident(BindByValue(MutImmutable)));
3411 let (qself, path) = if try!(self.eat_lt()) {
3412 // Parse a qualified path
3414 try!(self.parse_qualified_path(NoTypesAllowed));
3417 // Parse an unqualified path
3418 (None, try!(self.parse_path(LifetimeAndTypesWithColons)))
3421 token::DotDotDot => {
3423 let hi = self.last_span.hi;
3424 let begin = self.mk_expr(lo, hi, ExprPath(qself, path), None);
3426 let end = try!(self.parse_pat_range_end());
3427 pat = PatRange(begin, end);
3429 token::OpenDelim(token::Brace) => {
3430 if qself.is_some() {
3431 return Err(self.fatal("unexpected `{` after qualified path"));
3433 // Parse struct pattern
3435 let (fields, etc) = try!(self.parse_pat_fields());
3437 pat = PatStruct(path, fields, etc);
3439 token::OpenDelim(token::Paren) => {
3440 if qself.is_some() {
3441 return Err(self.fatal("unexpected `(` after qualified path"));
3443 // Parse tuple struct or enum pattern
3444 if self.look_ahead(1, |t| *t == token::DotDot) {
3445 // This is a "top constructor only" pat
3448 try!(self.expect(&token::CloseDelim(token::Paren)));
3449 pat = PatEnum(path, None);
3451 let args = try!(self.parse_enum_variant_seq(
3452 &token::OpenDelim(token::Paren),
3453 &token::CloseDelim(token::Paren),
3454 seq_sep_trailing_allowed(token::Comma),
3455 |p| p.parse_pat()));
3456 pat = PatEnum(path, Some(args));
3461 // Parse qualified path
3462 Some(qself) => PatQPath(qself, path),
3463 // Parse nullary enum
3464 None => PatEnum(path, Some(vec![]))
3470 // Try to parse everything else as literal with optional minus
3471 let begin = try!(self.parse_pat_literal_maybe_minus());
3472 if try!(self.eat(&token::DotDotDot)) {
3473 let end = try!(self.parse_pat_range_end());
3474 pat = PatRange(begin, end);
3476 pat = PatLit(begin);
3482 let hi = self.last_span.hi;
3484 id: ast::DUMMY_NODE_ID,
3486 span: mk_sp(lo, hi),
3490 /// Parse ident or ident @ pat
3491 /// used by the copy foo and ref foo patterns to give a good
3492 /// error message when parsing mistakes like ref foo(a,b)
3493 fn parse_pat_ident(&mut self,
3494 binding_mode: ast::BindingMode)
3495 -> PResult<ast::Pat_> {
3496 if !self.token.is_plain_ident() {
3497 let span = self.span;
3498 let tok_str = self.this_token_to_string();
3499 return Err(self.span_fatal(span,
3500 &format!("expected identifier, found `{}`", tok_str)))
3502 let ident = try!(self.parse_ident());
3503 let last_span = self.last_span;
3504 let name = codemap::Spanned{span: last_span, node: ident};
3505 let sub = if try!(self.eat(&token::At) ){
3506 Some(try!(self.parse_pat()))
3511 // just to be friendly, if they write something like
3513 // we end up here with ( as the current token. This shortly
3514 // leads to a parse error. Note that if there is no explicit
3515 // binding mode then we do not end up here, because the lookahead
3516 // will direct us over to parse_enum_variant()
3517 if self.token == token::OpenDelim(token::Paren) {
3518 let last_span = self.last_span;
3519 return Err(self.span_fatal(
3521 "expected identifier, found enum pattern"))
3524 Ok(PatIdent(binding_mode, name, sub))
3527 /// Parse a local variable declaration
3528 fn parse_local(&mut self, attrs: ThinAttributes) -> PResult<P<Local>> {
3529 let lo = self.span.lo;
3530 let pat = try!(self.parse_pat());
3533 if try!(self.eat(&token::Colon) ){
3534 ty = Some(try!(self.parse_ty_sum()));
3536 let init = try!(self.parse_initializer());
3541 id: ast::DUMMY_NODE_ID,
3542 span: mk_sp(lo, self.last_span.hi),
3547 /// Parse a "let" stmt
3548 fn parse_let(&mut self, attrs: ThinAttributes) -> PResult<P<Decl>> {
3549 let lo = self.span.lo;
3550 let local = try!(self.parse_local(attrs));
3551 Ok(P(spanned(lo, self.last_span.hi, DeclLocal(local))))
3554 /// Parse a structure field
3555 fn parse_name_and_ty(&mut self, pr: Visibility,
3556 attrs: Vec<Attribute> ) -> PResult<StructField> {
3558 Inherited => self.span.lo,
3559 Public => self.last_span.lo,
3561 if !self.token.is_plain_ident() {
3562 return Err(self.fatal("expected ident"));
3564 let name = try!(self.parse_ident());
3565 try!(self.expect(&token::Colon));
3566 let ty = try!(self.parse_ty_sum());
3567 Ok(spanned(lo, self.last_span.hi, ast::StructField_ {
3568 kind: NamedField(name, pr),
3569 id: ast::DUMMY_NODE_ID,
3575 /// Emit an expected item after attributes error.
3576 fn expected_item_err(&self, attrs: &[Attribute]) {
3577 let message = match attrs.last() {
3578 Some(&Attribute { node: ast::Attribute_ { is_sugared_doc: true, .. }, .. }) => {
3579 "expected item after doc comment"
3581 _ => "expected item after attributes",
3584 self.span_err(self.last_span, message);
3587 /// Parse a statement. may include decl.
3588 pub fn parse_stmt(&mut self) -> PResult<Option<P<Stmt>>> {
3589 Ok(try!(self.parse_stmt_()).map(P))
3592 fn parse_stmt_(&mut self) -> PResult<Option<Stmt>> {
3593 maybe_whole!(Some deref self, NtStmt);
3595 let attrs = try!(self.parse_outer_attributes());
3596 let lo = self.span.lo;
3598 Ok(Some(if self.check_keyword(keywords::Let) {
3599 try!(self.expect_keyword(keywords::Let));
3600 let decl = try!(self.parse_let(attrs.into_thin_attrs()));
3601 let hi = decl.span.hi;
3602 let stmt = StmtDecl(decl, ast::DUMMY_NODE_ID);
3603 spanned(lo, hi, stmt)
3604 } else if self.token.is_ident()
3605 && !self.token.is_any_keyword()
3606 && self.look_ahead(1, |t| *t == token::Not) {
3607 // it's a macro invocation:
3609 // Potential trouble: if we allow macros with paths instead of
3610 // idents, we'd need to look ahead past the whole path here...
3611 let pth = try!(self.parse_path(NoTypesAllowed));
3614 let id = match self.token {
3615 token::OpenDelim(_) => token::special_idents::invalid, // no special identifier
3616 _ => try!(self.parse_ident()),
3619 // check that we're pointing at delimiters (need to check
3620 // again after the `if`, because of `parse_ident`
3621 // consuming more tokens).
3622 let delim = match self.token {
3623 token::OpenDelim(delim) => delim,
3625 // we only expect an ident if we didn't parse one
3627 let ident_str = if id.name == token::special_idents::invalid.name {
3632 let tok_str = self.this_token_to_string();
3633 return Err(self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
3639 let tts = try!(self.parse_unspanned_seq(
3640 &token::OpenDelim(delim),
3641 &token::CloseDelim(delim),
3643 |p| p.parse_token_tree()
3645 let hi = self.last_span.hi;
3647 let style = if delim == token::Brace {
3650 MacStmtWithoutBraces
3653 if id.name == token::special_idents::invalid.name {
3654 let stmt = StmtMac(P(spanned(lo,
3656 Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT })),
3658 attrs.into_thin_attrs());
3659 spanned(lo, hi, stmt)
3661 // if it has a special ident, it's definitely an item
3663 // Require a semicolon or braces.
3664 if style != MacStmtWithBraces {
3665 if !try!(self.eat(&token::Semi) ){
3666 let last_span = self.last_span;
3667 self.span_err(last_span,
3668 "macros that expand to items must \
3669 either be surrounded with braces or \
3670 followed by a semicolon");
3673 spanned(lo, hi, StmtDecl(
3674 P(spanned(lo, hi, DeclItem(
3676 lo, hi, id /*id is good here*/,
3677 ItemMac(spanned(lo, hi,
3678 Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT })),
3679 Inherited, attrs)))),
3680 ast::DUMMY_NODE_ID))
3683 // FIXME: Bad copy of attrs
3684 match try!(self.parse_item_(attrs.clone(), false, true)) {
3687 let decl = P(spanned(lo, hi, DeclItem(i)));
3688 spanned(lo, hi, StmtDecl(decl, ast::DUMMY_NODE_ID))
3691 let unused_attrs = |attrs: &[_], s: &mut Self| {
3692 if attrs.len() > 0 {
3694 "expected statement after outer attribute");
3698 // Do not attempt to parse an expression if we're done here.
3699 if self.token == token::Semi {
3700 unused_attrs(&attrs, self);
3705 if self.token == token::CloseDelim(token::Brace) {
3706 unused_attrs(&attrs, self);
3710 // Remainder are line-expr stmts.
3711 let e = try!(self.parse_expr_res(
3712 Restrictions::RESTRICTION_STMT_EXPR, Some(attrs.into_thin_attrs())));
3714 let stmt = StmtExpr(e, ast::DUMMY_NODE_ID);
3715 spanned(lo, hi, stmt)
3721 /// Is this expression a successfully-parsed statement?
3722 fn expr_is_complete(&mut self, e: &Expr) -> bool {
3723 self.restrictions.contains(Restrictions::RESTRICTION_STMT_EXPR) &&
3724 !classify::expr_requires_semi_to_be_stmt(e)
3727 /// Parse a block. No inner attrs are allowed.
3728 pub fn parse_block(&mut self) -> PResult<P<Block>> {
3729 maybe_whole!(no_clone self, NtBlock);
3731 let lo = self.span.lo;
3733 if !try!(self.eat(&token::OpenDelim(token::Brace)) ){
3735 let tok = self.this_token_to_string();
3736 return Err(self.span_fatal_help(sp,
3737 &format!("expected `{{`, found `{}`", tok),
3738 "place this code inside a block"));
3741 self.parse_block_tail(lo, DefaultBlock)
3744 /// Parse a block. Inner attrs are allowed.
3745 fn parse_inner_attrs_and_block(&mut self) -> PResult<(Vec<Attribute>, P<Block>)> {
3746 maybe_whole!(pair_empty self, NtBlock);
3748 let lo = self.span.lo;
3749 try!(self.expect(&token::OpenDelim(token::Brace)));
3750 Ok((try!(self.parse_inner_attributes()),
3751 try!(self.parse_block_tail(lo, DefaultBlock))))
3754 /// Parse the rest of a block expression or function body
3755 /// Precondition: already parsed the '{'.
3756 fn parse_block_tail(&mut self, lo: BytePos, s: BlockCheckMode) -> PResult<P<Block>> {
3757 let mut stmts = vec![];
3758 let mut expr = None;
3760 while !try!(self.eat(&token::CloseDelim(token::Brace))) {
3761 let Spanned {node, span} = if let Some(s) = try!(self.parse_stmt_()) {
3764 // Found only `;` or `}`.
3769 try!(self.handle_expression_like_statement(e, span, &mut stmts, &mut expr));
3771 StmtMac(mac, MacStmtWithoutBraces, attrs) => {
3772 // statement macro without braces; might be an
3773 // expr depending on whether a semicolon follows
3776 stmts.push(P(Spanned {
3777 node: StmtMac(mac, MacStmtWithSemicolon, attrs),
3778 span: mk_sp(span.lo, self.span.hi),
3783 let e = self.mk_mac_expr(span.lo, span.hi,
3784 mac.and_then(|m| m.node),
3786 let e = try!(self.parse_dot_or_call_expr_with(e, attrs));
3787 let e = try!(self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e)));
3788 try!(self.handle_expression_like_statement(
3796 StmtMac(m, style, attrs) => {
3797 // statement macro; might be an expr
3800 stmts.push(P(Spanned {
3801 node: StmtMac(m, MacStmtWithSemicolon, attrs),
3802 span: mk_sp(span.lo, self.span.hi),
3806 token::CloseDelim(token::Brace) => {
3807 // if a block ends in `m!(arg)` without
3808 // a `;`, it must be an expr
3809 expr = Some(self.mk_mac_expr(span.lo, span.hi,
3810 m.and_then(|x| x.node),
3814 stmts.push(P(Spanned {
3815 node: StmtMac(m, style, attrs),
3821 _ => { // all other kinds of statements:
3822 let mut hi = span.hi;
3823 if classify::stmt_ends_with_semi(&node) {
3824 try!(self.commit_stmt_expecting(token::Semi));
3825 hi = self.last_span.hi;
3828 stmts.push(P(Spanned {
3830 span: mk_sp(span.lo, hi)
3839 id: ast::DUMMY_NODE_ID,
3841 span: mk_sp(lo, self.last_span.hi),
3845 fn handle_expression_like_statement(
3849 stmts: &mut Vec<P<Stmt>>,
3850 last_block_expr: &mut Option<P<Expr>>) -> PResult<()> {
3851 // expression without semicolon
3852 if classify::expr_requires_semi_to_be_stmt(&*e) {
3853 // Just check for errors and recover; do not eat semicolon yet.
3854 try!(self.commit_stmt(&[],
3855 &[token::Semi, token::CloseDelim(token::Brace)]));
3861 let span_with_semi = Span {
3863 hi: self.last_span.hi,
3864 expn_id: span.expn_id,
3866 stmts.push(P(Spanned {
3867 node: StmtSemi(e, ast::DUMMY_NODE_ID),
3868 span: span_with_semi,
3871 token::CloseDelim(token::Brace) => *last_block_expr = Some(e),
3873 stmts.push(P(Spanned {
3874 node: StmtExpr(e, ast::DUMMY_NODE_ID),
3882 // Parses a sequence of bounds if a `:` is found,
3883 // otherwise returns empty list.
3884 fn parse_colon_then_ty_param_bounds(&mut self,
3885 mode: BoundParsingMode)
3886 -> PResult<OwnedSlice<TyParamBound>>
3888 if !try!(self.eat(&token::Colon) ){
3889 Ok(OwnedSlice::empty())
3891 self.parse_ty_param_bounds(mode)
3895 // matches bounds = ( boundseq )?
3896 // where boundseq = ( polybound + boundseq ) | polybound
3897 // and polybound = ( 'for' '<' 'region '>' )? bound
3898 // and bound = 'region | trait_ref
3899 fn parse_ty_param_bounds(&mut self,
3900 mode: BoundParsingMode)
3901 -> PResult<OwnedSlice<TyParamBound>>
3903 let mut result = vec!();
3905 let question_span = self.span;
3906 let ate_question = try!(self.eat(&token::Question));
3908 token::Lifetime(lifetime) => {
3910 self.span_err(question_span,
3911 "`?` may only modify trait bounds, not lifetime bounds");
3913 result.push(RegionTyParamBound(ast::Lifetime {
3914 id: ast::DUMMY_NODE_ID,
3920 token::ModSep | token::Ident(..) => {
3921 let poly_trait_ref = try!(self.parse_poly_trait_ref());
3922 let modifier = if ate_question {
3923 if mode == BoundParsingMode::Modified {
3924 TraitBoundModifier::Maybe
3926 self.span_err(question_span,
3928 TraitBoundModifier::None
3931 TraitBoundModifier::None
3933 result.push(TraitTyParamBound(poly_trait_ref, modifier))
3938 if !try!(self.eat(&token::BinOp(token::Plus)) ){
3943 return Ok(OwnedSlice::from_vec(result));
3946 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
3947 fn parse_ty_param(&mut self) -> PResult<TyParam> {
3948 let span = self.span;
3949 let ident = try!(self.parse_ident());
3951 let bounds = try!(self.parse_colon_then_ty_param_bounds(BoundParsingMode::Modified));
3953 let default = if self.check(&token::Eq) {
3955 Some(try!(self.parse_ty_sum()))
3962 id: ast::DUMMY_NODE_ID,
3969 /// Parse a set of optional generic type parameter declarations. Where
3970 /// clauses are not parsed here, and must be added later via
3971 /// `parse_where_clause()`.
3973 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
3974 /// | ( < lifetimes , typaramseq ( , )? > )
3975 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
3976 pub fn parse_generics(&mut self) -> PResult<ast::Generics> {
3977 maybe_whole!(self, NtGenerics);
3979 if try!(self.eat(&token::Lt) ){
3980 let lifetime_defs = try!(self.parse_lifetime_defs());
3981 let mut seen_default = false;
3982 let ty_params = try!(self.parse_seq_to_gt(Some(token::Comma), |p| {
3983 try!(p.forbid_lifetime());
3984 let ty_param = try!(p.parse_ty_param());
3985 if ty_param.default.is_some() {
3986 seen_default = true;
3987 } else if seen_default {
3988 let last_span = p.last_span;
3989 p.span_err(last_span,
3990 "type parameters with a default must be trailing");
3995 lifetimes: lifetime_defs,
3996 ty_params: ty_params,
3997 where_clause: WhereClause {
3998 id: ast::DUMMY_NODE_ID,
3999 predicates: Vec::new(),
4003 Ok(ast::Generics::default())
4007 fn parse_generic_values_after_lt(&mut self) -> PResult<(Vec<ast::Lifetime>,
4009 Vec<P<TypeBinding>>)> {
4010 let span_lo = self.span.lo;
4011 let lifetimes = try!(self.parse_lifetimes(token::Comma));
4013 let missing_comma = !lifetimes.is_empty() &&
4014 !self.token.is_like_gt() &&
4016 .as_ref().map_or(true,
4017 |x| &**x != &token::Comma);
4021 let msg = format!("expected `,` or `>` after lifetime \
4023 self.this_token_to_string());
4024 self.span_err(self.span, &msg);
4026 let span_hi = self.span.hi;
4027 let span_hi = if self.parse_ty().is_ok() {
4033 let msg = format!("did you mean a single argument type &'a Type, \
4034 or did you mean the comma-separated arguments \
4036 self.span_note(mk_sp(span_lo, span_hi), &msg);
4038 self.abort_if_errors()
4041 // First parse types.
4042 let (types, returned) = try!(self.parse_seq_to_gt_or_return(
4045 try!(p.forbid_lifetime());
4046 if p.look_ahead(1, |t| t == &token::Eq) {
4049 Ok(Some(try!(p.parse_ty_sum())))
4054 // If we found the `>`, don't continue.
4056 return Ok((lifetimes, types.into_vec(), Vec::new()));
4059 // Then parse type bindings.
4060 let bindings = try!(self.parse_seq_to_gt(
4063 try!(p.forbid_lifetime());
4065 let ident = try!(p.parse_ident());
4066 let found_eq = try!(p.eat(&token::Eq));
4069 p.span_warn(span, "whoops, no =?");
4071 let ty = try!(p.parse_ty());
4072 let hi = ty.span.hi;
4073 let span = mk_sp(lo, hi);
4074 return Ok(P(TypeBinding{id: ast::DUMMY_NODE_ID,
4081 Ok((lifetimes, types.into_vec(), bindings.into_vec()))
4084 fn forbid_lifetime(&mut self) -> PResult<()> {
4085 if self.token.is_lifetime() {
4086 let span = self.span;
4087 return Err(self.span_fatal(span, "lifetime parameters must be declared \
4088 prior to type parameters"))
4093 /// Parses an optional `where` clause and places it in `generics`.
4096 /// where T : Trait<U, V> + 'b, 'a : 'b
4098 pub fn parse_where_clause(&mut self) -> PResult<ast::WhereClause> {
4099 maybe_whole!(self, NtWhereClause);
4101 let mut where_clause = WhereClause {
4102 id: ast::DUMMY_NODE_ID,
4103 predicates: Vec::new(),
4106 if !try!(self.eat_keyword(keywords::Where)) {
4107 return Ok(where_clause);
4110 let mut parsed_something = false;
4112 let lo = self.span.lo;
4114 token::OpenDelim(token::Brace) => {
4118 token::Lifetime(..) => {
4119 let bounded_lifetime =
4120 try!(self.parse_lifetime());
4122 try!(self.eat(&token::Colon));
4125 try!(self.parse_lifetimes(token::BinOp(token::Plus)));
4127 let hi = self.last_span.hi;
4128 let span = mk_sp(lo, hi);
4130 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
4131 ast::WhereRegionPredicate {
4133 lifetime: bounded_lifetime,
4138 parsed_something = true;
4142 let bound_lifetimes = if try!(self.eat_keyword(keywords::For) ){
4143 // Higher ranked constraint.
4144 try!(self.expect(&token::Lt));
4145 let lifetime_defs = try!(self.parse_lifetime_defs());
4146 try!(self.expect_gt());
4152 let bounded_ty = try!(self.parse_ty());
4154 if try!(self.eat(&token::Colon) ){
4155 let bounds = try!(self.parse_ty_param_bounds(BoundParsingMode::Bare));
4156 let hi = self.last_span.hi;
4157 let span = mk_sp(lo, hi);
4159 if bounds.is_empty() {
4161 "each predicate in a `where` clause must have \
4162 at least one bound in it");
4165 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
4166 ast::WhereBoundPredicate {
4168 bound_lifetimes: bound_lifetimes,
4169 bounded_ty: bounded_ty,
4173 parsed_something = true;
4174 } else if try!(self.eat(&token::Eq) ){
4175 // let ty = try!(self.parse_ty());
4176 let hi = self.last_span.hi;
4177 let span = mk_sp(lo, hi);
4178 // where_clause.predicates.push(
4179 // ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
4180 // id: ast::DUMMY_NODE_ID,
4182 // path: panic!("NYI"), //bounded_ty,
4185 // parsed_something = true;
4188 "equality constraints are not yet supported \
4189 in where clauses (#20041)");
4191 let last_span = self.last_span;
4192 self.span_err(last_span,
4193 "unexpected token in `where` clause");
4198 if !try!(self.eat(&token::Comma) ){
4203 if !parsed_something {
4204 let last_span = self.last_span;
4205 self.span_err(last_span,
4206 "a `where` clause must have at least one predicate \
4213 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
4214 -> PResult<(Vec<Arg> , bool)> {
4216 let mut args: Vec<Option<Arg>> =
4217 try!(self.parse_unspanned_seq(
4218 &token::OpenDelim(token::Paren),
4219 &token::CloseDelim(token::Paren),
4220 seq_sep_trailing_allowed(token::Comma),
4222 if p.token == token::DotDotDot {
4225 if p.token != token::CloseDelim(token::Paren) {
4227 return Err(p.span_fatal(span,
4228 "`...` must be last in argument list for variadic function"))
4232 return Err(p.span_fatal(span,
4233 "only foreign functions are allowed to be variadic"))
4237 Ok(Some(try!(p.parse_arg_general(named_args))))
4242 let variadic = match args.pop() {
4245 // Need to put back that last arg
4252 if variadic && args.is_empty() {
4254 "variadic function must be declared with at least one named argument");
4257 let args = args.into_iter().map(|x| x.unwrap()).collect();
4259 Ok((args, variadic))
4262 /// Parse the argument list and result type of a function declaration
4263 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<P<FnDecl>> {
4265 let (args, variadic) = try!(self.parse_fn_args(true, allow_variadic));
4266 let ret_ty = try!(self.parse_ret_ty());
4275 fn is_self_ident(&mut self) -> bool {
4277 token::Ident(id, token::Plain) => id.name == special_idents::self_.name,
4282 fn expect_self_ident(&mut self) -> PResult<ast::Ident> {
4284 token::Ident(id, token::Plain) if id.name == special_idents::self_.name => {
4289 let token_str = self.this_token_to_string();
4290 return Err(self.fatal(&format!("expected `self`, found `{}`",
4296 fn is_self_type_ident(&mut self) -> bool {
4298 token::Ident(id, token::Plain) => id.name == special_idents::type_self.name,
4303 fn expect_self_type_ident(&mut self) -> PResult<ast::Ident> {
4305 token::Ident(id, token::Plain) if id.name == special_idents::type_self.name => {
4310 let token_str = self.this_token_to_string();
4311 Err(self.fatal(&format!("expected `Self`, found `{}`",
4317 /// Parse the argument list and result type of a function
4318 /// that may have a self type.
4319 fn parse_fn_decl_with_self<F>(&mut self,
4320 parse_arg_fn: F) -> PResult<(ExplicitSelf, P<FnDecl>)> where
4321 F: FnMut(&mut Parser) -> PResult<Arg>,
4323 fn maybe_parse_borrowed_explicit_self(this: &mut Parser)
4324 -> PResult<ast::ExplicitSelf_> {
4325 // The following things are possible to see here:
4330 // fn(&'lt mut self)
4332 // We already know that the current token is `&`.
4334 if this.look_ahead(1, |t| t.is_keyword(keywords::SelfValue)) {
4336 Ok(SelfRegion(None, MutImmutable, try!(this.expect_self_ident())))
4337 } else if this.look_ahead(1, |t| t.is_mutability()) &&
4338 this.look_ahead(2, |t| t.is_keyword(keywords::SelfValue)) {
4340 let mutability = try!(this.parse_mutability());
4341 Ok(SelfRegion(None, mutability, try!(this.expect_self_ident())))
4342 } else if this.look_ahead(1, |t| t.is_lifetime()) &&
4343 this.look_ahead(2, |t| t.is_keyword(keywords::SelfValue)) {
4345 let lifetime = try!(this.parse_lifetime());
4346 Ok(SelfRegion(Some(lifetime), MutImmutable, try!(this.expect_self_ident())))
4347 } else if this.look_ahead(1, |t| t.is_lifetime()) &&
4348 this.look_ahead(2, |t| t.is_mutability()) &&
4349 this.look_ahead(3, |t| t.is_keyword(keywords::SelfValue)) {
4351 let lifetime = try!(this.parse_lifetime());
4352 let mutability = try!(this.parse_mutability());
4353 Ok(SelfRegion(Some(lifetime), mutability, try!(this.expect_self_ident())))
4359 try!(self.expect(&token::OpenDelim(token::Paren)));
4361 // A bit of complexity and lookahead is needed here in order to be
4362 // backwards compatible.
4363 let lo = self.span.lo;
4364 let mut self_ident_lo = self.span.lo;
4365 let mut self_ident_hi = self.span.hi;
4367 let mut mutbl_self = MutImmutable;
4368 let explicit_self = match self.token {
4369 token::BinOp(token::And) => {
4370 let eself = try!(maybe_parse_borrowed_explicit_self(self));
4371 self_ident_lo = self.last_span.lo;
4372 self_ident_hi = self.last_span.hi;
4375 token::BinOp(token::Star) => {
4376 // Possibly "*self" or "*mut self" -- not supported. Try to avoid
4377 // emitting cryptic "unexpected token" errors.
4379 let _mutability = if self.token.is_mutability() {
4380 try!(self.parse_mutability())
4384 if self.is_self_ident() {
4385 let span = self.span;
4386 self.span_err(span, "cannot pass self by raw pointer");
4389 // error case, making bogus self ident:
4390 SelfValue(special_idents::self_)
4392 token::Ident(..) => {
4393 if self.is_self_ident() {
4394 let self_ident = try!(self.expect_self_ident());
4396 // Determine whether this is the fully explicit form, `self:
4398 if try!(self.eat(&token::Colon) ){
4399 SelfExplicit(try!(self.parse_ty_sum()), self_ident)
4401 SelfValue(self_ident)
4403 } else if self.token.is_mutability() &&
4404 self.look_ahead(1, |t| t.is_keyword(keywords::SelfValue)) {
4405 mutbl_self = try!(self.parse_mutability());
4406 let self_ident = try!(self.expect_self_ident());
4408 // Determine whether this is the fully explicit form,
4410 if try!(self.eat(&token::Colon) ){
4411 SelfExplicit(try!(self.parse_ty_sum()), self_ident)
4413 SelfValue(self_ident)
4422 let explicit_self_sp = mk_sp(self_ident_lo, self_ident_hi);
4424 // shared fall-through for the three cases below. borrowing prevents simply
4425 // writing this as a closure
4426 macro_rules! parse_remaining_arguments {
4429 // If we parsed a self type, expect a comma before the argument list.
4433 let sep = seq_sep_trailing_allowed(token::Comma);
4434 let mut fn_inputs = try!(self.parse_seq_to_before_end(
4435 &token::CloseDelim(token::Paren),
4439 fn_inputs.insert(0, Arg::new_self(explicit_self_sp, mutbl_self, $self_id));
4442 token::CloseDelim(token::Paren) => {
4443 vec!(Arg::new_self(explicit_self_sp, mutbl_self, $self_id))
4446 let token_str = self.this_token_to_string();
4447 return Err(self.fatal(&format!("expected `,` or `)`, found `{}`",
4454 let fn_inputs = match explicit_self {
4456 let sep = seq_sep_trailing_allowed(token::Comma);
4457 try!(self.parse_seq_to_before_end(&token::CloseDelim(token::Paren),
4460 SelfValue(id) => parse_remaining_arguments!(id),
4461 SelfRegion(_,_,id) => parse_remaining_arguments!(id),
4462 SelfExplicit(_,id) => parse_remaining_arguments!(id),
4466 try!(self.expect(&token::CloseDelim(token::Paren)));
4468 let hi = self.span.hi;
4470 let ret_ty = try!(self.parse_ret_ty());
4472 let fn_decl = P(FnDecl {
4478 Ok((spanned(lo, hi, explicit_self), fn_decl))
4481 // parse the |arg, arg| header on a lambda
4482 fn parse_fn_block_decl(&mut self) -> PResult<P<FnDecl>> {
4483 let inputs_captures = {
4484 if try!(self.eat(&token::OrOr) ){
4487 try!(self.expect(&token::BinOp(token::Or)));
4488 try!(self.parse_obsolete_closure_kind());
4489 let args = try!(self.parse_seq_to_before_end(
4490 &token::BinOp(token::Or),
4491 seq_sep_trailing_allowed(token::Comma),
4492 |p| p.parse_fn_block_arg()
4498 let output = try!(self.parse_ret_ty());
4501 inputs: inputs_captures,
4507 /// Parse the name and optional generic types of a function header.
4508 fn parse_fn_header(&mut self) -> PResult<(Ident, ast::Generics)> {
4509 let id = try!(self.parse_ident());
4510 let generics = try!(self.parse_generics());
4514 fn mk_item(&mut self, lo: BytePos, hi: BytePos, ident: Ident,
4515 node: Item_, vis: Visibility,
4516 attrs: Vec<Attribute>) -> P<Item> {
4520 id: ast::DUMMY_NODE_ID,
4527 /// Parse an item-position function declaration.
4528 fn parse_item_fn(&mut self,
4530 constness: Constness,
4532 -> PResult<ItemInfo> {
4533 let (ident, mut generics) = try!(self.parse_fn_header());
4534 let decl = try!(self.parse_fn_decl(false));
4535 generics.where_clause = try!(self.parse_where_clause());
4536 let (inner_attrs, body) = try!(self.parse_inner_attrs_and_block());
4537 Ok((ident, ItemFn(decl, unsafety, constness, abi, generics, body), Some(inner_attrs)))
4540 /// true if we are looking at `const ID`, false for things like `const fn` etc
4541 pub fn is_const_item(&mut self) -> bool {
4542 self.token.is_keyword(keywords::Const) &&
4543 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
4544 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
4547 /// parses all the "front matter" for a `fn` declaration, up to
4548 /// and including the `fn` keyword:
4552 /// - `const unsafe fn`
4555 pub fn parse_fn_front_matter(&mut self) -> PResult<(ast::Constness, ast::Unsafety, abi::Abi)> {
4556 let is_const_fn = try!(self.eat_keyword(keywords::Const));
4557 let unsafety = try!(self.parse_unsafety());
4558 let (constness, unsafety, abi) = if is_const_fn {
4559 (Constness::Const, unsafety, abi::Rust)
4561 let abi = if try!(self.eat_keyword(keywords::Extern)) {
4562 try!(self.parse_opt_abi()).unwrap_or(abi::C)
4566 (Constness::NotConst, unsafety, abi)
4568 try!(self.expect_keyword(keywords::Fn));
4569 Ok((constness, unsafety, abi))
4572 /// Parse an impl item.
4573 pub fn parse_impl_item(&mut self) -> PResult<P<ImplItem>> {
4574 maybe_whole!(no_clone self, NtImplItem);
4576 let mut attrs = try!(self.parse_outer_attributes());
4577 let lo = self.span.lo;
4578 let vis = try!(self.parse_visibility());
4579 let (name, node) = if try!(self.eat_keyword(keywords::Type)) {
4580 let name = try!(self.parse_ident());
4581 try!(self.expect(&token::Eq));
4582 let typ = try!(self.parse_ty_sum());
4583 try!(self.expect(&token::Semi));
4584 (name, ast::ImplItemKind::Type(typ))
4585 } else if self.is_const_item() {
4586 try!(self.expect_keyword(keywords::Const));
4587 let name = try!(self.parse_ident());
4588 try!(self.expect(&token::Colon));
4589 let typ = try!(self.parse_ty_sum());
4590 try!(self.expect(&token::Eq));
4591 let expr = try!(self.parse_expr());
4592 try!(self.commit_expr_expecting(&expr, token::Semi));
4593 (name, ast::ImplItemKind::Const(typ, expr))
4595 let (name, inner_attrs, node) = try!(self.parse_impl_method(vis));
4596 attrs.extend(inner_attrs);
4601 id: ast::DUMMY_NODE_ID,
4602 span: mk_sp(lo, self.last_span.hi),
4610 fn complain_if_pub_macro(&mut self, visa: Visibility, span: Span) {
4613 self.span_err(span, "can't qualify macro invocation with `pub`");
4614 self.fileline_help(span, "try adjusting the macro to put `pub` inside \
4621 /// Parse a method or a macro invocation in a trait impl.
4622 fn parse_impl_method(&mut self, vis: Visibility)
4623 -> PResult<(Ident, Vec<ast::Attribute>, ast::ImplItemKind)> {
4624 // code copied from parse_macro_use_or_failure... abstraction!
4625 if !self.token.is_any_keyword()
4626 && self.look_ahead(1, |t| *t == token::Not)
4627 && (self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren))
4628 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) {
4631 let last_span = self.last_span;
4632 self.complain_if_pub_macro(vis, last_span);
4634 let lo = self.span.lo;
4635 let pth = try!(self.parse_path(NoTypesAllowed));
4636 try!(self.expect(&token::Not));
4638 // eat a matched-delimiter token tree:
4639 let delim = try!(self.expect_open_delim());
4640 let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
4642 |p| p.parse_token_tree()));
4643 let m_ = Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT };
4644 let m: ast::Mac = codemap::Spanned { node: m_,
4646 self.last_span.hi) };
4647 if delim != token::Brace {
4648 try!(self.expect(&token::Semi))
4650 Ok((token::special_idents::invalid, vec![], ast::ImplItemKind::Macro(m)))
4652 let (constness, unsafety, abi) = try!(self.parse_fn_front_matter());
4653 let ident = try!(self.parse_ident());
4654 let mut generics = try!(self.parse_generics());
4655 let (explicit_self, decl) = try!(self.parse_fn_decl_with_self(|p| {
4658 generics.where_clause = try!(self.parse_where_clause());
4659 let (inner_attrs, body) = try!(self.parse_inner_attrs_and_block());
4660 Ok((ident, inner_attrs, ast::ImplItemKind::Method(ast::MethodSig {
4663 explicit_self: explicit_self,
4665 constness: constness,
4671 /// Parse trait Foo { ... }
4672 fn parse_item_trait(&mut self, unsafety: Unsafety) -> PResult<ItemInfo> {
4674 let ident = try!(self.parse_ident());
4675 let mut tps = try!(self.parse_generics());
4677 // Parse supertrait bounds.
4678 let bounds = try!(self.parse_colon_then_ty_param_bounds(BoundParsingMode::Bare));
4680 tps.where_clause = try!(self.parse_where_clause());
4682 let meths = try!(self.parse_trait_items());
4683 Ok((ident, ItemTrait(unsafety, tps, bounds, meths), None))
4686 /// Parses items implementations variants
4687 /// impl<T> Foo { ... }
4688 /// impl<T> ToString for &'static T { ... }
4689 /// impl Send for .. {}
4690 fn parse_item_impl(&mut self, unsafety: ast::Unsafety) -> PResult<ItemInfo> {
4691 let impl_span = self.span;
4693 // First, parse type parameters if necessary.
4694 let mut generics = try!(self.parse_generics());
4696 // Special case: if the next identifier that follows is '(', don't
4697 // allow this to be parsed as a trait.
4698 let could_be_trait = self.token != token::OpenDelim(token::Paren);
4700 let neg_span = self.span;
4701 let polarity = if try!(self.eat(&token::Not) ){
4702 ast::ImplPolarity::Negative
4704 ast::ImplPolarity::Positive
4708 let mut ty = try!(self.parse_ty_sum());
4710 // Parse traits, if necessary.
4711 let opt_trait = if could_be_trait && try!(self.eat_keyword(keywords::For) ){
4712 // New-style trait. Reinterpret the type as a trait.
4714 TyPath(None, ref path) => {
4716 path: (*path).clone(),
4721 self.span_err(ty.span, "not a trait");
4727 ast::ImplPolarity::Negative => {
4728 // This is a negated type implementation
4729 // `impl !MyType {}`, which is not allowed.
4730 self.span_err(neg_span, "inherent implementation can't be negated");
4737 if opt_trait.is_some() && try!(self.eat(&token::DotDot) ){
4738 if generics.is_parameterized() {
4739 self.span_err(impl_span, "default trait implementations are not \
4740 allowed to have generics");
4743 try!(self.expect(&token::OpenDelim(token::Brace)));
4744 try!(self.expect(&token::CloseDelim(token::Brace)));
4745 Ok((ast_util::impl_pretty_name(&opt_trait, None),
4746 ItemDefaultImpl(unsafety, opt_trait.unwrap()), None))
4748 if opt_trait.is_some() {
4749 ty = try!(self.parse_ty_sum());
4751 generics.where_clause = try!(self.parse_where_clause());
4753 try!(self.expect(&token::OpenDelim(token::Brace)));
4754 let attrs = try!(self.parse_inner_attributes());
4756 let mut impl_items = vec![];
4757 while !try!(self.eat(&token::CloseDelim(token::Brace))) {
4758 impl_items.push(try!(self.parse_impl_item()));
4761 Ok((ast_util::impl_pretty_name(&opt_trait, Some(&*ty)),
4762 ItemImpl(unsafety, polarity, generics, opt_trait, ty, impl_items),
4767 /// Parse a::B<String,i32>
4768 fn parse_trait_ref(&mut self) -> PResult<TraitRef> {
4770 path: try!(self.parse_path(LifetimeAndTypesWithoutColons)),
4771 ref_id: ast::DUMMY_NODE_ID,
4775 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<Vec<ast::LifetimeDef>> {
4776 if try!(self.eat_keyword(keywords::For) ){
4777 try!(self.expect(&token::Lt));
4778 let lifetime_defs = try!(self.parse_lifetime_defs());
4779 try!(self.expect_gt());
4786 /// Parse for<'l> a::B<String,i32>
4787 fn parse_poly_trait_ref(&mut self) -> PResult<PolyTraitRef> {
4788 let lo = self.span.lo;
4789 let lifetime_defs = try!(self.parse_late_bound_lifetime_defs());
4791 Ok(ast::PolyTraitRef {
4792 bound_lifetimes: lifetime_defs,
4793 trait_ref: try!(self.parse_trait_ref()),
4794 span: mk_sp(lo, self.last_span.hi),
4798 /// Parse struct Foo { ... }
4799 fn parse_item_struct(&mut self) -> PResult<ItemInfo> {
4800 let class_name = try!(self.parse_ident());
4801 let mut generics = try!(self.parse_generics());
4803 // There is a special case worth noting here, as reported in issue #17904.
4804 // If we are parsing a tuple struct it is the case that the where clause
4805 // should follow the field list. Like so:
4807 // struct Foo<T>(T) where T: Copy;
4809 // If we are parsing a normal record-style struct it is the case
4810 // that the where clause comes before the body, and after the generics.
4811 // So if we look ahead and see a brace or a where-clause we begin
4812 // parsing a record style struct.
4814 // Otherwise if we look ahead and see a paren we parse a tuple-style
4817 let vdata = if self.token.is_keyword(keywords::Where) {
4818 generics.where_clause = try!(self.parse_where_clause());
4819 if try!(self.eat(&token::Semi)) {
4820 // If we see a: `struct Foo<T> where T: Copy;` style decl.
4821 VariantData::Unit(ast::DUMMY_NODE_ID)
4823 // If we see: `struct Foo<T> where T: Copy { ... }`
4824 VariantData::Struct(try!(self.parse_record_struct_body(ParsePub::Yes)),
4827 // No `where` so: `struct Foo<T>;`
4828 } else if try!(self.eat(&token::Semi) ){
4829 VariantData::Unit(ast::DUMMY_NODE_ID)
4830 // Record-style struct definition
4831 } else if self.token == token::OpenDelim(token::Brace) {
4832 VariantData::Struct(try!(self.parse_record_struct_body(ParsePub::Yes)),
4834 // Tuple-style struct definition with optional where-clause.
4835 } else if self.token == token::OpenDelim(token::Paren) {
4836 let body = VariantData::Tuple(try!(self.parse_tuple_struct_body(ParsePub::Yes)),
4837 ast::DUMMY_NODE_ID);
4838 generics.where_clause = try!(self.parse_where_clause());
4839 try!(self.expect(&token::Semi));
4842 let token_str = self.this_token_to_string();
4843 return Err(self.fatal(&format!("expected `where`, `{{`, `(`, or `;` after struct \
4844 name, found `{}`", token_str)))
4847 Ok((class_name, ItemStruct(vdata, generics), None))
4850 pub fn parse_record_struct_body(&mut self, parse_pub: ParsePub) -> PResult<Vec<StructField>> {
4851 let mut fields = Vec::new();
4852 if try!(self.eat(&token::OpenDelim(token::Brace)) ){
4853 while self.token != token::CloseDelim(token::Brace) {
4854 fields.push(try!(self.parse_struct_decl_field(parse_pub)));
4859 let token_str = self.this_token_to_string();
4860 return Err(self.fatal(&format!("expected `where`, or `{{` after struct \
4868 pub fn parse_tuple_struct_body(&mut self, parse_pub: ParsePub) -> PResult<Vec<StructField>> {
4869 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
4870 // Unit like structs are handled in parse_item_struct function
4871 let fields = try!(self.parse_unspanned_seq(
4872 &token::OpenDelim(token::Paren),
4873 &token::CloseDelim(token::Paren),
4874 seq_sep_trailing_allowed(token::Comma),
4876 let attrs = try!(p.parse_outer_attributes());
4878 let struct_field_ = ast::StructField_ {
4879 kind: UnnamedField (
4880 if parse_pub == ParsePub::Yes {
4881 try!(p.parse_visibility())
4886 id: ast::DUMMY_NODE_ID,
4887 ty: try!(p.parse_ty_sum()),
4890 Ok(spanned(lo, p.span.hi, struct_field_))
4896 /// Parse a structure field declaration
4897 pub fn parse_single_struct_field(&mut self,
4899 attrs: Vec<Attribute> )
4900 -> PResult<StructField> {
4901 let a_var = try!(self.parse_name_and_ty(vis, attrs));
4906 token::CloseDelim(token::Brace) => {}
4908 let span = self.span;
4909 let token_str = self.this_token_to_string();
4910 return Err(self.span_fatal_help(span,
4911 &format!("expected `,`, or `}}`, found `{}`",
4913 "struct fields should be separated by commas"))
4919 /// Parse an element of a struct definition
4920 fn parse_struct_decl_field(&mut self, parse_pub: ParsePub) -> PResult<StructField> {
4922 let attrs = try!(self.parse_outer_attributes());
4924 if try!(self.eat_keyword(keywords::Pub) ){
4925 if parse_pub == ParsePub::No {
4926 let span = self.last_span;
4927 self.span_err(span, "`pub` is not allowed here");
4929 return self.parse_single_struct_field(Public, attrs);
4932 return self.parse_single_struct_field(Inherited, attrs);
4935 /// Parse visibility: PUB or nothing
4936 fn parse_visibility(&mut self) -> PResult<Visibility> {
4937 if try!(self.eat_keyword(keywords::Pub)) { Ok(Public) }
4938 else { Ok(Inherited) }
4941 /// Given a termination token, parse all of the items in a module
4942 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: BytePos) -> PResult<Mod> {
4943 let mut items = vec![];
4944 while let Some(item) = try!(self.parse_item()) {
4948 if !try!(self.eat(term)) {
4949 let token_str = self.this_token_to_string();
4950 return Err(self.fatal(&format!("expected item, found `{}`", token_str)));
4953 let hi = if self.span == codemap::DUMMY_SP {
4960 inner: mk_sp(inner_lo, hi),
4965 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<ItemInfo> {
4966 let id = try!(self.parse_ident());
4967 try!(self.expect(&token::Colon));
4968 let ty = try!(self.parse_ty_sum());
4969 try!(self.expect(&token::Eq));
4970 let e = try!(self.parse_expr());
4971 try!(self.commit_expr_expecting(&*e, token::Semi));
4972 let item = match m {
4973 Some(m) => ItemStatic(ty, m, e),
4974 None => ItemConst(ty, e),
4976 Ok((id, item, None))
4979 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
4980 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<ItemInfo> {
4981 let id_span = self.span;
4982 let id = try!(self.parse_ident());
4983 if self.check(&token::Semi) {
4985 // This mod is in an external file. Let's go get it!
4986 let (m, attrs) = try!(self.eval_src_mod(id, outer_attrs, id_span));
4987 Ok((id, m, Some(attrs)))
4989 self.push_mod_path(id, outer_attrs);
4990 try!(self.expect(&token::OpenDelim(token::Brace)));
4991 let mod_inner_lo = self.span.lo;
4992 let old_owns_directory = self.owns_directory;
4993 self.owns_directory = true;
4994 let attrs = try!(self.parse_inner_attributes());
4995 let m = try!(self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo));
4996 self.owns_directory = old_owns_directory;
4997 self.pop_mod_path();
4998 Ok((id, ItemMod(m), Some(attrs)))
5002 fn push_mod_path(&mut self, id: Ident, attrs: &[Attribute]) {
5003 let default_path = self.id_to_interned_str(id);
5004 let file_path = match ::attr::first_attr_value_str_by_name(attrs, "path") {
5006 None => default_path,
5008 self.mod_path_stack.push(file_path)
5011 fn pop_mod_path(&mut self) {
5012 self.mod_path_stack.pop().unwrap();
5015 pub fn submod_path_from_attr(attrs: &[ast::Attribute], dir_path: &Path) -> Option<PathBuf> {
5016 ::attr::first_attr_value_str_by_name(attrs, "path").map(|d| dir_path.join(&*d))
5019 /// Returns either a path to a module, or .
5020 pub fn default_submod_path(id: ast::Ident, dir_path: &Path, codemap: &CodeMap) -> ModulePath
5022 let mod_name = id.to_string();
5023 let default_path_str = format!("{}.rs", mod_name);
5024 let secondary_path_str = format!("{}/mod.rs", mod_name);
5025 let default_path = dir_path.join(&default_path_str);
5026 let secondary_path = dir_path.join(&secondary_path_str);
5027 let default_exists = codemap.file_exists(&default_path);
5028 let secondary_exists = codemap.file_exists(&secondary_path);
5030 let result = match (default_exists, secondary_exists) {
5031 (true, false) => Ok(ModulePathSuccess { path: default_path, owns_directory: false }),
5032 (false, true) => Ok(ModulePathSuccess { path: secondary_path, owns_directory: true }),
5033 (false, false) => Err(ModulePathError {
5034 err_msg: format!("file not found for module `{}`", mod_name),
5035 help_msg: format!("name the file either {} or {} inside the directory {:?}",
5038 dir_path.display()),
5040 (true, true) => Err(ModulePathError {
5041 err_msg: format!("file for module `{}` found at both {} and {}",
5044 secondary_path_str),
5045 help_msg: "delete or rename one of them to remove the ambiguity".to_owned(),
5051 path_exists: default_exists || secondary_exists,
5056 fn submod_path(&mut self,
5058 outer_attrs: &[ast::Attribute],
5059 id_sp: Span) -> PResult<ModulePathSuccess> {
5060 let mut prefix = PathBuf::from(&self.sess.codemap().span_to_filename(self.span));
5062 let mut dir_path = prefix;
5063 for part in &self.mod_path_stack {
5064 dir_path.push(&**part);
5067 if let Some(p) = Parser::submod_path_from_attr(outer_attrs, &dir_path) {
5068 return Ok(ModulePathSuccess { path: p, owns_directory: true });
5071 let paths = Parser::default_submod_path(id, &dir_path, self.sess.codemap());
5073 if !self.owns_directory {
5074 self.span_err(id_sp, "cannot declare a new module at this location");
5075 let this_module = match self.mod_path_stack.last() {
5076 Some(name) => name.to_string(),
5077 None => self.root_module_name.as_ref().unwrap().clone(),
5079 self.span_note(id_sp,
5080 &format!("maybe move this module `{0}` to its own directory \
5083 if paths.path_exists {
5084 self.span_note(id_sp,
5085 &format!("... or maybe `use` the module `{}` instead \
5086 of possibly redeclaring it",
5089 self.abort_if_errors();
5092 match paths.result {
5093 Ok(succ) => Ok(succ),
5094 Err(err) => Err(self.span_fatal_help(id_sp, &err.err_msg, &err.help_msg)),
5098 /// Read a module from a source file.
5099 fn eval_src_mod(&mut self,
5101 outer_attrs: &[ast::Attribute],
5103 -> PResult<(ast::Item_, Vec<ast::Attribute> )> {
5104 let ModulePathSuccess { path, owns_directory } = try!(self.submod_path(id,
5108 self.eval_src_mod_from_path(path,
5114 fn eval_src_mod_from_path(&mut self,
5116 owns_directory: bool,
5118 id_sp: Span) -> PResult<(ast::Item_, Vec<ast::Attribute> )> {
5119 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
5120 match included_mod_stack.iter().position(|p| *p == path) {
5122 let mut err = String::from("circular modules: ");
5123 let len = included_mod_stack.len();
5124 for p in &included_mod_stack[i.. len] {
5125 err.push_str(&p.to_string_lossy());
5126 err.push_str(" -> ");
5128 err.push_str(&path.to_string_lossy());
5129 return Err(self.span_fatal(id_sp, &err[..]));
5133 included_mod_stack.push(path.clone());
5134 drop(included_mod_stack);
5136 let mut p0 = new_sub_parser_from_file(self.sess,
5142 let mod_inner_lo = p0.span.lo;
5143 let mod_attrs = try!(p0.parse_inner_attributes());
5144 let m0 = try!(p0.parse_mod_items(&token::Eof, mod_inner_lo));
5145 self.sess.included_mod_stack.borrow_mut().pop();
5146 Ok((ast::ItemMod(m0), mod_attrs))
5149 /// Parse a function declaration from a foreign module
5150 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: BytePos,
5151 attrs: Vec<Attribute>) -> PResult<P<ForeignItem>> {
5152 try!(self.expect_keyword(keywords::Fn));
5154 let (ident, mut generics) = try!(self.parse_fn_header());
5155 let decl = try!(self.parse_fn_decl(true));
5156 generics.where_clause = try!(self.parse_where_clause());
5157 let hi = self.span.hi;
5158 try!(self.expect(&token::Semi));
5159 Ok(P(ast::ForeignItem {
5162 node: ForeignItemFn(decl, generics),
5163 id: ast::DUMMY_NODE_ID,
5164 span: mk_sp(lo, hi),
5169 /// Parse a static item from a foreign module
5170 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: BytePos,
5171 attrs: Vec<Attribute>) -> PResult<P<ForeignItem>> {
5172 try!(self.expect_keyword(keywords::Static));
5173 let mutbl = try!(self.eat_keyword(keywords::Mut));
5175 let ident = try!(self.parse_ident());
5176 try!(self.expect(&token::Colon));
5177 let ty = try!(self.parse_ty_sum());
5178 let hi = self.span.hi;
5179 try!(self.expect(&token::Semi));
5183 node: ForeignItemStatic(ty, mutbl),
5184 id: ast::DUMMY_NODE_ID,
5185 span: mk_sp(lo, hi),
5190 /// Parse extern crate links
5194 /// extern crate foo;
5195 /// extern crate bar as foo;
5196 fn parse_item_extern_crate(&mut self,
5198 visibility: Visibility,
5199 attrs: Vec<Attribute>)
5200 -> PResult<P<Item>> {
5202 let crate_name = try!(self.parse_ident());
5203 let (maybe_path, ident) = if let Some(ident) = try!(self.parse_rename()) {
5204 (Some(crate_name.name), ident)
5208 try!(self.expect(&token::Semi));
5210 let last_span = self.last_span;
5212 if visibility == ast::Public {
5213 self.span_warn(mk_sp(lo, last_span.hi),
5214 "`pub extern crate` does not work as expected and should not be used. \
5215 Likely to become an error. Prefer `extern crate` and `pub use`.");
5221 ItemExternCrate(maybe_path),
5226 /// Parse `extern` for foreign ABIs
5229 /// `extern` is expected to have been
5230 /// consumed before calling this method
5236 fn parse_item_foreign_mod(&mut self,
5238 opt_abi: Option<abi::Abi>,
5239 visibility: Visibility,
5240 mut attrs: Vec<Attribute>)
5241 -> PResult<P<Item>> {
5242 try!(self.expect(&token::OpenDelim(token::Brace)));
5244 let abi = opt_abi.unwrap_or(abi::C);
5246 attrs.extend(try!(self.parse_inner_attributes()));
5248 let mut foreign_items = vec![];
5249 while let Some(item) = try!(self.parse_foreign_item()) {
5250 foreign_items.push(item);
5252 try!(self.expect(&token::CloseDelim(token::Brace)));
5254 let last_span = self.last_span;
5255 let m = ast::ForeignMod {
5257 items: foreign_items
5261 special_idents::invalid,
5267 /// Parse type Foo = Bar;
5268 fn parse_item_type(&mut self) -> PResult<ItemInfo> {
5269 let ident = try!(self.parse_ident());
5270 let mut tps = try!(self.parse_generics());
5271 tps.where_clause = try!(self.parse_where_clause());
5272 try!(self.expect(&token::Eq));
5273 let ty = try!(self.parse_ty_sum());
5274 try!(self.expect(&token::Semi));
5275 Ok((ident, ItemTy(ty, tps), None))
5278 /// Parse the part of an "enum" decl following the '{'
5279 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<EnumDef> {
5280 let mut variants = Vec::new();
5281 let mut all_nullary = true;
5282 let mut any_disr = None;
5283 while self.token != token::CloseDelim(token::Brace) {
5284 let variant_attrs = try!(self.parse_outer_attributes());
5285 let vlo = self.span.lo;
5288 let mut disr_expr = None;
5289 let ident = try!(self.parse_ident());
5290 if self.check(&token::OpenDelim(token::Brace)) {
5291 // Parse a struct variant.
5292 all_nullary = false;
5293 struct_def = VariantData::Struct(try!(self.parse_record_struct_body(ParsePub::No)),
5294 ast::DUMMY_NODE_ID);
5295 } else if self.check(&token::OpenDelim(token::Paren)) {
5296 all_nullary = false;
5297 struct_def = VariantData::Tuple(try!(self.parse_tuple_struct_body(ParsePub::No)),
5298 ast::DUMMY_NODE_ID);
5299 } else if try!(self.eat(&token::Eq) ){
5300 disr_expr = Some(try!(self.parse_expr()));
5301 any_disr = disr_expr.as_ref().map(|expr| expr.span);
5302 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5304 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5307 let vr = ast::Variant_ {
5309 attrs: variant_attrs,
5311 disr_expr: disr_expr,
5313 variants.push(P(spanned(vlo, self.last_span.hi, vr)));
5315 if !try!(self.eat(&token::Comma)) { break; }
5317 try!(self.expect(&token::CloseDelim(token::Brace)));
5319 Some(disr_span) if !all_nullary =>
5320 self.span_err(disr_span,
5321 "discriminator values can only be used with a c-like enum"),
5325 Ok(ast::EnumDef { variants: variants })
5328 /// Parse an "enum" declaration
5329 fn parse_item_enum(&mut self) -> PResult<ItemInfo> {
5330 let id = try!(self.parse_ident());
5331 let mut generics = try!(self.parse_generics());
5332 generics.where_clause = try!(self.parse_where_clause());
5333 try!(self.expect(&token::OpenDelim(token::Brace)));
5335 let enum_definition = try!(self.parse_enum_def(&generics));
5336 Ok((id, ItemEnum(enum_definition, generics), None))
5339 /// Parses a string as an ABI spec on an extern type or module. Consumes
5340 /// the `extern` keyword, if one is found.
5341 fn parse_opt_abi(&mut self) -> PResult<Option<abi::Abi>> {
5343 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
5345 self.expect_no_suffix(sp, "ABI spec", suf);
5347 match abi::lookup(&s.as_str()) {
5348 Some(abi) => Ok(Some(abi)),
5350 let last_span = self.last_span;
5353 &format!("invalid ABI: expected one of [{}], \
5355 abi::all_names().join(", "),
5366 /// Parse one of the items allowed by the flags.
5367 /// NB: this function no longer parses the items inside an
5369 fn parse_item_(&mut self, attrs: Vec<Attribute>,
5370 macros_allowed: bool, attributes_allowed: bool) -> PResult<Option<P<Item>>> {
5371 let nt_item = match self.token {
5372 token::Interpolated(token::NtItem(ref item)) => {
5373 Some((**item).clone())
5380 let mut attrs = attrs;
5381 mem::swap(&mut item.attrs, &mut attrs);
5382 item.attrs.extend(attrs);
5383 return Ok(Some(P(item)));
5388 let lo = self.span.lo;
5390 let visibility = try!(self.parse_visibility());
5392 if try!(self.eat_keyword(keywords::Use) ){
5394 let item_ = ItemUse(try!(self.parse_view_path()));
5395 try!(self.expect(&token::Semi));
5397 let last_span = self.last_span;
5398 let item = self.mk_item(lo,
5400 token::special_idents::invalid,
5404 return Ok(Some(item));
5407 if try!(self.eat_keyword(keywords::Extern)) {
5408 if try!(self.eat_keyword(keywords::Crate)) {
5409 return Ok(Some(try!(self.parse_item_extern_crate(lo, visibility, attrs))));
5412 let opt_abi = try!(self.parse_opt_abi());
5414 if try!(self.eat_keyword(keywords::Fn) ){
5415 // EXTERN FUNCTION ITEM
5416 let abi = opt_abi.unwrap_or(abi::C);
5417 let (ident, item_, extra_attrs) =
5418 try!(self.parse_item_fn(Unsafety::Normal, Constness::NotConst, abi));
5419 let last_span = self.last_span;
5420 let item = self.mk_item(lo,
5425 maybe_append(attrs, extra_attrs));
5426 return Ok(Some(item));
5427 } else if self.check(&token::OpenDelim(token::Brace)) {
5428 return Ok(Some(try!(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs))));
5431 try!(self.expect_one_of(&[], &[]));
5434 if try!(self.eat_keyword(keywords::Static) ){
5436 let m = if try!(self.eat_keyword(keywords::Mut)) {MutMutable} else {MutImmutable};
5437 let (ident, item_, extra_attrs) = try!(self.parse_item_const(Some(m)));
5438 let last_span = self.last_span;
5439 let item = self.mk_item(lo,
5444 maybe_append(attrs, extra_attrs));
5445 return Ok(Some(item));
5447 if try!(self.eat_keyword(keywords::Const) ){
5448 if self.check_keyword(keywords::Fn)
5449 || (self.check_keyword(keywords::Unsafe)
5450 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
5451 // CONST FUNCTION ITEM
5452 let unsafety = if try!(self.eat_keyword(keywords::Unsafe) ){
5458 let (ident, item_, extra_attrs) =
5459 try!(self.parse_item_fn(unsafety, Constness::Const, abi::Rust));
5460 let last_span = self.last_span;
5461 let item = self.mk_item(lo,
5466 maybe_append(attrs, extra_attrs));
5467 return Ok(Some(item));
5471 if try!(self.eat_keyword(keywords::Mut) ){
5472 let last_span = self.last_span;
5473 self.span_err(last_span, "const globals cannot be mutable");
5474 self.fileline_help(last_span, "did you mean to declare a static?");
5476 let (ident, item_, extra_attrs) = try!(self.parse_item_const(None));
5477 let last_span = self.last_span;
5478 let item = self.mk_item(lo,
5483 maybe_append(attrs, extra_attrs));
5484 return Ok(Some(item));
5486 if self.check_keyword(keywords::Unsafe) &&
5487 self.look_ahead(1, |t| t.is_keyword(keywords::Trait))
5489 // UNSAFE TRAIT ITEM
5490 try!(self.expect_keyword(keywords::Unsafe));
5491 try!(self.expect_keyword(keywords::Trait));
5492 let (ident, item_, extra_attrs) =
5493 try!(self.parse_item_trait(ast::Unsafety::Unsafe));
5494 let last_span = self.last_span;
5495 let item = self.mk_item(lo,
5500 maybe_append(attrs, extra_attrs));
5501 return Ok(Some(item));
5503 if self.check_keyword(keywords::Unsafe) &&
5504 self.look_ahead(1, |t| t.is_keyword(keywords::Impl))
5507 try!(self.expect_keyword(keywords::Unsafe));
5508 try!(self.expect_keyword(keywords::Impl));
5509 let (ident, item_, extra_attrs) = try!(self.parse_item_impl(ast::Unsafety::Unsafe));
5510 let last_span = self.last_span;
5511 let item = self.mk_item(lo,
5516 maybe_append(attrs, extra_attrs));
5517 return Ok(Some(item));
5519 if self.check_keyword(keywords::Fn) {
5522 let (ident, item_, extra_attrs) =
5523 try!(self.parse_item_fn(Unsafety::Normal, Constness::NotConst, abi::Rust));
5524 let last_span = self.last_span;
5525 let item = self.mk_item(lo,
5530 maybe_append(attrs, extra_attrs));
5531 return Ok(Some(item));
5533 if self.check_keyword(keywords::Unsafe)
5534 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
5535 // UNSAFE FUNCTION ITEM
5537 let abi = if try!(self.eat_keyword(keywords::Extern) ){
5538 try!(self.parse_opt_abi()).unwrap_or(abi::C)
5542 try!(self.expect_keyword(keywords::Fn));
5543 let (ident, item_, extra_attrs) =
5544 try!(self.parse_item_fn(Unsafety::Unsafe, Constness::NotConst, abi));
5545 let last_span = self.last_span;
5546 let item = self.mk_item(lo,
5551 maybe_append(attrs, extra_attrs));
5552 return Ok(Some(item));
5554 if try!(self.eat_keyword(keywords::Mod) ){
5556 let (ident, item_, extra_attrs) =
5557 try!(self.parse_item_mod(&attrs[..]));
5558 let last_span = self.last_span;
5559 let item = self.mk_item(lo,
5564 maybe_append(attrs, extra_attrs));
5565 return Ok(Some(item));
5567 if try!(self.eat_keyword(keywords::Type) ){
5569 let (ident, item_, extra_attrs) = try!(self.parse_item_type());
5570 let last_span = self.last_span;
5571 let item = self.mk_item(lo,
5576 maybe_append(attrs, extra_attrs));
5577 return Ok(Some(item));
5579 if try!(self.eat_keyword(keywords::Enum) ){
5581 let (ident, item_, extra_attrs) = try!(self.parse_item_enum());
5582 let last_span = self.last_span;
5583 let item = self.mk_item(lo,
5588 maybe_append(attrs, extra_attrs));
5589 return Ok(Some(item));
5591 if try!(self.eat_keyword(keywords::Trait) ){
5593 let (ident, item_, extra_attrs) =
5594 try!(self.parse_item_trait(ast::Unsafety::Normal));
5595 let last_span = self.last_span;
5596 let item = self.mk_item(lo,
5601 maybe_append(attrs, extra_attrs));
5602 return Ok(Some(item));
5604 if try!(self.eat_keyword(keywords::Impl) ){
5606 let (ident, item_, extra_attrs) = try!(self.parse_item_impl(ast::Unsafety::Normal));
5607 let last_span = self.last_span;
5608 let item = self.mk_item(lo,
5613 maybe_append(attrs, extra_attrs));
5614 return Ok(Some(item));
5616 if try!(self.eat_keyword(keywords::Struct) ){
5618 let (ident, item_, extra_attrs) = try!(self.parse_item_struct());
5619 let last_span = self.last_span;
5620 let item = self.mk_item(lo,
5625 maybe_append(attrs, extra_attrs));
5626 return Ok(Some(item));
5628 self.parse_macro_use_or_failure(attrs,macros_allowed,attributes_allowed,lo,visibility)
5631 /// Parse a foreign item.
5632 fn parse_foreign_item(&mut self) -> PResult<Option<P<ForeignItem>>> {
5633 let attrs = try!(self.parse_outer_attributes());
5634 let lo = self.span.lo;
5635 let visibility = try!(self.parse_visibility());
5637 if self.check_keyword(keywords::Static) {
5638 // FOREIGN STATIC ITEM
5639 return Ok(Some(try!(self.parse_item_foreign_static(visibility, lo, attrs))));
5641 if self.check_keyword(keywords::Fn) || self.check_keyword(keywords::Unsafe) {
5642 // FOREIGN FUNCTION ITEM
5643 return Ok(Some(try!(self.parse_item_foreign_fn(visibility, lo, attrs))));
5646 // FIXME #5668: this will occur for a macro invocation:
5647 match try!(self.parse_macro_use_or_failure(attrs, true, false, lo, visibility)) {
5649 return Err(self.span_fatal(item.span, "macros cannot expand to foreign items"));
5655 /// This is the fall-through for parsing items.
5656 fn parse_macro_use_or_failure(
5658 attrs: Vec<Attribute> ,
5659 macros_allowed: bool,
5660 attributes_allowed: bool,
5662 visibility: Visibility
5663 ) -> PResult<Option<P<Item>>> {
5664 if macros_allowed && !self.token.is_any_keyword()
5665 && self.look_ahead(1, |t| *t == token::Not)
5666 && (self.look_ahead(2, |t| t.is_plain_ident())
5667 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren))
5668 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) {
5669 // MACRO INVOCATION ITEM
5671 let last_span = self.last_span;
5672 self.complain_if_pub_macro(visibility, last_span);
5674 let mac_lo = self.span.lo;
5677 let pth = try!(self.parse_path(NoTypesAllowed));
5678 try!(self.expect(&token::Not));
5680 // a 'special' identifier (like what `macro_rules!` uses)
5681 // is optional. We should eventually unify invoc syntax
5683 let id = if self.token.is_plain_ident() {
5684 try!(self.parse_ident())
5686 token::special_idents::invalid // no special identifier
5688 // eat a matched-delimiter token tree:
5689 let delim = try!(self.expect_open_delim());
5690 let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
5692 |p| p.parse_token_tree()));
5693 // single-variant-enum... :
5694 let m = Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT };
5695 let m: ast::Mac = codemap::Spanned { node: m,
5697 self.last_span.hi) };
5699 if delim != token::Brace {
5700 if !try!(self.eat(&token::Semi) ){
5701 let last_span = self.last_span;
5702 self.span_err(last_span,
5703 "macros that expand to items must either \
5704 be surrounded with braces or followed by \
5709 let item_ = ItemMac(m);
5710 let last_span = self.last_span;
5711 let item = self.mk_item(lo,
5717 return Ok(Some(item));
5720 // FAILURE TO PARSE ITEM
5724 let last_span = self.last_span;
5725 return Err(self.span_fatal(last_span, "unmatched visibility `pub`"));
5729 if !attributes_allowed && !attrs.is_empty() {
5730 self.expected_item_err(&attrs);
5735 pub fn parse_item(&mut self) -> PResult<Option<P<Item>>> {
5736 let attrs = try!(self.parse_outer_attributes());
5737 self.parse_item_(attrs, true, false)
5741 /// Matches view_path : MOD? non_global_path as IDENT
5742 /// | MOD? non_global_path MOD_SEP LBRACE RBRACE
5743 /// | MOD? non_global_path MOD_SEP LBRACE ident_seq RBRACE
5744 /// | MOD? non_global_path MOD_SEP STAR
5745 /// | MOD? non_global_path
5746 fn parse_view_path(&mut self) -> PResult<P<ViewPath>> {
5747 let lo = self.span.lo;
5749 // Allow a leading :: because the paths are absolute either way.
5750 // This occurs with "use $crate::..." in macros.
5751 try!(self.eat(&token::ModSep));
5753 if self.check(&token::OpenDelim(token::Brace)) {
5755 let idents = try!(self.parse_unspanned_seq(
5756 &token::OpenDelim(token::Brace),
5757 &token::CloseDelim(token::Brace),
5758 seq_sep_trailing_allowed(token::Comma),
5759 |p| p.parse_path_list_item()));
5760 let path = ast::Path {
5761 span: mk_sp(lo, self.span.hi),
5763 segments: Vec::new()
5765 return Ok(P(spanned(lo, self.span.hi, ViewPathList(path, idents))));
5768 let first_ident = try!(self.parse_ident());
5769 let mut path = vec!(first_ident);
5770 if let token::ModSep = self.token {
5771 // foo::bar or foo::{a,b,c} or foo::*
5772 while self.check(&token::ModSep) {
5776 token::Ident(..) => {
5777 let ident = try!(self.parse_ident());
5781 // foo::bar::{a,b,c}
5782 token::OpenDelim(token::Brace) => {
5783 let idents = try!(self.parse_unspanned_seq(
5784 &token::OpenDelim(token::Brace),
5785 &token::CloseDelim(token::Brace),
5786 seq_sep_trailing_allowed(token::Comma),
5787 |p| p.parse_path_list_item()
5789 let path = ast::Path {
5790 span: mk_sp(lo, self.span.hi),
5792 segments: path.into_iter().map(|identifier| {
5794 identifier: identifier,
5795 parameters: ast::PathParameters::none(),
5799 return Ok(P(spanned(lo, self.span.hi, ViewPathList(path, idents))));
5803 token::BinOp(token::Star) => {
5805 let path = ast::Path {
5806 span: mk_sp(lo, self.span.hi),
5808 segments: path.into_iter().map(|identifier| {
5810 identifier: identifier,
5811 parameters: ast::PathParameters::none(),
5815 return Ok(P(spanned(lo, self.span.hi, ViewPathGlob(path))));
5818 // fall-through for case foo::bar::;
5820 self.span_err(self.span, "expected identifier or `{` or `*`, found `;`");
5827 let mut rename_to = path[path.len() - 1];
5828 let path = ast::Path {
5829 span: mk_sp(lo, self.last_span.hi),
5831 segments: path.into_iter().map(|identifier| {
5833 identifier: identifier,
5834 parameters: ast::PathParameters::none(),
5838 rename_to = try!(self.parse_rename()).unwrap_or(rename_to);
5839 Ok(P(spanned(lo, self.last_span.hi, ViewPathSimple(rename_to, path))))
5842 fn parse_rename(&mut self) -> PResult<Option<Ident>> {
5843 if try!(self.eat_keyword(keywords::As)) {
5844 self.parse_ident().map(Some)
5850 /// Parses a source module as a crate. This is the main
5851 /// entry point for the parser.
5852 pub fn parse_crate_mod(&mut self) -> PResult<Crate> {
5853 let lo = self.span.lo;
5855 attrs: try!(self.parse_inner_attributes()),
5856 module: try!(self.parse_mod_items(&token::Eof, lo)),
5857 config: self.cfg.clone(),
5858 span: mk_sp(lo, self.span.lo),
5859 exported_macros: Vec::new(),
5863 pub fn parse_optional_str(&mut self)
5864 -> PResult<Option<(InternedString,
5866 Option<ast::Name>)>> {
5867 let ret = match self.token {
5868 token::Literal(token::Str_(s), suf) => {
5869 (self.id_to_interned_str(ast::Ident::with_empty_ctxt(s)), ast::CookedStr, suf)
5871 token::Literal(token::StrRaw(s, n), suf) => {
5872 (self.id_to_interned_str(ast::Ident::with_empty_ctxt(s)), ast::RawStr(n), suf)
5874 _ => return Ok(None)
5880 pub fn parse_str(&mut self) -> PResult<(InternedString, StrStyle)> {
5881 match try!(self.parse_optional_str()) {
5882 Some((s, style, suf)) => {
5883 let sp = self.last_span;
5884 self.expect_no_suffix(sp, "string literal", suf);
5887 _ => Err(self.fatal("expected string literal"))