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 fn maybe_append(mut lhs: Vec<Attribute>, rhs: Option<Vec<Attribute>>)
238 if let Some(ref attrs) = rhs {
239 lhs.extend(attrs.iter().cloned())
244 /* ident is handled by common.rs */
246 pub struct Parser<'a> {
247 pub sess: &'a ParseSess,
248 /// the current token:
249 pub token: token::Token,
250 /// the span of the current token:
252 /// the span of the prior token:
254 pub cfg: CrateConfig,
255 /// the previous token or None (only stashed sometimes).
256 pub last_token: Option<Box<token::Token>>,
257 last_token_interpolated: bool,
258 pub buffer: [TokenAndSpan; 4],
259 pub buffer_start: isize,
260 pub buffer_end: isize,
261 pub tokens_consumed: usize,
262 pub restrictions: Restrictions,
263 pub quote_depth: usize, // not (yet) related to the quasiquoter
264 pub reader: Box<Reader+'a>,
265 pub interner: Rc<token::IdentInterner>,
266 /// The set of seen errors about obsolete syntax. Used to suppress
267 /// extra detail when the same error is seen twice
268 pub obsolete_set: HashSet<ObsoleteSyntax>,
269 /// Used to determine the path to externally loaded source files
270 pub mod_path_stack: Vec<InternedString>,
271 /// Stack of spans of open delimiters. Used for error message.
272 pub open_braces: Vec<Span>,
273 /// Flag if this parser "owns" the directory that it is currently parsing
274 /// in. This will affect how nested files are looked up.
275 pub owns_directory: bool,
276 /// Name of the root module this parser originated from. If `None`, then the
277 /// name is not known. This does not change while the parser is descending
278 /// into modules, and sub-parsers have new values for this name.
279 pub root_module_name: Option<String>,
280 pub expected_tokens: Vec<TokenType>,
283 #[derive(PartialEq, Eq, Clone)]
286 Keyword(keywords::Keyword),
291 fn to_string(&self) -> String {
293 TokenType::Token(ref t) => format!("`{}`", Parser::token_to_string(t)),
294 TokenType::Operator => "an operator".to_string(),
295 TokenType::Keyword(kw) => format!("`{}`", kw.to_name()),
300 fn is_plain_ident_or_underscore(t: &token::Token) -> bool {
301 t.is_plain_ident() || *t == token::Underscore
304 /// Information about the path to a module.
305 pub struct ModulePath {
307 pub path_exists: bool,
308 pub result: Result<ModulePathSuccess, ModulePathError>,
311 pub struct ModulePathSuccess {
312 pub path: ::std::path::PathBuf,
313 pub owns_directory: bool,
316 pub struct ModulePathError {
318 pub help_msg: String,
323 AttributesParsed(ThinAttributes),
324 AlreadyParsed(P<Expr>),
327 impl From<Option<ThinAttributes>> for LhsExpr {
328 fn from(o: Option<ThinAttributes>) -> Self {
329 if let Some(attrs) = o {
330 LhsExpr::AttributesParsed(attrs)
332 LhsExpr::NotYetParsed
337 impl From<P<Expr>> for LhsExpr {
338 fn from(expr: P<Expr>) -> Self {
339 LhsExpr::AlreadyParsed(expr)
343 impl<'a> Parser<'a> {
344 pub fn new(sess: &'a ParseSess,
345 cfg: ast::CrateConfig,
346 mut rdr: Box<Reader+'a>)
349 let tok0 = rdr.real_token();
351 let placeholder = TokenAndSpan {
352 tok: token::Underscore,
358 interner: token::get_ident_interner(),
365 last_token_interpolated: false,
375 restrictions: Restrictions::empty(),
377 obsolete_set: HashSet::new(),
378 mod_path_stack: Vec::new(),
379 open_braces: Vec::new(),
380 owns_directory: true,
381 root_module_name: None,
382 expected_tokens: Vec::new(),
386 /// Convert a token to a string using self's reader
387 pub fn token_to_string(token: &token::Token) -> String {
388 pprust::token_to_string(token)
391 /// Convert the current token to a string using self's reader
392 pub fn this_token_to_string(&self) -> String {
393 Parser::token_to_string(&self.token)
396 pub fn unexpected_last<T>(&self, t: &token::Token) -> PResult<'a, T> {
397 let token_str = Parser::token_to_string(t);
398 let last_span = self.last_span;
399 Err(self.span_fatal(last_span, &format!("unexpected token: `{}`", token_str)))
402 pub fn unexpected<T>(&mut self) -> PResult<'a, T> {
403 match self.expect_one_of(&[], &[]) {
405 Ok(_) => unreachable!(),
409 /// Expect and consume the token t. Signal an error if
410 /// the next token is not t.
411 pub fn expect(&mut self, t: &token::Token) -> PResult<'a, ()> {
412 if self.expected_tokens.is_empty() {
413 if self.token == *t {
417 let token_str = Parser::token_to_string(t);
418 let this_token_str = self.this_token_to_string();
419 Err(self.fatal(&format!("expected `{}`, found `{}`",
424 self.expect_one_of(unsafe { slice::from_raw_parts(t, 1) }, &[])
428 /// Expect next token to be edible or inedible token. If edible,
429 /// then consume it; if inedible, then return without consuming
430 /// anything. Signal a fatal error if next token is unexpected.
431 pub fn expect_one_of(&mut self,
432 edible: &[token::Token],
433 inedible: &[token::Token]) -> PResult<'a, ()>{
434 fn tokens_to_string(tokens: &[TokenType]) -> String {
435 let mut i = tokens.iter();
436 // This might be a sign we need a connect method on Iterator.
438 .map_or("".to_string(), |t| t.to_string());
439 i.enumerate().fold(b, |mut b, (i, ref a)| {
440 if tokens.len() > 2 && i == tokens.len() - 2 {
442 } else if tokens.len() == 2 && i == tokens.len() - 2 {
447 b.push_str(&*a.to_string());
451 if edible.contains(&self.token) {
454 } else if inedible.contains(&self.token) {
455 // leave it in the input
458 let mut expected = edible.iter()
459 .map(|x| TokenType::Token(x.clone()))
460 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
461 .chain(self.expected_tokens.iter().cloned())
462 .collect::<Vec<_>>();
463 expected.sort_by(|a, b| a.to_string().cmp(&b.to_string()));
465 let expect = tokens_to_string(&expected[..]);
466 let actual = self.this_token_to_string();
468 &(if expected.len() > 1 {
469 (format!("expected one of {}, found `{}`",
472 } else if expected.is_empty() {
473 (format!("unexpected token: `{}`",
476 (format!("expected {}, found `{}`",
484 /// Check for erroneous `ident { }`; if matches, signal error and
485 /// recover (without consuming any expected input token). Returns
486 /// true if and only if input was consumed for recovery.
487 pub fn check_for_erroneous_unit_struct_expecting(&mut self,
488 expected: &[token::Token])
490 if self.token == token::OpenDelim(token::Brace)
491 && expected.iter().all(|t| *t != token::OpenDelim(token::Brace))
492 && self.look_ahead(1, |t| *t == token::CloseDelim(token::Brace)) {
493 // matched; signal non-fatal error and recover.
494 let span = self.span;
495 self.span_err(span, "unit-like struct construction is written with no trailing `{ }`");
496 self.eat(&token::OpenDelim(token::Brace));
497 self.eat(&token::CloseDelim(token::Brace));
504 /// Commit to parsing a complete expression `e` expected to be
505 /// followed by some token from the set edible + inedible. Recover
506 /// from anticipated input errors, discarding erroneous characters.
507 pub fn commit_expr(&mut self, e: &Expr, edible: &[token::Token],
508 inedible: &[token::Token]) -> PResult<'a, ()> {
509 debug!("commit_expr {:?}", e);
510 if let ExprPath(..) = e.node {
511 // might be unit-struct construction; check for recoverableinput error.
512 let expected = edible.iter()
514 .chain(inedible.iter().cloned())
515 .collect::<Vec<_>>();
516 self.check_for_erroneous_unit_struct_expecting(&expected[..]);
518 self.expect_one_of(edible, inedible)
521 pub fn commit_expr_expecting(&mut self, e: &Expr, edible: token::Token) -> PResult<'a, ()> {
522 self.commit_expr(e, &[edible], &[])
525 /// Commit to parsing a complete statement `s`, which expects to be
526 /// followed by some token from the set edible + inedible. Check
527 /// for recoverable input errors, discarding erroneous characters.
528 pub fn commit_stmt(&mut self, edible: &[token::Token],
529 inedible: &[token::Token]) -> PResult<'a, ()> {
532 .map_or(false, |t| t.is_ident() || t.is_path()) {
533 let expected = edible.iter()
535 .chain(inedible.iter().cloned())
536 .collect::<Vec<_>>();
537 self.check_for_erroneous_unit_struct_expecting(&expected);
539 self.expect_one_of(edible, inedible)
542 pub fn commit_stmt_expecting(&mut self, edible: token::Token) -> PResult<'a, ()> {
543 self.commit_stmt(&[edible], &[])
546 /// returns the span of expr, if it was not interpolated or the span of the interpolated token
547 fn interpolated_or_expr_span(&self,
548 expr: PResult<'a, P<Expr>>)
549 -> PResult<'a, (Span, P<Expr>)> {
551 if self.last_token_interpolated {
559 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
560 self.check_strict_keywords();
561 self.check_reserved_keywords();
563 token::Ident(i, _) => {
567 token::Interpolated(token::NtIdent(..)) => {
568 self.bug("ident interpolation not converted to real token");
571 let token_str = self.this_token_to_string();
572 Err(self.fatal(&format!("expected ident, found `{}`",
578 pub fn parse_ident_or_self_type(&mut self) -> PResult<'a, ast::Ident> {
579 if self.is_self_type_ident() {
580 self.expect_self_type_ident()
586 pub fn parse_path_list_item(&mut self) -> PResult<'a, ast::PathListItem> {
587 let lo = self.span.lo;
588 let node = if self.eat_keyword(keywords::SelfValue) {
589 let rename = try!(self.parse_rename());
590 ast::PathListMod { id: ast::DUMMY_NODE_ID, rename: rename }
592 let ident = try!(self.parse_ident());
593 let rename = try!(self.parse_rename());
594 ast::PathListIdent { name: ident, rename: rename, id: ast::DUMMY_NODE_ID }
596 let hi = self.last_span.hi;
597 Ok(spanned(lo, hi, node))
600 /// Check if the next token is `tok`, and return `true` if so.
602 /// This method is will automatically add `tok` to `expected_tokens` if `tok` is not
604 pub fn check(&mut self, tok: &token::Token) -> bool {
605 let is_present = self.token == *tok;
606 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
610 /// Consume token 'tok' if it exists. Returns true if the given
611 /// token was present, false otherwise.
612 pub fn eat(&mut self, tok: &token::Token) -> bool {
613 let is_present = self.check(tok);
614 if is_present { self.bump() }
618 pub fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
619 self.expected_tokens.push(TokenType::Keyword(kw));
620 self.token.is_keyword(kw)
623 /// If the next token is the given keyword, eat it and return
624 /// true. Otherwise, return false.
625 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
626 if self.check_keyword(kw) {
634 pub fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
635 if self.token.is_keyword(kw) {
643 /// If the given word is not a keyword, signal an error.
644 /// If the next token is not the given word, signal an error.
645 /// Otherwise, eat it.
646 pub fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> {
647 if !self.eat_keyword(kw) {
654 /// Signal an error if the given string is a strict keyword
655 pub fn check_strict_keywords(&mut self) {
656 if self.token.is_strict_keyword() {
657 let token_str = self.this_token_to_string();
658 let span = self.span;
660 &format!("expected identifier, found keyword `{}`",
665 /// Signal an error if the current token is a reserved keyword
666 pub fn check_reserved_keywords(&mut self) {
667 if self.token.is_reserved_keyword() {
668 let token_str = self.this_token_to_string();
669 self.fatal(&format!("`{}` is a reserved keyword", token_str)).emit()
673 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
674 /// `&` and continue. If an `&` is not seen, signal an error.
675 fn expect_and(&mut self) -> PResult<'a, ()> {
676 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
678 token::BinOp(token::And) => {
683 let span = self.span;
684 let lo = span.lo + BytePos(1);
685 Ok(self.replace_token(token::BinOp(token::And), lo, span.hi))
687 _ => self.unexpected()
691 pub fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
693 None => {/* everything ok */}
695 let text = suf.as_str();
697 self.span_bug(sp, "found empty literal suffix in Some")
699 self.span_err(sp, &*format!("{} with a suffix is invalid", kind));
705 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
706 /// `<` and continue. If a `<` is not seen, return false.
708 /// This is meant to be used when parsing generics on a path to get the
710 fn eat_lt(&mut self) -> bool {
711 self.expected_tokens.push(TokenType::Token(token::Lt));
717 token::BinOp(token::Shl) => {
718 let span = self.span;
719 let lo = span.lo + BytePos(1);
720 self.replace_token(token::Lt, lo, span.hi);
727 fn expect_lt(&mut self) -> PResult<'a, ()> {
735 /// Expect and consume a GT. if a >> is seen, replace it
736 /// with a single > and continue. If a GT is not seen,
738 pub fn expect_gt(&mut self) -> PResult<'a, ()> {
739 self.expected_tokens.push(TokenType::Token(token::Gt));
745 token::BinOp(token::Shr) => {
746 let span = self.span;
747 let lo = span.lo + BytePos(1);
748 Ok(self.replace_token(token::Gt, lo, span.hi))
750 token::BinOpEq(token::Shr) => {
751 let span = self.span;
752 let lo = span.lo + BytePos(1);
753 Ok(self.replace_token(token::Ge, lo, span.hi))
756 let span = self.span;
757 let lo = span.lo + BytePos(1);
758 Ok(self.replace_token(token::Eq, lo, span.hi))
761 let gt_str = Parser::token_to_string(&token::Gt);
762 let this_token_str = self.this_token_to_string();
763 Err(self.fatal(&format!("expected `{}`, found `{}`",
770 pub fn parse_seq_to_before_gt_or_return<T, F>(&mut self,
771 sep: Option<token::Token>,
773 -> PResult<'a, (P<[T]>, bool)>
774 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
776 let mut v = Vec::new();
777 // This loop works by alternating back and forth between parsing types
778 // and commas. For example, given a string `A, B,>`, the parser would
779 // first parse `A`, then a comma, then `B`, then a comma. After that it
780 // would encounter a `>` and stop. This lets the parser handle trailing
781 // commas in generic parameters, because it can stop either after
782 // parsing a type or after parsing a comma.
784 if self.check(&token::Gt)
785 || self.token == token::BinOp(token::Shr)
786 || self.token == token::Ge
787 || self.token == token::BinOpEq(token::Shr) {
792 match try!(f(self)) {
793 Some(result) => v.push(result),
794 None => return Ok((P::from_vec(v), true))
797 if let Some(t) = sep.as_ref() {
798 try!(self.expect(t));
803 return Ok((P::from_vec(v), false));
806 /// Parse a sequence bracketed by '<' and '>', stopping
808 pub fn parse_seq_to_before_gt<T, F>(&mut self,
809 sep: Option<token::Token>,
811 -> PResult<'a, P<[T]>> where
812 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
814 let (result, returned) = try!(self.parse_seq_to_before_gt_or_return(sep,
815 |p| Ok(Some(try!(f(p))))));
820 pub fn parse_seq_to_gt<T, F>(&mut self,
821 sep: Option<token::Token>,
823 -> PResult<'a, P<[T]>> where
824 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
826 let v = try!(self.parse_seq_to_before_gt(sep, f));
827 try!(self.expect_gt());
831 pub fn parse_seq_to_gt_or_return<T, F>(&mut self,
832 sep: Option<token::Token>,
834 -> PResult<'a, (P<[T]>, bool)> where
835 F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
837 let (v, returned) = try!(self.parse_seq_to_before_gt_or_return(sep, f));
839 try!(self.expect_gt());
841 return Ok((v, returned));
844 /// Parse a sequence, including the closing delimiter. The function
845 /// f must consume tokens until reaching the next separator or
847 pub fn parse_seq_to_end<T, F>(&mut self,
851 -> PResult<'a, Vec<T>> where
852 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
854 let val = try!(self.parse_seq_to_before_end(ket, sep, f));
859 /// Parse a sequence, not including the closing delimiter. The function
860 /// f must consume tokens until reaching the next separator or
862 pub fn parse_seq_to_before_end<T, F>(&mut self,
866 -> PResult<'a, Vec<T>> where
867 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
869 let mut first: bool = true;
871 while self.token != *ket {
874 if first { first = false; }
875 else { try!(self.expect(t)); }
879 if sep.trailing_sep_allowed && self.check(ket) { break; }
880 v.push(try!(f(self)));
885 /// Parse a sequence, including the closing delimiter. The function
886 /// f must consume tokens until reaching the next separator or
888 pub fn parse_unspanned_seq<T, F>(&mut self,
893 -> PResult<'a, Vec<T>> where
894 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
896 try!(self.expect(bra));
897 let result = try!(self.parse_seq_to_before_end(ket, sep, f));
902 /// Parse a sequence parameter of enum variant. For consistency purposes,
903 /// these should not be empty.
904 pub fn parse_enum_variant_seq<T, F>(&mut self,
909 -> PResult<'a, Vec<T>> where
910 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
912 let result = try!(self.parse_unspanned_seq(bra, ket, sep, f));
913 if result.is_empty() {
914 let last_span = self.last_span;
915 self.span_err(last_span,
916 "nullary enum variants are written with no trailing `( )`");
921 // NB: Do not use this function unless you actually plan to place the
922 // spanned list in the AST.
923 pub fn parse_seq<T, F>(&mut self,
928 -> PResult<'a, Spanned<Vec<T>>> where
929 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
931 let lo = self.span.lo;
932 try!(self.expect(bra));
933 let result = try!(self.parse_seq_to_before_end(ket, sep, f));
934 let hi = self.span.hi;
936 Ok(spanned(lo, hi, result))
939 /// Advance the parser by one token
940 pub fn bump(&mut self) {
941 self.last_span = self.span;
942 // Stash token for error recovery (sometimes; clone is not necessarily cheap).
943 self.last_token = if self.token.is_ident() ||
944 self.token.is_path() ||
945 self.token == token::Comma {
946 Some(Box::new(self.token.clone()))
950 self.last_token_interpolated = self.token.is_interpolated();
951 let next = if self.buffer_start == self.buffer_end {
952 self.reader.real_token()
954 // Avoid token copies with `replace`.
955 let buffer_start = self.buffer_start as usize;
956 let next_index = (buffer_start + 1) & 3;
957 self.buffer_start = next_index as isize;
959 let placeholder = TokenAndSpan {
960 tok: token::Underscore,
963 mem::replace(&mut self.buffer[buffer_start], placeholder)
966 self.token = next.tok;
967 self.tokens_consumed += 1;
968 self.expected_tokens.clear();
969 // check after each token
970 self.check_unknown_macro_variable();
973 /// Advance the parser by one token and return the bumped token.
974 pub fn bump_and_get(&mut self) -> token::Token {
975 let old_token = mem::replace(&mut self.token, token::Underscore);
980 /// EFFECT: replace the current token and span with the given one
981 pub fn replace_token(&mut self,
985 self.last_span = mk_sp(self.span.lo, lo);
987 self.span = mk_sp(lo, hi);
989 pub fn buffer_length(&mut self) -> isize {
990 if self.buffer_start <= self.buffer_end {
991 return self.buffer_end - self.buffer_start;
993 return (4 - self.buffer_start) + self.buffer_end;
995 pub fn look_ahead<R, F>(&mut self, distance: usize, f: F) -> R where
996 F: FnOnce(&token::Token) -> R,
998 let dist = distance as isize;
999 while self.buffer_length() < dist {
1000 self.buffer[self.buffer_end as usize] = self.reader.real_token();
1001 self.buffer_end = (self.buffer_end + 1) & 3;
1003 f(&self.buffer[((self.buffer_start + dist - 1) & 3) as usize].tok)
1005 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
1006 self.sess.span_diagnostic.struct_span_fatal(self.span, m)
1008 pub fn span_fatal(&self, sp: Span, m: &str) -> DiagnosticBuilder<'a> {
1009 self.sess.span_diagnostic.struct_span_fatal(sp, m)
1011 pub fn span_fatal_help(&self, sp: Span, m: &str, help: &str) -> DiagnosticBuilder<'a> {
1012 let mut err = self.sess.span_diagnostic.struct_span_fatal(sp, m);
1013 err.fileline_help(sp, help);
1016 pub fn bug(&self, m: &str) -> ! {
1017 self.sess.span_diagnostic.span_bug(self.span, m)
1019 pub fn warn(&self, m: &str) {
1020 self.sess.span_diagnostic.span_warn(self.span, m)
1022 pub fn span_warn(&self, sp: Span, m: &str) {
1023 self.sess.span_diagnostic.span_warn(sp, m)
1025 pub fn span_err(&self, sp: Span, m: &str) {
1026 self.sess.span_diagnostic.span_err(sp, m)
1028 pub fn span_bug(&self, sp: Span, m: &str) -> ! {
1029 self.sess.span_diagnostic.span_bug(sp, m)
1031 pub fn abort_if_errors(&self) {
1032 self.sess.span_diagnostic.abort_if_errors();
1035 pub fn diagnostic(&self) -> &'a errors::Handler {
1036 &self.sess.span_diagnostic
1039 pub fn id_to_interned_str(&mut self, id: Ident) -> InternedString {
1043 /// Is the current token one of the keywords that signals a bare function
1045 pub fn token_is_bare_fn_keyword(&mut self) -> bool {
1046 self.check_keyword(keywords::Fn) ||
1047 self.check_keyword(keywords::Unsafe) ||
1048 self.check_keyword(keywords::Extern)
1051 pub fn get_lifetime(&mut self) -> ast::Ident {
1053 token::Lifetime(ref ident) => *ident,
1054 _ => self.bug("not a lifetime"),
1058 pub fn parse_for_in_type(&mut self) -> PResult<'a, Ty_> {
1060 Parses whatever can come after a `for` keyword in a type.
1061 The `for` has already been consumed.
1065 - for <'lt> |S| -> T
1069 - for <'lt> [unsafe] [extern "ABI"] fn (S) -> T
1070 - for <'lt> path::foo(a, b)
1075 let lo = self.span.lo;
1077 let lifetime_defs = try!(self.parse_late_bound_lifetime_defs());
1079 // examine next token to decide to do
1080 if self.token_is_bare_fn_keyword() {
1081 self.parse_ty_bare_fn(lifetime_defs)
1083 let hi = self.span.hi;
1084 let trait_ref = try!(self.parse_trait_ref());
1085 let poly_trait_ref = ast::PolyTraitRef { bound_lifetimes: lifetime_defs,
1086 trait_ref: trait_ref,
1087 span: mk_sp(lo, hi)};
1088 let other_bounds = if self.eat(&token::BinOp(token::Plus)) {
1089 try!(self.parse_ty_param_bounds(BoundParsingMode::Bare))
1094 Some(TraitTyParamBound(poly_trait_ref, TraitBoundModifier::None)).into_iter()
1095 .chain(other_bounds.into_vec())
1097 Ok(ast::TyPolyTraitRef(all_bounds))
1101 pub fn parse_ty_path(&mut self) -> PResult<'a, Ty_> {
1102 Ok(TyPath(None, try!(self.parse_path(LifetimeAndTypesWithoutColons))))
1105 /// parse a TyBareFn type:
1106 pub fn parse_ty_bare_fn(&mut self, lifetime_defs: Vec<ast::LifetimeDef>) -> PResult<'a, Ty_> {
1109 [unsafe] [extern "ABI"] fn <'lt> (S) -> T
1110 ^~~~^ ^~~~^ ^~~~^ ^~^ ^
1113 | | | Argument types
1119 let unsafety = try!(self.parse_unsafety());
1120 let abi = if self.eat_keyword(keywords::Extern) {
1121 try!(self.parse_opt_abi()).unwrap_or(abi::C)
1126 try!(self.expect_keyword(keywords::Fn));
1127 let (inputs, variadic) = try!(self.parse_fn_args(false, true));
1128 let ret_ty = try!(self.parse_ret_ty());
1129 let decl = P(FnDecl {
1134 Ok(TyBareFn(P(BareFnTy {
1137 lifetimes: lifetime_defs,
1142 /// Parses an obsolete closure kind (`&:`, `&mut:`, or `:`).
1143 pub fn parse_obsolete_closure_kind(&mut self) -> PResult<'a, ()> {
1144 let lo = self.span.lo;
1146 self.check(&token::BinOp(token::And)) &&
1147 self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
1148 self.look_ahead(2, |t| *t == token::Colon)
1154 self.token == token::BinOp(token::And) &&
1155 self.look_ahead(1, |t| *t == token::Colon)
1160 self.eat(&token::Colon)
1167 let span = mk_sp(lo, self.span.hi);
1168 self.obsolete(span, ObsoleteSyntax::ClosureKind);
1172 pub fn parse_unsafety(&mut self) -> PResult<'a, Unsafety> {
1173 if self.eat_keyword(keywords::Unsafe) {
1174 return Ok(Unsafety::Unsafe);
1176 return Ok(Unsafety::Normal);
1180 /// Parse the items in a trait declaration
1181 pub fn parse_trait_items(&mut self) -> PResult<'a, Vec<P<TraitItem>>> {
1182 self.parse_unspanned_seq(
1183 &token::OpenDelim(token::Brace),
1184 &token::CloseDelim(token::Brace),
1186 |p| -> PResult<'a, P<TraitItem>> {
1187 maybe_whole!(no_clone p, NtTraitItem);
1188 let mut attrs = try!(p.parse_outer_attributes());
1191 let (name, node) = if p.eat_keyword(keywords::Type) {
1192 let TyParam {ident, bounds, default, ..} = try!(p.parse_ty_param());
1193 try!(p.expect(&token::Semi));
1194 (ident, TypeTraitItem(bounds, default))
1195 } else if p.is_const_item() {
1196 try!(p.expect_keyword(keywords::Const));
1197 let ident = try!(p.parse_ident());
1198 try!(p.expect(&token::Colon));
1199 let ty = try!(p.parse_ty_sum());
1200 let default = if p.check(&token::Eq) {
1202 let expr = try!(p.parse_expr());
1203 try!(p.commit_expr_expecting(&expr, token::Semi));
1206 try!(p.expect(&token::Semi));
1209 (ident, ConstTraitItem(ty, default))
1211 let (constness, unsafety, abi) = try!(p.parse_fn_front_matter());
1213 let ident = try!(p.parse_ident());
1214 let mut generics = try!(p.parse_generics());
1216 let (explicit_self, d) = try!(p.parse_fn_decl_with_self(|p: &mut Parser<'a>|{
1217 // This is somewhat dubious; We don't want to allow
1218 // argument names to be left off if there is a
1220 p.parse_arg_general(false)
1223 generics.where_clause = try!(p.parse_where_clause());
1224 let sig = ast::MethodSig {
1226 constness: constness,
1230 explicit_self: explicit_self,
1233 let body = match p.token {
1236 debug!("parse_trait_methods(): parsing required method");
1239 token::OpenDelim(token::Brace) => {
1240 debug!("parse_trait_methods(): parsing provided method");
1241 let (inner_attrs, body) =
1242 try!(p.parse_inner_attrs_and_block());
1243 attrs.extend(inner_attrs.iter().cloned());
1248 let token_str = p.this_token_to_string();
1249 return Err(p.fatal(&format!("expected `;` or `{{`, found `{}`",
1253 (ident, ast::MethodTraitItem(sig, body))
1257 id: ast::DUMMY_NODE_ID,
1261 span: mk_sp(lo, p.last_span.hi),
1266 /// Parse a possibly mutable type
1267 pub fn parse_mt(&mut self) -> PResult<'a, MutTy> {
1268 let mutbl = try!(self.parse_mutability());
1269 let t = try!(self.parse_ty());
1270 Ok(MutTy { ty: t, mutbl: mutbl })
1273 /// Parse optional return type [ -> TY ] in function decl
1274 pub fn parse_ret_ty(&mut self) -> PResult<'a, FunctionRetTy> {
1275 if self.eat(&token::RArrow) {
1276 if self.eat(&token::Not) {
1277 Ok(NoReturn(self.last_span))
1279 Ok(Return(try!(self.parse_ty())))
1282 let pos = self.span.lo;
1283 Ok(DefaultReturn(mk_sp(pos, pos)))
1287 /// Parse a type in a context where `T1+T2` is allowed.
1288 pub fn parse_ty_sum(&mut self) -> PResult<'a, P<Ty>> {
1289 let lo = self.span.lo;
1290 let lhs = try!(self.parse_ty());
1292 if !self.eat(&token::BinOp(token::Plus)) {
1296 let bounds = try!(self.parse_ty_param_bounds(BoundParsingMode::Bare));
1298 // In type grammar, `+` is treated like a binary operator,
1299 // and hence both L and R side are required.
1300 if bounds.is_empty() {
1301 let last_span = self.last_span;
1302 self.span_err(last_span,
1303 "at least one type parameter bound \
1304 must be specified");
1307 let sp = mk_sp(lo, self.last_span.hi);
1308 let sum = ast::TyObjectSum(lhs, bounds);
1309 Ok(P(Ty {id: ast::DUMMY_NODE_ID, node: sum, span: sp}))
1313 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1314 maybe_whole!(no_clone self, NtTy);
1316 let lo = self.span.lo;
1318 let t = if self.check(&token::OpenDelim(token::Paren)) {
1321 // (t) is a parenthesized ty
1322 // (t,) is the type of a tuple with only one field,
1324 let mut ts = vec![];
1325 let mut last_comma = false;
1326 while self.token != token::CloseDelim(token::Paren) {
1327 ts.push(try!(self.parse_ty_sum()));
1328 if self.check(&token::Comma) {
1337 try!(self.expect(&token::CloseDelim(token::Paren)));
1338 if ts.len() == 1 && !last_comma {
1339 TyParen(ts.into_iter().nth(0).unwrap())
1343 } else if self.check(&token::BinOp(token::Star)) {
1344 // STAR POINTER (bare pointer?)
1346 TyPtr(try!(self.parse_ptr()))
1347 } else if self.check(&token::OpenDelim(token::Bracket)) {
1349 try!(self.expect(&token::OpenDelim(token::Bracket)));
1350 let t = try!(self.parse_ty_sum());
1352 // Parse the `; e` in `[ i32; e ]`
1353 // where `e` is a const expression
1354 let t = match try!(self.maybe_parse_fixed_length_of_vec()) {
1356 Some(suffix) => TyFixedLengthVec(t, suffix)
1358 try!(self.expect(&token::CloseDelim(token::Bracket)));
1360 } else if self.check(&token::BinOp(token::And)) ||
1361 self.token == token::AndAnd {
1363 try!(self.expect_and());
1364 try!(self.parse_borrowed_pointee())
1365 } else if self.check_keyword(keywords::For) {
1366 try!(self.parse_for_in_type())
1367 } else if self.token_is_bare_fn_keyword() {
1369 try!(self.parse_ty_bare_fn(Vec::new()))
1370 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1372 // In order to not be ambiguous, the type must be surrounded by parens.
1373 try!(self.expect(&token::OpenDelim(token::Paren)));
1374 let e = try!(self.parse_expr());
1375 try!(self.expect(&token::CloseDelim(token::Paren)));
1377 } else if self.eat_lt() {
1380 try!(self.parse_qualified_path(NoTypesAllowed));
1382 TyPath(Some(qself), path)
1383 } else if self.check(&token::ModSep) ||
1384 self.token.is_ident() ||
1385 self.token.is_path() {
1386 let path = try!(self.parse_path(LifetimeAndTypesWithoutColons));
1387 if self.check(&token::Not) {
1390 let delim = try!(self.expect_open_delim());
1391 let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
1393 |p| p.parse_token_tree()));
1394 let hi = self.span.hi;
1395 TyMac(spanned(lo, hi, Mac_ { path: path, tts: tts, ctxt: EMPTY_CTXT }))
1400 } else if self.eat(&token::Underscore) {
1401 // TYPE TO BE INFERRED
1404 let this_token_str = self.this_token_to_string();
1405 let msg = format!("expected type, found `{}`", this_token_str);
1406 return Err(self.fatal(&msg[..]));
1409 let sp = mk_sp(lo, self.last_span.hi);
1410 Ok(P(Ty {id: ast::DUMMY_NODE_ID, node: t, span: sp}))
1413 pub fn parse_borrowed_pointee(&mut self) -> PResult<'a, Ty_> {
1414 // look for `&'lt` or `&'foo ` and interpret `foo` as the region name:
1415 let opt_lifetime = try!(self.parse_opt_lifetime());
1417 let mt = try!(self.parse_mt());
1418 return Ok(TyRptr(opt_lifetime, mt));
1421 pub fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1422 let mutbl = if self.eat_keyword(keywords::Mut) {
1424 } else if self.eat_keyword(keywords::Const) {
1427 let span = self.last_span;
1429 "bare raw pointers are no longer allowed, you should \
1430 likely use `*mut T`, but otherwise `*T` is now \
1431 known as `*const T`");
1434 let t = try!(self.parse_ty());
1435 Ok(MutTy { ty: t, mutbl: mutbl })
1438 pub fn is_named_argument(&mut self) -> bool {
1439 let offset = match self.token {
1440 token::BinOp(token::And) => 1,
1442 _ if self.token.is_keyword(keywords::Mut) => 1,
1446 debug!("parser is_named_argument offset:{}", offset);
1449 is_plain_ident_or_underscore(&self.token)
1450 && self.look_ahead(1, |t| *t == token::Colon)
1452 self.look_ahead(offset, |t| is_plain_ident_or_underscore(t))
1453 && self.look_ahead(offset + 1, |t| *t == token::Colon)
1457 /// This version of parse arg doesn't necessarily require
1458 /// identifier names.
1459 pub fn parse_arg_general(&mut self, require_name: bool) -> PResult<'a, Arg> {
1460 maybe_whole!(no_clone self, NtArg);
1462 let pat = if require_name || self.is_named_argument() {
1463 debug!("parse_arg_general parse_pat (require_name:{})",
1465 let pat = try!(self.parse_pat());
1467 try!(self.expect(&token::Colon));
1470 debug!("parse_arg_general ident_to_pat");
1471 ast_util::ident_to_pat(ast::DUMMY_NODE_ID,
1473 special_idents::invalid)
1476 let t = try!(self.parse_ty_sum());
1481 id: ast::DUMMY_NODE_ID,
1485 /// Parse a single function argument
1486 pub fn parse_arg(&mut self) -> PResult<'a, Arg> {
1487 self.parse_arg_general(true)
1490 /// Parse an argument in a lambda header e.g. |arg, arg|
1491 pub fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1492 let pat = try!(self.parse_pat());
1493 let t = if self.eat(&token::Colon) {
1494 try!(self.parse_ty_sum())
1497 id: ast::DUMMY_NODE_ID,
1499 span: mk_sp(self.span.lo, self.span.hi),
1505 id: ast::DUMMY_NODE_ID
1509 pub fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1510 if self.check(&token::Semi) {
1512 Ok(Some(try!(self.parse_expr())))
1518 /// Matches token_lit = LIT_INTEGER | ...
1519 pub fn lit_from_token(&self, tok: &token::Token) -> PResult<'a, Lit_> {
1521 token::Interpolated(token::NtExpr(ref v)) => {
1523 ExprLit(ref lit) => { Ok(lit.node.clone()) }
1524 _ => { return self.unexpected_last(tok); }
1527 token::Literal(lit, suf) => {
1528 let (suffix_illegal, out) = match lit {
1529 token::Byte(i) => (true, LitByte(parse::byte_lit(&i.as_str()).0)),
1530 token::Char(i) => (true, LitChar(parse::char_lit(&i.as_str()).0)),
1532 // there are some valid suffixes for integer and
1533 // float literals, so all the handling is done
1535 token::Integer(s) => {
1536 (false, parse::integer_lit(&s.as_str(),
1537 suf.as_ref().map(|s| s.as_str()),
1538 &self.sess.span_diagnostic,
1541 token::Float(s) => {
1542 (false, parse::float_lit(&s.as_str(),
1543 suf.as_ref().map(|s| s.as_str()),
1544 &self.sess.span_diagnostic,
1550 LitStr(token::intern_and_get_ident(&parse::str_lit(&s.as_str())),
1553 token::StrRaw(s, n) => {
1556 token::intern_and_get_ident(&parse::raw_str_lit(&s.as_str())),
1559 token::ByteStr(i) =>
1560 (true, LitByteStr(parse::byte_str_lit(&i.as_str()))),
1561 token::ByteStrRaw(i, _) =>
1563 LitByteStr(Rc::new(i.to_string().into_bytes()))),
1567 let sp = self.last_span;
1568 self.expect_no_suffix(sp, &*format!("{} literal", lit.short_name()), suf)
1573 _ => { return self.unexpected_last(tok); }
1577 /// Matches lit = true | false | token_lit
1578 pub fn parse_lit(&mut self) -> PResult<'a, Lit> {
1579 let lo = self.span.lo;
1580 let lit = if self.eat_keyword(keywords::True) {
1582 } else if self.eat_keyword(keywords::False) {
1585 let token = self.bump_and_get();
1586 let lit = try!(self.lit_from_token(&token));
1589 Ok(codemap::Spanned { node: lit, span: mk_sp(lo, self.last_span.hi) })
1592 /// matches '-' lit | lit
1593 pub fn parse_pat_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1594 let minus_lo = self.span.lo;
1595 let minus_present = self.eat(&token::BinOp(token::Minus));
1596 let lo = self.span.lo;
1597 let literal = P(try!(self.parse_lit()));
1598 let hi = self.last_span.hi;
1599 let expr = self.mk_expr(lo, hi, ExprLit(literal), None);
1602 let minus_hi = self.last_span.hi;
1603 let unary = self.mk_unary(UnNeg, expr);
1604 Ok(self.mk_expr(minus_lo, minus_hi, unary, None))
1610 /// Parses qualified path.
1612 /// Assumes that the leading `<` has been parsed already.
1614 /// Qualifed paths are a part of the universal function call
1617 /// `qualified_path = <type [as trait_ref]>::path`
1619 /// See `parse_path` for `mode` meaning.
1624 /// `<T as U>::F::a::<S>`
1625 pub fn parse_qualified_path(&mut self, mode: PathParsingMode)
1626 -> PResult<'a, (QSelf, ast::Path)> {
1627 let span = self.last_span;
1628 let self_type = try!(self.parse_ty_sum());
1629 let mut path = if self.eat_keyword(keywords::As) {
1630 try!(self.parse_path(LifetimeAndTypesWithoutColons))
1641 position: path.segments.len()
1644 try!(self.expect(&token::Gt));
1645 try!(self.expect(&token::ModSep));
1647 let segments = match mode {
1648 LifetimeAndTypesWithoutColons => {
1649 try!(self.parse_path_segments_without_colons())
1651 LifetimeAndTypesWithColons => {
1652 try!(self.parse_path_segments_with_colons())
1655 try!(self.parse_path_segments_without_types())
1658 path.segments.extend(segments);
1660 path.span.hi = self.last_span.hi;
1665 /// Parses a path and optional type parameter bounds, depending on the
1666 /// mode. The `mode` parameter determines whether lifetimes, types, and/or
1667 /// bounds are permitted and whether `::` must precede type parameter
1669 pub fn parse_path(&mut self, mode: PathParsingMode) -> PResult<'a, ast::Path> {
1670 // Check for a whole path...
1671 let found = match self.token {
1672 token::Interpolated(token::NtPath(_)) => Some(self.bump_and_get()),
1675 if let Some(token::Interpolated(token::NtPath(path))) = found {
1679 let lo = self.span.lo;
1680 let is_global = self.eat(&token::ModSep);
1682 // Parse any number of segments and bound sets. A segment is an
1683 // identifier followed by an optional lifetime and a set of types.
1684 // A bound set is a set of type parameter bounds.
1685 let segments = match mode {
1686 LifetimeAndTypesWithoutColons => {
1687 try!(self.parse_path_segments_without_colons())
1689 LifetimeAndTypesWithColons => {
1690 try!(self.parse_path_segments_with_colons())
1693 try!(self.parse_path_segments_without_types())
1697 // Assemble the span.
1698 let span = mk_sp(lo, self.last_span.hi);
1700 // Assemble the result.
1709 /// - `a::b<T,U>::c<V,W>`
1710 /// - `a::b<T,U>::c(V) -> W`
1711 /// - `a::b<T,U>::c(V)`
1712 pub fn parse_path_segments_without_colons(&mut self) -> PResult<'a, Vec<ast::PathSegment>> {
1713 let mut segments = Vec::new();
1715 // First, parse an identifier.
1716 let identifier = try!(self.parse_ident_or_self_type());
1718 // Parse types, optionally.
1719 let parameters = if self.eat_lt() {
1720 let (lifetimes, types, bindings) = try!(self.parse_generic_values_after_lt());
1722 ast::PathParameters::AngleBracketed(ast::AngleBracketedParameterData {
1723 lifetimes: lifetimes,
1724 types: P::from_vec(types),
1725 bindings: P::from_vec(bindings),
1727 } else if self.eat(&token::OpenDelim(token::Paren)) {
1728 let lo = self.last_span.lo;
1730 let inputs = try!(self.parse_seq_to_end(
1731 &token::CloseDelim(token::Paren),
1732 seq_sep_trailing_allowed(token::Comma),
1733 |p| p.parse_ty_sum()));
1735 let output_ty = if self.eat(&token::RArrow) {
1736 Some(try!(self.parse_ty()))
1741 let hi = self.last_span.hi;
1743 ast::PathParameters::Parenthesized(ast::ParenthesizedParameterData {
1744 span: mk_sp(lo, hi),
1749 ast::PathParameters::none()
1752 // Assemble and push the result.
1753 segments.push(ast::PathSegment { identifier: identifier,
1754 parameters: parameters });
1756 // Continue only if we see a `::`
1757 if !self.eat(&token::ModSep) {
1758 return Ok(segments);
1764 /// - `a::b::<T,U>::c`
1765 pub fn parse_path_segments_with_colons(&mut self) -> PResult<'a, Vec<ast::PathSegment>> {
1766 let mut segments = Vec::new();
1768 // First, parse an identifier.
1769 let identifier = try!(self.parse_ident_or_self_type());
1771 // If we do not see a `::`, stop.
1772 if !self.eat(&token::ModSep) {
1773 segments.push(ast::PathSegment {
1774 identifier: identifier,
1775 parameters: ast::PathParameters::none()
1777 return Ok(segments);
1780 // Check for a type segment.
1782 // Consumed `a::b::<`, go look for types
1783 let (lifetimes, types, bindings) = try!(self.parse_generic_values_after_lt());
1784 let parameters = ast::AngleBracketedParameterData {
1785 lifetimes: lifetimes,
1786 types: P::from_vec(types),
1787 bindings: P::from_vec(bindings),
1789 segments.push(ast::PathSegment {
1790 identifier: identifier,
1791 parameters: ast::PathParameters::AngleBracketed(parameters),
1794 // Consumed `a::b::<T,U>`, check for `::` before proceeding
1795 if !self.eat(&token::ModSep) {
1796 return Ok(segments);
1799 // Consumed `a::`, go look for `b`
1800 segments.push(ast::PathSegment {
1801 identifier: identifier,
1802 parameters: ast::PathParameters::none(),
1811 pub fn parse_path_segments_without_types(&mut self) -> PResult<'a, Vec<ast::PathSegment>> {
1812 let mut segments = Vec::new();
1814 // First, parse an identifier.
1815 let identifier = try!(self.parse_ident_or_self_type());
1817 // Assemble and push the result.
1818 segments.push(ast::PathSegment {
1819 identifier: identifier,
1820 parameters: ast::PathParameters::none()
1823 // If we do not see a `::`, stop.
1824 if !self.eat(&token::ModSep) {
1825 return Ok(segments);
1830 /// parses 0 or 1 lifetime
1831 pub fn parse_opt_lifetime(&mut self) -> PResult<'a, Option<ast::Lifetime>> {
1833 token::Lifetime(..) => {
1834 Ok(Some(try!(self.parse_lifetime())))
1842 /// Parses a single lifetime
1843 /// Matches lifetime = LIFETIME
1844 pub fn parse_lifetime(&mut self) -> PResult<'a, ast::Lifetime> {
1846 token::Lifetime(i) => {
1847 let span = self.span;
1849 return Ok(ast::Lifetime {
1850 id: ast::DUMMY_NODE_ID,
1856 return Err(self.fatal("expected a lifetime name"));
1861 /// Parses `lifetime_defs = [ lifetime_defs { ',' lifetime_defs } ]` where `lifetime_def =
1862 /// lifetime [':' lifetimes]`
1863 pub fn parse_lifetime_defs(&mut self) -> PResult<'a, Vec<ast::LifetimeDef>> {
1865 let mut res = Vec::new();
1868 token::Lifetime(_) => {
1869 let lifetime = try!(self.parse_lifetime());
1871 if self.eat(&token::Colon) {
1872 try!(self.parse_lifetimes(token::BinOp(token::Plus)))
1876 res.push(ast::LifetimeDef { lifetime: lifetime,
1886 token::Comma => { self.bump();}
1887 token::Gt => { return Ok(res); }
1888 token::BinOp(token::Shr) => { return Ok(res); }
1890 let this_token_str = self.this_token_to_string();
1891 let msg = format!("expected `,` or `>` after lifetime \
1894 return Err(self.fatal(&msg[..]));
1900 /// matches lifetimes = ( lifetime ) | ( lifetime , lifetimes ) actually, it matches the empty
1901 /// one too, but putting that in there messes up the grammar....
1903 /// Parses zero or more comma separated lifetimes. Expects each lifetime to be followed by
1904 /// either a comma or `>`. Used when parsing type parameter lists, where we expect something
1905 /// like `<'a, 'b, T>`.
1906 pub fn parse_lifetimes(&mut self, sep: token::Token) -> PResult<'a, Vec<ast::Lifetime>> {
1908 let mut res = Vec::new();
1911 token::Lifetime(_) => {
1912 res.push(try!(self.parse_lifetime()));
1919 if self.token != sep {
1927 /// Parse mutability declaration (mut/const/imm)
1928 pub fn parse_mutability(&mut self) -> PResult<'a, Mutability> {
1929 if self.eat_keyword(keywords::Mut) {
1936 /// Parse ident COLON expr
1937 pub fn parse_field(&mut self) -> PResult<'a, Field> {
1938 let lo = self.span.lo;
1939 let i = try!(self.parse_ident());
1940 let hi = self.last_span.hi;
1941 try!(self.expect(&token::Colon));
1942 let e = try!(self.parse_expr());
1944 ident: spanned(lo, hi, i),
1945 span: mk_sp(lo, e.span.hi),
1950 pub fn mk_expr(&mut self, lo: BytePos, hi: BytePos,
1951 node: Expr_, attrs: ThinAttributes) -> P<Expr> {
1953 id: ast::DUMMY_NODE_ID,
1955 span: mk_sp(lo, hi),
1960 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::Expr_ {
1961 ExprUnary(unop, expr)
1964 pub fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::Expr_ {
1965 ExprBinary(binop, lhs, rhs)
1968 pub fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::Expr_ {
1972 fn mk_method_call(&mut self,
1973 ident: ast::SpannedIdent,
1977 ExprMethodCall(ident, tps, args)
1980 pub fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::Expr_ {
1981 ExprIndex(expr, idx)
1984 pub fn mk_range(&mut self,
1985 start: Option<P<Expr>>,
1986 end: Option<P<Expr>>)
1988 ExprRange(start, end)
1991 pub fn mk_field(&mut self, expr: P<Expr>, ident: ast::SpannedIdent) -> ast::Expr_ {
1992 ExprField(expr, ident)
1995 pub fn mk_tup_field(&mut self, expr: P<Expr>, idx: codemap::Spanned<usize>) -> ast::Expr_ {
1996 ExprTupField(expr, idx)
1999 pub fn mk_assign_op(&mut self, binop: ast::BinOp,
2000 lhs: P<Expr>, rhs: P<Expr>) -> ast::Expr_ {
2001 ExprAssignOp(binop, lhs, rhs)
2004 pub fn mk_mac_expr(&mut self, lo: BytePos, hi: BytePos,
2005 m: Mac_, attrs: ThinAttributes) -> P<Expr> {
2007 id: ast::DUMMY_NODE_ID,
2008 node: ExprMac(codemap::Spanned {node: m, span: mk_sp(lo, hi)}),
2009 span: mk_sp(lo, hi),
2014 pub fn mk_lit_u32(&mut self, i: u32, attrs: ThinAttributes) -> P<Expr> {
2015 let span = &self.span;
2016 let lv_lit = P(codemap::Spanned {
2017 node: LitInt(i as u64, ast::UnsignedIntLit(TyU32)),
2022 id: ast::DUMMY_NODE_ID,
2023 node: ExprLit(lv_lit),
2029 fn expect_open_delim(&mut self) -> PResult<'a, token::DelimToken> {
2030 self.expected_tokens.push(TokenType::Token(token::Gt));
2032 token::OpenDelim(delim) => {
2036 _ => Err(self.fatal("expected open delimiter")),
2040 /// At the bottom (top?) of the precedence hierarchy,
2041 /// parse things like parenthesized exprs,
2042 /// macros, return, etc.
2044 /// NB: This does not parse outer attributes,
2045 /// and is private because it only works
2046 /// correctly if called from parse_dot_or_call_expr().
2047 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2048 maybe_whole_expr!(self);
2050 // Outer attributes are already parsed and will be
2051 // added to the return value after the fact.
2053 // Therefore, prevent sub-parser from parsing
2054 // attributes by giving them a empty "already parsed" list.
2055 let mut attrs = None;
2057 let lo = self.span.lo;
2058 let mut hi = self.span.hi;
2062 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2064 token::OpenDelim(token::Paren) => {
2067 let attrs = try!(self.parse_inner_attributes())
2071 // (e) is parenthesized e
2072 // (e,) is a tuple with only one field, e
2073 let mut es = vec![];
2074 let mut trailing_comma = false;
2075 while self.token != token::CloseDelim(token::Paren) {
2076 es.push(try!(self.parse_expr()));
2077 try!(self.commit_expr(&**es.last().unwrap(), &[],
2078 &[token::Comma, token::CloseDelim(token::Paren)]));
2079 if self.check(&token::Comma) {
2080 trailing_comma = true;
2084 trailing_comma = false;
2090 hi = self.last_span.hi;
2091 return if es.len() == 1 && !trailing_comma {
2092 Ok(self.mk_expr(lo, hi, ExprParen(es.into_iter().nth(0).unwrap()), attrs))
2094 Ok(self.mk_expr(lo, hi, ExprTup(es), attrs))
2097 token::OpenDelim(token::Brace) => {
2098 return self.parse_block_expr(lo, DefaultBlock, attrs);
2100 token::BinOp(token::Or) | token::OrOr => {
2101 let lo = self.span.lo;
2102 return self.parse_lambda_expr(lo, CaptureByRef, attrs);
2104 token::Ident(id @ ast::Ident {
2105 name: token::SELF_KEYWORD_NAME,
2107 }, token::Plain) => {
2109 let path = ast_util::ident_to_path(mk_sp(lo, hi), id);
2110 ex = ExprPath(None, path);
2111 hi = self.last_span.hi;
2113 token::OpenDelim(token::Bracket) => {
2116 let inner_attrs = try!(self.parse_inner_attributes())
2118 attrs.update(|attrs| attrs.append(inner_attrs));
2120 if self.check(&token::CloseDelim(token::Bracket)) {
2123 ex = ExprVec(Vec::new());
2126 let first_expr = try!(self.parse_expr());
2127 if self.check(&token::Semi) {
2128 // Repeating array syntax: [ 0; 512 ]
2130 let count = try!(self.parse_expr());
2131 try!(self.expect(&token::CloseDelim(token::Bracket)));
2132 ex = ExprRepeat(first_expr, count);
2133 } else if self.check(&token::Comma) {
2134 // Vector with two or more elements.
2136 let remaining_exprs = try!(self.parse_seq_to_end(
2137 &token::CloseDelim(token::Bracket),
2138 seq_sep_trailing_allowed(token::Comma),
2139 |p| Ok(try!(p.parse_expr()))
2141 let mut exprs = vec!(first_expr);
2142 exprs.extend(remaining_exprs);
2143 ex = ExprVec(exprs);
2145 // Vector with one element.
2146 try!(self.expect(&token::CloseDelim(token::Bracket)));
2147 ex = ExprVec(vec!(first_expr));
2150 hi = self.last_span.hi;
2155 try!(self.parse_qualified_path(LifetimeAndTypesWithColons));
2157 return Ok(self.mk_expr(lo, hi, ExprPath(Some(qself), path), attrs));
2159 if self.eat_keyword(keywords::Move) {
2160 let lo = self.last_span.lo;
2161 return self.parse_lambda_expr(lo, CaptureByValue, attrs);
2163 if self.eat_keyword(keywords::If) {
2164 return self.parse_if_expr(attrs);
2166 if self.eat_keyword(keywords::For) {
2167 let lo = self.last_span.lo;
2168 return self.parse_for_expr(None, lo, attrs);
2170 if self.eat_keyword(keywords::While) {
2171 let lo = self.last_span.lo;
2172 return self.parse_while_expr(None, lo, attrs);
2174 if self.token.is_lifetime() {
2175 let lifetime = self.get_lifetime();
2176 let lo = self.span.lo;
2178 try!(self.expect(&token::Colon));
2179 if self.eat_keyword(keywords::While) {
2180 return self.parse_while_expr(Some(lifetime), lo, attrs)
2182 if self.eat_keyword(keywords::For) {
2183 return self.parse_for_expr(Some(lifetime), lo, attrs)
2185 if self.eat_keyword(keywords::Loop) {
2186 return self.parse_loop_expr(Some(lifetime), lo, attrs)
2188 return Err(self.fatal("expected `while`, `for`, or `loop` after a label"))
2190 if self.eat_keyword(keywords::Loop) {
2191 let lo = self.last_span.lo;
2192 return self.parse_loop_expr(None, lo, attrs);
2194 if self.eat_keyword(keywords::Continue) {
2195 let ex = if self.token.is_lifetime() {
2196 let ex = ExprAgain(Some(Spanned{
2197 node: self.get_lifetime(),
2205 let hi = self.last_span.hi;
2206 return Ok(self.mk_expr(lo, hi, ex, attrs));
2208 if self.eat_keyword(keywords::Match) {
2209 return self.parse_match_expr(attrs);
2211 if self.eat_keyword(keywords::Unsafe) {
2212 return self.parse_block_expr(
2214 UnsafeBlock(ast::UserProvided),
2217 if self.eat_keyword(keywords::Return) {
2218 if self.token.can_begin_expr() {
2219 let e = try!(self.parse_expr());
2221 ex = ExprRet(Some(e));
2225 } else if self.eat_keyword(keywords::Break) {
2226 if self.token.is_lifetime() {
2227 ex = ExprBreak(Some(Spanned {
2228 node: self.get_lifetime(),
2233 ex = ExprBreak(None);
2235 hi = self.last_span.hi;
2236 } else if self.token.is_keyword(keywords::Let) {
2237 // Catch this syntax error here, instead of in `check_strict_keywords`, so
2238 // that we can explicitly mention that let is not to be used as an expression
2239 let mut db = self.fatal("expected expression, found statement (`let`)");
2240 db.note("variable declaration using `let` is a statement");
2242 } else if self.check(&token::ModSep) ||
2243 self.token.is_ident() &&
2244 !self.check_keyword(keywords::True) &&
2245 !self.check_keyword(keywords::False) {
2247 try!(self.parse_path(LifetimeAndTypesWithColons));
2249 // `!`, as an operator, is prefix, so we know this isn't that
2250 if self.check(&token::Not) {
2251 // MACRO INVOCATION expression
2254 let delim = try!(self.expect_open_delim());
2255 let tts = try!(self.parse_seq_to_end(
2256 &token::CloseDelim(delim),
2258 |p| p.parse_token_tree()));
2259 let hi = self.last_span.hi;
2261 return Ok(self.mk_mac_expr(lo,
2263 Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT },
2266 if self.check(&token::OpenDelim(token::Brace)) {
2267 // This is a struct literal, unless we're prohibited
2268 // from parsing struct literals here.
2269 let prohibited = self.restrictions.contains(
2270 Restrictions::RESTRICTION_NO_STRUCT_LITERAL
2273 // It's a struct literal.
2275 let mut fields = Vec::new();
2276 let mut base = None;
2278 let attrs = attrs.append(
2279 try!(self.parse_inner_attributes())
2280 .into_thin_attrs());
2282 while self.token != token::CloseDelim(token::Brace) {
2283 if self.eat(&token::DotDot) {
2284 base = Some(try!(self.parse_expr()));
2288 fields.push(try!(self.parse_field()));
2289 try!(self.commit_expr(&*fields.last().unwrap().expr,
2291 &[token::CloseDelim(token::Brace)]));
2295 try!(self.expect(&token::CloseDelim(token::Brace)));
2296 ex = ExprStruct(pth, fields, base);
2297 return Ok(self.mk_expr(lo, hi, ex, attrs));
2302 ex = ExprPath(None, pth);
2304 // other literal expression
2305 let lit = try!(self.parse_lit());
2307 ex = ExprLit(P(lit));
2312 return Ok(self.mk_expr(lo, hi, ex, attrs));
2315 fn parse_or_use_outer_attributes(&mut self,
2316 already_parsed_attrs: Option<ThinAttributes>)
2317 -> PResult<'a, ThinAttributes> {
2318 if let Some(attrs) = already_parsed_attrs {
2321 self.parse_outer_attributes().map(|a| a.into_thin_attrs())
2325 /// Parse a block or unsafe block
2326 pub fn parse_block_expr(&mut self, lo: BytePos, blk_mode: BlockCheckMode,
2327 attrs: ThinAttributes)
2328 -> PResult<'a, P<Expr>> {
2330 let outer_attrs = attrs;
2331 try!(self.expect(&token::OpenDelim(token::Brace)));
2333 let inner_attrs = try!(self.parse_inner_attributes()).into_thin_attrs();
2334 let attrs = outer_attrs.append(inner_attrs);
2336 let blk = try!(self.parse_block_tail(lo, blk_mode));
2337 return Ok(self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk), attrs));
2340 /// parse a.b or a(13) or a[4] or just a
2341 pub fn parse_dot_or_call_expr(&mut self,
2342 already_parsed_attrs: Option<ThinAttributes>)
2343 -> PResult<'a, P<Expr>> {
2344 let attrs = try!(self.parse_or_use_outer_attributes(already_parsed_attrs));
2346 let b = self.parse_bottom_expr();
2347 let (span, b) = try!(self.interpolated_or_expr_span(b));
2348 self.parse_dot_or_call_expr_with(b, span.lo, attrs)
2351 pub fn parse_dot_or_call_expr_with(&mut self,
2354 attrs: ThinAttributes)
2355 -> PResult<'a, P<Expr>> {
2356 // Stitch the list of outer attributes onto the return value.
2357 // A little bit ugly, but the best way given the current code
2359 self.parse_dot_or_call_expr_with_(e0, lo)
2361 expr.map(|mut expr| {
2362 expr.attrs.update(|a| a.prepend(attrs));
2364 ExprIf(..) | ExprIfLet(..) => {
2365 if !expr.attrs.as_attr_slice().is_empty() {
2366 // Just point to the first attribute in there...
2367 let span = expr.attrs.as_attr_slice()[0].span;
2370 "attributes are not yet allowed on `if` \
2381 // Assuming we have just parsed `.foo` (i.e., a dot and an ident), continue
2382 // parsing into an expression.
2383 fn parse_dot_suffix(&mut self,
2386 self_value: P<Expr>,
2388 -> PResult<'a, P<Expr>> {
2389 let (_, tys, bindings) = if self.eat(&token::ModSep) {
2390 try!(self.expect_lt());
2391 try!(self.parse_generic_values_after_lt())
2393 (Vec::new(), Vec::new(), Vec::new())
2396 if !bindings.is_empty() {
2397 let last_span = self.last_span;
2398 self.span_err(last_span, "type bindings are only permitted on trait paths");
2401 Ok(match self.token {
2402 // expr.f() method call.
2403 token::OpenDelim(token::Paren) => {
2404 let mut es = try!(self.parse_unspanned_seq(
2405 &token::OpenDelim(token::Paren),
2406 &token::CloseDelim(token::Paren),
2407 seq_sep_trailing_allowed(token::Comma),
2408 |p| Ok(try!(p.parse_expr()))
2410 let hi = self.last_span.hi;
2412 es.insert(0, self_value);
2413 let id = spanned(ident_span.lo, ident_span.hi, ident);
2414 let nd = self.mk_method_call(id, tys, es);
2415 self.mk_expr(lo, hi, nd, None)
2419 if !tys.is_empty() {
2420 let last_span = self.last_span;
2421 self.span_err(last_span,
2422 "field expressions may not \
2423 have type parameters");
2426 let id = spanned(ident_span.lo, ident_span.hi, ident);
2427 let field = self.mk_field(self_value, id);
2428 self.mk_expr(lo, ident_span.hi, field, None)
2433 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: BytePos) -> PResult<'a, P<Expr>> {
2438 if self.eat(&token::Dot) {
2440 token::Ident(i, _) => {
2441 let dot_pos = self.last_span.hi;
2445 e = try!(self.parse_dot_suffix(i, mk_sp(dot_pos, hi), e, lo));
2447 token::Literal(token::Integer(n), suf) => {
2450 // A tuple index may not have a suffix
2451 self.expect_no_suffix(sp, "tuple index", suf);
2453 let dot = self.last_span.hi;
2457 let index = n.as_str().parse::<usize>().ok();
2460 let id = spanned(dot, hi, n);
2461 let field = self.mk_tup_field(e, id);
2462 e = self.mk_expr(lo, hi, field, None);
2465 let last_span = self.last_span;
2466 self.span_err(last_span, "invalid tuple or tuple struct index");
2470 token::Literal(token::Float(n), _suf) => {
2472 let last_span = self.last_span;
2473 let fstr = n.as_str();
2474 let mut err = self.diagnostic().struct_span_err(last_span,
2475 &format!("unexpected token: `{}`", n.as_str()));
2476 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2477 let float = match fstr.parse::<f64>().ok() {
2481 err.fileline_help(last_span,
2482 &format!("try parenthesizing the first index; e.g., `(foo.{}){}`",
2483 float.trunc() as usize,
2484 format!(".{}", fstr.splitn(2, ".").last().unwrap())));
2490 // FIXME Could factor this out into non_fatal_unexpected or something.
2491 let actual = self.this_token_to_string();
2492 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
2494 let dot_pos = self.last_span.hi;
2495 e = try!(self.parse_dot_suffix(special_idents::invalid,
2496 mk_sp(dot_pos, dot_pos),
2502 if self.expr_is_complete(&*e) { break; }
2505 token::OpenDelim(token::Paren) => {
2506 let es = try!(self.parse_unspanned_seq(
2507 &token::OpenDelim(token::Paren),
2508 &token::CloseDelim(token::Paren),
2509 seq_sep_trailing_allowed(token::Comma),
2510 |p| Ok(try!(p.parse_expr()))
2512 hi = self.last_span.hi;
2514 let nd = self.mk_call(e, es);
2515 e = self.mk_expr(lo, hi, nd, None);
2519 // Could be either an index expression or a slicing expression.
2520 token::OpenDelim(token::Bracket) => {
2522 let ix = try!(self.parse_expr());
2524 try!(self.commit_expr_expecting(&*ix, token::CloseDelim(token::Bracket)));
2525 let index = self.mk_index(e, ix);
2526 e = self.mk_expr(lo, hi, index, None)
2534 // Parse unquoted tokens after a `$` in a token tree
2535 fn parse_unquoted(&mut self) -> PResult<'a, TokenTree> {
2536 let mut sp = self.span;
2537 let (name, namep) = match self.token {
2541 if self.token == token::OpenDelim(token::Paren) {
2542 let Spanned { node: seq, span: seq_span } = try!(self.parse_seq(
2543 &token::OpenDelim(token::Paren),
2544 &token::CloseDelim(token::Paren),
2546 |p| p.parse_token_tree()
2548 let (sep, repeat) = try!(self.parse_sep_and_kleene_op());
2549 let name_num = macro_parser::count_names(&seq);
2550 return Ok(TokenTree::Sequence(mk_sp(sp.lo, seq_span.hi),
2551 Rc::new(SequenceRepetition {
2555 num_captures: name_num
2557 } else if self.token.is_keyword_allow_following_colon(keywords::Crate) {
2559 return Ok(TokenTree::Token(sp, SpecialVarNt(SpecialMacroVar::CrateMacroVar)));
2561 sp = mk_sp(sp.lo, self.span.hi);
2562 let namep = match self.token { token::Ident(_, p) => p, _ => token::Plain };
2563 let name = try!(self.parse_ident());
2567 token::SubstNt(name, namep) => {
2573 // continue by trying to parse the `:ident` after `$name`
2574 if self.token == token::Colon && self.look_ahead(1, |t| t.is_ident() &&
2575 !t.is_strict_keyword() &&
2576 !t.is_reserved_keyword()) {
2578 sp = mk_sp(sp.lo, self.span.hi);
2579 let kindp = match self.token { token::Ident(_, p) => p, _ => token::Plain };
2580 let nt_kind = try!(self.parse_ident());
2581 Ok(TokenTree::Token(sp, MatchNt(name, nt_kind, namep, kindp)))
2583 Ok(TokenTree::Token(sp, SubstNt(name, namep)))
2587 pub fn check_unknown_macro_variable(&mut self) {
2588 if self.quote_depth == 0 {
2590 token::SubstNt(name, _) =>
2591 self.fatal(&format!("unknown macro variable `{}`", name)).emit(),
2597 /// Parse an optional separator followed by a Kleene-style
2598 /// repetition token (+ or *).
2599 pub fn parse_sep_and_kleene_op(&mut self)
2600 -> PResult<'a, (Option<token::Token>, ast::KleeneOp)> {
2601 fn parse_kleene_op<'a>(parser: &mut Parser<'a>) -> PResult<'a, Option<ast::KleeneOp>> {
2602 match parser.token {
2603 token::BinOp(token::Star) => {
2605 Ok(Some(ast::ZeroOrMore))
2607 token::BinOp(token::Plus) => {
2609 Ok(Some(ast::OneOrMore))
2615 match try!(parse_kleene_op(self)) {
2616 Some(kleene_op) => return Ok((None, kleene_op)),
2620 let separator = self.bump_and_get();
2621 match try!(parse_kleene_op(self)) {
2622 Some(zerok) => Ok((Some(separator), zerok)),
2623 None => return Err(self.fatal("expected `*` or `+`"))
2627 /// parse a single token tree from the input.
2628 pub fn parse_token_tree(&mut self) -> PResult<'a, TokenTree> {
2629 // FIXME #6994: currently, this is too eager. It
2630 // parses token trees but also identifies TokenType::Sequence's
2631 // and token::SubstNt's; it's too early to know yet
2632 // whether something will be a nonterminal or a seq
2634 maybe_whole!(deref self, NtTT);
2636 // this is the fall-through for the 'match' below.
2637 // invariants: the current token is not a left-delimiter,
2638 // not an EOF, and not the desired right-delimiter (if
2639 // it were, parse_seq_to_before_end would have prevented
2640 // reaching this point.
2641 fn parse_non_delim_tt_tok<'b>(p: &mut Parser<'b>) -> PResult<'b, TokenTree> {
2642 maybe_whole!(deref p, NtTT);
2644 token::CloseDelim(_) => {
2645 let token_str = p.this_token_to_string();
2646 let mut err = p.fatal(
2647 &format!("incorrect close delimiter: `{}`", token_str));
2648 // This is a conservative error: only report the last unclosed delimiter. The
2649 // previous unclosed delimiters could actually be closed! The parser just hasn't
2650 // gotten to them yet.
2651 if let Some(&sp) = p.open_braces.last() {
2652 err.span_note(sp, "unclosed delimiter");
2656 /* we ought to allow different depths of unquotation */
2657 token::Dollar | token::SubstNt(..) if p.quote_depth > 0 => {
2661 Ok(TokenTree::Token(p.span, p.bump_and_get()))
2668 let open_braces = self.open_braces.clone();
2669 let mut err: DiagnosticBuilder<'a> =
2670 self.fatal("this file contains an un-closed delimiter");
2671 for sp in &open_braces {
2672 err.span_help(*sp, "did you mean to close this delimiter?");
2676 token::OpenDelim(delim) => {
2677 // The span for beginning of the delimited section
2678 let pre_span = self.span;
2680 // Parse the open delimiter.
2681 self.open_braces.push(self.span);
2682 let open_span = self.span;
2685 // Parse the token trees within the delimiters
2686 let tts = try!(self.parse_seq_to_before_end(
2687 &token::CloseDelim(delim),
2689 |p| p.parse_token_tree()
2692 // Parse the close delimiter.
2693 let close_span = self.span;
2695 self.open_braces.pop().unwrap();
2697 // Expand to cover the entire delimited token tree
2698 let span = Span { hi: close_span.hi, ..pre_span };
2700 Ok(TokenTree::Delimited(span, Rc::new(Delimited {
2702 open_span: open_span,
2704 close_span: close_span,
2707 _ => parse_non_delim_tt_tok(self),
2711 // parse a stream of tokens into a list of TokenTree's,
2713 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2714 let mut tts = Vec::new();
2715 while self.token != token::Eof {
2716 tts.push(try!(self.parse_token_tree()));
2721 /// Parse a prefix-unary-operator expr
2722 pub fn parse_prefix_expr(&mut self,
2723 already_parsed_attrs: Option<ThinAttributes>)
2724 -> PResult<'a, P<Expr>> {
2725 let attrs = try!(self.parse_or_use_outer_attributes(already_parsed_attrs));
2726 let lo = self.span.lo;
2728 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2729 let ex = match self.token {
2732 let e = self.parse_prefix_expr(None);
2733 let (span, e) = try!(self.interpolated_or_expr_span(e));
2735 self.mk_unary(UnNot, e)
2737 token::BinOp(token::Minus) => {
2739 let e = self.parse_prefix_expr(None);
2740 let (span, e) = try!(self.interpolated_or_expr_span(e));
2742 self.mk_unary(UnNeg, e)
2744 token::BinOp(token::Star) => {
2746 let e = self.parse_prefix_expr(None);
2747 let (span, e) = try!(self.interpolated_or_expr_span(e));
2749 self.mk_unary(UnDeref, e)
2751 token::BinOp(token::And) | token::AndAnd => {
2752 try!(self.expect_and());
2753 let m = try!(self.parse_mutability());
2754 let e = self.parse_prefix_expr(None);
2755 let (span, e) = try!(self.interpolated_or_expr_span(e));
2759 token::Ident(..) if self.token.is_keyword(keywords::In) => {
2761 let place = try!(self.parse_expr_res(
2762 Restrictions::RESTRICTION_NO_STRUCT_LITERAL,
2765 let blk = try!(self.parse_block());
2766 let span = blk.span;
2768 let blk_expr = self.mk_expr(span.lo, span.hi, ExprBlock(blk),
2770 ExprInPlace(place, blk_expr)
2772 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
2774 let e = self.parse_prefix_expr(None);
2775 let (span, e) = try!(self.interpolated_or_expr_span(e));
2779 _ => return self.parse_dot_or_call_expr(Some(attrs))
2781 return Ok(self.mk_expr(lo, hi, ex, attrs));
2784 /// Parse an associative expression
2786 /// This parses an expression accounting for associativity and precedence of the operators in
2788 pub fn parse_assoc_expr(&mut self,
2789 already_parsed_attrs: Option<ThinAttributes>)
2790 -> PResult<'a, P<Expr>> {
2791 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
2794 /// Parse an associative expression with operators of at least `min_prec` precedence
2795 pub fn parse_assoc_expr_with(&mut self,
2798 -> PResult<'a, P<Expr>> {
2799 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
2802 let attrs = match lhs {
2803 LhsExpr::AttributesParsed(attrs) => Some(attrs),
2806 if self.token == token::DotDot {
2807 return self.parse_prefix_range_expr(attrs);
2809 try!(self.parse_prefix_expr(attrs))
2814 if self.expr_is_complete(&*lhs) {
2815 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
2818 self.expected_tokens.push(TokenType::Operator);
2819 while let Some(op) = AssocOp::from_token(&self.token) {
2821 let lhs_span = if self.last_token_interpolated {
2827 let cur_op_span = self.span;
2828 let restrictions = if op.is_assign_like() {
2829 self.restrictions & Restrictions::RESTRICTION_NO_STRUCT_LITERAL
2833 if op.precedence() < min_prec {
2837 if op.is_comparison() {
2838 self.check_no_chained_comparison(&*lhs, &op);
2841 if op == AssocOp::As {
2842 let rhs = try!(self.parse_ty());
2843 lhs = self.mk_expr(lhs_span.lo, rhs.span.hi,
2844 ExprCast(lhs, rhs), None);
2846 } else if op == AssocOp::Colon {
2847 let rhs = try!(self.parse_ty());
2848 lhs = self.mk_expr(lhs_span.lo, rhs.span.hi,
2849 ExprType(lhs, rhs), None);
2851 } else if op == AssocOp::DotDot {
2852 // If we didn’t have to handle `x..`, it would be pretty easy to generalise
2853 // it to the Fixity::None code.
2855 // We have 2 alternatives here: `x..y` and `x..` The other two variants are
2856 // handled with `parse_prefix_range_expr` call above.
2857 let rhs = if self.is_at_start_of_range_notation_rhs() {
2858 let rhs = self.parse_assoc_expr_with(op.precedence() + 1,
2859 LhsExpr::NotYetParsed);
2870 let (lhs_span, rhs_span) = (lhs_span, if let Some(ref x) = rhs {
2875 let r = self.mk_range(Some(lhs), rhs);
2876 lhs = self.mk_expr(lhs_span.lo, rhs_span.hi, r, None);
2880 let rhs = try!(match op.fixity() {
2881 Fixity::Right => self.with_res(
2882 restrictions - Restrictions::RESTRICTION_STMT_EXPR,
2884 this.parse_assoc_expr_with(op.precedence(),
2885 LhsExpr::NotYetParsed)
2887 Fixity::Left => self.with_res(
2888 restrictions - Restrictions::RESTRICTION_STMT_EXPR,
2890 this.parse_assoc_expr_with(op.precedence() + 1,
2891 LhsExpr::NotYetParsed)
2893 // We currently have no non-associative operators that are not handled above by
2894 // the special cases. The code is here only for future convenience.
2895 Fixity::None => self.with_res(
2896 restrictions - Restrictions::RESTRICTION_STMT_EXPR,
2898 this.parse_assoc_expr_with(op.precedence() + 1,
2899 LhsExpr::NotYetParsed)
2904 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
2905 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
2906 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
2907 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
2908 AssocOp::Greater | AssocOp::GreaterEqual => {
2909 let ast_op = op.to_ast_binop().unwrap();
2910 let (lhs_span, rhs_span) = (lhs_span, rhs.span);
2911 let binary = self.mk_binary(codemap::respan(cur_op_span, ast_op), lhs, rhs);
2912 self.mk_expr(lhs_span.lo, rhs_span.hi, binary, None)
2915 self.mk_expr(lhs_span.lo, rhs.span.hi, ExprAssign(lhs, rhs), None),
2917 self.mk_expr(lhs_span.lo, rhs.span.hi, ExprInPlace(lhs, rhs), None),
2918 AssocOp::AssignOp(k) => {
2920 token::Plus => BiAdd,
2921 token::Minus => BiSub,
2922 token::Star => BiMul,
2923 token::Slash => BiDiv,
2924 token::Percent => BiRem,
2925 token::Caret => BiBitXor,
2926 token::And => BiBitAnd,
2927 token::Or => BiBitOr,
2928 token::Shl => BiShl,
2931 let (lhs_span, rhs_span) = (lhs_span, rhs.span);
2932 let aopexpr = self.mk_assign_op(codemap::respan(cur_op_span, aop), lhs, rhs);
2933 self.mk_expr(lhs_span.lo, rhs_span.hi, aopexpr, None)
2935 AssocOp::As | AssocOp::Colon | AssocOp::DotDot => {
2936 self.bug("As, Colon or DotDot branch reached")
2940 if op.fixity() == Fixity::None { break }
2945 /// Produce an error if comparison operators are chained (RFC #558).
2946 /// We only need to check lhs, not rhs, because all comparison ops
2947 /// have same precedence and are left-associative
2948 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
2949 debug_assert!(outer_op.is_comparison());
2951 ExprBinary(op, _, _) if op.node.is_comparison() => {
2952 // respan to include both operators
2953 let op_span = mk_sp(op.span.lo, self.span.hi);
2954 let mut err = self.diagnostic().struct_span_err(op_span,
2955 "chained comparison operators require parentheses");
2956 if op.node == BiLt && *outer_op == AssocOp::Greater {
2957 err.fileline_help(op_span,
2958 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
2966 /// Parse prefix-forms of range notation: `..expr` and `..`
2967 fn parse_prefix_range_expr(&mut self,
2968 already_parsed_attrs: Option<ThinAttributes>)
2969 -> PResult<'a, P<Expr>> {
2970 debug_assert!(self.token == token::DotDot);
2971 let attrs = try!(self.parse_or_use_outer_attributes(already_parsed_attrs));
2972 let lo = self.span.lo;
2973 let mut hi = self.span.hi;
2975 let opt_end = if self.is_at_start_of_range_notation_rhs() {
2976 // RHS must be parsed with more associativity than DotDot.
2977 let next_prec = AssocOp::from_token(&token::DotDot).unwrap().precedence() + 1;
2978 Some(try!(self.parse_assoc_expr_with(next_prec,
2979 LhsExpr::NotYetParsed)
2987 let r = self.mk_range(None, opt_end);
2988 Ok(self.mk_expr(lo, hi, r, attrs))
2991 fn is_at_start_of_range_notation_rhs(&self) -> bool {
2992 if self.token.can_begin_expr() {
2993 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
2994 if self.token == token::OpenDelim(token::Brace) {
2995 return !self.restrictions.contains(Restrictions::RESTRICTION_NO_STRUCT_LITERAL);
3003 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
3004 pub fn parse_if_expr(&mut self, attrs: ThinAttributes) -> PResult<'a, P<Expr>> {
3005 if self.check_keyword(keywords::Let) {
3006 return self.parse_if_let_expr(attrs);
3008 let lo = self.last_span.lo;
3009 let cond = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3010 let thn = try!(self.parse_block());
3011 let mut els: Option<P<Expr>> = None;
3012 let mut hi = thn.span.hi;
3013 if self.eat_keyword(keywords::Else) {
3014 let elexpr = try!(self.parse_else_expr());
3015 hi = elexpr.span.hi;
3018 Ok(self.mk_expr(lo, hi, ExprIf(cond, thn, els), attrs))
3021 /// Parse an 'if let' expression ('if' token already eaten)
3022 pub fn parse_if_let_expr(&mut self, attrs: ThinAttributes)
3023 -> PResult<'a, P<Expr>> {
3024 let lo = self.last_span.lo;
3025 try!(self.expect_keyword(keywords::Let));
3026 let pat = try!(self.parse_pat());
3027 try!(self.expect(&token::Eq));
3028 let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3029 let thn = try!(self.parse_block());
3030 let (hi, els) = if self.eat_keyword(keywords::Else) {
3031 let expr = try!(self.parse_else_expr());
3032 (expr.span.hi, Some(expr))
3036 Ok(self.mk_expr(lo, hi, ExprIfLet(pat, expr, thn, els), attrs))
3040 pub fn parse_lambda_expr(&mut self, lo: BytePos,
3041 capture_clause: CaptureClause,
3042 attrs: ThinAttributes)
3043 -> PResult<'a, P<Expr>>
3045 let decl = try!(self.parse_fn_block_decl());
3046 let body = match decl.output {
3047 DefaultReturn(_) => {
3048 // If no explicit return type is given, parse any
3049 // expr and wrap it up in a dummy block:
3050 let body_expr = try!(self.parse_expr());
3052 id: ast::DUMMY_NODE_ID,
3054 span: body_expr.span,
3055 expr: Some(body_expr),
3056 rules: DefaultBlock,
3060 // If an explicit return type is given, require a
3061 // block to appear (RFC 968).
3062 try!(self.parse_block())
3069 ExprClosure(capture_clause, decl, body), attrs))
3072 // `else` token already eaten
3073 pub fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3074 if self.eat_keyword(keywords::If) {
3075 return self.parse_if_expr(None);
3077 let blk = try!(self.parse_block());
3078 return Ok(self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk), None));
3082 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3083 pub fn parse_for_expr(&mut self, opt_ident: Option<ast::Ident>,
3085 attrs: ThinAttributes) -> PResult<'a, P<Expr>> {
3086 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3088 let pat = try!(self.parse_pat());
3089 try!(self.expect_keyword(keywords::In));
3090 let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3091 let (iattrs, loop_block) = try!(self.parse_inner_attrs_and_block());
3092 let attrs = attrs.append(iattrs.into_thin_attrs());
3094 let hi = self.last_span.hi;
3096 Ok(self.mk_expr(span_lo, hi,
3097 ExprForLoop(pat, expr, loop_block, opt_ident),
3101 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3102 pub fn parse_while_expr(&mut self, opt_ident: Option<ast::Ident>,
3104 attrs: ThinAttributes) -> PResult<'a, P<Expr>> {
3105 if self.token.is_keyword(keywords::Let) {
3106 return self.parse_while_let_expr(opt_ident, span_lo, attrs);
3108 let cond = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3109 let (iattrs, body) = try!(self.parse_inner_attrs_and_block());
3110 let attrs = attrs.append(iattrs.into_thin_attrs());
3111 let hi = body.span.hi;
3112 return Ok(self.mk_expr(span_lo, hi, ExprWhile(cond, body, opt_ident),
3116 /// Parse a 'while let' expression ('while' token already eaten)
3117 pub fn parse_while_let_expr(&mut self, opt_ident: Option<ast::Ident>,
3119 attrs: ThinAttributes) -> PResult<'a, P<Expr>> {
3120 try!(self.expect_keyword(keywords::Let));
3121 let pat = try!(self.parse_pat());
3122 try!(self.expect(&token::Eq));
3123 let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3124 let (iattrs, body) = try!(self.parse_inner_attrs_and_block());
3125 let attrs = attrs.append(iattrs.into_thin_attrs());
3126 let hi = body.span.hi;
3127 return Ok(self.mk_expr(span_lo, hi, ExprWhileLet(pat, expr, body, opt_ident), attrs));
3130 // parse `loop {...}`, `loop` token already eaten
3131 pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::Ident>,
3133 attrs: ThinAttributes) -> PResult<'a, P<Expr>> {
3134 let (iattrs, body) = try!(self.parse_inner_attrs_and_block());
3135 let attrs = attrs.append(iattrs.into_thin_attrs());
3136 let hi = body.span.hi;
3137 Ok(self.mk_expr(span_lo, hi, ExprLoop(body, opt_ident), attrs))
3140 // `match` token already eaten
3141 fn parse_match_expr(&mut self, attrs: ThinAttributes) -> PResult<'a, P<Expr>> {
3142 let match_span = self.last_span;
3143 let lo = self.last_span.lo;
3144 let discriminant = try!(self.parse_expr_res(
3145 Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3146 if let Err(mut e) = self.commit_expr_expecting(&*discriminant,
3147 token::OpenDelim(token::Brace)) {
3148 if self.token == token::Token::Semi {
3149 e.span_note(match_span, "did you mean to remove this `match` keyword?");
3153 let attrs = attrs.append(
3154 try!(self.parse_inner_attributes()).into_thin_attrs());
3155 let mut arms: Vec<Arm> = Vec::new();
3156 while self.token != token::CloseDelim(token::Brace) {
3157 arms.push(try!(self.parse_arm()));
3159 let hi = self.span.hi;
3161 return Ok(self.mk_expr(lo, hi, ExprMatch(discriminant, arms), attrs));
3164 pub fn parse_arm(&mut self) -> PResult<'a, Arm> {
3165 maybe_whole!(no_clone self, NtArm);
3167 let attrs = try!(self.parse_outer_attributes());
3168 let pats = try!(self.parse_pats());
3169 let mut guard = None;
3170 if self.eat_keyword(keywords::If) {
3171 guard = Some(try!(self.parse_expr()));
3173 try!(self.expect(&token::FatArrow));
3174 let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_STMT_EXPR, None));
3177 !classify::expr_is_simple_block(&*expr)
3178 && self.token != token::CloseDelim(token::Brace);
3181 try!(self.commit_expr(&*expr, &[token::Comma], &[token::CloseDelim(token::Brace)]));
3183 self.eat(&token::Comma);
3194 /// Parse an expression
3195 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3196 self.parse_expr_res(Restrictions::empty(), None)
3199 /// Evaluate the closure with restrictions in place.
3201 /// After the closure is evaluated, restrictions are reset.
3202 pub fn with_res<F>(&mut self, r: Restrictions, f: F) -> PResult<'a, P<Expr>>
3203 where F: FnOnce(&mut Self) -> PResult<'a, P<Expr>>
3205 let old = self.restrictions;
3206 self.restrictions = r;
3208 self.restrictions = old;
3213 /// Parse an expression, subject to the given restrictions
3214 pub fn parse_expr_res(&mut self, r: Restrictions,
3215 already_parsed_attrs: Option<ThinAttributes>)
3216 -> PResult<'a, P<Expr>> {
3217 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3220 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3221 fn parse_initializer(&mut self) -> PResult<'a, Option<P<Expr>>> {
3222 if self.check(&token::Eq) {
3224 Ok(Some(try!(self.parse_expr())))
3230 /// Parse patterns, separated by '|' s
3231 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3232 let mut pats = Vec::new();
3234 pats.push(try!(self.parse_pat()));
3235 if self.check(&token::BinOp(token::Or)) { self.bump();}
3236 else { return Ok(pats); }
3240 fn parse_pat_tuple_elements(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3241 let mut fields = vec![];
3242 if !self.check(&token::CloseDelim(token::Paren)) {
3243 fields.push(try!(self.parse_pat()));
3244 if self.look_ahead(1, |t| *t != token::CloseDelim(token::Paren)) {
3245 while self.eat(&token::Comma) &&
3246 !self.check(&token::CloseDelim(token::Paren)) {
3247 fields.push(try!(self.parse_pat()));
3250 if fields.len() == 1 {
3251 try!(self.expect(&token::Comma));
3257 fn parse_pat_vec_elements(
3259 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3260 let mut before = Vec::new();
3261 let mut slice = None;
3262 let mut after = Vec::new();
3263 let mut first = true;
3264 let mut before_slice = true;
3266 while self.token != token::CloseDelim(token::Bracket) {
3270 try!(self.expect(&token::Comma));
3272 if self.token == token::CloseDelim(token::Bracket)
3273 && (before_slice || !after.is_empty()) {
3279 if self.check(&token::DotDot) {
3282 if self.check(&token::Comma) ||
3283 self.check(&token::CloseDelim(token::Bracket)) {
3284 slice = Some(P(ast::Pat {
3285 id: ast::DUMMY_NODE_ID,
3289 before_slice = false;
3295 let subpat = try!(self.parse_pat());
3296 if before_slice && self.check(&token::DotDot) {
3298 slice = Some(subpat);
3299 before_slice = false;
3300 } else if before_slice {
3301 before.push(subpat);
3307 Ok((before, slice, after))
3310 /// Parse the fields of a struct-like pattern
3311 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<codemap::Spanned<ast::FieldPat>> , bool)> {
3312 let mut fields = Vec::new();
3313 let mut etc = false;
3314 let mut first = true;
3315 while self.token != token::CloseDelim(token::Brace) {
3319 try!(self.expect(&token::Comma));
3320 // accept trailing commas
3321 if self.check(&token::CloseDelim(token::Brace)) { break }
3324 let lo = self.span.lo;
3327 if self.check(&token::DotDot) {
3329 if self.token != token::CloseDelim(token::Brace) {
3330 let token_str = self.this_token_to_string();
3331 return Err(self.fatal(&format!("expected `{}`, found `{}`", "}",
3338 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3339 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3340 // Parsing a pattern of the form "fieldname: pat"
3341 let fieldname = try!(self.parse_ident());
3343 let pat = try!(self.parse_pat());
3345 (pat, fieldname, false)
3347 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3348 let is_box = self.eat_keyword(keywords::Box);
3349 let boxed_span_lo = self.span.lo;
3350 let is_ref = self.eat_keyword(keywords::Ref);
3351 let is_mut = self.eat_keyword(keywords::Mut);
3352 let fieldname = try!(self.parse_ident());
3353 hi = self.last_span.hi;
3355 let bind_type = match (is_ref, is_mut) {
3356 (true, true) => BindingMode::ByRef(MutMutable),
3357 (true, false) => BindingMode::ByRef(MutImmutable),
3358 (false, true) => BindingMode::ByValue(MutMutable),
3359 (false, false) => BindingMode::ByValue(MutImmutable),
3361 let fieldpath = codemap::Spanned{span:self.last_span, node:fieldname};
3362 let fieldpat = P(ast::Pat{
3363 id: ast::DUMMY_NODE_ID,
3364 node: PatIdent(bind_type, fieldpath, None),
3365 span: mk_sp(boxed_span_lo, hi),
3368 let subpat = if is_box {
3370 id: ast::DUMMY_NODE_ID,
3371 node: PatBox(fieldpat),
3372 span: mk_sp(lo, hi),
3377 (subpat, fieldname, true)
3380 fields.push(codemap::Spanned { span: mk_sp(lo, hi),
3381 node: ast::FieldPat { ident: fieldname,
3383 is_shorthand: is_shorthand }});
3385 return Ok((fields, etc));
3388 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
3389 if self.is_path_start() {
3390 let lo = self.span.lo;
3391 let (qself, path) = if self.eat_lt() {
3392 // Parse a qualified path
3394 try!(self.parse_qualified_path(NoTypesAllowed));
3397 // Parse an unqualified path
3398 (None, try!(self.parse_path(LifetimeAndTypesWithColons)))
3400 let hi = self.last_span.hi;
3401 Ok(self.mk_expr(lo, hi, ExprPath(qself, path), None))
3403 self.parse_pat_literal_maybe_minus()
3407 fn is_path_start(&self) -> bool {
3408 (self.token == token::Lt || self.token == token::ModSep
3409 || self.token.is_ident() || self.token.is_path())
3410 && !self.token.is_keyword(keywords::True) && !self.token.is_keyword(keywords::False)
3413 /// Parse a pattern.
3414 pub fn parse_pat(&mut self) -> PResult<'a, P<Pat>> {
3415 maybe_whole!(self, NtPat);
3417 let lo = self.span.lo;
3420 token::Underscore => {
3425 token::BinOp(token::And) | token::AndAnd => {
3426 // Parse &pat / &mut pat
3427 try!(self.expect_and());
3428 let mutbl = try!(self.parse_mutability());
3429 if let token::Lifetime(ident) = self.token {
3430 return Err(self.fatal(&format!("unexpected lifetime `{}` in pattern", ident)));
3433 let subpat = try!(self.parse_pat());
3434 pat = PatRegion(subpat, mutbl);
3436 token::OpenDelim(token::Paren) => {
3437 // Parse (pat,pat,pat,...) as tuple pattern
3439 let fields = try!(self.parse_pat_tuple_elements());
3440 try!(self.expect(&token::CloseDelim(token::Paren)));
3441 pat = PatTup(fields);
3443 token::OpenDelim(token::Bracket) => {
3444 // Parse [pat,pat,...] as slice pattern
3446 let (before, slice, after) = try!(self.parse_pat_vec_elements());
3447 try!(self.expect(&token::CloseDelim(token::Bracket)));
3448 pat = PatVec(before, slice, after);
3451 // At this point, token != _, &, &&, (, [
3452 if self.eat_keyword(keywords::Mut) {
3453 // Parse mut ident @ pat
3454 pat = try!(self.parse_pat_ident(BindingMode::ByValue(MutMutable)));
3455 } else if self.eat_keyword(keywords::Ref) {
3456 // Parse ref ident @ pat / ref mut ident @ pat
3457 let mutbl = try!(self.parse_mutability());
3458 pat = try!(self.parse_pat_ident(BindingMode::ByRef(mutbl)));
3459 } else if self.eat_keyword(keywords::Box) {
3461 let subpat = try!(self.parse_pat());
3462 pat = PatBox(subpat);
3463 } else if self.is_path_start() {
3464 // Parse pattern starting with a path
3465 if self.token.is_plain_ident() && self.look_ahead(1, |t| *t != token::DotDotDot &&
3466 *t != token::OpenDelim(token::Brace) &&
3467 *t != token::OpenDelim(token::Paren) &&
3468 // Contrary to its definition, a plain ident can be followed by :: in macros
3469 *t != token::ModSep) {
3470 // Plain idents have some extra abilities here compared to general paths
3471 if self.look_ahead(1, |t| *t == token::Not) {
3472 // Parse macro invocation
3473 let ident = try!(self.parse_ident());
3474 let ident_span = self.last_span;
3475 let path = ident_to_path(ident_span, ident);
3477 let delim = try!(self.expect_open_delim());
3478 let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
3479 seq_sep_none(), |p| p.parse_token_tree()));
3480 let mac = Mac_ { path: path, tts: tts, ctxt: EMPTY_CTXT };
3481 pat = PatMac(codemap::Spanned {node: mac,
3482 span: mk_sp(lo, self.last_span.hi)});
3484 // Parse ident @ pat
3485 // This can give false positives and parse nullary enums,
3486 // they are dealt with later in resolve
3487 pat = try!(self.parse_pat_ident(BindingMode::ByValue(MutImmutable)));
3490 let (qself, path) = if self.eat_lt() {
3491 // Parse a qualified path
3493 try!(self.parse_qualified_path(NoTypesAllowed));
3496 // Parse an unqualified path
3497 (None, try!(self.parse_path(LifetimeAndTypesWithColons)))
3500 token::DotDotDot => {
3502 let hi = self.last_span.hi;
3503 let begin = self.mk_expr(lo, hi, ExprPath(qself, path), None);
3505 let end = try!(self.parse_pat_range_end());
3506 pat = PatRange(begin, end);
3508 token::OpenDelim(token::Brace) => {
3509 if qself.is_some() {
3510 return Err(self.fatal("unexpected `{` after qualified path"));
3512 // Parse struct pattern
3514 let (fields, etc) = try!(self.parse_pat_fields());
3516 pat = PatStruct(path, fields, etc);
3518 token::OpenDelim(token::Paren) => {
3519 if qself.is_some() {
3520 return Err(self.fatal("unexpected `(` after qualified path"));
3522 // Parse tuple struct or enum pattern
3523 if self.look_ahead(1, |t| *t == token::DotDot) {
3524 // This is a "top constructor only" pat
3527 try!(self.expect(&token::CloseDelim(token::Paren)));
3528 pat = PatEnum(path, None);
3530 let args = try!(self.parse_enum_variant_seq(
3531 &token::OpenDelim(token::Paren),
3532 &token::CloseDelim(token::Paren),
3533 seq_sep_trailing_allowed(token::Comma),
3534 |p| p.parse_pat()));
3535 pat = PatEnum(path, Some(args));
3540 // Parse qualified path
3541 Some(qself) => PatQPath(qself, path),
3542 // Parse nullary enum
3543 None => PatEnum(path, Some(vec![]))
3549 // Try to parse everything else as literal with optional minus
3550 let begin = try!(self.parse_pat_literal_maybe_minus());
3551 if self.eat(&token::DotDotDot) {
3552 let end = try!(self.parse_pat_range_end());
3553 pat = PatRange(begin, end);
3555 pat = PatLit(begin);
3561 let hi = self.last_span.hi;
3563 id: ast::DUMMY_NODE_ID,
3565 span: mk_sp(lo, hi),
3569 /// Parse ident or ident @ pat
3570 /// used by the copy foo and ref foo patterns to give a good
3571 /// error message when parsing mistakes like ref foo(a,b)
3572 fn parse_pat_ident(&mut self,
3573 binding_mode: ast::BindingMode)
3574 -> PResult<'a, ast::Pat_> {
3575 if !self.token.is_plain_ident() {
3576 let span = self.span;
3577 let tok_str = self.this_token_to_string();
3578 return Err(self.span_fatal(span,
3579 &format!("expected identifier, found `{}`", tok_str)))
3581 let ident = try!(self.parse_ident());
3582 let last_span = self.last_span;
3583 let name = codemap::Spanned{span: last_span, node: ident};
3584 let sub = if self.eat(&token::At) {
3585 Some(try!(self.parse_pat()))
3590 // just to be friendly, if they write something like
3592 // we end up here with ( as the current token. This shortly
3593 // leads to a parse error. Note that if there is no explicit
3594 // binding mode then we do not end up here, because the lookahead
3595 // will direct us over to parse_enum_variant()
3596 if self.token == token::OpenDelim(token::Paren) {
3597 let last_span = self.last_span;
3598 return Err(self.span_fatal(
3600 "expected identifier, found enum pattern"))
3603 Ok(PatIdent(binding_mode, name, sub))
3606 /// Parse a local variable declaration
3607 fn parse_local(&mut self, attrs: ThinAttributes) -> PResult<'a, P<Local>> {
3608 let lo = self.span.lo;
3609 let pat = try!(self.parse_pat());
3612 if self.eat(&token::Colon) {
3613 ty = Some(try!(self.parse_ty_sum()));
3615 let init = try!(self.parse_initializer());
3620 id: ast::DUMMY_NODE_ID,
3621 span: mk_sp(lo, self.last_span.hi),
3626 /// Parse a "let" stmt
3627 fn parse_let(&mut self, attrs: ThinAttributes) -> PResult<'a, P<Decl>> {
3628 let lo = self.span.lo;
3629 let local = try!(self.parse_local(attrs));
3630 Ok(P(spanned(lo, self.last_span.hi, DeclLocal(local))))
3633 /// Parse a structure field
3634 fn parse_name_and_ty(&mut self, pr: Visibility,
3635 attrs: Vec<Attribute> ) -> PResult<'a, StructField> {
3637 Inherited => self.span.lo,
3638 Public => self.last_span.lo,
3640 if !self.token.is_plain_ident() {
3641 return Err(self.fatal("expected ident"));
3643 let name = try!(self.parse_ident());
3644 try!(self.expect(&token::Colon));
3645 let ty = try!(self.parse_ty_sum());
3646 Ok(spanned(lo, self.last_span.hi, ast::StructField_ {
3647 kind: NamedField(name, pr),
3648 id: ast::DUMMY_NODE_ID,
3654 /// Emit an expected item after attributes error.
3655 fn expected_item_err(&self, attrs: &[Attribute]) {
3656 let message = match attrs.last() {
3657 Some(&Attribute { node: ast::Attribute_ { is_sugared_doc: true, .. }, .. }) => {
3658 "expected item after doc comment"
3660 _ => "expected item after attributes",
3663 self.span_err(self.last_span, message);
3666 /// Parse a statement. may include decl.
3667 pub fn parse_stmt(&mut self) -> PResult<'a, Option<P<Stmt>>> {
3668 Ok(try!(self.parse_stmt_()).map(P))
3671 fn parse_stmt_(&mut self) -> PResult<'a, Option<Stmt>> {
3672 maybe_whole!(Some deref self, NtStmt);
3674 let attrs = try!(self.parse_outer_attributes());
3675 let lo = self.span.lo;
3677 Ok(Some(if self.check_keyword(keywords::Let) {
3678 try!(self.expect_keyword(keywords::Let));
3679 let decl = try!(self.parse_let(attrs.into_thin_attrs()));
3680 let hi = decl.span.hi;
3681 let stmt = StmtDecl(decl, ast::DUMMY_NODE_ID);
3682 spanned(lo, hi, stmt)
3683 } else if self.token.is_ident()
3684 && !self.token.is_any_keyword()
3685 && self.look_ahead(1, |t| *t == token::Not) {
3686 // it's a macro invocation:
3688 // Potential trouble: if we allow macros with paths instead of
3689 // idents, we'd need to look ahead past the whole path here...
3690 let pth = try!(self.parse_path(NoTypesAllowed));
3693 let id = match self.token {
3694 token::OpenDelim(_) => token::special_idents::invalid, // no special identifier
3695 _ => try!(self.parse_ident()),
3698 // check that we're pointing at delimiters (need to check
3699 // again after the `if`, because of `parse_ident`
3700 // consuming more tokens).
3701 let delim = match self.token {
3702 token::OpenDelim(delim) => delim,
3704 // we only expect an ident if we didn't parse one
3706 let ident_str = if id.name == token::special_idents::invalid.name {
3711 let tok_str = self.this_token_to_string();
3712 return Err(self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
3718 let tts = try!(self.parse_unspanned_seq(
3719 &token::OpenDelim(delim),
3720 &token::CloseDelim(delim),
3722 |p| p.parse_token_tree()
3724 let hi = self.last_span.hi;
3726 let style = if delim == token::Brace {
3729 MacStmtWithoutBraces
3732 if id.name == token::special_idents::invalid.name {
3733 let stmt = StmtMac(P(spanned(lo,
3735 Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT })),
3737 attrs.into_thin_attrs());
3738 spanned(lo, hi, stmt)
3740 // if it has a special ident, it's definitely an item
3742 // Require a semicolon or braces.
3743 if style != MacStmtWithBraces {
3744 if !self.eat(&token::Semi) {
3745 let last_span = self.last_span;
3746 self.span_err(last_span,
3747 "macros that expand to items must \
3748 either be surrounded with braces or \
3749 followed by a semicolon");
3752 spanned(lo, hi, StmtDecl(
3753 P(spanned(lo, hi, DeclItem(
3755 lo, hi, id /*id is good here*/,
3756 ItemMac(spanned(lo, hi,
3757 Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT })),
3758 Inherited, attrs)))),
3759 ast::DUMMY_NODE_ID))
3762 // FIXME: Bad copy of attrs
3763 match try!(self.parse_item_(attrs.clone(), false, true)) {
3766 let decl = P(spanned(lo, hi, DeclItem(i)));
3767 spanned(lo, hi, StmtDecl(decl, ast::DUMMY_NODE_ID))
3770 let unused_attrs = |attrs: &[_], s: &mut Self| {
3771 if attrs.len() > 0 {
3773 "expected statement after outer attribute");
3777 // Do not attempt to parse an expression if we're done here.
3778 if self.token == token::Semi {
3779 unused_attrs(&attrs, self);
3784 if self.token == token::CloseDelim(token::Brace) {
3785 unused_attrs(&attrs, self);
3789 // Remainder are line-expr stmts.
3790 let e = try!(self.parse_expr_res(
3791 Restrictions::RESTRICTION_STMT_EXPR, Some(attrs.into_thin_attrs())));
3793 let stmt = StmtExpr(e, ast::DUMMY_NODE_ID);
3794 spanned(lo, hi, stmt)
3800 /// Is this expression a successfully-parsed statement?
3801 fn expr_is_complete(&mut self, e: &Expr) -> bool {
3802 self.restrictions.contains(Restrictions::RESTRICTION_STMT_EXPR) &&
3803 !classify::expr_requires_semi_to_be_stmt(e)
3806 /// Parse a block. No inner attrs are allowed.
3807 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
3808 maybe_whole!(no_clone self, NtBlock);
3810 let lo = self.span.lo;
3812 if !self.eat(&token::OpenDelim(token::Brace)) {
3814 let tok = self.this_token_to_string();
3815 return Err(self.span_fatal_help(sp,
3816 &format!("expected `{{`, found `{}`", tok),
3817 "place this code inside a block"));
3820 self.parse_block_tail(lo, DefaultBlock)
3823 /// Parse a block. Inner attrs are allowed.
3824 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
3825 maybe_whole!(pair_empty self, NtBlock);
3827 let lo = self.span.lo;
3828 try!(self.expect(&token::OpenDelim(token::Brace)));
3829 Ok((try!(self.parse_inner_attributes()),
3830 try!(self.parse_block_tail(lo, DefaultBlock))))
3833 /// Parse the rest of a block expression or function body
3834 /// Precondition: already parsed the '{'.
3835 fn parse_block_tail(&mut self, lo: BytePos, s: BlockCheckMode) -> PResult<'a, P<Block>> {
3836 let mut stmts = vec![];
3837 let mut expr = None;
3839 while !self.eat(&token::CloseDelim(token::Brace)) {
3840 let Spanned {node, span} = if let Some(s) = try!(self.parse_stmt_()) {
3843 // Found only `;` or `}`.
3848 try!(self.handle_expression_like_statement(e, span, &mut stmts, &mut expr));
3850 StmtMac(mac, MacStmtWithoutBraces, attrs) => {
3851 // statement macro without braces; might be an
3852 // expr depending on whether a semicolon follows
3855 stmts.push(P(Spanned {
3856 node: StmtMac(mac, MacStmtWithSemicolon, attrs),
3857 span: mk_sp(span.lo, self.span.hi),
3862 let e = self.mk_mac_expr(span.lo, span.hi,
3863 mac.and_then(|m| m.node),
3866 let e = try!(self.parse_dot_or_call_expr_with(e, lo, attrs));
3867 let e = try!(self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e)));
3868 try!(self.handle_expression_like_statement(
3876 StmtMac(m, style, attrs) => {
3877 // statement macro; might be an expr
3880 stmts.push(P(Spanned {
3881 node: StmtMac(m, MacStmtWithSemicolon, attrs),
3882 span: mk_sp(span.lo, self.span.hi),
3886 token::CloseDelim(token::Brace) => {
3887 // if a block ends in `m!(arg)` without
3888 // a `;`, it must be an expr
3889 expr = Some(self.mk_mac_expr(span.lo, span.hi,
3890 m.and_then(|x| x.node),
3894 stmts.push(P(Spanned {
3895 node: StmtMac(m, style, attrs),
3901 _ => { // all other kinds of statements:
3902 let mut hi = span.hi;
3903 if classify::stmt_ends_with_semi(&node) {
3904 try!(self.commit_stmt_expecting(token::Semi));
3905 hi = self.last_span.hi;
3908 stmts.push(P(Spanned {
3910 span: mk_sp(span.lo, hi)
3919 id: ast::DUMMY_NODE_ID,
3921 span: mk_sp(lo, self.last_span.hi),
3925 fn handle_expression_like_statement(
3929 stmts: &mut Vec<P<Stmt>>,
3930 last_block_expr: &mut Option<P<Expr>>) -> PResult<'a, ()> {
3931 // expression without semicolon
3932 if classify::expr_requires_semi_to_be_stmt(&*e) {
3933 // Just check for errors and recover; do not eat semicolon yet.
3934 try!(self.commit_stmt(&[],
3935 &[token::Semi, token::CloseDelim(token::Brace)]));
3941 let span_with_semi = Span {
3943 hi: self.last_span.hi,
3944 expn_id: span.expn_id,
3946 stmts.push(P(Spanned {
3947 node: StmtSemi(e, ast::DUMMY_NODE_ID),
3948 span: span_with_semi,
3951 token::CloseDelim(token::Brace) => *last_block_expr = Some(e),
3953 stmts.push(P(Spanned {
3954 node: StmtExpr(e, ast::DUMMY_NODE_ID),
3962 // Parses a sequence of bounds if a `:` is found,
3963 // otherwise returns empty list.
3964 fn parse_colon_then_ty_param_bounds(&mut self,
3965 mode: BoundParsingMode)
3966 -> PResult<'a, TyParamBounds>
3968 if !self.eat(&token::Colon) {
3971 self.parse_ty_param_bounds(mode)
3975 // matches bounds = ( boundseq )?
3976 // where boundseq = ( polybound + boundseq ) | polybound
3977 // and polybound = ( 'for' '<' 'region '>' )? bound
3978 // and bound = 'region | trait_ref
3979 fn parse_ty_param_bounds(&mut self,
3980 mode: BoundParsingMode)
3981 -> PResult<'a, TyParamBounds>
3983 let mut result = vec!();
3985 let question_span = self.span;
3986 let ate_question = self.eat(&token::Question);
3988 token::Lifetime(lifetime) => {
3990 self.span_err(question_span,
3991 "`?` may only modify trait bounds, not lifetime bounds");
3993 result.push(RegionTyParamBound(ast::Lifetime {
3994 id: ast::DUMMY_NODE_ID,
4000 token::ModSep | token::Ident(..) => {
4001 let poly_trait_ref = try!(self.parse_poly_trait_ref());
4002 let modifier = if ate_question {
4003 if mode == BoundParsingMode::Modified {
4004 TraitBoundModifier::Maybe
4006 self.span_err(question_span,
4008 TraitBoundModifier::None
4011 TraitBoundModifier::None
4013 result.push(TraitTyParamBound(poly_trait_ref, modifier))
4018 if !self.eat(&token::BinOp(token::Plus)) {
4023 return Ok(P::from_vec(result));
4026 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
4027 fn parse_ty_param(&mut self) -> PResult<'a, TyParam> {
4028 let span = self.span;
4029 let ident = try!(self.parse_ident());
4031 let bounds = try!(self.parse_colon_then_ty_param_bounds(BoundParsingMode::Modified));
4033 let default = if self.check(&token::Eq) {
4035 Some(try!(self.parse_ty_sum()))
4042 id: ast::DUMMY_NODE_ID,
4049 /// Parse a set of optional generic type parameter declarations. Where
4050 /// clauses are not parsed here, and must be added later via
4051 /// `parse_where_clause()`.
4053 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
4054 /// | ( < lifetimes , typaramseq ( , )? > )
4055 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
4056 pub fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
4057 maybe_whole!(self, NtGenerics);
4059 if self.eat(&token::Lt) {
4060 let lifetime_defs = try!(self.parse_lifetime_defs());
4061 let mut seen_default = false;
4062 let ty_params = try!(self.parse_seq_to_gt(Some(token::Comma), |p| {
4063 try!(p.forbid_lifetime());
4064 let ty_param = try!(p.parse_ty_param());
4065 if ty_param.default.is_some() {
4066 seen_default = true;
4067 } else if seen_default {
4068 let last_span = p.last_span;
4069 p.span_err(last_span,
4070 "type parameters with a default must be trailing");
4075 lifetimes: lifetime_defs,
4076 ty_params: ty_params,
4077 where_clause: WhereClause {
4078 id: ast::DUMMY_NODE_ID,
4079 predicates: Vec::new(),
4083 Ok(ast::Generics::default())
4087 fn parse_generic_values_after_lt(&mut self) -> PResult<'a, (Vec<ast::Lifetime>,
4089 Vec<P<TypeBinding>>)> {
4090 let span_lo = self.span.lo;
4091 let lifetimes = try!(self.parse_lifetimes(token::Comma));
4093 let missing_comma = !lifetimes.is_empty() &&
4094 !self.token.is_like_gt() &&
4096 .as_ref().map_or(true,
4097 |x| &**x != &token::Comma);
4101 let msg = format!("expected `,` or `>` after lifetime \
4103 self.this_token_to_string());
4104 let mut err = self.diagnostic().struct_span_err(self.span, &msg);
4106 let span_hi = self.span.hi;
4107 let span_hi = match self.parse_ty() {
4108 Ok(..) => self.span.hi,
4109 Err(ref mut err) => {
4115 let msg = format!("did you mean a single argument type &'a Type, \
4116 or did you mean the comma-separated arguments \
4118 err.span_note(mk_sp(span_lo, span_hi), &msg);
4122 // First parse types.
4123 let (types, returned) = try!(self.parse_seq_to_gt_or_return(
4126 try!(p.forbid_lifetime());
4127 if p.look_ahead(1, |t| t == &token::Eq) {
4130 Ok(Some(try!(p.parse_ty_sum())))
4135 // If we found the `>`, don't continue.
4137 return Ok((lifetimes, types.into_vec(), Vec::new()));
4140 // Then parse type bindings.
4141 let bindings = try!(self.parse_seq_to_gt(
4144 try!(p.forbid_lifetime());
4146 let ident = try!(p.parse_ident());
4147 let found_eq = p.eat(&token::Eq);
4150 p.span_warn(span, "whoops, no =?");
4152 let ty = try!(p.parse_ty());
4153 let hi = ty.span.hi;
4154 let span = mk_sp(lo, hi);
4155 return Ok(P(TypeBinding{id: ast::DUMMY_NODE_ID,
4162 Ok((lifetimes, types.into_vec(), bindings.into_vec()))
4165 fn forbid_lifetime(&mut self) -> PResult<'a, ()> {
4166 if self.token.is_lifetime() {
4167 let span = self.span;
4168 return Err(self.span_fatal(span, "lifetime parameters must be declared \
4169 prior to type parameters"))
4174 /// Parses an optional `where` clause and places it in `generics`.
4177 /// where T : Trait<U, V> + 'b, 'a : 'b
4179 pub fn parse_where_clause(&mut self) -> PResult<'a, ast::WhereClause> {
4180 maybe_whole!(self, NtWhereClause);
4182 let mut where_clause = WhereClause {
4183 id: ast::DUMMY_NODE_ID,
4184 predicates: Vec::new(),
4187 if !self.eat_keyword(keywords::Where) {
4188 return Ok(where_clause);
4191 let mut parsed_something = false;
4193 let lo = self.span.lo;
4195 token::OpenDelim(token::Brace) => {
4199 token::Lifetime(..) => {
4200 let bounded_lifetime =
4201 try!(self.parse_lifetime());
4203 self.eat(&token::Colon);
4206 try!(self.parse_lifetimes(token::BinOp(token::Plus)));
4208 let hi = self.last_span.hi;
4209 let span = mk_sp(lo, hi);
4211 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
4212 ast::WhereRegionPredicate {
4214 lifetime: bounded_lifetime,
4219 parsed_something = true;
4223 let bound_lifetimes = if self.eat_keyword(keywords::For) {
4224 // Higher ranked constraint.
4225 try!(self.expect(&token::Lt));
4226 let lifetime_defs = try!(self.parse_lifetime_defs());
4227 try!(self.expect_gt());
4233 let bounded_ty = try!(self.parse_ty());
4235 if self.eat(&token::Colon) {
4236 let bounds = try!(self.parse_ty_param_bounds(BoundParsingMode::Bare));
4237 let hi = self.last_span.hi;
4238 let span = mk_sp(lo, hi);
4240 if bounds.is_empty() {
4242 "each predicate in a `where` clause must have \
4243 at least one bound in it");
4246 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
4247 ast::WhereBoundPredicate {
4249 bound_lifetimes: bound_lifetimes,
4250 bounded_ty: bounded_ty,
4254 parsed_something = true;
4255 } else if self.eat(&token::Eq) {
4256 // let ty = try!(self.parse_ty());
4257 let hi = self.last_span.hi;
4258 let span = mk_sp(lo, hi);
4259 // where_clause.predicates.push(
4260 // ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
4261 // id: ast::DUMMY_NODE_ID,
4263 // path: panic!("NYI"), //bounded_ty,
4266 // parsed_something = true;
4269 "equality constraints are not yet supported \
4270 in where clauses (#20041)");
4272 let last_span = self.last_span;
4273 self.span_err(last_span,
4274 "unexpected token in `where` clause");
4279 if !self.eat(&token::Comma) {
4284 if !parsed_something {
4285 let last_span = self.last_span;
4286 self.span_err(last_span,
4287 "a `where` clause must have at least one predicate \
4294 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
4295 -> PResult<'a, (Vec<Arg> , bool)> {
4297 let mut args: Vec<Option<Arg>> =
4298 try!(self.parse_unspanned_seq(
4299 &token::OpenDelim(token::Paren),
4300 &token::CloseDelim(token::Paren),
4301 seq_sep_trailing_allowed(token::Comma),
4303 if p.token == token::DotDotDot {
4306 if p.token != token::CloseDelim(token::Paren) {
4308 return Err(p.span_fatal(span,
4309 "`...` must be last in argument list for variadic function"))
4313 return Err(p.span_fatal(span,
4314 "only foreign functions are allowed to be variadic"))
4318 Ok(Some(try!(p.parse_arg_general(named_args))))
4323 let variadic = match args.pop() {
4326 // Need to put back that last arg
4333 if variadic && args.is_empty() {
4335 "variadic function must be declared with at least one named argument");
4338 let args = args.into_iter().map(|x| x.unwrap()).collect();
4340 Ok((args, variadic))
4343 /// Parse the argument list and result type of a function declaration
4344 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> {
4346 let (args, variadic) = try!(self.parse_fn_args(true, allow_variadic));
4347 let ret_ty = try!(self.parse_ret_ty());
4356 fn is_self_ident(&mut self) -> bool {
4358 token::Ident(id, token::Plain) => id.name == special_idents::self_.name,
4363 fn expect_self_ident(&mut self) -> PResult<'a, ast::Ident> {
4365 token::Ident(id, token::Plain) if id.name == special_idents::self_.name => {
4370 let token_str = self.this_token_to_string();
4371 return Err(self.fatal(&format!("expected `self`, found `{}`",
4377 fn is_self_type_ident(&mut self) -> bool {
4379 token::Ident(id, token::Plain) => id.name == special_idents::type_self.name,
4384 fn expect_self_type_ident(&mut self) -> PResult<'a, ast::Ident> {
4386 token::Ident(id, token::Plain) if id.name == special_idents::type_self.name => {
4391 let token_str = self.this_token_to_string();
4392 Err(self.fatal(&format!("expected `Self`, found `{}`",
4398 /// Parse the argument list and result type of a function
4399 /// that may have a self type.
4400 fn parse_fn_decl_with_self<F>(&mut self,
4401 parse_arg_fn: F) -> PResult<'a, (ExplicitSelf, P<FnDecl>)> where
4402 F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
4404 fn maybe_parse_borrowed_explicit_self<'b>(this: &mut Parser<'b>)
4405 -> PResult<'b, ast::ExplicitSelf_> {
4406 // The following things are possible to see here:
4411 // fn(&'lt mut self)
4413 // We already know that the current token is `&`.
4415 if this.look_ahead(1, |t| t.is_keyword(keywords::SelfValue)) {
4417 Ok(SelfRegion(None, MutImmutable, try!(this.expect_self_ident())))
4418 } else if this.look_ahead(1, |t| t.is_mutability()) &&
4419 this.look_ahead(2, |t| t.is_keyword(keywords::SelfValue)) {
4421 let mutability = try!(this.parse_mutability());
4422 Ok(SelfRegion(None, mutability, try!(this.expect_self_ident())))
4423 } else if this.look_ahead(1, |t| t.is_lifetime()) &&
4424 this.look_ahead(2, |t| t.is_keyword(keywords::SelfValue)) {
4426 let lifetime = try!(this.parse_lifetime());
4427 Ok(SelfRegion(Some(lifetime), MutImmutable, try!(this.expect_self_ident())))
4428 } else if this.look_ahead(1, |t| t.is_lifetime()) &&
4429 this.look_ahead(2, |t| t.is_mutability()) &&
4430 this.look_ahead(3, |t| t.is_keyword(keywords::SelfValue)) {
4432 let lifetime = try!(this.parse_lifetime());
4433 let mutability = try!(this.parse_mutability());
4434 Ok(SelfRegion(Some(lifetime), mutability, try!(this.expect_self_ident())))
4440 try!(self.expect(&token::OpenDelim(token::Paren)));
4442 // A bit of complexity and lookahead is needed here in order to be
4443 // backwards compatible.
4444 let lo = self.span.lo;
4445 let mut self_ident_lo = self.span.lo;
4446 let mut self_ident_hi = self.span.hi;
4448 let mut mutbl_self = MutImmutable;
4449 let explicit_self = match self.token {
4450 token::BinOp(token::And) => {
4451 let eself = try!(maybe_parse_borrowed_explicit_self(self));
4452 self_ident_lo = self.last_span.lo;
4453 self_ident_hi = self.last_span.hi;
4456 token::BinOp(token::Star) => {
4457 // Possibly "*self" or "*mut self" -- not supported. Try to avoid
4458 // emitting cryptic "unexpected token" errors.
4460 let _mutability = if self.token.is_mutability() {
4461 try!(self.parse_mutability())
4465 if self.is_self_ident() {
4466 let span = self.span;
4467 self.span_err(span, "cannot pass self by raw pointer");
4470 // error case, making bogus self ident:
4471 SelfValue(special_idents::self_)
4473 token::Ident(..) => {
4474 if self.is_self_ident() {
4475 let self_ident = try!(self.expect_self_ident());
4477 // Determine whether this is the fully explicit form, `self:
4479 if self.eat(&token::Colon) {
4480 SelfExplicit(try!(self.parse_ty_sum()), self_ident)
4482 SelfValue(self_ident)
4484 } else if self.token.is_mutability() &&
4485 self.look_ahead(1, |t| t.is_keyword(keywords::SelfValue)) {
4486 mutbl_self = try!(self.parse_mutability());
4487 let self_ident = try!(self.expect_self_ident());
4489 // Determine whether this is the fully explicit form,
4491 if self.eat(&token::Colon) {
4492 SelfExplicit(try!(self.parse_ty_sum()), self_ident)
4494 SelfValue(self_ident)
4503 let explicit_self_sp = mk_sp(self_ident_lo, self_ident_hi);
4505 // shared fall-through for the three cases below. borrowing prevents simply
4506 // writing this as a closure
4507 macro_rules! parse_remaining_arguments {
4510 // If we parsed a self type, expect a comma before the argument list.
4514 let sep = seq_sep_trailing_allowed(token::Comma);
4515 let mut fn_inputs = try!(self.parse_seq_to_before_end(
4516 &token::CloseDelim(token::Paren),
4520 fn_inputs.insert(0, Arg::new_self(explicit_self_sp, mutbl_self, $self_id));
4523 token::CloseDelim(token::Paren) => {
4524 vec!(Arg::new_self(explicit_self_sp, mutbl_self, $self_id))
4527 let token_str = self.this_token_to_string();
4528 return Err(self.fatal(&format!("expected `,` or `)`, found `{}`",
4535 let fn_inputs = match explicit_self {
4537 let sep = seq_sep_trailing_allowed(token::Comma);
4538 try!(self.parse_seq_to_before_end(&token::CloseDelim(token::Paren),
4541 SelfValue(id) => parse_remaining_arguments!(id),
4542 SelfRegion(_,_,id) => parse_remaining_arguments!(id),
4543 SelfExplicit(_,id) => parse_remaining_arguments!(id),
4547 try!(self.expect(&token::CloseDelim(token::Paren)));
4549 let hi = self.span.hi;
4551 let ret_ty = try!(self.parse_ret_ty());
4553 let fn_decl = P(FnDecl {
4559 Ok((spanned(lo, hi, explicit_self), fn_decl))
4562 // parse the |arg, arg| header on a lambda
4563 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
4564 let inputs_captures = {
4565 if self.eat(&token::OrOr) {
4568 try!(self.expect(&token::BinOp(token::Or)));
4569 try!(self.parse_obsolete_closure_kind());
4570 let args = try!(self.parse_seq_to_before_end(
4571 &token::BinOp(token::Or),
4572 seq_sep_trailing_allowed(token::Comma),
4573 |p| p.parse_fn_block_arg()
4579 let output = try!(self.parse_ret_ty());
4582 inputs: inputs_captures,
4588 /// Parse the name and optional generic types of a function header.
4589 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
4590 let id = try!(self.parse_ident());
4591 let generics = try!(self.parse_generics());
4595 fn mk_item(&mut self, lo: BytePos, hi: BytePos, ident: Ident,
4596 node: Item_, vis: Visibility,
4597 attrs: Vec<Attribute>) -> P<Item> {
4601 id: ast::DUMMY_NODE_ID,
4608 /// Parse an item-position function declaration.
4609 fn parse_item_fn(&mut self,
4611 constness: Constness,
4613 -> PResult<'a, ItemInfo> {
4614 let (ident, mut generics) = try!(self.parse_fn_header());
4615 let decl = try!(self.parse_fn_decl(false));
4616 generics.where_clause = try!(self.parse_where_clause());
4617 let (inner_attrs, body) = try!(self.parse_inner_attrs_and_block());
4618 Ok((ident, ItemFn(decl, unsafety, constness, abi, generics, body), Some(inner_attrs)))
4621 /// true if we are looking at `const ID`, false for things like `const fn` etc
4622 pub fn is_const_item(&mut self) -> bool {
4623 self.token.is_keyword(keywords::Const) &&
4624 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
4625 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
4628 /// parses all the "front matter" for a `fn` declaration, up to
4629 /// and including the `fn` keyword:
4633 /// - `const unsafe fn`
4636 pub fn parse_fn_front_matter(&mut self)
4637 -> PResult<'a, (ast::Constness, ast::Unsafety, abi::Abi)> {
4638 let is_const_fn = self.eat_keyword(keywords::Const);
4639 let unsafety = try!(self.parse_unsafety());
4640 let (constness, unsafety, abi) = if is_const_fn {
4641 (Constness::Const, unsafety, abi::Rust)
4643 let abi = if self.eat_keyword(keywords::Extern) {
4644 try!(self.parse_opt_abi()).unwrap_or(abi::C)
4648 (Constness::NotConst, unsafety, abi)
4650 try!(self.expect_keyword(keywords::Fn));
4651 Ok((constness, unsafety, abi))
4654 /// Parse an impl item.
4655 pub fn parse_impl_item(&mut self) -> PResult<'a, P<ImplItem>> {
4656 maybe_whole!(no_clone self, NtImplItem);
4658 let mut attrs = try!(self.parse_outer_attributes());
4659 let lo = self.span.lo;
4660 let vis = try!(self.parse_visibility());
4661 let (name, node) = if self.eat_keyword(keywords::Type) {
4662 let name = try!(self.parse_ident());
4663 try!(self.expect(&token::Eq));
4664 let typ = try!(self.parse_ty_sum());
4665 try!(self.expect(&token::Semi));
4666 (name, ast::ImplItemKind::Type(typ))
4667 } else if self.is_const_item() {
4668 try!(self.expect_keyword(keywords::Const));
4669 let name = try!(self.parse_ident());
4670 try!(self.expect(&token::Colon));
4671 let typ = try!(self.parse_ty_sum());
4672 try!(self.expect(&token::Eq));
4673 let expr = try!(self.parse_expr());
4674 try!(self.commit_expr_expecting(&expr, token::Semi));
4675 (name, ast::ImplItemKind::Const(typ, expr))
4677 let (name, inner_attrs, node) = try!(self.parse_impl_method(vis));
4678 attrs.extend(inner_attrs);
4683 id: ast::DUMMY_NODE_ID,
4684 span: mk_sp(lo, self.last_span.hi),
4692 fn complain_if_pub_macro(&mut self, visa: Visibility, span: Span) {
4695 let is_macro_rules: bool = match self.token {
4696 token::Ident(sid, _) => sid.name == intern("macro_rules"),
4700 self.diagnostic().struct_span_err(span, "can't qualify macro_rules \
4701 invocation with `pub`")
4702 .fileline_help(span, "did you mean #[macro_export]?")
4705 self.diagnostic().struct_span_err(span, "can't qualify macro \
4706 invocation with `pub`")
4707 .fileline_help(span, "try adjusting the macro to put `pub` \
4708 inside the invocation")
4716 /// Parse a method or a macro invocation in a trait impl.
4717 fn parse_impl_method(&mut self, vis: Visibility)
4718 -> PResult<'a, (Ident, Vec<ast::Attribute>, ast::ImplItemKind)> {
4719 // code copied from parse_macro_use_or_failure... abstraction!
4720 if !self.token.is_any_keyword()
4721 && self.look_ahead(1, |t| *t == token::Not)
4722 && (self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren))
4723 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) {
4726 let last_span = self.last_span;
4727 self.complain_if_pub_macro(vis, last_span);
4729 let lo = self.span.lo;
4730 let pth = try!(self.parse_path(NoTypesAllowed));
4731 try!(self.expect(&token::Not));
4733 // eat a matched-delimiter token tree:
4734 let delim = try!(self.expect_open_delim());
4735 let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
4737 |p| p.parse_token_tree()));
4738 let m_ = Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT };
4739 let m: ast::Mac = codemap::Spanned { node: m_,
4741 self.last_span.hi) };
4742 if delim != token::Brace {
4743 try!(self.expect(&token::Semi))
4745 Ok((token::special_idents::invalid, vec![], ast::ImplItemKind::Macro(m)))
4747 let (constness, unsafety, abi) = try!(self.parse_fn_front_matter());
4748 let ident = try!(self.parse_ident());
4749 let mut generics = try!(self.parse_generics());
4750 let (explicit_self, decl) = try!(self.parse_fn_decl_with_self(|p| {
4753 generics.where_clause = try!(self.parse_where_clause());
4754 let (inner_attrs, body) = try!(self.parse_inner_attrs_and_block());
4755 Ok((ident, inner_attrs, ast::ImplItemKind::Method(ast::MethodSig {
4758 explicit_self: explicit_self,
4760 constness: constness,
4766 /// Parse trait Foo { ... }
4767 fn parse_item_trait(&mut self, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
4769 let ident = try!(self.parse_ident());
4770 let mut tps = try!(self.parse_generics());
4772 // Parse supertrait bounds.
4773 let bounds = try!(self.parse_colon_then_ty_param_bounds(BoundParsingMode::Bare));
4775 tps.where_clause = try!(self.parse_where_clause());
4777 let meths = try!(self.parse_trait_items());
4778 Ok((ident, ItemTrait(unsafety, tps, bounds, meths), None))
4781 /// Parses items implementations variants
4782 /// impl<T> Foo { ... }
4783 /// impl<T> ToString for &'static T { ... }
4784 /// impl Send for .. {}
4785 fn parse_item_impl(&mut self, unsafety: ast::Unsafety) -> PResult<'a, ItemInfo> {
4786 let impl_span = self.span;
4788 // First, parse type parameters if necessary.
4789 let mut generics = try!(self.parse_generics());
4791 // Special case: if the next identifier that follows is '(', don't
4792 // allow this to be parsed as a trait.
4793 let could_be_trait = self.token != token::OpenDelim(token::Paren);
4795 let neg_span = self.span;
4796 let polarity = if self.eat(&token::Not) {
4797 ast::ImplPolarity::Negative
4799 ast::ImplPolarity::Positive
4803 let mut ty = try!(self.parse_ty_sum());
4805 // Parse traits, if necessary.
4806 let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) {
4807 // New-style trait. Reinterpret the type as a trait.
4809 TyPath(None, ref path) => {
4811 path: (*path).clone(),
4816 self.span_err(ty.span, "not a trait");
4822 ast::ImplPolarity::Negative => {
4823 // This is a negated type implementation
4824 // `impl !MyType {}`, which is not allowed.
4825 self.span_err(neg_span, "inherent implementation can't be negated");
4832 if opt_trait.is_some() && self.eat(&token::DotDot) {
4833 if generics.is_parameterized() {
4834 self.span_err(impl_span, "default trait implementations are not \
4835 allowed to have generics");
4838 try!(self.expect(&token::OpenDelim(token::Brace)));
4839 try!(self.expect(&token::CloseDelim(token::Brace)));
4840 Ok((ast_util::impl_pretty_name(&opt_trait, None),
4841 ItemDefaultImpl(unsafety, opt_trait.unwrap()), None))
4843 if opt_trait.is_some() {
4844 ty = try!(self.parse_ty_sum());
4846 generics.where_clause = try!(self.parse_where_clause());
4848 try!(self.expect(&token::OpenDelim(token::Brace)));
4849 let attrs = try!(self.parse_inner_attributes());
4851 let mut impl_items = vec![];
4852 while !self.eat(&token::CloseDelim(token::Brace)) {
4853 impl_items.push(try!(self.parse_impl_item()));
4856 Ok((ast_util::impl_pretty_name(&opt_trait, Some(&*ty)),
4857 ItemImpl(unsafety, polarity, generics, opt_trait, ty, impl_items),
4862 /// Parse a::B<String,i32>
4863 fn parse_trait_ref(&mut self) -> PResult<'a, TraitRef> {
4865 path: try!(self.parse_path(LifetimeAndTypesWithoutColons)),
4866 ref_id: ast::DUMMY_NODE_ID,
4870 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<ast::LifetimeDef>> {
4871 if self.eat_keyword(keywords::For) {
4872 try!(self.expect(&token::Lt));
4873 let lifetime_defs = try!(self.parse_lifetime_defs());
4874 try!(self.expect_gt());
4881 /// Parse for<'l> a::B<String,i32>
4882 fn parse_poly_trait_ref(&mut self) -> PResult<'a, PolyTraitRef> {
4883 let lo = self.span.lo;
4884 let lifetime_defs = try!(self.parse_late_bound_lifetime_defs());
4886 Ok(ast::PolyTraitRef {
4887 bound_lifetimes: lifetime_defs,
4888 trait_ref: try!(self.parse_trait_ref()),
4889 span: mk_sp(lo, self.last_span.hi),
4893 /// Parse struct Foo { ... }
4894 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
4895 let class_name = try!(self.parse_ident());
4896 let mut generics = try!(self.parse_generics());
4898 // There is a special case worth noting here, as reported in issue #17904.
4899 // If we are parsing a tuple struct it is the case that the where clause
4900 // should follow the field list. Like so:
4902 // struct Foo<T>(T) where T: Copy;
4904 // If we are parsing a normal record-style struct it is the case
4905 // that the where clause comes before the body, and after the generics.
4906 // So if we look ahead and see a brace or a where-clause we begin
4907 // parsing a record style struct.
4909 // Otherwise if we look ahead and see a paren we parse a tuple-style
4912 let vdata = if self.token.is_keyword(keywords::Where) {
4913 generics.where_clause = try!(self.parse_where_clause());
4914 if self.eat(&token::Semi) {
4915 // If we see a: `struct Foo<T> where T: Copy;` style decl.
4916 VariantData::Unit(ast::DUMMY_NODE_ID)
4918 // If we see: `struct Foo<T> where T: Copy { ... }`
4919 VariantData::Struct(try!(self.parse_record_struct_body(ParsePub::Yes)),
4922 // No `where` so: `struct Foo<T>;`
4923 } else if self.eat(&token::Semi) {
4924 VariantData::Unit(ast::DUMMY_NODE_ID)
4925 // Record-style struct definition
4926 } else if self.token == token::OpenDelim(token::Brace) {
4927 VariantData::Struct(try!(self.parse_record_struct_body(ParsePub::Yes)),
4929 // Tuple-style struct definition with optional where-clause.
4930 } else if self.token == token::OpenDelim(token::Paren) {
4931 let body = VariantData::Tuple(try!(self.parse_tuple_struct_body(ParsePub::Yes)),
4932 ast::DUMMY_NODE_ID);
4933 generics.where_clause = try!(self.parse_where_clause());
4934 try!(self.expect(&token::Semi));
4937 let token_str = self.this_token_to_string();
4938 return Err(self.fatal(&format!("expected `where`, `{{`, `(`, or `;` after struct \
4939 name, found `{}`", token_str)))
4942 Ok((class_name, ItemStruct(vdata, generics), None))
4945 pub fn parse_record_struct_body(&mut self,
4946 parse_pub: ParsePub)
4947 -> PResult<'a, Vec<StructField>> {
4948 let mut fields = Vec::new();
4949 if self.eat(&token::OpenDelim(token::Brace)) {
4950 while self.token != token::CloseDelim(token::Brace) {
4951 fields.push(try!(self.parse_struct_decl_field(parse_pub)));
4956 let token_str = self.this_token_to_string();
4957 return Err(self.fatal(&format!("expected `where`, or `{{` after struct \
4965 pub fn parse_tuple_struct_body(&mut self,
4966 parse_pub: ParsePub)
4967 -> PResult<'a, Vec<StructField>> {
4968 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
4969 // Unit like structs are handled in parse_item_struct function
4970 let fields = try!(self.parse_unspanned_seq(
4971 &token::OpenDelim(token::Paren),
4972 &token::CloseDelim(token::Paren),
4973 seq_sep_trailing_allowed(token::Comma),
4975 let attrs = try!(p.parse_outer_attributes());
4977 let struct_field_ = ast::StructField_ {
4978 kind: UnnamedField (
4979 if parse_pub == ParsePub::Yes {
4980 try!(p.parse_visibility())
4985 id: ast::DUMMY_NODE_ID,
4986 ty: try!(p.parse_ty_sum()),
4989 Ok(spanned(lo, p.span.hi, struct_field_))
4995 /// Parse a structure field declaration
4996 pub fn parse_single_struct_field(&mut self,
4998 attrs: Vec<Attribute> )
4999 -> PResult<'a, StructField> {
5000 let a_var = try!(self.parse_name_and_ty(vis, attrs));
5005 token::CloseDelim(token::Brace) => {}
5007 let span = self.span;
5008 let token_str = self.this_token_to_string();
5009 return Err(self.span_fatal_help(span,
5010 &format!("expected `,`, or `}}`, found `{}`",
5012 "struct fields should be separated by commas"))
5018 /// Parse an element of a struct definition
5019 fn parse_struct_decl_field(&mut self, parse_pub: ParsePub) -> PResult<'a, StructField> {
5021 let attrs = try!(self.parse_outer_attributes());
5023 if self.eat_keyword(keywords::Pub) {
5024 if parse_pub == ParsePub::No {
5025 let span = self.last_span;
5026 self.span_err(span, "`pub` is not allowed here");
5028 return self.parse_single_struct_field(Public, attrs);
5031 return self.parse_single_struct_field(Inherited, attrs);
5034 /// Parse visibility: PUB or nothing
5035 fn parse_visibility(&mut self) -> PResult<'a, Visibility> {
5036 if self.eat_keyword(keywords::Pub) { Ok(Public) }
5037 else { Ok(Inherited) }
5040 /// Given a termination token, parse all of the items in a module
5041 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: BytePos) -> PResult<'a, Mod> {
5042 let mut items = vec![];
5043 while let Some(item) = try!(self.parse_item()) {
5047 if !self.eat(term) {
5048 let token_str = self.this_token_to_string();
5049 return Err(self.fatal(&format!("expected item, found `{}`", token_str)));
5052 let hi = if self.span == codemap::DUMMY_SP {
5059 inner: mk_sp(inner_lo, hi),
5064 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
5065 let id = try!(self.parse_ident());
5066 try!(self.expect(&token::Colon));
5067 let ty = try!(self.parse_ty_sum());
5068 try!(self.expect(&token::Eq));
5069 let e = try!(self.parse_expr());
5070 try!(self.commit_expr_expecting(&*e, token::Semi));
5071 let item = match m {
5072 Some(m) => ItemStatic(ty, m, e),
5073 None => ItemConst(ty, e),
5075 Ok((id, item, None))
5078 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
5079 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
5080 let id_span = self.span;
5081 let id = try!(self.parse_ident());
5082 if self.check(&token::Semi) {
5084 // This mod is in an external file. Let's go get it!
5085 let (m, attrs) = try!(self.eval_src_mod(id, outer_attrs, id_span));
5086 Ok((id, m, Some(attrs)))
5088 self.push_mod_path(id, outer_attrs);
5089 try!(self.expect(&token::OpenDelim(token::Brace)));
5090 let mod_inner_lo = self.span.lo;
5091 let old_owns_directory = self.owns_directory;
5092 self.owns_directory = true;
5093 let attrs = try!(self.parse_inner_attributes());
5094 let m = try!(self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo));
5095 self.owns_directory = old_owns_directory;
5096 self.pop_mod_path();
5097 Ok((id, ItemMod(m), Some(attrs)))
5101 fn push_mod_path(&mut self, id: Ident, attrs: &[Attribute]) {
5102 let default_path = self.id_to_interned_str(id);
5103 let file_path = match ::attr::first_attr_value_str_by_name(attrs, "path") {
5105 None => default_path,
5107 self.mod_path_stack.push(file_path)
5110 fn pop_mod_path(&mut self) {
5111 self.mod_path_stack.pop().unwrap();
5114 pub fn submod_path_from_attr(attrs: &[ast::Attribute], dir_path: &Path) -> Option<PathBuf> {
5115 ::attr::first_attr_value_str_by_name(attrs, "path").map(|d| dir_path.join(&*d))
5118 /// Returns either a path to a module, or .
5119 pub fn default_submod_path(id: ast::Ident, dir_path: &Path, codemap: &CodeMap) -> ModulePath
5121 let mod_name = id.to_string();
5122 let default_path_str = format!("{}.rs", mod_name);
5123 let secondary_path_str = format!("{}/mod.rs", mod_name);
5124 let default_path = dir_path.join(&default_path_str);
5125 let secondary_path = dir_path.join(&secondary_path_str);
5126 let default_exists = codemap.file_exists(&default_path);
5127 let secondary_exists = codemap.file_exists(&secondary_path);
5129 let result = match (default_exists, secondary_exists) {
5130 (true, false) => Ok(ModulePathSuccess { path: default_path, owns_directory: false }),
5131 (false, true) => Ok(ModulePathSuccess { path: secondary_path, owns_directory: true }),
5132 (false, false) => Err(ModulePathError {
5133 err_msg: format!("file not found for module `{}`", mod_name),
5134 help_msg: format!("name the file either {} or {} inside the directory {:?}",
5137 dir_path.display()),
5139 (true, true) => Err(ModulePathError {
5140 err_msg: format!("file for module `{}` found at both {} and {}",
5143 secondary_path_str),
5144 help_msg: "delete or rename one of them to remove the ambiguity".to_owned(),
5150 path_exists: default_exists || secondary_exists,
5155 fn submod_path(&mut self,
5157 outer_attrs: &[ast::Attribute],
5158 id_sp: Span) -> PResult<'a, ModulePathSuccess> {
5159 let mut prefix = PathBuf::from(&self.sess.codemap().span_to_filename(self.span));
5161 let mut dir_path = prefix;
5162 for part in &self.mod_path_stack {
5163 dir_path.push(&**part);
5166 if let Some(p) = Parser::submod_path_from_attr(outer_attrs, &dir_path) {
5167 return Ok(ModulePathSuccess { path: p, owns_directory: true });
5170 let paths = Parser::default_submod_path(id, &dir_path, self.sess.codemap());
5172 if !self.owns_directory {
5173 let mut err = self.diagnostic().struct_span_err(id_sp,
5174 "cannot declare a new module at this location");
5175 let this_module = match self.mod_path_stack.last() {
5176 Some(name) => name.to_string(),
5177 None => self.root_module_name.as_ref().unwrap().clone(),
5179 err.span_note(id_sp,
5180 &format!("maybe move this module `{0}` to its own directory \
5183 if paths.path_exists {
5184 err.span_note(id_sp,
5185 &format!("... or maybe `use` the module `{}` instead \
5186 of possibly redeclaring it",
5192 match paths.result {
5193 Ok(succ) => Ok(succ),
5194 Err(err) => Err(self.span_fatal_help(id_sp, &err.err_msg, &err.help_msg)),
5198 /// Read a module from a source file.
5199 fn eval_src_mod(&mut self,
5201 outer_attrs: &[ast::Attribute],
5203 -> PResult<'a, (ast::Item_, Vec<ast::Attribute> )> {
5204 let ModulePathSuccess { path, owns_directory } = try!(self.submod_path(id,
5208 self.eval_src_mod_from_path(path,
5214 fn eval_src_mod_from_path(&mut self,
5216 owns_directory: bool,
5218 id_sp: Span) -> PResult<'a, (ast::Item_, Vec<ast::Attribute> )> {
5219 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
5220 match included_mod_stack.iter().position(|p| *p == path) {
5222 let mut err = String::from("circular modules: ");
5223 let len = included_mod_stack.len();
5224 for p in &included_mod_stack[i.. len] {
5225 err.push_str(&p.to_string_lossy());
5226 err.push_str(" -> ");
5228 err.push_str(&path.to_string_lossy());
5229 return Err(self.span_fatal(id_sp, &err[..]));
5233 included_mod_stack.push(path.clone());
5234 drop(included_mod_stack);
5236 let mut p0 = new_sub_parser_from_file(self.sess,
5242 let mod_inner_lo = p0.span.lo;
5243 let mod_attrs = try!(p0.parse_inner_attributes());
5244 let m0 = try!(p0.parse_mod_items(&token::Eof, mod_inner_lo));
5245 self.sess.included_mod_stack.borrow_mut().pop();
5246 Ok((ast::ItemMod(m0), mod_attrs))
5249 /// Parse a function declaration from a foreign module
5250 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: BytePos,
5251 attrs: Vec<Attribute>) -> PResult<'a, P<ForeignItem>> {
5252 try!(self.expect_keyword(keywords::Fn));
5254 let (ident, mut generics) = try!(self.parse_fn_header());
5255 let decl = try!(self.parse_fn_decl(true));
5256 generics.where_clause = try!(self.parse_where_clause());
5257 let hi = self.span.hi;
5258 try!(self.expect(&token::Semi));
5259 Ok(P(ast::ForeignItem {
5262 node: ForeignItemFn(decl, generics),
5263 id: ast::DUMMY_NODE_ID,
5264 span: mk_sp(lo, hi),
5269 /// Parse a static item from a foreign module
5270 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: BytePos,
5271 attrs: Vec<Attribute>) -> PResult<'a, P<ForeignItem>> {
5272 try!(self.expect_keyword(keywords::Static));
5273 let mutbl = self.eat_keyword(keywords::Mut);
5275 let ident = try!(self.parse_ident());
5276 try!(self.expect(&token::Colon));
5277 let ty = try!(self.parse_ty_sum());
5278 let hi = self.span.hi;
5279 try!(self.expect(&token::Semi));
5283 node: ForeignItemStatic(ty, mutbl),
5284 id: ast::DUMMY_NODE_ID,
5285 span: mk_sp(lo, hi),
5290 /// Parse extern crate links
5294 /// extern crate foo;
5295 /// extern crate bar as foo;
5296 fn parse_item_extern_crate(&mut self,
5298 visibility: Visibility,
5299 attrs: Vec<Attribute>)
5300 -> PResult<'a, P<Item>> {
5302 let crate_name = try!(self.parse_ident());
5303 let (maybe_path, ident) = if let Some(ident) = try!(self.parse_rename()) {
5304 (Some(crate_name.name), ident)
5308 try!(self.expect(&token::Semi));
5310 let last_span = self.last_span;
5312 if visibility == ast::Public {
5313 self.span_warn(mk_sp(lo, last_span.hi),
5314 "`pub extern crate` does not work as expected and should not be used. \
5315 Likely to become an error. Prefer `extern crate` and `pub use`.");
5321 ItemExternCrate(maybe_path),
5326 /// Parse `extern` for foreign ABIs
5329 /// `extern` is expected to have been
5330 /// consumed before calling this method
5336 fn parse_item_foreign_mod(&mut self,
5338 opt_abi: Option<abi::Abi>,
5339 visibility: Visibility,
5340 mut attrs: Vec<Attribute>)
5341 -> PResult<'a, P<Item>> {
5342 try!(self.expect(&token::OpenDelim(token::Brace)));
5344 let abi = opt_abi.unwrap_or(abi::C);
5346 attrs.extend(try!(self.parse_inner_attributes()));
5348 let mut foreign_items = vec![];
5349 while let Some(item) = try!(self.parse_foreign_item()) {
5350 foreign_items.push(item);
5352 try!(self.expect(&token::CloseDelim(token::Brace)));
5354 let last_span = self.last_span;
5355 let m = ast::ForeignMod {
5357 items: foreign_items
5361 special_idents::invalid,
5367 /// Parse type Foo = Bar;
5368 fn parse_item_type(&mut self) -> PResult<'a, ItemInfo> {
5369 let ident = try!(self.parse_ident());
5370 let mut tps = try!(self.parse_generics());
5371 tps.where_clause = try!(self.parse_where_clause());
5372 try!(self.expect(&token::Eq));
5373 let ty = try!(self.parse_ty_sum());
5374 try!(self.expect(&token::Semi));
5375 Ok((ident, ItemTy(ty, tps), None))
5378 /// Parse the part of an "enum" decl following the '{'
5379 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
5380 let mut variants = Vec::new();
5381 let mut all_nullary = true;
5382 let mut any_disr = None;
5383 while self.token != token::CloseDelim(token::Brace) {
5384 let variant_attrs = try!(self.parse_outer_attributes());
5385 let vlo = self.span.lo;
5388 let mut disr_expr = None;
5389 let ident = try!(self.parse_ident());
5390 if self.check(&token::OpenDelim(token::Brace)) {
5391 // Parse a struct variant.
5392 all_nullary = false;
5393 struct_def = VariantData::Struct(try!(self.parse_record_struct_body(ParsePub::No)),
5394 ast::DUMMY_NODE_ID);
5395 } else if self.check(&token::OpenDelim(token::Paren)) {
5396 all_nullary = false;
5397 struct_def = VariantData::Tuple(try!(self.parse_tuple_struct_body(ParsePub::No)),
5398 ast::DUMMY_NODE_ID);
5399 } else if self.eat(&token::Eq) {
5400 disr_expr = Some(try!(self.parse_expr()));
5401 any_disr = disr_expr.as_ref().map(|expr| expr.span);
5402 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5404 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5407 let vr = ast::Variant_ {
5409 attrs: variant_attrs,
5411 disr_expr: disr_expr,
5413 variants.push(P(spanned(vlo, self.last_span.hi, vr)));
5415 if !self.eat(&token::Comma) { break; }
5417 try!(self.expect(&token::CloseDelim(token::Brace)));
5419 Some(disr_span) if !all_nullary =>
5420 self.span_err(disr_span,
5421 "discriminator values can only be used with a c-like enum"),
5425 Ok(ast::EnumDef { variants: variants })
5428 /// Parse an "enum" declaration
5429 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
5430 let id = try!(self.parse_ident());
5431 let mut generics = try!(self.parse_generics());
5432 generics.where_clause = try!(self.parse_where_clause());
5433 try!(self.expect(&token::OpenDelim(token::Brace)));
5435 let enum_definition = try!(self.parse_enum_def(&generics));
5436 Ok((id, ItemEnum(enum_definition, generics), None))
5439 /// Parses a string as an ABI spec on an extern type or module. Consumes
5440 /// the `extern` keyword, if one is found.
5441 fn parse_opt_abi(&mut self) -> PResult<'a, Option<abi::Abi>> {
5443 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
5445 self.expect_no_suffix(sp, "ABI spec", suf);
5447 match abi::lookup(&s.as_str()) {
5448 Some(abi) => Ok(Some(abi)),
5450 let last_span = self.last_span;
5453 &format!("invalid ABI: expected one of [{}], \
5455 abi::all_names().join(", "),
5466 /// Parse one of the items allowed by the flags.
5467 /// NB: this function no longer parses the items inside an
5469 fn parse_item_(&mut self, attrs: Vec<Attribute>,
5470 macros_allowed: bool, attributes_allowed: bool) -> PResult<'a, Option<P<Item>>> {
5471 let nt_item = match self.token {
5472 token::Interpolated(token::NtItem(ref item)) => {
5473 Some((**item).clone())
5480 let mut attrs = attrs;
5481 mem::swap(&mut item.attrs, &mut attrs);
5482 item.attrs.extend(attrs);
5483 return Ok(Some(P(item)));
5488 let lo = self.span.lo;
5490 let visibility = try!(self.parse_visibility());
5492 if self.eat_keyword(keywords::Use) {
5494 let item_ = ItemUse(try!(self.parse_view_path()));
5495 try!(self.expect(&token::Semi));
5497 let last_span = self.last_span;
5498 let item = self.mk_item(lo,
5500 token::special_idents::invalid,
5504 return Ok(Some(item));
5507 if self.eat_keyword(keywords::Extern) {
5508 if self.eat_keyword(keywords::Crate) {
5509 return Ok(Some(try!(self.parse_item_extern_crate(lo, visibility, attrs))));
5512 let opt_abi = try!(self.parse_opt_abi());
5514 if self.eat_keyword(keywords::Fn) {
5515 // EXTERN FUNCTION ITEM
5516 let abi = opt_abi.unwrap_or(abi::C);
5517 let (ident, item_, extra_attrs) =
5518 try!(self.parse_item_fn(Unsafety::Normal, Constness::NotConst, abi));
5519 let last_span = self.last_span;
5520 let item = self.mk_item(lo,
5525 maybe_append(attrs, extra_attrs));
5526 return Ok(Some(item));
5527 } else if self.check(&token::OpenDelim(token::Brace)) {
5528 return Ok(Some(try!(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs))));
5531 try!(self.unexpected());
5534 if self.eat_keyword(keywords::Static) {
5536 let m = if self.eat_keyword(keywords::Mut) {MutMutable} else {MutImmutable};
5537 let (ident, item_, extra_attrs) = try!(self.parse_item_const(Some(m)));
5538 let last_span = self.last_span;
5539 let item = self.mk_item(lo,
5544 maybe_append(attrs, extra_attrs));
5545 return Ok(Some(item));
5547 if self.eat_keyword(keywords::Const) {
5548 if self.check_keyword(keywords::Fn)
5549 || (self.check_keyword(keywords::Unsafe)
5550 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
5551 // CONST FUNCTION ITEM
5552 let unsafety = if self.eat_keyword(keywords::Unsafe) {
5558 let (ident, item_, extra_attrs) =
5559 try!(self.parse_item_fn(unsafety, Constness::Const, abi::Rust));
5560 let last_span = self.last_span;
5561 let item = self.mk_item(lo,
5566 maybe_append(attrs, extra_attrs));
5567 return Ok(Some(item));
5571 if self.eat_keyword(keywords::Mut) {
5572 let last_span = self.last_span;
5573 self.diagnostic().struct_span_err(last_span, "const globals cannot be mutable")
5574 .fileline_help(last_span, "did you mean to declare a static?")
5577 let (ident, item_, extra_attrs) = try!(self.parse_item_const(None));
5578 let last_span = self.last_span;
5579 let item = self.mk_item(lo,
5584 maybe_append(attrs, extra_attrs));
5585 return Ok(Some(item));
5587 if self.check_keyword(keywords::Unsafe) &&
5588 self.look_ahead(1, |t| t.is_keyword(keywords::Trait))
5590 // UNSAFE TRAIT ITEM
5591 try!(self.expect_keyword(keywords::Unsafe));
5592 try!(self.expect_keyword(keywords::Trait));
5593 let (ident, item_, extra_attrs) =
5594 try!(self.parse_item_trait(ast::Unsafety::Unsafe));
5595 let last_span = self.last_span;
5596 let item = self.mk_item(lo,
5601 maybe_append(attrs, extra_attrs));
5602 return Ok(Some(item));
5604 if self.check_keyword(keywords::Unsafe) &&
5605 self.look_ahead(1, |t| t.is_keyword(keywords::Impl))
5608 try!(self.expect_keyword(keywords::Unsafe));
5609 try!(self.expect_keyword(keywords::Impl));
5610 let (ident, item_, extra_attrs) = try!(self.parse_item_impl(ast::Unsafety::Unsafe));
5611 let last_span = self.last_span;
5612 let item = self.mk_item(lo,
5617 maybe_append(attrs, extra_attrs));
5618 return Ok(Some(item));
5620 if self.check_keyword(keywords::Fn) {
5623 let (ident, item_, extra_attrs) =
5624 try!(self.parse_item_fn(Unsafety::Normal, Constness::NotConst, abi::Rust));
5625 let last_span = self.last_span;
5626 let item = self.mk_item(lo,
5631 maybe_append(attrs, extra_attrs));
5632 return Ok(Some(item));
5634 if self.check_keyword(keywords::Unsafe)
5635 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
5636 // UNSAFE FUNCTION ITEM
5638 let abi = if self.eat_keyword(keywords::Extern) {
5639 try!(self.parse_opt_abi()).unwrap_or(abi::C)
5643 try!(self.expect_keyword(keywords::Fn));
5644 let (ident, item_, extra_attrs) =
5645 try!(self.parse_item_fn(Unsafety::Unsafe, Constness::NotConst, abi));
5646 let last_span = self.last_span;
5647 let item = self.mk_item(lo,
5652 maybe_append(attrs, extra_attrs));
5653 return Ok(Some(item));
5655 if self.eat_keyword(keywords::Mod) {
5657 let (ident, item_, extra_attrs) =
5658 try!(self.parse_item_mod(&attrs[..]));
5659 let last_span = self.last_span;
5660 let item = self.mk_item(lo,
5665 maybe_append(attrs, extra_attrs));
5666 return Ok(Some(item));
5668 if self.eat_keyword(keywords::Type) {
5670 let (ident, item_, extra_attrs) = try!(self.parse_item_type());
5671 let last_span = self.last_span;
5672 let item = self.mk_item(lo,
5677 maybe_append(attrs, extra_attrs));
5678 return Ok(Some(item));
5680 if self.eat_keyword(keywords::Enum) {
5682 let (ident, item_, extra_attrs) = try!(self.parse_item_enum());
5683 let last_span = self.last_span;
5684 let item = self.mk_item(lo,
5689 maybe_append(attrs, extra_attrs));
5690 return Ok(Some(item));
5692 if self.eat_keyword(keywords::Trait) {
5694 let (ident, item_, extra_attrs) =
5695 try!(self.parse_item_trait(ast::Unsafety::Normal));
5696 let last_span = self.last_span;
5697 let item = self.mk_item(lo,
5702 maybe_append(attrs, extra_attrs));
5703 return Ok(Some(item));
5705 if self.eat_keyword(keywords::Impl) {
5707 let (ident, item_, extra_attrs) = try!(self.parse_item_impl(ast::Unsafety::Normal));
5708 let last_span = self.last_span;
5709 let item = self.mk_item(lo,
5714 maybe_append(attrs, extra_attrs));
5715 return Ok(Some(item));
5717 if self.eat_keyword(keywords::Struct) {
5719 let (ident, item_, extra_attrs) = try!(self.parse_item_struct());
5720 let last_span = self.last_span;
5721 let item = self.mk_item(lo,
5726 maybe_append(attrs, extra_attrs));
5727 return Ok(Some(item));
5729 self.parse_macro_use_or_failure(attrs,macros_allowed,attributes_allowed,lo,visibility)
5732 /// Parse a foreign item.
5733 fn parse_foreign_item(&mut self) -> PResult<'a, Option<P<ForeignItem>>> {
5734 let attrs = try!(self.parse_outer_attributes());
5735 let lo = self.span.lo;
5736 let visibility = try!(self.parse_visibility());
5738 if self.check_keyword(keywords::Static) {
5739 // FOREIGN STATIC ITEM
5740 return Ok(Some(try!(self.parse_item_foreign_static(visibility, lo, attrs))));
5742 if self.check_keyword(keywords::Fn) || self.check_keyword(keywords::Unsafe) {
5743 // FOREIGN FUNCTION ITEM
5744 return Ok(Some(try!(self.parse_item_foreign_fn(visibility, lo, attrs))));
5747 // FIXME #5668: this will occur for a macro invocation:
5748 match try!(self.parse_macro_use_or_failure(attrs, true, false, lo, visibility)) {
5750 return Err(self.span_fatal(item.span, "macros cannot expand to foreign items"));
5756 /// This is the fall-through for parsing items.
5757 fn parse_macro_use_or_failure(
5759 attrs: Vec<Attribute> ,
5760 macros_allowed: bool,
5761 attributes_allowed: bool,
5763 visibility: Visibility
5764 ) -> PResult<'a, Option<P<Item>>> {
5765 if macros_allowed && !self.token.is_any_keyword()
5766 && self.look_ahead(1, |t| *t == token::Not)
5767 && (self.look_ahead(2, |t| t.is_plain_ident())
5768 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren))
5769 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) {
5770 // MACRO INVOCATION ITEM
5772 let last_span = self.last_span;
5773 self.complain_if_pub_macro(visibility, last_span);
5775 let mac_lo = self.span.lo;
5778 let pth = try!(self.parse_path(NoTypesAllowed));
5779 try!(self.expect(&token::Not));
5781 // a 'special' identifier (like what `macro_rules!` uses)
5782 // is optional. We should eventually unify invoc syntax
5784 let id = if self.token.is_plain_ident() {
5785 try!(self.parse_ident())
5787 token::special_idents::invalid // no special identifier
5789 // eat a matched-delimiter token tree:
5790 let delim = try!(self.expect_open_delim());
5791 let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
5793 |p| p.parse_token_tree()));
5794 // single-variant-enum... :
5795 let m = Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT };
5796 let m: ast::Mac = codemap::Spanned { node: m,
5798 self.last_span.hi) };
5800 if delim != token::Brace {
5801 if !self.eat(&token::Semi) {
5802 let last_span = self.last_span;
5803 self.span_err(last_span,
5804 "macros that expand to items must either \
5805 be surrounded with braces or followed by \
5810 let item_ = ItemMac(m);
5811 let last_span = self.last_span;
5812 let item = self.mk_item(lo,
5818 return Ok(Some(item));
5821 // FAILURE TO PARSE ITEM
5825 let last_span = self.last_span;
5826 return Err(self.span_fatal(last_span, "unmatched visibility `pub`"));
5830 if !attributes_allowed && !attrs.is_empty() {
5831 self.expected_item_err(&attrs);
5836 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
5837 let attrs = try!(self.parse_outer_attributes());
5838 self.parse_item_(attrs, true, false)
5842 /// Matches view_path : MOD? non_global_path as IDENT
5843 /// | MOD? non_global_path MOD_SEP LBRACE RBRACE
5844 /// | MOD? non_global_path MOD_SEP LBRACE ident_seq RBRACE
5845 /// | MOD? non_global_path MOD_SEP STAR
5846 /// | MOD? non_global_path
5847 fn parse_view_path(&mut self) -> PResult<'a, P<ViewPath>> {
5848 let lo = self.span.lo;
5850 // Allow a leading :: because the paths are absolute either way.
5851 // This occurs with "use $crate::..." in macros.
5852 self.eat(&token::ModSep);
5854 if self.check(&token::OpenDelim(token::Brace)) {
5856 let idents = try!(self.parse_unspanned_seq(
5857 &token::OpenDelim(token::Brace),
5858 &token::CloseDelim(token::Brace),
5859 seq_sep_trailing_allowed(token::Comma),
5860 |p| p.parse_path_list_item()));
5861 let path = ast::Path {
5862 span: mk_sp(lo, self.span.hi),
5864 segments: Vec::new()
5866 return Ok(P(spanned(lo, self.span.hi, ViewPathList(path, idents))));
5869 let first_ident = try!(self.parse_ident());
5870 let mut path = vec!(first_ident);
5871 if let token::ModSep = self.token {
5872 // foo::bar or foo::{a,b,c} or foo::*
5873 while self.check(&token::ModSep) {
5877 token::Ident(..) => {
5878 let ident = try!(self.parse_ident());
5882 // foo::bar::{a,b,c}
5883 token::OpenDelim(token::Brace) => {
5884 let idents = try!(self.parse_unspanned_seq(
5885 &token::OpenDelim(token::Brace),
5886 &token::CloseDelim(token::Brace),
5887 seq_sep_trailing_allowed(token::Comma),
5888 |p| p.parse_path_list_item()
5890 let path = ast::Path {
5891 span: mk_sp(lo, self.span.hi),
5893 segments: path.into_iter().map(|identifier| {
5895 identifier: identifier,
5896 parameters: ast::PathParameters::none(),
5900 return Ok(P(spanned(lo, self.span.hi, ViewPathList(path, idents))));
5904 token::BinOp(token::Star) => {
5906 let path = ast::Path {
5907 span: mk_sp(lo, self.span.hi),
5909 segments: path.into_iter().map(|identifier| {
5911 identifier: identifier,
5912 parameters: ast::PathParameters::none(),
5916 return Ok(P(spanned(lo, self.span.hi, ViewPathGlob(path))));
5919 // fall-through for case foo::bar::;
5921 self.span_err(self.span, "expected identifier or `{` or `*`, found `;`");
5928 let mut rename_to = path[path.len() - 1];
5929 let path = ast::Path {
5930 span: mk_sp(lo, self.last_span.hi),
5932 segments: path.into_iter().map(|identifier| {
5934 identifier: identifier,
5935 parameters: ast::PathParameters::none(),
5939 rename_to = try!(self.parse_rename()).unwrap_or(rename_to);
5940 Ok(P(spanned(lo, self.last_span.hi, ViewPathSimple(rename_to, path))))
5943 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
5944 if self.eat_keyword(keywords::As) {
5945 self.parse_ident().map(Some)
5951 /// Parses a source module as a crate. This is the main
5952 /// entry point for the parser.
5953 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
5954 let lo = self.span.lo;
5956 attrs: try!(self.parse_inner_attributes()),
5957 module: try!(self.parse_mod_items(&token::Eof, lo)),
5958 config: self.cfg.clone(),
5959 span: mk_sp(lo, self.span.lo),
5960 exported_macros: Vec::new(),
5964 pub fn parse_optional_str(&mut self)
5965 -> Option<(InternedString,
5967 Option<ast::Name>)> {
5968 let ret = match self.token {
5969 token::Literal(token::Str_(s), suf) => {
5970 (self.id_to_interned_str(ast::Ident::with_empty_ctxt(s)), ast::CookedStr, suf)
5972 token::Literal(token::StrRaw(s, n), suf) => {
5973 (self.id_to_interned_str(ast::Ident::with_empty_ctxt(s)), ast::RawStr(n), suf)
5981 pub fn parse_str(&mut self) -> PResult<'a, (InternedString, StrStyle)> {
5982 match self.parse_optional_str() {
5983 Some((s, style, suf)) => {
5984 let sp = self.last_span;
5985 self.expect_no_suffix(sp, "string literal", suf);
5988 _ => Err(self.fatal("expected string literal"))