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, ExprType, 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, TyParamBounds, 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};
63 use errors::{self, FatalError};
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};
78 use std::collections::HashSet;
79 use std::io::prelude::*;
81 use std::path::{Path, PathBuf};
86 flags Restrictions: u8 {
87 const RESTRICTION_STMT_EXPR = 1 << 0,
88 const RESTRICTION_NO_STRUCT_LITERAL = 1 << 1,
92 type ItemInfo = (Ident, Item_, Option<Vec<Attribute> >);
94 /// How to parse a path. There are four different kinds of paths, all of which
95 /// are parsed somewhat differently.
96 #[derive(Copy, Clone, PartialEq)]
97 pub enum PathParsingMode {
98 /// A path with no type parameters; e.g. `foo::bar::Baz`
100 /// A path with a lifetime and type parameters, with no double colons
101 /// before the type parameters; e.g. `foo::bar<'a>::Baz<T>`
102 LifetimeAndTypesWithoutColons,
103 /// A path with a lifetime and type parameters with double colons before
104 /// the type parameters; e.g. `foo::bar::<'a>::Baz::<T>`
105 LifetimeAndTypesWithColons,
108 /// How to parse a bound, whether to allow bound modifiers such as `?`.
109 #[derive(Copy, Clone, PartialEq)]
110 pub enum BoundParsingMode {
115 /// `pub` should be parsed in struct fields and not parsed in variant fields
116 #[derive(Clone, Copy, PartialEq)]
122 /// Possibly accept an `token::Interpolated` expression (a pre-parsed expression
123 /// dropped into the token stream, which happens while parsing the result of
124 /// macro expansion). Placement of these is not as complex as I feared it would
125 /// be. The important thing is to make sure that lookahead doesn't balk at
126 /// `token::Interpolated` tokens.
127 macro_rules! maybe_whole_expr {
130 let found = match $p.token {
131 token::Interpolated(token::NtExpr(ref e)) => {
134 token::Interpolated(token::NtPath(_)) => {
135 // FIXME: The following avoids an issue with lexical borrowck scopes,
136 // but the clone is unfortunate.
137 let pt = match $p.token {
138 token::Interpolated(token::NtPath(ref pt)) => (**pt).clone(),
142 Some($p.mk_expr(span.lo, span.hi, ExprPath(None, pt), None))
144 token::Interpolated(token::NtBlock(_)) => {
145 // FIXME: The following avoids an issue with lexical borrowck scopes,
146 // but the clone is unfortunate.
147 let b = match $p.token {
148 token::Interpolated(token::NtBlock(ref b)) => (*b).clone(),
152 Some($p.mk_expr(span.lo, span.hi, ExprBlock(b), None))
167 /// As maybe_whole_expr, but for things other than expressions
168 macro_rules! maybe_whole {
169 ($p:expr, $constructor:ident) => (
171 let found = match ($p).token {
172 token::Interpolated(token::$constructor(_)) => {
173 Some(try!(($p).bump_and_get()))
177 if let Some(token::Interpolated(token::$constructor(x))) = found {
178 return Ok(x.clone());
182 (no_clone $p:expr, $constructor:ident) => (
184 let found = match ($p).token {
185 token::Interpolated(token::$constructor(_)) => {
186 Some(try!(($p).bump_and_get()))
190 if let Some(token::Interpolated(token::$constructor(x))) = found {
195 (deref $p:expr, $constructor:ident) => (
197 let found = match ($p).token {
198 token::Interpolated(token::$constructor(_)) => {
199 Some(try!(($p).bump_and_get()))
203 if let Some(token::Interpolated(token::$constructor(x))) = found {
204 return Ok((*x).clone());
208 (Some deref $p:expr, $constructor:ident) => (
210 let found = match ($p).token {
211 token::Interpolated(token::$constructor(_)) => {
212 Some(try!(($p).bump_and_get()))
216 if let Some(token::Interpolated(token::$constructor(x))) = found {
217 return Ok(Some((*x).clone()));
221 (pair_empty $p:expr, $constructor:ident) => (
223 let found = match ($p).token {
224 token::Interpolated(token::$constructor(_)) => {
225 Some(try!(($p).bump_and_get()))
229 if let Some(token::Interpolated(token::$constructor(x))) = found {
230 return Ok((Vec::new(), x));
237 fn maybe_append(mut lhs: Vec<Attribute>, rhs: Option<Vec<Attribute>>)
239 if let Some(ref attrs) = rhs {
240 lhs.extend(attrs.iter().cloned())
245 /* ident is handled by common.rs */
247 pub struct Parser<'a> {
248 pub sess: &'a ParseSess,
249 /// the current token:
250 pub token: token::Token,
251 /// the span of the current token:
253 /// the span of the prior token:
255 pub cfg: CrateConfig,
256 /// the previous token or None (only stashed sometimes).
257 pub last_token: Option<Box<token::Token>>,
258 pub buffer: [TokenAndSpan; 4],
259 pub buffer_start: isize,
260 pub buffer_end: isize,
261 pub tokens_consumed: usize,
262 pub restrictions: Restrictions,
263 pub quote_depth: usize, // not (yet) related to the quasiquoter
264 pub reader: Box<Reader+'a>,
265 pub interner: Rc<token::IdentInterner>,
266 /// The set of seen errors about obsolete syntax. Used to suppress
267 /// extra detail when the same error is seen twice
268 pub obsolete_set: HashSet<ObsoleteSyntax>,
269 /// Used to determine the path to externally loaded source files
270 pub mod_path_stack: Vec<InternedString>,
271 /// Stack of spans of open delimiters. Used for error message.
272 pub open_braces: Vec<Span>,
273 /// Flag if this parser "owns" the directory that it is currently parsing
274 /// in. This will affect how nested files are looked up.
275 pub owns_directory: bool,
276 /// Name of the root module this parser originated from. If `None`, then the
277 /// name is not known. This does not change while the parser is descending
278 /// into modules, and sub-parsers have new values for this name.
279 pub root_module_name: Option<String>,
280 pub expected_tokens: Vec<TokenType>,
283 #[derive(PartialEq, Eq, Clone)]
286 Keyword(keywords::Keyword),
291 fn to_string(&self) -> String {
293 TokenType::Token(ref t) => format!("`{}`", Parser::token_to_string(t)),
294 TokenType::Operator => "an operator".to_string(),
295 TokenType::Keyword(kw) => format!("`{}`", kw.to_name()),
300 fn is_plain_ident_or_underscore(t: &token::Token) -> bool {
301 t.is_plain_ident() || *t == token::Underscore
304 /// Information about the path to a module.
305 pub struct ModulePath {
307 pub path_exists: bool,
308 pub result: Result<ModulePathSuccess, ModulePathError>,
311 pub struct ModulePathSuccess {
312 pub path: ::std::path::PathBuf,
313 pub owns_directory: bool,
316 pub struct ModulePathError {
318 pub help_msg: String,
323 AttributesParsed(ThinAttributes),
324 AlreadyParsed(P<Expr>),
327 impl From<Option<ThinAttributes>> for LhsExpr {
328 fn from(o: Option<ThinAttributes>) -> Self {
329 if let Some(attrs) = o {
330 LhsExpr::AttributesParsed(attrs)
332 LhsExpr::NotYetParsed
337 impl From<P<Expr>> for LhsExpr {
338 fn from(expr: P<Expr>) -> Self {
339 LhsExpr::AlreadyParsed(expr)
343 impl<'a> Parser<'a> {
344 pub fn new(sess: &'a ParseSess,
345 cfg: ast::CrateConfig,
346 mut rdr: Box<Reader+'a>)
349 let tok0 = rdr.real_token();
351 let placeholder = TokenAndSpan {
352 tok: token::Underscore,
358 interner: token::get_ident_interner(),
374 restrictions: Restrictions::empty(),
376 obsolete_set: HashSet::new(),
377 mod_path_stack: Vec::new(),
378 open_braces: Vec::new(),
379 owns_directory: true,
380 root_module_name: None,
381 expected_tokens: Vec::new(),
385 /// Convert a token to a string using self's reader
386 pub fn token_to_string(token: &token::Token) -> String {
387 pprust::token_to_string(token)
390 /// Convert the current token to a string using self's reader
391 pub fn this_token_to_string(&self) -> String {
392 Parser::token_to_string(&self.token)
395 pub fn unexpected_last(&self, t: &token::Token) -> FatalError {
396 let token_str = Parser::token_to_string(t);
397 let last_span = self.last_span;
398 self.span_fatal(last_span, &format!("unexpected token: `{}`",
402 pub fn unexpected(&mut self) -> FatalError {
403 match self.expect_one_of(&[], &[]) {
405 Ok(_) => unreachable!()
409 /// Expect and consume the token t. Signal an error if
410 /// the next token is not t.
411 pub fn expect(&mut self, t: &token::Token) -> PResult<()> {
412 if self.expected_tokens.is_empty() {
413 if self.token == *t {
416 let token_str = Parser::token_to_string(t);
417 let this_token_str = self.this_token_to_string();
418 Err(self.fatal(&format!("expected `{}`, found `{}`",
423 self.expect_one_of(unsafe { slice::from_raw_parts(t, 1) }, &[])
427 /// Expect next token to be edible or inedible token. If edible,
428 /// then consume it; if inedible, then return without consuming
429 /// anything. Signal a fatal error if next token is unexpected.
430 pub fn expect_one_of(&mut self,
431 edible: &[token::Token],
432 inedible: &[token::Token]) -> PResult<()>{
433 fn tokens_to_string(tokens: &[TokenType]) -> String {
434 let mut i = tokens.iter();
435 // This might be a sign we need a connect method on Iterator.
437 .map_or("".to_string(), |t| t.to_string());
438 i.enumerate().fold(b, |mut b, (i, ref a)| {
439 if tokens.len() > 2 && i == tokens.len() - 2 {
441 } else if tokens.len() == 2 && i == tokens.len() - 2 {
446 b.push_str(&*a.to_string());
450 if edible.contains(&self.token) {
452 } else if inedible.contains(&self.token) {
453 // leave it in the input
456 let mut expected = edible.iter()
457 .map(|x| TokenType::Token(x.clone()))
458 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
459 .chain(self.expected_tokens.iter().cloned())
460 .collect::<Vec<_>>();
461 expected.sort_by(|a, b| a.to_string().cmp(&b.to_string()));
463 let expect = tokens_to_string(&expected[..]);
464 let actual = self.this_token_to_string();
466 &(if expected.len() > 1 {
467 (format!("expected one of {}, found `{}`",
470 } else if expected.is_empty() {
471 (format!("unexpected token: `{}`",
474 (format!("expected {}, found `{}`",
482 /// Check for erroneous `ident { }`; if matches, signal error and
483 /// recover (without consuming any expected input token). Returns
484 /// true if and only if input was consumed for recovery.
485 pub fn check_for_erroneous_unit_struct_expecting(&mut self,
486 expected: &[token::Token])
488 if self.token == token::OpenDelim(token::Brace)
489 && expected.iter().all(|t| *t != token::OpenDelim(token::Brace))
490 && self.look_ahead(1, |t| *t == token::CloseDelim(token::Brace)) {
491 // matched; signal non-fatal error and recover.
492 let span = self.span;
494 "unit-like struct construction is written with no trailing `{ }`");
495 try!(self.eat(&token::OpenDelim(token::Brace)));
496 try!(self.eat(&token::CloseDelim(token::Brace)));
503 /// Commit to parsing a complete expression `e` expected to be
504 /// followed by some token from the set edible + inedible. Recover
505 /// from anticipated input errors, discarding erroneous characters.
506 pub fn commit_expr(&mut self, e: &Expr, edible: &[token::Token],
507 inedible: &[token::Token]) -> PResult<()> {
508 debug!("commit_expr {:?}", e);
509 if let ExprPath(..) = e.node {
510 // might be unit-struct construction; check for recoverableinput error.
511 let expected = edible.iter()
513 .chain(inedible.iter().cloned())
514 .collect::<Vec<_>>();
515 try!(self.check_for_erroneous_unit_struct_expecting(&expected[..]));
517 self.expect_one_of(edible, inedible)
520 pub fn commit_expr_expecting(&mut self, e: &Expr, edible: token::Token) -> PResult<()> {
521 self.commit_expr(e, &[edible], &[])
524 /// Commit to parsing a complete statement `s`, which expects to be
525 /// followed by some token from the set edible + inedible. Check
526 /// for recoverable input errors, discarding erroneous characters.
527 pub fn commit_stmt(&mut self, edible: &[token::Token],
528 inedible: &[token::Token]) -> PResult<()> {
531 .map_or(false, |t| t.is_ident() || t.is_path()) {
532 let expected = edible.iter()
534 .chain(inedible.iter().cloned())
535 .collect::<Vec<_>>();
536 try!(self.check_for_erroneous_unit_struct_expecting(&expected));
538 self.expect_one_of(edible, inedible)
541 pub fn commit_stmt_expecting(&mut self, edible: token::Token) -> PResult<()> {
542 self.commit_stmt(&[edible], &[])
545 pub fn parse_ident(&mut self) -> PResult<ast::Ident> {
546 self.check_strict_keywords();
547 try!(self.check_reserved_keywords());
549 token::Ident(i, _) => {
553 token::Interpolated(token::NtIdent(..)) => {
554 self.bug("ident interpolation not converted to real token");
557 let token_str = self.this_token_to_string();
558 Err(self.fatal(&format!("expected ident, found `{}`",
564 pub fn parse_ident_or_self_type(&mut self) -> PResult<ast::Ident> {
565 if self.is_self_type_ident() {
566 self.expect_self_type_ident()
572 pub fn parse_path_list_item(&mut self) -> PResult<ast::PathListItem> {
573 let lo = self.span.lo;
574 let node = if try!(self.eat_keyword(keywords::SelfValue)) {
575 let rename = try!(self.parse_rename());
576 ast::PathListMod { id: ast::DUMMY_NODE_ID, rename: rename }
578 let ident = try!(self.parse_ident());
579 let rename = try!(self.parse_rename());
580 ast::PathListIdent { name: ident, rename: rename, id: ast::DUMMY_NODE_ID }
582 let hi = self.last_span.hi;
583 Ok(spanned(lo, hi, node))
586 /// Check if the next token is `tok`, and return `true` if so.
588 /// This method is will automatically add `tok` to `expected_tokens` if `tok` is not
590 pub fn check(&mut self, tok: &token::Token) -> bool {
591 let is_present = self.token == *tok;
592 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
596 /// Consume token 'tok' if it exists. Returns true if the given
597 /// token was present, false otherwise.
598 pub fn eat(&mut self, tok: &token::Token) -> PResult<bool> {
599 let is_present = self.check(tok);
600 if is_present { try!(self.bump())}
604 pub fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
605 self.expected_tokens.push(TokenType::Keyword(kw));
606 self.token.is_keyword(kw)
609 /// If the next token is the given keyword, eat it and return
610 /// true. Otherwise, return false.
611 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> PResult<bool> {
612 if self.check_keyword(kw) {
620 pub fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> PResult<bool> {
621 if self.token.is_keyword(kw) {
629 /// If the given word is not a keyword, signal an error.
630 /// If the next token is not the given word, signal an error.
631 /// Otherwise, eat it.
632 pub fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<()> {
633 if !try!(self.eat_keyword(kw) ){
634 self.expect_one_of(&[], &[])
640 /// Signal an error if the given string is a strict keyword
641 pub fn check_strict_keywords(&mut self) {
642 if self.token.is_strict_keyword() {
643 let token_str = self.this_token_to_string();
644 let span = self.span;
646 &format!("expected identifier, found keyword `{}`",
651 /// Signal an error if the current token is a reserved keyword
652 pub fn check_reserved_keywords(&mut self) -> PResult<()>{
653 if self.token.is_reserved_keyword() {
654 let token_str = self.this_token_to_string();
655 Err(self.fatal(&format!("`{}` is a reserved keyword",
662 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
663 /// `&` and continue. If an `&` is not seen, signal an error.
664 fn expect_and(&mut self) -> PResult<()> {
665 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
667 token::BinOp(token::And) => self.bump(),
669 let span = self.span;
670 let lo = span.lo + BytePos(1);
671 Ok(self.replace_token(token::BinOp(token::And), lo, span.hi))
673 _ => self.expect_one_of(&[], &[])
677 pub fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
679 None => {/* everything ok */}
681 let text = suf.as_str();
683 self.span_bug(sp, "found empty literal suffix in Some")
685 self.span_err(sp, &*format!("{} with a suffix is invalid", kind));
691 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
692 /// `<` and continue. If a `<` is not seen, return false.
694 /// This is meant to be used when parsing generics on a path to get the
696 fn eat_lt(&mut self) -> PResult<bool> {
697 self.expected_tokens.push(TokenType::Token(token::Lt));
699 token::Lt => { try!(self.bump()); Ok(true)}
700 token::BinOp(token::Shl) => {
701 let span = self.span;
702 let lo = span.lo + BytePos(1);
703 self.replace_token(token::Lt, lo, span.hi);
710 fn expect_lt(&mut self) -> PResult<()> {
711 if !try!(self.eat_lt()) {
712 self.expect_one_of(&[], &[])
718 /// Expect and consume a GT. if a >> is seen, replace it
719 /// with a single > and continue. If a GT is not seen,
721 pub fn expect_gt(&mut self) -> PResult<()> {
722 self.expected_tokens.push(TokenType::Token(token::Gt));
724 token::Gt => self.bump(),
725 token::BinOp(token::Shr) => {
726 let span = self.span;
727 let lo = span.lo + BytePos(1);
728 Ok(self.replace_token(token::Gt, lo, span.hi))
730 token::BinOpEq(token::Shr) => {
731 let span = self.span;
732 let lo = span.lo + BytePos(1);
733 Ok(self.replace_token(token::Ge, lo, span.hi))
736 let span = self.span;
737 let lo = span.lo + BytePos(1);
738 Ok(self.replace_token(token::Eq, lo, span.hi))
741 let gt_str = Parser::token_to_string(&token::Gt);
742 let this_token_str = self.this_token_to_string();
743 Err(self.fatal(&format!("expected `{}`, found `{}`",
750 pub fn parse_seq_to_before_gt_or_return<T, F>(&mut self,
751 sep: Option<token::Token>,
753 -> PResult<(P<[T]>, bool)> where
754 F: FnMut(&mut Parser) -> PResult<Option<T>>,
756 let mut v = Vec::new();
757 // This loop works by alternating back and forth between parsing types
758 // and commas. For example, given a string `A, B,>`, the parser would
759 // first parse `A`, then a comma, then `B`, then a comma. After that it
760 // would encounter a `>` and stop. This lets the parser handle trailing
761 // commas in generic parameters, because it can stop either after
762 // parsing a type or after parsing a comma.
764 if self.check(&token::Gt)
765 || self.token == token::BinOp(token::Shr)
766 || self.token == token::Ge
767 || self.token == token::BinOpEq(token::Shr) {
772 match try!(f(self)) {
773 Some(result) => v.push(result),
774 None => return Ok((P::from_vec(v), true))
777 if let Some(t) = sep.as_ref() {
778 try!(self.expect(t));
783 return Ok((P::from_vec(v), false));
786 /// Parse a sequence bracketed by '<' and '>', stopping
788 pub fn parse_seq_to_before_gt<T, F>(&mut self,
789 sep: Option<token::Token>,
791 -> PResult<P<[T]>> where
792 F: FnMut(&mut Parser) -> PResult<T>,
794 let (result, returned) = try!(self.parse_seq_to_before_gt_or_return(sep,
795 |p| Ok(Some(try!(f(p))))));
800 pub fn parse_seq_to_gt<T, F>(&mut self,
801 sep: Option<token::Token>,
803 -> PResult<P<[T]>> where
804 F: FnMut(&mut Parser) -> PResult<T>,
806 let v = try!(self.parse_seq_to_before_gt(sep, f));
807 try!(self.expect_gt());
811 pub fn parse_seq_to_gt_or_return<T, F>(&mut self,
812 sep: Option<token::Token>,
814 -> PResult<(P<[T]>, bool)> where
815 F: FnMut(&mut Parser) -> PResult<Option<T>>,
817 let (v, returned) = try!(self.parse_seq_to_before_gt_or_return(sep, f));
819 try!(self.expect_gt());
821 return Ok((v, returned));
824 /// Parse a sequence, including the closing delimiter. The function
825 /// f must consume tokens until reaching the next separator or
827 pub fn parse_seq_to_end<T, F>(&mut self,
831 -> PResult<Vec<T>> where
832 F: FnMut(&mut Parser) -> PResult<T>,
834 let val = try!(self.parse_seq_to_before_end(ket, sep, f));
839 /// Parse a sequence, not including the closing delimiter. The function
840 /// f must consume tokens until reaching the next separator or
842 pub fn parse_seq_to_before_end<T, F>(&mut self,
846 -> PResult<Vec<T>> where
847 F: FnMut(&mut Parser) -> PResult<T>,
849 let mut first: bool = true;
851 while self.token != *ket {
854 if first { first = false; }
855 else { try!(self.expect(t)); }
859 if sep.trailing_sep_allowed && self.check(ket) { break; }
860 v.push(try!(f(self)));
865 /// Parse a sequence, including the closing delimiter. The function
866 /// f must consume tokens until reaching the next separator or
868 pub fn parse_unspanned_seq<T, F>(&mut self,
873 -> PResult<Vec<T>> where
874 F: FnMut(&mut Parser) -> PResult<T>,
876 try!(self.expect(bra));
877 let result = try!(self.parse_seq_to_before_end(ket, sep, f));
882 /// Parse a sequence parameter of enum variant. For consistency purposes,
883 /// these should not be empty.
884 pub fn parse_enum_variant_seq<T, F>(&mut self,
889 -> PResult<Vec<T>> where
890 F: FnMut(&mut Parser) -> PResult<T>,
892 let result = try!(self.parse_unspanned_seq(bra, ket, sep, f));
893 if result.is_empty() {
894 let last_span = self.last_span;
895 self.span_err(last_span,
896 "nullary enum variants are written with no trailing `( )`");
901 // NB: Do not use this function unless you actually plan to place the
902 // spanned list in the AST.
903 pub fn parse_seq<T, F>(&mut self,
908 -> PResult<Spanned<Vec<T>>> where
909 F: FnMut(&mut Parser) -> PResult<T>,
911 let lo = self.span.lo;
912 try!(self.expect(bra));
913 let result = try!(self.parse_seq_to_before_end(ket, sep, f));
914 let hi = self.span.hi;
916 Ok(spanned(lo, hi, result))
919 /// Advance the parser by one token
920 pub fn bump(&mut self) -> PResult<()> {
921 self.last_span = self.span;
922 // Stash token for error recovery (sometimes; clone is not necessarily cheap).
923 self.last_token = if self.token.is_ident() ||
924 self.token.is_path() ||
925 self.token == token::Comma {
926 Some(Box::new(self.token.clone()))
930 let next = if self.buffer_start == self.buffer_end {
931 self.reader.real_token()
933 // Avoid token copies with `replace`.
934 let buffer_start = self.buffer_start as usize;
935 let next_index = (buffer_start + 1) & 3;
936 self.buffer_start = next_index as isize;
938 let placeholder = TokenAndSpan {
939 tok: token::Underscore,
942 mem::replace(&mut self.buffer[buffer_start], placeholder)
945 self.token = next.tok;
946 self.tokens_consumed += 1;
947 self.expected_tokens.clear();
948 // check after each token
949 self.check_unknown_macro_variable()
952 /// Advance the parser by one token and return the bumped token.
953 pub fn bump_and_get(&mut self) -> PResult<token::Token> {
954 let old_token = mem::replace(&mut self.token, token::Underscore);
959 /// EFFECT: replace the current token and span with the given one
960 pub fn replace_token(&mut self,
964 self.last_span = mk_sp(self.span.lo, lo);
966 self.span = mk_sp(lo, hi);
968 pub fn buffer_length(&mut self) -> isize {
969 if self.buffer_start <= self.buffer_end {
970 return self.buffer_end - self.buffer_start;
972 return (4 - self.buffer_start) + self.buffer_end;
974 pub fn look_ahead<R, F>(&mut self, distance: usize, f: F) -> R where
975 F: FnOnce(&token::Token) -> R,
977 let dist = distance as isize;
978 while self.buffer_length() < dist {
979 self.buffer[self.buffer_end as usize] = self.reader.real_token();
980 self.buffer_end = (self.buffer_end + 1) & 3;
982 f(&self.buffer[((self.buffer_start + dist - 1) & 3) as usize].tok)
984 pub fn fatal(&self, m: &str) -> errors::FatalError {
985 self.sess.span_diagnostic.span_fatal(self.span, m)
987 pub fn span_fatal(&self, sp: Span, m: &str) -> errors::FatalError {
988 self.sess.span_diagnostic.span_fatal(sp, m)
990 pub fn span_fatal_help(&self, sp: Span, m: &str, help: &str) -> errors::FatalError {
991 self.span_err(sp, m);
992 self.fileline_help(sp, help);
995 pub fn span_note(&self, sp: Span, m: &str) {
996 self.sess.span_diagnostic.span_note(sp, m)
998 pub fn span_help(&self, sp: Span, m: &str) {
999 self.sess.span_diagnostic.span_help(sp, m)
1001 pub fn span_suggestion(&self, sp: Span, m: &str, n: String) {
1002 self.sess.span_diagnostic.span_suggestion(sp, m, n)
1004 pub fn fileline_help(&self, sp: Span, m: &str) {
1005 self.sess.span_diagnostic.fileline_help(sp, m)
1007 pub fn bug(&self, m: &str) -> ! {
1008 self.sess.span_diagnostic.span_bug(self.span, m)
1010 pub fn warn(&self, m: &str) {
1011 self.sess.span_diagnostic.span_warn(self.span, m)
1013 pub fn span_warn(&self, sp: Span, m: &str) {
1014 self.sess.span_diagnostic.span_warn(sp, m)
1016 pub fn span_err(&self, sp: Span, m: &str) {
1017 self.sess.span_diagnostic.span_err(sp, m)
1019 pub fn span_bug(&self, sp: Span, m: &str) -> ! {
1020 self.sess.span_diagnostic.span_bug(sp, m)
1022 pub fn abort_if_errors(&self) {
1023 self.sess.span_diagnostic.abort_if_errors();
1026 pub fn id_to_interned_str(&mut self, id: Ident) -> InternedString {
1030 /// Is the current token one of the keywords that signals a bare function
1032 pub fn token_is_bare_fn_keyword(&mut self) -> bool {
1033 self.check_keyword(keywords::Fn) ||
1034 self.check_keyword(keywords::Unsafe) ||
1035 self.check_keyword(keywords::Extern)
1038 pub fn get_lifetime(&mut self) -> ast::Ident {
1040 token::Lifetime(ref ident) => *ident,
1041 _ => self.bug("not a lifetime"),
1045 pub fn parse_for_in_type(&mut self) -> PResult<Ty_> {
1047 Parses whatever can come after a `for` keyword in a type.
1048 The `for` has already been consumed.
1052 - for <'lt> |S| -> T
1056 - for <'lt> [unsafe] [extern "ABI"] fn (S) -> T
1057 - for <'lt> path::foo(a, b)
1062 let lo = self.span.lo;
1064 let lifetime_defs = try!(self.parse_late_bound_lifetime_defs());
1066 // examine next token to decide to do
1067 if self.token_is_bare_fn_keyword() {
1068 self.parse_ty_bare_fn(lifetime_defs)
1070 let hi = self.span.hi;
1071 let trait_ref = try!(self.parse_trait_ref());
1072 let poly_trait_ref = ast::PolyTraitRef { bound_lifetimes: lifetime_defs,
1073 trait_ref: trait_ref,
1074 span: mk_sp(lo, hi)};
1075 let other_bounds = if try!(self.eat(&token::BinOp(token::Plus)) ){
1076 try!(self.parse_ty_param_bounds(BoundParsingMode::Bare))
1081 Some(TraitTyParamBound(poly_trait_ref, TraitBoundModifier::None)).into_iter()
1082 .chain(other_bounds.into_vec())
1084 Ok(ast::TyPolyTraitRef(all_bounds))
1088 pub fn parse_ty_path(&mut self) -> PResult<Ty_> {
1089 Ok(TyPath(None, try!(self.parse_path(LifetimeAndTypesWithoutColons))))
1092 /// parse a TyBareFn type:
1093 pub fn parse_ty_bare_fn(&mut self, lifetime_defs: Vec<ast::LifetimeDef>) -> PResult<Ty_> {
1096 [unsafe] [extern "ABI"] fn <'lt> (S) -> T
1097 ^~~~^ ^~~~^ ^~~~^ ^~^ ^
1100 | | | Argument types
1106 let unsafety = try!(self.parse_unsafety());
1107 let abi = if try!(self.eat_keyword(keywords::Extern) ){
1108 try!(self.parse_opt_abi()).unwrap_or(abi::C)
1113 try!(self.expect_keyword(keywords::Fn));
1114 let (inputs, variadic) = try!(self.parse_fn_args(false, true));
1115 let ret_ty = try!(self.parse_ret_ty());
1116 let decl = P(FnDecl {
1121 Ok(TyBareFn(P(BareFnTy {
1124 lifetimes: lifetime_defs,
1129 /// Parses an obsolete closure kind (`&:`, `&mut:`, or `:`).
1130 pub fn parse_obsolete_closure_kind(&mut self) -> PResult<()> {
1131 let lo = self.span.lo;
1133 self.check(&token::BinOp(token::And)) &&
1134 self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
1135 self.look_ahead(2, |t| *t == token::Colon)
1141 self.token == token::BinOp(token::And) &&
1142 self.look_ahead(1, |t| *t == token::Colon)
1147 try!(self.eat(&token::Colon))
1154 let span = mk_sp(lo, self.span.hi);
1155 self.obsolete(span, ObsoleteSyntax::ClosureKind);
1159 pub fn parse_unsafety(&mut self) -> PResult<Unsafety> {
1160 if try!(self.eat_keyword(keywords::Unsafe)) {
1161 return Ok(Unsafety::Unsafe);
1163 return Ok(Unsafety::Normal);
1167 /// Parse the items in a trait declaration
1168 pub fn parse_trait_items(&mut self) -> PResult<Vec<P<TraitItem>>> {
1169 self.parse_unspanned_seq(
1170 &token::OpenDelim(token::Brace),
1171 &token::CloseDelim(token::Brace),
1173 |p| -> PResult<P<TraitItem>> {
1174 maybe_whole!(no_clone p, NtTraitItem);
1175 let mut attrs = try!(p.parse_outer_attributes());
1178 let (name, node) = if try!(p.eat_keyword(keywords::Type)) {
1179 let TyParam {ident, bounds, default, ..} = try!(p.parse_ty_param());
1180 try!(p.expect(&token::Semi));
1181 (ident, TypeTraitItem(bounds, default))
1182 } else if p.is_const_item() {
1183 try!(p.expect_keyword(keywords::Const));
1184 let ident = try!(p.parse_ident());
1185 try!(p.expect(&token::Colon));
1186 let ty = try!(p.parse_ty_sum());
1187 let default = if p.check(&token::Eq) {
1189 let expr = try!(p.parse_expr());
1190 try!(p.commit_expr_expecting(&expr, token::Semi));
1193 try!(p.expect(&token::Semi));
1196 (ident, ConstTraitItem(ty, default))
1198 let (constness, unsafety, abi) = try!(p.parse_fn_front_matter());
1200 let ident = try!(p.parse_ident());
1201 let mut generics = try!(p.parse_generics());
1203 let (explicit_self, d) = try!(p.parse_fn_decl_with_self(|p|{
1204 // This is somewhat dubious; We don't want to allow
1205 // argument names to be left off if there is a
1207 p.parse_arg_general(false)
1210 generics.where_clause = try!(p.parse_where_clause());
1211 let sig = ast::MethodSig {
1213 constness: constness,
1217 explicit_self: explicit_self,
1220 let body = match p.token {
1223 debug!("parse_trait_methods(): parsing required method");
1226 token::OpenDelim(token::Brace) => {
1227 debug!("parse_trait_methods(): parsing provided method");
1228 let (inner_attrs, body) =
1229 try!(p.parse_inner_attrs_and_block());
1230 attrs.extend(inner_attrs.iter().cloned());
1235 let token_str = p.this_token_to_string();
1236 return Err(p.fatal(&format!("expected `;` or `{{`, found `{}`",
1240 (ident, ast::MethodTraitItem(sig, body))
1244 id: ast::DUMMY_NODE_ID,
1248 span: mk_sp(lo, p.last_span.hi),
1253 /// Parse a possibly mutable type
1254 pub fn parse_mt(&mut self) -> PResult<MutTy> {
1255 let mutbl = try!(self.parse_mutability());
1256 let t = try!(self.parse_ty());
1257 Ok(MutTy { ty: t, mutbl: mutbl })
1260 /// Parse optional return type [ -> TY ] in function decl
1261 pub fn parse_ret_ty(&mut self) -> PResult<FunctionRetTy> {
1262 if try!(self.eat(&token::RArrow) ){
1263 if try!(self.eat(&token::Not) ){
1264 Ok(NoReturn(self.last_span))
1266 Ok(Return(try!(self.parse_ty())))
1269 let pos = self.span.lo;
1270 Ok(DefaultReturn(mk_sp(pos, pos)))
1274 /// Parse a type in a context where `T1+T2` is allowed.
1275 pub fn parse_ty_sum(&mut self) -> PResult<P<Ty>> {
1276 let lo = self.span.lo;
1277 let lhs = try!(self.parse_ty());
1279 if !try!(self.eat(&token::BinOp(token::Plus)) ){
1283 let bounds = try!(self.parse_ty_param_bounds(BoundParsingMode::Bare));
1285 // In type grammar, `+` is treated like a binary operator,
1286 // and hence both L and R side are required.
1287 if bounds.is_empty() {
1288 let last_span = self.last_span;
1289 self.span_err(last_span,
1290 "at least one type parameter bound \
1291 must be specified");
1294 let sp = mk_sp(lo, self.last_span.hi);
1295 let sum = ast::TyObjectSum(lhs, bounds);
1296 Ok(P(Ty {id: ast::DUMMY_NODE_ID, node: sum, span: sp}))
1300 pub fn parse_ty(&mut self) -> PResult<P<Ty>> {
1301 maybe_whole!(no_clone self, NtTy);
1303 let lo = self.span.lo;
1305 let t = if self.check(&token::OpenDelim(token::Paren)) {
1308 // (t) is a parenthesized ty
1309 // (t,) is the type of a tuple with only one field,
1311 let mut ts = vec![];
1312 let mut last_comma = false;
1313 while self.token != token::CloseDelim(token::Paren) {
1314 ts.push(try!(self.parse_ty_sum()));
1315 if self.check(&token::Comma) {
1324 try!(self.expect(&token::CloseDelim(token::Paren)));
1325 if ts.len() == 1 && !last_comma {
1326 TyParen(ts.into_iter().nth(0).unwrap())
1330 } else if self.check(&token::BinOp(token::Star)) {
1331 // STAR POINTER (bare pointer?)
1333 TyPtr(try!(self.parse_ptr()))
1334 } else if self.check(&token::OpenDelim(token::Bracket)) {
1336 try!(self.expect(&token::OpenDelim(token::Bracket)));
1337 let t = try!(self.parse_ty_sum());
1339 // Parse the `; e` in `[ i32; e ]`
1340 // where `e` is a const expression
1341 let t = match try!(self.maybe_parse_fixed_length_of_vec()) {
1343 Some(suffix) => TyFixedLengthVec(t, suffix)
1345 try!(self.expect(&token::CloseDelim(token::Bracket)));
1347 } else if self.check(&token::BinOp(token::And)) ||
1348 self.token == token::AndAnd {
1350 try!(self.expect_and());
1351 try!(self.parse_borrowed_pointee())
1352 } else if self.check_keyword(keywords::For) {
1353 try!(self.parse_for_in_type())
1354 } else if self.token_is_bare_fn_keyword() {
1356 try!(self.parse_ty_bare_fn(Vec::new()))
1357 } else if try!(self.eat_keyword_noexpect(keywords::Typeof)) {
1359 // In order to not be ambiguous, the type must be surrounded by parens.
1360 try!(self.expect(&token::OpenDelim(token::Paren)));
1361 let e = try!(self.parse_expr());
1362 try!(self.expect(&token::CloseDelim(token::Paren)));
1364 } else if try!(self.eat_lt()) {
1367 try!(self.parse_qualified_path(NoTypesAllowed));
1369 TyPath(Some(qself), path)
1370 } else if self.check(&token::ModSep) ||
1371 self.token.is_ident() ||
1372 self.token.is_path() {
1373 let path = try!(self.parse_path(LifetimeAndTypesWithoutColons));
1374 if self.check(&token::Not) {
1377 let delim = try!(self.expect_open_delim());
1378 let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
1380 |p| p.parse_token_tree()));
1381 let hi = self.span.hi;
1382 TyMac(spanned(lo, hi, Mac_ { path: path, tts: tts, ctxt: EMPTY_CTXT }))
1387 } else if try!(self.eat(&token::Underscore) ){
1388 // TYPE TO BE INFERRED
1391 let this_token_str = self.this_token_to_string();
1392 let msg = format!("expected type, found `{}`", this_token_str);
1393 return Err(self.fatal(&msg[..]));
1396 let sp = mk_sp(lo, self.last_span.hi);
1397 Ok(P(Ty {id: ast::DUMMY_NODE_ID, node: t, span: sp}))
1400 pub fn parse_borrowed_pointee(&mut self) -> PResult<Ty_> {
1401 // look for `&'lt` or `&'foo ` and interpret `foo` as the region name:
1402 let opt_lifetime = try!(self.parse_opt_lifetime());
1404 let mt = try!(self.parse_mt());
1405 return Ok(TyRptr(opt_lifetime, mt));
1408 pub fn parse_ptr(&mut self) -> PResult<MutTy> {
1409 let mutbl = if try!(self.eat_keyword(keywords::Mut) ){
1411 } else if try!(self.eat_keyword(keywords::Const) ){
1414 let span = self.last_span;
1416 "bare raw pointers are no longer allowed, you should \
1417 likely use `*mut T`, but otherwise `*T` is now \
1418 known as `*const T`");
1421 let t = try!(self.parse_ty());
1422 Ok(MutTy { ty: t, mutbl: mutbl })
1425 pub fn is_named_argument(&mut self) -> bool {
1426 let offset = match self.token {
1427 token::BinOp(token::And) => 1,
1429 _ if self.token.is_keyword(keywords::Mut) => 1,
1433 debug!("parser is_named_argument offset:{}", offset);
1436 is_plain_ident_or_underscore(&self.token)
1437 && self.look_ahead(1, |t| *t == token::Colon)
1439 self.look_ahead(offset, |t| is_plain_ident_or_underscore(t))
1440 && self.look_ahead(offset + 1, |t| *t == token::Colon)
1444 /// This version of parse arg doesn't necessarily require
1445 /// identifier names.
1446 pub fn parse_arg_general(&mut self, require_name: bool) -> PResult<Arg> {
1447 maybe_whole!(no_clone self, NtArg);
1449 let pat = if require_name || self.is_named_argument() {
1450 debug!("parse_arg_general parse_pat (require_name:{})",
1452 let pat = try!(self.parse_pat());
1454 try!(self.expect(&token::Colon));
1457 debug!("parse_arg_general ident_to_pat");
1458 ast_util::ident_to_pat(ast::DUMMY_NODE_ID,
1460 special_idents::invalid)
1463 let t = try!(self.parse_ty_sum());
1468 id: ast::DUMMY_NODE_ID,
1472 /// Parse a single function argument
1473 pub fn parse_arg(&mut self) -> PResult<Arg> {
1474 self.parse_arg_general(true)
1477 /// Parse an argument in a lambda header e.g. |arg, arg|
1478 pub fn parse_fn_block_arg(&mut self) -> PResult<Arg> {
1479 let pat = try!(self.parse_pat());
1480 let t = if try!(self.eat(&token::Colon) ){
1481 try!(self.parse_ty_sum())
1484 id: ast::DUMMY_NODE_ID,
1486 span: mk_sp(self.span.lo, self.span.hi),
1492 id: ast::DUMMY_NODE_ID
1496 pub fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<Option<P<ast::Expr>>> {
1497 if self.check(&token::Semi) {
1499 Ok(Some(try!(self.parse_expr())))
1505 /// Matches token_lit = LIT_INTEGER | ...
1506 pub fn lit_from_token(&self, tok: &token::Token) -> PResult<Lit_> {
1508 token::Interpolated(token::NtExpr(ref v)) => {
1510 ExprLit(ref lit) => { Ok(lit.node.clone()) }
1511 _ => { return Err(self.unexpected_last(tok)); }
1514 token::Literal(lit, suf) => {
1515 let (suffix_illegal, out) = match lit {
1516 token::Byte(i) => (true, LitByte(parse::byte_lit(&i.as_str()).0)),
1517 token::Char(i) => (true, LitChar(parse::char_lit(&i.as_str()).0)),
1519 // there are some valid suffixes for integer and
1520 // float literals, so all the handling is done
1522 token::Integer(s) => {
1523 (false, parse::integer_lit(&s.as_str(),
1524 suf.as_ref().map(|s| s.as_str()),
1525 &self.sess.span_diagnostic,
1528 token::Float(s) => {
1529 (false, parse::float_lit(&s.as_str(),
1530 suf.as_ref().map(|s| s.as_str()),
1531 &self.sess.span_diagnostic,
1537 LitStr(token::intern_and_get_ident(&parse::str_lit(&s.as_str())),
1540 token::StrRaw(s, n) => {
1543 token::intern_and_get_ident(&parse::raw_str_lit(&s.as_str())),
1546 token::ByteStr(i) =>
1547 (true, LitByteStr(parse::byte_str_lit(&i.as_str()))),
1548 token::ByteStrRaw(i, _) =>
1550 LitByteStr(Rc::new(i.to_string().into_bytes()))),
1554 let sp = self.last_span;
1555 self.expect_no_suffix(sp, &*format!("{} literal", lit.short_name()), suf)
1560 _ => { return Err(self.unexpected_last(tok)); }
1564 /// Matches lit = true | false | token_lit
1565 pub fn parse_lit(&mut self) -> PResult<Lit> {
1566 let lo = self.span.lo;
1567 let lit = if try!(self.eat_keyword(keywords::True) ){
1569 } else if try!(self.eat_keyword(keywords::False) ){
1572 let token = try!(self.bump_and_get());
1573 let lit = try!(self.lit_from_token(&token));
1576 Ok(codemap::Spanned { node: lit, span: mk_sp(lo, self.last_span.hi) })
1579 /// matches '-' lit | lit
1580 pub fn parse_pat_literal_maybe_minus(&mut self) -> PResult<P<Expr>> {
1581 let minus_lo = self.span.lo;
1582 let minus_present = try!(self.eat(&token::BinOp(token::Minus)));
1583 let lo = self.span.lo;
1584 let literal = P(try!(self.parse_lit()));
1585 let hi = self.last_span.hi;
1586 let expr = self.mk_expr(lo, hi, ExprLit(literal), None);
1589 let minus_hi = self.last_span.hi;
1590 let unary = self.mk_unary(UnNeg, expr);
1591 Ok(self.mk_expr(minus_lo, minus_hi, unary, None))
1597 /// Parses qualified path.
1599 /// Assumes that the leading `<` has been parsed already.
1601 /// Qualifed paths are a part of the universal function call
1604 /// `qualified_path = <type [as trait_ref]>::path`
1606 /// See `parse_path` for `mode` meaning.
1611 /// `<T as U>::F::a::<S>`
1612 pub fn parse_qualified_path(&mut self, mode: PathParsingMode)
1613 -> PResult<(QSelf, ast::Path)> {
1614 let span = self.last_span;
1615 let self_type = try!(self.parse_ty_sum());
1616 let mut path = if try!(self.eat_keyword(keywords::As)) {
1617 try!(self.parse_path(LifetimeAndTypesWithoutColons))
1628 position: path.segments.len()
1631 try!(self.expect(&token::Gt));
1632 try!(self.expect(&token::ModSep));
1634 let segments = match mode {
1635 LifetimeAndTypesWithoutColons => {
1636 try!(self.parse_path_segments_without_colons())
1638 LifetimeAndTypesWithColons => {
1639 try!(self.parse_path_segments_with_colons())
1642 try!(self.parse_path_segments_without_types())
1645 path.segments.extend(segments);
1647 path.span.hi = self.last_span.hi;
1652 /// Parses a path and optional type parameter bounds, depending on the
1653 /// mode. The `mode` parameter determines whether lifetimes, types, and/or
1654 /// bounds are permitted and whether `::` must precede type parameter
1656 pub fn parse_path(&mut self, mode: PathParsingMode) -> PResult<ast::Path> {
1657 // Check for a whole path...
1658 let found = match self.token {
1659 token::Interpolated(token::NtPath(_)) => Some(try!(self.bump_and_get())),
1662 if let Some(token::Interpolated(token::NtPath(path))) = found {
1666 let lo = self.span.lo;
1667 let is_global = try!(self.eat(&token::ModSep));
1669 // Parse any number of segments and bound sets. A segment is an
1670 // identifier followed by an optional lifetime and a set of types.
1671 // A bound set is a set of type parameter bounds.
1672 let segments = match mode {
1673 LifetimeAndTypesWithoutColons => {
1674 try!(self.parse_path_segments_without_colons())
1676 LifetimeAndTypesWithColons => {
1677 try!(self.parse_path_segments_with_colons())
1680 try!(self.parse_path_segments_without_types())
1684 // Assemble the span.
1685 let span = mk_sp(lo, self.last_span.hi);
1687 // Assemble the result.
1696 /// - `a::b<T,U>::c<V,W>`
1697 /// - `a::b<T,U>::c(V) -> W`
1698 /// - `a::b<T,U>::c(V)`
1699 pub fn parse_path_segments_without_colons(&mut self) -> PResult<Vec<ast::PathSegment>> {
1700 let mut segments = Vec::new();
1702 // First, parse an identifier.
1703 let identifier = try!(self.parse_ident_or_self_type());
1705 // Parse types, optionally.
1706 let parameters = if try!(self.eat_lt() ){
1707 let (lifetimes, types, bindings) = try!(self.parse_generic_values_after_lt());
1709 ast::AngleBracketedParameters(ast::AngleBracketedParameterData {
1710 lifetimes: lifetimes,
1711 types: P::from_vec(types),
1712 bindings: P::from_vec(bindings),
1714 } else if try!(self.eat(&token::OpenDelim(token::Paren)) ){
1715 let lo = self.last_span.lo;
1717 let inputs = try!(self.parse_seq_to_end(
1718 &token::CloseDelim(token::Paren),
1719 seq_sep_trailing_allowed(token::Comma),
1720 |p| p.parse_ty_sum()));
1722 let output_ty = if try!(self.eat(&token::RArrow) ){
1723 Some(try!(self.parse_ty()))
1728 let hi = self.last_span.hi;
1730 ast::ParenthesizedParameters(ast::ParenthesizedParameterData {
1731 span: mk_sp(lo, hi),
1736 ast::PathParameters::none()
1739 // Assemble and push the result.
1740 segments.push(ast::PathSegment { identifier: identifier,
1741 parameters: parameters });
1743 // Continue only if we see a `::`
1744 if !try!(self.eat(&token::ModSep) ){
1745 return Ok(segments);
1751 /// - `a::b::<T,U>::c`
1752 pub fn parse_path_segments_with_colons(&mut self) -> PResult<Vec<ast::PathSegment>> {
1753 let mut segments = Vec::new();
1755 // First, parse an identifier.
1756 let identifier = try!(self.parse_ident_or_self_type());
1758 // If we do not see a `::`, stop.
1759 if !try!(self.eat(&token::ModSep) ){
1760 segments.push(ast::PathSegment {
1761 identifier: identifier,
1762 parameters: ast::PathParameters::none()
1764 return Ok(segments);
1767 // Check for a type segment.
1768 if try!(self.eat_lt() ){
1769 // Consumed `a::b::<`, go look for types
1770 let (lifetimes, types, bindings) = try!(self.parse_generic_values_after_lt());
1771 segments.push(ast::PathSegment {
1772 identifier: identifier,
1773 parameters: ast::AngleBracketedParameters(ast::AngleBracketedParameterData {
1774 lifetimes: lifetimes,
1775 types: P::from_vec(types),
1776 bindings: P::from_vec(bindings),
1780 // Consumed `a::b::<T,U>`, check for `::` before proceeding
1781 if !try!(self.eat(&token::ModSep) ){
1782 return Ok(segments);
1785 // Consumed `a::`, go look for `b`
1786 segments.push(ast::PathSegment {
1787 identifier: identifier,
1788 parameters: ast::PathParameters::none(),
1797 pub fn parse_path_segments_without_types(&mut self) -> PResult<Vec<ast::PathSegment>> {
1798 let mut segments = Vec::new();
1800 // First, parse an identifier.
1801 let identifier = try!(self.parse_ident_or_self_type());
1803 // Assemble and push the result.
1804 segments.push(ast::PathSegment {
1805 identifier: identifier,
1806 parameters: ast::PathParameters::none()
1809 // If we do not see a `::`, stop.
1810 if !try!(self.eat(&token::ModSep) ){
1811 return Ok(segments);
1816 /// parses 0 or 1 lifetime
1817 pub fn parse_opt_lifetime(&mut self) -> PResult<Option<ast::Lifetime>> {
1819 token::Lifetime(..) => {
1820 Ok(Some(try!(self.parse_lifetime())))
1828 /// Parses a single lifetime
1829 /// Matches lifetime = LIFETIME
1830 pub fn parse_lifetime(&mut self) -> PResult<ast::Lifetime> {
1832 token::Lifetime(i) => {
1833 let span = self.span;
1835 return Ok(ast::Lifetime {
1836 id: ast::DUMMY_NODE_ID,
1842 return Err(self.fatal("expected a lifetime name"));
1847 /// Parses `lifetime_defs = [ lifetime_defs { ',' lifetime_defs } ]` where `lifetime_def =
1848 /// lifetime [':' lifetimes]`
1849 pub fn parse_lifetime_defs(&mut self) -> PResult<Vec<ast::LifetimeDef>> {
1851 let mut res = Vec::new();
1854 token::Lifetime(_) => {
1855 let lifetime = try!(self.parse_lifetime());
1857 if try!(self.eat(&token::Colon) ){
1858 try!(self.parse_lifetimes(token::BinOp(token::Plus)))
1862 res.push(ast::LifetimeDef { lifetime: lifetime,
1872 token::Comma => { try!(self.bump());}
1873 token::Gt => { return Ok(res); }
1874 token::BinOp(token::Shr) => { return Ok(res); }
1876 let this_token_str = self.this_token_to_string();
1877 let msg = format!("expected `,` or `>` after lifetime \
1880 return Err(self.fatal(&msg[..]));
1886 /// matches lifetimes = ( lifetime ) | ( lifetime , lifetimes ) actually, it matches the empty
1887 /// one too, but putting that in there messes up the grammar....
1889 /// Parses zero or more comma separated lifetimes. Expects each lifetime to be followed by
1890 /// either a comma or `>`. Used when parsing type parameter lists, where we expect something
1891 /// like `<'a, 'b, T>`.
1892 pub fn parse_lifetimes(&mut self, sep: token::Token) -> PResult<Vec<ast::Lifetime>> {
1894 let mut res = Vec::new();
1897 token::Lifetime(_) => {
1898 res.push(try!(self.parse_lifetime()));
1905 if self.token != sep {
1913 /// Parse mutability declaration (mut/const/imm)
1914 pub fn parse_mutability(&mut self) -> PResult<Mutability> {
1915 if try!(self.eat_keyword(keywords::Mut) ){
1922 /// Parse ident COLON expr
1923 pub fn parse_field(&mut self) -> PResult<Field> {
1924 let lo = self.span.lo;
1925 let i = try!(self.parse_ident());
1926 let hi = self.last_span.hi;
1927 try!(self.expect(&token::Colon));
1928 let e = try!(self.parse_expr());
1930 ident: spanned(lo, hi, i),
1931 span: mk_sp(lo, e.span.hi),
1936 pub fn mk_expr(&mut self, lo: BytePos, hi: BytePos,
1937 node: Expr_, attrs: ThinAttributes) -> P<Expr> {
1939 id: ast::DUMMY_NODE_ID,
1941 span: mk_sp(lo, hi),
1946 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::Expr_ {
1947 ExprUnary(unop, expr)
1950 pub fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::Expr_ {
1951 ExprBinary(binop, lhs, rhs)
1954 pub fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::Expr_ {
1958 fn mk_method_call(&mut self,
1959 ident: ast::SpannedIdent,
1963 ExprMethodCall(ident, tps, args)
1966 pub fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::Expr_ {
1967 ExprIndex(expr, idx)
1970 pub fn mk_range(&mut self,
1971 start: Option<P<Expr>>,
1972 end: Option<P<Expr>>)
1974 ExprRange(start, end)
1977 pub fn mk_field(&mut self, expr: P<Expr>, ident: ast::SpannedIdent) -> ast::Expr_ {
1978 ExprField(expr, ident)
1981 pub fn mk_tup_field(&mut self, expr: P<Expr>, idx: codemap::Spanned<usize>) -> ast::Expr_ {
1982 ExprTupField(expr, idx)
1985 pub fn mk_assign_op(&mut self, binop: ast::BinOp,
1986 lhs: P<Expr>, rhs: P<Expr>) -> ast::Expr_ {
1987 ExprAssignOp(binop, lhs, rhs)
1990 pub fn mk_mac_expr(&mut self, lo: BytePos, hi: BytePos,
1991 m: Mac_, attrs: ThinAttributes) -> P<Expr> {
1993 id: ast::DUMMY_NODE_ID,
1994 node: ExprMac(codemap::Spanned {node: m, span: mk_sp(lo, hi)}),
1995 span: mk_sp(lo, hi),
2000 pub fn mk_lit_u32(&mut self, i: u32, attrs: ThinAttributes) -> P<Expr> {
2001 let span = &self.span;
2002 let lv_lit = P(codemap::Spanned {
2003 node: LitInt(i as u64, ast::UnsignedIntLit(TyU32)),
2008 id: ast::DUMMY_NODE_ID,
2009 node: ExprLit(lv_lit),
2015 fn expect_open_delim(&mut self) -> PResult<token::DelimToken> {
2016 self.expected_tokens.push(TokenType::Token(token::Gt));
2018 token::OpenDelim(delim) => {
2022 _ => Err(self.fatal("expected open delimiter")),
2026 /// At the bottom (top?) of the precedence hierarchy,
2027 /// parse things like parenthesized exprs,
2028 /// macros, return, etc.
2030 /// NB: This does not parse outer attributes,
2031 /// and is private because it only works
2032 /// correctly if called from parse_dot_or_call_expr().
2033 fn parse_bottom_expr(&mut self) -> PResult<P<Expr>> {
2034 maybe_whole_expr!(self);
2036 // Outer attributes are already parsed and will be
2037 // added to the return value after the fact.
2039 // Therefore, prevent sub-parser from parsing
2040 // attributes by giving them a empty "already parsed" list.
2041 let mut attrs = None;
2043 let lo = self.span.lo;
2044 let mut hi = self.span.hi;
2048 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2050 token::OpenDelim(token::Paren) => {
2053 let attrs = try!(self.parse_inner_attributes())
2057 // (e) is parenthesized e
2058 // (e,) is a tuple with only one field, e
2059 let mut es = vec![];
2060 let mut trailing_comma = false;
2061 while self.token != token::CloseDelim(token::Paren) {
2062 es.push(try!(self.parse_expr()));
2063 try!(self.commit_expr(&**es.last().unwrap(), &[],
2064 &[token::Comma, token::CloseDelim(token::Paren)]));
2065 if self.check(&token::Comma) {
2066 trailing_comma = true;
2070 trailing_comma = false;
2076 hi = self.last_span.hi;
2077 return if es.len() == 1 && !trailing_comma {
2078 Ok(self.mk_expr(lo, hi, ExprParen(es.into_iter().nth(0).unwrap()), attrs))
2080 Ok(self.mk_expr(lo, hi, ExprTup(es), attrs))
2083 token::OpenDelim(token::Brace) => {
2084 return self.parse_block_expr(lo, DefaultBlock, attrs);
2086 token::BinOp(token::Or) | token::OrOr => {
2087 let lo = self.span.lo;
2088 return self.parse_lambda_expr(lo, CaptureByRef, attrs);
2090 token::Ident(id @ ast::Ident {
2091 name: token::SELF_KEYWORD_NAME,
2093 }, token::Plain) => {
2095 let path = ast_util::ident_to_path(mk_sp(lo, hi), id);
2096 ex = ExprPath(None, path);
2097 hi = self.last_span.hi;
2099 token::OpenDelim(token::Bracket) => {
2102 let inner_attrs = try!(self.parse_inner_attributes())
2104 attrs.update(|attrs| attrs.append(inner_attrs));
2106 if self.check(&token::CloseDelim(token::Bracket)) {
2109 ex = ExprVec(Vec::new());
2112 let first_expr = try!(self.parse_expr());
2113 if self.check(&token::Semi) {
2114 // Repeating array syntax: [ 0; 512 ]
2116 let count = try!(self.parse_expr());
2117 try!(self.expect(&token::CloseDelim(token::Bracket)));
2118 ex = ExprRepeat(first_expr, count);
2119 } else if self.check(&token::Comma) {
2120 // Vector with two or more elements.
2122 let remaining_exprs = try!(self.parse_seq_to_end(
2123 &token::CloseDelim(token::Bracket),
2124 seq_sep_trailing_allowed(token::Comma),
2125 |p| Ok(try!(p.parse_expr()))
2127 let mut exprs = vec!(first_expr);
2128 exprs.extend(remaining_exprs);
2129 ex = ExprVec(exprs);
2131 // Vector with one element.
2132 try!(self.expect(&token::CloseDelim(token::Bracket)));
2133 ex = ExprVec(vec!(first_expr));
2136 hi = self.last_span.hi;
2139 if try!(self.eat_lt()){
2141 try!(self.parse_qualified_path(LifetimeAndTypesWithColons));
2143 return Ok(self.mk_expr(lo, hi, ExprPath(Some(qself), path), attrs));
2145 if try!(self.eat_keyword(keywords::Move) ){
2146 let lo = self.last_span.lo;
2147 return self.parse_lambda_expr(lo, CaptureByValue, attrs);
2149 if try!(self.eat_keyword(keywords::If)) {
2150 return self.parse_if_expr(attrs);
2152 if try!(self.eat_keyword(keywords::For) ){
2153 let lo = self.last_span.lo;
2154 return self.parse_for_expr(None, lo, attrs);
2156 if try!(self.eat_keyword(keywords::While) ){
2157 let lo = self.last_span.lo;
2158 return self.parse_while_expr(None, lo, attrs);
2160 if self.token.is_lifetime() {
2161 let lifetime = self.get_lifetime();
2162 let lo = self.span.lo;
2164 try!(self.expect(&token::Colon));
2165 if try!(self.eat_keyword(keywords::While) ){
2166 return self.parse_while_expr(Some(lifetime), lo, attrs)
2168 if try!(self.eat_keyword(keywords::For) ){
2169 return self.parse_for_expr(Some(lifetime), lo, attrs)
2171 if try!(self.eat_keyword(keywords::Loop) ){
2172 return self.parse_loop_expr(Some(lifetime), lo, attrs)
2174 return Err(self.fatal("expected `while`, `for`, or `loop` after a label"))
2176 if try!(self.eat_keyword(keywords::Loop) ){
2177 let lo = self.last_span.lo;
2178 return self.parse_loop_expr(None, lo, attrs);
2180 if try!(self.eat_keyword(keywords::Continue) ){
2181 let ex = if self.token.is_lifetime() {
2182 let ex = ExprAgain(Some(Spanned{
2183 node: self.get_lifetime(),
2191 let hi = self.last_span.hi;
2192 return Ok(self.mk_expr(lo, hi, ex, attrs));
2194 if try!(self.eat_keyword(keywords::Match) ){
2195 return self.parse_match_expr(attrs);
2197 if try!(self.eat_keyword(keywords::Unsafe) ){
2198 return self.parse_block_expr(
2200 UnsafeBlock(ast::UserProvided),
2203 if try!(self.eat_keyword(keywords::Return) ){
2204 if self.token.can_begin_expr() {
2205 let e = try!(self.parse_expr());
2207 ex = ExprRet(Some(e));
2211 } else if try!(self.eat_keyword(keywords::Break) ){
2212 if self.token.is_lifetime() {
2213 ex = ExprBreak(Some(Spanned {
2214 node: self.get_lifetime(),
2219 ex = ExprBreak(None);
2221 hi = self.last_span.hi;
2222 } else if self.check(&token::ModSep) ||
2223 self.token.is_ident() &&
2224 !self.check_keyword(keywords::True) &&
2225 !self.check_keyword(keywords::False) {
2227 try!(self.parse_path(LifetimeAndTypesWithColons));
2229 // `!`, as an operator, is prefix, so we know this isn't that
2230 if self.check(&token::Not) {
2231 // MACRO INVOCATION expression
2234 let delim = try!(self.expect_open_delim());
2235 let tts = try!(self.parse_seq_to_end(
2236 &token::CloseDelim(delim),
2238 |p| p.parse_token_tree()));
2239 let hi = self.last_span.hi;
2241 return Ok(self.mk_mac_expr(lo,
2243 Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT },
2246 if self.check(&token::OpenDelim(token::Brace)) {
2247 // This is a struct literal, unless we're prohibited
2248 // from parsing struct literals here.
2249 let prohibited = self.restrictions.contains(
2250 Restrictions::RESTRICTION_NO_STRUCT_LITERAL
2253 // It's a struct literal.
2255 let mut fields = Vec::new();
2256 let mut base = None;
2258 let attrs = attrs.append(
2259 try!(self.parse_inner_attributes())
2260 .into_thin_attrs());
2262 while self.token != token::CloseDelim(token::Brace) {
2263 if try!(self.eat(&token::DotDot) ){
2264 base = Some(try!(self.parse_expr()));
2268 fields.push(try!(self.parse_field()));
2269 try!(self.commit_expr(&*fields.last().unwrap().expr,
2271 &[token::CloseDelim(token::Brace)]));
2275 try!(self.expect(&token::CloseDelim(token::Brace)));
2276 ex = ExprStruct(pth, fields, base);
2277 return Ok(self.mk_expr(lo, hi, ex, attrs));
2282 ex = ExprPath(None, pth);
2284 // other literal expression
2285 let lit = try!(self.parse_lit());
2287 ex = ExprLit(P(lit));
2292 return Ok(self.mk_expr(lo, hi, ex, attrs));
2295 fn parse_or_use_outer_attributes(&mut self,
2296 already_parsed_attrs: Option<ThinAttributes>)
2297 -> PResult<ThinAttributes> {
2298 if let Some(attrs) = already_parsed_attrs {
2301 self.parse_outer_attributes().map(|a| a.into_thin_attrs())
2305 /// Parse a block or unsafe block
2306 pub fn parse_block_expr(&mut self, lo: BytePos, blk_mode: BlockCheckMode,
2307 attrs: ThinAttributes)
2308 -> PResult<P<Expr>> {
2310 let outer_attrs = attrs;
2311 try!(self.expect(&token::OpenDelim(token::Brace)));
2313 let inner_attrs = try!(self.parse_inner_attributes()).into_thin_attrs();
2314 let attrs = outer_attrs.append(inner_attrs);
2316 let blk = try!(self.parse_block_tail(lo, blk_mode));
2317 return Ok(self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk), attrs));
2320 /// parse a.b or a(13) or a[4] or just a
2321 pub fn parse_dot_or_call_expr(&mut self,
2322 already_parsed_attrs: Option<ThinAttributes>)
2323 -> PResult<P<Expr>> {
2324 let attrs = try!(self.parse_or_use_outer_attributes(already_parsed_attrs));
2326 let b = try!(self.parse_bottom_expr());
2327 self.parse_dot_or_call_expr_with(b, attrs)
2330 pub fn parse_dot_or_call_expr_with(&mut self,
2332 attrs: ThinAttributes)
2333 -> PResult<P<Expr>> {
2334 // Stitch the list of outer attributes onto the return value.
2335 // A little bit ugly, but the best way given the current code
2337 self.parse_dot_or_call_expr_with_(e0)
2339 expr.map(|mut expr| {
2340 expr.attrs.update(|a| a.prepend(attrs));
2342 ExprIf(..) | ExprIfLet(..) => {
2343 if !expr.attrs.as_attr_slice().is_empty() {
2344 // Just point to the first attribute in there...
2345 let span = expr.attrs.as_attr_slice()[0].span;
2348 "attributes are not yet allowed on `if` \
2359 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>) -> PResult<P<Expr>> {
2365 if try!(self.eat(&token::Dot) ){
2367 token::Ident(i, _) => {
2368 let dot = self.last_span.hi;
2371 let (_, tys, bindings) = if try!(self.eat(&token::ModSep) ){
2372 try!(self.expect_lt());
2373 try!(self.parse_generic_values_after_lt())
2375 (Vec::new(), Vec::new(), Vec::new())
2378 if !bindings.is_empty() {
2379 let last_span = self.last_span;
2380 self.span_err(last_span, "type bindings are only permitted on trait paths");
2383 // expr.f() method call
2385 token::OpenDelim(token::Paren) => {
2386 let mut es = try!(self.parse_unspanned_seq(
2387 &token::OpenDelim(token::Paren),
2388 &token::CloseDelim(token::Paren),
2389 seq_sep_trailing_allowed(token::Comma),
2390 |p| Ok(try!(p.parse_expr()))
2392 hi = self.last_span.hi;
2395 let id = spanned(dot, hi, i);
2396 let nd = self.mk_method_call(id, tys, es);
2397 e = self.mk_expr(lo, hi, nd, None);
2400 if !tys.is_empty() {
2401 let last_span = self.last_span;
2402 self.span_err(last_span,
2403 "field expressions may not \
2404 have type parameters");
2407 let id = spanned(dot, hi, i);
2408 let field = self.mk_field(e, id);
2409 e = self.mk_expr(lo, hi, field, None);
2413 token::Literal(token::Integer(n), suf) => {
2416 // A tuple index may not have a suffix
2417 self.expect_no_suffix(sp, "tuple index", suf);
2419 let dot = self.last_span.hi;
2423 let index = n.as_str().parse::<usize>().ok();
2426 let id = spanned(dot, hi, n);
2427 let field = self.mk_tup_field(e, id);
2428 e = self.mk_expr(lo, hi, field, None);
2431 let last_span = self.last_span;
2432 self.span_err(last_span, "invalid tuple or tuple struct index");
2436 token::Literal(token::Float(n), _suf) => {
2438 let last_span = self.last_span;
2439 let fstr = n.as_str();
2440 self.span_err(last_span,
2441 &format!("unexpected token: `{}`", n.as_str()));
2442 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2443 let float = match fstr.parse::<f64>().ok() {
2447 self.fileline_help(last_span,
2448 &format!("try parenthesizing the first index; e.g., `(foo.{}){}`",
2449 float.trunc() as usize,
2450 format!(".{}", fstr.splitn(2, ".").last().unwrap())));
2452 self.abort_if_errors();
2455 _ => return Err(self.unexpected())
2459 if self.expr_is_complete(&*e) { break; }
2462 token::OpenDelim(token::Paren) => {
2463 let es = try!(self.parse_unspanned_seq(
2464 &token::OpenDelim(token::Paren),
2465 &token::CloseDelim(token::Paren),
2466 seq_sep_trailing_allowed(token::Comma),
2467 |p| Ok(try!(p.parse_expr()))
2469 hi = self.last_span.hi;
2471 let nd = self.mk_call(e, es);
2472 e = self.mk_expr(lo, hi, nd, None);
2476 // Could be either an index expression or a slicing expression.
2477 token::OpenDelim(token::Bracket) => {
2479 let ix = try!(self.parse_expr());
2481 try!(self.commit_expr_expecting(&*ix, token::CloseDelim(token::Bracket)));
2482 let index = self.mk_index(e, ix);
2483 e = self.mk_expr(lo, hi, index, None)
2491 // Parse unquoted tokens after a `$` in a token tree
2492 fn parse_unquoted(&mut self) -> PResult<TokenTree> {
2493 let mut sp = self.span;
2494 let (name, namep) = match self.token {
2498 if self.token == token::OpenDelim(token::Paren) {
2499 let Spanned { node: seq, span: seq_span } = try!(self.parse_seq(
2500 &token::OpenDelim(token::Paren),
2501 &token::CloseDelim(token::Paren),
2503 |p| p.parse_token_tree()
2505 let (sep, repeat) = try!(self.parse_sep_and_kleene_op());
2506 let name_num = macro_parser::count_names(&seq);
2507 return Ok(TokenTree::Sequence(mk_sp(sp.lo, seq_span.hi),
2508 Rc::new(SequenceRepetition {
2512 num_captures: name_num
2514 } else if self.token.is_keyword_allow_following_colon(keywords::Crate) {
2516 return Ok(TokenTree::Token(sp, SpecialVarNt(SpecialMacroVar::CrateMacroVar)));
2518 sp = mk_sp(sp.lo, self.span.hi);
2519 let namep = match self.token { token::Ident(_, p) => p, _ => token::Plain };
2520 let name = try!(self.parse_ident());
2524 token::SubstNt(name, namep) => {
2530 // continue by trying to parse the `:ident` after `$name`
2531 if self.token == token::Colon && self.look_ahead(1, |t| t.is_ident() &&
2532 !t.is_strict_keyword() &&
2533 !t.is_reserved_keyword()) {
2535 sp = mk_sp(sp.lo, self.span.hi);
2536 let kindp = match self.token { token::Ident(_, p) => p, _ => token::Plain };
2537 let nt_kind = try!(self.parse_ident());
2538 Ok(TokenTree::Token(sp, MatchNt(name, nt_kind, namep, kindp)))
2540 Ok(TokenTree::Token(sp, SubstNt(name, namep)))
2544 pub fn check_unknown_macro_variable(&mut self) -> PResult<()> {
2545 if self.quote_depth == 0 {
2547 token::SubstNt(name, _) =>
2548 return Err(self.fatal(&format!("unknown macro variable `{}`",
2556 /// Parse an optional separator followed by a Kleene-style
2557 /// repetition token (+ or *).
2558 pub fn parse_sep_and_kleene_op(&mut self) -> PResult<(Option<token::Token>, ast::KleeneOp)> {
2559 fn parse_kleene_op(parser: &mut Parser) -> PResult<Option<ast::KleeneOp>> {
2560 match parser.token {
2561 token::BinOp(token::Star) => {
2562 try!(parser.bump());
2563 Ok(Some(ast::ZeroOrMore))
2565 token::BinOp(token::Plus) => {
2566 try!(parser.bump());
2567 Ok(Some(ast::OneOrMore))
2573 match try!(parse_kleene_op(self)) {
2574 Some(kleene_op) => return Ok((None, kleene_op)),
2578 let separator = try!(self.bump_and_get());
2579 match try!(parse_kleene_op(self)) {
2580 Some(zerok) => Ok((Some(separator), zerok)),
2581 None => return Err(self.fatal("expected `*` or `+`"))
2585 /// parse a single token tree from the input.
2586 pub fn parse_token_tree(&mut self) -> PResult<TokenTree> {
2587 // FIXME #6994: currently, this is too eager. It
2588 // parses token trees but also identifies TokenType::Sequence's
2589 // and token::SubstNt's; it's too early to know yet
2590 // whether something will be a nonterminal or a seq
2592 maybe_whole!(deref self, NtTT);
2594 // this is the fall-through for the 'match' below.
2595 // invariants: the current token is not a left-delimiter,
2596 // not an EOF, and not the desired right-delimiter (if
2597 // it were, parse_seq_to_before_end would have prevented
2598 // reaching this point.
2599 fn parse_non_delim_tt_tok(p: &mut Parser) -> PResult<TokenTree> {
2600 maybe_whole!(deref p, NtTT);
2602 token::CloseDelim(_) => {
2603 // This is a conservative error: only report the last unclosed delimiter. The
2604 // previous unclosed delimiters could actually be closed! The parser just hasn't
2605 // gotten to them yet.
2606 match p.open_braces.last() {
2608 Some(&sp) => p.span_note(sp, "unclosed delimiter"),
2610 let token_str = p.this_token_to_string();
2611 Err(p.fatal(&format!("incorrect close delimiter: `{}`",
2614 /* we ought to allow different depths of unquotation */
2615 token::Dollar | token::SubstNt(..) if p.quote_depth > 0 => {
2619 Ok(TokenTree::Token(p.span, try!(p.bump_and_get())))
2626 let open_braces = self.open_braces.clone();
2627 for sp in &open_braces {
2628 self.span_help(*sp, "did you mean to close this delimiter?");
2630 // There shouldn't really be a span, but it's easier for the test runner
2631 // if we give it one
2632 return Err(self.fatal("this file contains an un-closed delimiter "));
2634 token::OpenDelim(delim) => {
2635 // The span for beginning of the delimited section
2636 let pre_span = self.span;
2638 // Parse the open delimiter.
2639 self.open_braces.push(self.span);
2640 let open_span = self.span;
2643 // Parse the token trees within the delimiters
2644 let tts = try!(self.parse_seq_to_before_end(
2645 &token::CloseDelim(delim),
2647 |p| p.parse_token_tree()
2650 // Parse the close delimiter.
2651 let close_span = self.span;
2653 self.open_braces.pop().unwrap();
2655 // Expand to cover the entire delimited token tree
2656 let span = Span { hi: close_span.hi, ..pre_span };
2658 Ok(TokenTree::Delimited(span, Rc::new(Delimited {
2660 open_span: open_span,
2662 close_span: close_span,
2665 _ => parse_non_delim_tt_tok(self),
2669 // parse a stream of tokens into a list of TokenTree's,
2671 pub fn parse_all_token_trees(&mut self) -> PResult<Vec<TokenTree>> {
2672 let mut tts = Vec::new();
2673 while self.token != token::Eof {
2674 tts.push(try!(self.parse_token_tree()));
2679 /// Parse a prefix-unary-operator expr
2680 pub fn parse_prefix_expr(&mut self,
2681 already_parsed_attrs: Option<ThinAttributes>)
2682 -> PResult<P<Expr>> {
2683 let attrs = try!(self.parse_or_use_outer_attributes(already_parsed_attrs));
2684 let lo = self.span.lo;
2686 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2687 let ex = match self.token {
2690 let e = try!(self.parse_prefix_expr(None));
2692 self.mk_unary(UnNot, e)
2694 token::BinOp(token::Minus) => {
2696 let e = try!(self.parse_prefix_expr(None));
2698 self.mk_unary(UnNeg, e)
2700 token::BinOp(token::Star) => {
2702 let e = try!(self.parse_prefix_expr(None));
2704 self.mk_unary(UnDeref, e)
2706 token::BinOp(token::And) | token::AndAnd => {
2707 try!(self.expect_and());
2708 let m = try!(self.parse_mutability());
2709 let e = try!(self.parse_prefix_expr(None));
2713 token::Ident(..) if self.token.is_keyword(keywords::In) => {
2715 let place = try!(self.parse_expr_res(
2716 Restrictions::RESTRICTION_NO_STRUCT_LITERAL,
2719 let blk = try!(self.parse_block());
2720 let span = blk.span;
2722 let blk_expr = self.mk_expr(span.lo, span.hi, ExprBlock(blk),
2724 ExprInPlace(place, blk_expr)
2726 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
2728 let subexpression = try!(self.parse_prefix_expr(None));
2729 hi = subexpression.span.hi;
2730 ExprBox(subexpression)
2732 _ => return self.parse_dot_or_call_expr(Some(attrs))
2734 return Ok(self.mk_expr(lo, hi, ex, attrs));
2737 /// Parse an associative expression
2739 /// This parses an expression accounting for associativity and precedence of the operators in
2741 pub fn parse_assoc_expr(&mut self,
2742 already_parsed_attrs: Option<ThinAttributes>)
2743 -> PResult<P<Expr>> {
2744 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
2747 /// Parse an associative expression with operators of at least `min_prec` precedence
2748 pub fn parse_assoc_expr_with(&mut self,
2751 -> PResult<P<Expr>> {
2752 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
2755 let attrs = match lhs {
2756 LhsExpr::AttributesParsed(attrs) => Some(attrs),
2759 if self.token == token::DotDot {
2760 return self.parse_prefix_range_expr(attrs);
2762 try!(self.parse_prefix_expr(attrs))
2765 if self.expr_is_complete(&*lhs) {
2766 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
2769 self.expected_tokens.push(TokenType::Operator);
2770 while let Some(op) = AssocOp::from_token(&self.token) {
2771 let cur_op_span = self.span;
2772 let restrictions = if op.is_assign_like() {
2773 self.restrictions & Restrictions::RESTRICTION_NO_STRUCT_LITERAL
2777 if op.precedence() < min_prec {
2781 if op.is_comparison() {
2782 self.check_no_chained_comparison(&*lhs, &op);
2785 if op == AssocOp::As {
2786 let rhs = try!(self.parse_ty());
2787 lhs = self.mk_expr(lhs.span.lo, rhs.span.hi,
2788 ExprCast(lhs, rhs), None);
2790 } else if op == AssocOp::Colon {
2791 let rhs = try!(self.parse_ty());
2792 lhs = self.mk_expr(lhs.span.lo, rhs.span.hi,
2793 ExprType(lhs, rhs), None);
2795 } else if op == AssocOp::DotDot {
2796 // If we didn’t have to handle `x..`, it would be pretty easy to generalise
2797 // it to the Fixity::None code.
2799 // We have 2 alternatives here: `x..y` and `x..` The other two variants are
2800 // handled with `parse_prefix_range_expr` call above.
2801 let rhs = if self.is_at_start_of_range_notation_rhs() {
2802 self.parse_assoc_expr_with(op.precedence() + 1,
2803 LhsExpr::NotYetParsed).ok()
2807 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
2812 let r = self.mk_range(Some(lhs), rhs);
2813 lhs = self.mk_expr(lhs_span.lo, rhs_span.hi, r, None);
2817 let rhs = try!(match op.fixity() {
2818 Fixity::Right => self.with_res(restrictions, |this|{
2819 this.parse_assoc_expr_with(op.precedence(), LhsExpr::NotYetParsed)
2821 Fixity::Left => self.with_res(restrictions, |this|{
2822 this.parse_assoc_expr_with(op.precedence() + 1, LhsExpr::NotYetParsed)
2824 // We currently have no non-associative operators that are not handled above by
2825 // the special cases. The code is here only for future convenience.
2826 Fixity::None => self.with_res(restrictions, |this|{
2827 this.parse_assoc_expr_with(op.precedence() + 1, LhsExpr::NotYetParsed)
2832 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
2833 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
2834 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
2835 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
2836 AssocOp::Greater | AssocOp::GreaterEqual => {
2837 let ast_op = op.to_ast_binop().unwrap();
2838 let (lhs_span, rhs_span) = (lhs.span, rhs.span);
2839 let binary = self.mk_binary(codemap::respan(cur_op_span, ast_op), lhs, rhs);
2840 self.mk_expr(lhs_span.lo, rhs_span.hi, binary, None)
2843 self.mk_expr(lhs.span.lo, rhs.span.hi, ExprAssign(lhs, rhs), None),
2845 self.mk_expr(lhs.span.lo, rhs.span.hi, ExprInPlace(lhs, rhs), None),
2846 AssocOp::AssignOp(k) => {
2848 token::Plus => BiAdd,
2849 token::Minus => BiSub,
2850 token::Star => BiMul,
2851 token::Slash => BiDiv,
2852 token::Percent => BiRem,
2853 token::Caret => BiBitXor,
2854 token::And => BiBitAnd,
2855 token::Or => BiBitOr,
2856 token::Shl => BiShl,
2859 let (lhs_span, rhs_span) = (lhs.span, rhs.span);
2860 let aopexpr = self.mk_assign_op(codemap::respan(cur_op_span, aop), lhs, rhs);
2861 self.mk_expr(lhs_span.lo, rhs_span.hi, aopexpr, None)
2863 AssocOp::As | AssocOp::Colon | AssocOp::DotDot => {
2864 self.bug("As, Colon or DotDot branch reached")
2868 if op.fixity() == Fixity::None { break }
2873 /// Produce an error if comparison operators are chained (RFC #558).
2874 /// We only need to check lhs, not rhs, because all comparison ops
2875 /// have same precedence and are left-associative
2876 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
2877 debug_assert!(outer_op.is_comparison());
2879 ExprBinary(op, _, _) if op.node.is_comparison() => {
2880 // respan to include both operators
2881 let op_span = mk_sp(op.span.lo, self.span.hi);
2882 self.span_err(op_span,
2883 "chained comparison operators require parentheses");
2884 if op.node == BiLt && *outer_op == AssocOp::Greater {
2885 self.fileline_help(op_span,
2886 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
2893 /// Parse prefix-forms of range notation: `..expr` and `..`
2894 fn parse_prefix_range_expr(&mut self,
2895 already_parsed_attrs: Option<ThinAttributes>)
2896 -> PResult<P<Expr>> {
2897 debug_assert!(self.token == token::DotDot);
2898 let attrs = try!(self.parse_or_use_outer_attributes(already_parsed_attrs));
2899 let lo = self.span.lo;
2900 let mut hi = self.span.hi;
2902 let opt_end = if self.is_at_start_of_range_notation_rhs() {
2903 // RHS must be parsed with more associativity than DotDot.
2904 let next_prec = AssocOp::from_token(&token::DotDot).unwrap().precedence() + 1;
2905 Some(try!(self.parse_assoc_expr_with(next_prec,
2906 LhsExpr::NotYetParsed)
2914 let r = self.mk_range(None, opt_end);
2915 Ok(self.mk_expr(lo, hi, r, attrs))
2918 fn is_at_start_of_range_notation_rhs(&self) -> bool {
2919 if self.token.can_begin_expr() {
2920 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
2921 if self.token == token::OpenDelim(token::Brace) {
2922 return !self.restrictions.contains(Restrictions::RESTRICTION_NO_STRUCT_LITERAL);
2930 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
2931 pub fn parse_if_expr(&mut self, attrs: ThinAttributes) -> PResult<P<Expr>> {
2932 if self.check_keyword(keywords::Let) {
2933 return self.parse_if_let_expr(attrs);
2935 let lo = self.last_span.lo;
2936 let cond = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
2937 let thn = try!(self.parse_block());
2938 let mut els: Option<P<Expr>> = None;
2939 let mut hi = thn.span.hi;
2940 if try!(self.eat_keyword(keywords::Else) ){
2941 let elexpr = try!(self.parse_else_expr());
2942 hi = elexpr.span.hi;
2945 Ok(self.mk_expr(lo, hi, ExprIf(cond, thn, els), attrs))
2948 /// Parse an 'if let' expression ('if' token already eaten)
2949 pub fn parse_if_let_expr(&mut self, attrs: ThinAttributes)
2950 -> PResult<P<Expr>> {
2951 let lo = self.last_span.lo;
2952 try!(self.expect_keyword(keywords::Let));
2953 let pat = try!(self.parse_pat());
2954 try!(self.expect(&token::Eq));
2955 let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
2956 let thn = try!(self.parse_block());
2957 let (hi, els) = if try!(self.eat_keyword(keywords::Else) ){
2958 let expr = try!(self.parse_else_expr());
2959 (expr.span.hi, Some(expr))
2963 Ok(self.mk_expr(lo, hi, ExprIfLet(pat, expr, thn, els), attrs))
2967 pub fn parse_lambda_expr(&mut self, lo: BytePos,
2968 capture_clause: CaptureClause,
2969 attrs: ThinAttributes)
2972 let decl = try!(self.parse_fn_block_decl());
2973 let body = match decl.output {
2974 DefaultReturn(_) => {
2975 // If no explicit return type is given, parse any
2976 // expr and wrap it up in a dummy block:
2977 let body_expr = try!(self.parse_expr());
2979 id: ast::DUMMY_NODE_ID,
2981 span: body_expr.span,
2982 expr: Some(body_expr),
2983 rules: DefaultBlock,
2987 // If an explicit return type is given, require a
2988 // block to appear (RFC 968).
2989 try!(self.parse_block())
2996 ExprClosure(capture_clause, decl, body), attrs))
2999 // `else` token already eaten
3000 pub fn parse_else_expr(&mut self) -> PResult<P<Expr>> {
3001 if try!(self.eat_keyword(keywords::If) ){
3002 return self.parse_if_expr(None);
3004 let blk = try!(self.parse_block());
3005 return Ok(self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk), None));
3009 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3010 pub fn parse_for_expr(&mut self, opt_ident: Option<ast::Ident>,
3012 attrs: ThinAttributes) -> PResult<P<Expr>> {
3013 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3015 let pat = try!(self.parse_pat());
3016 try!(self.expect_keyword(keywords::In));
3017 let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3018 let (iattrs, loop_block) = try!(self.parse_inner_attrs_and_block());
3019 let attrs = attrs.append(iattrs.into_thin_attrs());
3021 let hi = self.last_span.hi;
3023 Ok(self.mk_expr(span_lo, hi,
3024 ExprForLoop(pat, expr, loop_block, opt_ident),
3028 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3029 pub fn parse_while_expr(&mut self, opt_ident: Option<ast::Ident>,
3031 attrs: ThinAttributes) -> PResult<P<Expr>> {
3032 if self.token.is_keyword(keywords::Let) {
3033 return self.parse_while_let_expr(opt_ident, span_lo, attrs);
3035 let cond = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3036 let (iattrs, body) = try!(self.parse_inner_attrs_and_block());
3037 let attrs = attrs.append(iattrs.into_thin_attrs());
3038 let hi = body.span.hi;
3039 return Ok(self.mk_expr(span_lo, hi, ExprWhile(cond, body, opt_ident),
3043 /// Parse a 'while let' expression ('while' token already eaten)
3044 pub fn parse_while_let_expr(&mut self, opt_ident: Option<ast::Ident>,
3046 attrs: ThinAttributes) -> PResult<P<Expr>> {
3047 try!(self.expect_keyword(keywords::Let));
3048 let pat = try!(self.parse_pat());
3049 try!(self.expect(&token::Eq));
3050 let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3051 let (iattrs, body) = try!(self.parse_inner_attrs_and_block());
3052 let attrs = attrs.append(iattrs.into_thin_attrs());
3053 let hi = body.span.hi;
3054 return Ok(self.mk_expr(span_lo, hi, ExprWhileLet(pat, expr, body, opt_ident), attrs));
3057 // parse `loop {...}`, `loop` token already eaten
3058 pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::Ident>,
3060 attrs: ThinAttributes) -> PResult<P<Expr>> {
3061 let (iattrs, body) = try!(self.parse_inner_attrs_and_block());
3062 let attrs = attrs.append(iattrs.into_thin_attrs());
3063 let hi = body.span.hi;
3064 Ok(self.mk_expr(span_lo, hi, ExprLoop(body, opt_ident), attrs))
3067 // `match` token already eaten
3068 fn parse_match_expr(&mut self, attrs: ThinAttributes) -> PResult<P<Expr>> {
3069 let match_span = self.last_span;
3070 let lo = self.last_span.lo;
3071 let discriminant = try!(self.parse_expr_res(
3072 Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3073 if let Err(e) = self.commit_expr_expecting(&*discriminant, token::OpenDelim(token::Brace)) {
3074 if self.token == token::Token::Semi {
3075 self.span_note(match_span, "did you mean to remove this `match` keyword?");
3079 let attrs = attrs.append(
3080 try!(self.parse_inner_attributes()).into_thin_attrs());
3081 let mut arms: Vec<Arm> = Vec::new();
3082 while self.token != token::CloseDelim(token::Brace) {
3083 arms.push(try!(self.parse_arm()));
3085 let hi = self.span.hi;
3087 return Ok(self.mk_expr(lo, hi, ExprMatch(discriminant, arms), attrs));
3090 pub fn parse_arm(&mut self) -> PResult<Arm> {
3091 maybe_whole!(no_clone self, NtArm);
3093 let attrs = try!(self.parse_outer_attributes());
3094 let pats = try!(self.parse_pats());
3095 let mut guard = None;
3096 if try!(self.eat_keyword(keywords::If) ){
3097 guard = Some(try!(self.parse_expr()));
3099 try!(self.expect(&token::FatArrow));
3100 let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_STMT_EXPR, None));
3103 !classify::expr_is_simple_block(&*expr)
3104 && self.token != token::CloseDelim(token::Brace);
3107 try!(self.commit_expr(&*expr, &[token::Comma], &[token::CloseDelim(token::Brace)]));
3109 try!(self.eat(&token::Comma));
3120 /// Parse an expression
3121 pub fn parse_expr(&mut self) -> PResult<P<Expr>> {
3122 self.parse_expr_res(Restrictions::empty(), None)
3125 /// Evaluate the closure with restrictions in place.
3127 /// After the closure is evaluated, restrictions are reset.
3128 pub fn with_res<F>(&mut self, r: Restrictions, f: F) -> PResult<P<Expr>>
3129 where F: FnOnce(&mut Self) -> PResult<P<Expr>> {
3130 let old = self.restrictions;
3131 self.restrictions = r;
3133 self.restrictions = old;
3138 /// Parse an expression, subject to the given restrictions
3139 pub fn parse_expr_res(&mut self, r: Restrictions,
3140 already_parsed_attrs: Option<ThinAttributes>)
3141 -> PResult<P<Expr>> {
3142 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3145 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3146 fn parse_initializer(&mut self) -> PResult<Option<P<Expr>>> {
3147 if self.check(&token::Eq) {
3149 Ok(Some(try!(self.parse_expr())))
3155 /// Parse patterns, separated by '|' s
3156 fn parse_pats(&mut self) -> PResult<Vec<P<Pat>>> {
3157 let mut pats = Vec::new();
3159 pats.push(try!(self.parse_pat()));
3160 if self.check(&token::BinOp(token::Or)) { try!(self.bump());}
3161 else { return Ok(pats); }
3165 fn parse_pat_tuple_elements(&mut self) -> PResult<Vec<P<Pat>>> {
3166 let mut fields = vec![];
3167 if !self.check(&token::CloseDelim(token::Paren)) {
3168 fields.push(try!(self.parse_pat()));
3169 if self.look_ahead(1, |t| *t != token::CloseDelim(token::Paren)) {
3170 while try!(self.eat(&token::Comma)) &&
3171 !self.check(&token::CloseDelim(token::Paren)) {
3172 fields.push(try!(self.parse_pat()));
3175 if fields.len() == 1 {
3176 try!(self.expect(&token::Comma));
3182 fn parse_pat_vec_elements(
3184 ) -> PResult<(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3185 let mut before = Vec::new();
3186 let mut slice = None;
3187 let mut after = Vec::new();
3188 let mut first = true;
3189 let mut before_slice = true;
3191 while self.token != token::CloseDelim(token::Bracket) {
3195 try!(self.expect(&token::Comma));
3197 if self.token == token::CloseDelim(token::Bracket)
3198 && (before_slice || !after.is_empty()) {
3204 if self.check(&token::DotDot) {
3207 if self.check(&token::Comma) ||
3208 self.check(&token::CloseDelim(token::Bracket)) {
3209 slice = Some(P(ast::Pat {
3210 id: ast::DUMMY_NODE_ID,
3214 before_slice = false;
3220 let subpat = try!(self.parse_pat());
3221 if before_slice && self.check(&token::DotDot) {
3223 slice = Some(subpat);
3224 before_slice = false;
3225 } else if before_slice {
3226 before.push(subpat);
3232 Ok((before, slice, after))
3235 /// Parse the fields of a struct-like pattern
3236 fn parse_pat_fields(&mut self) -> PResult<(Vec<codemap::Spanned<ast::FieldPat>> , bool)> {
3237 let mut fields = Vec::new();
3238 let mut etc = false;
3239 let mut first = true;
3240 while self.token != token::CloseDelim(token::Brace) {
3244 try!(self.expect(&token::Comma));
3245 // accept trailing commas
3246 if self.check(&token::CloseDelim(token::Brace)) { break }
3249 let lo = self.span.lo;
3252 if self.check(&token::DotDot) {
3254 if self.token != token::CloseDelim(token::Brace) {
3255 let token_str = self.this_token_to_string();
3256 return Err(self.fatal(&format!("expected `{}`, found `{}`", "}",
3263 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3264 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3265 // Parsing a pattern of the form "fieldname: pat"
3266 let fieldname = try!(self.parse_ident());
3268 let pat = try!(self.parse_pat());
3270 (pat, fieldname, false)
3272 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3273 let is_box = try!(self.eat_keyword(keywords::Box));
3274 let boxed_span_lo = self.span.lo;
3275 let is_ref = try!(self.eat_keyword(keywords::Ref));
3276 let is_mut = try!(self.eat_keyword(keywords::Mut));
3277 let fieldname = try!(self.parse_ident());
3278 hi = self.last_span.hi;
3280 let bind_type = match (is_ref, is_mut) {
3281 (true, true) => BindByRef(MutMutable),
3282 (true, false) => BindByRef(MutImmutable),
3283 (false, true) => BindByValue(MutMutable),
3284 (false, false) => BindByValue(MutImmutable),
3286 let fieldpath = codemap::Spanned{span:self.last_span, node:fieldname};
3287 let fieldpat = P(ast::Pat{
3288 id: ast::DUMMY_NODE_ID,
3289 node: PatIdent(bind_type, fieldpath, None),
3290 span: mk_sp(boxed_span_lo, hi),
3293 let subpat = if is_box {
3295 id: ast::DUMMY_NODE_ID,
3296 node: PatBox(fieldpat),
3297 span: mk_sp(lo, hi),
3302 (subpat, fieldname, true)
3305 fields.push(codemap::Spanned { span: mk_sp(lo, hi),
3306 node: ast::FieldPat { ident: fieldname,
3308 is_shorthand: is_shorthand }});
3310 return Ok((fields, etc));
3313 fn parse_pat_range_end(&mut self) -> PResult<P<Expr>> {
3314 if self.is_path_start() {
3315 let lo = self.span.lo;
3316 let (qself, path) = if try!(self.eat_lt()) {
3317 // Parse a qualified path
3319 try!(self.parse_qualified_path(NoTypesAllowed));
3322 // Parse an unqualified path
3323 (None, try!(self.parse_path(LifetimeAndTypesWithColons)))
3325 let hi = self.last_span.hi;
3326 Ok(self.mk_expr(lo, hi, ExprPath(qself, path), None))
3328 self.parse_pat_literal_maybe_minus()
3332 fn is_path_start(&self) -> bool {
3333 (self.token == token::Lt || self.token == token::ModSep
3334 || self.token.is_ident() || self.token.is_path())
3335 && !self.token.is_keyword(keywords::True) && !self.token.is_keyword(keywords::False)
3338 /// Parse a pattern.
3339 pub fn parse_pat(&mut self) -> PResult<P<Pat>> {
3340 maybe_whole!(self, NtPat);
3342 let lo = self.span.lo;
3345 token::Underscore => {
3350 token::BinOp(token::And) | token::AndAnd => {
3351 // Parse &pat / &mut pat
3352 try!(self.expect_and());
3353 let mutbl = try!(self.parse_mutability());
3354 if let token::Lifetime(ident) = self.token {
3355 return Err(self.fatal(&format!("unexpected lifetime `{}` in pattern", ident)));
3358 let subpat = try!(self.parse_pat());
3359 pat = PatRegion(subpat, mutbl);
3361 token::OpenDelim(token::Paren) => {
3362 // Parse (pat,pat,pat,...) as tuple pattern
3364 let fields = try!(self.parse_pat_tuple_elements());
3365 try!(self.expect(&token::CloseDelim(token::Paren)));
3366 pat = PatTup(fields);
3368 token::OpenDelim(token::Bracket) => {
3369 // Parse [pat,pat,...] as slice pattern
3371 let (before, slice, after) = try!(self.parse_pat_vec_elements());
3372 try!(self.expect(&token::CloseDelim(token::Bracket)));
3373 pat = PatVec(before, slice, after);
3376 // At this point, token != _, &, &&, (, [
3377 if try!(self.eat_keyword(keywords::Mut)) {
3378 // Parse mut ident @ pat
3379 pat = try!(self.parse_pat_ident(BindByValue(MutMutable)));
3380 } else if try!(self.eat_keyword(keywords::Ref)) {
3381 // Parse ref ident @ pat / ref mut ident @ pat
3382 let mutbl = try!(self.parse_mutability());
3383 pat = try!(self.parse_pat_ident(BindByRef(mutbl)));
3384 } else if try!(self.eat_keyword(keywords::Box)) {
3386 let subpat = try!(self.parse_pat());
3387 pat = PatBox(subpat);
3388 } else if self.is_path_start() {
3389 // Parse pattern starting with a path
3390 if self.token.is_plain_ident() && self.look_ahead(1, |t| *t != token::DotDotDot &&
3391 *t != token::OpenDelim(token::Brace) &&
3392 *t != token::OpenDelim(token::Paren) &&
3393 // Contrary to its definition, a plain ident can be followed by :: in macros
3394 *t != token::ModSep) {
3395 // Plain idents have some extra abilities here compared to general paths
3396 if self.look_ahead(1, |t| *t == token::Not) {
3397 // Parse macro invocation
3398 let ident = try!(self.parse_ident());
3399 let ident_span = self.last_span;
3400 let path = ident_to_path(ident_span, ident);
3402 let delim = try!(self.expect_open_delim());
3403 let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
3404 seq_sep_none(), |p| p.parse_token_tree()));
3405 let mac = Mac_ { path: path, tts: tts, ctxt: EMPTY_CTXT };
3406 pat = PatMac(codemap::Spanned {node: mac,
3407 span: mk_sp(lo, self.last_span.hi)});
3409 // Parse ident @ pat
3410 // This can give false positives and parse nullary enums,
3411 // they are dealt with later in resolve
3412 pat = try!(self.parse_pat_ident(BindByValue(MutImmutable)));
3415 let (qself, path) = if try!(self.eat_lt()) {
3416 // Parse a qualified path
3418 try!(self.parse_qualified_path(NoTypesAllowed));
3421 // Parse an unqualified path
3422 (None, try!(self.parse_path(LifetimeAndTypesWithColons)))
3425 token::DotDotDot => {
3427 let hi = self.last_span.hi;
3428 let begin = self.mk_expr(lo, hi, ExprPath(qself, path), None);
3430 let end = try!(self.parse_pat_range_end());
3431 pat = PatRange(begin, end);
3433 token::OpenDelim(token::Brace) => {
3434 if qself.is_some() {
3435 return Err(self.fatal("unexpected `{` after qualified path"));
3437 // Parse struct pattern
3439 let (fields, etc) = try!(self.parse_pat_fields());
3441 pat = PatStruct(path, fields, etc);
3443 token::OpenDelim(token::Paren) => {
3444 if qself.is_some() {
3445 return Err(self.fatal("unexpected `(` after qualified path"));
3447 // Parse tuple struct or enum pattern
3448 if self.look_ahead(1, |t| *t == token::DotDot) {
3449 // This is a "top constructor only" pat
3452 try!(self.expect(&token::CloseDelim(token::Paren)));
3453 pat = PatEnum(path, None);
3455 let args = try!(self.parse_enum_variant_seq(
3456 &token::OpenDelim(token::Paren),
3457 &token::CloseDelim(token::Paren),
3458 seq_sep_trailing_allowed(token::Comma),
3459 |p| p.parse_pat()));
3460 pat = PatEnum(path, Some(args));
3465 // Parse qualified path
3466 Some(qself) => PatQPath(qself, path),
3467 // Parse nullary enum
3468 None => PatEnum(path, Some(vec![]))
3474 // Try to parse everything else as literal with optional minus
3475 let begin = try!(self.parse_pat_literal_maybe_minus());
3476 if try!(self.eat(&token::DotDotDot)) {
3477 let end = try!(self.parse_pat_range_end());
3478 pat = PatRange(begin, end);
3480 pat = PatLit(begin);
3486 let hi = self.last_span.hi;
3488 id: ast::DUMMY_NODE_ID,
3490 span: mk_sp(lo, hi),
3494 /// Parse ident or ident @ pat
3495 /// used by the copy foo and ref foo patterns to give a good
3496 /// error message when parsing mistakes like ref foo(a,b)
3497 fn parse_pat_ident(&mut self,
3498 binding_mode: ast::BindingMode)
3499 -> PResult<ast::Pat_> {
3500 if !self.token.is_plain_ident() {
3501 let span = self.span;
3502 let tok_str = self.this_token_to_string();
3503 return Err(self.span_fatal(span,
3504 &format!("expected identifier, found `{}`", tok_str)))
3506 let ident = try!(self.parse_ident());
3507 let last_span = self.last_span;
3508 let name = codemap::Spanned{span: last_span, node: ident};
3509 let sub = if try!(self.eat(&token::At) ){
3510 Some(try!(self.parse_pat()))
3515 // just to be friendly, if they write something like
3517 // we end up here with ( as the current token. This shortly
3518 // leads to a parse error. Note that if there is no explicit
3519 // binding mode then we do not end up here, because the lookahead
3520 // will direct us over to parse_enum_variant()
3521 if self.token == token::OpenDelim(token::Paren) {
3522 let last_span = self.last_span;
3523 return Err(self.span_fatal(
3525 "expected identifier, found enum pattern"))
3528 Ok(PatIdent(binding_mode, name, sub))
3531 /// Parse a local variable declaration
3532 fn parse_local(&mut self, attrs: ThinAttributes) -> PResult<P<Local>> {
3533 let lo = self.span.lo;
3534 let pat = try!(self.parse_pat());
3537 if try!(self.eat(&token::Colon) ){
3538 ty = Some(try!(self.parse_ty_sum()));
3540 let init = try!(self.parse_initializer());
3545 id: ast::DUMMY_NODE_ID,
3546 span: mk_sp(lo, self.last_span.hi),
3551 /// Parse a "let" stmt
3552 fn parse_let(&mut self, attrs: ThinAttributes) -> PResult<P<Decl>> {
3553 let lo = self.span.lo;
3554 let local = try!(self.parse_local(attrs));
3555 Ok(P(spanned(lo, self.last_span.hi, DeclLocal(local))))
3558 /// Parse a structure field
3559 fn parse_name_and_ty(&mut self, pr: Visibility,
3560 attrs: Vec<Attribute> ) -> PResult<StructField> {
3562 Inherited => self.span.lo,
3563 Public => self.last_span.lo,
3565 if !self.token.is_plain_ident() {
3566 return Err(self.fatal("expected ident"));
3568 let name = try!(self.parse_ident());
3569 try!(self.expect(&token::Colon));
3570 let ty = try!(self.parse_ty_sum());
3571 Ok(spanned(lo, self.last_span.hi, ast::StructField_ {
3572 kind: NamedField(name, pr),
3573 id: ast::DUMMY_NODE_ID,
3579 /// Emit an expected item after attributes error.
3580 fn expected_item_err(&self, attrs: &[Attribute]) {
3581 let message = match attrs.last() {
3582 Some(&Attribute { node: ast::Attribute_ { is_sugared_doc: true, .. }, .. }) => {
3583 "expected item after doc comment"
3585 _ => "expected item after attributes",
3588 self.span_err(self.last_span, message);
3591 /// Parse a statement. may include decl.
3592 pub fn parse_stmt(&mut self) -> PResult<Option<P<Stmt>>> {
3593 Ok(try!(self.parse_stmt_()).map(P))
3596 fn parse_stmt_(&mut self) -> PResult<Option<Stmt>> {
3597 maybe_whole!(Some deref self, NtStmt);
3599 let attrs = try!(self.parse_outer_attributes());
3600 let lo = self.span.lo;
3602 Ok(Some(if self.check_keyword(keywords::Let) {
3603 try!(self.expect_keyword(keywords::Let));
3604 let decl = try!(self.parse_let(attrs.into_thin_attrs()));
3605 let hi = decl.span.hi;
3606 let stmt = StmtDecl(decl, ast::DUMMY_NODE_ID);
3607 spanned(lo, hi, stmt)
3608 } else if self.token.is_ident()
3609 && !self.token.is_any_keyword()
3610 && self.look_ahead(1, |t| *t == token::Not) {
3611 // it's a macro invocation:
3613 // Potential trouble: if we allow macros with paths instead of
3614 // idents, we'd need to look ahead past the whole path here...
3615 let pth = try!(self.parse_path(NoTypesAllowed));
3618 let id = match self.token {
3619 token::OpenDelim(_) => token::special_idents::invalid, // no special identifier
3620 _ => try!(self.parse_ident()),
3623 // check that we're pointing at delimiters (need to check
3624 // again after the `if`, because of `parse_ident`
3625 // consuming more tokens).
3626 let delim = match self.token {
3627 token::OpenDelim(delim) => delim,
3629 // we only expect an ident if we didn't parse one
3631 let ident_str = if id.name == token::special_idents::invalid.name {
3636 let tok_str = self.this_token_to_string();
3637 return Err(self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
3643 let tts = try!(self.parse_unspanned_seq(
3644 &token::OpenDelim(delim),
3645 &token::CloseDelim(delim),
3647 |p| p.parse_token_tree()
3649 let hi = self.last_span.hi;
3651 let style = if delim == token::Brace {
3654 MacStmtWithoutBraces
3657 if id.name == token::special_idents::invalid.name {
3658 let stmt = StmtMac(P(spanned(lo,
3660 Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT })),
3662 attrs.into_thin_attrs());
3663 spanned(lo, hi, stmt)
3665 // if it has a special ident, it's definitely an item
3667 // Require a semicolon or braces.
3668 if style != MacStmtWithBraces {
3669 if !try!(self.eat(&token::Semi) ){
3670 let last_span = self.last_span;
3671 self.span_err(last_span,
3672 "macros that expand to items must \
3673 either be surrounded with braces or \
3674 followed by a semicolon");
3677 spanned(lo, hi, StmtDecl(
3678 P(spanned(lo, hi, DeclItem(
3680 lo, hi, id /*id is good here*/,
3681 ItemMac(spanned(lo, hi,
3682 Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT })),
3683 Inherited, attrs)))),
3684 ast::DUMMY_NODE_ID))
3687 // FIXME: Bad copy of attrs
3688 match try!(self.parse_item_(attrs.clone(), false, true)) {
3691 let decl = P(spanned(lo, hi, DeclItem(i)));
3692 spanned(lo, hi, StmtDecl(decl, ast::DUMMY_NODE_ID))
3695 let unused_attrs = |attrs: &[_], s: &mut Self| {
3696 if attrs.len() > 0 {
3698 "expected statement after outer attribute");
3702 // Do not attempt to parse an expression if we're done here.
3703 if self.token == token::Semi {
3704 unused_attrs(&attrs, self);
3709 if self.token == token::CloseDelim(token::Brace) {
3710 unused_attrs(&attrs, self);
3714 // Remainder are line-expr stmts.
3715 let e = try!(self.parse_expr_res(
3716 Restrictions::RESTRICTION_STMT_EXPR, Some(attrs.into_thin_attrs())));
3718 let stmt = StmtExpr(e, ast::DUMMY_NODE_ID);
3719 spanned(lo, hi, stmt)
3725 /// Is this expression a successfully-parsed statement?
3726 fn expr_is_complete(&mut self, e: &Expr) -> bool {
3727 self.restrictions.contains(Restrictions::RESTRICTION_STMT_EXPR) &&
3728 !classify::expr_requires_semi_to_be_stmt(e)
3731 /// Parse a block. No inner attrs are allowed.
3732 pub fn parse_block(&mut self) -> PResult<P<Block>> {
3733 maybe_whole!(no_clone self, NtBlock);
3735 let lo = self.span.lo;
3737 if !try!(self.eat(&token::OpenDelim(token::Brace)) ){
3739 let tok = self.this_token_to_string();
3740 return Err(self.span_fatal_help(sp,
3741 &format!("expected `{{`, found `{}`", tok),
3742 "place this code inside a block"));
3745 self.parse_block_tail(lo, DefaultBlock)
3748 /// Parse a block. Inner attrs are allowed.
3749 fn parse_inner_attrs_and_block(&mut self) -> PResult<(Vec<Attribute>, P<Block>)> {
3750 maybe_whole!(pair_empty self, NtBlock);
3752 let lo = self.span.lo;
3753 try!(self.expect(&token::OpenDelim(token::Brace)));
3754 Ok((try!(self.parse_inner_attributes()),
3755 try!(self.parse_block_tail(lo, DefaultBlock))))
3758 /// Parse the rest of a block expression or function body
3759 /// Precondition: already parsed the '{'.
3760 fn parse_block_tail(&mut self, lo: BytePos, s: BlockCheckMode) -> PResult<P<Block>> {
3761 let mut stmts = vec![];
3762 let mut expr = None;
3764 while !try!(self.eat(&token::CloseDelim(token::Brace))) {
3765 let Spanned {node, span} = if let Some(s) = try!(self.parse_stmt_()) {
3768 // Found only `;` or `}`.
3773 try!(self.handle_expression_like_statement(e, span, &mut stmts, &mut expr));
3775 StmtMac(mac, MacStmtWithoutBraces, attrs) => {
3776 // statement macro without braces; might be an
3777 // expr depending on whether a semicolon follows
3780 stmts.push(P(Spanned {
3781 node: StmtMac(mac, MacStmtWithSemicolon, attrs),
3782 span: mk_sp(span.lo, self.span.hi),
3787 let e = self.mk_mac_expr(span.lo, span.hi,
3788 mac.and_then(|m| m.node),
3790 let e = try!(self.parse_dot_or_call_expr_with(e, attrs));
3791 let e = try!(self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e)));
3792 try!(self.handle_expression_like_statement(
3800 StmtMac(m, style, attrs) => {
3801 // statement macro; might be an expr
3804 stmts.push(P(Spanned {
3805 node: StmtMac(m, MacStmtWithSemicolon, attrs),
3806 span: mk_sp(span.lo, self.span.hi),
3810 token::CloseDelim(token::Brace) => {
3811 // if a block ends in `m!(arg)` without
3812 // a `;`, it must be an expr
3813 expr = Some(self.mk_mac_expr(span.lo, span.hi,
3814 m.and_then(|x| x.node),
3818 stmts.push(P(Spanned {
3819 node: StmtMac(m, style, attrs),
3825 _ => { // all other kinds of statements:
3826 let mut hi = span.hi;
3827 if classify::stmt_ends_with_semi(&node) {
3828 try!(self.commit_stmt_expecting(token::Semi));
3829 hi = self.last_span.hi;
3832 stmts.push(P(Spanned {
3834 span: mk_sp(span.lo, hi)
3843 id: ast::DUMMY_NODE_ID,
3845 span: mk_sp(lo, self.last_span.hi),
3849 fn handle_expression_like_statement(
3853 stmts: &mut Vec<P<Stmt>>,
3854 last_block_expr: &mut Option<P<Expr>>) -> PResult<()> {
3855 // expression without semicolon
3856 if classify::expr_requires_semi_to_be_stmt(&*e) {
3857 // Just check for errors and recover; do not eat semicolon yet.
3858 try!(self.commit_stmt(&[],
3859 &[token::Semi, token::CloseDelim(token::Brace)]));
3865 let span_with_semi = Span {
3867 hi: self.last_span.hi,
3868 expn_id: span.expn_id,
3870 stmts.push(P(Spanned {
3871 node: StmtSemi(e, ast::DUMMY_NODE_ID),
3872 span: span_with_semi,
3875 token::CloseDelim(token::Brace) => *last_block_expr = Some(e),
3877 stmts.push(P(Spanned {
3878 node: StmtExpr(e, ast::DUMMY_NODE_ID),
3886 // Parses a sequence of bounds if a `:` is found,
3887 // otherwise returns empty list.
3888 fn parse_colon_then_ty_param_bounds(&mut self,
3889 mode: BoundParsingMode)
3890 -> PResult<TyParamBounds>
3892 if !try!(self.eat(&token::Colon) ){
3895 self.parse_ty_param_bounds(mode)
3899 // matches bounds = ( boundseq )?
3900 // where boundseq = ( polybound + boundseq ) | polybound
3901 // and polybound = ( 'for' '<' 'region '>' )? bound
3902 // and bound = 'region | trait_ref
3903 fn parse_ty_param_bounds(&mut self,
3904 mode: BoundParsingMode)
3905 -> PResult<TyParamBounds>
3907 let mut result = vec!();
3909 let question_span = self.span;
3910 let ate_question = try!(self.eat(&token::Question));
3912 token::Lifetime(lifetime) => {
3914 self.span_err(question_span,
3915 "`?` may only modify trait bounds, not lifetime bounds");
3917 result.push(RegionTyParamBound(ast::Lifetime {
3918 id: ast::DUMMY_NODE_ID,
3924 token::ModSep | token::Ident(..) => {
3925 let poly_trait_ref = try!(self.parse_poly_trait_ref());
3926 let modifier = if ate_question {
3927 if mode == BoundParsingMode::Modified {
3928 TraitBoundModifier::Maybe
3930 self.span_err(question_span,
3932 TraitBoundModifier::None
3935 TraitBoundModifier::None
3937 result.push(TraitTyParamBound(poly_trait_ref, modifier))
3942 if !try!(self.eat(&token::BinOp(token::Plus)) ){
3947 return Ok(P::from_vec(result));
3950 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
3951 fn parse_ty_param(&mut self) -> PResult<TyParam> {
3952 let span = self.span;
3953 let ident = try!(self.parse_ident());
3955 let bounds = try!(self.parse_colon_then_ty_param_bounds(BoundParsingMode::Modified));
3957 let default = if self.check(&token::Eq) {
3959 Some(try!(self.parse_ty_sum()))
3966 id: ast::DUMMY_NODE_ID,
3973 /// Parse a set of optional generic type parameter declarations. Where
3974 /// clauses are not parsed here, and must be added later via
3975 /// `parse_where_clause()`.
3977 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
3978 /// | ( < lifetimes , typaramseq ( , )? > )
3979 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
3980 pub fn parse_generics(&mut self) -> PResult<ast::Generics> {
3981 maybe_whole!(self, NtGenerics);
3983 if try!(self.eat(&token::Lt) ){
3984 let lifetime_defs = try!(self.parse_lifetime_defs());
3985 let mut seen_default = false;
3986 let ty_params = try!(self.parse_seq_to_gt(Some(token::Comma), |p| {
3987 try!(p.forbid_lifetime());
3988 let ty_param = try!(p.parse_ty_param());
3989 if ty_param.default.is_some() {
3990 seen_default = true;
3991 } else if seen_default {
3992 let last_span = p.last_span;
3993 p.span_err(last_span,
3994 "type parameters with a default must be trailing");
3999 lifetimes: lifetime_defs,
4000 ty_params: ty_params,
4001 where_clause: WhereClause {
4002 id: ast::DUMMY_NODE_ID,
4003 predicates: Vec::new(),
4007 Ok(ast::Generics::default())
4011 fn parse_generic_values_after_lt(&mut self) -> PResult<(Vec<ast::Lifetime>,
4013 Vec<P<TypeBinding>>)> {
4014 let span_lo = self.span.lo;
4015 let lifetimes = try!(self.parse_lifetimes(token::Comma));
4017 let missing_comma = !lifetimes.is_empty() &&
4018 !self.token.is_like_gt() &&
4020 .as_ref().map_or(true,
4021 |x| &**x != &token::Comma);
4025 let msg = format!("expected `,` or `>` after lifetime \
4027 self.this_token_to_string());
4028 self.span_err(self.span, &msg);
4030 let span_hi = self.span.hi;
4031 let span_hi = if self.parse_ty().is_ok() {
4037 let msg = format!("did you mean a single argument type &'a Type, \
4038 or did you mean the comma-separated arguments \
4040 self.span_note(mk_sp(span_lo, span_hi), &msg);
4042 self.abort_if_errors()
4045 // First parse types.
4046 let (types, returned) = try!(self.parse_seq_to_gt_or_return(
4049 try!(p.forbid_lifetime());
4050 if p.look_ahead(1, |t| t == &token::Eq) {
4053 Ok(Some(try!(p.parse_ty_sum())))
4058 // If we found the `>`, don't continue.
4060 return Ok((lifetimes, types.into_vec(), Vec::new()));
4063 // Then parse type bindings.
4064 let bindings = try!(self.parse_seq_to_gt(
4067 try!(p.forbid_lifetime());
4069 let ident = try!(p.parse_ident());
4070 let found_eq = try!(p.eat(&token::Eq));
4073 p.span_warn(span, "whoops, no =?");
4075 let ty = try!(p.parse_ty());
4076 let hi = ty.span.hi;
4077 let span = mk_sp(lo, hi);
4078 return Ok(P(TypeBinding{id: ast::DUMMY_NODE_ID,
4085 Ok((lifetimes, types.into_vec(), bindings.into_vec()))
4088 fn forbid_lifetime(&mut self) -> PResult<()> {
4089 if self.token.is_lifetime() {
4090 let span = self.span;
4091 return Err(self.span_fatal(span, "lifetime parameters must be declared \
4092 prior to type parameters"))
4097 /// Parses an optional `where` clause and places it in `generics`.
4100 /// where T : Trait<U, V> + 'b, 'a : 'b
4102 pub fn parse_where_clause(&mut self) -> PResult<ast::WhereClause> {
4103 maybe_whole!(self, NtWhereClause);
4105 let mut where_clause = WhereClause {
4106 id: ast::DUMMY_NODE_ID,
4107 predicates: Vec::new(),
4110 if !try!(self.eat_keyword(keywords::Where)) {
4111 return Ok(where_clause);
4114 let mut parsed_something = false;
4116 let lo = self.span.lo;
4118 token::OpenDelim(token::Brace) => {
4122 token::Lifetime(..) => {
4123 let bounded_lifetime =
4124 try!(self.parse_lifetime());
4126 try!(self.eat(&token::Colon));
4129 try!(self.parse_lifetimes(token::BinOp(token::Plus)));
4131 let hi = self.last_span.hi;
4132 let span = mk_sp(lo, hi);
4134 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
4135 ast::WhereRegionPredicate {
4137 lifetime: bounded_lifetime,
4142 parsed_something = true;
4146 let bound_lifetimes = if try!(self.eat_keyword(keywords::For) ){
4147 // Higher ranked constraint.
4148 try!(self.expect(&token::Lt));
4149 let lifetime_defs = try!(self.parse_lifetime_defs());
4150 try!(self.expect_gt());
4156 let bounded_ty = try!(self.parse_ty());
4158 if try!(self.eat(&token::Colon) ){
4159 let bounds = try!(self.parse_ty_param_bounds(BoundParsingMode::Bare));
4160 let hi = self.last_span.hi;
4161 let span = mk_sp(lo, hi);
4163 if bounds.is_empty() {
4165 "each predicate in a `where` clause must have \
4166 at least one bound in it");
4169 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
4170 ast::WhereBoundPredicate {
4172 bound_lifetimes: bound_lifetimes,
4173 bounded_ty: bounded_ty,
4177 parsed_something = true;
4178 } else if try!(self.eat(&token::Eq) ){
4179 // let ty = try!(self.parse_ty());
4180 let hi = self.last_span.hi;
4181 let span = mk_sp(lo, hi);
4182 // where_clause.predicates.push(
4183 // ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
4184 // id: ast::DUMMY_NODE_ID,
4186 // path: panic!("NYI"), //bounded_ty,
4189 // parsed_something = true;
4192 "equality constraints are not yet supported \
4193 in where clauses (#20041)");
4195 let last_span = self.last_span;
4196 self.span_err(last_span,
4197 "unexpected token in `where` clause");
4202 if !try!(self.eat(&token::Comma) ){
4207 if !parsed_something {
4208 let last_span = self.last_span;
4209 self.span_err(last_span,
4210 "a `where` clause must have at least one predicate \
4217 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
4218 -> PResult<(Vec<Arg> , bool)> {
4220 let mut args: Vec<Option<Arg>> =
4221 try!(self.parse_unspanned_seq(
4222 &token::OpenDelim(token::Paren),
4223 &token::CloseDelim(token::Paren),
4224 seq_sep_trailing_allowed(token::Comma),
4226 if p.token == token::DotDotDot {
4229 if p.token != token::CloseDelim(token::Paren) {
4231 return Err(p.span_fatal(span,
4232 "`...` must be last in argument list for variadic function"))
4236 return Err(p.span_fatal(span,
4237 "only foreign functions are allowed to be variadic"))
4241 Ok(Some(try!(p.parse_arg_general(named_args))))
4246 let variadic = match args.pop() {
4249 // Need to put back that last arg
4256 if variadic && args.is_empty() {
4258 "variadic function must be declared with at least one named argument");
4261 let args = args.into_iter().map(|x| x.unwrap()).collect();
4263 Ok((args, variadic))
4266 /// Parse the argument list and result type of a function declaration
4267 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<P<FnDecl>> {
4269 let (args, variadic) = try!(self.parse_fn_args(true, allow_variadic));
4270 let ret_ty = try!(self.parse_ret_ty());
4279 fn is_self_ident(&mut self) -> bool {
4281 token::Ident(id, token::Plain) => id.name == special_idents::self_.name,
4286 fn expect_self_ident(&mut self) -> PResult<ast::Ident> {
4288 token::Ident(id, token::Plain) if id.name == special_idents::self_.name => {
4293 let token_str = self.this_token_to_string();
4294 return Err(self.fatal(&format!("expected `self`, found `{}`",
4300 fn is_self_type_ident(&mut self) -> bool {
4302 token::Ident(id, token::Plain) => id.name == special_idents::type_self.name,
4307 fn expect_self_type_ident(&mut self) -> PResult<ast::Ident> {
4309 token::Ident(id, token::Plain) if id.name == special_idents::type_self.name => {
4314 let token_str = self.this_token_to_string();
4315 Err(self.fatal(&format!("expected `Self`, found `{}`",
4321 /// Parse the argument list and result type of a function
4322 /// that may have a self type.
4323 fn parse_fn_decl_with_self<F>(&mut self,
4324 parse_arg_fn: F) -> PResult<(ExplicitSelf, P<FnDecl>)> where
4325 F: FnMut(&mut Parser) -> PResult<Arg>,
4327 fn maybe_parse_borrowed_explicit_self(this: &mut Parser)
4328 -> PResult<ast::ExplicitSelf_> {
4329 // The following things are possible to see here:
4334 // fn(&'lt mut self)
4336 // We already know that the current token is `&`.
4338 if this.look_ahead(1, |t| t.is_keyword(keywords::SelfValue)) {
4340 Ok(SelfRegion(None, MutImmutable, try!(this.expect_self_ident())))
4341 } else if this.look_ahead(1, |t| t.is_mutability()) &&
4342 this.look_ahead(2, |t| t.is_keyword(keywords::SelfValue)) {
4344 let mutability = try!(this.parse_mutability());
4345 Ok(SelfRegion(None, mutability, try!(this.expect_self_ident())))
4346 } else if this.look_ahead(1, |t| t.is_lifetime()) &&
4347 this.look_ahead(2, |t| t.is_keyword(keywords::SelfValue)) {
4349 let lifetime = try!(this.parse_lifetime());
4350 Ok(SelfRegion(Some(lifetime), MutImmutable, try!(this.expect_self_ident())))
4351 } else if this.look_ahead(1, |t| t.is_lifetime()) &&
4352 this.look_ahead(2, |t| t.is_mutability()) &&
4353 this.look_ahead(3, |t| t.is_keyword(keywords::SelfValue)) {
4355 let lifetime = try!(this.parse_lifetime());
4356 let mutability = try!(this.parse_mutability());
4357 Ok(SelfRegion(Some(lifetime), mutability, try!(this.expect_self_ident())))
4363 try!(self.expect(&token::OpenDelim(token::Paren)));
4365 // A bit of complexity and lookahead is needed here in order to be
4366 // backwards compatible.
4367 let lo = self.span.lo;
4368 let mut self_ident_lo = self.span.lo;
4369 let mut self_ident_hi = self.span.hi;
4371 let mut mutbl_self = MutImmutable;
4372 let explicit_self = match self.token {
4373 token::BinOp(token::And) => {
4374 let eself = try!(maybe_parse_borrowed_explicit_self(self));
4375 self_ident_lo = self.last_span.lo;
4376 self_ident_hi = self.last_span.hi;
4379 token::BinOp(token::Star) => {
4380 // Possibly "*self" or "*mut self" -- not supported. Try to avoid
4381 // emitting cryptic "unexpected token" errors.
4383 let _mutability = if self.token.is_mutability() {
4384 try!(self.parse_mutability())
4388 if self.is_self_ident() {
4389 let span = self.span;
4390 self.span_err(span, "cannot pass self by raw pointer");
4393 // error case, making bogus self ident:
4394 SelfValue(special_idents::self_)
4396 token::Ident(..) => {
4397 if self.is_self_ident() {
4398 let self_ident = try!(self.expect_self_ident());
4400 // Determine whether this is the fully explicit form, `self:
4402 if try!(self.eat(&token::Colon) ){
4403 SelfExplicit(try!(self.parse_ty_sum()), self_ident)
4405 SelfValue(self_ident)
4407 } else if self.token.is_mutability() &&
4408 self.look_ahead(1, |t| t.is_keyword(keywords::SelfValue)) {
4409 mutbl_self = try!(self.parse_mutability());
4410 let self_ident = try!(self.expect_self_ident());
4412 // Determine whether this is the fully explicit form,
4414 if try!(self.eat(&token::Colon) ){
4415 SelfExplicit(try!(self.parse_ty_sum()), self_ident)
4417 SelfValue(self_ident)
4426 let explicit_self_sp = mk_sp(self_ident_lo, self_ident_hi);
4428 // shared fall-through for the three cases below. borrowing prevents simply
4429 // writing this as a closure
4430 macro_rules! parse_remaining_arguments {
4433 // If we parsed a self type, expect a comma before the argument list.
4437 let sep = seq_sep_trailing_allowed(token::Comma);
4438 let mut fn_inputs = try!(self.parse_seq_to_before_end(
4439 &token::CloseDelim(token::Paren),
4443 fn_inputs.insert(0, Arg::new_self(explicit_self_sp, mutbl_self, $self_id));
4446 token::CloseDelim(token::Paren) => {
4447 vec!(Arg::new_self(explicit_self_sp, mutbl_self, $self_id))
4450 let token_str = self.this_token_to_string();
4451 return Err(self.fatal(&format!("expected `,` or `)`, found `{}`",
4458 let fn_inputs = match explicit_self {
4460 let sep = seq_sep_trailing_allowed(token::Comma);
4461 try!(self.parse_seq_to_before_end(&token::CloseDelim(token::Paren),
4464 SelfValue(id) => parse_remaining_arguments!(id),
4465 SelfRegion(_,_,id) => parse_remaining_arguments!(id),
4466 SelfExplicit(_,id) => parse_remaining_arguments!(id),
4470 try!(self.expect(&token::CloseDelim(token::Paren)));
4472 let hi = self.span.hi;
4474 let ret_ty = try!(self.parse_ret_ty());
4476 let fn_decl = P(FnDecl {
4482 Ok((spanned(lo, hi, explicit_self), fn_decl))
4485 // parse the |arg, arg| header on a lambda
4486 fn parse_fn_block_decl(&mut self) -> PResult<P<FnDecl>> {
4487 let inputs_captures = {
4488 if try!(self.eat(&token::OrOr) ){
4491 try!(self.expect(&token::BinOp(token::Or)));
4492 try!(self.parse_obsolete_closure_kind());
4493 let args = try!(self.parse_seq_to_before_end(
4494 &token::BinOp(token::Or),
4495 seq_sep_trailing_allowed(token::Comma),
4496 |p| p.parse_fn_block_arg()
4502 let output = try!(self.parse_ret_ty());
4505 inputs: inputs_captures,
4511 /// Parse the name and optional generic types of a function header.
4512 fn parse_fn_header(&mut self) -> PResult<(Ident, ast::Generics)> {
4513 let id = try!(self.parse_ident());
4514 let generics = try!(self.parse_generics());
4518 fn mk_item(&mut self, lo: BytePos, hi: BytePos, ident: Ident,
4519 node: Item_, vis: Visibility,
4520 attrs: Vec<Attribute>) -> P<Item> {
4524 id: ast::DUMMY_NODE_ID,
4531 /// Parse an item-position function declaration.
4532 fn parse_item_fn(&mut self,
4534 constness: Constness,
4536 -> PResult<ItemInfo> {
4537 let (ident, mut generics) = try!(self.parse_fn_header());
4538 let decl = try!(self.parse_fn_decl(false));
4539 generics.where_clause = try!(self.parse_where_clause());
4540 let (inner_attrs, body) = try!(self.parse_inner_attrs_and_block());
4541 Ok((ident, ItemFn(decl, unsafety, constness, abi, generics, body), Some(inner_attrs)))
4544 /// true if we are looking at `const ID`, false for things like `const fn` etc
4545 pub fn is_const_item(&mut self) -> bool {
4546 self.token.is_keyword(keywords::Const) &&
4547 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
4548 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
4551 /// parses all the "front matter" for a `fn` declaration, up to
4552 /// and including the `fn` keyword:
4556 /// - `const unsafe fn`
4559 pub fn parse_fn_front_matter(&mut self) -> PResult<(ast::Constness, ast::Unsafety, abi::Abi)> {
4560 let is_const_fn = try!(self.eat_keyword(keywords::Const));
4561 let unsafety = try!(self.parse_unsafety());
4562 let (constness, unsafety, abi) = if is_const_fn {
4563 (Constness::Const, unsafety, abi::Rust)
4565 let abi = if try!(self.eat_keyword(keywords::Extern)) {
4566 try!(self.parse_opt_abi()).unwrap_or(abi::C)
4570 (Constness::NotConst, unsafety, abi)
4572 try!(self.expect_keyword(keywords::Fn));
4573 Ok((constness, unsafety, abi))
4576 /// Parse an impl item.
4577 pub fn parse_impl_item(&mut self) -> PResult<P<ImplItem>> {
4578 maybe_whole!(no_clone self, NtImplItem);
4580 let mut attrs = try!(self.parse_outer_attributes());
4581 let lo = self.span.lo;
4582 let vis = try!(self.parse_visibility());
4583 let (name, node) = if try!(self.eat_keyword(keywords::Type)) {
4584 let name = try!(self.parse_ident());
4585 try!(self.expect(&token::Eq));
4586 let typ = try!(self.parse_ty_sum());
4587 try!(self.expect(&token::Semi));
4588 (name, ast::ImplItemKind::Type(typ))
4589 } else if self.is_const_item() {
4590 try!(self.expect_keyword(keywords::Const));
4591 let name = try!(self.parse_ident());
4592 try!(self.expect(&token::Colon));
4593 let typ = try!(self.parse_ty_sum());
4594 try!(self.expect(&token::Eq));
4595 let expr = try!(self.parse_expr());
4596 try!(self.commit_expr_expecting(&expr, token::Semi));
4597 (name, ast::ImplItemKind::Const(typ, expr))
4599 let (name, inner_attrs, node) = try!(self.parse_impl_method(vis));
4600 attrs.extend(inner_attrs);
4605 id: ast::DUMMY_NODE_ID,
4606 span: mk_sp(lo, self.last_span.hi),
4614 fn complain_if_pub_macro(&mut self, visa: Visibility, span: Span) {
4617 self.span_err(span, "can't qualify macro invocation with `pub`");
4618 self.fileline_help(span, "try adjusting the macro to put `pub` inside \
4625 /// Parse a method or a macro invocation in a trait impl.
4626 fn parse_impl_method(&mut self, vis: Visibility)
4627 -> PResult<(Ident, Vec<ast::Attribute>, ast::ImplItemKind)> {
4628 // code copied from parse_macro_use_or_failure... abstraction!
4629 if !self.token.is_any_keyword()
4630 && self.look_ahead(1, |t| *t == token::Not)
4631 && (self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren))
4632 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) {
4635 let last_span = self.last_span;
4636 self.complain_if_pub_macro(vis, last_span);
4638 let lo = self.span.lo;
4639 let pth = try!(self.parse_path(NoTypesAllowed));
4640 try!(self.expect(&token::Not));
4642 // eat a matched-delimiter token tree:
4643 let delim = try!(self.expect_open_delim());
4644 let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
4646 |p| p.parse_token_tree()));
4647 let m_ = Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT };
4648 let m: ast::Mac = codemap::Spanned { node: m_,
4650 self.last_span.hi) };
4651 if delim != token::Brace {
4652 try!(self.expect(&token::Semi))
4654 Ok((token::special_idents::invalid, vec![], ast::ImplItemKind::Macro(m)))
4656 let (constness, unsafety, abi) = try!(self.parse_fn_front_matter());
4657 let ident = try!(self.parse_ident());
4658 let mut generics = try!(self.parse_generics());
4659 let (explicit_self, decl) = try!(self.parse_fn_decl_with_self(|p| {
4662 generics.where_clause = try!(self.parse_where_clause());
4663 let (inner_attrs, body) = try!(self.parse_inner_attrs_and_block());
4664 Ok((ident, inner_attrs, ast::ImplItemKind::Method(ast::MethodSig {
4667 explicit_self: explicit_self,
4669 constness: constness,
4675 /// Parse trait Foo { ... }
4676 fn parse_item_trait(&mut self, unsafety: Unsafety) -> PResult<ItemInfo> {
4678 let ident = try!(self.parse_ident());
4679 let mut tps = try!(self.parse_generics());
4681 // Parse supertrait bounds.
4682 let bounds = try!(self.parse_colon_then_ty_param_bounds(BoundParsingMode::Bare));
4684 tps.where_clause = try!(self.parse_where_clause());
4686 let meths = try!(self.parse_trait_items());
4687 Ok((ident, ItemTrait(unsafety, tps, bounds, meths), None))
4690 /// Parses items implementations variants
4691 /// impl<T> Foo { ... }
4692 /// impl<T> ToString for &'static T { ... }
4693 /// impl Send for .. {}
4694 fn parse_item_impl(&mut self, unsafety: ast::Unsafety) -> PResult<ItemInfo> {
4695 let impl_span = self.span;
4697 // First, parse type parameters if necessary.
4698 let mut generics = try!(self.parse_generics());
4700 // Special case: if the next identifier that follows is '(', don't
4701 // allow this to be parsed as a trait.
4702 let could_be_trait = self.token != token::OpenDelim(token::Paren);
4704 let neg_span = self.span;
4705 let polarity = if try!(self.eat(&token::Not) ){
4706 ast::ImplPolarity::Negative
4708 ast::ImplPolarity::Positive
4712 let mut ty = try!(self.parse_ty_sum());
4714 // Parse traits, if necessary.
4715 let opt_trait = if could_be_trait && try!(self.eat_keyword(keywords::For) ){
4716 // New-style trait. Reinterpret the type as a trait.
4718 TyPath(None, ref path) => {
4720 path: (*path).clone(),
4725 self.span_err(ty.span, "not a trait");
4731 ast::ImplPolarity::Negative => {
4732 // This is a negated type implementation
4733 // `impl !MyType {}`, which is not allowed.
4734 self.span_err(neg_span, "inherent implementation can't be negated");
4741 if opt_trait.is_some() && try!(self.eat(&token::DotDot) ){
4742 if generics.is_parameterized() {
4743 self.span_err(impl_span, "default trait implementations are not \
4744 allowed to have generics");
4747 try!(self.expect(&token::OpenDelim(token::Brace)));
4748 try!(self.expect(&token::CloseDelim(token::Brace)));
4749 Ok((ast_util::impl_pretty_name(&opt_trait, None),
4750 ItemDefaultImpl(unsafety, opt_trait.unwrap()), None))
4752 if opt_trait.is_some() {
4753 ty = try!(self.parse_ty_sum());
4755 generics.where_clause = try!(self.parse_where_clause());
4757 try!(self.expect(&token::OpenDelim(token::Brace)));
4758 let attrs = try!(self.parse_inner_attributes());
4760 let mut impl_items = vec![];
4761 while !try!(self.eat(&token::CloseDelim(token::Brace))) {
4762 impl_items.push(try!(self.parse_impl_item()));
4765 Ok((ast_util::impl_pretty_name(&opt_trait, Some(&*ty)),
4766 ItemImpl(unsafety, polarity, generics, opt_trait, ty, impl_items),
4771 /// Parse a::B<String,i32>
4772 fn parse_trait_ref(&mut self) -> PResult<TraitRef> {
4774 path: try!(self.parse_path(LifetimeAndTypesWithoutColons)),
4775 ref_id: ast::DUMMY_NODE_ID,
4779 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<Vec<ast::LifetimeDef>> {
4780 if try!(self.eat_keyword(keywords::For) ){
4781 try!(self.expect(&token::Lt));
4782 let lifetime_defs = try!(self.parse_lifetime_defs());
4783 try!(self.expect_gt());
4790 /// Parse for<'l> a::B<String,i32>
4791 fn parse_poly_trait_ref(&mut self) -> PResult<PolyTraitRef> {
4792 let lo = self.span.lo;
4793 let lifetime_defs = try!(self.parse_late_bound_lifetime_defs());
4795 Ok(ast::PolyTraitRef {
4796 bound_lifetimes: lifetime_defs,
4797 trait_ref: try!(self.parse_trait_ref()),
4798 span: mk_sp(lo, self.last_span.hi),
4802 /// Parse struct Foo { ... }
4803 fn parse_item_struct(&mut self) -> PResult<ItemInfo> {
4804 let class_name = try!(self.parse_ident());
4805 let mut generics = try!(self.parse_generics());
4807 // There is a special case worth noting here, as reported in issue #17904.
4808 // If we are parsing a tuple struct it is the case that the where clause
4809 // should follow the field list. Like so:
4811 // struct Foo<T>(T) where T: Copy;
4813 // If we are parsing a normal record-style struct it is the case
4814 // that the where clause comes before the body, and after the generics.
4815 // So if we look ahead and see a brace or a where-clause we begin
4816 // parsing a record style struct.
4818 // Otherwise if we look ahead and see a paren we parse a tuple-style
4821 let vdata = if self.token.is_keyword(keywords::Where) {
4822 generics.where_clause = try!(self.parse_where_clause());
4823 if try!(self.eat(&token::Semi)) {
4824 // If we see a: `struct Foo<T> where T: Copy;` style decl.
4825 VariantData::Unit(ast::DUMMY_NODE_ID)
4827 // If we see: `struct Foo<T> where T: Copy { ... }`
4828 VariantData::Struct(try!(self.parse_record_struct_body(ParsePub::Yes)),
4831 // No `where` so: `struct Foo<T>;`
4832 } else if try!(self.eat(&token::Semi) ){
4833 VariantData::Unit(ast::DUMMY_NODE_ID)
4834 // Record-style struct definition
4835 } else if self.token == token::OpenDelim(token::Brace) {
4836 VariantData::Struct(try!(self.parse_record_struct_body(ParsePub::Yes)),
4838 // Tuple-style struct definition with optional where-clause.
4839 } else if self.token == token::OpenDelim(token::Paren) {
4840 let body = VariantData::Tuple(try!(self.parse_tuple_struct_body(ParsePub::Yes)),
4841 ast::DUMMY_NODE_ID);
4842 generics.where_clause = try!(self.parse_where_clause());
4843 try!(self.expect(&token::Semi));
4846 let token_str = self.this_token_to_string();
4847 return Err(self.fatal(&format!("expected `where`, `{{`, `(`, or `;` after struct \
4848 name, found `{}`", token_str)))
4851 Ok((class_name, ItemStruct(vdata, generics), None))
4854 pub fn parse_record_struct_body(&mut self, parse_pub: ParsePub) -> PResult<Vec<StructField>> {
4855 let mut fields = Vec::new();
4856 if try!(self.eat(&token::OpenDelim(token::Brace)) ){
4857 while self.token != token::CloseDelim(token::Brace) {
4858 fields.push(try!(self.parse_struct_decl_field(parse_pub)));
4863 let token_str = self.this_token_to_string();
4864 return Err(self.fatal(&format!("expected `where`, or `{{` after struct \
4872 pub fn parse_tuple_struct_body(&mut self, parse_pub: ParsePub) -> PResult<Vec<StructField>> {
4873 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
4874 // Unit like structs are handled in parse_item_struct function
4875 let fields = try!(self.parse_unspanned_seq(
4876 &token::OpenDelim(token::Paren),
4877 &token::CloseDelim(token::Paren),
4878 seq_sep_trailing_allowed(token::Comma),
4880 let attrs = try!(p.parse_outer_attributes());
4882 let struct_field_ = ast::StructField_ {
4883 kind: UnnamedField (
4884 if parse_pub == ParsePub::Yes {
4885 try!(p.parse_visibility())
4890 id: ast::DUMMY_NODE_ID,
4891 ty: try!(p.parse_ty_sum()),
4894 Ok(spanned(lo, p.span.hi, struct_field_))
4900 /// Parse a structure field declaration
4901 pub fn parse_single_struct_field(&mut self,
4903 attrs: Vec<Attribute> )
4904 -> PResult<StructField> {
4905 let a_var = try!(self.parse_name_and_ty(vis, attrs));
4910 token::CloseDelim(token::Brace) => {}
4912 let span = self.span;
4913 let token_str = self.this_token_to_string();
4914 return Err(self.span_fatal_help(span,
4915 &format!("expected `,`, or `}}`, found `{}`",
4917 "struct fields should be separated by commas"))
4923 /// Parse an element of a struct definition
4924 fn parse_struct_decl_field(&mut self, parse_pub: ParsePub) -> PResult<StructField> {
4926 let attrs = try!(self.parse_outer_attributes());
4928 if try!(self.eat_keyword(keywords::Pub) ){
4929 if parse_pub == ParsePub::No {
4930 let span = self.last_span;
4931 self.span_err(span, "`pub` is not allowed here");
4933 return self.parse_single_struct_field(Public, attrs);
4936 return self.parse_single_struct_field(Inherited, attrs);
4939 /// Parse visibility: PUB or nothing
4940 fn parse_visibility(&mut self) -> PResult<Visibility> {
4941 if try!(self.eat_keyword(keywords::Pub)) { Ok(Public) }
4942 else { Ok(Inherited) }
4945 /// Given a termination token, parse all of the items in a module
4946 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: BytePos) -> PResult<Mod> {
4947 let mut items = vec![];
4948 while let Some(item) = try!(self.parse_item()) {
4952 if !try!(self.eat(term)) {
4953 let token_str = self.this_token_to_string();
4954 return Err(self.fatal(&format!("expected item, found `{}`", token_str)));
4957 let hi = if self.span == codemap::DUMMY_SP {
4964 inner: mk_sp(inner_lo, hi),
4969 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<ItemInfo> {
4970 let id = try!(self.parse_ident());
4971 try!(self.expect(&token::Colon));
4972 let ty = try!(self.parse_ty_sum());
4973 try!(self.expect(&token::Eq));
4974 let e = try!(self.parse_expr());
4975 try!(self.commit_expr_expecting(&*e, token::Semi));
4976 let item = match m {
4977 Some(m) => ItemStatic(ty, m, e),
4978 None => ItemConst(ty, e),
4980 Ok((id, item, None))
4983 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
4984 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<ItemInfo> {
4985 let id_span = self.span;
4986 let id = try!(self.parse_ident());
4987 if self.check(&token::Semi) {
4989 // This mod is in an external file. Let's go get it!
4990 let (m, attrs) = try!(self.eval_src_mod(id, outer_attrs, id_span));
4991 Ok((id, m, Some(attrs)))
4993 self.push_mod_path(id, outer_attrs);
4994 try!(self.expect(&token::OpenDelim(token::Brace)));
4995 let mod_inner_lo = self.span.lo;
4996 let old_owns_directory = self.owns_directory;
4997 self.owns_directory = true;
4998 let attrs = try!(self.parse_inner_attributes());
4999 let m = try!(self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo));
5000 self.owns_directory = old_owns_directory;
5001 self.pop_mod_path();
5002 Ok((id, ItemMod(m), Some(attrs)))
5006 fn push_mod_path(&mut self, id: Ident, attrs: &[Attribute]) {
5007 let default_path = self.id_to_interned_str(id);
5008 let file_path = match ::attr::first_attr_value_str_by_name(attrs, "path") {
5010 None => default_path,
5012 self.mod_path_stack.push(file_path)
5015 fn pop_mod_path(&mut self) {
5016 self.mod_path_stack.pop().unwrap();
5019 pub fn submod_path_from_attr(attrs: &[ast::Attribute], dir_path: &Path) -> Option<PathBuf> {
5020 ::attr::first_attr_value_str_by_name(attrs, "path").map(|d| dir_path.join(&*d))
5023 /// Returns either a path to a module, or .
5024 pub fn default_submod_path(id: ast::Ident, dir_path: &Path, codemap: &CodeMap) -> ModulePath
5026 let mod_name = id.to_string();
5027 let default_path_str = format!("{}.rs", mod_name);
5028 let secondary_path_str = format!("{}/mod.rs", mod_name);
5029 let default_path = dir_path.join(&default_path_str);
5030 let secondary_path = dir_path.join(&secondary_path_str);
5031 let default_exists = codemap.file_exists(&default_path);
5032 let secondary_exists = codemap.file_exists(&secondary_path);
5034 let result = match (default_exists, secondary_exists) {
5035 (true, false) => Ok(ModulePathSuccess { path: default_path, owns_directory: false }),
5036 (false, true) => Ok(ModulePathSuccess { path: secondary_path, owns_directory: true }),
5037 (false, false) => Err(ModulePathError {
5038 err_msg: format!("file not found for module `{}`", mod_name),
5039 help_msg: format!("name the file either {} or {} inside the directory {:?}",
5042 dir_path.display()),
5044 (true, true) => Err(ModulePathError {
5045 err_msg: format!("file for module `{}` found at both {} and {}",
5048 secondary_path_str),
5049 help_msg: "delete or rename one of them to remove the ambiguity".to_owned(),
5055 path_exists: default_exists || secondary_exists,
5060 fn submod_path(&mut self,
5062 outer_attrs: &[ast::Attribute],
5063 id_sp: Span) -> PResult<ModulePathSuccess> {
5064 let mut prefix = PathBuf::from(&self.sess.codemap().span_to_filename(self.span));
5066 let mut dir_path = prefix;
5067 for part in &self.mod_path_stack {
5068 dir_path.push(&**part);
5071 if let Some(p) = Parser::submod_path_from_attr(outer_attrs, &dir_path) {
5072 return Ok(ModulePathSuccess { path: p, owns_directory: true });
5075 let paths = Parser::default_submod_path(id, &dir_path, self.sess.codemap());
5077 if !self.owns_directory {
5078 self.span_err(id_sp, "cannot declare a new module at this location");
5079 let this_module = match self.mod_path_stack.last() {
5080 Some(name) => name.to_string(),
5081 None => self.root_module_name.as_ref().unwrap().clone(),
5083 self.span_note(id_sp,
5084 &format!("maybe move this module `{0}` to its own directory \
5087 if paths.path_exists {
5088 self.span_note(id_sp,
5089 &format!("... or maybe `use` the module `{}` instead \
5090 of possibly redeclaring it",
5093 self.abort_if_errors();
5096 match paths.result {
5097 Ok(succ) => Ok(succ),
5098 Err(err) => Err(self.span_fatal_help(id_sp, &err.err_msg, &err.help_msg)),
5102 /// Read a module from a source file.
5103 fn eval_src_mod(&mut self,
5105 outer_attrs: &[ast::Attribute],
5107 -> PResult<(ast::Item_, Vec<ast::Attribute> )> {
5108 let ModulePathSuccess { path, owns_directory } = try!(self.submod_path(id,
5112 self.eval_src_mod_from_path(path,
5118 fn eval_src_mod_from_path(&mut self,
5120 owns_directory: bool,
5122 id_sp: Span) -> PResult<(ast::Item_, Vec<ast::Attribute> )> {
5123 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
5124 match included_mod_stack.iter().position(|p| *p == path) {
5126 let mut err = String::from("circular modules: ");
5127 let len = included_mod_stack.len();
5128 for p in &included_mod_stack[i.. len] {
5129 err.push_str(&p.to_string_lossy());
5130 err.push_str(" -> ");
5132 err.push_str(&path.to_string_lossy());
5133 return Err(self.span_fatal(id_sp, &err[..]));
5137 included_mod_stack.push(path.clone());
5138 drop(included_mod_stack);
5140 let mut p0 = new_sub_parser_from_file(self.sess,
5146 let mod_inner_lo = p0.span.lo;
5147 let mod_attrs = try!(p0.parse_inner_attributes());
5148 let m0 = try!(p0.parse_mod_items(&token::Eof, mod_inner_lo));
5149 self.sess.included_mod_stack.borrow_mut().pop();
5150 Ok((ast::ItemMod(m0), mod_attrs))
5153 /// Parse a function declaration from a foreign module
5154 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: BytePos,
5155 attrs: Vec<Attribute>) -> PResult<P<ForeignItem>> {
5156 try!(self.expect_keyword(keywords::Fn));
5158 let (ident, mut generics) = try!(self.parse_fn_header());
5159 let decl = try!(self.parse_fn_decl(true));
5160 generics.where_clause = try!(self.parse_where_clause());
5161 let hi = self.span.hi;
5162 try!(self.expect(&token::Semi));
5163 Ok(P(ast::ForeignItem {
5166 node: ForeignItemFn(decl, generics),
5167 id: ast::DUMMY_NODE_ID,
5168 span: mk_sp(lo, hi),
5173 /// Parse a static item from a foreign module
5174 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: BytePos,
5175 attrs: Vec<Attribute>) -> PResult<P<ForeignItem>> {
5176 try!(self.expect_keyword(keywords::Static));
5177 let mutbl = try!(self.eat_keyword(keywords::Mut));
5179 let ident = try!(self.parse_ident());
5180 try!(self.expect(&token::Colon));
5181 let ty = try!(self.parse_ty_sum());
5182 let hi = self.span.hi;
5183 try!(self.expect(&token::Semi));
5187 node: ForeignItemStatic(ty, mutbl),
5188 id: ast::DUMMY_NODE_ID,
5189 span: mk_sp(lo, hi),
5194 /// Parse extern crate links
5198 /// extern crate foo;
5199 /// extern crate bar as foo;
5200 fn parse_item_extern_crate(&mut self,
5202 visibility: Visibility,
5203 attrs: Vec<Attribute>)
5204 -> PResult<P<Item>> {
5206 let crate_name = try!(self.parse_ident());
5207 let (maybe_path, ident) = if let Some(ident) = try!(self.parse_rename()) {
5208 (Some(crate_name.name), ident)
5212 try!(self.expect(&token::Semi));
5214 let last_span = self.last_span;
5216 if visibility == ast::Public {
5217 self.span_warn(mk_sp(lo, last_span.hi),
5218 "`pub extern crate` does not work as expected and should not be used. \
5219 Likely to become an error. Prefer `extern crate` and `pub use`.");
5225 ItemExternCrate(maybe_path),
5230 /// Parse `extern` for foreign ABIs
5233 /// `extern` is expected to have been
5234 /// consumed before calling this method
5240 fn parse_item_foreign_mod(&mut self,
5242 opt_abi: Option<abi::Abi>,
5243 visibility: Visibility,
5244 mut attrs: Vec<Attribute>)
5245 -> PResult<P<Item>> {
5246 try!(self.expect(&token::OpenDelim(token::Brace)));
5248 let abi = opt_abi.unwrap_or(abi::C);
5250 attrs.extend(try!(self.parse_inner_attributes()));
5252 let mut foreign_items = vec![];
5253 while let Some(item) = try!(self.parse_foreign_item()) {
5254 foreign_items.push(item);
5256 try!(self.expect(&token::CloseDelim(token::Brace)));
5258 let last_span = self.last_span;
5259 let m = ast::ForeignMod {
5261 items: foreign_items
5265 special_idents::invalid,
5271 /// Parse type Foo = Bar;
5272 fn parse_item_type(&mut self) -> PResult<ItemInfo> {
5273 let ident = try!(self.parse_ident());
5274 let mut tps = try!(self.parse_generics());
5275 tps.where_clause = try!(self.parse_where_clause());
5276 try!(self.expect(&token::Eq));
5277 let ty = try!(self.parse_ty_sum());
5278 try!(self.expect(&token::Semi));
5279 Ok((ident, ItemTy(ty, tps), None))
5282 /// Parse the part of an "enum" decl following the '{'
5283 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<EnumDef> {
5284 let mut variants = Vec::new();
5285 let mut all_nullary = true;
5286 let mut any_disr = None;
5287 while self.token != token::CloseDelim(token::Brace) {
5288 let variant_attrs = try!(self.parse_outer_attributes());
5289 let vlo = self.span.lo;
5292 let mut disr_expr = None;
5293 let ident = try!(self.parse_ident());
5294 if self.check(&token::OpenDelim(token::Brace)) {
5295 // Parse a struct variant.
5296 all_nullary = false;
5297 struct_def = VariantData::Struct(try!(self.parse_record_struct_body(ParsePub::No)),
5298 ast::DUMMY_NODE_ID);
5299 } else if self.check(&token::OpenDelim(token::Paren)) {
5300 all_nullary = false;
5301 struct_def = VariantData::Tuple(try!(self.parse_tuple_struct_body(ParsePub::No)),
5302 ast::DUMMY_NODE_ID);
5303 } else if try!(self.eat(&token::Eq) ){
5304 disr_expr = Some(try!(self.parse_expr()));
5305 any_disr = disr_expr.as_ref().map(|expr| expr.span);
5306 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5308 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5311 let vr = ast::Variant_ {
5313 attrs: variant_attrs,
5315 disr_expr: disr_expr,
5317 variants.push(P(spanned(vlo, self.last_span.hi, vr)));
5319 if !try!(self.eat(&token::Comma)) { break; }
5321 try!(self.expect(&token::CloseDelim(token::Brace)));
5323 Some(disr_span) if !all_nullary =>
5324 self.span_err(disr_span,
5325 "discriminator values can only be used with a c-like enum"),
5329 Ok(ast::EnumDef { variants: variants })
5332 /// Parse an "enum" declaration
5333 fn parse_item_enum(&mut self) -> PResult<ItemInfo> {
5334 let id = try!(self.parse_ident());
5335 let mut generics = try!(self.parse_generics());
5336 generics.where_clause = try!(self.parse_where_clause());
5337 try!(self.expect(&token::OpenDelim(token::Brace)));
5339 let enum_definition = try!(self.parse_enum_def(&generics));
5340 Ok((id, ItemEnum(enum_definition, generics), None))
5343 /// Parses a string as an ABI spec on an extern type or module. Consumes
5344 /// the `extern` keyword, if one is found.
5345 fn parse_opt_abi(&mut self) -> PResult<Option<abi::Abi>> {
5347 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
5349 self.expect_no_suffix(sp, "ABI spec", suf);
5351 match abi::lookup(&s.as_str()) {
5352 Some(abi) => Ok(Some(abi)),
5354 let last_span = self.last_span;
5357 &format!("invalid ABI: expected one of [{}], \
5359 abi::all_names().join(", "),
5370 /// Parse one of the items allowed by the flags.
5371 /// NB: this function no longer parses the items inside an
5373 fn parse_item_(&mut self, attrs: Vec<Attribute>,
5374 macros_allowed: bool, attributes_allowed: bool) -> PResult<Option<P<Item>>> {
5375 let nt_item = match self.token {
5376 token::Interpolated(token::NtItem(ref item)) => {
5377 Some((**item).clone())
5384 let mut attrs = attrs;
5385 mem::swap(&mut item.attrs, &mut attrs);
5386 item.attrs.extend(attrs);
5387 return Ok(Some(P(item)));
5392 let lo = self.span.lo;
5394 let visibility = try!(self.parse_visibility());
5396 if try!(self.eat_keyword(keywords::Use) ){
5398 let item_ = ItemUse(try!(self.parse_view_path()));
5399 try!(self.expect(&token::Semi));
5401 let last_span = self.last_span;
5402 let item = self.mk_item(lo,
5404 token::special_idents::invalid,
5408 return Ok(Some(item));
5411 if try!(self.eat_keyword(keywords::Extern)) {
5412 if try!(self.eat_keyword(keywords::Crate)) {
5413 return Ok(Some(try!(self.parse_item_extern_crate(lo, visibility, attrs))));
5416 let opt_abi = try!(self.parse_opt_abi());
5418 if try!(self.eat_keyword(keywords::Fn) ){
5419 // EXTERN FUNCTION ITEM
5420 let abi = opt_abi.unwrap_or(abi::C);
5421 let (ident, item_, extra_attrs) =
5422 try!(self.parse_item_fn(Unsafety::Normal, Constness::NotConst, abi));
5423 let last_span = self.last_span;
5424 let item = self.mk_item(lo,
5429 maybe_append(attrs, extra_attrs));
5430 return Ok(Some(item));
5431 } else if self.check(&token::OpenDelim(token::Brace)) {
5432 return Ok(Some(try!(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs))));
5435 try!(self.expect_one_of(&[], &[]));
5438 if try!(self.eat_keyword(keywords::Static) ){
5440 let m = if try!(self.eat_keyword(keywords::Mut)) {MutMutable} else {MutImmutable};
5441 let (ident, item_, extra_attrs) = try!(self.parse_item_const(Some(m)));
5442 let last_span = self.last_span;
5443 let item = self.mk_item(lo,
5448 maybe_append(attrs, extra_attrs));
5449 return Ok(Some(item));
5451 if try!(self.eat_keyword(keywords::Const) ){
5452 if self.check_keyword(keywords::Fn)
5453 || (self.check_keyword(keywords::Unsafe)
5454 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
5455 // CONST FUNCTION ITEM
5456 let unsafety = if try!(self.eat_keyword(keywords::Unsafe) ){
5462 let (ident, item_, extra_attrs) =
5463 try!(self.parse_item_fn(unsafety, Constness::Const, abi::Rust));
5464 let last_span = self.last_span;
5465 let item = self.mk_item(lo,
5470 maybe_append(attrs, extra_attrs));
5471 return Ok(Some(item));
5475 if try!(self.eat_keyword(keywords::Mut) ){
5476 let last_span = self.last_span;
5477 self.span_err(last_span, "const globals cannot be mutable");
5478 self.fileline_help(last_span, "did you mean to declare a static?");
5480 let (ident, item_, extra_attrs) = try!(self.parse_item_const(None));
5481 let last_span = self.last_span;
5482 let item = self.mk_item(lo,
5487 maybe_append(attrs, extra_attrs));
5488 return Ok(Some(item));
5490 if self.check_keyword(keywords::Unsafe) &&
5491 self.look_ahead(1, |t| t.is_keyword(keywords::Trait))
5493 // UNSAFE TRAIT ITEM
5494 try!(self.expect_keyword(keywords::Unsafe));
5495 try!(self.expect_keyword(keywords::Trait));
5496 let (ident, item_, extra_attrs) =
5497 try!(self.parse_item_trait(ast::Unsafety::Unsafe));
5498 let last_span = self.last_span;
5499 let item = self.mk_item(lo,
5504 maybe_append(attrs, extra_attrs));
5505 return Ok(Some(item));
5507 if self.check_keyword(keywords::Unsafe) &&
5508 self.look_ahead(1, |t| t.is_keyword(keywords::Impl))
5511 try!(self.expect_keyword(keywords::Unsafe));
5512 try!(self.expect_keyword(keywords::Impl));
5513 let (ident, item_, extra_attrs) = try!(self.parse_item_impl(ast::Unsafety::Unsafe));
5514 let last_span = self.last_span;
5515 let item = self.mk_item(lo,
5520 maybe_append(attrs, extra_attrs));
5521 return Ok(Some(item));
5523 if self.check_keyword(keywords::Fn) {
5526 let (ident, item_, extra_attrs) =
5527 try!(self.parse_item_fn(Unsafety::Normal, Constness::NotConst, abi::Rust));
5528 let last_span = self.last_span;
5529 let item = self.mk_item(lo,
5534 maybe_append(attrs, extra_attrs));
5535 return Ok(Some(item));
5537 if self.check_keyword(keywords::Unsafe)
5538 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
5539 // UNSAFE FUNCTION ITEM
5541 let abi = if try!(self.eat_keyword(keywords::Extern) ){
5542 try!(self.parse_opt_abi()).unwrap_or(abi::C)
5546 try!(self.expect_keyword(keywords::Fn));
5547 let (ident, item_, extra_attrs) =
5548 try!(self.parse_item_fn(Unsafety::Unsafe, Constness::NotConst, abi));
5549 let last_span = self.last_span;
5550 let item = self.mk_item(lo,
5555 maybe_append(attrs, extra_attrs));
5556 return Ok(Some(item));
5558 if try!(self.eat_keyword(keywords::Mod) ){
5560 let (ident, item_, extra_attrs) =
5561 try!(self.parse_item_mod(&attrs[..]));
5562 let last_span = self.last_span;
5563 let item = self.mk_item(lo,
5568 maybe_append(attrs, extra_attrs));
5569 return Ok(Some(item));
5571 if try!(self.eat_keyword(keywords::Type) ){
5573 let (ident, item_, extra_attrs) = try!(self.parse_item_type());
5574 let last_span = self.last_span;
5575 let item = self.mk_item(lo,
5580 maybe_append(attrs, extra_attrs));
5581 return Ok(Some(item));
5583 if try!(self.eat_keyword(keywords::Enum) ){
5585 let (ident, item_, extra_attrs) = try!(self.parse_item_enum());
5586 let last_span = self.last_span;
5587 let item = self.mk_item(lo,
5592 maybe_append(attrs, extra_attrs));
5593 return Ok(Some(item));
5595 if try!(self.eat_keyword(keywords::Trait) ){
5597 let (ident, item_, extra_attrs) =
5598 try!(self.parse_item_trait(ast::Unsafety::Normal));
5599 let last_span = self.last_span;
5600 let item = self.mk_item(lo,
5605 maybe_append(attrs, extra_attrs));
5606 return Ok(Some(item));
5608 if try!(self.eat_keyword(keywords::Impl) ){
5610 let (ident, item_, extra_attrs) = try!(self.parse_item_impl(ast::Unsafety::Normal));
5611 let last_span = self.last_span;
5612 let item = self.mk_item(lo,
5617 maybe_append(attrs, extra_attrs));
5618 return Ok(Some(item));
5620 if try!(self.eat_keyword(keywords::Struct) ){
5622 let (ident, item_, extra_attrs) = try!(self.parse_item_struct());
5623 let last_span = self.last_span;
5624 let item = self.mk_item(lo,
5629 maybe_append(attrs, extra_attrs));
5630 return Ok(Some(item));
5632 self.parse_macro_use_or_failure(attrs,macros_allowed,attributes_allowed,lo,visibility)
5635 /// Parse a foreign item.
5636 fn parse_foreign_item(&mut self) -> PResult<Option<P<ForeignItem>>> {
5637 let attrs = try!(self.parse_outer_attributes());
5638 let lo = self.span.lo;
5639 let visibility = try!(self.parse_visibility());
5641 if self.check_keyword(keywords::Static) {
5642 // FOREIGN STATIC ITEM
5643 return Ok(Some(try!(self.parse_item_foreign_static(visibility, lo, attrs))));
5645 if self.check_keyword(keywords::Fn) || self.check_keyword(keywords::Unsafe) {
5646 // FOREIGN FUNCTION ITEM
5647 return Ok(Some(try!(self.parse_item_foreign_fn(visibility, lo, attrs))));
5650 // FIXME #5668: this will occur for a macro invocation:
5651 match try!(self.parse_macro_use_or_failure(attrs, true, false, lo, visibility)) {
5653 return Err(self.span_fatal(item.span, "macros cannot expand to foreign items"));
5659 /// This is the fall-through for parsing items.
5660 fn parse_macro_use_or_failure(
5662 attrs: Vec<Attribute> ,
5663 macros_allowed: bool,
5664 attributes_allowed: bool,
5666 visibility: Visibility
5667 ) -> PResult<Option<P<Item>>> {
5668 if macros_allowed && !self.token.is_any_keyword()
5669 && self.look_ahead(1, |t| *t == token::Not)
5670 && (self.look_ahead(2, |t| t.is_plain_ident())
5671 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren))
5672 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) {
5673 // MACRO INVOCATION ITEM
5675 let last_span = self.last_span;
5676 self.complain_if_pub_macro(visibility, last_span);
5678 let mac_lo = self.span.lo;
5681 let pth = try!(self.parse_path(NoTypesAllowed));
5682 try!(self.expect(&token::Not));
5684 // a 'special' identifier (like what `macro_rules!` uses)
5685 // is optional. We should eventually unify invoc syntax
5687 let id = if self.token.is_plain_ident() {
5688 try!(self.parse_ident())
5690 token::special_idents::invalid // no special identifier
5692 // eat a matched-delimiter token tree:
5693 let delim = try!(self.expect_open_delim());
5694 let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
5696 |p| p.parse_token_tree()));
5697 // single-variant-enum... :
5698 let m = Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT };
5699 let m: ast::Mac = codemap::Spanned { node: m,
5701 self.last_span.hi) };
5703 if delim != token::Brace {
5704 if !try!(self.eat(&token::Semi) ){
5705 let last_span = self.last_span;
5706 self.span_err(last_span,
5707 "macros that expand to items must either \
5708 be surrounded with braces or followed by \
5713 let item_ = ItemMac(m);
5714 let last_span = self.last_span;
5715 let item = self.mk_item(lo,
5721 return Ok(Some(item));
5724 // FAILURE TO PARSE ITEM
5728 let last_span = self.last_span;
5729 return Err(self.span_fatal(last_span, "unmatched visibility `pub`"));
5733 if !attributes_allowed && !attrs.is_empty() {
5734 self.expected_item_err(&attrs);
5739 pub fn parse_item(&mut self) -> PResult<Option<P<Item>>> {
5740 let attrs = try!(self.parse_outer_attributes());
5741 self.parse_item_(attrs, true, false)
5745 /// Matches view_path : MOD? non_global_path as IDENT
5746 /// | MOD? non_global_path MOD_SEP LBRACE RBRACE
5747 /// | MOD? non_global_path MOD_SEP LBRACE ident_seq RBRACE
5748 /// | MOD? non_global_path MOD_SEP STAR
5749 /// | MOD? non_global_path
5750 fn parse_view_path(&mut self) -> PResult<P<ViewPath>> {
5751 let lo = self.span.lo;
5753 // Allow a leading :: because the paths are absolute either way.
5754 // This occurs with "use $crate::..." in macros.
5755 try!(self.eat(&token::ModSep));
5757 if self.check(&token::OpenDelim(token::Brace)) {
5759 let idents = try!(self.parse_unspanned_seq(
5760 &token::OpenDelim(token::Brace),
5761 &token::CloseDelim(token::Brace),
5762 seq_sep_trailing_allowed(token::Comma),
5763 |p| p.parse_path_list_item()));
5764 let path = ast::Path {
5765 span: mk_sp(lo, self.span.hi),
5767 segments: Vec::new()
5769 return Ok(P(spanned(lo, self.span.hi, ViewPathList(path, idents))));
5772 let first_ident = try!(self.parse_ident());
5773 let mut path = vec!(first_ident);
5774 if let token::ModSep = self.token {
5775 // foo::bar or foo::{a,b,c} or foo::*
5776 while self.check(&token::ModSep) {
5780 token::Ident(..) => {
5781 let ident = try!(self.parse_ident());
5785 // foo::bar::{a,b,c}
5786 token::OpenDelim(token::Brace) => {
5787 let idents = try!(self.parse_unspanned_seq(
5788 &token::OpenDelim(token::Brace),
5789 &token::CloseDelim(token::Brace),
5790 seq_sep_trailing_allowed(token::Comma),
5791 |p| p.parse_path_list_item()
5793 let path = ast::Path {
5794 span: mk_sp(lo, self.span.hi),
5796 segments: path.into_iter().map(|identifier| {
5798 identifier: identifier,
5799 parameters: ast::PathParameters::none(),
5803 return Ok(P(spanned(lo, self.span.hi, ViewPathList(path, idents))));
5807 token::BinOp(token::Star) => {
5809 let path = ast::Path {
5810 span: mk_sp(lo, self.span.hi),
5812 segments: path.into_iter().map(|identifier| {
5814 identifier: identifier,
5815 parameters: ast::PathParameters::none(),
5819 return Ok(P(spanned(lo, self.span.hi, ViewPathGlob(path))));
5822 // fall-through for case foo::bar::;
5824 self.span_err(self.span, "expected identifier or `{` or `*`, found `;`");
5831 let mut rename_to = path[path.len() - 1];
5832 let path = ast::Path {
5833 span: mk_sp(lo, self.last_span.hi),
5835 segments: path.into_iter().map(|identifier| {
5837 identifier: identifier,
5838 parameters: ast::PathParameters::none(),
5842 rename_to = try!(self.parse_rename()).unwrap_or(rename_to);
5843 Ok(P(spanned(lo, self.last_span.hi, ViewPathSimple(rename_to, path))))
5846 fn parse_rename(&mut self) -> PResult<Option<Ident>> {
5847 if try!(self.eat_keyword(keywords::As)) {
5848 self.parse_ident().map(Some)
5854 /// Parses a source module as a crate. This is the main
5855 /// entry point for the parser.
5856 pub fn parse_crate_mod(&mut self) -> PResult<Crate> {
5857 let lo = self.span.lo;
5859 attrs: try!(self.parse_inner_attributes()),
5860 module: try!(self.parse_mod_items(&token::Eof, lo)),
5861 config: self.cfg.clone(),
5862 span: mk_sp(lo, self.span.lo),
5863 exported_macros: Vec::new(),
5867 pub fn parse_optional_str(&mut self)
5868 -> PResult<Option<(InternedString,
5870 Option<ast::Name>)>> {
5871 let ret = match self.token {
5872 token::Literal(token::Str_(s), suf) => {
5873 (self.id_to_interned_str(ast::Ident::with_empty_ctxt(s)), ast::CookedStr, suf)
5875 token::Literal(token::StrRaw(s, n), suf) => {
5876 (self.id_to_interned_str(ast::Ident::with_empty_ctxt(s)), ast::RawStr(n), suf)
5878 _ => return Ok(None)
5884 pub fn parse_str(&mut self) -> PResult<(InternedString, StrStyle)> {
5885 match try!(self.parse_optional_str()) {
5886 Some((s, style, suf)) => {
5887 let sp = self.last_span;
5888 self.expect_no_suffix(sp, "string literal", suf);
5891 _ => Err(self.fatal("expected string literal"))