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, BindingMode};
18 use ast::{BiBitAnd, BiBitOr, BiBitXor, BiRem, BiLt, Block};
19 use ast::{BlockCheckMode, CaptureByRef, CaptureByValue, CaptureClause};
20 use ast::{Constness, ConstTraitItem, Crate, CrateConfig};
21 use ast::{Decl, DeclItem, DeclLocal, DefaultBlock, DefaultReturn};
22 use ast::{UnDeref, BiDiv, EMPTY_CTXT, EnumDef, ExplicitSelf};
23 use ast::{Expr, Expr_, ExprAddrOf, ExprMatch, ExprAgain};
24 use ast::{ExprAssign, ExprAssignOp, ExprBinary, ExprBlock, ExprBox};
25 use ast::{ExprBreak, ExprCall, ExprCast, ExprInPlace};
26 use ast::{ExprField, ExprTupField, ExprClosure, ExprIf, ExprIfLet, ExprIndex};
27 use ast::{ExprLit, ExprLoop, ExprMac, ExprRange};
28 use ast::{ExprMethodCall, ExprParen, ExprPath};
29 use ast::{ExprRepeat, ExprRet, ExprStruct, ExprTup, ExprType, ExprUnary};
30 use ast::{ExprVec, ExprWhile, ExprWhileLet, ExprForLoop, Field, FnDecl};
31 use ast::{ForeignItem, ForeignItemStatic, ForeignItemFn, FunctionRetTy};
32 use ast::{Ident, Inherited, ImplItem, Item, Item_, ItemStatic};
33 use ast::{ItemEnum, ItemFn, ItemForeignMod, ItemImpl, ItemConst};
34 use ast::{ItemMac, ItemMod, ItemStruct, ItemTrait, ItemTy, ItemDefaultImpl};
35 use ast::{ItemExternCrate, ItemUse};
37 use ast::{LitBool, LitChar, LitByte, LitByteStr};
38 use ast::{LitStr, LitInt, Local};
39 use ast::{MacStmtWithBraces, MacStmtWithSemicolon, MacStmtWithoutBraces};
40 use ast::{MutImmutable, MutMutable, Mac_};
41 use ast::{MutTy, BiMul, Mutability};
42 use ast::{NamedField, UnNeg, NoReturn, UnNot};
43 use ast::{Pat, PatBox, PatEnum, PatIdent, PatLit, PatQPath, PatMac, PatRange};
44 use ast::{PatRegion, PatStruct, PatTup, PatVec, PatWild};
45 use ast::{PolyTraitRef, QSelf};
46 use ast::{Return, BiShl, BiShr, Stmt, StmtDecl};
47 use ast::{StmtExpr, StmtSemi, StmtMac, VariantData, StructField};
48 use ast::{BiSub, StrStyle};
49 use ast::{SelfExplicit, SelfRegion, SelfStatic, SelfValue};
50 use ast::{Delimited, SequenceRepetition, TokenTree, TraitItem, TraitRef};
51 use ast::{Ty, Ty_, TypeBinding, TyMac};
52 use ast::{TyFixedLengthVec, TyBareFn, TyTypeof, TyInfer};
53 use ast::{TyParam, TyParamBounds, TyParen, TyPath, TyPtr};
54 use ast::{TyRptr, TyTup, TyU32, TyVec};
55 use ast::TypeTraitItem;
56 use ast::{UnnamedField, UnsafeBlock};
57 use ast::{ViewPath, ViewPathGlob, ViewPathList, ViewPathSimple};
58 use ast::{Visibility, WhereClause};
59 use attr::{ThinAttributes, ThinAttributesExt, AttributesExt};
61 use ast_util::{self, ident_to_path};
62 use codemap::{self, Span, BytePos, Spanned, spanned, mk_sp, CodeMap};
63 use errors::{self, DiagnosticBuilder};
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, intern, 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(($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(($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(($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(($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(($p).bump_and_get())
229 if let Some(token::Interpolated(token::$constructor(x))) = found {
230 return Ok((Vec::new(), x));
236 /// Uses $parse_expr to parse an expression and returns the span of the interpolated
237 /// token or the span of the parsed expression, if it was not interpolated
238 macro_rules! interpolated_or_expr_span {
239 ($p:expr, $parse_expr:expr) => {
241 let is_interpolated = $p.token.is_interpolated();
252 fn maybe_append(mut lhs: Vec<Attribute>, rhs: Option<Vec<Attribute>>)
254 if let Some(ref attrs) = rhs {
255 lhs.extend(attrs.iter().cloned())
260 /* ident is handled by common.rs */
262 pub struct Parser<'a> {
263 pub sess: &'a ParseSess,
264 /// the current token:
265 pub token: token::Token,
266 /// the span of the current token:
268 /// the span of the prior token:
270 pub cfg: CrateConfig,
271 /// the previous token or None (only stashed sometimes).
272 pub last_token: Option<Box<token::Token>>,
273 pub buffer: [TokenAndSpan; 4],
274 pub buffer_start: isize,
275 pub buffer_end: isize,
276 pub tokens_consumed: usize,
277 pub restrictions: Restrictions,
278 pub quote_depth: usize, // not (yet) related to the quasiquoter
279 pub reader: Box<Reader+'a>,
280 pub interner: Rc<token::IdentInterner>,
281 /// The set of seen errors about obsolete syntax. Used to suppress
282 /// extra detail when the same error is seen twice
283 pub obsolete_set: HashSet<ObsoleteSyntax>,
284 /// Used to determine the path to externally loaded source files
285 pub mod_path_stack: Vec<InternedString>,
286 /// Stack of spans of open delimiters. Used for error message.
287 pub open_braces: Vec<Span>,
288 /// Flag if this parser "owns" the directory that it is currently parsing
289 /// in. This will affect how nested files are looked up.
290 pub owns_directory: bool,
291 /// Name of the root module this parser originated from. If `None`, then the
292 /// name is not known. This does not change while the parser is descending
293 /// into modules, and sub-parsers have new values for this name.
294 pub root_module_name: Option<String>,
295 pub expected_tokens: Vec<TokenType>,
298 #[derive(PartialEq, Eq, Clone)]
301 Keyword(keywords::Keyword),
306 fn to_string(&self) -> String {
308 TokenType::Token(ref t) => format!("`{}`", Parser::token_to_string(t)),
309 TokenType::Operator => "an operator".to_string(),
310 TokenType::Keyword(kw) => format!("`{}`", kw.to_name()),
315 fn is_plain_ident_or_underscore(t: &token::Token) -> bool {
316 t.is_plain_ident() || *t == token::Underscore
319 /// Information about the path to a module.
320 pub struct ModulePath {
322 pub path_exists: bool,
323 pub result: Result<ModulePathSuccess, ModulePathError>,
326 pub struct ModulePathSuccess {
327 pub path: ::std::path::PathBuf,
328 pub owns_directory: bool,
331 pub struct ModulePathError {
333 pub help_msg: String,
338 AttributesParsed(ThinAttributes),
339 AlreadyParsed(P<Expr>),
342 impl From<Option<ThinAttributes>> for LhsExpr {
343 fn from(o: Option<ThinAttributes>) -> Self {
344 if let Some(attrs) = o {
345 LhsExpr::AttributesParsed(attrs)
347 LhsExpr::NotYetParsed
352 impl From<P<Expr>> for LhsExpr {
353 fn from(expr: P<Expr>) -> Self {
354 LhsExpr::AlreadyParsed(expr)
358 impl<'a> Parser<'a> {
359 pub fn new(sess: &'a ParseSess,
360 cfg: ast::CrateConfig,
361 mut rdr: Box<Reader+'a>)
364 let tok0 = rdr.real_token();
366 let placeholder = TokenAndSpan {
367 tok: token::Underscore,
373 interner: token::get_ident_interner(),
389 restrictions: Restrictions::empty(),
391 obsolete_set: HashSet::new(),
392 mod_path_stack: Vec::new(),
393 open_braces: Vec::new(),
394 owns_directory: true,
395 root_module_name: None,
396 expected_tokens: Vec::new(),
400 /// Convert a token to a string using self's reader
401 pub fn token_to_string(token: &token::Token) -> String {
402 pprust::token_to_string(token)
405 /// Convert the current token to a string using self's reader
406 pub fn this_token_to_string(&self) -> String {
407 Parser::token_to_string(&self.token)
410 pub fn unexpected_last<T>(&self, t: &token::Token) -> PResult<'a, T> {
411 let token_str = Parser::token_to_string(t);
412 let last_span = self.last_span;
413 Err(self.span_fatal(last_span, &format!("unexpected token: `{}`", token_str)))
416 pub fn unexpected<T>(&mut self) -> PResult<'a, T> {
417 match self.expect_one_of(&[], &[]) {
419 Ok(_) => unreachable!(),
423 /// Expect and consume the token t. Signal an error if
424 /// the next token is not t.
425 pub fn expect(&mut self, t: &token::Token) -> PResult<'a, ()> {
426 if self.expected_tokens.is_empty() {
427 if self.token == *t {
431 let token_str = Parser::token_to_string(t);
432 let this_token_str = self.this_token_to_string();
433 Err(self.fatal(&format!("expected `{}`, found `{}`",
438 self.expect_one_of(unsafe { slice::from_raw_parts(t, 1) }, &[])
442 /// Expect next token to be edible or inedible token. If edible,
443 /// then consume it; if inedible, then return without consuming
444 /// anything. Signal a fatal error if next token is unexpected.
445 pub fn expect_one_of(&mut self,
446 edible: &[token::Token],
447 inedible: &[token::Token]) -> PResult<'a, ()>{
448 fn tokens_to_string(tokens: &[TokenType]) -> String {
449 let mut i = tokens.iter();
450 // This might be a sign we need a connect method on Iterator.
452 .map_or("".to_string(), |t| t.to_string());
453 i.enumerate().fold(b, |mut b, (i, ref a)| {
454 if tokens.len() > 2 && i == tokens.len() - 2 {
456 } else if tokens.len() == 2 && i == tokens.len() - 2 {
461 b.push_str(&*a.to_string());
465 if edible.contains(&self.token) {
468 } else if inedible.contains(&self.token) {
469 // leave it in the input
472 let mut expected = edible.iter()
473 .map(|x| TokenType::Token(x.clone()))
474 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
475 .chain(self.expected_tokens.iter().cloned())
476 .collect::<Vec<_>>();
477 expected.sort_by(|a, b| a.to_string().cmp(&b.to_string()));
479 let expect = tokens_to_string(&expected[..]);
480 let actual = self.this_token_to_string();
482 &(if expected.len() > 1 {
483 (format!("expected one of {}, found `{}`",
486 } else if expected.is_empty() {
487 (format!("unexpected token: `{}`",
490 (format!("expected {}, found `{}`",
498 /// Check for erroneous `ident { }`; if matches, signal error and
499 /// recover (without consuming any expected input token). Returns
500 /// true if and only if input was consumed for recovery.
501 pub fn check_for_erroneous_unit_struct_expecting(&mut self,
502 expected: &[token::Token])
504 if self.token == token::OpenDelim(token::Brace)
505 && expected.iter().all(|t| *t != token::OpenDelim(token::Brace))
506 && self.look_ahead(1, |t| *t == token::CloseDelim(token::Brace)) {
507 // matched; signal non-fatal error and recover.
508 let span = self.span;
509 self.span_err(span, "unit-like struct construction is written with no trailing `{ }`");
510 self.eat(&token::OpenDelim(token::Brace));
511 self.eat(&token::CloseDelim(token::Brace));
518 /// Commit to parsing a complete expression `e` expected to be
519 /// followed by some token from the set edible + inedible. Recover
520 /// from anticipated input errors, discarding erroneous characters.
521 pub fn commit_expr(&mut self, e: &Expr, edible: &[token::Token],
522 inedible: &[token::Token]) -> PResult<'a, ()> {
523 debug!("commit_expr {:?}", e);
524 if let ExprPath(..) = e.node {
525 // might be unit-struct construction; check for recoverableinput error.
526 let expected = edible.iter()
528 .chain(inedible.iter().cloned())
529 .collect::<Vec<_>>();
530 self.check_for_erroneous_unit_struct_expecting(&expected[..]);
532 self.expect_one_of(edible, inedible)
535 pub fn commit_expr_expecting(&mut self, e: &Expr, edible: token::Token) -> PResult<'a, ()> {
536 self.commit_expr(e, &[edible], &[])
539 /// Commit to parsing a complete statement `s`, which expects to be
540 /// followed by some token from the set edible + inedible. Check
541 /// for recoverable input errors, discarding erroneous characters.
542 pub fn commit_stmt(&mut self, edible: &[token::Token],
543 inedible: &[token::Token]) -> PResult<'a, ()> {
546 .map_or(false, |t| t.is_ident() || t.is_path()) {
547 let expected = edible.iter()
549 .chain(inedible.iter().cloned())
550 .collect::<Vec<_>>();
551 self.check_for_erroneous_unit_struct_expecting(&expected);
553 self.expect_one_of(edible, inedible)
556 pub fn commit_stmt_expecting(&mut self, edible: token::Token) -> PResult<'a, ()> {
557 self.commit_stmt(&[edible], &[])
560 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
561 self.check_strict_keywords();
562 self.check_reserved_keywords();
564 token::Ident(i, _) => {
568 token::Interpolated(token::NtIdent(..)) => {
569 self.bug("ident interpolation not converted to real token");
572 let token_str = self.this_token_to_string();
573 Err(self.fatal(&format!("expected ident, found `{}`",
579 pub fn parse_ident_or_self_type(&mut self) -> PResult<'a, ast::Ident> {
580 if self.is_self_type_ident() {
581 self.expect_self_type_ident()
587 pub fn parse_path_list_item(&mut self) -> PResult<'a, ast::PathListItem> {
588 let lo = self.span.lo;
589 let node = if self.eat_keyword(keywords::SelfValue) {
590 let rename = try!(self.parse_rename());
591 ast::PathListMod { id: ast::DUMMY_NODE_ID, rename: rename }
593 let ident = try!(self.parse_ident());
594 let rename = try!(self.parse_rename());
595 ast::PathListIdent { name: ident, rename: rename, id: ast::DUMMY_NODE_ID }
597 let hi = self.last_span.hi;
598 Ok(spanned(lo, hi, node))
601 /// Check if the next token is `tok`, and return `true` if so.
603 /// This method is will automatically add `tok` to `expected_tokens` if `tok` is not
605 pub fn check(&mut self, tok: &token::Token) -> bool {
606 let is_present = self.token == *tok;
607 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
611 /// Consume token 'tok' if it exists. Returns true if the given
612 /// token was present, false otherwise.
613 pub fn eat(&mut self, tok: &token::Token) -> bool {
614 let is_present = self.check(tok);
615 if is_present { self.bump() }
619 pub fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
620 self.expected_tokens.push(TokenType::Keyword(kw));
621 self.token.is_keyword(kw)
624 /// If the next token is the given keyword, eat it and return
625 /// true. Otherwise, return false.
626 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
627 if self.check_keyword(kw) {
635 pub fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
636 if self.token.is_keyword(kw) {
644 /// If the given word is not a keyword, signal an error.
645 /// If the next token is not the given word, signal an error.
646 /// Otherwise, eat it.
647 pub fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> {
648 if !self.eat_keyword(kw) {
655 /// Signal an error if the given string is a strict keyword
656 pub fn check_strict_keywords(&mut self) {
657 if self.token.is_strict_keyword() {
658 let token_str = self.this_token_to_string();
659 let span = self.span;
661 &format!("expected identifier, found keyword `{}`",
666 /// Signal an error if the current token is a reserved keyword
667 pub fn check_reserved_keywords(&mut self) {
668 if self.token.is_reserved_keyword() {
669 let token_str = self.this_token_to_string();
670 self.fatal(&format!("`{}` is a reserved keyword", token_str)).emit()
674 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
675 /// `&` and continue. If an `&` is not seen, signal an error.
676 fn expect_and(&mut self) -> PResult<'a, ()> {
677 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
679 token::BinOp(token::And) => {
684 let span = self.span;
685 let lo = span.lo + BytePos(1);
686 Ok(self.replace_token(token::BinOp(token::And), lo, span.hi))
688 _ => self.unexpected()
692 pub fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
694 None => {/* everything ok */}
696 let text = suf.as_str();
698 self.span_bug(sp, "found empty literal suffix in Some")
700 self.span_err(sp, &*format!("{} with a suffix is invalid", kind));
706 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
707 /// `<` and continue. If a `<` is not seen, return false.
709 /// This is meant to be used when parsing generics on a path to get the
711 fn eat_lt(&mut self) -> bool {
712 self.expected_tokens.push(TokenType::Token(token::Lt));
718 token::BinOp(token::Shl) => {
719 let span = self.span;
720 let lo = span.lo + BytePos(1);
721 self.replace_token(token::Lt, lo, span.hi);
728 fn expect_lt(&mut self) -> PResult<'a, ()> {
736 /// Expect and consume a GT. if a >> is seen, replace it
737 /// with a single > and continue. If a GT is not seen,
739 pub fn expect_gt(&mut self) -> PResult<'a, ()> {
740 self.expected_tokens.push(TokenType::Token(token::Gt));
746 token::BinOp(token::Shr) => {
747 let span = self.span;
748 let lo = span.lo + BytePos(1);
749 Ok(self.replace_token(token::Gt, lo, span.hi))
751 token::BinOpEq(token::Shr) => {
752 let span = self.span;
753 let lo = span.lo + BytePos(1);
754 Ok(self.replace_token(token::Ge, lo, span.hi))
757 let span = self.span;
758 let lo = span.lo + BytePos(1);
759 Ok(self.replace_token(token::Eq, lo, span.hi))
762 let gt_str = Parser::token_to_string(&token::Gt);
763 let this_token_str = self.this_token_to_string();
764 Err(self.fatal(&format!("expected `{}`, found `{}`",
771 pub fn parse_seq_to_before_gt_or_return<T, F>(&mut self,
772 sep: Option<token::Token>,
774 -> PResult<'a, (P<[T]>, bool)>
775 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
777 let mut v = Vec::new();
778 // This loop works by alternating back and forth between parsing types
779 // and commas. For example, given a string `A, B,>`, the parser would
780 // first parse `A`, then a comma, then `B`, then a comma. After that it
781 // would encounter a `>` and stop. This lets the parser handle trailing
782 // commas in generic parameters, because it can stop either after
783 // parsing a type or after parsing a comma.
785 if self.check(&token::Gt)
786 || self.token == token::BinOp(token::Shr)
787 || self.token == token::Ge
788 || self.token == token::BinOpEq(token::Shr) {
793 match try!(f(self)) {
794 Some(result) => v.push(result),
795 None => return Ok((P::from_vec(v), true))
798 if let Some(t) = sep.as_ref() {
799 try!(self.expect(t));
804 return Ok((P::from_vec(v), false));
807 /// Parse a sequence bracketed by '<' and '>', stopping
809 pub fn parse_seq_to_before_gt<T, F>(&mut self,
810 sep: Option<token::Token>,
812 -> PResult<'a, P<[T]>> where
813 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
815 let (result, returned) = try!(self.parse_seq_to_before_gt_or_return(sep,
816 |p| Ok(Some(try!(f(p))))));
821 pub fn parse_seq_to_gt<T, F>(&mut self,
822 sep: Option<token::Token>,
824 -> PResult<'a, P<[T]>> where
825 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
827 let v = try!(self.parse_seq_to_before_gt(sep, f));
828 try!(self.expect_gt());
832 pub fn parse_seq_to_gt_or_return<T, F>(&mut self,
833 sep: Option<token::Token>,
835 -> PResult<'a, (P<[T]>, bool)> where
836 F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
838 let (v, returned) = try!(self.parse_seq_to_before_gt_or_return(sep, f));
840 try!(self.expect_gt());
842 return Ok((v, returned));
845 /// Parse a sequence, including the closing delimiter. The function
846 /// f must consume tokens until reaching the next separator or
848 pub fn parse_seq_to_end<T, F>(&mut self,
852 -> PResult<'a, Vec<T>> where
853 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
855 let val = try!(self.parse_seq_to_before_end(ket, sep, f));
860 /// Parse a sequence, not including the closing delimiter. The function
861 /// f must consume tokens until reaching the next separator or
863 pub fn parse_seq_to_before_end<T, F>(&mut self,
867 -> PResult<'a, Vec<T>> where
868 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
870 let mut first: bool = true;
872 while self.token != *ket {
875 if first { first = false; }
876 else { try!(self.expect(t)); }
880 if sep.trailing_sep_allowed && self.check(ket) { break; }
881 v.push(try!(f(self)));
886 /// Parse a sequence, including the closing delimiter. The function
887 /// f must consume tokens until reaching the next separator or
889 pub fn parse_unspanned_seq<T, F>(&mut self,
894 -> PResult<'a, Vec<T>> where
895 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
897 try!(self.expect(bra));
898 let result = try!(self.parse_seq_to_before_end(ket, sep, f));
903 /// Parse a sequence parameter of enum variant. For consistency purposes,
904 /// these should not be empty.
905 pub fn parse_enum_variant_seq<T, F>(&mut self,
910 -> PResult<'a, Vec<T>> where
911 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
913 let result = try!(self.parse_unspanned_seq(bra, ket, sep, f));
914 if result.is_empty() {
915 let last_span = self.last_span;
916 self.span_err(last_span,
917 "nullary enum variants are written with no trailing `( )`");
922 // NB: Do not use this function unless you actually plan to place the
923 // spanned list in the AST.
924 pub fn parse_seq<T, F>(&mut self,
929 -> PResult<'a, Spanned<Vec<T>>> where
930 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
932 let lo = self.span.lo;
933 try!(self.expect(bra));
934 let result = try!(self.parse_seq_to_before_end(ket, sep, f));
935 let hi = self.span.hi;
937 Ok(spanned(lo, hi, result))
940 /// Advance the parser by one token
941 pub fn bump(&mut self) {
942 self.last_span = self.span;
943 // Stash token for error recovery (sometimes; clone is not necessarily cheap).
944 self.last_token = if self.token.is_ident() ||
945 self.token.is_path() ||
946 self.token.is_interpolated() ||
947 self.token == token::Comma {
948 Some(Box::new(self.token.clone()))
952 let next = if self.buffer_start == self.buffer_end {
953 self.reader.real_token()
955 // Avoid token copies with `replace`.
956 let buffer_start = self.buffer_start as usize;
957 let next_index = (buffer_start + 1) & 3;
958 self.buffer_start = next_index as isize;
960 let placeholder = TokenAndSpan {
961 tok: token::Underscore,
964 mem::replace(&mut self.buffer[buffer_start], placeholder)
967 self.token = next.tok;
968 self.tokens_consumed += 1;
969 self.expected_tokens.clear();
970 // check after each token
971 self.check_unknown_macro_variable();
974 /// Advance the parser by one token and return the bumped token.
975 pub fn bump_and_get(&mut self) -> token::Token {
976 let old_token = mem::replace(&mut self.token, token::Underscore);
981 /// EFFECT: replace the current token and span with the given one
982 pub fn replace_token(&mut self,
986 self.last_span = mk_sp(self.span.lo, lo);
988 self.span = mk_sp(lo, hi);
990 pub fn buffer_length(&mut self) -> isize {
991 if self.buffer_start <= self.buffer_end {
992 return self.buffer_end - self.buffer_start;
994 return (4 - self.buffer_start) + self.buffer_end;
996 pub fn look_ahead<R, F>(&mut self, distance: usize, f: F) -> R where
997 F: FnOnce(&token::Token) -> R,
999 let dist = distance as isize;
1000 while self.buffer_length() < dist {
1001 self.buffer[self.buffer_end as usize] = self.reader.real_token();
1002 self.buffer_end = (self.buffer_end + 1) & 3;
1004 f(&self.buffer[((self.buffer_start + dist - 1) & 3) as usize].tok)
1006 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
1007 self.sess.span_diagnostic.struct_span_fatal(self.span, m)
1009 pub fn span_fatal(&self, sp: Span, m: &str) -> DiagnosticBuilder<'a> {
1010 self.sess.span_diagnostic.struct_span_fatal(sp, m)
1012 pub fn span_fatal_help(&self, sp: Span, m: &str, help: &str) -> DiagnosticBuilder<'a> {
1013 let mut err = self.sess.span_diagnostic.struct_span_fatal(sp, m);
1014 err.fileline_help(sp, help);
1017 pub fn bug(&self, m: &str) -> ! {
1018 self.sess.span_diagnostic.span_bug(self.span, m)
1020 pub fn warn(&self, m: &str) {
1021 self.sess.span_diagnostic.span_warn(self.span, m)
1023 pub fn span_warn(&self, sp: Span, m: &str) {
1024 self.sess.span_diagnostic.span_warn(sp, m)
1026 pub fn span_err(&self, sp: Span, m: &str) {
1027 self.sess.span_diagnostic.span_err(sp, m)
1029 pub fn span_bug(&self, sp: Span, m: &str) -> ! {
1030 self.sess.span_diagnostic.span_bug(sp, m)
1032 pub fn abort_if_errors(&self) {
1033 self.sess.span_diagnostic.abort_if_errors();
1036 pub fn diagnostic(&self) -> &'a errors::Handler {
1037 &self.sess.span_diagnostic
1040 pub fn id_to_interned_str(&mut self, id: Ident) -> InternedString {
1044 /// Is the current token one of the keywords that signals a bare function
1046 pub fn token_is_bare_fn_keyword(&mut self) -> bool {
1047 self.check_keyword(keywords::Fn) ||
1048 self.check_keyword(keywords::Unsafe) ||
1049 self.check_keyword(keywords::Extern)
1052 pub fn get_lifetime(&mut self) -> ast::Ident {
1054 token::Lifetime(ref ident) => *ident,
1055 _ => self.bug("not a lifetime"),
1059 pub fn parse_for_in_type(&mut self) -> PResult<'a, Ty_> {
1061 Parses whatever can come after a `for` keyword in a type.
1062 The `for` has already been consumed.
1066 - for <'lt> |S| -> T
1070 - for <'lt> [unsafe] [extern "ABI"] fn (S) -> T
1071 - for <'lt> path::foo(a, b)
1076 let lo = self.span.lo;
1078 let lifetime_defs = try!(self.parse_late_bound_lifetime_defs());
1080 // examine next token to decide to do
1081 if self.token_is_bare_fn_keyword() {
1082 self.parse_ty_bare_fn(lifetime_defs)
1084 let hi = self.span.hi;
1085 let trait_ref = try!(self.parse_trait_ref());
1086 let poly_trait_ref = ast::PolyTraitRef { bound_lifetimes: lifetime_defs,
1087 trait_ref: trait_ref,
1088 span: mk_sp(lo, hi)};
1089 let other_bounds = if self.eat(&token::BinOp(token::Plus)) {
1090 try!(self.parse_ty_param_bounds(BoundParsingMode::Bare))
1095 Some(TraitTyParamBound(poly_trait_ref, TraitBoundModifier::None)).into_iter()
1096 .chain(other_bounds.into_vec())
1098 Ok(ast::TyPolyTraitRef(all_bounds))
1102 pub fn parse_ty_path(&mut self) -> PResult<'a, Ty_> {
1103 Ok(TyPath(None, try!(self.parse_path(LifetimeAndTypesWithoutColons))))
1106 /// parse a TyBareFn type:
1107 pub fn parse_ty_bare_fn(&mut self, lifetime_defs: Vec<ast::LifetimeDef>) -> PResult<'a, Ty_> {
1110 [unsafe] [extern "ABI"] fn <'lt> (S) -> T
1111 ^~~~^ ^~~~^ ^~~~^ ^~^ ^
1114 | | | Argument types
1120 let unsafety = try!(self.parse_unsafety());
1121 let abi = if self.eat_keyword(keywords::Extern) {
1122 try!(self.parse_opt_abi()).unwrap_or(abi::C)
1127 try!(self.expect_keyword(keywords::Fn));
1128 let (inputs, variadic) = try!(self.parse_fn_args(false, true));
1129 let ret_ty = try!(self.parse_ret_ty());
1130 let decl = P(FnDecl {
1135 Ok(TyBareFn(P(BareFnTy {
1138 lifetimes: lifetime_defs,
1143 /// Parses an obsolete closure kind (`&:`, `&mut:`, or `:`).
1144 pub fn parse_obsolete_closure_kind(&mut self) -> PResult<'a, ()> {
1145 let lo = self.span.lo;
1147 self.check(&token::BinOp(token::And)) &&
1148 self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
1149 self.look_ahead(2, |t| *t == token::Colon)
1155 self.token == token::BinOp(token::And) &&
1156 self.look_ahead(1, |t| *t == token::Colon)
1161 self.eat(&token::Colon)
1168 let span = mk_sp(lo, self.span.hi);
1169 self.obsolete(span, ObsoleteSyntax::ClosureKind);
1173 pub fn parse_unsafety(&mut self) -> PResult<'a, Unsafety> {
1174 if self.eat_keyword(keywords::Unsafe) {
1175 return Ok(Unsafety::Unsafe);
1177 return Ok(Unsafety::Normal);
1181 /// Parse the items in a trait declaration
1182 pub fn parse_trait_items(&mut self) -> PResult<'a, Vec<P<TraitItem>>> {
1183 self.parse_unspanned_seq(
1184 &token::OpenDelim(token::Brace),
1185 &token::CloseDelim(token::Brace),
1187 |p| -> PResult<'a, P<TraitItem>> {
1188 maybe_whole!(no_clone p, NtTraitItem);
1189 let mut attrs = try!(p.parse_outer_attributes());
1192 let (name, node) = if p.eat_keyword(keywords::Type) {
1193 let TyParam {ident, bounds, default, ..} = try!(p.parse_ty_param());
1194 try!(p.expect(&token::Semi));
1195 (ident, TypeTraitItem(bounds, default))
1196 } else if p.is_const_item() {
1197 try!(p.expect_keyword(keywords::Const));
1198 let ident = try!(p.parse_ident());
1199 try!(p.expect(&token::Colon));
1200 let ty = try!(p.parse_ty_sum());
1201 let default = if p.check(&token::Eq) {
1203 let expr = try!(p.parse_expr());
1204 try!(p.commit_expr_expecting(&expr, token::Semi));
1207 try!(p.expect(&token::Semi));
1210 (ident, ConstTraitItem(ty, default))
1212 let (constness, unsafety, abi) = try!(p.parse_fn_front_matter());
1214 let ident = try!(p.parse_ident());
1215 let mut generics = try!(p.parse_generics());
1217 let (explicit_self, d) = try!(p.parse_fn_decl_with_self(|p: &mut Parser<'a>|{
1218 // This is somewhat dubious; We don't want to allow
1219 // argument names to be left off if there is a
1221 p.parse_arg_general(false)
1224 generics.where_clause = try!(p.parse_where_clause());
1225 let sig = ast::MethodSig {
1227 constness: constness,
1231 explicit_self: explicit_self,
1234 let body = match p.token {
1237 debug!("parse_trait_methods(): parsing required method");
1240 token::OpenDelim(token::Brace) => {
1241 debug!("parse_trait_methods(): parsing provided method");
1242 let (inner_attrs, body) =
1243 try!(p.parse_inner_attrs_and_block());
1244 attrs.extend(inner_attrs.iter().cloned());
1249 let token_str = p.this_token_to_string();
1250 return Err(p.fatal(&format!("expected `;` or `{{`, found `{}`",
1254 (ident, ast::MethodTraitItem(sig, body))
1258 id: ast::DUMMY_NODE_ID,
1262 span: mk_sp(lo, p.last_span.hi),
1267 /// Parse a possibly mutable type
1268 pub fn parse_mt(&mut self) -> PResult<'a, MutTy> {
1269 let mutbl = try!(self.parse_mutability());
1270 let t = try!(self.parse_ty());
1271 Ok(MutTy { ty: t, mutbl: mutbl })
1274 /// Parse optional return type [ -> TY ] in function decl
1275 pub fn parse_ret_ty(&mut self) -> PResult<'a, FunctionRetTy> {
1276 if self.eat(&token::RArrow) {
1277 if self.eat(&token::Not) {
1278 Ok(NoReturn(self.last_span))
1280 Ok(Return(try!(self.parse_ty())))
1283 let pos = self.span.lo;
1284 Ok(DefaultReturn(mk_sp(pos, pos)))
1288 /// Parse a type in a context where `T1+T2` is allowed.
1289 pub fn parse_ty_sum(&mut self) -> PResult<'a, P<Ty>> {
1290 let lo = self.span.lo;
1291 let lhs = try!(self.parse_ty());
1293 if !self.eat(&token::BinOp(token::Plus)) {
1297 let bounds = try!(self.parse_ty_param_bounds(BoundParsingMode::Bare));
1299 // In type grammar, `+` is treated like a binary operator,
1300 // and hence both L and R side are required.
1301 if bounds.is_empty() {
1302 let last_span = self.last_span;
1303 self.span_err(last_span,
1304 "at least one type parameter bound \
1305 must be specified");
1308 let sp = mk_sp(lo, self.last_span.hi);
1309 let sum = ast::TyObjectSum(lhs, bounds);
1310 Ok(P(Ty {id: ast::DUMMY_NODE_ID, node: sum, span: sp}))
1314 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1315 maybe_whole!(no_clone self, NtTy);
1317 let lo = self.span.lo;
1319 let t = if self.check(&token::OpenDelim(token::Paren)) {
1322 // (t) is a parenthesized ty
1323 // (t,) is the type of a tuple with only one field,
1325 let mut ts = vec![];
1326 let mut last_comma = false;
1327 while self.token != token::CloseDelim(token::Paren) {
1328 ts.push(try!(self.parse_ty_sum()));
1329 if self.check(&token::Comma) {
1338 try!(self.expect(&token::CloseDelim(token::Paren)));
1339 if ts.len() == 1 && !last_comma {
1340 TyParen(ts.into_iter().nth(0).unwrap())
1344 } else if self.check(&token::BinOp(token::Star)) {
1345 // STAR POINTER (bare pointer?)
1347 TyPtr(try!(self.parse_ptr()))
1348 } else if self.check(&token::OpenDelim(token::Bracket)) {
1350 try!(self.expect(&token::OpenDelim(token::Bracket)));
1351 let t = try!(self.parse_ty_sum());
1353 // Parse the `; e` in `[ i32; e ]`
1354 // where `e` is a const expression
1355 let t = match try!(self.maybe_parse_fixed_length_of_vec()) {
1357 Some(suffix) => TyFixedLengthVec(t, suffix)
1359 try!(self.expect(&token::CloseDelim(token::Bracket)));
1361 } else if self.check(&token::BinOp(token::And)) ||
1362 self.token == token::AndAnd {
1364 try!(self.expect_and());
1365 try!(self.parse_borrowed_pointee())
1366 } else if self.check_keyword(keywords::For) {
1367 try!(self.parse_for_in_type())
1368 } else if self.token_is_bare_fn_keyword() {
1370 try!(self.parse_ty_bare_fn(Vec::new()))
1371 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1373 // In order to not be ambiguous, the type must be surrounded by parens.
1374 try!(self.expect(&token::OpenDelim(token::Paren)));
1375 let e = try!(self.parse_expr());
1376 try!(self.expect(&token::CloseDelim(token::Paren)));
1378 } else if self.eat_lt() {
1381 try!(self.parse_qualified_path(NoTypesAllowed));
1383 TyPath(Some(qself), path)
1384 } else if self.check(&token::ModSep) ||
1385 self.token.is_ident() ||
1386 self.token.is_path() {
1387 let path = try!(self.parse_path(LifetimeAndTypesWithoutColons));
1388 if self.check(&token::Not) {
1391 let delim = try!(self.expect_open_delim());
1392 let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
1394 |p| p.parse_token_tree()));
1395 let hi = self.span.hi;
1396 TyMac(spanned(lo, hi, Mac_ { path: path, tts: tts, ctxt: EMPTY_CTXT }))
1401 } else if self.eat(&token::Underscore) {
1402 // TYPE TO BE INFERRED
1405 let this_token_str = self.this_token_to_string();
1406 let msg = format!("expected type, found `{}`", this_token_str);
1407 return Err(self.fatal(&msg[..]));
1410 let sp = mk_sp(lo, self.last_span.hi);
1411 Ok(P(Ty {id: ast::DUMMY_NODE_ID, node: t, span: sp}))
1414 pub fn parse_borrowed_pointee(&mut self) -> PResult<'a, Ty_> {
1415 // look for `&'lt` or `&'foo ` and interpret `foo` as the region name:
1416 let opt_lifetime = try!(self.parse_opt_lifetime());
1418 let mt = try!(self.parse_mt());
1419 return Ok(TyRptr(opt_lifetime, mt));
1422 pub fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1423 let mutbl = if self.eat_keyword(keywords::Mut) {
1425 } else if self.eat_keyword(keywords::Const) {
1428 let span = self.last_span;
1430 "bare raw pointers are no longer allowed, you should \
1431 likely use `*mut T`, but otherwise `*T` is now \
1432 known as `*const T`");
1435 let t = try!(self.parse_ty());
1436 Ok(MutTy { ty: t, mutbl: mutbl })
1439 pub fn is_named_argument(&mut self) -> bool {
1440 let offset = match self.token {
1441 token::BinOp(token::And) => 1,
1443 _ if self.token.is_keyword(keywords::Mut) => 1,
1447 debug!("parser is_named_argument offset:{}", offset);
1450 is_plain_ident_or_underscore(&self.token)
1451 && self.look_ahead(1, |t| *t == token::Colon)
1453 self.look_ahead(offset, |t| is_plain_ident_or_underscore(t))
1454 && self.look_ahead(offset + 1, |t| *t == token::Colon)
1458 /// This version of parse arg doesn't necessarily require
1459 /// identifier names.
1460 pub fn parse_arg_general(&mut self, require_name: bool) -> PResult<'a, Arg> {
1461 maybe_whole!(no_clone self, NtArg);
1463 let pat = if require_name || self.is_named_argument() {
1464 debug!("parse_arg_general parse_pat (require_name:{})",
1466 let pat = try!(self.parse_pat());
1468 try!(self.expect(&token::Colon));
1471 debug!("parse_arg_general ident_to_pat");
1472 ast_util::ident_to_pat(ast::DUMMY_NODE_ID,
1474 special_idents::invalid)
1477 let t = try!(self.parse_ty_sum());
1482 id: ast::DUMMY_NODE_ID,
1486 /// Parse a single function argument
1487 pub fn parse_arg(&mut self) -> PResult<'a, Arg> {
1488 self.parse_arg_general(true)
1491 /// Parse an argument in a lambda header e.g. |arg, arg|
1492 pub fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1493 let pat = try!(self.parse_pat());
1494 let t = if self.eat(&token::Colon) {
1495 try!(self.parse_ty_sum())
1498 id: ast::DUMMY_NODE_ID,
1500 span: mk_sp(self.span.lo, self.span.hi),
1506 id: ast::DUMMY_NODE_ID
1510 pub fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1511 if self.check(&token::Semi) {
1513 Ok(Some(try!(self.parse_expr())))
1519 /// Matches token_lit = LIT_INTEGER | ...
1520 pub fn lit_from_token(&self, tok: &token::Token) -> PResult<'a, Lit_> {
1522 token::Interpolated(token::NtExpr(ref v)) => {
1524 ExprLit(ref lit) => { Ok(lit.node.clone()) }
1525 _ => { return self.unexpected_last(tok); }
1528 token::Literal(lit, suf) => {
1529 let (suffix_illegal, out) = match lit {
1530 token::Byte(i) => (true, LitByte(parse::byte_lit(&i.as_str()).0)),
1531 token::Char(i) => (true, LitChar(parse::char_lit(&i.as_str()).0)),
1533 // there are some valid suffixes for integer and
1534 // float literals, so all the handling is done
1536 token::Integer(s) => {
1537 (false, parse::integer_lit(&s.as_str(),
1538 suf.as_ref().map(|s| s.as_str()),
1539 &self.sess.span_diagnostic,
1542 token::Float(s) => {
1543 (false, parse::float_lit(&s.as_str(),
1544 suf.as_ref().map(|s| s.as_str()),
1545 &self.sess.span_diagnostic,
1551 LitStr(token::intern_and_get_ident(&parse::str_lit(&s.as_str())),
1554 token::StrRaw(s, n) => {
1557 token::intern_and_get_ident(&parse::raw_str_lit(&s.as_str())),
1560 token::ByteStr(i) =>
1561 (true, LitByteStr(parse::byte_str_lit(&i.as_str()))),
1562 token::ByteStrRaw(i, _) =>
1564 LitByteStr(Rc::new(i.to_string().into_bytes()))),
1568 let sp = self.last_span;
1569 self.expect_no_suffix(sp, &*format!("{} literal", lit.short_name()), suf)
1574 _ => { return self.unexpected_last(tok); }
1578 /// Matches lit = true | false | token_lit
1579 pub fn parse_lit(&mut self) -> PResult<'a, Lit> {
1580 let lo = self.span.lo;
1581 let lit = if self.eat_keyword(keywords::True) {
1583 } else if self.eat_keyword(keywords::False) {
1586 let token = self.bump_and_get();
1587 let lit = try!(self.lit_from_token(&token));
1590 Ok(codemap::Spanned { node: lit, span: mk_sp(lo, self.last_span.hi) })
1593 /// matches '-' lit | lit
1594 pub fn parse_pat_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1595 let minus_lo = self.span.lo;
1596 let minus_present = self.eat(&token::BinOp(token::Minus));
1597 let lo = self.span.lo;
1598 let literal = P(try!(self.parse_lit()));
1599 let hi = self.last_span.hi;
1600 let expr = self.mk_expr(lo, hi, ExprLit(literal), None);
1603 let minus_hi = self.last_span.hi;
1604 let unary = self.mk_unary(UnNeg, expr);
1605 Ok(self.mk_expr(minus_lo, minus_hi, unary, None))
1611 /// Parses qualified path.
1613 /// Assumes that the leading `<` has been parsed already.
1615 /// Qualifed paths are a part of the universal function call
1618 /// `qualified_path = <type [as trait_ref]>::path`
1620 /// See `parse_path` for `mode` meaning.
1625 /// `<T as U>::F::a::<S>`
1626 pub fn parse_qualified_path(&mut self, mode: PathParsingMode)
1627 -> PResult<'a, (QSelf, ast::Path)> {
1628 let span = self.last_span;
1629 let self_type = try!(self.parse_ty_sum());
1630 let mut path = if self.eat_keyword(keywords::As) {
1631 try!(self.parse_path(LifetimeAndTypesWithoutColons))
1642 position: path.segments.len()
1645 try!(self.expect(&token::Gt));
1646 try!(self.expect(&token::ModSep));
1648 let segments = match mode {
1649 LifetimeAndTypesWithoutColons => {
1650 try!(self.parse_path_segments_without_colons())
1652 LifetimeAndTypesWithColons => {
1653 try!(self.parse_path_segments_with_colons())
1656 try!(self.parse_path_segments_without_types())
1659 path.segments.extend(segments);
1661 path.span.hi = self.last_span.hi;
1666 /// Parses a path and optional type parameter bounds, depending on the
1667 /// mode. The `mode` parameter determines whether lifetimes, types, and/or
1668 /// bounds are permitted and whether `::` must precede type parameter
1670 pub fn parse_path(&mut self, mode: PathParsingMode) -> PResult<'a, ast::Path> {
1671 // Check for a whole path...
1672 let found = match self.token {
1673 token::Interpolated(token::NtPath(_)) => Some(self.bump_and_get()),
1676 if let Some(token::Interpolated(token::NtPath(path))) = found {
1680 let lo = self.span.lo;
1681 let is_global = self.eat(&token::ModSep);
1683 // Parse any number of segments and bound sets. A segment is an
1684 // identifier followed by an optional lifetime and a set of types.
1685 // A bound set is a set of type parameter bounds.
1686 let segments = match mode {
1687 LifetimeAndTypesWithoutColons => {
1688 try!(self.parse_path_segments_without_colons())
1690 LifetimeAndTypesWithColons => {
1691 try!(self.parse_path_segments_with_colons())
1694 try!(self.parse_path_segments_without_types())
1698 // Assemble the span.
1699 let span = mk_sp(lo, self.last_span.hi);
1701 // Assemble the result.
1710 /// - `a::b<T,U>::c<V,W>`
1711 /// - `a::b<T,U>::c(V) -> W`
1712 /// - `a::b<T,U>::c(V)`
1713 pub fn parse_path_segments_without_colons(&mut self) -> PResult<'a, Vec<ast::PathSegment>> {
1714 let mut segments = Vec::new();
1716 // First, parse an identifier.
1717 let identifier = try!(self.parse_ident_or_self_type());
1719 // Parse types, optionally.
1720 let parameters = if self.eat_lt() {
1721 let (lifetimes, types, bindings) = try!(self.parse_generic_values_after_lt());
1723 ast::PathParameters::AngleBracketed(ast::AngleBracketedParameterData {
1724 lifetimes: lifetimes,
1725 types: P::from_vec(types),
1726 bindings: P::from_vec(bindings),
1728 } else if self.eat(&token::OpenDelim(token::Paren)) {
1729 let lo = self.last_span.lo;
1731 let inputs = try!(self.parse_seq_to_end(
1732 &token::CloseDelim(token::Paren),
1733 seq_sep_trailing_allowed(token::Comma),
1734 |p| p.parse_ty_sum()));
1736 let output_ty = if self.eat(&token::RArrow) {
1737 Some(try!(self.parse_ty()))
1742 let hi = self.last_span.hi;
1744 ast::PathParameters::Parenthesized(ast::ParenthesizedParameterData {
1745 span: mk_sp(lo, hi),
1750 ast::PathParameters::none()
1753 // Assemble and push the result.
1754 segments.push(ast::PathSegment { identifier: identifier,
1755 parameters: parameters });
1757 // Continue only if we see a `::`
1758 if !self.eat(&token::ModSep) {
1759 return Ok(segments);
1765 /// - `a::b::<T,U>::c`
1766 pub fn parse_path_segments_with_colons(&mut self) -> PResult<'a, Vec<ast::PathSegment>> {
1767 let mut segments = Vec::new();
1769 // First, parse an identifier.
1770 let identifier = try!(self.parse_ident_or_self_type());
1772 // If we do not see a `::`, stop.
1773 if !self.eat(&token::ModSep) {
1774 segments.push(ast::PathSegment {
1775 identifier: identifier,
1776 parameters: ast::PathParameters::none()
1778 return Ok(segments);
1781 // Check for a type segment.
1783 // Consumed `a::b::<`, go look for types
1784 let (lifetimes, types, bindings) = try!(self.parse_generic_values_after_lt());
1785 let parameters = ast::AngleBracketedParameterData {
1786 lifetimes: lifetimes,
1787 types: P::from_vec(types),
1788 bindings: P::from_vec(bindings),
1790 segments.push(ast::PathSegment {
1791 identifier: identifier,
1792 parameters: ast::PathParameters::AngleBracketed(parameters),
1795 // Consumed `a::b::<T,U>`, check for `::` before proceeding
1796 if !self.eat(&token::ModSep) {
1797 return Ok(segments);
1800 // Consumed `a::`, go look for `b`
1801 segments.push(ast::PathSegment {
1802 identifier: identifier,
1803 parameters: ast::PathParameters::none(),
1812 pub fn parse_path_segments_without_types(&mut self) -> PResult<'a, Vec<ast::PathSegment>> {
1813 let mut segments = Vec::new();
1815 // First, parse an identifier.
1816 let identifier = try!(self.parse_ident_or_self_type());
1818 // Assemble and push the result.
1819 segments.push(ast::PathSegment {
1820 identifier: identifier,
1821 parameters: ast::PathParameters::none()
1824 // If we do not see a `::`, stop.
1825 if !self.eat(&token::ModSep) {
1826 return Ok(segments);
1831 /// parses 0 or 1 lifetime
1832 pub fn parse_opt_lifetime(&mut self) -> PResult<'a, Option<ast::Lifetime>> {
1834 token::Lifetime(..) => {
1835 Ok(Some(try!(self.parse_lifetime())))
1843 /// Parses a single lifetime
1844 /// Matches lifetime = LIFETIME
1845 pub fn parse_lifetime(&mut self) -> PResult<'a, ast::Lifetime> {
1847 token::Lifetime(i) => {
1848 let span = self.span;
1850 return Ok(ast::Lifetime {
1851 id: ast::DUMMY_NODE_ID,
1857 return Err(self.fatal("expected a lifetime name"));
1862 /// Parses `lifetime_defs = [ lifetime_defs { ',' lifetime_defs } ]` where `lifetime_def =
1863 /// lifetime [':' lifetimes]`
1864 pub fn parse_lifetime_defs(&mut self) -> PResult<'a, Vec<ast::LifetimeDef>> {
1866 let mut res = Vec::new();
1869 token::Lifetime(_) => {
1870 let lifetime = try!(self.parse_lifetime());
1872 if self.eat(&token::Colon) {
1873 try!(self.parse_lifetimes(token::BinOp(token::Plus)))
1877 res.push(ast::LifetimeDef { lifetime: lifetime,
1887 token::Comma => { self.bump();}
1888 token::Gt => { return Ok(res); }
1889 token::BinOp(token::Shr) => { return Ok(res); }
1891 let this_token_str = self.this_token_to_string();
1892 let msg = format!("expected `,` or `>` after lifetime \
1895 return Err(self.fatal(&msg[..]));
1901 /// matches lifetimes = ( lifetime ) | ( lifetime , lifetimes ) actually, it matches the empty
1902 /// one too, but putting that in there messes up the grammar....
1904 /// Parses zero or more comma separated lifetimes. Expects each lifetime to be followed by
1905 /// either a comma or `>`. Used when parsing type parameter lists, where we expect something
1906 /// like `<'a, 'b, T>`.
1907 pub fn parse_lifetimes(&mut self, sep: token::Token) -> PResult<'a, Vec<ast::Lifetime>> {
1909 let mut res = Vec::new();
1912 token::Lifetime(_) => {
1913 res.push(try!(self.parse_lifetime()));
1920 if self.token != sep {
1928 /// Parse mutability declaration (mut/const/imm)
1929 pub fn parse_mutability(&mut self) -> PResult<'a, Mutability> {
1930 if self.eat_keyword(keywords::Mut) {
1937 /// Parse ident COLON expr
1938 pub fn parse_field(&mut self) -> PResult<'a, Field> {
1939 let lo = self.span.lo;
1940 let i = try!(self.parse_ident());
1941 let hi = self.last_span.hi;
1942 try!(self.expect(&token::Colon));
1943 let e = try!(self.parse_expr());
1945 ident: spanned(lo, hi, i),
1946 span: mk_sp(lo, e.span.hi),
1951 pub fn mk_expr(&mut self, lo: BytePos, hi: BytePos,
1952 node: Expr_, attrs: ThinAttributes) -> P<Expr> {
1954 id: ast::DUMMY_NODE_ID,
1956 span: mk_sp(lo, hi),
1961 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::Expr_ {
1962 ExprUnary(unop, expr)
1965 pub fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::Expr_ {
1966 ExprBinary(binop, lhs, rhs)
1969 pub fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::Expr_ {
1973 fn mk_method_call(&mut self,
1974 ident: ast::SpannedIdent,
1978 ExprMethodCall(ident, tps, args)
1981 pub fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::Expr_ {
1982 ExprIndex(expr, idx)
1985 pub fn mk_range(&mut self,
1986 start: Option<P<Expr>>,
1987 end: Option<P<Expr>>)
1989 ExprRange(start, end)
1992 pub fn mk_field(&mut self, expr: P<Expr>, ident: ast::SpannedIdent) -> ast::Expr_ {
1993 ExprField(expr, ident)
1996 pub fn mk_tup_field(&mut self, expr: P<Expr>, idx: codemap::Spanned<usize>) -> ast::Expr_ {
1997 ExprTupField(expr, idx)
2000 pub fn mk_assign_op(&mut self, binop: ast::BinOp,
2001 lhs: P<Expr>, rhs: P<Expr>) -> ast::Expr_ {
2002 ExprAssignOp(binop, lhs, rhs)
2005 pub fn mk_mac_expr(&mut self, lo: BytePos, hi: BytePos,
2006 m: Mac_, attrs: ThinAttributes) -> P<Expr> {
2008 id: ast::DUMMY_NODE_ID,
2009 node: ExprMac(codemap::Spanned {node: m, span: mk_sp(lo, hi)}),
2010 span: mk_sp(lo, hi),
2015 pub fn mk_lit_u32(&mut self, i: u32, attrs: ThinAttributes) -> P<Expr> {
2016 let span = &self.span;
2017 let lv_lit = P(codemap::Spanned {
2018 node: LitInt(i as u64, ast::UnsignedIntLit(TyU32)),
2023 id: ast::DUMMY_NODE_ID,
2024 node: ExprLit(lv_lit),
2030 fn expect_open_delim(&mut self) -> PResult<'a, token::DelimToken> {
2031 self.expected_tokens.push(TokenType::Token(token::Gt));
2033 token::OpenDelim(delim) => {
2037 _ => Err(self.fatal("expected open delimiter")),
2041 /// At the bottom (top?) of the precedence hierarchy,
2042 /// parse things like parenthesized exprs,
2043 /// macros, return, etc.
2045 /// NB: This does not parse outer attributes,
2046 /// and is private because it only works
2047 /// correctly if called from parse_dot_or_call_expr().
2048 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2049 maybe_whole_expr!(self);
2051 // Outer attributes are already parsed and will be
2052 // added to the return value after the fact.
2054 // Therefore, prevent sub-parser from parsing
2055 // attributes by giving them a empty "already parsed" list.
2056 let mut attrs = None;
2058 let lo = self.span.lo;
2059 let mut hi = self.span.hi;
2063 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2065 token::OpenDelim(token::Paren) => {
2068 let attrs = try!(self.parse_inner_attributes())
2072 // (e) is parenthesized e
2073 // (e,) is a tuple with only one field, e
2074 let mut es = vec![];
2075 let mut trailing_comma = false;
2076 while self.token != token::CloseDelim(token::Paren) {
2077 es.push(try!(self.parse_expr()));
2078 try!(self.commit_expr(&**es.last().unwrap(), &[],
2079 &[token::Comma, token::CloseDelim(token::Paren)]));
2080 if self.check(&token::Comma) {
2081 trailing_comma = true;
2085 trailing_comma = false;
2091 hi = self.last_span.hi;
2092 return if es.len() == 1 && !trailing_comma {
2093 Ok(self.mk_expr(lo, hi, ExprParen(es.into_iter().nth(0).unwrap()), attrs))
2095 Ok(self.mk_expr(lo, hi, ExprTup(es), attrs))
2098 token::OpenDelim(token::Brace) => {
2099 return self.parse_block_expr(lo, DefaultBlock, attrs);
2101 token::BinOp(token::Or) | token::OrOr => {
2102 let lo = self.span.lo;
2103 return self.parse_lambda_expr(lo, CaptureByRef, attrs);
2105 token::Ident(id @ ast::Ident {
2106 name: token::SELF_KEYWORD_NAME,
2108 }, token::Plain) => {
2110 let path = ast_util::ident_to_path(mk_sp(lo, hi), id);
2111 ex = ExprPath(None, path);
2112 hi = self.last_span.hi;
2114 token::OpenDelim(token::Bracket) => {
2117 let inner_attrs = try!(self.parse_inner_attributes())
2119 attrs.update(|attrs| attrs.append(inner_attrs));
2121 if self.check(&token::CloseDelim(token::Bracket)) {
2124 ex = ExprVec(Vec::new());
2127 let first_expr = try!(self.parse_expr());
2128 if self.check(&token::Semi) {
2129 // Repeating array syntax: [ 0; 512 ]
2131 let count = try!(self.parse_expr());
2132 try!(self.expect(&token::CloseDelim(token::Bracket)));
2133 ex = ExprRepeat(first_expr, count);
2134 } else if self.check(&token::Comma) {
2135 // Vector with two or more elements.
2137 let remaining_exprs = try!(self.parse_seq_to_end(
2138 &token::CloseDelim(token::Bracket),
2139 seq_sep_trailing_allowed(token::Comma),
2140 |p| Ok(try!(p.parse_expr()))
2142 let mut exprs = vec!(first_expr);
2143 exprs.extend(remaining_exprs);
2144 ex = ExprVec(exprs);
2146 // Vector with one element.
2147 try!(self.expect(&token::CloseDelim(token::Bracket)));
2148 ex = ExprVec(vec!(first_expr));
2151 hi = self.last_span.hi;
2156 try!(self.parse_qualified_path(LifetimeAndTypesWithColons));
2158 return Ok(self.mk_expr(lo, hi, ExprPath(Some(qself), path), attrs));
2160 if self.eat_keyword(keywords::Move) {
2161 let lo = self.last_span.lo;
2162 return self.parse_lambda_expr(lo, CaptureByValue, attrs);
2164 if self.eat_keyword(keywords::If) {
2165 return self.parse_if_expr(attrs);
2167 if self.eat_keyword(keywords::For) {
2168 let lo = self.last_span.lo;
2169 return self.parse_for_expr(None, lo, attrs);
2171 if self.eat_keyword(keywords::While) {
2172 let lo = self.last_span.lo;
2173 return self.parse_while_expr(None, lo, attrs);
2175 if self.token.is_lifetime() {
2176 let lifetime = self.get_lifetime();
2177 let lo = self.span.lo;
2179 try!(self.expect(&token::Colon));
2180 if self.eat_keyword(keywords::While) {
2181 return self.parse_while_expr(Some(lifetime), lo, attrs)
2183 if self.eat_keyword(keywords::For) {
2184 return self.parse_for_expr(Some(lifetime), lo, attrs)
2186 if self.eat_keyword(keywords::Loop) {
2187 return self.parse_loop_expr(Some(lifetime), lo, attrs)
2189 return Err(self.fatal("expected `while`, `for`, or `loop` after a label"))
2191 if self.eat_keyword(keywords::Loop) {
2192 let lo = self.last_span.lo;
2193 return self.parse_loop_expr(None, lo, attrs);
2195 if self.eat_keyword(keywords::Continue) {
2196 let ex = if self.token.is_lifetime() {
2197 let ex = ExprAgain(Some(Spanned{
2198 node: self.get_lifetime(),
2206 let hi = self.last_span.hi;
2207 return Ok(self.mk_expr(lo, hi, ex, attrs));
2209 if self.eat_keyword(keywords::Match) {
2210 return self.parse_match_expr(attrs);
2212 if self.eat_keyword(keywords::Unsafe) {
2213 return self.parse_block_expr(
2215 UnsafeBlock(ast::UserProvided),
2218 if self.eat_keyword(keywords::Return) {
2219 if self.token.can_begin_expr() {
2220 let e = try!(self.parse_expr());
2222 ex = ExprRet(Some(e));
2226 } else if self.eat_keyword(keywords::Break) {
2227 if self.token.is_lifetime() {
2228 ex = ExprBreak(Some(Spanned {
2229 node: self.get_lifetime(),
2234 ex = ExprBreak(None);
2236 hi = self.last_span.hi;
2237 } else if self.check(&token::ModSep) ||
2238 self.token.is_ident() &&
2239 !self.check_keyword(keywords::True) &&
2240 !self.check_keyword(keywords::False) {
2242 try!(self.parse_path(LifetimeAndTypesWithColons));
2244 // `!`, as an operator, is prefix, so we know this isn't that
2245 if self.check(&token::Not) {
2246 // MACRO INVOCATION expression
2249 let delim = try!(self.expect_open_delim());
2250 let tts = try!(self.parse_seq_to_end(
2251 &token::CloseDelim(delim),
2253 |p| p.parse_token_tree()));
2254 let hi = self.last_span.hi;
2256 return Ok(self.mk_mac_expr(lo,
2258 Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT },
2261 if self.check(&token::OpenDelim(token::Brace)) {
2262 // This is a struct literal, unless we're prohibited
2263 // from parsing struct literals here.
2264 let prohibited = self.restrictions.contains(
2265 Restrictions::RESTRICTION_NO_STRUCT_LITERAL
2268 // It's a struct literal.
2270 let mut fields = Vec::new();
2271 let mut base = None;
2273 let attrs = attrs.append(
2274 try!(self.parse_inner_attributes())
2275 .into_thin_attrs());
2277 while self.token != token::CloseDelim(token::Brace) {
2278 if self.eat(&token::DotDot) {
2279 base = Some(try!(self.parse_expr()));
2283 fields.push(try!(self.parse_field()));
2284 try!(self.commit_expr(&*fields.last().unwrap().expr,
2286 &[token::CloseDelim(token::Brace)]));
2290 try!(self.expect(&token::CloseDelim(token::Brace)));
2291 ex = ExprStruct(pth, fields, base);
2292 return Ok(self.mk_expr(lo, hi, ex, attrs));
2297 ex = ExprPath(None, pth);
2299 // other literal expression
2300 let lit = try!(self.parse_lit());
2302 ex = ExprLit(P(lit));
2307 return Ok(self.mk_expr(lo, hi, ex, attrs));
2310 fn parse_or_use_outer_attributes(&mut self,
2311 already_parsed_attrs: Option<ThinAttributes>)
2312 -> PResult<'a, ThinAttributes> {
2313 if let Some(attrs) = already_parsed_attrs {
2316 self.parse_outer_attributes().map(|a| a.into_thin_attrs())
2320 /// Parse a block or unsafe block
2321 pub fn parse_block_expr(&mut self, lo: BytePos, blk_mode: BlockCheckMode,
2322 attrs: ThinAttributes)
2323 -> PResult<'a, P<Expr>> {
2325 let outer_attrs = attrs;
2326 try!(self.expect(&token::OpenDelim(token::Brace)));
2328 let inner_attrs = try!(self.parse_inner_attributes()).into_thin_attrs();
2329 let attrs = outer_attrs.append(inner_attrs);
2331 let blk = try!(self.parse_block_tail(lo, blk_mode));
2332 return Ok(self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk), attrs));
2335 /// parse a.b or a(13) or a[4] or just a
2336 pub fn parse_dot_or_call_expr(&mut self,
2337 already_parsed_attrs: Option<ThinAttributes>)
2338 -> PResult<'a, P<Expr>> {
2339 let attrs = try!(self.parse_or_use_outer_attributes(already_parsed_attrs));
2341 let (span, b) = interpolated_or_expr_span!(self, try!(self.parse_bottom_expr()));
2342 self.parse_dot_or_call_expr_with(b, span.lo, attrs)
2345 pub fn parse_dot_or_call_expr_with(&mut self,
2348 attrs: ThinAttributes)
2349 -> PResult<'a, P<Expr>> {
2350 // Stitch the list of outer attributes onto the return value.
2351 // A little bit ugly, but the best way given the current code
2353 self.parse_dot_or_call_expr_with_(e0, lo)
2355 expr.map(|mut expr| {
2356 expr.attrs.update(|a| a.prepend(attrs));
2358 ExprIf(..) | ExprIfLet(..) => {
2359 if !expr.attrs.as_attr_slice().is_empty() {
2360 // Just point to the first attribute in there...
2361 let span = expr.attrs.as_attr_slice()[0].span;
2364 "attributes are not yet allowed on `if` \
2375 // Assuming we have just parsed `.foo` (i.e., a dot and an ident), continue
2376 // parsing into an expression.
2377 fn parse_dot_suffix(&mut self,
2380 self_value: P<Expr>,
2382 -> PResult<'a, P<Expr>> {
2383 let (_, tys, bindings) = if self.eat(&token::ModSep) {
2384 try!(self.expect_lt());
2385 try!(self.parse_generic_values_after_lt())
2387 (Vec::new(), Vec::new(), Vec::new())
2390 if !bindings.is_empty() {
2391 let last_span = self.last_span;
2392 self.span_err(last_span, "type bindings are only permitted on trait paths");
2395 Ok(match self.token {
2396 // expr.f() method call.
2397 token::OpenDelim(token::Paren) => {
2398 let mut es = try!(self.parse_unspanned_seq(
2399 &token::OpenDelim(token::Paren),
2400 &token::CloseDelim(token::Paren),
2401 seq_sep_trailing_allowed(token::Comma),
2402 |p| Ok(try!(p.parse_expr()))
2404 let hi = self.last_span.hi;
2406 es.insert(0, self_value);
2407 let id = spanned(ident_span.lo, ident_span.hi, ident);
2408 let nd = self.mk_method_call(id, tys, es);
2409 self.mk_expr(lo, hi, nd, None)
2413 if !tys.is_empty() {
2414 let last_span = self.last_span;
2415 self.span_err(last_span,
2416 "field expressions may not \
2417 have type parameters");
2420 let id = spanned(ident_span.lo, ident_span.hi, ident);
2421 let field = self.mk_field(self_value, id);
2422 self.mk_expr(lo, ident_span.hi, field, None)
2427 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: BytePos) -> PResult<'a, P<Expr>> {
2432 if self.eat(&token::Dot) {
2434 token::Ident(i, _) => {
2435 let dot_pos = self.last_span.hi;
2439 e = try!(self.parse_dot_suffix(i, mk_sp(dot_pos, hi), e, lo));
2441 token::Literal(token::Integer(n), suf) => {
2444 // A tuple index may not have a suffix
2445 self.expect_no_suffix(sp, "tuple index", suf);
2447 let dot = self.last_span.hi;
2451 let index = n.as_str().parse::<usize>().ok();
2454 let id = spanned(dot, hi, n);
2455 let field = self.mk_tup_field(e, id);
2456 e = self.mk_expr(lo, hi, field, None);
2459 let last_span = self.last_span;
2460 self.span_err(last_span, "invalid tuple or tuple struct index");
2464 token::Literal(token::Float(n), _suf) => {
2466 let last_span = self.last_span;
2467 let fstr = n.as_str();
2468 let mut err = self.diagnostic().struct_span_err(last_span,
2469 &format!("unexpected token: `{}`", n.as_str()));
2470 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2471 let float = match fstr.parse::<f64>().ok() {
2475 err.fileline_help(last_span,
2476 &format!("try parenthesizing the first index; e.g., `(foo.{}){}`",
2477 float.trunc() as usize,
2478 format!(".{}", fstr.splitn(2, ".").last().unwrap())));
2481 self.abort_if_errors();
2485 // FIXME Could factor this out into non_fatal_unexpected or something.
2486 let actual = self.this_token_to_string();
2487 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
2489 let dot_pos = self.last_span.hi;
2490 e = try!(self.parse_dot_suffix(special_idents::invalid,
2491 mk_sp(dot_pos, dot_pos),
2497 if self.expr_is_complete(&*e) { break; }
2500 token::OpenDelim(token::Paren) => {
2501 let es = try!(self.parse_unspanned_seq(
2502 &token::OpenDelim(token::Paren),
2503 &token::CloseDelim(token::Paren),
2504 seq_sep_trailing_allowed(token::Comma),
2505 |p| Ok(try!(p.parse_expr()))
2507 hi = self.last_span.hi;
2509 let nd = self.mk_call(e, es);
2510 e = self.mk_expr(lo, hi, nd, None);
2514 // Could be either an index expression or a slicing expression.
2515 token::OpenDelim(token::Bracket) => {
2517 let ix = try!(self.parse_expr());
2519 try!(self.commit_expr_expecting(&*ix, token::CloseDelim(token::Bracket)));
2520 let index = self.mk_index(e, ix);
2521 e = self.mk_expr(lo, hi, index, None)
2529 // Parse unquoted tokens after a `$` in a token tree
2530 fn parse_unquoted(&mut self) -> PResult<'a, TokenTree> {
2531 let mut sp = self.span;
2532 let (name, namep) = match self.token {
2536 if self.token == token::OpenDelim(token::Paren) {
2537 let Spanned { node: seq, span: seq_span } = try!(self.parse_seq(
2538 &token::OpenDelim(token::Paren),
2539 &token::CloseDelim(token::Paren),
2541 |p| p.parse_token_tree()
2543 let (sep, repeat) = try!(self.parse_sep_and_kleene_op());
2544 let name_num = macro_parser::count_names(&seq);
2545 return Ok(TokenTree::Sequence(mk_sp(sp.lo, seq_span.hi),
2546 Rc::new(SequenceRepetition {
2550 num_captures: name_num
2552 } else if self.token.is_keyword_allow_following_colon(keywords::Crate) {
2554 return Ok(TokenTree::Token(sp, SpecialVarNt(SpecialMacroVar::CrateMacroVar)));
2556 sp = mk_sp(sp.lo, self.span.hi);
2557 let namep = match self.token { token::Ident(_, p) => p, _ => token::Plain };
2558 let name = try!(self.parse_ident());
2562 token::SubstNt(name, namep) => {
2568 // continue by trying to parse the `:ident` after `$name`
2569 if self.token == token::Colon && self.look_ahead(1, |t| t.is_ident() &&
2570 !t.is_strict_keyword() &&
2571 !t.is_reserved_keyword()) {
2573 sp = mk_sp(sp.lo, self.span.hi);
2574 let kindp = match self.token { token::Ident(_, p) => p, _ => token::Plain };
2575 let nt_kind = try!(self.parse_ident());
2576 Ok(TokenTree::Token(sp, MatchNt(name, nt_kind, namep, kindp)))
2578 Ok(TokenTree::Token(sp, SubstNt(name, namep)))
2582 pub fn check_unknown_macro_variable(&mut self) {
2583 if self.quote_depth == 0 {
2585 token::SubstNt(name, _) =>
2586 self.fatal(&format!("unknown macro variable `{}`", name)).emit(),
2592 /// Parse an optional separator followed by a Kleene-style
2593 /// repetition token (+ or *).
2594 pub fn parse_sep_and_kleene_op(&mut self)
2595 -> PResult<'a, (Option<token::Token>, ast::KleeneOp)> {
2596 fn parse_kleene_op<'a>(parser: &mut Parser<'a>) -> PResult<'a, Option<ast::KleeneOp>> {
2597 match parser.token {
2598 token::BinOp(token::Star) => {
2600 Ok(Some(ast::ZeroOrMore))
2602 token::BinOp(token::Plus) => {
2604 Ok(Some(ast::OneOrMore))
2610 match try!(parse_kleene_op(self)) {
2611 Some(kleene_op) => return Ok((None, kleene_op)),
2615 let separator = self.bump_and_get();
2616 match try!(parse_kleene_op(self)) {
2617 Some(zerok) => Ok((Some(separator), zerok)),
2618 None => return Err(self.fatal("expected `*` or `+`"))
2622 /// parse a single token tree from the input.
2623 pub fn parse_token_tree(&mut self) -> PResult<'a, TokenTree> {
2624 // FIXME #6994: currently, this is too eager. It
2625 // parses token trees but also identifies TokenType::Sequence's
2626 // and token::SubstNt's; it's too early to know yet
2627 // whether something will be a nonterminal or a seq
2629 maybe_whole!(deref self, NtTT);
2631 // this is the fall-through for the 'match' below.
2632 // invariants: the current token is not a left-delimiter,
2633 // not an EOF, and not the desired right-delimiter (if
2634 // it were, parse_seq_to_before_end would have prevented
2635 // reaching this point.
2636 fn parse_non_delim_tt_tok<'b>(p: &mut Parser<'b>) -> PResult<'b, TokenTree> {
2637 maybe_whole!(deref p, NtTT);
2639 token::CloseDelim(_) => {
2640 let token_str = p.this_token_to_string();
2641 let mut err = p.fatal(
2642 &format!("incorrect close delimiter: `{}`", token_str));
2643 // This is a conservative error: only report the last unclosed delimiter. The
2644 // previous unclosed delimiters could actually be closed! The parser just hasn't
2645 // gotten to them yet.
2646 if let Some(&sp) = p.open_braces.last() {
2647 err.span_note(sp, "unclosed delimiter");
2651 /* we ought to allow different depths of unquotation */
2652 token::Dollar | token::SubstNt(..) if p.quote_depth > 0 => {
2656 Ok(TokenTree::Token(p.span, p.bump_and_get()))
2663 let open_braces = self.open_braces.clone();
2664 let mut err: DiagnosticBuilder<'a> =
2665 self.fatal("this file contains an un-closed delimiter");
2666 for sp in &open_braces {
2667 err.span_help(*sp, "did you mean to close this delimiter?");
2671 token::OpenDelim(delim) => {
2672 // The span for beginning of the delimited section
2673 let pre_span = self.span;
2675 // Parse the open delimiter.
2676 self.open_braces.push(self.span);
2677 let open_span = self.span;
2680 // Parse the token trees within the delimiters
2681 let tts = try!(self.parse_seq_to_before_end(
2682 &token::CloseDelim(delim),
2684 |p| p.parse_token_tree()
2687 // Parse the close delimiter.
2688 let close_span = self.span;
2690 self.open_braces.pop().unwrap();
2692 // Expand to cover the entire delimited token tree
2693 let span = Span { hi: close_span.hi, ..pre_span };
2695 Ok(TokenTree::Delimited(span, Rc::new(Delimited {
2697 open_span: open_span,
2699 close_span: close_span,
2702 _ => parse_non_delim_tt_tok(self),
2706 // parse a stream of tokens into a list of TokenTree's,
2708 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2709 let mut tts = Vec::new();
2710 while self.token != token::Eof {
2711 tts.push(try!(self.parse_token_tree()));
2716 /// Parse a prefix-unary-operator expr
2717 pub fn parse_prefix_expr(&mut self,
2718 already_parsed_attrs: Option<ThinAttributes>)
2719 -> PResult<'a, P<Expr>> {
2720 let attrs = try!(self.parse_or_use_outer_attributes(already_parsed_attrs));
2721 let lo = self.span.lo;
2723 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2724 let ex = match self.token {
2727 let (span, e) = interpolated_or_expr_span!(self,
2728 try!(self.parse_prefix_expr(None)));
2730 self.mk_unary(UnNot, e)
2732 token::BinOp(token::Minus) => {
2734 let (span, e) = interpolated_or_expr_span!(self,
2735 try!(self.parse_prefix_expr(None)));
2737 self.mk_unary(UnNeg, e)
2739 token::BinOp(token::Star) => {
2741 let (span, e) = interpolated_or_expr_span!(self,
2742 try!(self.parse_prefix_expr(None)));
2744 self.mk_unary(UnDeref, e)
2746 token::BinOp(token::And) | token::AndAnd => {
2747 try!(self.expect_and());
2748 let m = try!(self.parse_mutability());
2749 let (span, e) = interpolated_or_expr_span!(self,
2750 try!(self.parse_prefix_expr(None)));
2754 token::Ident(..) if self.token.is_keyword(keywords::In) => {
2756 let place = try!(self.parse_expr_res(
2757 Restrictions::RESTRICTION_NO_STRUCT_LITERAL,
2760 let blk = try!(self.parse_block());
2761 let span = blk.span;
2763 let blk_expr = self.mk_expr(span.lo, span.hi, ExprBlock(blk),
2765 ExprInPlace(place, blk_expr)
2767 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
2769 let (span, e) = interpolated_or_expr_span!(self,
2770 try!(self.parse_prefix_expr(None)));
2774 _ => return self.parse_dot_or_call_expr(Some(attrs))
2776 return Ok(self.mk_expr(lo, hi, ex, attrs));
2779 /// Parse an associative expression
2781 /// This parses an expression accounting for associativity and precedence of the operators in
2783 pub fn parse_assoc_expr(&mut self,
2784 already_parsed_attrs: Option<ThinAttributes>)
2785 -> PResult<'a, P<Expr>> {
2786 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
2789 /// Parse an associative expression with operators of at least `min_prec` precedence
2790 pub fn parse_assoc_expr_with(&mut self,
2793 -> PResult<'a, P<Expr>> {
2794 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
2797 let attrs = match lhs {
2798 LhsExpr::AttributesParsed(attrs) => Some(attrs),
2801 if self.token == token::DotDot {
2802 return self.parse_prefix_range_expr(attrs);
2804 try!(self.parse_prefix_expr(attrs))
2809 if self.expr_is_complete(&*lhs) {
2810 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
2813 self.expected_tokens.push(TokenType::Operator);
2814 while let Some(op) = AssocOp::from_token(&self.token) {
2816 let lhs_span = match self.last_token {
2817 Some(ref lt) if lt.is_interpolated() => self.last_span,
2821 let cur_op_span = self.span;
2822 let restrictions = if op.is_assign_like() {
2823 self.restrictions & Restrictions::RESTRICTION_NO_STRUCT_LITERAL
2827 if op.precedence() < min_prec {
2831 if op.is_comparison() {
2832 self.check_no_chained_comparison(&*lhs, &op);
2835 if op == AssocOp::As {
2836 let rhs = try!(self.parse_ty());
2837 lhs = self.mk_expr(lhs_span.lo, rhs.span.hi,
2838 ExprCast(lhs, rhs), None);
2840 } else if op == AssocOp::Colon {
2841 let rhs = try!(self.parse_ty());
2842 lhs = self.mk_expr(lhs_span.lo, rhs.span.hi,
2843 ExprType(lhs, rhs), None);
2845 } else if op == AssocOp::DotDot {
2846 // If we didn’t have to handle `x..`, it would be pretty easy to generalise
2847 // it to the Fixity::None code.
2849 // We have 2 alternatives here: `x..y` and `x..` The other two variants are
2850 // handled with `parse_prefix_range_expr` call above.
2851 let rhs = if self.is_at_start_of_range_notation_rhs() {
2852 let rhs = self.parse_assoc_expr_with(op.precedence() + 1,
2853 LhsExpr::NotYetParsed);
2864 let (lhs_span, rhs_span) = (lhs_span, if let Some(ref x) = rhs {
2869 let r = self.mk_range(Some(lhs), rhs);
2870 lhs = self.mk_expr(lhs_span.lo, rhs_span.hi, r, None);
2874 let rhs = try!(match op.fixity() {
2875 Fixity::Right => self.with_res(
2876 restrictions - Restrictions::RESTRICTION_STMT_EXPR,
2878 this.parse_assoc_expr_with(op.precedence(),
2879 LhsExpr::NotYetParsed)
2881 Fixity::Left => self.with_res(
2882 restrictions - Restrictions::RESTRICTION_STMT_EXPR,
2884 this.parse_assoc_expr_with(op.precedence() + 1,
2885 LhsExpr::NotYetParsed)
2887 // We currently have no non-associative operators that are not handled above by
2888 // the special cases. The code is here only for future convenience.
2889 Fixity::None => self.with_res(
2890 restrictions - Restrictions::RESTRICTION_STMT_EXPR,
2892 this.parse_assoc_expr_with(op.precedence() + 1,
2893 LhsExpr::NotYetParsed)
2898 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
2899 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
2900 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
2901 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
2902 AssocOp::Greater | AssocOp::GreaterEqual => {
2903 let ast_op = op.to_ast_binop().unwrap();
2904 let (lhs_span, rhs_span) = (lhs_span, rhs.span);
2905 let binary = self.mk_binary(codemap::respan(cur_op_span, ast_op), lhs, rhs);
2906 self.mk_expr(lhs_span.lo, rhs_span.hi, binary, None)
2909 self.mk_expr(lhs_span.lo, rhs.span.hi, ExprAssign(lhs, rhs), None),
2911 self.mk_expr(lhs_span.lo, rhs.span.hi, ExprInPlace(lhs, rhs), None),
2912 AssocOp::AssignOp(k) => {
2914 token::Plus => BiAdd,
2915 token::Minus => BiSub,
2916 token::Star => BiMul,
2917 token::Slash => BiDiv,
2918 token::Percent => BiRem,
2919 token::Caret => BiBitXor,
2920 token::And => BiBitAnd,
2921 token::Or => BiBitOr,
2922 token::Shl => BiShl,
2925 let (lhs_span, rhs_span) = (lhs_span, rhs.span);
2926 let aopexpr = self.mk_assign_op(codemap::respan(cur_op_span, aop), lhs, rhs);
2927 self.mk_expr(lhs_span.lo, rhs_span.hi, aopexpr, None)
2929 AssocOp::As | AssocOp::Colon | AssocOp::DotDot => {
2930 self.bug("As, Colon or DotDot branch reached")
2934 if op.fixity() == Fixity::None { break }
2939 /// Produce an error if comparison operators are chained (RFC #558).
2940 /// We only need to check lhs, not rhs, because all comparison ops
2941 /// have same precedence and are left-associative
2942 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
2943 debug_assert!(outer_op.is_comparison());
2945 ExprBinary(op, _, _) if op.node.is_comparison() => {
2946 // respan to include both operators
2947 let op_span = mk_sp(op.span.lo, self.span.hi);
2948 let mut err = self.diagnostic().struct_span_err(op_span,
2949 "chained comparison operators require parentheses");
2950 if op.node == BiLt && *outer_op == AssocOp::Greater {
2951 err.fileline_help(op_span,
2952 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
2960 /// Parse prefix-forms of range notation: `..expr` and `..`
2961 fn parse_prefix_range_expr(&mut self,
2962 already_parsed_attrs: Option<ThinAttributes>)
2963 -> PResult<'a, P<Expr>> {
2964 debug_assert!(self.token == token::DotDot);
2965 let attrs = try!(self.parse_or_use_outer_attributes(already_parsed_attrs));
2966 let lo = self.span.lo;
2967 let mut hi = self.span.hi;
2969 let opt_end = if self.is_at_start_of_range_notation_rhs() {
2970 // RHS must be parsed with more associativity than DotDot.
2971 let next_prec = AssocOp::from_token(&token::DotDot).unwrap().precedence() + 1;
2972 Some(try!(self.parse_assoc_expr_with(next_prec,
2973 LhsExpr::NotYetParsed)
2981 let r = self.mk_range(None, opt_end);
2982 Ok(self.mk_expr(lo, hi, r, attrs))
2985 fn is_at_start_of_range_notation_rhs(&self) -> bool {
2986 if self.token.can_begin_expr() {
2987 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
2988 if self.token == token::OpenDelim(token::Brace) {
2989 return !self.restrictions.contains(Restrictions::RESTRICTION_NO_STRUCT_LITERAL);
2997 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
2998 pub fn parse_if_expr(&mut self, attrs: ThinAttributes) -> PResult<'a, P<Expr>> {
2999 if self.check_keyword(keywords::Let) {
3000 return self.parse_if_let_expr(attrs);
3002 let lo = self.last_span.lo;
3003 let cond = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3004 let thn = try!(self.parse_block());
3005 let mut els: Option<P<Expr>> = None;
3006 let mut hi = thn.span.hi;
3007 if self.eat_keyword(keywords::Else) {
3008 let elexpr = try!(self.parse_else_expr());
3009 hi = elexpr.span.hi;
3012 Ok(self.mk_expr(lo, hi, ExprIf(cond, thn, els), attrs))
3015 /// Parse an 'if let' expression ('if' token already eaten)
3016 pub fn parse_if_let_expr(&mut self, attrs: ThinAttributes)
3017 -> PResult<'a, P<Expr>> {
3018 let lo = self.last_span.lo;
3019 try!(self.expect_keyword(keywords::Let));
3020 let pat = try!(self.parse_pat());
3021 try!(self.expect(&token::Eq));
3022 let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3023 let thn = try!(self.parse_block());
3024 let (hi, els) = if self.eat_keyword(keywords::Else) {
3025 let expr = try!(self.parse_else_expr());
3026 (expr.span.hi, Some(expr))
3030 Ok(self.mk_expr(lo, hi, ExprIfLet(pat, expr, thn, els), attrs))
3034 pub fn parse_lambda_expr(&mut self, lo: BytePos,
3035 capture_clause: CaptureClause,
3036 attrs: ThinAttributes)
3037 -> PResult<'a, P<Expr>>
3039 let decl = try!(self.parse_fn_block_decl());
3040 let body = match decl.output {
3041 DefaultReturn(_) => {
3042 // If no explicit return type is given, parse any
3043 // expr and wrap it up in a dummy block:
3044 let body_expr = try!(self.parse_expr());
3046 id: ast::DUMMY_NODE_ID,
3048 span: body_expr.span,
3049 expr: Some(body_expr),
3050 rules: DefaultBlock,
3054 // If an explicit return type is given, require a
3055 // block to appear (RFC 968).
3056 try!(self.parse_block())
3063 ExprClosure(capture_clause, decl, body), attrs))
3066 // `else` token already eaten
3067 pub fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3068 if self.eat_keyword(keywords::If) {
3069 return self.parse_if_expr(None);
3071 let blk = try!(self.parse_block());
3072 return Ok(self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk), None));
3076 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3077 pub fn parse_for_expr(&mut self, opt_ident: Option<ast::Ident>,
3079 attrs: ThinAttributes) -> PResult<'a, P<Expr>> {
3080 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3082 let pat = try!(self.parse_pat());
3083 try!(self.expect_keyword(keywords::In));
3084 let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3085 let (iattrs, loop_block) = try!(self.parse_inner_attrs_and_block());
3086 let attrs = attrs.append(iattrs.into_thin_attrs());
3088 let hi = self.last_span.hi;
3090 Ok(self.mk_expr(span_lo, hi,
3091 ExprForLoop(pat, expr, loop_block, opt_ident),
3095 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3096 pub fn parse_while_expr(&mut self, opt_ident: Option<ast::Ident>,
3098 attrs: ThinAttributes) -> PResult<'a, P<Expr>> {
3099 if self.token.is_keyword(keywords::Let) {
3100 return self.parse_while_let_expr(opt_ident, span_lo, attrs);
3102 let cond = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3103 let (iattrs, body) = try!(self.parse_inner_attrs_and_block());
3104 let attrs = attrs.append(iattrs.into_thin_attrs());
3105 let hi = body.span.hi;
3106 return Ok(self.mk_expr(span_lo, hi, ExprWhile(cond, body, opt_ident),
3110 /// Parse a 'while let' expression ('while' token already eaten)
3111 pub fn parse_while_let_expr(&mut self, opt_ident: Option<ast::Ident>,
3113 attrs: ThinAttributes) -> PResult<'a, P<Expr>> {
3114 try!(self.expect_keyword(keywords::Let));
3115 let pat = try!(self.parse_pat());
3116 try!(self.expect(&token::Eq));
3117 let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3118 let (iattrs, body) = try!(self.parse_inner_attrs_and_block());
3119 let attrs = attrs.append(iattrs.into_thin_attrs());
3120 let hi = body.span.hi;
3121 return Ok(self.mk_expr(span_lo, hi, ExprWhileLet(pat, expr, body, opt_ident), attrs));
3124 // parse `loop {...}`, `loop` token already eaten
3125 pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::Ident>,
3127 attrs: ThinAttributes) -> PResult<'a, P<Expr>> {
3128 let (iattrs, body) = try!(self.parse_inner_attrs_and_block());
3129 let attrs = attrs.append(iattrs.into_thin_attrs());
3130 let hi = body.span.hi;
3131 Ok(self.mk_expr(span_lo, hi, ExprLoop(body, opt_ident), attrs))
3134 // `match` token already eaten
3135 fn parse_match_expr(&mut self, attrs: ThinAttributes) -> PResult<'a, P<Expr>> {
3136 let match_span = self.last_span;
3137 let lo = self.last_span.lo;
3138 let discriminant = try!(self.parse_expr_res(
3139 Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3140 if let Err(mut e) = self.commit_expr_expecting(&*discriminant,
3141 token::OpenDelim(token::Brace)) {
3142 if self.token == token::Token::Semi {
3143 e.span_note(match_span, "did you mean to remove this `match` keyword?");
3147 let attrs = attrs.append(
3148 try!(self.parse_inner_attributes()).into_thin_attrs());
3149 let mut arms: Vec<Arm> = Vec::new();
3150 while self.token != token::CloseDelim(token::Brace) {
3151 arms.push(try!(self.parse_arm()));
3153 let hi = self.span.hi;
3155 return Ok(self.mk_expr(lo, hi, ExprMatch(discriminant, arms), attrs));
3158 pub fn parse_arm(&mut self) -> PResult<'a, Arm> {
3159 maybe_whole!(no_clone self, NtArm);
3161 let attrs = try!(self.parse_outer_attributes());
3162 let pats = try!(self.parse_pats());
3163 let mut guard = None;
3164 if self.eat_keyword(keywords::If) {
3165 guard = Some(try!(self.parse_expr()));
3167 try!(self.expect(&token::FatArrow));
3168 let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_STMT_EXPR, None));
3171 !classify::expr_is_simple_block(&*expr)
3172 && self.token != token::CloseDelim(token::Brace);
3175 try!(self.commit_expr(&*expr, &[token::Comma], &[token::CloseDelim(token::Brace)]));
3177 self.eat(&token::Comma);
3188 /// Parse an expression
3189 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3190 self.parse_expr_res(Restrictions::empty(), None)
3193 /// Evaluate the closure with restrictions in place.
3195 /// After the closure is evaluated, restrictions are reset.
3196 pub fn with_res<F>(&mut self, r: Restrictions, f: F) -> PResult<'a, P<Expr>>
3197 where F: FnOnce(&mut Self) -> PResult<'a, P<Expr>>
3199 let old = self.restrictions;
3200 self.restrictions = r;
3202 self.restrictions = old;
3207 /// Parse an expression, subject to the given restrictions
3208 pub fn parse_expr_res(&mut self, r: Restrictions,
3209 already_parsed_attrs: Option<ThinAttributes>)
3210 -> PResult<'a, P<Expr>> {
3211 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3214 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3215 fn parse_initializer(&mut self) -> PResult<'a, Option<P<Expr>>> {
3216 if self.check(&token::Eq) {
3218 Ok(Some(try!(self.parse_expr())))
3224 /// Parse patterns, separated by '|' s
3225 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3226 let mut pats = Vec::new();
3228 pats.push(try!(self.parse_pat()));
3229 if self.check(&token::BinOp(token::Or)) { self.bump();}
3230 else { return Ok(pats); }
3234 fn parse_pat_tuple_elements(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3235 let mut fields = vec![];
3236 if !self.check(&token::CloseDelim(token::Paren)) {
3237 fields.push(try!(self.parse_pat()));
3238 if self.look_ahead(1, |t| *t != token::CloseDelim(token::Paren)) {
3239 while self.eat(&token::Comma) &&
3240 !self.check(&token::CloseDelim(token::Paren)) {
3241 fields.push(try!(self.parse_pat()));
3244 if fields.len() == 1 {
3245 try!(self.expect(&token::Comma));
3251 fn parse_pat_vec_elements(
3253 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3254 let mut before = Vec::new();
3255 let mut slice = None;
3256 let mut after = Vec::new();
3257 let mut first = true;
3258 let mut before_slice = true;
3260 while self.token != token::CloseDelim(token::Bracket) {
3264 try!(self.expect(&token::Comma));
3266 if self.token == token::CloseDelim(token::Bracket)
3267 && (before_slice || !after.is_empty()) {
3273 if self.check(&token::DotDot) {
3276 if self.check(&token::Comma) ||
3277 self.check(&token::CloseDelim(token::Bracket)) {
3278 slice = Some(P(ast::Pat {
3279 id: ast::DUMMY_NODE_ID,
3283 before_slice = false;
3289 let subpat = try!(self.parse_pat());
3290 if before_slice && self.check(&token::DotDot) {
3292 slice = Some(subpat);
3293 before_slice = false;
3294 } else if before_slice {
3295 before.push(subpat);
3301 Ok((before, slice, after))
3304 /// Parse the fields of a struct-like pattern
3305 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<codemap::Spanned<ast::FieldPat>> , bool)> {
3306 let mut fields = Vec::new();
3307 let mut etc = false;
3308 let mut first = true;
3309 while self.token != token::CloseDelim(token::Brace) {
3313 try!(self.expect(&token::Comma));
3314 // accept trailing commas
3315 if self.check(&token::CloseDelim(token::Brace)) { break }
3318 let lo = self.span.lo;
3321 if self.check(&token::DotDot) {
3323 if self.token != token::CloseDelim(token::Brace) {
3324 let token_str = self.this_token_to_string();
3325 return Err(self.fatal(&format!("expected `{}`, found `{}`", "}",
3332 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3333 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3334 // Parsing a pattern of the form "fieldname: pat"
3335 let fieldname = try!(self.parse_ident());
3337 let pat = try!(self.parse_pat());
3339 (pat, fieldname, false)
3341 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3342 let is_box = self.eat_keyword(keywords::Box);
3343 let boxed_span_lo = self.span.lo;
3344 let is_ref = self.eat_keyword(keywords::Ref);
3345 let is_mut = self.eat_keyword(keywords::Mut);
3346 let fieldname = try!(self.parse_ident());
3347 hi = self.last_span.hi;
3349 let bind_type = match (is_ref, is_mut) {
3350 (true, true) => BindingMode::ByRef(MutMutable),
3351 (true, false) => BindingMode::ByRef(MutImmutable),
3352 (false, true) => BindingMode::ByValue(MutMutable),
3353 (false, false) => BindingMode::ByValue(MutImmutable),
3355 let fieldpath = codemap::Spanned{span:self.last_span, node:fieldname};
3356 let fieldpat = P(ast::Pat{
3357 id: ast::DUMMY_NODE_ID,
3358 node: PatIdent(bind_type, fieldpath, None),
3359 span: mk_sp(boxed_span_lo, hi),
3362 let subpat = if is_box {
3364 id: ast::DUMMY_NODE_ID,
3365 node: PatBox(fieldpat),
3366 span: mk_sp(lo, hi),
3371 (subpat, fieldname, true)
3374 fields.push(codemap::Spanned { span: mk_sp(lo, hi),
3375 node: ast::FieldPat { ident: fieldname,
3377 is_shorthand: is_shorthand }});
3379 return Ok((fields, etc));
3382 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
3383 if self.is_path_start() {
3384 let lo = self.span.lo;
3385 let (qself, path) = if self.eat_lt() {
3386 // Parse a qualified path
3388 try!(self.parse_qualified_path(NoTypesAllowed));
3391 // Parse an unqualified path
3392 (None, try!(self.parse_path(LifetimeAndTypesWithColons)))
3394 let hi = self.last_span.hi;
3395 Ok(self.mk_expr(lo, hi, ExprPath(qself, path), None))
3397 self.parse_pat_literal_maybe_minus()
3401 fn is_path_start(&self) -> bool {
3402 (self.token == token::Lt || self.token == token::ModSep
3403 || self.token.is_ident() || self.token.is_path())
3404 && !self.token.is_keyword(keywords::True) && !self.token.is_keyword(keywords::False)
3407 /// Parse a pattern.
3408 pub fn parse_pat(&mut self) -> PResult<'a, P<Pat>> {
3409 maybe_whole!(self, NtPat);
3411 let lo = self.span.lo;
3414 token::Underscore => {
3419 token::BinOp(token::And) | token::AndAnd => {
3420 // Parse &pat / &mut pat
3421 try!(self.expect_and());
3422 let mutbl = try!(self.parse_mutability());
3423 if let token::Lifetime(ident) = self.token {
3424 return Err(self.fatal(&format!("unexpected lifetime `{}` in pattern", ident)));
3427 let subpat = try!(self.parse_pat());
3428 pat = PatRegion(subpat, mutbl);
3430 token::OpenDelim(token::Paren) => {
3431 // Parse (pat,pat,pat,...) as tuple pattern
3433 let fields = try!(self.parse_pat_tuple_elements());
3434 try!(self.expect(&token::CloseDelim(token::Paren)));
3435 pat = PatTup(fields);
3437 token::OpenDelim(token::Bracket) => {
3438 // Parse [pat,pat,...] as slice pattern
3440 let (before, slice, after) = try!(self.parse_pat_vec_elements());
3441 try!(self.expect(&token::CloseDelim(token::Bracket)));
3442 pat = PatVec(before, slice, after);
3445 // At this point, token != _, &, &&, (, [
3446 if self.eat_keyword(keywords::Mut) {
3447 // Parse mut ident @ pat
3448 pat = try!(self.parse_pat_ident(BindingMode::ByValue(MutMutable)));
3449 } else if self.eat_keyword(keywords::Ref) {
3450 // Parse ref ident @ pat / ref mut ident @ pat
3451 let mutbl = try!(self.parse_mutability());
3452 pat = try!(self.parse_pat_ident(BindingMode::ByRef(mutbl)));
3453 } else if self.eat_keyword(keywords::Box) {
3455 let subpat = try!(self.parse_pat());
3456 pat = PatBox(subpat);
3457 } else if self.is_path_start() {
3458 // Parse pattern starting with a path
3459 if self.token.is_plain_ident() && self.look_ahead(1, |t| *t != token::DotDotDot &&
3460 *t != token::OpenDelim(token::Brace) &&
3461 *t != token::OpenDelim(token::Paren) &&
3462 // Contrary to its definition, a plain ident can be followed by :: in macros
3463 *t != token::ModSep) {
3464 // Plain idents have some extra abilities here compared to general paths
3465 if self.look_ahead(1, |t| *t == token::Not) {
3466 // Parse macro invocation
3467 let ident = try!(self.parse_ident());
3468 let ident_span = self.last_span;
3469 let path = ident_to_path(ident_span, ident);
3471 let delim = try!(self.expect_open_delim());
3472 let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
3473 seq_sep_none(), |p| p.parse_token_tree()));
3474 let mac = Mac_ { path: path, tts: tts, ctxt: EMPTY_CTXT };
3475 pat = PatMac(codemap::Spanned {node: mac,
3476 span: mk_sp(lo, self.last_span.hi)});
3478 // Parse ident @ pat
3479 // This can give false positives and parse nullary enums,
3480 // they are dealt with later in resolve
3481 pat = try!(self.parse_pat_ident(BindingMode::ByValue(MutImmutable)));
3484 let (qself, path) = if self.eat_lt() {
3485 // Parse a qualified path
3487 try!(self.parse_qualified_path(NoTypesAllowed));
3490 // Parse an unqualified path
3491 (None, try!(self.parse_path(LifetimeAndTypesWithColons)))
3494 token::DotDotDot => {
3496 let hi = self.last_span.hi;
3497 let begin = self.mk_expr(lo, hi, ExprPath(qself, path), None);
3499 let end = try!(self.parse_pat_range_end());
3500 pat = PatRange(begin, end);
3502 token::OpenDelim(token::Brace) => {
3503 if qself.is_some() {
3504 return Err(self.fatal("unexpected `{` after qualified path"));
3506 // Parse struct pattern
3508 let (fields, etc) = try!(self.parse_pat_fields());
3510 pat = PatStruct(path, fields, etc);
3512 token::OpenDelim(token::Paren) => {
3513 if qself.is_some() {
3514 return Err(self.fatal("unexpected `(` after qualified path"));
3516 // Parse tuple struct or enum pattern
3517 if self.look_ahead(1, |t| *t == token::DotDot) {
3518 // This is a "top constructor only" pat
3521 try!(self.expect(&token::CloseDelim(token::Paren)));
3522 pat = PatEnum(path, None);
3524 let args = try!(self.parse_enum_variant_seq(
3525 &token::OpenDelim(token::Paren),
3526 &token::CloseDelim(token::Paren),
3527 seq_sep_trailing_allowed(token::Comma),
3528 |p| p.parse_pat()));
3529 pat = PatEnum(path, Some(args));
3534 // Parse qualified path
3535 Some(qself) => PatQPath(qself, path),
3536 // Parse nullary enum
3537 None => PatEnum(path, Some(vec![]))
3543 // Try to parse everything else as literal with optional minus
3544 let begin = try!(self.parse_pat_literal_maybe_minus());
3545 if self.eat(&token::DotDotDot) {
3546 let end = try!(self.parse_pat_range_end());
3547 pat = PatRange(begin, end);
3549 pat = PatLit(begin);
3555 let hi = self.last_span.hi;
3557 id: ast::DUMMY_NODE_ID,
3559 span: mk_sp(lo, hi),
3563 /// Parse ident or ident @ pat
3564 /// used by the copy foo and ref foo patterns to give a good
3565 /// error message when parsing mistakes like ref foo(a,b)
3566 fn parse_pat_ident(&mut self,
3567 binding_mode: ast::BindingMode)
3568 -> PResult<'a, ast::Pat_> {
3569 if !self.token.is_plain_ident() {
3570 let span = self.span;
3571 let tok_str = self.this_token_to_string();
3572 return Err(self.span_fatal(span,
3573 &format!("expected identifier, found `{}`", tok_str)))
3575 let ident = try!(self.parse_ident());
3576 let last_span = self.last_span;
3577 let name = codemap::Spanned{span: last_span, node: ident};
3578 let sub = if self.eat(&token::At) {
3579 Some(try!(self.parse_pat()))
3584 // just to be friendly, if they write something like
3586 // we end up here with ( as the current token. This shortly
3587 // leads to a parse error. Note that if there is no explicit
3588 // binding mode then we do not end up here, because the lookahead
3589 // will direct us over to parse_enum_variant()
3590 if self.token == token::OpenDelim(token::Paren) {
3591 let last_span = self.last_span;
3592 return Err(self.span_fatal(
3594 "expected identifier, found enum pattern"))
3597 Ok(PatIdent(binding_mode, name, sub))
3600 /// Parse a local variable declaration
3601 fn parse_local(&mut self, attrs: ThinAttributes) -> PResult<'a, P<Local>> {
3602 let lo = self.span.lo;
3603 let pat = try!(self.parse_pat());
3606 if self.eat(&token::Colon) {
3607 ty = Some(try!(self.parse_ty_sum()));
3609 let init = try!(self.parse_initializer());
3614 id: ast::DUMMY_NODE_ID,
3615 span: mk_sp(lo, self.last_span.hi),
3620 /// Parse a "let" stmt
3621 fn parse_let(&mut self, attrs: ThinAttributes) -> PResult<'a, P<Decl>> {
3622 let lo = self.span.lo;
3623 let local = try!(self.parse_local(attrs));
3624 Ok(P(spanned(lo, self.last_span.hi, DeclLocal(local))))
3627 /// Parse a structure field
3628 fn parse_name_and_ty(&mut self, pr: Visibility,
3629 attrs: Vec<Attribute> ) -> PResult<'a, StructField> {
3631 Inherited => self.span.lo,
3632 Public => self.last_span.lo,
3634 if !self.token.is_plain_ident() {
3635 return Err(self.fatal("expected ident"));
3637 let name = try!(self.parse_ident());
3638 try!(self.expect(&token::Colon));
3639 let ty = try!(self.parse_ty_sum());
3640 Ok(spanned(lo, self.last_span.hi, ast::StructField_ {
3641 kind: NamedField(name, pr),
3642 id: ast::DUMMY_NODE_ID,
3648 /// Emit an expected item after attributes error.
3649 fn expected_item_err(&self, attrs: &[Attribute]) {
3650 let message = match attrs.last() {
3651 Some(&Attribute { node: ast::Attribute_ { is_sugared_doc: true, .. }, .. }) => {
3652 "expected item after doc comment"
3654 _ => "expected item after attributes",
3657 self.span_err(self.last_span, message);
3660 /// Parse a statement. may include decl.
3661 pub fn parse_stmt(&mut self) -> PResult<'a, Option<P<Stmt>>> {
3662 Ok(try!(self.parse_stmt_()).map(P))
3665 fn parse_stmt_(&mut self) -> PResult<'a, Option<Stmt>> {
3666 maybe_whole!(Some deref self, NtStmt);
3668 let attrs = try!(self.parse_outer_attributes());
3669 let lo = self.span.lo;
3671 Ok(Some(if self.check_keyword(keywords::Let) {
3672 try!(self.expect_keyword(keywords::Let));
3673 let decl = try!(self.parse_let(attrs.into_thin_attrs()));
3674 let hi = decl.span.hi;
3675 let stmt = StmtDecl(decl, ast::DUMMY_NODE_ID);
3676 spanned(lo, hi, stmt)
3677 } else if self.token.is_ident()
3678 && !self.token.is_any_keyword()
3679 && self.look_ahead(1, |t| *t == token::Not) {
3680 // it's a macro invocation:
3682 // Potential trouble: if we allow macros with paths instead of
3683 // idents, we'd need to look ahead past the whole path here...
3684 let pth = try!(self.parse_path(NoTypesAllowed));
3687 let id = match self.token {
3688 token::OpenDelim(_) => token::special_idents::invalid, // no special identifier
3689 _ => try!(self.parse_ident()),
3692 // check that we're pointing at delimiters (need to check
3693 // again after the `if`, because of `parse_ident`
3694 // consuming more tokens).
3695 let delim = match self.token {
3696 token::OpenDelim(delim) => delim,
3698 // we only expect an ident if we didn't parse one
3700 let ident_str = if id.name == token::special_idents::invalid.name {
3705 let tok_str = self.this_token_to_string();
3706 return Err(self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
3712 let tts = try!(self.parse_unspanned_seq(
3713 &token::OpenDelim(delim),
3714 &token::CloseDelim(delim),
3716 |p| p.parse_token_tree()
3718 let hi = self.last_span.hi;
3720 let style = if delim == token::Brace {
3723 MacStmtWithoutBraces
3726 if id.name == token::special_idents::invalid.name {
3727 let stmt = StmtMac(P(spanned(lo,
3729 Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT })),
3731 attrs.into_thin_attrs());
3732 spanned(lo, hi, stmt)
3734 // if it has a special ident, it's definitely an item
3736 // Require a semicolon or braces.
3737 if style != MacStmtWithBraces {
3738 if !self.eat(&token::Semi) {
3739 let last_span = self.last_span;
3740 self.span_err(last_span,
3741 "macros that expand to items must \
3742 either be surrounded with braces or \
3743 followed by a semicolon");
3746 spanned(lo, hi, StmtDecl(
3747 P(spanned(lo, hi, DeclItem(
3749 lo, hi, id /*id is good here*/,
3750 ItemMac(spanned(lo, hi,
3751 Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT })),
3752 Inherited, attrs)))),
3753 ast::DUMMY_NODE_ID))
3756 // FIXME: Bad copy of attrs
3757 match try!(self.parse_item_(attrs.clone(), false, true)) {
3760 let decl = P(spanned(lo, hi, DeclItem(i)));
3761 spanned(lo, hi, StmtDecl(decl, ast::DUMMY_NODE_ID))
3764 let unused_attrs = |attrs: &[_], s: &mut Self| {
3765 if attrs.len() > 0 {
3767 "expected statement after outer attribute");
3771 // Do not attempt to parse an expression if we're done here.
3772 if self.token == token::Semi {
3773 unused_attrs(&attrs, self);
3778 if self.token == token::CloseDelim(token::Brace) {
3779 unused_attrs(&attrs, self);
3783 // Remainder are line-expr stmts.
3784 let e = try!(self.parse_expr_res(
3785 Restrictions::RESTRICTION_STMT_EXPR, Some(attrs.into_thin_attrs())));
3787 let stmt = StmtExpr(e, ast::DUMMY_NODE_ID);
3788 spanned(lo, hi, stmt)
3794 /// Is this expression a successfully-parsed statement?
3795 fn expr_is_complete(&mut self, e: &Expr) -> bool {
3796 self.restrictions.contains(Restrictions::RESTRICTION_STMT_EXPR) &&
3797 !classify::expr_requires_semi_to_be_stmt(e)
3800 /// Parse a block. No inner attrs are allowed.
3801 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
3802 maybe_whole!(no_clone self, NtBlock);
3804 let lo = self.span.lo;
3806 if !self.eat(&token::OpenDelim(token::Brace)) {
3808 let tok = self.this_token_to_string();
3809 return Err(self.span_fatal_help(sp,
3810 &format!("expected `{{`, found `{}`", tok),
3811 "place this code inside a block"));
3814 self.parse_block_tail(lo, DefaultBlock)
3817 /// Parse a block. Inner attrs are allowed.
3818 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
3819 maybe_whole!(pair_empty self, NtBlock);
3821 let lo = self.span.lo;
3822 try!(self.expect(&token::OpenDelim(token::Brace)));
3823 Ok((try!(self.parse_inner_attributes()),
3824 try!(self.parse_block_tail(lo, DefaultBlock))))
3827 /// Parse the rest of a block expression or function body
3828 /// Precondition: already parsed the '{'.
3829 fn parse_block_tail(&mut self, lo: BytePos, s: BlockCheckMode) -> PResult<'a, P<Block>> {
3830 let mut stmts = vec![];
3831 let mut expr = None;
3833 while !self.eat(&token::CloseDelim(token::Brace)) {
3834 let Spanned {node, span} = if let Some(s) = try!(self.parse_stmt_()) {
3837 // Found only `;` or `}`.
3842 try!(self.handle_expression_like_statement(e, span, &mut stmts, &mut expr));
3844 StmtMac(mac, MacStmtWithoutBraces, attrs) => {
3845 // statement macro without braces; might be an
3846 // expr depending on whether a semicolon follows
3849 stmts.push(P(Spanned {
3850 node: StmtMac(mac, MacStmtWithSemicolon, attrs),
3851 span: mk_sp(span.lo, self.span.hi),
3856 let e = self.mk_mac_expr(span.lo, span.hi,
3857 mac.and_then(|m| m.node),
3860 let e = try!(self.parse_dot_or_call_expr_with(e, lo, attrs));
3861 let e = try!(self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e)));
3862 try!(self.handle_expression_like_statement(
3870 StmtMac(m, style, attrs) => {
3871 // statement macro; might be an expr
3874 stmts.push(P(Spanned {
3875 node: StmtMac(m, MacStmtWithSemicolon, attrs),
3876 span: mk_sp(span.lo, self.span.hi),
3880 token::CloseDelim(token::Brace) => {
3881 // if a block ends in `m!(arg)` without
3882 // a `;`, it must be an expr
3883 expr = Some(self.mk_mac_expr(span.lo, span.hi,
3884 m.and_then(|x| x.node),
3888 stmts.push(P(Spanned {
3889 node: StmtMac(m, style, attrs),
3895 _ => { // all other kinds of statements:
3896 let mut hi = span.hi;
3897 if classify::stmt_ends_with_semi(&node) {
3898 try!(self.commit_stmt_expecting(token::Semi));
3899 hi = self.last_span.hi;
3902 stmts.push(P(Spanned {
3904 span: mk_sp(span.lo, hi)
3913 id: ast::DUMMY_NODE_ID,
3915 span: mk_sp(lo, self.last_span.hi),
3919 fn handle_expression_like_statement(
3923 stmts: &mut Vec<P<Stmt>>,
3924 last_block_expr: &mut Option<P<Expr>>) -> PResult<'a, ()> {
3925 // expression without semicolon
3926 if classify::expr_requires_semi_to_be_stmt(&*e) {
3927 // Just check for errors and recover; do not eat semicolon yet.
3928 try!(self.commit_stmt(&[],
3929 &[token::Semi, token::CloseDelim(token::Brace)]));
3935 let span_with_semi = Span {
3937 hi: self.last_span.hi,
3938 expn_id: span.expn_id,
3940 stmts.push(P(Spanned {
3941 node: StmtSemi(e, ast::DUMMY_NODE_ID),
3942 span: span_with_semi,
3945 token::CloseDelim(token::Brace) => *last_block_expr = Some(e),
3947 stmts.push(P(Spanned {
3948 node: StmtExpr(e, ast::DUMMY_NODE_ID),
3956 // Parses a sequence of bounds if a `:` is found,
3957 // otherwise returns empty list.
3958 fn parse_colon_then_ty_param_bounds(&mut self,
3959 mode: BoundParsingMode)
3960 -> PResult<'a, TyParamBounds>
3962 if !self.eat(&token::Colon) {
3965 self.parse_ty_param_bounds(mode)
3969 // matches bounds = ( boundseq )?
3970 // where boundseq = ( polybound + boundseq ) | polybound
3971 // and polybound = ( 'for' '<' 'region '>' )? bound
3972 // and bound = 'region | trait_ref
3973 fn parse_ty_param_bounds(&mut self,
3974 mode: BoundParsingMode)
3975 -> PResult<'a, TyParamBounds>
3977 let mut result = vec!();
3979 let question_span = self.span;
3980 let ate_question = self.eat(&token::Question);
3982 token::Lifetime(lifetime) => {
3984 self.span_err(question_span,
3985 "`?` may only modify trait bounds, not lifetime bounds");
3987 result.push(RegionTyParamBound(ast::Lifetime {
3988 id: ast::DUMMY_NODE_ID,
3994 token::ModSep | token::Ident(..) => {
3995 let poly_trait_ref = try!(self.parse_poly_trait_ref());
3996 let modifier = if ate_question {
3997 if mode == BoundParsingMode::Modified {
3998 TraitBoundModifier::Maybe
4000 self.span_err(question_span,
4002 TraitBoundModifier::None
4005 TraitBoundModifier::None
4007 result.push(TraitTyParamBound(poly_trait_ref, modifier))
4012 if !self.eat(&token::BinOp(token::Plus)) {
4017 return Ok(P::from_vec(result));
4020 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
4021 fn parse_ty_param(&mut self) -> PResult<'a, TyParam> {
4022 let span = self.span;
4023 let ident = try!(self.parse_ident());
4025 let bounds = try!(self.parse_colon_then_ty_param_bounds(BoundParsingMode::Modified));
4027 let default = if self.check(&token::Eq) {
4029 Some(try!(self.parse_ty_sum()))
4036 id: ast::DUMMY_NODE_ID,
4043 /// Parse a set of optional generic type parameter declarations. Where
4044 /// clauses are not parsed here, and must be added later via
4045 /// `parse_where_clause()`.
4047 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
4048 /// | ( < lifetimes , typaramseq ( , )? > )
4049 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
4050 pub fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
4051 maybe_whole!(self, NtGenerics);
4053 if self.eat(&token::Lt) {
4054 let lifetime_defs = try!(self.parse_lifetime_defs());
4055 let mut seen_default = false;
4056 let ty_params = try!(self.parse_seq_to_gt(Some(token::Comma), |p| {
4057 try!(p.forbid_lifetime());
4058 let ty_param = try!(p.parse_ty_param());
4059 if ty_param.default.is_some() {
4060 seen_default = true;
4061 } else if seen_default {
4062 let last_span = p.last_span;
4063 p.span_err(last_span,
4064 "type parameters with a default must be trailing");
4069 lifetimes: lifetime_defs,
4070 ty_params: ty_params,
4071 where_clause: WhereClause {
4072 id: ast::DUMMY_NODE_ID,
4073 predicates: Vec::new(),
4077 Ok(ast::Generics::default())
4081 fn parse_generic_values_after_lt(&mut self) -> PResult<'a, (Vec<ast::Lifetime>,
4083 Vec<P<TypeBinding>>)> {
4084 let span_lo = self.span.lo;
4085 let lifetimes = try!(self.parse_lifetimes(token::Comma));
4087 let missing_comma = !lifetimes.is_empty() &&
4088 !self.token.is_like_gt() &&
4090 .as_ref().map_or(true,
4091 |x| &**x != &token::Comma);
4095 let msg = format!("expected `,` or `>` after lifetime \
4097 self.this_token_to_string());
4098 let mut err = self.diagnostic().struct_span_err(self.span, &msg);
4100 let span_hi = self.span.hi;
4101 let span_hi = match self.parse_ty() {
4102 Ok(..) => self.span.hi,
4103 Err(ref mut err) => {
4109 let msg = format!("did you mean a single argument type &'a Type, \
4110 or did you mean the comma-separated arguments \
4112 err.span_note(mk_sp(span_lo, span_hi), &msg);
4115 self.abort_if_errors()
4118 // First parse types.
4119 let (types, returned) = try!(self.parse_seq_to_gt_or_return(
4122 try!(p.forbid_lifetime());
4123 if p.look_ahead(1, |t| t == &token::Eq) {
4126 Ok(Some(try!(p.parse_ty_sum())))
4131 // If we found the `>`, don't continue.
4133 return Ok((lifetimes, types.into_vec(), Vec::new()));
4136 // Then parse type bindings.
4137 let bindings = try!(self.parse_seq_to_gt(
4140 try!(p.forbid_lifetime());
4142 let ident = try!(p.parse_ident());
4143 let found_eq = p.eat(&token::Eq);
4146 p.span_warn(span, "whoops, no =?");
4148 let ty = try!(p.parse_ty());
4149 let hi = ty.span.hi;
4150 let span = mk_sp(lo, hi);
4151 return Ok(P(TypeBinding{id: ast::DUMMY_NODE_ID,
4158 Ok((lifetimes, types.into_vec(), bindings.into_vec()))
4161 fn forbid_lifetime(&mut self) -> PResult<'a, ()> {
4162 if self.token.is_lifetime() {
4163 let span = self.span;
4164 return Err(self.span_fatal(span, "lifetime parameters must be declared \
4165 prior to type parameters"))
4170 /// Parses an optional `where` clause and places it in `generics`.
4173 /// where T : Trait<U, V> + 'b, 'a : 'b
4175 pub fn parse_where_clause(&mut self) -> PResult<'a, ast::WhereClause> {
4176 maybe_whole!(self, NtWhereClause);
4178 let mut where_clause = WhereClause {
4179 id: ast::DUMMY_NODE_ID,
4180 predicates: Vec::new(),
4183 if !self.eat_keyword(keywords::Where) {
4184 return Ok(where_clause);
4187 let mut parsed_something = false;
4189 let lo = self.span.lo;
4191 token::OpenDelim(token::Brace) => {
4195 token::Lifetime(..) => {
4196 let bounded_lifetime =
4197 try!(self.parse_lifetime());
4199 self.eat(&token::Colon);
4202 try!(self.parse_lifetimes(token::BinOp(token::Plus)));
4204 let hi = self.last_span.hi;
4205 let span = mk_sp(lo, hi);
4207 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
4208 ast::WhereRegionPredicate {
4210 lifetime: bounded_lifetime,
4215 parsed_something = true;
4219 let bound_lifetimes = if self.eat_keyword(keywords::For) {
4220 // Higher ranked constraint.
4221 try!(self.expect(&token::Lt));
4222 let lifetime_defs = try!(self.parse_lifetime_defs());
4223 try!(self.expect_gt());
4229 let bounded_ty = try!(self.parse_ty());
4231 if self.eat(&token::Colon) {
4232 let bounds = try!(self.parse_ty_param_bounds(BoundParsingMode::Bare));
4233 let hi = self.last_span.hi;
4234 let span = mk_sp(lo, hi);
4236 if bounds.is_empty() {
4238 "each predicate in a `where` clause must have \
4239 at least one bound in it");
4242 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
4243 ast::WhereBoundPredicate {
4245 bound_lifetimes: bound_lifetimes,
4246 bounded_ty: bounded_ty,
4250 parsed_something = true;
4251 } else if self.eat(&token::Eq) {
4252 // let ty = try!(self.parse_ty());
4253 let hi = self.last_span.hi;
4254 let span = mk_sp(lo, hi);
4255 // where_clause.predicates.push(
4256 // ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
4257 // id: ast::DUMMY_NODE_ID,
4259 // path: panic!("NYI"), //bounded_ty,
4262 // parsed_something = true;
4265 "equality constraints are not yet supported \
4266 in where clauses (#20041)");
4268 let last_span = self.last_span;
4269 self.span_err(last_span,
4270 "unexpected token in `where` clause");
4275 if !self.eat(&token::Comma) {
4280 if !parsed_something {
4281 let last_span = self.last_span;
4282 self.span_err(last_span,
4283 "a `where` clause must have at least one predicate \
4290 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
4291 -> PResult<'a, (Vec<Arg> , bool)> {
4293 let mut args: Vec<Option<Arg>> =
4294 try!(self.parse_unspanned_seq(
4295 &token::OpenDelim(token::Paren),
4296 &token::CloseDelim(token::Paren),
4297 seq_sep_trailing_allowed(token::Comma),
4299 if p.token == token::DotDotDot {
4302 if p.token != token::CloseDelim(token::Paren) {
4304 return Err(p.span_fatal(span,
4305 "`...` must be last in argument list for variadic function"))
4309 return Err(p.span_fatal(span,
4310 "only foreign functions are allowed to be variadic"))
4314 Ok(Some(try!(p.parse_arg_general(named_args))))
4319 let variadic = match args.pop() {
4322 // Need to put back that last arg
4329 if variadic && args.is_empty() {
4331 "variadic function must be declared with at least one named argument");
4334 let args = args.into_iter().map(|x| x.unwrap()).collect();
4336 Ok((args, variadic))
4339 /// Parse the argument list and result type of a function declaration
4340 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> {
4342 let (args, variadic) = try!(self.parse_fn_args(true, allow_variadic));
4343 let ret_ty = try!(self.parse_ret_ty());
4352 fn is_self_ident(&mut self) -> bool {
4354 token::Ident(id, token::Plain) => id.name == special_idents::self_.name,
4359 fn expect_self_ident(&mut self) -> PResult<'a, ast::Ident> {
4361 token::Ident(id, token::Plain) if id.name == special_idents::self_.name => {
4366 let token_str = self.this_token_to_string();
4367 return Err(self.fatal(&format!("expected `self`, found `{}`",
4373 fn is_self_type_ident(&mut self) -> bool {
4375 token::Ident(id, token::Plain) => id.name == special_idents::type_self.name,
4380 fn expect_self_type_ident(&mut self) -> PResult<'a, ast::Ident> {
4382 token::Ident(id, token::Plain) if id.name == special_idents::type_self.name => {
4387 let token_str = self.this_token_to_string();
4388 Err(self.fatal(&format!("expected `Self`, found `{}`",
4394 /// Parse the argument list and result type of a function
4395 /// that may have a self type.
4396 fn parse_fn_decl_with_self<F>(&mut self,
4397 parse_arg_fn: F) -> PResult<'a, (ExplicitSelf, P<FnDecl>)> where
4398 F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
4400 fn maybe_parse_borrowed_explicit_self<'b>(this: &mut Parser<'b>)
4401 -> PResult<'b, ast::ExplicitSelf_> {
4402 // The following things are possible to see here:
4407 // fn(&'lt mut self)
4409 // We already know that the current token is `&`.
4411 if this.look_ahead(1, |t| t.is_keyword(keywords::SelfValue)) {
4413 Ok(SelfRegion(None, MutImmutable, try!(this.expect_self_ident())))
4414 } else if this.look_ahead(1, |t| t.is_mutability()) &&
4415 this.look_ahead(2, |t| t.is_keyword(keywords::SelfValue)) {
4417 let mutability = try!(this.parse_mutability());
4418 Ok(SelfRegion(None, mutability, try!(this.expect_self_ident())))
4419 } else if this.look_ahead(1, |t| t.is_lifetime()) &&
4420 this.look_ahead(2, |t| t.is_keyword(keywords::SelfValue)) {
4422 let lifetime = try!(this.parse_lifetime());
4423 Ok(SelfRegion(Some(lifetime), MutImmutable, try!(this.expect_self_ident())))
4424 } else if this.look_ahead(1, |t| t.is_lifetime()) &&
4425 this.look_ahead(2, |t| t.is_mutability()) &&
4426 this.look_ahead(3, |t| t.is_keyword(keywords::SelfValue)) {
4428 let lifetime = try!(this.parse_lifetime());
4429 let mutability = try!(this.parse_mutability());
4430 Ok(SelfRegion(Some(lifetime), mutability, try!(this.expect_self_ident())))
4436 try!(self.expect(&token::OpenDelim(token::Paren)));
4438 // A bit of complexity and lookahead is needed here in order to be
4439 // backwards compatible.
4440 let lo = self.span.lo;
4441 let mut self_ident_lo = self.span.lo;
4442 let mut self_ident_hi = self.span.hi;
4444 let mut mutbl_self = MutImmutable;
4445 let explicit_self = match self.token {
4446 token::BinOp(token::And) => {
4447 let eself = try!(maybe_parse_borrowed_explicit_self(self));
4448 self_ident_lo = self.last_span.lo;
4449 self_ident_hi = self.last_span.hi;
4452 token::BinOp(token::Star) => {
4453 // Possibly "*self" or "*mut self" -- not supported. Try to avoid
4454 // emitting cryptic "unexpected token" errors.
4456 let _mutability = if self.token.is_mutability() {
4457 try!(self.parse_mutability())
4461 if self.is_self_ident() {
4462 let span = self.span;
4463 self.span_err(span, "cannot pass self by raw pointer");
4466 // error case, making bogus self ident:
4467 SelfValue(special_idents::self_)
4469 token::Ident(..) => {
4470 if self.is_self_ident() {
4471 let self_ident = try!(self.expect_self_ident());
4473 // Determine whether this is the fully explicit form, `self:
4475 if self.eat(&token::Colon) {
4476 SelfExplicit(try!(self.parse_ty_sum()), self_ident)
4478 SelfValue(self_ident)
4480 } else if self.token.is_mutability() &&
4481 self.look_ahead(1, |t| t.is_keyword(keywords::SelfValue)) {
4482 mutbl_self = try!(self.parse_mutability());
4483 let self_ident = try!(self.expect_self_ident());
4485 // Determine whether this is the fully explicit form,
4487 if self.eat(&token::Colon) {
4488 SelfExplicit(try!(self.parse_ty_sum()), self_ident)
4490 SelfValue(self_ident)
4499 let explicit_self_sp = mk_sp(self_ident_lo, self_ident_hi);
4501 // shared fall-through for the three cases below. borrowing prevents simply
4502 // writing this as a closure
4503 macro_rules! parse_remaining_arguments {
4506 // If we parsed a self type, expect a comma before the argument list.
4510 let sep = seq_sep_trailing_allowed(token::Comma);
4511 let mut fn_inputs = try!(self.parse_seq_to_before_end(
4512 &token::CloseDelim(token::Paren),
4516 fn_inputs.insert(0, Arg::new_self(explicit_self_sp, mutbl_self, $self_id));
4519 token::CloseDelim(token::Paren) => {
4520 vec!(Arg::new_self(explicit_self_sp, mutbl_self, $self_id))
4523 let token_str = self.this_token_to_string();
4524 return Err(self.fatal(&format!("expected `,` or `)`, found `{}`",
4531 let fn_inputs = match explicit_self {
4533 let sep = seq_sep_trailing_allowed(token::Comma);
4534 try!(self.parse_seq_to_before_end(&token::CloseDelim(token::Paren),
4537 SelfValue(id) => parse_remaining_arguments!(id),
4538 SelfRegion(_,_,id) => parse_remaining_arguments!(id),
4539 SelfExplicit(_,id) => parse_remaining_arguments!(id),
4543 try!(self.expect(&token::CloseDelim(token::Paren)));
4545 let hi = self.span.hi;
4547 let ret_ty = try!(self.parse_ret_ty());
4549 let fn_decl = P(FnDecl {
4555 Ok((spanned(lo, hi, explicit_self), fn_decl))
4558 // parse the |arg, arg| header on a lambda
4559 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
4560 let inputs_captures = {
4561 if self.eat(&token::OrOr) {
4564 try!(self.expect(&token::BinOp(token::Or)));
4565 try!(self.parse_obsolete_closure_kind());
4566 let args = try!(self.parse_seq_to_before_end(
4567 &token::BinOp(token::Or),
4568 seq_sep_trailing_allowed(token::Comma),
4569 |p| p.parse_fn_block_arg()
4575 let output = try!(self.parse_ret_ty());
4578 inputs: inputs_captures,
4584 /// Parse the name and optional generic types of a function header.
4585 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
4586 let id = try!(self.parse_ident());
4587 let generics = try!(self.parse_generics());
4591 fn mk_item(&mut self, lo: BytePos, hi: BytePos, ident: Ident,
4592 node: Item_, vis: Visibility,
4593 attrs: Vec<Attribute>) -> P<Item> {
4597 id: ast::DUMMY_NODE_ID,
4604 /// Parse an item-position function declaration.
4605 fn parse_item_fn(&mut self,
4607 constness: Constness,
4609 -> PResult<'a, ItemInfo> {
4610 let (ident, mut generics) = try!(self.parse_fn_header());
4611 let decl = try!(self.parse_fn_decl(false));
4612 generics.where_clause = try!(self.parse_where_clause());
4613 let (inner_attrs, body) = try!(self.parse_inner_attrs_and_block());
4614 Ok((ident, ItemFn(decl, unsafety, constness, abi, generics, body), Some(inner_attrs)))
4617 /// true if we are looking at `const ID`, false for things like `const fn` etc
4618 pub fn is_const_item(&mut self) -> bool {
4619 self.token.is_keyword(keywords::Const) &&
4620 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
4621 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
4624 /// parses all the "front matter" for a `fn` declaration, up to
4625 /// and including the `fn` keyword:
4629 /// - `const unsafe fn`
4632 pub fn parse_fn_front_matter(&mut self)
4633 -> PResult<'a, (ast::Constness, ast::Unsafety, abi::Abi)> {
4634 let is_const_fn = self.eat_keyword(keywords::Const);
4635 let unsafety = try!(self.parse_unsafety());
4636 let (constness, unsafety, abi) = if is_const_fn {
4637 (Constness::Const, unsafety, abi::Rust)
4639 let abi = if self.eat_keyword(keywords::Extern) {
4640 try!(self.parse_opt_abi()).unwrap_or(abi::C)
4644 (Constness::NotConst, unsafety, abi)
4646 try!(self.expect_keyword(keywords::Fn));
4647 Ok((constness, unsafety, abi))
4650 /// Parse an impl item.
4651 pub fn parse_impl_item(&mut self) -> PResult<'a, P<ImplItem>> {
4652 maybe_whole!(no_clone self, NtImplItem);
4654 let mut attrs = try!(self.parse_outer_attributes());
4655 let lo = self.span.lo;
4656 let vis = try!(self.parse_visibility());
4657 let (name, node) = if self.eat_keyword(keywords::Type) {
4658 let name = try!(self.parse_ident());
4659 try!(self.expect(&token::Eq));
4660 let typ = try!(self.parse_ty_sum());
4661 try!(self.expect(&token::Semi));
4662 (name, ast::ImplItemKind::Type(typ))
4663 } else if self.is_const_item() {
4664 try!(self.expect_keyword(keywords::Const));
4665 let name = try!(self.parse_ident());
4666 try!(self.expect(&token::Colon));
4667 let typ = try!(self.parse_ty_sum());
4668 try!(self.expect(&token::Eq));
4669 let expr = try!(self.parse_expr());
4670 try!(self.commit_expr_expecting(&expr, token::Semi));
4671 (name, ast::ImplItemKind::Const(typ, expr))
4673 let (name, inner_attrs, node) = try!(self.parse_impl_method(vis));
4674 attrs.extend(inner_attrs);
4679 id: ast::DUMMY_NODE_ID,
4680 span: mk_sp(lo, self.last_span.hi),
4688 fn complain_if_pub_macro(&mut self, visa: Visibility, span: Span) {
4691 let is_macro_rules: bool = match self.token {
4692 token::Ident(sid, _) => sid.name == intern("macro_rules"),
4696 self.diagnostic().struct_span_err(span, "can't qualify macro_rules \
4697 invocation with `pub`")
4698 .fileline_help(span, "did you mean #[macro_export]?")
4701 self.diagnostic().struct_span_err(span, "can't qualify macro \
4702 invocation with `pub`")
4703 .fileline_help(span, "try adjusting the macro to put `pub` \
4704 inside the invocation")
4712 /// Parse a method or a macro invocation in a trait impl.
4713 fn parse_impl_method(&mut self, vis: Visibility)
4714 -> PResult<'a, (Ident, Vec<ast::Attribute>, ast::ImplItemKind)> {
4715 // code copied from parse_macro_use_or_failure... abstraction!
4716 if !self.token.is_any_keyword()
4717 && self.look_ahead(1, |t| *t == token::Not)
4718 && (self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren))
4719 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) {
4722 let last_span = self.last_span;
4723 self.complain_if_pub_macro(vis, last_span);
4725 let lo = self.span.lo;
4726 let pth = try!(self.parse_path(NoTypesAllowed));
4727 try!(self.expect(&token::Not));
4729 // eat a matched-delimiter token tree:
4730 let delim = try!(self.expect_open_delim());
4731 let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
4733 |p| p.parse_token_tree()));
4734 let m_ = Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT };
4735 let m: ast::Mac = codemap::Spanned { node: m_,
4737 self.last_span.hi) };
4738 if delim != token::Brace {
4739 try!(self.expect(&token::Semi))
4741 Ok((token::special_idents::invalid, vec![], ast::ImplItemKind::Macro(m)))
4743 let (constness, unsafety, abi) = try!(self.parse_fn_front_matter());
4744 let ident = try!(self.parse_ident());
4745 let mut generics = try!(self.parse_generics());
4746 let (explicit_self, decl) = try!(self.parse_fn_decl_with_self(|p| {
4749 generics.where_clause = try!(self.parse_where_clause());
4750 let (inner_attrs, body) = try!(self.parse_inner_attrs_and_block());
4751 Ok((ident, inner_attrs, ast::ImplItemKind::Method(ast::MethodSig {
4754 explicit_self: explicit_self,
4756 constness: constness,
4762 /// Parse trait Foo { ... }
4763 fn parse_item_trait(&mut self, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
4765 let ident = try!(self.parse_ident());
4766 let mut tps = try!(self.parse_generics());
4768 // Parse supertrait bounds.
4769 let bounds = try!(self.parse_colon_then_ty_param_bounds(BoundParsingMode::Bare));
4771 tps.where_clause = try!(self.parse_where_clause());
4773 let meths = try!(self.parse_trait_items());
4774 Ok((ident, ItemTrait(unsafety, tps, bounds, meths), None))
4777 /// Parses items implementations variants
4778 /// impl<T> Foo { ... }
4779 /// impl<T> ToString for &'static T { ... }
4780 /// impl Send for .. {}
4781 fn parse_item_impl(&mut self, unsafety: ast::Unsafety) -> PResult<'a, ItemInfo> {
4782 let impl_span = self.span;
4784 // First, parse type parameters if necessary.
4785 let mut generics = try!(self.parse_generics());
4787 // Special case: if the next identifier that follows is '(', don't
4788 // allow this to be parsed as a trait.
4789 let could_be_trait = self.token != token::OpenDelim(token::Paren);
4791 let neg_span = self.span;
4792 let polarity = if self.eat(&token::Not) {
4793 ast::ImplPolarity::Negative
4795 ast::ImplPolarity::Positive
4799 let mut ty = try!(self.parse_ty_sum());
4801 // Parse traits, if necessary.
4802 let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) {
4803 // New-style trait. Reinterpret the type as a trait.
4805 TyPath(None, ref path) => {
4807 path: (*path).clone(),
4812 self.span_err(ty.span, "not a trait");
4818 ast::ImplPolarity::Negative => {
4819 // This is a negated type implementation
4820 // `impl !MyType {}`, which is not allowed.
4821 self.span_err(neg_span, "inherent implementation can't be negated");
4828 if opt_trait.is_some() && self.eat(&token::DotDot) {
4829 if generics.is_parameterized() {
4830 self.span_err(impl_span, "default trait implementations are not \
4831 allowed to have generics");
4834 try!(self.expect(&token::OpenDelim(token::Brace)));
4835 try!(self.expect(&token::CloseDelim(token::Brace)));
4836 Ok((ast_util::impl_pretty_name(&opt_trait, None),
4837 ItemDefaultImpl(unsafety, opt_trait.unwrap()), None))
4839 if opt_trait.is_some() {
4840 ty = try!(self.parse_ty_sum());
4842 generics.where_clause = try!(self.parse_where_clause());
4844 try!(self.expect(&token::OpenDelim(token::Brace)));
4845 let attrs = try!(self.parse_inner_attributes());
4847 let mut impl_items = vec![];
4848 while !self.eat(&token::CloseDelim(token::Brace)) {
4849 impl_items.push(try!(self.parse_impl_item()));
4852 Ok((ast_util::impl_pretty_name(&opt_trait, Some(&*ty)),
4853 ItemImpl(unsafety, polarity, generics, opt_trait, ty, impl_items),
4858 /// Parse a::B<String,i32>
4859 fn parse_trait_ref(&mut self) -> PResult<'a, TraitRef> {
4861 path: try!(self.parse_path(LifetimeAndTypesWithoutColons)),
4862 ref_id: ast::DUMMY_NODE_ID,
4866 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<ast::LifetimeDef>> {
4867 if self.eat_keyword(keywords::For) {
4868 try!(self.expect(&token::Lt));
4869 let lifetime_defs = try!(self.parse_lifetime_defs());
4870 try!(self.expect_gt());
4877 /// Parse for<'l> a::B<String,i32>
4878 fn parse_poly_trait_ref(&mut self) -> PResult<'a, PolyTraitRef> {
4879 let lo = self.span.lo;
4880 let lifetime_defs = try!(self.parse_late_bound_lifetime_defs());
4882 Ok(ast::PolyTraitRef {
4883 bound_lifetimes: lifetime_defs,
4884 trait_ref: try!(self.parse_trait_ref()),
4885 span: mk_sp(lo, self.last_span.hi),
4889 /// Parse struct Foo { ... }
4890 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
4891 let class_name = try!(self.parse_ident());
4892 let mut generics = try!(self.parse_generics());
4894 // There is a special case worth noting here, as reported in issue #17904.
4895 // If we are parsing a tuple struct it is the case that the where clause
4896 // should follow the field list. Like so:
4898 // struct Foo<T>(T) where T: Copy;
4900 // If we are parsing a normal record-style struct it is the case
4901 // that the where clause comes before the body, and after the generics.
4902 // So if we look ahead and see a brace or a where-clause we begin
4903 // parsing a record style struct.
4905 // Otherwise if we look ahead and see a paren we parse a tuple-style
4908 let vdata = if self.token.is_keyword(keywords::Where) {
4909 generics.where_clause = try!(self.parse_where_clause());
4910 if self.eat(&token::Semi) {
4911 // If we see a: `struct Foo<T> where T: Copy;` style decl.
4912 VariantData::Unit(ast::DUMMY_NODE_ID)
4914 // If we see: `struct Foo<T> where T: Copy { ... }`
4915 VariantData::Struct(try!(self.parse_record_struct_body(ParsePub::Yes)),
4918 // No `where` so: `struct Foo<T>;`
4919 } else if self.eat(&token::Semi) {
4920 VariantData::Unit(ast::DUMMY_NODE_ID)
4921 // Record-style struct definition
4922 } else if self.token == token::OpenDelim(token::Brace) {
4923 VariantData::Struct(try!(self.parse_record_struct_body(ParsePub::Yes)),
4925 // Tuple-style struct definition with optional where-clause.
4926 } else if self.token == token::OpenDelim(token::Paren) {
4927 let body = VariantData::Tuple(try!(self.parse_tuple_struct_body(ParsePub::Yes)),
4928 ast::DUMMY_NODE_ID);
4929 generics.where_clause = try!(self.parse_where_clause());
4930 try!(self.expect(&token::Semi));
4933 let token_str = self.this_token_to_string();
4934 return Err(self.fatal(&format!("expected `where`, `{{`, `(`, or `;` after struct \
4935 name, found `{}`", token_str)))
4938 Ok((class_name, ItemStruct(vdata, generics), None))
4941 pub fn parse_record_struct_body(&mut self,
4942 parse_pub: ParsePub)
4943 -> PResult<'a, Vec<StructField>> {
4944 let mut fields = Vec::new();
4945 if self.eat(&token::OpenDelim(token::Brace)) {
4946 while self.token != token::CloseDelim(token::Brace) {
4947 fields.push(try!(self.parse_struct_decl_field(parse_pub)));
4952 let token_str = self.this_token_to_string();
4953 return Err(self.fatal(&format!("expected `where`, or `{{` after struct \
4961 pub fn parse_tuple_struct_body(&mut self,
4962 parse_pub: ParsePub)
4963 -> PResult<'a, Vec<StructField>> {
4964 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
4965 // Unit like structs are handled in parse_item_struct function
4966 let fields = try!(self.parse_unspanned_seq(
4967 &token::OpenDelim(token::Paren),
4968 &token::CloseDelim(token::Paren),
4969 seq_sep_trailing_allowed(token::Comma),
4971 let attrs = try!(p.parse_outer_attributes());
4973 let struct_field_ = ast::StructField_ {
4974 kind: UnnamedField (
4975 if parse_pub == ParsePub::Yes {
4976 try!(p.parse_visibility())
4981 id: ast::DUMMY_NODE_ID,
4982 ty: try!(p.parse_ty_sum()),
4985 Ok(spanned(lo, p.span.hi, struct_field_))
4991 /// Parse a structure field declaration
4992 pub fn parse_single_struct_field(&mut self,
4994 attrs: Vec<Attribute> )
4995 -> PResult<'a, StructField> {
4996 let a_var = try!(self.parse_name_and_ty(vis, attrs));
5001 token::CloseDelim(token::Brace) => {}
5003 let span = self.span;
5004 let token_str = self.this_token_to_string();
5005 return Err(self.span_fatal_help(span,
5006 &format!("expected `,`, or `}}`, found `{}`",
5008 "struct fields should be separated by commas"))
5014 /// Parse an element of a struct definition
5015 fn parse_struct_decl_field(&mut self, parse_pub: ParsePub) -> PResult<'a, StructField> {
5017 let attrs = try!(self.parse_outer_attributes());
5019 if self.eat_keyword(keywords::Pub) {
5020 if parse_pub == ParsePub::No {
5021 let span = self.last_span;
5022 self.span_err(span, "`pub` is not allowed here");
5024 return self.parse_single_struct_field(Public, attrs);
5027 return self.parse_single_struct_field(Inherited, attrs);
5030 /// Parse visibility: PUB or nothing
5031 fn parse_visibility(&mut self) -> PResult<'a, Visibility> {
5032 if self.eat_keyword(keywords::Pub) { Ok(Public) }
5033 else { Ok(Inherited) }
5036 /// Given a termination token, parse all of the items in a module
5037 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: BytePos) -> PResult<'a, Mod> {
5038 let mut items = vec![];
5039 while let Some(item) = try!(self.parse_item()) {
5043 if !self.eat(term) {
5044 let token_str = self.this_token_to_string();
5045 return Err(self.fatal(&format!("expected item, found `{}`", token_str)));
5048 let hi = if self.span == codemap::DUMMY_SP {
5055 inner: mk_sp(inner_lo, hi),
5060 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
5061 let id = try!(self.parse_ident());
5062 try!(self.expect(&token::Colon));
5063 let ty = try!(self.parse_ty_sum());
5064 try!(self.expect(&token::Eq));
5065 let e = try!(self.parse_expr());
5066 try!(self.commit_expr_expecting(&*e, token::Semi));
5067 let item = match m {
5068 Some(m) => ItemStatic(ty, m, e),
5069 None => ItemConst(ty, e),
5071 Ok((id, item, None))
5074 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
5075 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
5076 let id_span = self.span;
5077 let id = try!(self.parse_ident());
5078 if self.check(&token::Semi) {
5080 // This mod is in an external file. Let's go get it!
5081 let (m, attrs) = try!(self.eval_src_mod(id, outer_attrs, id_span));
5082 Ok((id, m, Some(attrs)))
5084 self.push_mod_path(id, outer_attrs);
5085 try!(self.expect(&token::OpenDelim(token::Brace)));
5086 let mod_inner_lo = self.span.lo;
5087 let old_owns_directory = self.owns_directory;
5088 self.owns_directory = true;
5089 let attrs = try!(self.parse_inner_attributes());
5090 let m = try!(self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo));
5091 self.owns_directory = old_owns_directory;
5092 self.pop_mod_path();
5093 Ok((id, ItemMod(m), Some(attrs)))
5097 fn push_mod_path(&mut self, id: Ident, attrs: &[Attribute]) {
5098 let default_path = self.id_to_interned_str(id);
5099 let file_path = match ::attr::first_attr_value_str_by_name(attrs, "path") {
5101 None => default_path,
5103 self.mod_path_stack.push(file_path)
5106 fn pop_mod_path(&mut self) {
5107 self.mod_path_stack.pop().unwrap();
5110 pub fn submod_path_from_attr(attrs: &[ast::Attribute], dir_path: &Path) -> Option<PathBuf> {
5111 ::attr::first_attr_value_str_by_name(attrs, "path").map(|d| dir_path.join(&*d))
5114 /// Returns either a path to a module, or .
5115 pub fn default_submod_path(id: ast::Ident, dir_path: &Path, codemap: &CodeMap) -> ModulePath
5117 let mod_name = id.to_string();
5118 let default_path_str = format!("{}.rs", mod_name);
5119 let secondary_path_str = format!("{}/mod.rs", mod_name);
5120 let default_path = dir_path.join(&default_path_str);
5121 let secondary_path = dir_path.join(&secondary_path_str);
5122 let default_exists = codemap.file_exists(&default_path);
5123 let secondary_exists = codemap.file_exists(&secondary_path);
5125 let result = match (default_exists, secondary_exists) {
5126 (true, false) => Ok(ModulePathSuccess { path: default_path, owns_directory: false }),
5127 (false, true) => Ok(ModulePathSuccess { path: secondary_path, owns_directory: true }),
5128 (false, false) => Err(ModulePathError {
5129 err_msg: format!("file not found for module `{}`", mod_name),
5130 help_msg: format!("name the file either {} or {} inside the directory {:?}",
5133 dir_path.display()),
5135 (true, true) => Err(ModulePathError {
5136 err_msg: format!("file for module `{}` found at both {} and {}",
5139 secondary_path_str),
5140 help_msg: "delete or rename one of them to remove the ambiguity".to_owned(),
5146 path_exists: default_exists || secondary_exists,
5151 fn submod_path(&mut self,
5153 outer_attrs: &[ast::Attribute],
5154 id_sp: Span) -> PResult<'a, ModulePathSuccess> {
5155 let mut prefix = PathBuf::from(&self.sess.codemap().span_to_filename(self.span));
5157 let mut dir_path = prefix;
5158 for part in &self.mod_path_stack {
5159 dir_path.push(&**part);
5162 if let Some(p) = Parser::submod_path_from_attr(outer_attrs, &dir_path) {
5163 return Ok(ModulePathSuccess { path: p, owns_directory: true });
5166 let paths = Parser::default_submod_path(id, &dir_path, self.sess.codemap());
5168 if !self.owns_directory {
5169 let mut err = self.diagnostic().struct_span_err(id_sp,
5170 "cannot declare a new module at this location");
5171 let this_module = match self.mod_path_stack.last() {
5172 Some(name) => name.to_string(),
5173 None => self.root_module_name.as_ref().unwrap().clone(),
5175 err.span_note(id_sp,
5176 &format!("maybe move this module `{0}` to its own directory \
5179 if paths.path_exists {
5180 err.span_note(id_sp,
5181 &format!("... or maybe `use` the module `{}` instead \
5182 of possibly redeclaring it",
5186 self.abort_if_errors();
5189 match paths.result {
5190 Ok(succ) => Ok(succ),
5191 Err(err) => Err(self.span_fatal_help(id_sp, &err.err_msg, &err.help_msg)),
5195 /// Read a module from a source file.
5196 fn eval_src_mod(&mut self,
5198 outer_attrs: &[ast::Attribute],
5200 -> PResult<'a, (ast::Item_, Vec<ast::Attribute> )> {
5201 let ModulePathSuccess { path, owns_directory } = try!(self.submod_path(id,
5205 self.eval_src_mod_from_path(path,
5211 fn eval_src_mod_from_path(&mut self,
5213 owns_directory: bool,
5215 id_sp: Span) -> PResult<'a, (ast::Item_, Vec<ast::Attribute> )> {
5216 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
5217 match included_mod_stack.iter().position(|p| *p == path) {
5219 let mut err = String::from("circular modules: ");
5220 let len = included_mod_stack.len();
5221 for p in &included_mod_stack[i.. len] {
5222 err.push_str(&p.to_string_lossy());
5223 err.push_str(" -> ");
5225 err.push_str(&path.to_string_lossy());
5226 return Err(self.span_fatal(id_sp, &err[..]));
5230 included_mod_stack.push(path.clone());
5231 drop(included_mod_stack);
5233 let mut p0 = new_sub_parser_from_file(self.sess,
5239 let mod_inner_lo = p0.span.lo;
5240 let mod_attrs = try!(p0.parse_inner_attributes());
5241 let m0 = try!(p0.parse_mod_items(&token::Eof, mod_inner_lo));
5242 self.sess.included_mod_stack.borrow_mut().pop();
5243 Ok((ast::ItemMod(m0), mod_attrs))
5246 /// Parse a function declaration from a foreign module
5247 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: BytePos,
5248 attrs: Vec<Attribute>) -> PResult<'a, P<ForeignItem>> {
5249 try!(self.expect_keyword(keywords::Fn));
5251 let (ident, mut generics) = try!(self.parse_fn_header());
5252 let decl = try!(self.parse_fn_decl(true));
5253 generics.where_clause = try!(self.parse_where_clause());
5254 let hi = self.span.hi;
5255 try!(self.expect(&token::Semi));
5256 Ok(P(ast::ForeignItem {
5259 node: ForeignItemFn(decl, generics),
5260 id: ast::DUMMY_NODE_ID,
5261 span: mk_sp(lo, hi),
5266 /// Parse a static item from a foreign module
5267 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: BytePos,
5268 attrs: Vec<Attribute>) -> PResult<'a, P<ForeignItem>> {
5269 try!(self.expect_keyword(keywords::Static));
5270 let mutbl = self.eat_keyword(keywords::Mut);
5272 let ident = try!(self.parse_ident());
5273 try!(self.expect(&token::Colon));
5274 let ty = try!(self.parse_ty_sum());
5275 let hi = self.span.hi;
5276 try!(self.expect(&token::Semi));
5280 node: ForeignItemStatic(ty, mutbl),
5281 id: ast::DUMMY_NODE_ID,
5282 span: mk_sp(lo, hi),
5287 /// Parse extern crate links
5291 /// extern crate foo;
5292 /// extern crate bar as foo;
5293 fn parse_item_extern_crate(&mut self,
5295 visibility: Visibility,
5296 attrs: Vec<Attribute>)
5297 -> PResult<'a, P<Item>> {
5299 let crate_name = try!(self.parse_ident());
5300 let (maybe_path, ident) = if let Some(ident) = try!(self.parse_rename()) {
5301 (Some(crate_name.name), ident)
5305 try!(self.expect(&token::Semi));
5307 let last_span = self.last_span;
5309 if visibility == ast::Public {
5310 self.span_warn(mk_sp(lo, last_span.hi),
5311 "`pub extern crate` does not work as expected and should not be used. \
5312 Likely to become an error. Prefer `extern crate` and `pub use`.");
5318 ItemExternCrate(maybe_path),
5323 /// Parse `extern` for foreign ABIs
5326 /// `extern` is expected to have been
5327 /// consumed before calling this method
5333 fn parse_item_foreign_mod(&mut self,
5335 opt_abi: Option<abi::Abi>,
5336 visibility: Visibility,
5337 mut attrs: Vec<Attribute>)
5338 -> PResult<'a, P<Item>> {
5339 try!(self.expect(&token::OpenDelim(token::Brace)));
5341 let abi = opt_abi.unwrap_or(abi::C);
5343 attrs.extend(try!(self.parse_inner_attributes()));
5345 let mut foreign_items = vec![];
5346 while let Some(item) = try!(self.parse_foreign_item()) {
5347 foreign_items.push(item);
5349 try!(self.expect(&token::CloseDelim(token::Brace)));
5351 let last_span = self.last_span;
5352 let m = ast::ForeignMod {
5354 items: foreign_items
5358 special_idents::invalid,
5364 /// Parse type Foo = Bar;
5365 fn parse_item_type(&mut self) -> PResult<'a, ItemInfo> {
5366 let ident = try!(self.parse_ident());
5367 let mut tps = try!(self.parse_generics());
5368 tps.where_clause = try!(self.parse_where_clause());
5369 try!(self.expect(&token::Eq));
5370 let ty = try!(self.parse_ty_sum());
5371 try!(self.expect(&token::Semi));
5372 Ok((ident, ItemTy(ty, tps), None))
5375 /// Parse the part of an "enum" decl following the '{'
5376 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
5377 let mut variants = Vec::new();
5378 let mut all_nullary = true;
5379 let mut any_disr = None;
5380 while self.token != token::CloseDelim(token::Brace) {
5381 let variant_attrs = try!(self.parse_outer_attributes());
5382 let vlo = self.span.lo;
5385 let mut disr_expr = None;
5386 let ident = try!(self.parse_ident());
5387 if self.check(&token::OpenDelim(token::Brace)) {
5388 // Parse a struct variant.
5389 all_nullary = false;
5390 struct_def = VariantData::Struct(try!(self.parse_record_struct_body(ParsePub::No)),
5391 ast::DUMMY_NODE_ID);
5392 } else if self.check(&token::OpenDelim(token::Paren)) {
5393 all_nullary = false;
5394 struct_def = VariantData::Tuple(try!(self.parse_tuple_struct_body(ParsePub::No)),
5395 ast::DUMMY_NODE_ID);
5396 } else if self.eat(&token::Eq) {
5397 disr_expr = Some(try!(self.parse_expr()));
5398 any_disr = disr_expr.as_ref().map(|expr| expr.span);
5399 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5401 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5404 let vr = ast::Variant_ {
5406 attrs: variant_attrs,
5408 disr_expr: disr_expr,
5410 variants.push(P(spanned(vlo, self.last_span.hi, vr)));
5412 if !self.eat(&token::Comma) { break; }
5414 try!(self.expect(&token::CloseDelim(token::Brace)));
5416 Some(disr_span) if !all_nullary =>
5417 self.span_err(disr_span,
5418 "discriminator values can only be used with a c-like enum"),
5422 Ok(ast::EnumDef { variants: variants })
5425 /// Parse an "enum" declaration
5426 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
5427 let id = try!(self.parse_ident());
5428 let mut generics = try!(self.parse_generics());
5429 generics.where_clause = try!(self.parse_where_clause());
5430 try!(self.expect(&token::OpenDelim(token::Brace)));
5432 let enum_definition = try!(self.parse_enum_def(&generics));
5433 Ok((id, ItemEnum(enum_definition, generics), None))
5436 /// Parses a string as an ABI spec on an extern type or module. Consumes
5437 /// the `extern` keyword, if one is found.
5438 fn parse_opt_abi(&mut self) -> PResult<'a, Option<abi::Abi>> {
5440 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
5442 self.expect_no_suffix(sp, "ABI spec", suf);
5444 match abi::lookup(&s.as_str()) {
5445 Some(abi) => Ok(Some(abi)),
5447 let last_span = self.last_span;
5450 &format!("invalid ABI: expected one of [{}], \
5452 abi::all_names().join(", "),
5463 /// Parse one of the items allowed by the flags.
5464 /// NB: this function no longer parses the items inside an
5466 fn parse_item_(&mut self, attrs: Vec<Attribute>,
5467 macros_allowed: bool, attributes_allowed: bool) -> PResult<'a, Option<P<Item>>> {
5468 let nt_item = match self.token {
5469 token::Interpolated(token::NtItem(ref item)) => {
5470 Some((**item).clone())
5477 let mut attrs = attrs;
5478 mem::swap(&mut item.attrs, &mut attrs);
5479 item.attrs.extend(attrs);
5480 return Ok(Some(P(item)));
5485 let lo = self.span.lo;
5487 let visibility = try!(self.parse_visibility());
5489 if self.eat_keyword(keywords::Use) {
5491 let item_ = ItemUse(try!(self.parse_view_path()));
5492 try!(self.expect(&token::Semi));
5494 let last_span = self.last_span;
5495 let item = self.mk_item(lo,
5497 token::special_idents::invalid,
5501 return Ok(Some(item));
5504 if self.eat_keyword(keywords::Extern) {
5505 if self.eat_keyword(keywords::Crate) {
5506 return Ok(Some(try!(self.parse_item_extern_crate(lo, visibility, attrs))));
5509 let opt_abi = try!(self.parse_opt_abi());
5511 if self.eat_keyword(keywords::Fn) {
5512 // EXTERN FUNCTION ITEM
5513 let abi = opt_abi.unwrap_or(abi::C);
5514 let (ident, item_, extra_attrs) =
5515 try!(self.parse_item_fn(Unsafety::Normal, Constness::NotConst, abi));
5516 let last_span = self.last_span;
5517 let item = self.mk_item(lo,
5522 maybe_append(attrs, extra_attrs));
5523 return Ok(Some(item));
5524 } else if self.check(&token::OpenDelim(token::Brace)) {
5525 return Ok(Some(try!(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs))));
5528 try!(self.unexpected());
5531 if self.eat_keyword(keywords::Static) {
5533 let m = if self.eat_keyword(keywords::Mut) {MutMutable} else {MutImmutable};
5534 let (ident, item_, extra_attrs) = try!(self.parse_item_const(Some(m)));
5535 let last_span = self.last_span;
5536 let item = self.mk_item(lo,
5541 maybe_append(attrs, extra_attrs));
5542 return Ok(Some(item));
5544 if self.eat_keyword(keywords::Const) {
5545 if self.check_keyword(keywords::Fn)
5546 || (self.check_keyword(keywords::Unsafe)
5547 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
5548 // CONST FUNCTION ITEM
5549 let unsafety = if self.eat_keyword(keywords::Unsafe) {
5555 let (ident, item_, extra_attrs) =
5556 try!(self.parse_item_fn(unsafety, Constness::Const, abi::Rust));
5557 let last_span = self.last_span;
5558 let item = self.mk_item(lo,
5563 maybe_append(attrs, extra_attrs));
5564 return Ok(Some(item));
5568 if self.eat_keyword(keywords::Mut) {
5569 let last_span = self.last_span;
5570 self.diagnostic().struct_span_err(last_span, "const globals cannot be mutable")
5571 .fileline_help(last_span, "did you mean to declare a static?")
5574 let (ident, item_, extra_attrs) = try!(self.parse_item_const(None));
5575 let last_span = self.last_span;
5576 let item = self.mk_item(lo,
5581 maybe_append(attrs, extra_attrs));
5582 return Ok(Some(item));
5584 if self.check_keyword(keywords::Unsafe) &&
5585 self.look_ahead(1, |t| t.is_keyword(keywords::Trait))
5587 // UNSAFE TRAIT ITEM
5588 try!(self.expect_keyword(keywords::Unsafe));
5589 try!(self.expect_keyword(keywords::Trait));
5590 let (ident, item_, extra_attrs) =
5591 try!(self.parse_item_trait(ast::Unsafety::Unsafe));
5592 let last_span = self.last_span;
5593 let item = self.mk_item(lo,
5598 maybe_append(attrs, extra_attrs));
5599 return Ok(Some(item));
5601 if self.check_keyword(keywords::Unsafe) &&
5602 self.look_ahead(1, |t| t.is_keyword(keywords::Impl))
5605 try!(self.expect_keyword(keywords::Unsafe));
5606 try!(self.expect_keyword(keywords::Impl));
5607 let (ident, item_, extra_attrs) = try!(self.parse_item_impl(ast::Unsafety::Unsafe));
5608 let last_span = self.last_span;
5609 let item = self.mk_item(lo,
5614 maybe_append(attrs, extra_attrs));
5615 return Ok(Some(item));
5617 if self.check_keyword(keywords::Fn) {
5620 let (ident, item_, extra_attrs) =
5621 try!(self.parse_item_fn(Unsafety::Normal, Constness::NotConst, abi::Rust));
5622 let last_span = self.last_span;
5623 let item = self.mk_item(lo,
5628 maybe_append(attrs, extra_attrs));
5629 return Ok(Some(item));
5631 if self.check_keyword(keywords::Unsafe)
5632 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
5633 // UNSAFE FUNCTION ITEM
5635 let abi = if self.eat_keyword(keywords::Extern) {
5636 try!(self.parse_opt_abi()).unwrap_or(abi::C)
5640 try!(self.expect_keyword(keywords::Fn));
5641 let (ident, item_, extra_attrs) =
5642 try!(self.parse_item_fn(Unsafety::Unsafe, Constness::NotConst, abi));
5643 let last_span = self.last_span;
5644 let item = self.mk_item(lo,
5649 maybe_append(attrs, extra_attrs));
5650 return Ok(Some(item));
5652 if self.eat_keyword(keywords::Mod) {
5654 let (ident, item_, extra_attrs) =
5655 try!(self.parse_item_mod(&attrs[..]));
5656 let last_span = self.last_span;
5657 let item = self.mk_item(lo,
5662 maybe_append(attrs, extra_attrs));
5663 return Ok(Some(item));
5665 if self.eat_keyword(keywords::Type) {
5667 let (ident, item_, extra_attrs) = try!(self.parse_item_type());
5668 let last_span = self.last_span;
5669 let item = self.mk_item(lo,
5674 maybe_append(attrs, extra_attrs));
5675 return Ok(Some(item));
5677 if self.eat_keyword(keywords::Enum) {
5679 let (ident, item_, extra_attrs) = try!(self.parse_item_enum());
5680 let last_span = self.last_span;
5681 let item = self.mk_item(lo,
5686 maybe_append(attrs, extra_attrs));
5687 return Ok(Some(item));
5689 if self.eat_keyword(keywords::Trait) {
5691 let (ident, item_, extra_attrs) =
5692 try!(self.parse_item_trait(ast::Unsafety::Normal));
5693 let last_span = self.last_span;
5694 let item = self.mk_item(lo,
5699 maybe_append(attrs, extra_attrs));
5700 return Ok(Some(item));
5702 if self.eat_keyword(keywords::Impl) {
5704 let (ident, item_, extra_attrs) = try!(self.parse_item_impl(ast::Unsafety::Normal));
5705 let last_span = self.last_span;
5706 let item = self.mk_item(lo,
5711 maybe_append(attrs, extra_attrs));
5712 return Ok(Some(item));
5714 if self.eat_keyword(keywords::Struct) {
5716 let (ident, item_, extra_attrs) = try!(self.parse_item_struct());
5717 let last_span = self.last_span;
5718 let item = self.mk_item(lo,
5723 maybe_append(attrs, extra_attrs));
5724 return Ok(Some(item));
5726 self.parse_macro_use_or_failure(attrs,macros_allowed,attributes_allowed,lo,visibility)
5729 /// Parse a foreign item.
5730 fn parse_foreign_item(&mut self) -> PResult<'a, Option<P<ForeignItem>>> {
5731 let attrs = try!(self.parse_outer_attributes());
5732 let lo = self.span.lo;
5733 let visibility = try!(self.parse_visibility());
5735 if self.check_keyword(keywords::Static) {
5736 // FOREIGN STATIC ITEM
5737 return Ok(Some(try!(self.parse_item_foreign_static(visibility, lo, attrs))));
5739 if self.check_keyword(keywords::Fn) || self.check_keyword(keywords::Unsafe) {
5740 // FOREIGN FUNCTION ITEM
5741 return Ok(Some(try!(self.parse_item_foreign_fn(visibility, lo, attrs))));
5744 // FIXME #5668: this will occur for a macro invocation:
5745 match try!(self.parse_macro_use_or_failure(attrs, true, false, lo, visibility)) {
5747 return Err(self.span_fatal(item.span, "macros cannot expand to foreign items"));
5753 /// This is the fall-through for parsing items.
5754 fn parse_macro_use_or_failure(
5756 attrs: Vec<Attribute> ,
5757 macros_allowed: bool,
5758 attributes_allowed: bool,
5760 visibility: Visibility
5761 ) -> PResult<'a, Option<P<Item>>> {
5762 if macros_allowed && !self.token.is_any_keyword()
5763 && self.look_ahead(1, |t| *t == token::Not)
5764 && (self.look_ahead(2, |t| t.is_plain_ident())
5765 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren))
5766 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) {
5767 // MACRO INVOCATION ITEM
5769 let last_span = self.last_span;
5770 self.complain_if_pub_macro(visibility, last_span);
5772 let mac_lo = self.span.lo;
5775 let pth = try!(self.parse_path(NoTypesAllowed));
5776 try!(self.expect(&token::Not));
5778 // a 'special' identifier (like what `macro_rules!` uses)
5779 // is optional. We should eventually unify invoc syntax
5781 let id = if self.token.is_plain_ident() {
5782 try!(self.parse_ident())
5784 token::special_idents::invalid // no special identifier
5786 // eat a matched-delimiter token tree:
5787 let delim = try!(self.expect_open_delim());
5788 let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
5790 |p| p.parse_token_tree()));
5791 // single-variant-enum... :
5792 let m = Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT };
5793 let m: ast::Mac = codemap::Spanned { node: m,
5795 self.last_span.hi) };
5797 if delim != token::Brace {
5798 if !self.eat(&token::Semi) {
5799 let last_span = self.last_span;
5800 self.span_err(last_span,
5801 "macros that expand to items must either \
5802 be surrounded with braces or followed by \
5807 let item_ = ItemMac(m);
5808 let last_span = self.last_span;
5809 let item = self.mk_item(lo,
5815 return Ok(Some(item));
5818 // FAILURE TO PARSE ITEM
5822 let last_span = self.last_span;
5823 return Err(self.span_fatal(last_span, "unmatched visibility `pub`"));
5827 if !attributes_allowed && !attrs.is_empty() {
5828 self.expected_item_err(&attrs);
5833 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
5834 let attrs = try!(self.parse_outer_attributes());
5835 self.parse_item_(attrs, true, false)
5839 /// Matches view_path : MOD? non_global_path as IDENT
5840 /// | MOD? non_global_path MOD_SEP LBRACE RBRACE
5841 /// | MOD? non_global_path MOD_SEP LBRACE ident_seq RBRACE
5842 /// | MOD? non_global_path MOD_SEP STAR
5843 /// | MOD? non_global_path
5844 fn parse_view_path(&mut self) -> PResult<'a, P<ViewPath>> {
5845 let lo = self.span.lo;
5847 // Allow a leading :: because the paths are absolute either way.
5848 // This occurs with "use $crate::..." in macros.
5849 self.eat(&token::ModSep);
5851 if self.check(&token::OpenDelim(token::Brace)) {
5853 let idents = try!(self.parse_unspanned_seq(
5854 &token::OpenDelim(token::Brace),
5855 &token::CloseDelim(token::Brace),
5856 seq_sep_trailing_allowed(token::Comma),
5857 |p| p.parse_path_list_item()));
5858 let path = ast::Path {
5859 span: mk_sp(lo, self.span.hi),
5861 segments: Vec::new()
5863 return Ok(P(spanned(lo, self.span.hi, ViewPathList(path, idents))));
5866 let first_ident = try!(self.parse_ident());
5867 let mut path = vec!(first_ident);
5868 if let token::ModSep = self.token {
5869 // foo::bar or foo::{a,b,c} or foo::*
5870 while self.check(&token::ModSep) {
5874 token::Ident(..) => {
5875 let ident = try!(self.parse_ident());
5879 // foo::bar::{a,b,c}
5880 token::OpenDelim(token::Brace) => {
5881 let idents = try!(self.parse_unspanned_seq(
5882 &token::OpenDelim(token::Brace),
5883 &token::CloseDelim(token::Brace),
5884 seq_sep_trailing_allowed(token::Comma),
5885 |p| p.parse_path_list_item()
5887 let path = ast::Path {
5888 span: mk_sp(lo, self.span.hi),
5890 segments: path.into_iter().map(|identifier| {
5892 identifier: identifier,
5893 parameters: ast::PathParameters::none(),
5897 return Ok(P(spanned(lo, self.span.hi, ViewPathList(path, idents))));
5901 token::BinOp(token::Star) => {
5903 let path = ast::Path {
5904 span: mk_sp(lo, self.span.hi),
5906 segments: path.into_iter().map(|identifier| {
5908 identifier: identifier,
5909 parameters: ast::PathParameters::none(),
5913 return Ok(P(spanned(lo, self.span.hi, ViewPathGlob(path))));
5916 // fall-through for case foo::bar::;
5918 self.span_err(self.span, "expected identifier or `{` or `*`, found `;`");
5925 let mut rename_to = path[path.len() - 1];
5926 let path = ast::Path {
5927 span: mk_sp(lo, self.last_span.hi),
5929 segments: path.into_iter().map(|identifier| {
5931 identifier: identifier,
5932 parameters: ast::PathParameters::none(),
5936 rename_to = try!(self.parse_rename()).unwrap_or(rename_to);
5937 Ok(P(spanned(lo, self.last_span.hi, ViewPathSimple(rename_to, path))))
5940 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
5941 if self.eat_keyword(keywords::As) {
5942 self.parse_ident().map(Some)
5948 /// Parses a source module as a crate. This is the main
5949 /// entry point for the parser.
5950 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
5951 let lo = self.span.lo;
5953 attrs: try!(self.parse_inner_attributes()),
5954 module: try!(self.parse_mod_items(&token::Eof, lo)),
5955 config: self.cfg.clone(),
5956 span: mk_sp(lo, self.span.lo),
5957 exported_macros: Vec::new(),
5961 pub fn parse_optional_str(&mut self)
5962 -> Option<(InternedString,
5964 Option<ast::Name>)> {
5965 let ret = match self.token {
5966 token::Literal(token::Str_(s), suf) => {
5967 (self.id_to_interned_str(ast::Ident::with_empty_ctxt(s)), ast::CookedStr, suf)
5969 token::Literal(token::StrRaw(s, n), suf) => {
5970 (self.id_to_interned_str(ast::Ident::with_empty_ctxt(s)), ast::RawStr(n), suf)
5978 pub fn parse_str(&mut self) -> PResult<'a, (InternedString, StrStyle)> {
5979 match self.parse_optional_str() {
5980 Some((s, style, suf)) => {
5981 let sp = self.last_span;
5982 self.expect_no_suffix(sp, "string literal", suf);
5985 _ => Err(self.fatal("expected string literal"))