1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 pub use self::PathParsingMode::*;
15 use ast::{RegionTyParamBound, TraitTyParamBound, TraitBoundModifier};
16 use ast::{Public, Unsafety};
17 use ast::{Mod, BiAdd, Arg, Arm, Attribute, BindByRef, BindByValue};
18 use ast::{BiBitAnd, BiBitOr, BiBitXor, BiRem, BiLt, Block};
19 use ast::{BlockCheckMode, CaptureByRef, CaptureByValue, CaptureClause};
20 use ast::{Constness, ConstTraitItem, Crate, CrateConfig};
21 use ast::{Decl, DeclItem, DeclLocal, DefaultBlock, DefaultReturn};
22 use ast::{UnDeref, BiDiv, EMPTY_CTXT, EnumDef, ExplicitSelf};
23 use ast::{Expr, Expr_, ExprAddrOf, ExprMatch, ExprAgain};
24 use ast::{ExprAssign, ExprAssignOp, ExprBinary, ExprBlock, ExprBox};
25 use ast::{ExprBreak, ExprCall, ExprCast, ExprInPlace};
26 use ast::{ExprField, ExprTupField, ExprClosure, ExprIf, ExprIfLet, ExprIndex};
27 use ast::{ExprLit, ExprLoop, ExprMac, ExprRange};
28 use ast::{ExprMethodCall, ExprParen, ExprPath};
29 use ast::{ExprRepeat, ExprRet, ExprStruct, ExprTup, ExprUnary};
30 use ast::{ExprVec, ExprWhile, ExprWhileLet, ExprForLoop, Field, FnDecl};
31 use ast::{ForeignItem, ForeignItemStatic, ForeignItemFn, FunctionRetTy};
32 use ast::{Ident, Inherited, ImplItem, Item, Item_, ItemStatic};
33 use ast::{ItemEnum, ItemFn, ItemForeignMod, ItemImpl, ItemConst};
34 use ast::{ItemMac, ItemMod, ItemStruct, ItemTrait, ItemTy, ItemDefaultImpl};
35 use ast::{ItemExternCrate, ItemUse};
37 use ast::{LitBool, LitChar, LitByte, LitByteStr};
38 use ast::{LitStr, LitInt, Local};
39 use ast::{MacStmtWithBraces, MacStmtWithSemicolon, MacStmtWithoutBraces};
40 use ast::{MutImmutable, MutMutable, Mac_};
41 use ast::{MutTy, BiMul, Mutability};
42 use ast::{NamedField, UnNeg, NoReturn, UnNot};
43 use ast::{Pat, PatBox, PatEnum, PatIdent, PatLit, PatQPath, PatMac, PatRange};
44 use ast::{PatRegion, PatStruct, PatTup, PatVec, PatWild};
45 use ast::{PolyTraitRef, QSelf};
46 use ast::{Return, BiShl, BiShr, Stmt, StmtDecl};
47 use ast::{StmtExpr, StmtSemi, StmtMac, VariantData, StructField};
48 use ast::{BiSub, StrStyle};
49 use ast::{SelfExplicit, SelfRegion, SelfStatic, SelfValue};
50 use ast::{Delimited, SequenceRepetition, TokenTree, TraitItem, TraitRef};
51 use ast::{Ty, Ty_, TypeBinding, TyMac};
52 use ast::{TyFixedLengthVec, TyBareFn, TyTypeof, TyInfer};
53 use ast::{TyParam, 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::DotDot {
2791 // If we didn’t have to handle `x..`, it would be pretty easy to generalise
2792 // it to the Fixity::None code.
2794 // We have 2 alternatives here: `x..y` and `x..` The other two variants are
2795 // handled with `parse_prefix_range_expr` call above.
2796 let rhs = if self.is_at_start_of_range_notation_rhs() {
2797 self.parse_assoc_expr_with(op.precedence() + 1,
2798 LhsExpr::NotYetParsed).ok()
2802 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
2807 let r = self.mk_range(Some(lhs), rhs);
2808 lhs = self.mk_expr(lhs_span.lo, rhs_span.hi, r, None);
2813 let rhs = try!(match op.fixity() {
2814 Fixity::Right => self.with_res(restrictions, |this|{
2815 this.parse_assoc_expr_with(op.precedence(), LhsExpr::NotYetParsed)
2817 Fixity::Left => self.with_res(restrictions, |this|{
2818 this.parse_assoc_expr_with(op.precedence() + 1, LhsExpr::NotYetParsed)
2820 // We currently have no non-associative operators that are not handled above by
2821 // the special cases. The code is here only for future convenience.
2822 Fixity::None => self.with_res(restrictions, |this|{
2823 this.parse_assoc_expr_with(op.precedence() + 1, LhsExpr::NotYetParsed)
2828 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
2829 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
2830 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
2831 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
2832 AssocOp::Greater | AssocOp::GreaterEqual => {
2833 let ast_op = op.to_ast_binop().unwrap();
2834 let (lhs_span, rhs_span) = (lhs.span, rhs.span);
2835 let binary = self.mk_binary(codemap::respan(cur_op_span, ast_op), lhs, rhs);
2836 self.mk_expr(lhs_span.lo, rhs_span.hi, binary, None)
2839 self.mk_expr(lhs.span.lo, rhs.span.hi, ExprAssign(lhs, rhs), None),
2841 self.mk_expr(lhs.span.lo, rhs.span.hi, ExprInPlace(lhs, rhs), None),
2842 AssocOp::AssignOp(k) => {
2844 token::Plus => BiAdd,
2845 token::Minus => BiSub,
2846 token::Star => BiMul,
2847 token::Slash => BiDiv,
2848 token::Percent => BiRem,
2849 token::Caret => BiBitXor,
2850 token::And => BiBitAnd,
2851 token::Or => BiBitOr,
2852 token::Shl => BiShl,
2855 let (lhs_span, rhs_span) = (lhs.span, rhs.span);
2856 let aopexpr = self.mk_assign_op(codemap::respan(cur_op_span, aop), lhs, rhs);
2857 self.mk_expr(lhs_span.lo, rhs_span.hi, aopexpr, None)
2859 AssocOp::As | AssocOp::DotDot => self.bug("As or DotDot branch reached")
2862 if op.fixity() == Fixity::None { break }
2867 /// Produce an error if comparison operators are chained (RFC #558).
2868 /// We only need to check lhs, not rhs, because all comparison ops
2869 /// have same precedence and are left-associative
2870 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
2871 debug_assert!(outer_op.is_comparison());
2873 ExprBinary(op, _, _) if op.node.is_comparison() => {
2874 // respan to include both operators
2875 let op_span = mk_sp(op.span.lo, self.span.hi);
2876 self.span_err(op_span,
2877 "chained comparison operators require parentheses");
2878 if op.node == BiLt && *outer_op == AssocOp::Greater {
2879 self.fileline_help(op_span,
2880 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
2887 /// Parse prefix-forms of range notation: `..expr` and `..`
2888 fn parse_prefix_range_expr(&mut self,
2889 already_parsed_attrs: Option<ThinAttributes>)
2890 -> PResult<P<Expr>> {
2891 debug_assert!(self.token == token::DotDot);
2892 let attrs = try!(self.parse_or_use_outer_attributes(already_parsed_attrs));
2893 let lo = self.span.lo;
2894 let mut hi = self.span.hi;
2896 let opt_end = if self.is_at_start_of_range_notation_rhs() {
2897 // RHS must be parsed with more associativity than DotDot.
2898 let next_prec = AssocOp::from_token(&token::DotDot).unwrap().precedence() + 1;
2899 Some(try!(self.parse_assoc_expr_with(next_prec,
2900 LhsExpr::NotYetParsed)
2908 let r = self.mk_range(None, opt_end);
2909 Ok(self.mk_expr(lo, hi, r, attrs))
2912 fn is_at_start_of_range_notation_rhs(&self) -> bool {
2913 if self.token.can_begin_expr() {
2914 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
2915 if self.token == token::OpenDelim(token::Brace) {
2916 return !self.restrictions.contains(Restrictions::RESTRICTION_NO_STRUCT_LITERAL);
2924 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
2925 pub fn parse_if_expr(&mut self, attrs: ThinAttributes) -> PResult<P<Expr>> {
2926 if self.check_keyword(keywords::Let) {
2927 return self.parse_if_let_expr(attrs);
2929 let lo = self.last_span.lo;
2930 let cond = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
2931 let thn = try!(self.parse_block());
2932 let mut els: Option<P<Expr>> = None;
2933 let mut hi = thn.span.hi;
2934 if try!(self.eat_keyword(keywords::Else) ){
2935 let elexpr = try!(self.parse_else_expr());
2936 hi = elexpr.span.hi;
2939 Ok(self.mk_expr(lo, hi, ExprIf(cond, thn, els), attrs))
2942 /// Parse an 'if let' expression ('if' token already eaten)
2943 pub fn parse_if_let_expr(&mut self, attrs: ThinAttributes)
2944 -> PResult<P<Expr>> {
2945 let lo = self.last_span.lo;
2946 try!(self.expect_keyword(keywords::Let));
2947 let pat = try!(self.parse_pat());
2948 try!(self.expect(&token::Eq));
2949 let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
2950 let thn = try!(self.parse_block());
2951 let (hi, els) = if try!(self.eat_keyword(keywords::Else) ){
2952 let expr = try!(self.parse_else_expr());
2953 (expr.span.hi, Some(expr))
2957 Ok(self.mk_expr(lo, hi, ExprIfLet(pat, expr, thn, els), attrs))
2961 pub fn parse_lambda_expr(&mut self, lo: BytePos,
2962 capture_clause: CaptureClause,
2963 attrs: ThinAttributes)
2966 let decl = try!(self.parse_fn_block_decl());
2967 let body = match decl.output {
2968 DefaultReturn(_) => {
2969 // If no explicit return type is given, parse any
2970 // expr and wrap it up in a dummy block:
2971 let body_expr = try!(self.parse_expr());
2973 id: ast::DUMMY_NODE_ID,
2975 span: body_expr.span,
2976 expr: Some(body_expr),
2977 rules: DefaultBlock,
2981 // If an explicit return type is given, require a
2982 // block to appear (RFC 968).
2983 try!(self.parse_block())
2990 ExprClosure(capture_clause, decl, body), attrs))
2993 // `else` token already eaten
2994 pub fn parse_else_expr(&mut self) -> PResult<P<Expr>> {
2995 if try!(self.eat_keyword(keywords::If) ){
2996 return self.parse_if_expr(None);
2998 let blk = try!(self.parse_block());
2999 return Ok(self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk), None));
3003 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3004 pub fn parse_for_expr(&mut self, opt_ident: Option<ast::Ident>,
3006 attrs: ThinAttributes) -> PResult<P<Expr>> {
3007 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3009 let pat = try!(self.parse_pat());
3010 try!(self.expect_keyword(keywords::In));
3011 let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3012 let (iattrs, loop_block) = try!(self.parse_inner_attrs_and_block());
3013 let attrs = attrs.append(iattrs.into_thin_attrs());
3015 let hi = self.last_span.hi;
3017 Ok(self.mk_expr(span_lo, hi,
3018 ExprForLoop(pat, expr, loop_block, opt_ident),
3022 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3023 pub fn parse_while_expr(&mut self, opt_ident: Option<ast::Ident>,
3025 attrs: ThinAttributes) -> PResult<P<Expr>> {
3026 if self.token.is_keyword(keywords::Let) {
3027 return self.parse_while_let_expr(opt_ident, span_lo, attrs);
3029 let cond = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3030 let (iattrs, body) = try!(self.parse_inner_attrs_and_block());
3031 let attrs = attrs.append(iattrs.into_thin_attrs());
3032 let hi = body.span.hi;
3033 return Ok(self.mk_expr(span_lo, hi, ExprWhile(cond, body, opt_ident),
3037 /// Parse a 'while let' expression ('while' token already eaten)
3038 pub fn parse_while_let_expr(&mut self, opt_ident: Option<ast::Ident>,
3040 attrs: ThinAttributes) -> PResult<P<Expr>> {
3041 try!(self.expect_keyword(keywords::Let));
3042 let pat = try!(self.parse_pat());
3043 try!(self.expect(&token::Eq));
3044 let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3045 let (iattrs, body) = try!(self.parse_inner_attrs_and_block());
3046 let attrs = attrs.append(iattrs.into_thin_attrs());
3047 let hi = body.span.hi;
3048 return Ok(self.mk_expr(span_lo, hi, ExprWhileLet(pat, expr, body, opt_ident), attrs));
3051 // parse `loop {...}`, `loop` token already eaten
3052 pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::Ident>,
3054 attrs: ThinAttributes) -> PResult<P<Expr>> {
3055 let (iattrs, body) = try!(self.parse_inner_attrs_and_block());
3056 let attrs = attrs.append(iattrs.into_thin_attrs());
3057 let hi = body.span.hi;
3058 Ok(self.mk_expr(span_lo, hi, ExprLoop(body, opt_ident), attrs))
3061 // `match` token already eaten
3062 fn parse_match_expr(&mut self, attrs: ThinAttributes) -> PResult<P<Expr>> {
3063 let match_span = self.last_span;
3064 let lo = self.last_span.lo;
3065 let discriminant = try!(self.parse_expr_res(
3066 Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3067 if let Err(e) = self.commit_expr_expecting(&*discriminant, token::OpenDelim(token::Brace)) {
3068 if self.token == token::Token::Semi {
3069 self.span_note(match_span, "did you mean to remove this `match` keyword?");
3073 let attrs = attrs.append(
3074 try!(self.parse_inner_attributes()).into_thin_attrs());
3075 let mut arms: Vec<Arm> = Vec::new();
3076 while self.token != token::CloseDelim(token::Brace) {
3077 arms.push(try!(self.parse_arm()));
3079 let hi = self.span.hi;
3081 return Ok(self.mk_expr(lo, hi, ExprMatch(discriminant, arms), attrs));
3084 pub fn parse_arm(&mut self) -> PResult<Arm> {
3085 maybe_whole!(no_clone self, NtArm);
3087 let attrs = try!(self.parse_outer_attributes());
3088 let pats = try!(self.parse_pats());
3089 let mut guard = None;
3090 if try!(self.eat_keyword(keywords::If) ){
3091 guard = Some(try!(self.parse_expr()));
3093 try!(self.expect(&token::FatArrow));
3094 let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_STMT_EXPR, None));
3097 !classify::expr_is_simple_block(&*expr)
3098 && self.token != token::CloseDelim(token::Brace);
3101 try!(self.commit_expr(&*expr, &[token::Comma], &[token::CloseDelim(token::Brace)]));
3103 try!(self.eat(&token::Comma));
3114 /// Parse an expression
3115 pub fn parse_expr(&mut self) -> PResult<P<Expr>> {
3116 self.parse_expr_res(Restrictions::empty(), None)
3119 /// Evaluate the closure with restrictions in place.
3121 /// After the closure is evaluated, restrictions are reset.
3122 pub fn with_res<F>(&mut self, r: Restrictions, f: F) -> PResult<P<Expr>>
3123 where F: FnOnce(&mut Self) -> PResult<P<Expr>> {
3124 let old = self.restrictions;
3125 self.restrictions = r;
3127 self.restrictions = old;
3132 /// Parse an expression, subject to the given restrictions
3133 pub fn parse_expr_res(&mut self, r: Restrictions,
3134 already_parsed_attrs: Option<ThinAttributes>)
3135 -> PResult<P<Expr>> {
3136 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3139 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3140 fn parse_initializer(&mut self) -> PResult<Option<P<Expr>>> {
3141 if self.check(&token::Eq) {
3143 Ok(Some(try!(self.parse_expr())))
3149 /// Parse patterns, separated by '|' s
3150 fn parse_pats(&mut self) -> PResult<Vec<P<Pat>>> {
3151 let mut pats = Vec::new();
3153 pats.push(try!(self.parse_pat()));
3154 if self.check(&token::BinOp(token::Or)) { try!(self.bump());}
3155 else { return Ok(pats); }
3159 fn parse_pat_tuple_elements(&mut self) -> PResult<Vec<P<Pat>>> {
3160 let mut fields = vec![];
3161 if !self.check(&token::CloseDelim(token::Paren)) {
3162 fields.push(try!(self.parse_pat()));
3163 if self.look_ahead(1, |t| *t != token::CloseDelim(token::Paren)) {
3164 while try!(self.eat(&token::Comma)) &&
3165 !self.check(&token::CloseDelim(token::Paren)) {
3166 fields.push(try!(self.parse_pat()));
3169 if fields.len() == 1 {
3170 try!(self.expect(&token::Comma));
3176 fn parse_pat_vec_elements(
3178 ) -> PResult<(Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3179 let mut before = Vec::new();
3180 let mut slice = None;
3181 let mut after = Vec::new();
3182 let mut first = true;
3183 let mut before_slice = true;
3185 while self.token != token::CloseDelim(token::Bracket) {
3189 try!(self.expect(&token::Comma));
3191 if self.token == token::CloseDelim(token::Bracket)
3192 && (before_slice || !after.is_empty()) {
3198 if self.check(&token::DotDot) {
3201 if self.check(&token::Comma) ||
3202 self.check(&token::CloseDelim(token::Bracket)) {
3203 slice = Some(P(ast::Pat {
3204 id: ast::DUMMY_NODE_ID,
3208 before_slice = false;
3214 let subpat = try!(self.parse_pat());
3215 if before_slice && self.check(&token::DotDot) {
3217 slice = Some(subpat);
3218 before_slice = false;
3219 } else if before_slice {
3220 before.push(subpat);
3226 Ok((before, slice, after))
3229 /// Parse the fields of a struct-like pattern
3230 fn parse_pat_fields(&mut self) -> PResult<(Vec<codemap::Spanned<ast::FieldPat>> , bool)> {
3231 let mut fields = Vec::new();
3232 let mut etc = false;
3233 let mut first = true;
3234 while self.token != token::CloseDelim(token::Brace) {
3238 try!(self.expect(&token::Comma));
3239 // accept trailing commas
3240 if self.check(&token::CloseDelim(token::Brace)) { break }
3243 let lo = self.span.lo;
3246 if self.check(&token::DotDot) {
3248 if self.token != token::CloseDelim(token::Brace) {
3249 let token_str = self.this_token_to_string();
3250 return Err(self.fatal(&format!("expected `{}`, found `{}`", "}",
3257 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3258 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3259 // Parsing a pattern of the form "fieldname: pat"
3260 let fieldname = try!(self.parse_ident());
3262 let pat = try!(self.parse_pat());
3264 (pat, fieldname, false)
3266 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3267 let is_box = try!(self.eat_keyword(keywords::Box));
3268 let boxed_span_lo = self.span.lo;
3269 let is_ref = try!(self.eat_keyword(keywords::Ref));
3270 let is_mut = try!(self.eat_keyword(keywords::Mut));
3271 let fieldname = try!(self.parse_ident());
3272 hi = self.last_span.hi;
3274 let bind_type = match (is_ref, is_mut) {
3275 (true, true) => BindByRef(MutMutable),
3276 (true, false) => BindByRef(MutImmutable),
3277 (false, true) => BindByValue(MutMutable),
3278 (false, false) => BindByValue(MutImmutable),
3280 let fieldpath = codemap::Spanned{span:self.last_span, node:fieldname};
3281 let fieldpat = P(ast::Pat{
3282 id: ast::DUMMY_NODE_ID,
3283 node: PatIdent(bind_type, fieldpath, None),
3284 span: mk_sp(boxed_span_lo, hi),
3287 let subpat = if is_box {
3289 id: ast::DUMMY_NODE_ID,
3290 node: PatBox(fieldpat),
3291 span: mk_sp(lo, hi),
3296 (subpat, fieldname, true)
3299 fields.push(codemap::Spanned { span: mk_sp(lo, hi),
3300 node: ast::FieldPat { ident: fieldname,
3302 is_shorthand: is_shorthand }});
3304 return Ok((fields, etc));
3307 fn parse_pat_range_end(&mut self) -> PResult<P<Expr>> {
3308 if self.is_path_start() {
3309 let lo = self.span.lo;
3310 let (qself, path) = if try!(self.eat_lt()) {
3311 // Parse a qualified path
3313 try!(self.parse_qualified_path(NoTypesAllowed));
3316 // Parse an unqualified path
3317 (None, try!(self.parse_path(LifetimeAndTypesWithColons)))
3319 let hi = self.last_span.hi;
3320 Ok(self.mk_expr(lo, hi, ExprPath(qself, path), None))
3322 self.parse_pat_literal_maybe_minus()
3326 fn is_path_start(&self) -> bool {
3327 (self.token == token::Lt || self.token == token::ModSep
3328 || self.token.is_ident() || self.token.is_path())
3329 && !self.token.is_keyword(keywords::True) && !self.token.is_keyword(keywords::False)
3332 /// Parse a pattern.
3333 pub fn parse_pat(&mut self) -> PResult<P<Pat>> {
3334 maybe_whole!(self, NtPat);
3336 let lo = self.span.lo;
3339 token::Underscore => {
3344 token::BinOp(token::And) | token::AndAnd => {
3345 // Parse &pat / &mut pat
3346 try!(self.expect_and());
3347 let mutbl = try!(self.parse_mutability());
3348 if let token::Lifetime(ident) = self.token {
3349 return Err(self.fatal(&format!("unexpected lifetime `{}` in pattern", ident)));
3352 let subpat = try!(self.parse_pat());
3353 pat = PatRegion(subpat, mutbl);
3355 token::OpenDelim(token::Paren) => {
3356 // Parse (pat,pat,pat,...) as tuple pattern
3358 let fields = try!(self.parse_pat_tuple_elements());
3359 try!(self.expect(&token::CloseDelim(token::Paren)));
3360 pat = PatTup(fields);
3362 token::OpenDelim(token::Bracket) => {
3363 // Parse [pat,pat,...] as slice pattern
3365 let (before, slice, after) = try!(self.parse_pat_vec_elements());
3366 try!(self.expect(&token::CloseDelim(token::Bracket)));
3367 pat = PatVec(before, slice, after);
3370 // At this point, token != _, &, &&, (, [
3371 if try!(self.eat_keyword(keywords::Mut)) {
3372 // Parse mut ident @ pat
3373 pat = try!(self.parse_pat_ident(BindByValue(MutMutable)));
3374 } else if try!(self.eat_keyword(keywords::Ref)) {
3375 // Parse ref ident @ pat / ref mut ident @ pat
3376 let mutbl = try!(self.parse_mutability());
3377 pat = try!(self.parse_pat_ident(BindByRef(mutbl)));
3378 } else if try!(self.eat_keyword(keywords::Box)) {
3380 let subpat = try!(self.parse_pat());
3381 pat = PatBox(subpat);
3382 } else if self.is_path_start() {
3383 // Parse pattern starting with a path
3384 if self.token.is_plain_ident() && self.look_ahead(1, |t| *t != token::DotDotDot &&
3385 *t != token::OpenDelim(token::Brace) &&
3386 *t != token::OpenDelim(token::Paren) &&
3387 // Contrary to its definition, a plain ident can be followed by :: in macros
3388 *t != token::ModSep) {
3389 // Plain idents have some extra abilities here compared to general paths
3390 if self.look_ahead(1, |t| *t == token::Not) {
3391 // Parse macro invocation
3392 let ident = try!(self.parse_ident());
3393 let ident_span = self.last_span;
3394 let path = ident_to_path(ident_span, ident);
3396 let delim = try!(self.expect_open_delim());
3397 let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
3398 seq_sep_none(), |p| p.parse_token_tree()));
3399 let mac = Mac_ { path: path, tts: tts, ctxt: EMPTY_CTXT };
3400 pat = PatMac(codemap::Spanned {node: mac,
3401 span: mk_sp(lo, self.last_span.hi)});
3403 // Parse ident @ pat
3404 // This can give false positives and parse nullary enums,
3405 // they are dealt with later in resolve
3406 pat = try!(self.parse_pat_ident(BindByValue(MutImmutable)));
3409 let (qself, path) = if try!(self.eat_lt()) {
3410 // Parse a qualified path
3412 try!(self.parse_qualified_path(NoTypesAllowed));
3415 // Parse an unqualified path
3416 (None, try!(self.parse_path(LifetimeAndTypesWithColons)))
3419 token::DotDotDot => {
3421 let hi = self.last_span.hi;
3422 let begin = self.mk_expr(lo, hi, ExprPath(qself, path), None);
3424 let end = try!(self.parse_pat_range_end());
3425 pat = PatRange(begin, end);
3427 token::OpenDelim(token::Brace) => {
3428 if qself.is_some() {
3429 return Err(self.fatal("unexpected `{` after qualified path"));
3431 // Parse struct pattern
3433 let (fields, etc) = try!(self.parse_pat_fields());
3435 pat = PatStruct(path, fields, etc);
3437 token::OpenDelim(token::Paren) => {
3438 if qself.is_some() {
3439 return Err(self.fatal("unexpected `(` after qualified path"));
3441 // Parse tuple struct or enum pattern
3442 if self.look_ahead(1, |t| *t == token::DotDot) {
3443 // This is a "top constructor only" pat
3446 try!(self.expect(&token::CloseDelim(token::Paren)));
3447 pat = PatEnum(path, None);
3449 let args = try!(self.parse_enum_variant_seq(
3450 &token::OpenDelim(token::Paren),
3451 &token::CloseDelim(token::Paren),
3452 seq_sep_trailing_allowed(token::Comma),
3453 |p| p.parse_pat()));
3454 pat = PatEnum(path, Some(args));
3459 // Parse qualified path
3460 Some(qself) => PatQPath(qself, path),
3461 // Parse nullary enum
3462 None => PatEnum(path, Some(vec![]))
3468 // Try to parse everything else as literal with optional minus
3469 let begin = try!(self.parse_pat_literal_maybe_minus());
3470 if try!(self.eat(&token::DotDotDot)) {
3471 let end = try!(self.parse_pat_range_end());
3472 pat = PatRange(begin, end);
3474 pat = PatLit(begin);
3480 let hi = self.last_span.hi;
3482 id: ast::DUMMY_NODE_ID,
3484 span: mk_sp(lo, hi),
3488 /// Parse ident or ident @ pat
3489 /// used by the copy foo and ref foo patterns to give a good
3490 /// error message when parsing mistakes like ref foo(a,b)
3491 fn parse_pat_ident(&mut self,
3492 binding_mode: ast::BindingMode)
3493 -> PResult<ast::Pat_> {
3494 if !self.token.is_plain_ident() {
3495 let span = self.span;
3496 let tok_str = self.this_token_to_string();
3497 return Err(self.span_fatal(span,
3498 &format!("expected identifier, found `{}`", tok_str)))
3500 let ident = try!(self.parse_ident());
3501 let last_span = self.last_span;
3502 let name = codemap::Spanned{span: last_span, node: ident};
3503 let sub = if try!(self.eat(&token::At) ){
3504 Some(try!(self.parse_pat()))
3509 // just to be friendly, if they write something like
3511 // we end up here with ( as the current token. This shortly
3512 // leads to a parse error. Note that if there is no explicit
3513 // binding mode then we do not end up here, because the lookahead
3514 // will direct us over to parse_enum_variant()
3515 if self.token == token::OpenDelim(token::Paren) {
3516 let last_span = self.last_span;
3517 return Err(self.span_fatal(
3519 "expected identifier, found enum pattern"))
3522 Ok(PatIdent(binding_mode, name, sub))
3525 /// Parse a local variable declaration
3526 fn parse_local(&mut self, attrs: ThinAttributes) -> PResult<P<Local>> {
3527 let lo = self.span.lo;
3528 let pat = try!(self.parse_pat());
3531 if try!(self.eat(&token::Colon) ){
3532 ty = Some(try!(self.parse_ty_sum()));
3534 let init = try!(self.parse_initializer());
3539 id: ast::DUMMY_NODE_ID,
3540 span: mk_sp(lo, self.last_span.hi),
3545 /// Parse a "let" stmt
3546 fn parse_let(&mut self, attrs: ThinAttributes) -> PResult<P<Decl>> {
3547 let lo = self.span.lo;
3548 let local = try!(self.parse_local(attrs));
3549 Ok(P(spanned(lo, self.last_span.hi, DeclLocal(local))))
3552 /// Parse a structure field
3553 fn parse_name_and_ty(&mut self, pr: Visibility,
3554 attrs: Vec<Attribute> ) -> PResult<StructField> {
3556 Inherited => self.span.lo,
3557 Public => self.last_span.lo,
3559 if !self.token.is_plain_ident() {
3560 return Err(self.fatal("expected ident"));
3562 let name = try!(self.parse_ident());
3563 try!(self.expect(&token::Colon));
3564 let ty = try!(self.parse_ty_sum());
3565 Ok(spanned(lo, self.last_span.hi, ast::StructField_ {
3566 kind: NamedField(name, pr),
3567 id: ast::DUMMY_NODE_ID,
3573 /// Emit an expected item after attributes error.
3574 fn expected_item_err(&self, attrs: &[Attribute]) {
3575 let message = match attrs.last() {
3576 Some(&Attribute { node: ast::Attribute_ { is_sugared_doc: true, .. }, .. }) => {
3577 "expected item after doc comment"
3579 _ => "expected item after attributes",
3582 self.span_err(self.last_span, message);
3585 /// Parse a statement. may include decl.
3586 pub fn parse_stmt(&mut self) -> PResult<Option<P<Stmt>>> {
3587 Ok(try!(self.parse_stmt_()).map(P))
3590 fn parse_stmt_(&mut self) -> PResult<Option<Stmt>> {
3591 maybe_whole!(Some deref self, NtStmt);
3593 let attrs = try!(self.parse_outer_attributes());
3594 let lo = self.span.lo;
3596 Ok(Some(if self.check_keyword(keywords::Let) {
3597 try!(self.expect_keyword(keywords::Let));
3598 let decl = try!(self.parse_let(attrs.into_thin_attrs()));
3599 let hi = decl.span.hi;
3600 let stmt = StmtDecl(decl, ast::DUMMY_NODE_ID);
3601 spanned(lo, hi, stmt)
3602 } else if self.token.is_ident()
3603 && !self.token.is_any_keyword()
3604 && self.look_ahead(1, |t| *t == token::Not) {
3605 // it's a macro invocation:
3607 // Potential trouble: if we allow macros with paths instead of
3608 // idents, we'd need to look ahead past the whole path here...
3609 let pth = try!(self.parse_path(NoTypesAllowed));
3612 let id = match self.token {
3613 token::OpenDelim(_) => token::special_idents::invalid, // no special identifier
3614 _ => try!(self.parse_ident()),
3617 // check that we're pointing at delimiters (need to check
3618 // again after the `if`, because of `parse_ident`
3619 // consuming more tokens).
3620 let delim = match self.token {
3621 token::OpenDelim(delim) => delim,
3623 // we only expect an ident if we didn't parse one
3625 let ident_str = if id.name == token::special_idents::invalid.name {
3630 let tok_str = self.this_token_to_string();
3631 return Err(self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
3637 let tts = try!(self.parse_unspanned_seq(
3638 &token::OpenDelim(delim),
3639 &token::CloseDelim(delim),
3641 |p| p.parse_token_tree()
3643 let hi = self.last_span.hi;
3645 let style = if delim == token::Brace {
3648 MacStmtWithoutBraces
3651 if id.name == token::special_idents::invalid.name {
3652 let stmt = StmtMac(P(spanned(lo,
3654 Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT })),
3656 attrs.into_thin_attrs());
3657 spanned(lo, hi, stmt)
3659 // if it has a special ident, it's definitely an item
3661 // Require a semicolon or braces.
3662 if style != MacStmtWithBraces {
3663 if !try!(self.eat(&token::Semi) ){
3664 let last_span = self.last_span;
3665 self.span_err(last_span,
3666 "macros that expand to items must \
3667 either be surrounded with braces or \
3668 followed by a semicolon");
3671 spanned(lo, hi, StmtDecl(
3672 P(spanned(lo, hi, DeclItem(
3674 lo, hi, id /*id is good here*/,
3675 ItemMac(spanned(lo, hi,
3676 Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT })),
3677 Inherited, attrs)))),
3678 ast::DUMMY_NODE_ID))
3681 // FIXME: Bad copy of attrs
3682 match try!(self.parse_item_(attrs.clone(), false, true)) {
3685 let decl = P(spanned(lo, hi, DeclItem(i)));
3686 spanned(lo, hi, StmtDecl(decl, ast::DUMMY_NODE_ID))
3689 let unused_attrs = |attrs: &[_], s: &mut Self| {
3690 if attrs.len() > 0 {
3692 "expected statement after outer attribute");
3696 // Do not attempt to parse an expression if we're done here.
3697 if self.token == token::Semi {
3698 unused_attrs(&attrs, self);
3703 if self.token == token::CloseDelim(token::Brace) {
3704 unused_attrs(&attrs, self);
3708 // Remainder are line-expr stmts.
3709 let e = try!(self.parse_expr_res(
3710 Restrictions::RESTRICTION_STMT_EXPR, Some(attrs.into_thin_attrs())));
3712 let stmt = StmtExpr(e, ast::DUMMY_NODE_ID);
3713 spanned(lo, hi, stmt)
3719 /// Is this expression a successfully-parsed statement?
3720 fn expr_is_complete(&mut self, e: &Expr) -> bool {
3721 self.restrictions.contains(Restrictions::RESTRICTION_STMT_EXPR) &&
3722 !classify::expr_requires_semi_to_be_stmt(e)
3725 /// Parse a block. No inner attrs are allowed.
3726 pub fn parse_block(&mut self) -> PResult<P<Block>> {
3727 maybe_whole!(no_clone self, NtBlock);
3729 let lo = self.span.lo;
3731 if !try!(self.eat(&token::OpenDelim(token::Brace)) ){
3733 let tok = self.this_token_to_string();
3734 return Err(self.span_fatal_help(sp,
3735 &format!("expected `{{`, found `{}`", tok),
3736 "place this code inside a block"));
3739 self.parse_block_tail(lo, DefaultBlock)
3742 /// Parse a block. Inner attrs are allowed.
3743 fn parse_inner_attrs_and_block(&mut self) -> PResult<(Vec<Attribute>, P<Block>)> {
3744 maybe_whole!(pair_empty self, NtBlock);
3746 let lo = self.span.lo;
3747 try!(self.expect(&token::OpenDelim(token::Brace)));
3748 Ok((try!(self.parse_inner_attributes()),
3749 try!(self.parse_block_tail(lo, DefaultBlock))))
3752 /// Parse the rest of a block expression or function body
3753 /// Precondition: already parsed the '{'.
3754 fn parse_block_tail(&mut self, lo: BytePos, s: BlockCheckMode) -> PResult<P<Block>> {
3755 let mut stmts = vec![];
3756 let mut expr = None;
3758 while !try!(self.eat(&token::CloseDelim(token::Brace))) {
3759 let Spanned {node, span} = if let Some(s) = try!(self.parse_stmt_()) {
3762 // Found only `;` or `}`.
3767 try!(self.handle_expression_like_statement(e, span, &mut stmts, &mut expr));
3769 StmtMac(mac, MacStmtWithoutBraces, attrs) => {
3770 // statement macro without braces; might be an
3771 // expr depending on whether a semicolon follows
3774 stmts.push(P(Spanned {
3775 node: StmtMac(mac, MacStmtWithSemicolon, attrs),
3776 span: mk_sp(span.lo, self.span.hi),
3781 let e = self.mk_mac_expr(span.lo, span.hi,
3782 mac.and_then(|m| m.node),
3784 let e = try!(self.parse_dot_or_call_expr_with(e, attrs));
3785 let e = try!(self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e)));
3786 try!(self.handle_expression_like_statement(
3794 StmtMac(m, style, attrs) => {
3795 // statement macro; might be an expr
3798 stmts.push(P(Spanned {
3799 node: StmtMac(m, MacStmtWithSemicolon, attrs),
3800 span: mk_sp(span.lo, self.span.hi),
3804 token::CloseDelim(token::Brace) => {
3805 // if a block ends in `m!(arg)` without
3806 // a `;`, it must be an expr
3807 expr = Some(self.mk_mac_expr(span.lo, span.hi,
3808 m.and_then(|x| x.node),
3812 stmts.push(P(Spanned {
3813 node: StmtMac(m, style, attrs),
3819 _ => { // all other kinds of statements:
3820 let mut hi = span.hi;
3821 if classify::stmt_ends_with_semi(&node) {
3822 try!(self.commit_stmt_expecting(token::Semi));
3823 hi = self.last_span.hi;
3826 stmts.push(P(Spanned {
3828 span: mk_sp(span.lo, hi)
3837 id: ast::DUMMY_NODE_ID,
3839 span: mk_sp(lo, self.last_span.hi),
3843 fn handle_expression_like_statement(
3847 stmts: &mut Vec<P<Stmt>>,
3848 last_block_expr: &mut Option<P<Expr>>) -> PResult<()> {
3849 // expression without semicolon
3850 if classify::expr_requires_semi_to_be_stmt(&*e) {
3851 // Just check for errors and recover; do not eat semicolon yet.
3852 try!(self.commit_stmt(&[],
3853 &[token::Semi, token::CloseDelim(token::Brace)]));
3859 let span_with_semi = Span {
3861 hi: self.last_span.hi,
3862 expn_id: span.expn_id,
3864 stmts.push(P(Spanned {
3865 node: StmtSemi(e, ast::DUMMY_NODE_ID),
3866 span: span_with_semi,
3869 token::CloseDelim(token::Brace) => *last_block_expr = Some(e),
3871 stmts.push(P(Spanned {
3872 node: StmtExpr(e, ast::DUMMY_NODE_ID),
3880 // Parses a sequence of bounds if a `:` is found,
3881 // otherwise returns empty list.
3882 fn parse_colon_then_ty_param_bounds(&mut self,
3883 mode: BoundParsingMode)
3884 -> PResult<TyParamBounds>
3886 if !try!(self.eat(&token::Colon) ){
3889 self.parse_ty_param_bounds(mode)
3893 // matches bounds = ( boundseq )?
3894 // where boundseq = ( polybound + boundseq ) | polybound
3895 // and polybound = ( 'for' '<' 'region '>' )? bound
3896 // and bound = 'region | trait_ref
3897 fn parse_ty_param_bounds(&mut self,
3898 mode: BoundParsingMode)
3899 -> PResult<TyParamBounds>
3901 let mut result = vec!();
3903 let question_span = self.span;
3904 let ate_question = try!(self.eat(&token::Question));
3906 token::Lifetime(lifetime) => {
3908 self.span_err(question_span,
3909 "`?` may only modify trait bounds, not lifetime bounds");
3911 result.push(RegionTyParamBound(ast::Lifetime {
3912 id: ast::DUMMY_NODE_ID,
3918 token::ModSep | token::Ident(..) => {
3919 let poly_trait_ref = try!(self.parse_poly_trait_ref());
3920 let modifier = if ate_question {
3921 if mode == BoundParsingMode::Modified {
3922 TraitBoundModifier::Maybe
3924 self.span_err(question_span,
3926 TraitBoundModifier::None
3929 TraitBoundModifier::None
3931 result.push(TraitTyParamBound(poly_trait_ref, modifier))
3936 if !try!(self.eat(&token::BinOp(token::Plus)) ){
3941 return Ok(P::from_vec(result));
3944 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
3945 fn parse_ty_param(&mut self) -> PResult<TyParam> {
3946 let span = self.span;
3947 let ident = try!(self.parse_ident());
3949 let bounds = try!(self.parse_colon_then_ty_param_bounds(BoundParsingMode::Modified));
3951 let default = if self.check(&token::Eq) {
3953 Some(try!(self.parse_ty_sum()))
3960 id: ast::DUMMY_NODE_ID,
3967 /// Parse a set of optional generic type parameter declarations. Where
3968 /// clauses are not parsed here, and must be added later via
3969 /// `parse_where_clause()`.
3971 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
3972 /// | ( < lifetimes , typaramseq ( , )? > )
3973 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
3974 pub fn parse_generics(&mut self) -> PResult<ast::Generics> {
3975 maybe_whole!(self, NtGenerics);
3977 if try!(self.eat(&token::Lt) ){
3978 let lifetime_defs = try!(self.parse_lifetime_defs());
3979 let mut seen_default = false;
3980 let ty_params = try!(self.parse_seq_to_gt(Some(token::Comma), |p| {
3981 try!(p.forbid_lifetime());
3982 let ty_param = try!(p.parse_ty_param());
3983 if ty_param.default.is_some() {
3984 seen_default = true;
3985 } else if seen_default {
3986 let last_span = p.last_span;
3987 p.span_err(last_span,
3988 "type parameters with a default must be trailing");
3993 lifetimes: lifetime_defs,
3994 ty_params: ty_params,
3995 where_clause: WhereClause {
3996 id: ast::DUMMY_NODE_ID,
3997 predicates: Vec::new(),
4001 Ok(ast::Generics::default())
4005 fn parse_generic_values_after_lt(&mut self) -> PResult<(Vec<ast::Lifetime>,
4007 Vec<P<TypeBinding>>)> {
4008 let span_lo = self.span.lo;
4009 let lifetimes = try!(self.parse_lifetimes(token::Comma));
4011 let missing_comma = !lifetimes.is_empty() &&
4012 !self.token.is_like_gt() &&
4014 .as_ref().map_or(true,
4015 |x| &**x != &token::Comma);
4019 let msg = format!("expected `,` or `>` after lifetime \
4021 self.this_token_to_string());
4022 self.span_err(self.span, &msg);
4024 let span_hi = self.span.hi;
4025 let span_hi = if self.parse_ty().is_ok() {
4031 let msg = format!("did you mean a single argument type &'a Type, \
4032 or did you mean the comma-separated arguments \
4034 self.span_note(mk_sp(span_lo, span_hi), &msg);
4036 self.abort_if_errors()
4039 // First parse types.
4040 let (types, returned) = try!(self.parse_seq_to_gt_or_return(
4043 try!(p.forbid_lifetime());
4044 if p.look_ahead(1, |t| t == &token::Eq) {
4047 Ok(Some(try!(p.parse_ty_sum())))
4052 // If we found the `>`, don't continue.
4054 return Ok((lifetimes, types.into_vec(), Vec::new()));
4057 // Then parse type bindings.
4058 let bindings = try!(self.parse_seq_to_gt(
4061 try!(p.forbid_lifetime());
4063 let ident = try!(p.parse_ident());
4064 let found_eq = try!(p.eat(&token::Eq));
4067 p.span_warn(span, "whoops, no =?");
4069 let ty = try!(p.parse_ty());
4070 let hi = ty.span.hi;
4071 let span = mk_sp(lo, hi);
4072 return Ok(P(TypeBinding{id: ast::DUMMY_NODE_ID,
4079 Ok((lifetimes, types.into_vec(), bindings.into_vec()))
4082 fn forbid_lifetime(&mut self) -> PResult<()> {
4083 if self.token.is_lifetime() {
4084 let span = self.span;
4085 return Err(self.span_fatal(span, "lifetime parameters must be declared \
4086 prior to type parameters"))
4091 /// Parses an optional `where` clause and places it in `generics`.
4094 /// where T : Trait<U, V> + 'b, 'a : 'b
4096 pub fn parse_where_clause(&mut self) -> PResult<ast::WhereClause> {
4097 maybe_whole!(self, NtWhereClause);
4099 let mut where_clause = WhereClause {
4100 id: ast::DUMMY_NODE_ID,
4101 predicates: Vec::new(),
4104 if !try!(self.eat_keyword(keywords::Where)) {
4105 return Ok(where_clause);
4108 let mut parsed_something = false;
4110 let lo = self.span.lo;
4112 token::OpenDelim(token::Brace) => {
4116 token::Lifetime(..) => {
4117 let bounded_lifetime =
4118 try!(self.parse_lifetime());
4120 try!(self.eat(&token::Colon));
4123 try!(self.parse_lifetimes(token::BinOp(token::Plus)));
4125 let hi = self.last_span.hi;
4126 let span = mk_sp(lo, hi);
4128 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
4129 ast::WhereRegionPredicate {
4131 lifetime: bounded_lifetime,
4136 parsed_something = true;
4140 let bound_lifetimes = if try!(self.eat_keyword(keywords::For) ){
4141 // Higher ranked constraint.
4142 try!(self.expect(&token::Lt));
4143 let lifetime_defs = try!(self.parse_lifetime_defs());
4144 try!(self.expect_gt());
4150 let bounded_ty = try!(self.parse_ty());
4152 if try!(self.eat(&token::Colon) ){
4153 let bounds = try!(self.parse_ty_param_bounds(BoundParsingMode::Bare));
4154 let hi = self.last_span.hi;
4155 let span = mk_sp(lo, hi);
4157 if bounds.is_empty() {
4159 "each predicate in a `where` clause must have \
4160 at least one bound in it");
4163 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
4164 ast::WhereBoundPredicate {
4166 bound_lifetimes: bound_lifetimes,
4167 bounded_ty: bounded_ty,
4171 parsed_something = true;
4172 } else if try!(self.eat(&token::Eq) ){
4173 // let ty = try!(self.parse_ty());
4174 let hi = self.last_span.hi;
4175 let span = mk_sp(lo, hi);
4176 // where_clause.predicates.push(
4177 // ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
4178 // id: ast::DUMMY_NODE_ID,
4180 // path: panic!("NYI"), //bounded_ty,
4183 // parsed_something = true;
4186 "equality constraints are not yet supported \
4187 in where clauses (#20041)");
4189 let last_span = self.last_span;
4190 self.span_err(last_span,
4191 "unexpected token in `where` clause");
4196 if !try!(self.eat(&token::Comma) ){
4201 if !parsed_something {
4202 let last_span = self.last_span;
4203 self.span_err(last_span,
4204 "a `where` clause must have at least one predicate \
4211 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
4212 -> PResult<(Vec<Arg> , bool)> {
4214 let mut args: Vec<Option<Arg>> =
4215 try!(self.parse_unspanned_seq(
4216 &token::OpenDelim(token::Paren),
4217 &token::CloseDelim(token::Paren),
4218 seq_sep_trailing_allowed(token::Comma),
4220 if p.token == token::DotDotDot {
4223 if p.token != token::CloseDelim(token::Paren) {
4225 return Err(p.span_fatal(span,
4226 "`...` must be last in argument list for variadic function"))
4230 return Err(p.span_fatal(span,
4231 "only foreign functions are allowed to be variadic"))
4235 Ok(Some(try!(p.parse_arg_general(named_args))))
4240 let variadic = match args.pop() {
4243 // Need to put back that last arg
4250 if variadic && args.is_empty() {
4252 "variadic function must be declared with at least one named argument");
4255 let args = args.into_iter().map(|x| x.unwrap()).collect();
4257 Ok((args, variadic))
4260 /// Parse the argument list and result type of a function declaration
4261 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<P<FnDecl>> {
4263 let (args, variadic) = try!(self.parse_fn_args(true, allow_variadic));
4264 let ret_ty = try!(self.parse_ret_ty());
4273 fn is_self_ident(&mut self) -> bool {
4275 token::Ident(id, token::Plain) => id.name == special_idents::self_.name,
4280 fn expect_self_ident(&mut self) -> PResult<ast::Ident> {
4282 token::Ident(id, token::Plain) if id.name == special_idents::self_.name => {
4287 let token_str = self.this_token_to_string();
4288 return Err(self.fatal(&format!("expected `self`, found `{}`",
4294 fn is_self_type_ident(&mut self) -> bool {
4296 token::Ident(id, token::Plain) => id.name == special_idents::type_self.name,
4301 fn expect_self_type_ident(&mut self) -> PResult<ast::Ident> {
4303 token::Ident(id, token::Plain) if id.name == special_idents::type_self.name => {
4308 let token_str = self.this_token_to_string();
4309 Err(self.fatal(&format!("expected `Self`, found `{}`",
4315 /// Parse the argument list and result type of a function
4316 /// that may have a self type.
4317 fn parse_fn_decl_with_self<F>(&mut self,
4318 parse_arg_fn: F) -> PResult<(ExplicitSelf, P<FnDecl>)> where
4319 F: FnMut(&mut Parser) -> PResult<Arg>,
4321 fn maybe_parse_borrowed_explicit_self(this: &mut Parser)
4322 -> PResult<ast::ExplicitSelf_> {
4323 // The following things are possible to see here:
4328 // fn(&'lt mut self)
4330 // We already know that the current token is `&`.
4332 if this.look_ahead(1, |t| t.is_keyword(keywords::SelfValue)) {
4334 Ok(SelfRegion(None, MutImmutable, try!(this.expect_self_ident())))
4335 } else if this.look_ahead(1, |t| t.is_mutability()) &&
4336 this.look_ahead(2, |t| t.is_keyword(keywords::SelfValue)) {
4338 let mutability = try!(this.parse_mutability());
4339 Ok(SelfRegion(None, mutability, try!(this.expect_self_ident())))
4340 } else if this.look_ahead(1, |t| t.is_lifetime()) &&
4341 this.look_ahead(2, |t| t.is_keyword(keywords::SelfValue)) {
4343 let lifetime = try!(this.parse_lifetime());
4344 Ok(SelfRegion(Some(lifetime), MutImmutable, try!(this.expect_self_ident())))
4345 } else if this.look_ahead(1, |t| t.is_lifetime()) &&
4346 this.look_ahead(2, |t| t.is_mutability()) &&
4347 this.look_ahead(3, |t| t.is_keyword(keywords::SelfValue)) {
4349 let lifetime = try!(this.parse_lifetime());
4350 let mutability = try!(this.parse_mutability());
4351 Ok(SelfRegion(Some(lifetime), mutability, try!(this.expect_self_ident())))
4357 try!(self.expect(&token::OpenDelim(token::Paren)));
4359 // A bit of complexity and lookahead is needed here in order to be
4360 // backwards compatible.
4361 let lo = self.span.lo;
4362 let mut self_ident_lo = self.span.lo;
4363 let mut self_ident_hi = self.span.hi;
4365 let mut mutbl_self = MutImmutable;
4366 let explicit_self = match self.token {
4367 token::BinOp(token::And) => {
4368 let eself = try!(maybe_parse_borrowed_explicit_self(self));
4369 self_ident_lo = self.last_span.lo;
4370 self_ident_hi = self.last_span.hi;
4373 token::BinOp(token::Star) => {
4374 // Possibly "*self" or "*mut self" -- not supported. Try to avoid
4375 // emitting cryptic "unexpected token" errors.
4377 let _mutability = if self.token.is_mutability() {
4378 try!(self.parse_mutability())
4382 if self.is_self_ident() {
4383 let span = self.span;
4384 self.span_err(span, "cannot pass self by raw pointer");
4387 // error case, making bogus self ident:
4388 SelfValue(special_idents::self_)
4390 token::Ident(..) => {
4391 if self.is_self_ident() {
4392 let self_ident = try!(self.expect_self_ident());
4394 // Determine whether this is the fully explicit form, `self:
4396 if try!(self.eat(&token::Colon) ){
4397 SelfExplicit(try!(self.parse_ty_sum()), self_ident)
4399 SelfValue(self_ident)
4401 } else if self.token.is_mutability() &&
4402 self.look_ahead(1, |t| t.is_keyword(keywords::SelfValue)) {
4403 mutbl_self = try!(self.parse_mutability());
4404 let self_ident = try!(self.expect_self_ident());
4406 // Determine whether this is the fully explicit form,
4408 if try!(self.eat(&token::Colon) ){
4409 SelfExplicit(try!(self.parse_ty_sum()), self_ident)
4411 SelfValue(self_ident)
4420 let explicit_self_sp = mk_sp(self_ident_lo, self_ident_hi);
4422 // shared fall-through for the three cases below. borrowing prevents simply
4423 // writing this as a closure
4424 macro_rules! parse_remaining_arguments {
4427 // If we parsed a self type, expect a comma before the argument list.
4431 let sep = seq_sep_trailing_allowed(token::Comma);
4432 let mut fn_inputs = try!(self.parse_seq_to_before_end(
4433 &token::CloseDelim(token::Paren),
4437 fn_inputs.insert(0, Arg::new_self(explicit_self_sp, mutbl_self, $self_id));
4440 token::CloseDelim(token::Paren) => {
4441 vec!(Arg::new_self(explicit_self_sp, mutbl_self, $self_id))
4444 let token_str = self.this_token_to_string();
4445 return Err(self.fatal(&format!("expected `,` or `)`, found `{}`",
4452 let fn_inputs = match explicit_self {
4454 let sep = seq_sep_trailing_allowed(token::Comma);
4455 try!(self.parse_seq_to_before_end(&token::CloseDelim(token::Paren),
4458 SelfValue(id) => parse_remaining_arguments!(id),
4459 SelfRegion(_,_,id) => parse_remaining_arguments!(id),
4460 SelfExplicit(_,id) => parse_remaining_arguments!(id),
4464 try!(self.expect(&token::CloseDelim(token::Paren)));
4466 let hi = self.span.hi;
4468 let ret_ty = try!(self.parse_ret_ty());
4470 let fn_decl = P(FnDecl {
4476 Ok((spanned(lo, hi, explicit_self), fn_decl))
4479 // parse the |arg, arg| header on a lambda
4480 fn parse_fn_block_decl(&mut self) -> PResult<P<FnDecl>> {
4481 let inputs_captures = {
4482 if try!(self.eat(&token::OrOr) ){
4485 try!(self.expect(&token::BinOp(token::Or)));
4486 try!(self.parse_obsolete_closure_kind());
4487 let args = try!(self.parse_seq_to_before_end(
4488 &token::BinOp(token::Or),
4489 seq_sep_trailing_allowed(token::Comma),
4490 |p| p.parse_fn_block_arg()
4496 let output = try!(self.parse_ret_ty());
4499 inputs: inputs_captures,
4505 /// Parse the name and optional generic types of a function header.
4506 fn parse_fn_header(&mut self) -> PResult<(Ident, ast::Generics)> {
4507 let id = try!(self.parse_ident());
4508 let generics = try!(self.parse_generics());
4512 fn mk_item(&mut self, lo: BytePos, hi: BytePos, ident: Ident,
4513 node: Item_, vis: Visibility,
4514 attrs: Vec<Attribute>) -> P<Item> {
4518 id: ast::DUMMY_NODE_ID,
4525 /// Parse an item-position function declaration.
4526 fn parse_item_fn(&mut self,
4528 constness: Constness,
4530 -> PResult<ItemInfo> {
4531 let (ident, mut generics) = try!(self.parse_fn_header());
4532 let decl = try!(self.parse_fn_decl(false));
4533 generics.where_clause = try!(self.parse_where_clause());
4534 let (inner_attrs, body) = try!(self.parse_inner_attrs_and_block());
4535 Ok((ident, ItemFn(decl, unsafety, constness, abi, generics, body), Some(inner_attrs)))
4538 /// true if we are looking at `const ID`, false for things like `const fn` etc
4539 pub fn is_const_item(&mut self) -> bool {
4540 self.token.is_keyword(keywords::Const) &&
4541 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
4542 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
4545 /// parses all the "front matter" for a `fn` declaration, up to
4546 /// and including the `fn` keyword:
4550 /// - `const unsafe fn`
4553 pub fn parse_fn_front_matter(&mut self) -> PResult<(ast::Constness, ast::Unsafety, abi::Abi)> {
4554 let is_const_fn = try!(self.eat_keyword(keywords::Const));
4555 let unsafety = try!(self.parse_unsafety());
4556 let (constness, unsafety, abi) = if is_const_fn {
4557 (Constness::Const, unsafety, abi::Rust)
4559 let abi = if try!(self.eat_keyword(keywords::Extern)) {
4560 try!(self.parse_opt_abi()).unwrap_or(abi::C)
4564 (Constness::NotConst, unsafety, abi)
4566 try!(self.expect_keyword(keywords::Fn));
4567 Ok((constness, unsafety, abi))
4570 /// Parse an impl item.
4571 pub fn parse_impl_item(&mut self) -> PResult<P<ImplItem>> {
4572 maybe_whole!(no_clone self, NtImplItem);
4574 let mut attrs = try!(self.parse_outer_attributes());
4575 let lo = self.span.lo;
4576 let vis = try!(self.parse_visibility());
4577 let (name, node) = if try!(self.eat_keyword(keywords::Type)) {
4578 let name = try!(self.parse_ident());
4579 try!(self.expect(&token::Eq));
4580 let typ = try!(self.parse_ty_sum());
4581 try!(self.expect(&token::Semi));
4582 (name, ast::ImplItemKind::Type(typ))
4583 } else if self.is_const_item() {
4584 try!(self.expect_keyword(keywords::Const));
4585 let name = try!(self.parse_ident());
4586 try!(self.expect(&token::Colon));
4587 let typ = try!(self.parse_ty_sum());
4588 try!(self.expect(&token::Eq));
4589 let expr = try!(self.parse_expr());
4590 try!(self.commit_expr_expecting(&expr, token::Semi));
4591 (name, ast::ImplItemKind::Const(typ, expr))
4593 let (name, inner_attrs, node) = try!(self.parse_impl_method(vis));
4594 attrs.extend(inner_attrs);
4599 id: ast::DUMMY_NODE_ID,
4600 span: mk_sp(lo, self.last_span.hi),
4608 fn complain_if_pub_macro(&mut self, visa: Visibility, span: Span) {
4611 self.span_err(span, "can't qualify macro invocation with `pub`");
4612 self.fileline_help(span, "try adjusting the macro to put `pub` inside \
4619 /// Parse a method or a macro invocation in a trait impl.
4620 fn parse_impl_method(&mut self, vis: Visibility)
4621 -> PResult<(Ident, Vec<ast::Attribute>, ast::ImplItemKind)> {
4622 // code copied from parse_macro_use_or_failure... abstraction!
4623 if !self.token.is_any_keyword()
4624 && self.look_ahead(1, |t| *t == token::Not)
4625 && (self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren))
4626 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) {
4629 let last_span = self.last_span;
4630 self.complain_if_pub_macro(vis, last_span);
4632 let lo = self.span.lo;
4633 let pth = try!(self.parse_path(NoTypesAllowed));
4634 try!(self.expect(&token::Not));
4636 // eat a matched-delimiter token tree:
4637 let delim = try!(self.expect_open_delim());
4638 let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
4640 |p| p.parse_token_tree()));
4641 let m_ = Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT };
4642 let m: ast::Mac = codemap::Spanned { node: m_,
4644 self.last_span.hi) };
4645 if delim != token::Brace {
4646 try!(self.expect(&token::Semi))
4648 Ok((token::special_idents::invalid, vec![], ast::ImplItemKind::Macro(m)))
4650 let (constness, unsafety, abi) = try!(self.parse_fn_front_matter());
4651 let ident = try!(self.parse_ident());
4652 let mut generics = try!(self.parse_generics());
4653 let (explicit_self, decl) = try!(self.parse_fn_decl_with_self(|p| {
4656 generics.where_clause = try!(self.parse_where_clause());
4657 let (inner_attrs, body) = try!(self.parse_inner_attrs_and_block());
4658 Ok((ident, inner_attrs, ast::ImplItemKind::Method(ast::MethodSig {
4661 explicit_self: explicit_self,
4663 constness: constness,
4669 /// Parse trait Foo { ... }
4670 fn parse_item_trait(&mut self, unsafety: Unsafety) -> PResult<ItemInfo> {
4672 let ident = try!(self.parse_ident());
4673 let mut tps = try!(self.parse_generics());
4675 // Parse supertrait bounds.
4676 let bounds = try!(self.parse_colon_then_ty_param_bounds(BoundParsingMode::Bare));
4678 tps.where_clause = try!(self.parse_where_clause());
4680 let meths = try!(self.parse_trait_items());
4681 Ok((ident, ItemTrait(unsafety, tps, bounds, meths), None))
4684 /// Parses items implementations variants
4685 /// impl<T> Foo { ... }
4686 /// impl<T> ToString for &'static T { ... }
4687 /// impl Send for .. {}
4688 fn parse_item_impl(&mut self, unsafety: ast::Unsafety) -> PResult<ItemInfo> {
4689 let impl_span = self.span;
4691 // First, parse type parameters if necessary.
4692 let mut generics = try!(self.parse_generics());
4694 // Special case: if the next identifier that follows is '(', don't
4695 // allow this to be parsed as a trait.
4696 let could_be_trait = self.token != token::OpenDelim(token::Paren);
4698 let neg_span = self.span;
4699 let polarity = if try!(self.eat(&token::Not) ){
4700 ast::ImplPolarity::Negative
4702 ast::ImplPolarity::Positive
4706 let mut ty = try!(self.parse_ty_sum());
4708 // Parse traits, if necessary.
4709 let opt_trait = if could_be_trait && try!(self.eat_keyword(keywords::For) ){
4710 // New-style trait. Reinterpret the type as a trait.
4712 TyPath(None, ref path) => {
4714 path: (*path).clone(),
4719 self.span_err(ty.span, "not a trait");
4725 ast::ImplPolarity::Negative => {
4726 // This is a negated type implementation
4727 // `impl !MyType {}`, which is not allowed.
4728 self.span_err(neg_span, "inherent implementation can't be negated");
4735 if opt_trait.is_some() && try!(self.eat(&token::DotDot) ){
4736 if generics.is_parameterized() {
4737 self.span_err(impl_span, "default trait implementations are not \
4738 allowed to have generics");
4741 try!(self.expect(&token::OpenDelim(token::Brace)));
4742 try!(self.expect(&token::CloseDelim(token::Brace)));
4743 Ok((ast_util::impl_pretty_name(&opt_trait, None),
4744 ItemDefaultImpl(unsafety, opt_trait.unwrap()), None))
4746 if opt_trait.is_some() {
4747 ty = try!(self.parse_ty_sum());
4749 generics.where_clause = try!(self.parse_where_clause());
4751 try!(self.expect(&token::OpenDelim(token::Brace)));
4752 let attrs = try!(self.parse_inner_attributes());
4754 let mut impl_items = vec![];
4755 while !try!(self.eat(&token::CloseDelim(token::Brace))) {
4756 impl_items.push(try!(self.parse_impl_item()));
4759 Ok((ast_util::impl_pretty_name(&opt_trait, Some(&*ty)),
4760 ItemImpl(unsafety, polarity, generics, opt_trait, ty, impl_items),
4765 /// Parse a::B<String,i32>
4766 fn parse_trait_ref(&mut self) -> PResult<TraitRef> {
4768 path: try!(self.parse_path(LifetimeAndTypesWithoutColons)),
4769 ref_id: ast::DUMMY_NODE_ID,
4773 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<Vec<ast::LifetimeDef>> {
4774 if try!(self.eat_keyword(keywords::For) ){
4775 try!(self.expect(&token::Lt));
4776 let lifetime_defs = try!(self.parse_lifetime_defs());
4777 try!(self.expect_gt());
4784 /// Parse for<'l> a::B<String,i32>
4785 fn parse_poly_trait_ref(&mut self) -> PResult<PolyTraitRef> {
4786 let lo = self.span.lo;
4787 let lifetime_defs = try!(self.parse_late_bound_lifetime_defs());
4789 Ok(ast::PolyTraitRef {
4790 bound_lifetimes: lifetime_defs,
4791 trait_ref: try!(self.parse_trait_ref()),
4792 span: mk_sp(lo, self.last_span.hi),
4796 /// Parse struct Foo { ... }
4797 fn parse_item_struct(&mut self) -> PResult<ItemInfo> {
4798 let class_name = try!(self.parse_ident());
4799 let mut generics = try!(self.parse_generics());
4801 // There is a special case worth noting here, as reported in issue #17904.
4802 // If we are parsing a tuple struct it is the case that the where clause
4803 // should follow the field list. Like so:
4805 // struct Foo<T>(T) where T: Copy;
4807 // If we are parsing a normal record-style struct it is the case
4808 // that the where clause comes before the body, and after the generics.
4809 // So if we look ahead and see a brace or a where-clause we begin
4810 // parsing a record style struct.
4812 // Otherwise if we look ahead and see a paren we parse a tuple-style
4815 let vdata = if self.token.is_keyword(keywords::Where) {
4816 generics.where_clause = try!(self.parse_where_clause());
4817 if try!(self.eat(&token::Semi)) {
4818 // If we see a: `struct Foo<T> where T: Copy;` style decl.
4819 VariantData::Unit(ast::DUMMY_NODE_ID)
4821 // If we see: `struct Foo<T> where T: Copy { ... }`
4822 VariantData::Struct(try!(self.parse_record_struct_body(ParsePub::Yes)),
4825 // No `where` so: `struct Foo<T>;`
4826 } else if try!(self.eat(&token::Semi) ){
4827 VariantData::Unit(ast::DUMMY_NODE_ID)
4828 // Record-style struct definition
4829 } else if self.token == token::OpenDelim(token::Brace) {
4830 VariantData::Struct(try!(self.parse_record_struct_body(ParsePub::Yes)),
4832 // Tuple-style struct definition with optional where-clause.
4833 } else if self.token == token::OpenDelim(token::Paren) {
4834 let body = VariantData::Tuple(try!(self.parse_tuple_struct_body(ParsePub::Yes)),
4835 ast::DUMMY_NODE_ID);
4836 generics.where_clause = try!(self.parse_where_clause());
4837 try!(self.expect(&token::Semi));
4840 let token_str = self.this_token_to_string();
4841 return Err(self.fatal(&format!("expected `where`, `{{`, `(`, or `;` after struct \
4842 name, found `{}`", token_str)))
4845 Ok((class_name, ItemStruct(vdata, generics), None))
4848 pub fn parse_record_struct_body(&mut self, parse_pub: ParsePub) -> PResult<Vec<StructField>> {
4849 let mut fields = Vec::new();
4850 if try!(self.eat(&token::OpenDelim(token::Brace)) ){
4851 while self.token != token::CloseDelim(token::Brace) {
4852 fields.push(try!(self.parse_struct_decl_field(parse_pub)));
4857 let token_str = self.this_token_to_string();
4858 return Err(self.fatal(&format!("expected `where`, or `{{` after struct \
4866 pub fn parse_tuple_struct_body(&mut self, parse_pub: ParsePub) -> PResult<Vec<StructField>> {
4867 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
4868 // Unit like structs are handled in parse_item_struct function
4869 let fields = try!(self.parse_unspanned_seq(
4870 &token::OpenDelim(token::Paren),
4871 &token::CloseDelim(token::Paren),
4872 seq_sep_trailing_allowed(token::Comma),
4874 let attrs = try!(p.parse_outer_attributes());
4876 let struct_field_ = ast::StructField_ {
4877 kind: UnnamedField (
4878 if parse_pub == ParsePub::Yes {
4879 try!(p.parse_visibility())
4884 id: ast::DUMMY_NODE_ID,
4885 ty: try!(p.parse_ty_sum()),
4888 Ok(spanned(lo, p.span.hi, struct_field_))
4894 /// Parse a structure field declaration
4895 pub fn parse_single_struct_field(&mut self,
4897 attrs: Vec<Attribute> )
4898 -> PResult<StructField> {
4899 let a_var = try!(self.parse_name_and_ty(vis, attrs));
4904 token::CloseDelim(token::Brace) => {}
4906 let span = self.span;
4907 let token_str = self.this_token_to_string();
4908 return Err(self.span_fatal_help(span,
4909 &format!("expected `,`, or `}}`, found `{}`",
4911 "struct fields should be separated by commas"))
4917 /// Parse an element of a struct definition
4918 fn parse_struct_decl_field(&mut self, parse_pub: ParsePub) -> PResult<StructField> {
4920 let attrs = try!(self.parse_outer_attributes());
4922 if try!(self.eat_keyword(keywords::Pub) ){
4923 if parse_pub == ParsePub::No {
4924 let span = self.last_span;
4925 self.span_err(span, "`pub` is not allowed here");
4927 return self.parse_single_struct_field(Public, attrs);
4930 return self.parse_single_struct_field(Inherited, attrs);
4933 /// Parse visibility: PUB or nothing
4934 fn parse_visibility(&mut self) -> PResult<Visibility> {
4935 if try!(self.eat_keyword(keywords::Pub)) { Ok(Public) }
4936 else { Ok(Inherited) }
4939 /// Given a termination token, parse all of the items in a module
4940 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: BytePos) -> PResult<Mod> {
4941 let mut items = vec![];
4942 while let Some(item) = try!(self.parse_item()) {
4946 if !try!(self.eat(term)) {
4947 let token_str = self.this_token_to_string();
4948 return Err(self.fatal(&format!("expected item, found `{}`", token_str)));
4951 let hi = if self.span == codemap::DUMMY_SP {
4958 inner: mk_sp(inner_lo, hi),
4963 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<ItemInfo> {
4964 let id = try!(self.parse_ident());
4965 try!(self.expect(&token::Colon));
4966 let ty = try!(self.parse_ty_sum());
4967 try!(self.expect(&token::Eq));
4968 let e = try!(self.parse_expr());
4969 try!(self.commit_expr_expecting(&*e, token::Semi));
4970 let item = match m {
4971 Some(m) => ItemStatic(ty, m, e),
4972 None => ItemConst(ty, e),
4974 Ok((id, item, None))
4977 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
4978 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<ItemInfo> {
4979 let id_span = self.span;
4980 let id = try!(self.parse_ident());
4981 if self.check(&token::Semi) {
4983 // This mod is in an external file. Let's go get it!
4984 let (m, attrs) = try!(self.eval_src_mod(id, outer_attrs, id_span));
4985 Ok((id, m, Some(attrs)))
4987 self.push_mod_path(id, outer_attrs);
4988 try!(self.expect(&token::OpenDelim(token::Brace)));
4989 let mod_inner_lo = self.span.lo;
4990 let old_owns_directory = self.owns_directory;
4991 self.owns_directory = true;
4992 let attrs = try!(self.parse_inner_attributes());
4993 let m = try!(self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo));
4994 self.owns_directory = old_owns_directory;
4995 self.pop_mod_path();
4996 Ok((id, ItemMod(m), Some(attrs)))
5000 fn push_mod_path(&mut self, id: Ident, attrs: &[Attribute]) {
5001 let default_path = self.id_to_interned_str(id);
5002 let file_path = match ::attr::first_attr_value_str_by_name(attrs, "path") {
5004 None => default_path,
5006 self.mod_path_stack.push(file_path)
5009 fn pop_mod_path(&mut self) {
5010 self.mod_path_stack.pop().unwrap();
5013 pub fn submod_path_from_attr(attrs: &[ast::Attribute], dir_path: &Path) -> Option<PathBuf> {
5014 ::attr::first_attr_value_str_by_name(attrs, "path").map(|d| dir_path.join(&*d))
5017 /// Returns either a path to a module, or .
5018 pub fn default_submod_path(id: ast::Ident, dir_path: &Path, codemap: &CodeMap) -> ModulePath
5020 let mod_name = id.to_string();
5021 let default_path_str = format!("{}.rs", mod_name);
5022 let secondary_path_str = format!("{}/mod.rs", mod_name);
5023 let default_path = dir_path.join(&default_path_str);
5024 let secondary_path = dir_path.join(&secondary_path_str);
5025 let default_exists = codemap.file_exists(&default_path);
5026 let secondary_exists = codemap.file_exists(&secondary_path);
5028 let result = match (default_exists, secondary_exists) {
5029 (true, false) => Ok(ModulePathSuccess { path: default_path, owns_directory: false }),
5030 (false, true) => Ok(ModulePathSuccess { path: secondary_path, owns_directory: true }),
5031 (false, false) => Err(ModulePathError {
5032 err_msg: format!("file not found for module `{}`", mod_name),
5033 help_msg: format!("name the file either {} or {} inside the directory {:?}",
5036 dir_path.display()),
5038 (true, true) => Err(ModulePathError {
5039 err_msg: format!("file for module `{}` found at both {} and {}",
5042 secondary_path_str),
5043 help_msg: "delete or rename one of them to remove the ambiguity".to_owned(),
5049 path_exists: default_exists || secondary_exists,
5054 fn submod_path(&mut self,
5056 outer_attrs: &[ast::Attribute],
5057 id_sp: Span) -> PResult<ModulePathSuccess> {
5058 let mut prefix = PathBuf::from(&self.sess.codemap().span_to_filename(self.span));
5060 let mut dir_path = prefix;
5061 for part in &self.mod_path_stack {
5062 dir_path.push(&**part);
5065 if let Some(p) = Parser::submod_path_from_attr(outer_attrs, &dir_path) {
5066 return Ok(ModulePathSuccess { path: p, owns_directory: true });
5069 let paths = Parser::default_submod_path(id, &dir_path, self.sess.codemap());
5071 if !self.owns_directory {
5072 self.span_err(id_sp, "cannot declare a new module at this location");
5073 let this_module = match self.mod_path_stack.last() {
5074 Some(name) => name.to_string(),
5075 None => self.root_module_name.as_ref().unwrap().clone(),
5077 self.span_note(id_sp,
5078 &format!("maybe move this module `{0}` to its own directory \
5081 if paths.path_exists {
5082 self.span_note(id_sp,
5083 &format!("... or maybe `use` the module `{}` instead \
5084 of possibly redeclaring it",
5087 self.abort_if_errors();
5090 match paths.result {
5091 Ok(succ) => Ok(succ),
5092 Err(err) => Err(self.span_fatal_help(id_sp, &err.err_msg, &err.help_msg)),
5096 /// Read a module from a source file.
5097 fn eval_src_mod(&mut self,
5099 outer_attrs: &[ast::Attribute],
5101 -> PResult<(ast::Item_, Vec<ast::Attribute> )> {
5102 let ModulePathSuccess { path, owns_directory } = try!(self.submod_path(id,
5106 self.eval_src_mod_from_path(path,
5112 fn eval_src_mod_from_path(&mut self,
5114 owns_directory: bool,
5116 id_sp: Span) -> PResult<(ast::Item_, Vec<ast::Attribute> )> {
5117 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
5118 match included_mod_stack.iter().position(|p| *p == path) {
5120 let mut err = String::from("circular modules: ");
5121 let len = included_mod_stack.len();
5122 for p in &included_mod_stack[i.. len] {
5123 err.push_str(&p.to_string_lossy());
5124 err.push_str(" -> ");
5126 err.push_str(&path.to_string_lossy());
5127 return Err(self.span_fatal(id_sp, &err[..]));
5131 included_mod_stack.push(path.clone());
5132 drop(included_mod_stack);
5134 let mut p0 = new_sub_parser_from_file(self.sess,
5140 let mod_inner_lo = p0.span.lo;
5141 let mod_attrs = try!(p0.parse_inner_attributes());
5142 let m0 = try!(p0.parse_mod_items(&token::Eof, mod_inner_lo));
5143 self.sess.included_mod_stack.borrow_mut().pop();
5144 Ok((ast::ItemMod(m0), mod_attrs))
5147 /// Parse a function declaration from a foreign module
5148 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: BytePos,
5149 attrs: Vec<Attribute>) -> PResult<P<ForeignItem>> {
5150 try!(self.expect_keyword(keywords::Fn));
5152 let (ident, mut generics) = try!(self.parse_fn_header());
5153 let decl = try!(self.parse_fn_decl(true));
5154 generics.where_clause = try!(self.parse_where_clause());
5155 let hi = self.span.hi;
5156 try!(self.expect(&token::Semi));
5157 Ok(P(ast::ForeignItem {
5160 node: ForeignItemFn(decl, generics),
5161 id: ast::DUMMY_NODE_ID,
5162 span: mk_sp(lo, hi),
5167 /// Parse a static item from a foreign module
5168 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: BytePos,
5169 attrs: Vec<Attribute>) -> PResult<P<ForeignItem>> {
5170 try!(self.expect_keyword(keywords::Static));
5171 let mutbl = try!(self.eat_keyword(keywords::Mut));
5173 let ident = try!(self.parse_ident());
5174 try!(self.expect(&token::Colon));
5175 let ty = try!(self.parse_ty_sum());
5176 let hi = self.span.hi;
5177 try!(self.expect(&token::Semi));
5181 node: ForeignItemStatic(ty, mutbl),
5182 id: ast::DUMMY_NODE_ID,
5183 span: mk_sp(lo, hi),
5188 /// Parse extern crate links
5192 /// extern crate foo;
5193 /// extern crate bar as foo;
5194 fn parse_item_extern_crate(&mut self,
5196 visibility: Visibility,
5197 attrs: Vec<Attribute>)
5198 -> PResult<P<Item>> {
5200 let crate_name = try!(self.parse_ident());
5201 let (maybe_path, ident) = if let Some(ident) = try!(self.parse_rename()) {
5202 (Some(crate_name.name), ident)
5206 try!(self.expect(&token::Semi));
5208 let last_span = self.last_span;
5210 if visibility == ast::Public {
5211 self.span_warn(mk_sp(lo, last_span.hi),
5212 "`pub extern crate` does not work as expected and should not be used. \
5213 Likely to become an error. Prefer `extern crate` and `pub use`.");
5219 ItemExternCrate(maybe_path),
5224 /// Parse `extern` for foreign ABIs
5227 /// `extern` is expected to have been
5228 /// consumed before calling this method
5234 fn parse_item_foreign_mod(&mut self,
5236 opt_abi: Option<abi::Abi>,
5237 visibility: Visibility,
5238 mut attrs: Vec<Attribute>)
5239 -> PResult<P<Item>> {
5240 try!(self.expect(&token::OpenDelim(token::Brace)));
5242 let abi = opt_abi.unwrap_or(abi::C);
5244 attrs.extend(try!(self.parse_inner_attributes()));
5246 let mut foreign_items = vec![];
5247 while let Some(item) = try!(self.parse_foreign_item()) {
5248 foreign_items.push(item);
5250 try!(self.expect(&token::CloseDelim(token::Brace)));
5252 let last_span = self.last_span;
5253 let m = ast::ForeignMod {
5255 items: foreign_items
5259 special_idents::invalid,
5265 /// Parse type Foo = Bar;
5266 fn parse_item_type(&mut self) -> PResult<ItemInfo> {
5267 let ident = try!(self.parse_ident());
5268 let mut tps = try!(self.parse_generics());
5269 tps.where_clause = try!(self.parse_where_clause());
5270 try!(self.expect(&token::Eq));
5271 let ty = try!(self.parse_ty_sum());
5272 try!(self.expect(&token::Semi));
5273 Ok((ident, ItemTy(ty, tps), None))
5276 /// Parse the part of an "enum" decl following the '{'
5277 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<EnumDef> {
5278 let mut variants = Vec::new();
5279 let mut all_nullary = true;
5280 let mut any_disr = None;
5281 while self.token != token::CloseDelim(token::Brace) {
5282 let variant_attrs = try!(self.parse_outer_attributes());
5283 let vlo = self.span.lo;
5286 let mut disr_expr = None;
5287 let ident = try!(self.parse_ident());
5288 if self.check(&token::OpenDelim(token::Brace)) {
5289 // Parse a struct variant.
5290 all_nullary = false;
5291 struct_def = VariantData::Struct(try!(self.parse_record_struct_body(ParsePub::No)),
5292 ast::DUMMY_NODE_ID);
5293 } else if self.check(&token::OpenDelim(token::Paren)) {
5294 all_nullary = false;
5295 struct_def = VariantData::Tuple(try!(self.parse_tuple_struct_body(ParsePub::No)),
5296 ast::DUMMY_NODE_ID);
5297 } else if try!(self.eat(&token::Eq) ){
5298 disr_expr = Some(try!(self.parse_expr()));
5299 any_disr = disr_expr.as_ref().map(|expr| expr.span);
5300 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5302 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5305 let vr = ast::Variant_ {
5307 attrs: variant_attrs,
5309 disr_expr: disr_expr,
5311 variants.push(P(spanned(vlo, self.last_span.hi, vr)));
5313 if !try!(self.eat(&token::Comma)) { break; }
5315 try!(self.expect(&token::CloseDelim(token::Brace)));
5317 Some(disr_span) if !all_nullary =>
5318 self.span_err(disr_span,
5319 "discriminator values can only be used with a c-like enum"),
5323 Ok(ast::EnumDef { variants: variants })
5326 /// Parse an "enum" declaration
5327 fn parse_item_enum(&mut self) -> PResult<ItemInfo> {
5328 let id = try!(self.parse_ident());
5329 let mut generics = try!(self.parse_generics());
5330 generics.where_clause = try!(self.parse_where_clause());
5331 try!(self.expect(&token::OpenDelim(token::Brace)));
5333 let enum_definition = try!(self.parse_enum_def(&generics));
5334 Ok((id, ItemEnum(enum_definition, generics), None))
5337 /// Parses a string as an ABI spec on an extern type or module. Consumes
5338 /// the `extern` keyword, if one is found.
5339 fn parse_opt_abi(&mut self) -> PResult<Option<abi::Abi>> {
5341 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
5343 self.expect_no_suffix(sp, "ABI spec", suf);
5345 match abi::lookup(&s.as_str()) {
5346 Some(abi) => Ok(Some(abi)),
5348 let last_span = self.last_span;
5351 &format!("invalid ABI: expected one of [{}], \
5353 abi::all_names().join(", "),
5364 /// Parse one of the items allowed by the flags.
5365 /// NB: this function no longer parses the items inside an
5367 fn parse_item_(&mut self, attrs: Vec<Attribute>,
5368 macros_allowed: bool, attributes_allowed: bool) -> PResult<Option<P<Item>>> {
5369 let nt_item = match self.token {
5370 token::Interpolated(token::NtItem(ref item)) => {
5371 Some((**item).clone())
5378 let mut attrs = attrs;
5379 mem::swap(&mut item.attrs, &mut attrs);
5380 item.attrs.extend(attrs);
5381 return Ok(Some(P(item)));
5386 let lo = self.span.lo;
5388 let visibility = try!(self.parse_visibility());
5390 if try!(self.eat_keyword(keywords::Use) ){
5392 let item_ = ItemUse(try!(self.parse_view_path()));
5393 try!(self.expect(&token::Semi));
5395 let last_span = self.last_span;
5396 let item = self.mk_item(lo,
5398 token::special_idents::invalid,
5402 return Ok(Some(item));
5405 if try!(self.eat_keyword(keywords::Extern)) {
5406 if try!(self.eat_keyword(keywords::Crate)) {
5407 return Ok(Some(try!(self.parse_item_extern_crate(lo, visibility, attrs))));
5410 let opt_abi = try!(self.parse_opt_abi());
5412 if try!(self.eat_keyword(keywords::Fn) ){
5413 // EXTERN FUNCTION ITEM
5414 let abi = opt_abi.unwrap_or(abi::C);
5415 let (ident, item_, extra_attrs) =
5416 try!(self.parse_item_fn(Unsafety::Normal, Constness::NotConst, abi));
5417 let last_span = self.last_span;
5418 let item = self.mk_item(lo,
5423 maybe_append(attrs, extra_attrs));
5424 return Ok(Some(item));
5425 } else if self.check(&token::OpenDelim(token::Brace)) {
5426 return Ok(Some(try!(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs))));
5429 try!(self.expect_one_of(&[], &[]));
5432 if try!(self.eat_keyword(keywords::Static) ){
5434 let m = if try!(self.eat_keyword(keywords::Mut)) {MutMutable} else {MutImmutable};
5435 let (ident, item_, extra_attrs) = try!(self.parse_item_const(Some(m)));
5436 let last_span = self.last_span;
5437 let item = self.mk_item(lo,
5442 maybe_append(attrs, extra_attrs));
5443 return Ok(Some(item));
5445 if try!(self.eat_keyword(keywords::Const) ){
5446 if self.check_keyword(keywords::Fn)
5447 || (self.check_keyword(keywords::Unsafe)
5448 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
5449 // CONST FUNCTION ITEM
5450 let unsafety = if try!(self.eat_keyword(keywords::Unsafe) ){
5456 let (ident, item_, extra_attrs) =
5457 try!(self.parse_item_fn(unsafety, Constness::Const, abi::Rust));
5458 let last_span = self.last_span;
5459 let item = self.mk_item(lo,
5464 maybe_append(attrs, extra_attrs));
5465 return Ok(Some(item));
5469 if try!(self.eat_keyword(keywords::Mut) ){
5470 let last_span = self.last_span;
5471 self.span_err(last_span, "const globals cannot be mutable");
5472 self.fileline_help(last_span, "did you mean to declare a static?");
5474 let (ident, item_, extra_attrs) = try!(self.parse_item_const(None));
5475 let last_span = self.last_span;
5476 let item = self.mk_item(lo,
5481 maybe_append(attrs, extra_attrs));
5482 return Ok(Some(item));
5484 if self.check_keyword(keywords::Unsafe) &&
5485 self.look_ahead(1, |t| t.is_keyword(keywords::Trait))
5487 // UNSAFE TRAIT ITEM
5488 try!(self.expect_keyword(keywords::Unsafe));
5489 try!(self.expect_keyword(keywords::Trait));
5490 let (ident, item_, extra_attrs) =
5491 try!(self.parse_item_trait(ast::Unsafety::Unsafe));
5492 let last_span = self.last_span;
5493 let item = self.mk_item(lo,
5498 maybe_append(attrs, extra_attrs));
5499 return Ok(Some(item));
5501 if self.check_keyword(keywords::Unsafe) &&
5502 self.look_ahead(1, |t| t.is_keyword(keywords::Impl))
5505 try!(self.expect_keyword(keywords::Unsafe));
5506 try!(self.expect_keyword(keywords::Impl));
5507 let (ident, item_, extra_attrs) = try!(self.parse_item_impl(ast::Unsafety::Unsafe));
5508 let last_span = self.last_span;
5509 let item = self.mk_item(lo,
5514 maybe_append(attrs, extra_attrs));
5515 return Ok(Some(item));
5517 if self.check_keyword(keywords::Fn) {
5520 let (ident, item_, extra_attrs) =
5521 try!(self.parse_item_fn(Unsafety::Normal, Constness::NotConst, abi::Rust));
5522 let last_span = self.last_span;
5523 let item = self.mk_item(lo,
5528 maybe_append(attrs, extra_attrs));
5529 return Ok(Some(item));
5531 if self.check_keyword(keywords::Unsafe)
5532 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
5533 // UNSAFE FUNCTION ITEM
5535 let abi = if try!(self.eat_keyword(keywords::Extern) ){
5536 try!(self.parse_opt_abi()).unwrap_or(abi::C)
5540 try!(self.expect_keyword(keywords::Fn));
5541 let (ident, item_, extra_attrs) =
5542 try!(self.parse_item_fn(Unsafety::Unsafe, Constness::NotConst, abi));
5543 let last_span = self.last_span;
5544 let item = self.mk_item(lo,
5549 maybe_append(attrs, extra_attrs));
5550 return Ok(Some(item));
5552 if try!(self.eat_keyword(keywords::Mod) ){
5554 let (ident, item_, extra_attrs) =
5555 try!(self.parse_item_mod(&attrs[..]));
5556 let last_span = self.last_span;
5557 let item = self.mk_item(lo,
5562 maybe_append(attrs, extra_attrs));
5563 return Ok(Some(item));
5565 if try!(self.eat_keyword(keywords::Type) ){
5567 let (ident, item_, extra_attrs) = try!(self.parse_item_type());
5568 let last_span = self.last_span;
5569 let item = self.mk_item(lo,
5574 maybe_append(attrs, extra_attrs));
5575 return Ok(Some(item));
5577 if try!(self.eat_keyword(keywords::Enum) ){
5579 let (ident, item_, extra_attrs) = try!(self.parse_item_enum());
5580 let last_span = self.last_span;
5581 let item = self.mk_item(lo,
5586 maybe_append(attrs, extra_attrs));
5587 return Ok(Some(item));
5589 if try!(self.eat_keyword(keywords::Trait) ){
5591 let (ident, item_, extra_attrs) =
5592 try!(self.parse_item_trait(ast::Unsafety::Normal));
5593 let last_span = self.last_span;
5594 let item = self.mk_item(lo,
5599 maybe_append(attrs, extra_attrs));
5600 return Ok(Some(item));
5602 if try!(self.eat_keyword(keywords::Impl) ){
5604 let (ident, item_, extra_attrs) = try!(self.parse_item_impl(ast::Unsafety::Normal));
5605 let last_span = self.last_span;
5606 let item = self.mk_item(lo,
5611 maybe_append(attrs, extra_attrs));
5612 return Ok(Some(item));
5614 if try!(self.eat_keyword(keywords::Struct) ){
5616 let (ident, item_, extra_attrs) = try!(self.parse_item_struct());
5617 let last_span = self.last_span;
5618 let item = self.mk_item(lo,
5623 maybe_append(attrs, extra_attrs));
5624 return Ok(Some(item));
5626 self.parse_macro_use_or_failure(attrs,macros_allowed,attributes_allowed,lo,visibility)
5629 /// Parse a foreign item.
5630 fn parse_foreign_item(&mut self) -> PResult<Option<P<ForeignItem>>> {
5631 let attrs = try!(self.parse_outer_attributes());
5632 let lo = self.span.lo;
5633 let visibility = try!(self.parse_visibility());
5635 if self.check_keyword(keywords::Static) {
5636 // FOREIGN STATIC ITEM
5637 return Ok(Some(try!(self.parse_item_foreign_static(visibility, lo, attrs))));
5639 if self.check_keyword(keywords::Fn) || self.check_keyword(keywords::Unsafe) {
5640 // FOREIGN FUNCTION ITEM
5641 return Ok(Some(try!(self.parse_item_foreign_fn(visibility, lo, attrs))));
5644 // FIXME #5668: this will occur for a macro invocation:
5645 match try!(self.parse_macro_use_or_failure(attrs, true, false, lo, visibility)) {
5647 return Err(self.span_fatal(item.span, "macros cannot expand to foreign items"));
5653 /// This is the fall-through for parsing items.
5654 fn parse_macro_use_or_failure(
5656 attrs: Vec<Attribute> ,
5657 macros_allowed: bool,
5658 attributes_allowed: bool,
5660 visibility: Visibility
5661 ) -> PResult<Option<P<Item>>> {
5662 if macros_allowed && !self.token.is_any_keyword()
5663 && self.look_ahead(1, |t| *t == token::Not)
5664 && (self.look_ahead(2, |t| t.is_plain_ident())
5665 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren))
5666 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) {
5667 // MACRO INVOCATION ITEM
5669 let last_span = self.last_span;
5670 self.complain_if_pub_macro(visibility, last_span);
5672 let mac_lo = self.span.lo;
5675 let pth = try!(self.parse_path(NoTypesAllowed));
5676 try!(self.expect(&token::Not));
5678 // a 'special' identifier (like what `macro_rules!` uses)
5679 // is optional. We should eventually unify invoc syntax
5681 let id = if self.token.is_plain_ident() {
5682 try!(self.parse_ident())
5684 token::special_idents::invalid // no special identifier
5686 // eat a matched-delimiter token tree:
5687 let delim = try!(self.expect_open_delim());
5688 let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
5690 |p| p.parse_token_tree()));
5691 // single-variant-enum... :
5692 let m = Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT };
5693 let m: ast::Mac = codemap::Spanned { node: m,
5695 self.last_span.hi) };
5697 if delim != token::Brace {
5698 if !try!(self.eat(&token::Semi) ){
5699 let last_span = self.last_span;
5700 self.span_err(last_span,
5701 "macros that expand to items must either \
5702 be surrounded with braces or followed by \
5707 let item_ = ItemMac(m);
5708 let last_span = self.last_span;
5709 let item = self.mk_item(lo,
5715 return Ok(Some(item));
5718 // FAILURE TO PARSE ITEM
5722 let last_span = self.last_span;
5723 return Err(self.span_fatal(last_span, "unmatched visibility `pub`"));
5727 if !attributes_allowed && !attrs.is_empty() {
5728 self.expected_item_err(&attrs);
5733 pub fn parse_item(&mut self) -> PResult<Option<P<Item>>> {
5734 let attrs = try!(self.parse_outer_attributes());
5735 self.parse_item_(attrs, true, false)
5739 /// Matches view_path : MOD? non_global_path as IDENT
5740 /// | MOD? non_global_path MOD_SEP LBRACE RBRACE
5741 /// | MOD? non_global_path MOD_SEP LBRACE ident_seq RBRACE
5742 /// | MOD? non_global_path MOD_SEP STAR
5743 /// | MOD? non_global_path
5744 fn parse_view_path(&mut self) -> PResult<P<ViewPath>> {
5745 let lo = self.span.lo;
5747 // Allow a leading :: because the paths are absolute either way.
5748 // This occurs with "use $crate::..." in macros.
5749 try!(self.eat(&token::ModSep));
5751 if self.check(&token::OpenDelim(token::Brace)) {
5753 let idents = try!(self.parse_unspanned_seq(
5754 &token::OpenDelim(token::Brace),
5755 &token::CloseDelim(token::Brace),
5756 seq_sep_trailing_allowed(token::Comma),
5757 |p| p.parse_path_list_item()));
5758 let path = ast::Path {
5759 span: mk_sp(lo, self.span.hi),
5761 segments: Vec::new()
5763 return Ok(P(spanned(lo, self.span.hi, ViewPathList(path, idents))));
5766 let first_ident = try!(self.parse_ident());
5767 let mut path = vec!(first_ident);
5768 if let token::ModSep = self.token {
5769 // foo::bar or foo::{a,b,c} or foo::*
5770 while self.check(&token::ModSep) {
5774 token::Ident(..) => {
5775 let ident = try!(self.parse_ident());
5779 // foo::bar::{a,b,c}
5780 token::OpenDelim(token::Brace) => {
5781 let idents = try!(self.parse_unspanned_seq(
5782 &token::OpenDelim(token::Brace),
5783 &token::CloseDelim(token::Brace),
5784 seq_sep_trailing_allowed(token::Comma),
5785 |p| p.parse_path_list_item()
5787 let path = ast::Path {
5788 span: mk_sp(lo, self.span.hi),
5790 segments: path.into_iter().map(|identifier| {
5792 identifier: identifier,
5793 parameters: ast::PathParameters::none(),
5797 return Ok(P(spanned(lo, self.span.hi, ViewPathList(path, idents))));
5801 token::BinOp(token::Star) => {
5803 let path = ast::Path {
5804 span: mk_sp(lo, self.span.hi),
5806 segments: path.into_iter().map(|identifier| {
5808 identifier: identifier,
5809 parameters: ast::PathParameters::none(),
5813 return Ok(P(spanned(lo, self.span.hi, ViewPathGlob(path))));
5816 // fall-through for case foo::bar::;
5818 self.span_err(self.span, "expected identifier or `{` or `*`, found `;`");
5825 let mut rename_to = path[path.len() - 1];
5826 let path = ast::Path {
5827 span: mk_sp(lo, self.last_span.hi),
5829 segments: path.into_iter().map(|identifier| {
5831 identifier: identifier,
5832 parameters: ast::PathParameters::none(),
5836 rename_to = try!(self.parse_rename()).unwrap_or(rename_to);
5837 Ok(P(spanned(lo, self.last_span.hi, ViewPathSimple(rename_to, path))))
5840 fn parse_rename(&mut self) -> PResult<Option<Ident>> {
5841 if try!(self.eat_keyword(keywords::As)) {
5842 self.parse_ident().map(Some)
5848 /// Parses a source module as a crate. This is the main
5849 /// entry point for the parser.
5850 pub fn parse_crate_mod(&mut self) -> PResult<Crate> {
5851 let lo = self.span.lo;
5853 attrs: try!(self.parse_inner_attributes()),
5854 module: try!(self.parse_mod_items(&token::Eof, lo)),
5855 config: self.cfg.clone(),
5856 span: mk_sp(lo, self.span.lo),
5857 exported_macros: Vec::new(),
5861 pub fn parse_optional_str(&mut self)
5862 -> PResult<Option<(InternedString,
5864 Option<ast::Name>)>> {
5865 let ret = match self.token {
5866 token::Literal(token::Str_(s), suf) => {
5867 (self.id_to_interned_str(ast::Ident::with_empty_ctxt(s)), ast::CookedStr, suf)
5869 token::Literal(token::StrRaw(s, n), suf) => {
5870 (self.id_to_interned_str(ast::Ident::with_empty_ctxt(s)), ast::RawStr(n), suf)
5872 _ => return Ok(None)
5878 pub fn parse_str(&mut self) -> PResult<(InternedString, StrStyle)> {
5879 match try!(self.parse_optional_str()) {
5880 Some((s, style, suf)) => {
5881 let sp = self.last_span;
5882 self.expect_no_suffix(sp, "string literal", suf);
5885 _ => Err(self.fatal("expected string literal"))