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(try!(($p).bump_and_get()))
177 if let Some(token::Interpolated(token::$constructor(x))) = found {
178 return Ok(x.clone());
182 (no_clone $p:expr, $constructor:ident) => (
184 let found = match ($p).token {
185 token::Interpolated(token::$constructor(_)) => {
186 Some(try!(($p).bump_and_get()))
190 if let Some(token::Interpolated(token::$constructor(x))) = found {
195 (deref $p:expr, $constructor:ident) => (
197 let found = match ($p).token {
198 token::Interpolated(token::$constructor(_)) => {
199 Some(try!(($p).bump_and_get()))
203 if let Some(token::Interpolated(token::$constructor(x))) = found {
204 return Ok((*x).clone());
208 (Some deref $p:expr, $constructor:ident) => (
210 let found = match ($p).token {
211 token::Interpolated(token::$constructor(_)) => {
212 Some(try!(($p).bump_and_get()))
216 if let Some(token::Interpolated(token::$constructor(x))) = found {
217 return Ok(Some((*x).clone()));
221 (pair_empty $p:expr, $constructor:ident) => (
223 let found = match ($p).token {
224 token::Interpolated(token::$constructor(_)) => {
225 Some(try!(($p).bump_and_get()))
229 if let Some(token::Interpolated(token::$constructor(x))) = found {
230 return Ok((Vec::new(), x));
237 fn maybe_append(mut lhs: Vec<Attribute>, rhs: Option<Vec<Attribute>>)
239 if let Some(ref attrs) = rhs {
240 lhs.extend(attrs.iter().cloned())
245 /* ident is handled by common.rs */
247 pub struct Parser<'a> {
248 pub sess: &'a ParseSess,
249 /// the current token:
250 pub token: token::Token,
251 /// the span of the current token:
253 /// the span of the prior token:
255 pub cfg: CrateConfig,
256 /// the previous token or None (only stashed sometimes).
257 pub last_token: Option<Box<token::Token>>,
258 pub buffer: [TokenAndSpan; 4],
259 pub buffer_start: isize,
260 pub buffer_end: isize,
261 pub tokens_consumed: usize,
262 pub restrictions: Restrictions,
263 pub quote_depth: usize, // not (yet) related to the quasiquoter
264 pub reader: Box<Reader+'a>,
265 pub interner: Rc<token::IdentInterner>,
266 /// The set of seen errors about obsolete syntax. Used to suppress
267 /// extra detail when the same error is seen twice
268 pub obsolete_set: HashSet<ObsoleteSyntax>,
269 /// Used to determine the path to externally loaded source files
270 pub mod_path_stack: Vec<InternedString>,
271 /// Stack of spans of open delimiters. Used for error message.
272 pub open_braces: Vec<Span>,
273 /// Flag if this parser "owns" the directory that it is currently parsing
274 /// in. This will affect how nested files are looked up.
275 pub owns_directory: bool,
276 /// Name of the root module this parser originated from. If `None`, then the
277 /// name is not known. This does not change while the parser is descending
278 /// into modules, and sub-parsers have new values for this name.
279 pub root_module_name: Option<String>,
280 pub expected_tokens: Vec<TokenType>,
283 #[derive(PartialEq, Eq, Clone)]
286 Keyword(keywords::Keyword),
291 fn to_string(&self) -> String {
293 TokenType::Token(ref t) => format!("`{}`", Parser::token_to_string(t)),
294 TokenType::Operator => "an operator".to_string(),
295 TokenType::Keyword(kw) => format!("`{}`", kw.to_name()),
300 fn is_plain_ident_or_underscore(t: &token::Token) -> bool {
301 t.is_plain_ident() || *t == token::Underscore
304 /// Information about the path to a module.
305 pub struct ModulePath {
307 pub path_exists: bool,
308 pub result: Result<ModulePathSuccess, ModulePathError>,
311 pub struct ModulePathSuccess {
312 pub path: ::std::path::PathBuf,
313 pub owns_directory: bool,
316 pub struct ModulePathError {
318 pub help_msg: String,
323 AttributesParsed(ThinAttributes),
324 AlreadyParsed(P<Expr>),
327 impl From<Option<ThinAttributes>> for LhsExpr {
328 fn from(o: Option<ThinAttributes>) -> Self {
329 if let Some(attrs) = o {
330 LhsExpr::AttributesParsed(attrs)
332 LhsExpr::NotYetParsed
337 impl From<P<Expr>> for LhsExpr {
338 fn from(expr: P<Expr>) -> Self {
339 LhsExpr::AlreadyParsed(expr)
343 impl<'a> Parser<'a> {
344 pub fn new(sess: &'a ParseSess,
345 cfg: ast::CrateConfig,
346 mut rdr: Box<Reader+'a>)
349 let tok0 = rdr.real_token();
351 let placeholder = TokenAndSpan {
352 tok: token::Underscore,
358 interner: token::get_ident_interner(),
374 restrictions: Restrictions::empty(),
376 obsolete_set: HashSet::new(),
377 mod_path_stack: Vec::new(),
378 open_braces: Vec::new(),
379 owns_directory: true,
380 root_module_name: None,
381 expected_tokens: Vec::new(),
385 /// Convert a token to a string using self's reader
386 pub fn token_to_string(token: &token::Token) -> String {
387 pprust::token_to_string(token)
390 /// Convert the current token to a string using self's reader
391 pub fn this_token_to_string(&self) -> String {
392 Parser::token_to_string(&self.token)
395 pub fn unexpected_last(&self, t: &token::Token) -> DiagnosticBuilder<'a> {
396 let token_str = Parser::token_to_string(t);
397 let last_span = self.last_span;
398 self.span_fatal(last_span, &format!("unexpected token: `{}`",
402 pub fn unexpected(&mut self) -> DiagnosticBuilder<'a> {
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 {
416 let token_str = Parser::token_to_string(t);
417 let this_token_str = self.this_token_to_string();
418 Err(self.fatal(&format!("expected `{}`, found `{}`",
423 self.expect_one_of(unsafe { slice::from_raw_parts(t, 1) }, &[])
427 /// Expect next token to be edible or inedible token. If edible,
428 /// then consume it; if inedible, then return without consuming
429 /// anything. Signal a fatal error if next token is unexpected.
430 pub fn expect_one_of(&mut self,
431 edible: &[token::Token],
432 inedible: &[token::Token]) -> PResult<'a, ()>{
433 fn tokens_to_string(tokens: &[TokenType]) -> String {
434 let mut i = tokens.iter();
435 // This might be a sign we need a connect method on Iterator.
437 .map_or("".to_string(), |t| t.to_string());
438 i.enumerate().fold(b, |mut b, (i, ref a)| {
439 if tokens.len() > 2 && i == tokens.len() - 2 {
441 } else if tokens.len() == 2 && i == tokens.len() - 2 {
446 b.push_str(&*a.to_string());
450 if edible.contains(&self.token) {
452 } else if inedible.contains(&self.token) {
453 // leave it in the input
456 let mut expected = edible.iter()
457 .map(|x| TokenType::Token(x.clone()))
458 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
459 .chain(self.expected_tokens.iter().cloned())
460 .collect::<Vec<_>>();
461 expected.sort_by(|a, b| a.to_string().cmp(&b.to_string()));
463 let expect = tokens_to_string(&expected[..]);
464 let actual = self.this_token_to_string();
466 &(if expected.len() > 1 {
467 (format!("expected one of {}, found `{}`",
470 } else if expected.is_empty() {
471 (format!("unexpected token: `{}`",
474 (format!("expected {}, found `{}`",
482 /// Check for erroneous `ident { }`; if matches, signal error and
483 /// recover (without consuming any expected input token). Returns
484 /// true if and only if input was consumed for recovery.
485 pub fn check_for_erroneous_unit_struct_expecting(&mut self,
486 expected: &[token::Token])
487 -> PResult<'a, bool> {
488 if self.token == token::OpenDelim(token::Brace)
489 && expected.iter().all(|t| *t != token::OpenDelim(token::Brace))
490 && self.look_ahead(1, |t| *t == token::CloseDelim(token::Brace)) {
491 // matched; signal non-fatal error and recover.
492 let span = self.span;
494 "unit-like struct construction is written with no trailing `{ }`");
495 try!(self.eat(&token::OpenDelim(token::Brace)));
496 try!(self.eat(&token::CloseDelim(token::Brace)));
503 /// Commit to parsing a complete expression `e` expected to be
504 /// followed by some token from the set edible + inedible. Recover
505 /// from anticipated input errors, discarding erroneous characters.
506 pub fn commit_expr(&mut self, e: &Expr, edible: &[token::Token],
507 inedible: &[token::Token]) -> PResult<'a, ()> {
508 debug!("commit_expr {:?}", e);
509 if let ExprPath(..) = e.node {
510 // might be unit-struct construction; check for recoverableinput error.
511 let expected = edible.iter()
513 .chain(inedible.iter().cloned())
514 .collect::<Vec<_>>();
515 try!(self.check_for_erroneous_unit_struct_expecting(&expected[..]));
517 self.expect_one_of(edible, inedible)
520 pub fn commit_expr_expecting(&mut self, e: &Expr, edible: token::Token) -> PResult<'a, ()> {
521 self.commit_expr(e, &[edible], &[])
524 /// Commit to parsing a complete statement `s`, which expects to be
525 /// followed by some token from the set edible + inedible. Check
526 /// for recoverable input errors, discarding erroneous characters.
527 pub fn commit_stmt(&mut self, edible: &[token::Token],
528 inedible: &[token::Token]) -> PResult<'a, ()> {
531 .map_or(false, |t| t.is_ident() || t.is_path()) {
532 let expected = edible.iter()
534 .chain(inedible.iter().cloned())
535 .collect::<Vec<_>>();
536 try!(self.check_for_erroneous_unit_struct_expecting(&expected));
538 self.expect_one_of(edible, inedible)
541 pub fn commit_stmt_expecting(&mut self, edible: token::Token) -> PResult<'a, ()> {
542 self.commit_stmt(&[edible], &[])
545 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
546 self.check_strict_keywords();
547 try!(self.check_reserved_keywords());
549 token::Ident(i, _) => {
553 token::Interpolated(token::NtIdent(..)) => {
554 self.bug("ident interpolation not converted to real token");
557 let token_str = self.this_token_to_string();
558 Err(self.fatal(&format!("expected ident, found `{}`",
564 pub fn parse_ident_or_self_type(&mut self) -> PResult<'a, ast::Ident> {
565 if self.is_self_type_ident() {
566 self.expect_self_type_ident()
572 pub fn parse_path_list_item(&mut self) -> PResult<'a, ast::PathListItem> {
573 let lo = self.span.lo;
574 let node = if try!(self.eat_keyword(keywords::SelfValue)) {
575 let rename = try!(self.parse_rename());
576 ast::PathListMod { id: ast::DUMMY_NODE_ID, rename: rename }
578 let ident = try!(self.parse_ident());
579 let rename = try!(self.parse_rename());
580 ast::PathListIdent { name: ident, rename: rename, id: ast::DUMMY_NODE_ID }
582 let hi = self.last_span.hi;
583 Ok(spanned(lo, hi, node))
586 /// Check if the next token is `tok`, and return `true` if so.
588 /// This method is will automatically add `tok` to `expected_tokens` if `tok` is not
590 pub fn check(&mut self, tok: &token::Token) -> bool {
591 let is_present = self.token == *tok;
592 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
596 /// Consume token 'tok' if it exists. Returns true if the given
597 /// token was present, false otherwise.
598 pub fn eat(&mut self, tok: &token::Token) -> PResult<'a, bool> {
599 let is_present = self.check(tok);
600 if is_present { try!(self.bump())}
604 pub fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
605 self.expected_tokens.push(TokenType::Keyword(kw));
606 self.token.is_keyword(kw)
609 /// If the next token is the given keyword, eat it and return
610 /// true. Otherwise, return false.
611 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, bool> {
612 if self.check_keyword(kw) {
620 pub fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> PResult<'a, bool> {
621 if self.token.is_keyword(kw) {
629 /// If the given word is not a keyword, signal an error.
630 /// If the next token is not the given word, signal an error.
631 /// Otherwise, eat it.
632 pub fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> {
633 if !try!(self.eat_keyword(kw) ){
634 self.expect_one_of(&[], &[])
640 /// Signal an error if the given string is a strict keyword
641 pub fn check_strict_keywords(&mut self) {
642 if self.token.is_strict_keyword() {
643 let token_str = self.this_token_to_string();
644 let span = self.span;
646 &format!("expected identifier, found keyword `{}`",
651 /// Signal an error if the current token is a reserved keyword
652 pub fn check_reserved_keywords(&mut self) -> PResult<'a, ()>{
653 if self.token.is_reserved_keyword() {
654 let token_str = self.this_token_to_string();
655 Err(self.fatal(&format!("`{}` is a reserved keyword", token_str)))
661 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
662 /// `&` and continue. If an `&` is not seen, signal an error.
663 fn expect_and(&mut self) -> PResult<'a, ()> {
664 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
666 token::BinOp(token::And) => self.bump(),
668 let span = self.span;
669 let lo = span.lo + BytePos(1);
670 Ok(self.replace_token(token::BinOp(token::And), lo, span.hi))
672 _ => self.expect_one_of(&[], &[])
676 pub fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
678 None => {/* everything ok */}
680 let text = suf.as_str();
682 self.span_bug(sp, "found empty literal suffix in Some")
684 self.span_err(sp, &*format!("{} with a suffix is invalid", kind));
690 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
691 /// `<` and continue. If a `<` is not seen, return false.
693 /// This is meant to be used when parsing generics on a path to get the
695 fn eat_lt(&mut self) -> PResult<'a, bool> {
696 self.expected_tokens.push(TokenType::Token(token::Lt));
698 token::Lt => { try!(self.bump()); Ok(true)}
699 token::BinOp(token::Shl) => {
700 let span = self.span;
701 let lo = span.lo + BytePos(1);
702 self.replace_token(token::Lt, lo, span.hi);
709 fn expect_lt(&mut self) -> PResult<'a, ()> {
710 if !try!(self.eat_lt()) {
711 self.expect_one_of(&[], &[])
717 /// Expect and consume a GT. if a >> is seen, replace it
718 /// with a single > and continue. If a GT is not seen,
720 pub fn expect_gt(&mut self) -> PResult<'a, ()> {
721 self.expected_tokens.push(TokenType::Token(token::Gt));
723 token::Gt => self.bump(),
724 token::BinOp(token::Shr) => {
725 let span = self.span;
726 let lo = span.lo + BytePos(1);
727 Ok(self.replace_token(token::Gt, lo, span.hi))
729 token::BinOpEq(token::Shr) => {
730 let span = self.span;
731 let lo = span.lo + BytePos(1);
732 Ok(self.replace_token(token::Ge, lo, span.hi))
735 let span = self.span;
736 let lo = span.lo + BytePos(1);
737 Ok(self.replace_token(token::Eq, lo, span.hi))
740 let gt_str = Parser::token_to_string(&token::Gt);
741 let this_token_str = self.this_token_to_string();
742 Err(self.fatal(&format!("expected `{}`, found `{}`",
749 pub fn parse_seq_to_before_gt_or_return<T, F>(&mut self,
750 sep: Option<token::Token>,
752 -> PResult<'a, (P<[T]>, bool)>
753 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
755 let mut v = Vec::new();
756 // This loop works by alternating back and forth between parsing types
757 // and commas. For example, given a string `A, B,>`, the parser would
758 // first parse `A`, then a comma, then `B`, then a comma. After that it
759 // would encounter a `>` and stop. This lets the parser handle trailing
760 // commas in generic parameters, because it can stop either after
761 // parsing a type or after parsing a comma.
763 if self.check(&token::Gt)
764 || self.token == token::BinOp(token::Shr)
765 || self.token == token::Ge
766 || self.token == token::BinOpEq(token::Shr) {
771 match try!(f(self)) {
772 Some(result) => v.push(result),
773 None => return Ok((P::from_vec(v), true))
776 if let Some(t) = sep.as_ref() {
777 try!(self.expect(t));
782 return Ok((P::from_vec(v), false));
785 /// Parse a sequence bracketed by '<' and '>', stopping
787 pub fn parse_seq_to_before_gt<T, F>(&mut self,
788 sep: Option<token::Token>,
790 -> PResult<'a, P<[T]>> where
791 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
793 let (result, returned) = try!(self.parse_seq_to_before_gt_or_return(sep,
794 |p| Ok(Some(try!(f(p))))));
799 pub fn parse_seq_to_gt<T, F>(&mut self,
800 sep: Option<token::Token>,
802 -> PResult<'a, P<[T]>> where
803 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
805 let v = try!(self.parse_seq_to_before_gt(sep, f));
806 try!(self.expect_gt());
810 pub fn parse_seq_to_gt_or_return<T, F>(&mut self,
811 sep: Option<token::Token>,
813 -> PResult<'a, (P<[T]>, bool)> where
814 F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
816 let (v, returned) = try!(self.parse_seq_to_before_gt_or_return(sep, f));
818 try!(self.expect_gt());
820 return Ok((v, returned));
823 /// Parse a sequence, including the closing delimiter. The function
824 /// f must consume tokens until reaching the next separator or
826 pub fn parse_seq_to_end<T, F>(&mut self,
830 -> PResult<'a, Vec<T>> where
831 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
833 let val = try!(self.parse_seq_to_before_end(ket, sep, f));
838 /// Parse a sequence, not including the closing delimiter. The function
839 /// f must consume tokens until reaching the next separator or
841 pub fn parse_seq_to_before_end<T, F>(&mut self,
845 -> PResult<'a, Vec<T>> where
846 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
848 let mut first: bool = true;
850 while self.token != *ket {
853 if first { first = false; }
854 else { try!(self.expect(t)); }
858 if sep.trailing_sep_allowed && self.check(ket) { break; }
859 v.push(try!(f(self)));
864 /// Parse a sequence, including the closing delimiter. The function
865 /// f must consume tokens until reaching the next separator or
867 pub fn parse_unspanned_seq<T, F>(&mut self,
872 -> PResult<'a, Vec<T>> where
873 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
875 try!(self.expect(bra));
876 let result = try!(self.parse_seq_to_before_end(ket, sep, f));
881 /// Parse a sequence parameter of enum variant. For consistency purposes,
882 /// these should not be empty.
883 pub fn parse_enum_variant_seq<T, F>(&mut self,
888 -> PResult<'a, Vec<T>> where
889 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
891 let result = try!(self.parse_unspanned_seq(bra, ket, sep, f));
892 if result.is_empty() {
893 let last_span = self.last_span;
894 self.span_err(last_span,
895 "nullary enum variants are written with no trailing `( )`");
900 // NB: Do not use this function unless you actually plan to place the
901 // spanned list in the AST.
902 pub fn parse_seq<T, F>(&mut self,
907 -> PResult<'a, Spanned<Vec<T>>> where
908 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
910 let lo = self.span.lo;
911 try!(self.expect(bra));
912 let result = try!(self.parse_seq_to_before_end(ket, sep, f));
913 let hi = self.span.hi;
915 Ok(spanned(lo, hi, result))
918 /// Advance the parser by one token
919 pub fn bump(&mut self) -> PResult<'a, ()> {
920 self.last_span = self.span;
921 // Stash token for error recovery (sometimes; clone is not necessarily cheap).
922 self.last_token = if self.token.is_ident() ||
923 self.token.is_path() ||
924 self.token == token::Comma {
925 Some(Box::new(self.token.clone()))
929 let next = if self.buffer_start == self.buffer_end {
930 self.reader.real_token()
932 // Avoid token copies with `replace`.
933 let buffer_start = self.buffer_start as usize;
934 let next_index = (buffer_start + 1) & 3;
935 self.buffer_start = next_index as isize;
937 let placeholder = TokenAndSpan {
938 tok: token::Underscore,
941 mem::replace(&mut self.buffer[buffer_start], placeholder)
944 self.token = next.tok;
945 self.tokens_consumed += 1;
946 self.expected_tokens.clear();
947 // check after each token
948 self.check_unknown_macro_variable()
951 /// Advance the parser by one token and return the bumped token.
952 pub fn bump_and_get(&mut self) -> PResult<'a, token::Token> {
953 let old_token = mem::replace(&mut self.token, token::Underscore);
958 /// EFFECT: replace the current token and span with the given one
959 pub fn replace_token(&mut self,
963 self.last_span = mk_sp(self.span.lo, lo);
965 self.span = mk_sp(lo, hi);
967 pub fn buffer_length(&mut self) -> isize {
968 if self.buffer_start <= self.buffer_end {
969 return self.buffer_end - self.buffer_start;
971 return (4 - self.buffer_start) + self.buffer_end;
973 pub fn look_ahead<R, F>(&mut self, distance: usize, f: F) -> R where
974 F: FnOnce(&token::Token) -> R,
976 let dist = distance as isize;
977 while self.buffer_length() < dist {
978 self.buffer[self.buffer_end as usize] = self.reader.real_token();
979 self.buffer_end = (self.buffer_end + 1) & 3;
981 f(&self.buffer[((self.buffer_start + dist - 1) & 3) as usize].tok)
983 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
984 self.sess.span_diagnostic.struct_span_fatal(self.span, m)
986 pub fn span_fatal(&self, sp: Span, m: &str) -> DiagnosticBuilder<'a> {
987 self.sess.span_diagnostic.struct_span_fatal(sp, m)
989 pub fn span_fatal_help(&self, sp: Span, m: &str, help: &str) -> DiagnosticBuilder<'a> {
990 let mut err = self.sess.span_diagnostic.struct_span_fatal(sp, m);
991 err.fileline_help(sp, help);
994 pub fn bug(&self, m: &str) -> ! {
995 self.sess.span_diagnostic.span_bug(self.span, m)
997 pub fn warn(&self, m: &str) {
998 self.sess.span_diagnostic.span_warn(self.span, m)
1000 pub fn span_warn(&self, sp: Span, m: &str) {
1001 self.sess.span_diagnostic.span_warn(sp, m)
1003 pub fn span_err(&self, sp: Span, m: &str) {
1004 self.sess.span_diagnostic.span_err(sp, m)
1006 pub fn span_bug(&self, sp: Span, m: &str) -> ! {
1007 self.sess.span_diagnostic.span_bug(sp, m)
1009 pub fn abort_if_errors(&self) {
1010 self.sess.span_diagnostic.abort_if_errors();
1013 pub fn diagnostic(&self) -> &'a errors::Handler {
1014 &self.sess.span_diagnostic
1017 pub fn id_to_interned_str(&mut self, id: Ident) -> InternedString {
1021 /// Is the current token one of the keywords that signals a bare function
1023 pub fn token_is_bare_fn_keyword(&mut self) -> bool {
1024 self.check_keyword(keywords::Fn) ||
1025 self.check_keyword(keywords::Unsafe) ||
1026 self.check_keyword(keywords::Extern)
1029 pub fn get_lifetime(&mut self) -> ast::Ident {
1031 token::Lifetime(ref ident) => *ident,
1032 _ => self.bug("not a lifetime"),
1036 pub fn parse_for_in_type(&mut self) -> PResult<'a, Ty_> {
1038 Parses whatever can come after a `for` keyword in a type.
1039 The `for` has already been consumed.
1043 - for <'lt> |S| -> T
1047 - for <'lt> [unsafe] [extern "ABI"] fn (S) -> T
1048 - for <'lt> path::foo(a, b)
1053 let lo = self.span.lo;
1055 let lifetime_defs = try!(self.parse_late_bound_lifetime_defs());
1057 // examine next token to decide to do
1058 if self.token_is_bare_fn_keyword() {
1059 self.parse_ty_bare_fn(lifetime_defs)
1061 let hi = self.span.hi;
1062 let trait_ref = try!(self.parse_trait_ref());
1063 let poly_trait_ref = ast::PolyTraitRef { bound_lifetimes: lifetime_defs,
1064 trait_ref: trait_ref,
1065 span: mk_sp(lo, hi)};
1066 let other_bounds = if try!(self.eat(&token::BinOp(token::Plus)) ){
1067 try!(self.parse_ty_param_bounds(BoundParsingMode::Bare))
1072 Some(TraitTyParamBound(poly_trait_ref, TraitBoundModifier::None)).into_iter()
1073 .chain(other_bounds.into_vec())
1075 Ok(ast::TyPolyTraitRef(all_bounds))
1079 pub fn parse_ty_path(&mut self) -> PResult<'a, Ty_> {
1080 Ok(TyPath(None, try!(self.parse_path(LifetimeAndTypesWithoutColons))))
1083 /// parse a TyBareFn type:
1084 pub fn parse_ty_bare_fn(&mut self, lifetime_defs: Vec<ast::LifetimeDef>) -> PResult<'a, Ty_> {
1087 [unsafe] [extern "ABI"] fn <'lt> (S) -> T
1088 ^~~~^ ^~~~^ ^~~~^ ^~^ ^
1091 | | | Argument types
1097 let unsafety = try!(self.parse_unsafety());
1098 let abi = if try!(self.eat_keyword(keywords::Extern) ){
1099 try!(self.parse_opt_abi()).unwrap_or(abi::C)
1104 try!(self.expect_keyword(keywords::Fn));
1105 let (inputs, variadic) = try!(self.parse_fn_args(false, true));
1106 let ret_ty = try!(self.parse_ret_ty());
1107 let decl = P(FnDecl {
1112 Ok(TyBareFn(P(BareFnTy {
1115 lifetimes: lifetime_defs,
1120 /// Parses an obsolete closure kind (`&:`, `&mut:`, or `:`).
1121 pub fn parse_obsolete_closure_kind(&mut self) -> PResult<'a, ()> {
1122 let lo = self.span.lo;
1124 self.check(&token::BinOp(token::And)) &&
1125 self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
1126 self.look_ahead(2, |t| *t == token::Colon)
1132 self.token == token::BinOp(token::And) &&
1133 self.look_ahead(1, |t| *t == token::Colon)
1138 try!(self.eat(&token::Colon))
1145 let span = mk_sp(lo, self.span.hi);
1146 self.obsolete(span, ObsoleteSyntax::ClosureKind);
1150 pub fn parse_unsafety(&mut self) -> PResult<'a, Unsafety> {
1151 if try!(self.eat_keyword(keywords::Unsafe)) {
1152 return Ok(Unsafety::Unsafe);
1154 return Ok(Unsafety::Normal);
1158 /// Parse the items in a trait declaration
1159 pub fn parse_trait_items(&mut self) -> PResult<'a, Vec<P<TraitItem>>> {
1160 self.parse_unspanned_seq(
1161 &token::OpenDelim(token::Brace),
1162 &token::CloseDelim(token::Brace),
1164 |p| -> PResult<'a, P<TraitItem>> {
1165 maybe_whole!(no_clone p, NtTraitItem);
1166 let mut attrs = try!(p.parse_outer_attributes());
1169 let (name, node) = if try!(p.eat_keyword(keywords::Type)) {
1170 let TyParam {ident, bounds, default, ..} = try!(p.parse_ty_param());
1171 try!(p.expect(&token::Semi));
1172 (ident, TypeTraitItem(bounds, default))
1173 } else if p.is_const_item() {
1174 try!(p.expect_keyword(keywords::Const));
1175 let ident = try!(p.parse_ident());
1176 try!(p.expect(&token::Colon));
1177 let ty = try!(p.parse_ty_sum());
1178 let default = if p.check(&token::Eq) {
1180 let expr = try!(p.parse_expr());
1181 try!(p.commit_expr_expecting(&expr, token::Semi));
1184 try!(p.expect(&token::Semi));
1187 (ident, ConstTraitItem(ty, default))
1189 let (constness, unsafety, abi) = try!(p.parse_fn_front_matter());
1191 let ident = try!(p.parse_ident());
1192 let mut generics = try!(p.parse_generics());
1194 let (explicit_self, d) = try!(p.parse_fn_decl_with_self(|p: &mut Parser<'a>|{
1195 // This is somewhat dubious; We don't want to allow
1196 // argument names to be left off if there is a
1198 p.parse_arg_general(false)
1201 generics.where_clause = try!(p.parse_where_clause());
1202 let sig = ast::MethodSig {
1204 constness: constness,
1208 explicit_self: explicit_self,
1211 let body = match p.token {
1214 debug!("parse_trait_methods(): parsing required method");
1217 token::OpenDelim(token::Brace) => {
1218 debug!("parse_trait_methods(): parsing provided method");
1219 let (inner_attrs, body) =
1220 try!(p.parse_inner_attrs_and_block());
1221 attrs.extend(inner_attrs.iter().cloned());
1226 let token_str = p.this_token_to_string();
1227 return Err(p.fatal(&format!("expected `;` or `{{`, found `{}`",
1231 (ident, ast::MethodTraitItem(sig, body))
1235 id: ast::DUMMY_NODE_ID,
1239 span: mk_sp(lo, p.last_span.hi),
1244 /// Parse a possibly mutable type
1245 pub fn parse_mt(&mut self) -> PResult<'a, MutTy> {
1246 let mutbl = try!(self.parse_mutability());
1247 let t = try!(self.parse_ty());
1248 Ok(MutTy { ty: t, mutbl: mutbl })
1251 /// Parse optional return type [ -> TY ] in function decl
1252 pub fn parse_ret_ty(&mut self) -> PResult<'a, FunctionRetTy> {
1253 if try!(self.eat(&token::RArrow) ){
1254 if try!(self.eat(&token::Not) ){
1255 Ok(NoReturn(self.last_span))
1257 Ok(Return(try!(self.parse_ty())))
1260 let pos = self.span.lo;
1261 Ok(DefaultReturn(mk_sp(pos, pos)))
1265 /// Parse a type in a context where `T1+T2` is allowed.
1266 pub fn parse_ty_sum(&mut self) -> PResult<'a, P<Ty>> {
1267 let lo = self.span.lo;
1268 let lhs = try!(self.parse_ty());
1270 if !try!(self.eat(&token::BinOp(token::Plus)) ){
1274 let bounds = try!(self.parse_ty_param_bounds(BoundParsingMode::Bare));
1276 // In type grammar, `+` is treated like a binary operator,
1277 // and hence both L and R side are required.
1278 if bounds.is_empty() {
1279 let last_span = self.last_span;
1280 self.span_err(last_span,
1281 "at least one type parameter bound \
1282 must be specified");
1285 let sp = mk_sp(lo, self.last_span.hi);
1286 let sum = ast::TyObjectSum(lhs, bounds);
1287 Ok(P(Ty {id: ast::DUMMY_NODE_ID, node: sum, span: sp}))
1291 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1292 maybe_whole!(no_clone self, NtTy);
1294 let lo = self.span.lo;
1296 let t = if self.check(&token::OpenDelim(token::Paren)) {
1299 // (t) is a parenthesized ty
1300 // (t,) is the type of a tuple with only one field,
1302 let mut ts = vec![];
1303 let mut last_comma = false;
1304 while self.token != token::CloseDelim(token::Paren) {
1305 ts.push(try!(self.parse_ty_sum()));
1306 if self.check(&token::Comma) {
1315 try!(self.expect(&token::CloseDelim(token::Paren)));
1316 if ts.len() == 1 && !last_comma {
1317 TyParen(ts.into_iter().nth(0).unwrap())
1321 } else if self.check(&token::BinOp(token::Star)) {
1322 // STAR POINTER (bare pointer?)
1324 TyPtr(try!(self.parse_ptr()))
1325 } else if self.check(&token::OpenDelim(token::Bracket)) {
1327 try!(self.expect(&token::OpenDelim(token::Bracket)));
1328 let t = try!(self.parse_ty_sum());
1330 // Parse the `; e` in `[ i32; e ]`
1331 // where `e` is a const expression
1332 let t = match try!(self.maybe_parse_fixed_length_of_vec()) {
1334 Some(suffix) => TyFixedLengthVec(t, suffix)
1336 try!(self.expect(&token::CloseDelim(token::Bracket)));
1338 } else if self.check(&token::BinOp(token::And)) ||
1339 self.token == token::AndAnd {
1341 try!(self.expect_and());
1342 try!(self.parse_borrowed_pointee())
1343 } else if self.check_keyword(keywords::For) {
1344 try!(self.parse_for_in_type())
1345 } else if self.token_is_bare_fn_keyword() {
1347 try!(self.parse_ty_bare_fn(Vec::new()))
1348 } else if try!(self.eat_keyword_noexpect(keywords::Typeof)) {
1350 // In order to not be ambiguous, the type must be surrounded by parens.
1351 try!(self.expect(&token::OpenDelim(token::Paren)));
1352 let e = try!(self.parse_expr());
1353 try!(self.expect(&token::CloseDelim(token::Paren)));
1355 } else if try!(self.eat_lt()) {
1358 try!(self.parse_qualified_path(NoTypesAllowed));
1360 TyPath(Some(qself), path)
1361 } else if self.check(&token::ModSep) ||
1362 self.token.is_ident() ||
1363 self.token.is_path() {
1364 let path = try!(self.parse_path(LifetimeAndTypesWithoutColons));
1365 if self.check(&token::Not) {
1368 let delim = try!(self.expect_open_delim());
1369 let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
1371 |p| p.parse_token_tree()));
1372 let hi = self.span.hi;
1373 TyMac(spanned(lo, hi, Mac_ { path: path, tts: tts, ctxt: EMPTY_CTXT }))
1378 } else if try!(self.eat(&token::Underscore) ){
1379 // TYPE TO BE INFERRED
1382 let this_token_str = self.this_token_to_string();
1383 let msg = format!("expected type, found `{}`", this_token_str);
1384 return Err(self.fatal(&msg[..]));
1387 let sp = mk_sp(lo, self.last_span.hi);
1388 Ok(P(Ty {id: ast::DUMMY_NODE_ID, node: t, span: sp}))
1391 pub fn parse_borrowed_pointee(&mut self) -> PResult<'a, Ty_> {
1392 // look for `&'lt` or `&'foo ` and interpret `foo` as the region name:
1393 let opt_lifetime = try!(self.parse_opt_lifetime());
1395 let mt = try!(self.parse_mt());
1396 return Ok(TyRptr(opt_lifetime, mt));
1399 pub fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1400 let mutbl = if try!(self.eat_keyword(keywords::Mut) ){
1402 } else if try!(self.eat_keyword(keywords::Const) ){
1405 let span = self.last_span;
1407 "bare raw pointers are no longer allowed, you should \
1408 likely use `*mut T`, but otherwise `*T` is now \
1409 known as `*const T`");
1412 let t = try!(self.parse_ty());
1413 Ok(MutTy { ty: t, mutbl: mutbl })
1416 pub fn is_named_argument(&mut self) -> bool {
1417 let offset = match self.token {
1418 token::BinOp(token::And) => 1,
1420 _ if self.token.is_keyword(keywords::Mut) => 1,
1424 debug!("parser is_named_argument offset:{}", offset);
1427 is_plain_ident_or_underscore(&self.token)
1428 && self.look_ahead(1, |t| *t == token::Colon)
1430 self.look_ahead(offset, |t| is_plain_ident_or_underscore(t))
1431 && self.look_ahead(offset + 1, |t| *t == token::Colon)
1435 /// This version of parse arg doesn't necessarily require
1436 /// identifier names.
1437 pub fn parse_arg_general(&mut self, require_name: bool) -> PResult<'a, Arg> {
1438 maybe_whole!(no_clone self, NtArg);
1440 let pat = if require_name || self.is_named_argument() {
1441 debug!("parse_arg_general parse_pat (require_name:{})",
1443 let pat = try!(self.parse_pat());
1445 try!(self.expect(&token::Colon));
1448 debug!("parse_arg_general ident_to_pat");
1449 ast_util::ident_to_pat(ast::DUMMY_NODE_ID,
1451 special_idents::invalid)
1454 let t = try!(self.parse_ty_sum());
1459 id: ast::DUMMY_NODE_ID,
1463 /// Parse a single function argument
1464 pub fn parse_arg(&mut self) -> PResult<'a, Arg> {
1465 self.parse_arg_general(true)
1468 /// Parse an argument in a lambda header e.g. |arg, arg|
1469 pub fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1470 let pat = try!(self.parse_pat());
1471 let t = if try!(self.eat(&token::Colon) ){
1472 try!(self.parse_ty_sum())
1475 id: ast::DUMMY_NODE_ID,
1477 span: mk_sp(self.span.lo, self.span.hi),
1483 id: ast::DUMMY_NODE_ID
1487 pub fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1488 if self.check(&token::Semi) {
1490 Ok(Some(try!(self.parse_expr())))
1496 /// Matches token_lit = LIT_INTEGER | ...
1497 pub fn lit_from_token(&self, tok: &token::Token) -> PResult<'a, Lit_> {
1499 token::Interpolated(token::NtExpr(ref v)) => {
1501 ExprLit(ref lit) => { Ok(lit.node.clone()) }
1502 _ => { return Err(self.unexpected_last(tok)); }
1505 token::Literal(lit, suf) => {
1506 let (suffix_illegal, out) = match lit {
1507 token::Byte(i) => (true, LitByte(parse::byte_lit(&i.as_str()).0)),
1508 token::Char(i) => (true, LitChar(parse::char_lit(&i.as_str()).0)),
1510 // there are some valid suffixes for integer and
1511 // float literals, so all the handling is done
1513 token::Integer(s) => {
1514 (false, parse::integer_lit(&s.as_str(),
1515 suf.as_ref().map(|s| s.as_str()),
1516 &self.sess.span_diagnostic,
1519 token::Float(s) => {
1520 (false, parse::float_lit(&s.as_str(),
1521 suf.as_ref().map(|s| s.as_str()),
1522 &self.sess.span_diagnostic,
1528 LitStr(token::intern_and_get_ident(&parse::str_lit(&s.as_str())),
1531 token::StrRaw(s, n) => {
1534 token::intern_and_get_ident(&parse::raw_str_lit(&s.as_str())),
1537 token::ByteStr(i) =>
1538 (true, LitByteStr(parse::byte_str_lit(&i.as_str()))),
1539 token::ByteStrRaw(i, _) =>
1541 LitByteStr(Rc::new(i.to_string().into_bytes()))),
1545 let sp = self.last_span;
1546 self.expect_no_suffix(sp, &*format!("{} literal", lit.short_name()), suf)
1551 _ => { return Err(self.unexpected_last(tok)); }
1555 /// Matches lit = true | false | token_lit
1556 pub fn parse_lit(&mut self) -> PResult<'a, Lit> {
1557 let lo = self.span.lo;
1558 let lit = if try!(self.eat_keyword(keywords::True) ){
1560 } else if try!(self.eat_keyword(keywords::False) ){
1563 let token = try!(self.bump_and_get());
1564 let lit = try!(self.lit_from_token(&token));
1567 Ok(codemap::Spanned { node: lit, span: mk_sp(lo, self.last_span.hi) })
1570 /// matches '-' lit | lit
1571 pub fn parse_pat_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1572 let minus_lo = self.span.lo;
1573 let minus_present = try!(self.eat(&token::BinOp(token::Minus)));
1574 let lo = self.span.lo;
1575 let literal = P(try!(self.parse_lit()));
1576 let hi = self.last_span.hi;
1577 let expr = self.mk_expr(lo, hi, ExprLit(literal), None);
1580 let minus_hi = self.last_span.hi;
1581 let unary = self.mk_unary(UnNeg, expr);
1582 Ok(self.mk_expr(minus_lo, minus_hi, unary, None))
1588 /// Parses qualified path.
1590 /// Assumes that the leading `<` has been parsed already.
1592 /// Qualifed paths are a part of the universal function call
1595 /// `qualified_path = <type [as trait_ref]>::path`
1597 /// See `parse_path` for `mode` meaning.
1602 /// `<T as U>::F::a::<S>`
1603 pub fn parse_qualified_path(&mut self, mode: PathParsingMode)
1604 -> PResult<'a, (QSelf, ast::Path)> {
1605 let span = self.last_span;
1606 let self_type = try!(self.parse_ty_sum());
1607 let mut path = if try!(self.eat_keyword(keywords::As)) {
1608 try!(self.parse_path(LifetimeAndTypesWithoutColons))
1619 position: path.segments.len()
1622 try!(self.expect(&token::Gt));
1623 try!(self.expect(&token::ModSep));
1625 let segments = match mode {
1626 LifetimeAndTypesWithoutColons => {
1627 try!(self.parse_path_segments_without_colons())
1629 LifetimeAndTypesWithColons => {
1630 try!(self.parse_path_segments_with_colons())
1633 try!(self.parse_path_segments_without_types())
1636 path.segments.extend(segments);
1638 path.span.hi = self.last_span.hi;
1643 /// Parses a path and optional type parameter bounds, depending on the
1644 /// mode. The `mode` parameter determines whether lifetimes, types, and/or
1645 /// bounds are permitted and whether `::` must precede type parameter
1647 pub fn parse_path(&mut self, mode: PathParsingMode) -> PResult<'a, ast::Path> {
1648 // Check for a whole path...
1649 let found = match self.token {
1650 token::Interpolated(token::NtPath(_)) => Some(try!(self.bump_and_get())),
1653 if let Some(token::Interpolated(token::NtPath(path))) = found {
1657 let lo = self.span.lo;
1658 let is_global = try!(self.eat(&token::ModSep));
1660 // Parse any number of segments and bound sets. A segment is an
1661 // identifier followed by an optional lifetime and a set of types.
1662 // A bound set is a set of type parameter bounds.
1663 let segments = match mode {
1664 LifetimeAndTypesWithoutColons => {
1665 try!(self.parse_path_segments_without_colons())
1667 LifetimeAndTypesWithColons => {
1668 try!(self.parse_path_segments_with_colons())
1671 try!(self.parse_path_segments_without_types())
1675 // Assemble the span.
1676 let span = mk_sp(lo, self.last_span.hi);
1678 // Assemble the result.
1687 /// - `a::b<T,U>::c<V,W>`
1688 /// - `a::b<T,U>::c(V) -> W`
1689 /// - `a::b<T,U>::c(V)`
1690 pub fn parse_path_segments_without_colons(&mut self) -> PResult<'a, Vec<ast::PathSegment>> {
1691 let mut segments = Vec::new();
1693 // First, parse an identifier.
1694 let identifier = try!(self.parse_ident_or_self_type());
1696 // Parse types, optionally.
1697 let parameters = if try!(self.eat_lt() ){
1698 let (lifetimes, types, bindings) = try!(self.parse_generic_values_after_lt());
1700 ast::PathParameters::AngleBracketed(ast::AngleBracketedParameterData {
1701 lifetimes: lifetimes,
1702 types: P::from_vec(types),
1703 bindings: P::from_vec(bindings),
1705 } else if try!(self.eat(&token::OpenDelim(token::Paren)) ){
1706 let lo = self.last_span.lo;
1708 let inputs = try!(self.parse_seq_to_end(
1709 &token::CloseDelim(token::Paren),
1710 seq_sep_trailing_allowed(token::Comma),
1711 |p| p.parse_ty_sum()));
1713 let output_ty = if try!(self.eat(&token::RArrow) ){
1714 Some(try!(self.parse_ty()))
1719 let hi = self.last_span.hi;
1721 ast::PathParameters::Parenthesized(ast::ParenthesizedParameterData {
1722 span: mk_sp(lo, hi),
1727 ast::PathParameters::none()
1730 // Assemble and push the result.
1731 segments.push(ast::PathSegment { identifier: identifier,
1732 parameters: parameters });
1734 // Continue only if we see a `::`
1735 if !try!(self.eat(&token::ModSep) ){
1736 return Ok(segments);
1742 /// - `a::b::<T,U>::c`
1743 pub fn parse_path_segments_with_colons(&mut self) -> PResult<'a, Vec<ast::PathSegment>> {
1744 let mut segments = Vec::new();
1746 // First, parse an identifier.
1747 let identifier = try!(self.parse_ident_or_self_type());
1749 // If we do not see a `::`, stop.
1750 if !try!(self.eat(&token::ModSep) ){
1751 segments.push(ast::PathSegment {
1752 identifier: identifier,
1753 parameters: ast::PathParameters::none()
1755 return Ok(segments);
1758 // Check for a type segment.
1759 if try!(self.eat_lt() ){
1760 // Consumed `a::b::<`, go look for types
1761 let (lifetimes, types, bindings) = try!(self.parse_generic_values_after_lt());
1762 let parameters = ast::AngleBracketedParameterData {
1763 lifetimes: lifetimes,
1764 types: P::from_vec(types),
1765 bindings: P::from_vec(bindings),
1767 segments.push(ast::PathSegment {
1768 identifier: identifier,
1769 parameters: ast::PathParameters::AngleBracketed(parameters),
1772 // Consumed `a::b::<T,U>`, check for `::` before proceeding
1773 if !try!(self.eat(&token::ModSep) ){
1774 return Ok(segments);
1777 // Consumed `a::`, go look for `b`
1778 segments.push(ast::PathSegment {
1779 identifier: identifier,
1780 parameters: ast::PathParameters::none(),
1789 pub fn parse_path_segments_without_types(&mut self) -> PResult<'a, Vec<ast::PathSegment>> {
1790 let mut segments = Vec::new();
1792 // First, parse an identifier.
1793 let identifier = try!(self.parse_ident_or_self_type());
1795 // Assemble and push the result.
1796 segments.push(ast::PathSegment {
1797 identifier: identifier,
1798 parameters: ast::PathParameters::none()
1801 // If we do not see a `::`, stop.
1802 if !try!(self.eat(&token::ModSep) ){
1803 return Ok(segments);
1808 /// parses 0 or 1 lifetime
1809 pub fn parse_opt_lifetime(&mut self) -> PResult<'a, Option<ast::Lifetime>> {
1811 token::Lifetime(..) => {
1812 Ok(Some(try!(self.parse_lifetime())))
1820 /// Parses a single lifetime
1821 /// Matches lifetime = LIFETIME
1822 pub fn parse_lifetime(&mut self) -> PResult<'a, ast::Lifetime> {
1824 token::Lifetime(i) => {
1825 let span = self.span;
1827 return Ok(ast::Lifetime {
1828 id: ast::DUMMY_NODE_ID,
1834 return Err(self.fatal("expected a lifetime name"));
1839 /// Parses `lifetime_defs = [ lifetime_defs { ',' lifetime_defs } ]` where `lifetime_def =
1840 /// lifetime [':' lifetimes]`
1841 pub fn parse_lifetime_defs(&mut self) -> PResult<'a, Vec<ast::LifetimeDef>> {
1843 let mut res = Vec::new();
1846 token::Lifetime(_) => {
1847 let lifetime = try!(self.parse_lifetime());
1849 if try!(self.eat(&token::Colon) ){
1850 try!(self.parse_lifetimes(token::BinOp(token::Plus)))
1854 res.push(ast::LifetimeDef { lifetime: lifetime,
1864 token::Comma => { try!(self.bump());}
1865 token::Gt => { return Ok(res); }
1866 token::BinOp(token::Shr) => { return Ok(res); }
1868 let this_token_str = self.this_token_to_string();
1869 let msg = format!("expected `,` or `>` after lifetime \
1872 return Err(self.fatal(&msg[..]));
1878 /// matches lifetimes = ( lifetime ) | ( lifetime , lifetimes ) actually, it matches the empty
1879 /// one too, but putting that in there messes up the grammar....
1881 /// Parses zero or more comma separated lifetimes. Expects each lifetime to be followed by
1882 /// either a comma or `>`. Used when parsing type parameter lists, where we expect something
1883 /// like `<'a, 'b, T>`.
1884 pub fn parse_lifetimes(&mut self, sep: token::Token) -> PResult<'a, Vec<ast::Lifetime>> {
1886 let mut res = Vec::new();
1889 token::Lifetime(_) => {
1890 res.push(try!(self.parse_lifetime()));
1897 if self.token != sep {
1905 /// Parse mutability declaration (mut/const/imm)
1906 pub fn parse_mutability(&mut self) -> PResult<'a, Mutability> {
1907 if try!(self.eat_keyword(keywords::Mut) ){
1914 /// Parse ident COLON expr
1915 pub fn parse_field(&mut self) -> PResult<'a, Field> {
1916 let lo = self.span.lo;
1917 let i = try!(self.parse_ident());
1918 let hi = self.last_span.hi;
1919 try!(self.expect(&token::Colon));
1920 let e = try!(self.parse_expr());
1922 ident: spanned(lo, hi, i),
1923 span: mk_sp(lo, e.span.hi),
1928 pub fn mk_expr(&mut self, lo: BytePos, hi: BytePos,
1929 node: Expr_, attrs: ThinAttributes) -> P<Expr> {
1931 id: ast::DUMMY_NODE_ID,
1933 span: mk_sp(lo, hi),
1938 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::Expr_ {
1939 ExprUnary(unop, expr)
1942 pub fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::Expr_ {
1943 ExprBinary(binop, lhs, rhs)
1946 pub fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::Expr_ {
1950 fn mk_method_call(&mut self,
1951 ident: ast::SpannedIdent,
1955 ExprMethodCall(ident, tps, args)
1958 pub fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::Expr_ {
1959 ExprIndex(expr, idx)
1962 pub fn mk_range(&mut self,
1963 start: Option<P<Expr>>,
1964 end: Option<P<Expr>>)
1966 ExprRange(start, end)
1969 pub fn mk_field(&mut self, expr: P<Expr>, ident: ast::SpannedIdent) -> ast::Expr_ {
1970 ExprField(expr, ident)
1973 pub fn mk_tup_field(&mut self, expr: P<Expr>, idx: codemap::Spanned<usize>) -> ast::Expr_ {
1974 ExprTupField(expr, idx)
1977 pub fn mk_assign_op(&mut self, binop: ast::BinOp,
1978 lhs: P<Expr>, rhs: P<Expr>) -> ast::Expr_ {
1979 ExprAssignOp(binop, lhs, rhs)
1982 pub fn mk_mac_expr(&mut self, lo: BytePos, hi: BytePos,
1983 m: Mac_, attrs: ThinAttributes) -> P<Expr> {
1985 id: ast::DUMMY_NODE_ID,
1986 node: ExprMac(codemap::Spanned {node: m, span: mk_sp(lo, hi)}),
1987 span: mk_sp(lo, hi),
1992 pub fn mk_lit_u32(&mut self, i: u32, attrs: ThinAttributes) -> P<Expr> {
1993 let span = &self.span;
1994 let lv_lit = P(codemap::Spanned {
1995 node: LitInt(i as u64, ast::UnsignedIntLit(TyU32)),
2000 id: ast::DUMMY_NODE_ID,
2001 node: ExprLit(lv_lit),
2007 fn expect_open_delim(&mut self) -> PResult<'a, token::DelimToken> {
2008 self.expected_tokens.push(TokenType::Token(token::Gt));
2010 token::OpenDelim(delim) => {
2014 _ => Err(self.fatal("expected open delimiter")),
2018 /// At the bottom (top?) of the precedence hierarchy,
2019 /// parse things like parenthesized exprs,
2020 /// macros, return, etc.
2022 /// NB: This does not parse outer attributes,
2023 /// and is private because it only works
2024 /// correctly if called from parse_dot_or_call_expr().
2025 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2026 maybe_whole_expr!(self);
2028 // Outer attributes are already parsed and will be
2029 // added to the return value after the fact.
2031 // Therefore, prevent sub-parser from parsing
2032 // attributes by giving them a empty "already parsed" list.
2033 let mut attrs = None;
2035 let lo = self.span.lo;
2036 let mut hi = self.span.hi;
2040 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2042 token::OpenDelim(token::Paren) => {
2045 let attrs = try!(self.parse_inner_attributes())
2049 // (e) is parenthesized e
2050 // (e,) is a tuple with only one field, e
2051 let mut es = vec![];
2052 let mut trailing_comma = false;
2053 while self.token != token::CloseDelim(token::Paren) {
2054 es.push(try!(self.parse_expr()));
2055 try!(self.commit_expr(&**es.last().unwrap(), &[],
2056 &[token::Comma, token::CloseDelim(token::Paren)]));
2057 if self.check(&token::Comma) {
2058 trailing_comma = true;
2062 trailing_comma = false;
2068 hi = self.last_span.hi;
2069 return if es.len() == 1 && !trailing_comma {
2070 Ok(self.mk_expr(lo, hi, ExprParen(es.into_iter().nth(0).unwrap()), attrs))
2072 Ok(self.mk_expr(lo, hi, ExprTup(es), attrs))
2075 token::OpenDelim(token::Brace) => {
2076 return self.parse_block_expr(lo, DefaultBlock, attrs);
2078 token::BinOp(token::Or) | token::OrOr => {
2079 let lo = self.span.lo;
2080 return self.parse_lambda_expr(lo, CaptureByRef, attrs);
2082 token::Ident(id @ ast::Ident {
2083 name: token::SELF_KEYWORD_NAME,
2085 }, token::Plain) => {
2087 let path = ast_util::ident_to_path(mk_sp(lo, hi), id);
2088 ex = ExprPath(None, path);
2089 hi = self.last_span.hi;
2091 token::OpenDelim(token::Bracket) => {
2094 let inner_attrs = try!(self.parse_inner_attributes())
2096 attrs.update(|attrs| attrs.append(inner_attrs));
2098 if self.check(&token::CloseDelim(token::Bracket)) {
2101 ex = ExprVec(Vec::new());
2104 let first_expr = try!(self.parse_expr());
2105 if self.check(&token::Semi) {
2106 // Repeating array syntax: [ 0; 512 ]
2108 let count = try!(self.parse_expr());
2109 try!(self.expect(&token::CloseDelim(token::Bracket)));
2110 ex = ExprRepeat(first_expr, count);
2111 } else if self.check(&token::Comma) {
2112 // Vector with two or more elements.
2114 let remaining_exprs = try!(self.parse_seq_to_end(
2115 &token::CloseDelim(token::Bracket),
2116 seq_sep_trailing_allowed(token::Comma),
2117 |p| Ok(try!(p.parse_expr()))
2119 let mut exprs = vec!(first_expr);
2120 exprs.extend(remaining_exprs);
2121 ex = ExprVec(exprs);
2123 // Vector with one element.
2124 try!(self.expect(&token::CloseDelim(token::Bracket)));
2125 ex = ExprVec(vec!(first_expr));
2128 hi = self.last_span.hi;
2131 if try!(self.eat_lt()){
2133 try!(self.parse_qualified_path(LifetimeAndTypesWithColons));
2135 return Ok(self.mk_expr(lo, hi, ExprPath(Some(qself), path), attrs));
2137 if try!(self.eat_keyword(keywords::Move) ){
2138 let lo = self.last_span.lo;
2139 return self.parse_lambda_expr(lo, CaptureByValue, attrs);
2141 if try!(self.eat_keyword(keywords::If)) {
2142 return self.parse_if_expr(attrs);
2144 if try!(self.eat_keyword(keywords::For) ){
2145 let lo = self.last_span.lo;
2146 return self.parse_for_expr(None, lo, attrs);
2148 if try!(self.eat_keyword(keywords::While) ){
2149 let lo = self.last_span.lo;
2150 return self.parse_while_expr(None, lo, attrs);
2152 if self.token.is_lifetime() {
2153 let lifetime = self.get_lifetime();
2154 let lo = self.span.lo;
2156 try!(self.expect(&token::Colon));
2157 if try!(self.eat_keyword(keywords::While) ){
2158 return self.parse_while_expr(Some(lifetime), lo, attrs)
2160 if try!(self.eat_keyword(keywords::For) ){
2161 return self.parse_for_expr(Some(lifetime), lo, attrs)
2163 if try!(self.eat_keyword(keywords::Loop) ){
2164 return self.parse_loop_expr(Some(lifetime), lo, attrs)
2166 return Err(self.fatal("expected `while`, `for`, or `loop` after a label"))
2168 if try!(self.eat_keyword(keywords::Loop) ){
2169 let lo = self.last_span.lo;
2170 return self.parse_loop_expr(None, lo, attrs);
2172 if try!(self.eat_keyword(keywords::Continue) ){
2173 let ex = if self.token.is_lifetime() {
2174 let ex = ExprAgain(Some(Spanned{
2175 node: self.get_lifetime(),
2183 let hi = self.last_span.hi;
2184 return Ok(self.mk_expr(lo, hi, ex, attrs));
2186 if try!(self.eat_keyword(keywords::Match) ){
2187 return self.parse_match_expr(attrs);
2189 if try!(self.eat_keyword(keywords::Unsafe) ){
2190 return self.parse_block_expr(
2192 UnsafeBlock(ast::UserProvided),
2195 if try!(self.eat_keyword(keywords::Return) ){
2196 if self.token.can_begin_expr() {
2197 let e = try!(self.parse_expr());
2199 ex = ExprRet(Some(e));
2203 } else if try!(self.eat_keyword(keywords::Break) ){
2204 if self.token.is_lifetime() {
2205 ex = ExprBreak(Some(Spanned {
2206 node: self.get_lifetime(),
2211 ex = ExprBreak(None);
2213 hi = self.last_span.hi;
2214 } else if self.check(&token::ModSep) ||
2215 self.token.is_ident() &&
2216 !self.check_keyword(keywords::True) &&
2217 !self.check_keyword(keywords::False) {
2219 try!(self.parse_path(LifetimeAndTypesWithColons));
2221 // `!`, as an operator, is prefix, so we know this isn't that
2222 if self.check(&token::Not) {
2223 // MACRO INVOCATION expression
2226 let delim = try!(self.expect_open_delim());
2227 let tts = try!(self.parse_seq_to_end(
2228 &token::CloseDelim(delim),
2230 |p| p.parse_token_tree()));
2231 let hi = self.last_span.hi;
2233 return Ok(self.mk_mac_expr(lo,
2235 Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT },
2238 if self.check(&token::OpenDelim(token::Brace)) {
2239 // This is a struct literal, unless we're prohibited
2240 // from parsing struct literals here.
2241 let prohibited = self.restrictions.contains(
2242 Restrictions::RESTRICTION_NO_STRUCT_LITERAL
2245 // It's a struct literal.
2247 let mut fields = Vec::new();
2248 let mut base = None;
2250 let attrs = attrs.append(
2251 try!(self.parse_inner_attributes())
2252 .into_thin_attrs());
2254 while self.token != token::CloseDelim(token::Brace) {
2255 if try!(self.eat(&token::DotDot) ){
2256 base = Some(try!(self.parse_expr()));
2260 fields.push(try!(self.parse_field()));
2261 try!(self.commit_expr(&*fields.last().unwrap().expr,
2263 &[token::CloseDelim(token::Brace)]));
2267 try!(self.expect(&token::CloseDelim(token::Brace)));
2268 ex = ExprStruct(pth, fields, base);
2269 return Ok(self.mk_expr(lo, hi, ex, attrs));
2274 ex = ExprPath(None, pth);
2276 // other literal expression
2277 let lit = try!(self.parse_lit());
2279 ex = ExprLit(P(lit));
2284 return Ok(self.mk_expr(lo, hi, ex, attrs));
2287 fn parse_or_use_outer_attributes(&mut self,
2288 already_parsed_attrs: Option<ThinAttributes>)
2289 -> PResult<'a, ThinAttributes> {
2290 if let Some(attrs) = already_parsed_attrs {
2293 self.parse_outer_attributes().map(|a| a.into_thin_attrs())
2297 /// Parse a block or unsafe block
2298 pub fn parse_block_expr(&mut self, lo: BytePos, blk_mode: BlockCheckMode,
2299 attrs: ThinAttributes)
2300 -> PResult<'a, P<Expr>> {
2302 let outer_attrs = attrs;
2303 try!(self.expect(&token::OpenDelim(token::Brace)));
2305 let inner_attrs = try!(self.parse_inner_attributes()).into_thin_attrs();
2306 let attrs = outer_attrs.append(inner_attrs);
2308 let blk = try!(self.parse_block_tail(lo, blk_mode));
2309 return Ok(self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk), attrs));
2312 /// parse a.b or a(13) or a[4] or just a
2313 pub fn parse_dot_or_call_expr(&mut self,
2314 already_parsed_attrs: Option<ThinAttributes>)
2315 -> PResult<'a, P<Expr>> {
2316 let attrs = try!(self.parse_or_use_outer_attributes(already_parsed_attrs));
2318 let b = try!(self.parse_bottom_expr());
2319 self.parse_dot_or_call_expr_with(b, attrs)
2322 pub fn parse_dot_or_call_expr_with(&mut self,
2324 attrs: ThinAttributes)
2325 -> PResult<'a, P<Expr>> {
2326 // Stitch the list of outer attributes onto the return value.
2327 // A little bit ugly, but the best way given the current code
2329 self.parse_dot_or_call_expr_with_(e0)
2331 expr.map(|mut expr| {
2332 expr.attrs.update(|a| a.prepend(attrs));
2334 ExprIf(..) | ExprIfLet(..) => {
2335 if !expr.attrs.as_attr_slice().is_empty() {
2336 // Just point to the first attribute in there...
2337 let span = expr.attrs.as_attr_slice()[0].span;
2340 "attributes are not yet allowed on `if` \
2351 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>) -> PResult<'a, P<Expr>> {
2357 if try!(self.eat(&token::Dot) ){
2359 token::Ident(i, _) => {
2360 let dot = self.last_span.hi;
2363 let (_, tys, bindings) = if try!(self.eat(&token::ModSep) ){
2364 try!(self.expect_lt());
2365 try!(self.parse_generic_values_after_lt())
2367 (Vec::new(), Vec::new(), Vec::new())
2370 if !bindings.is_empty() {
2371 let last_span = self.last_span;
2372 self.span_err(last_span, "type bindings are only permitted on trait paths");
2375 // expr.f() method call
2377 token::OpenDelim(token::Paren) => {
2378 let mut es = try!(self.parse_unspanned_seq(
2379 &token::OpenDelim(token::Paren),
2380 &token::CloseDelim(token::Paren),
2381 seq_sep_trailing_allowed(token::Comma),
2382 |p| Ok(try!(p.parse_expr()))
2384 hi = self.last_span.hi;
2387 let id = spanned(dot, hi, i);
2388 let nd = self.mk_method_call(id, tys, es);
2389 e = self.mk_expr(lo, hi, nd, None);
2392 if !tys.is_empty() {
2393 let last_span = self.last_span;
2394 self.span_err(last_span,
2395 "field expressions may not \
2396 have type parameters");
2399 let id = spanned(dot, hi, i);
2400 let field = self.mk_field(e, id);
2401 e = self.mk_expr(lo, hi, field, None);
2405 token::Literal(token::Integer(n), suf) => {
2408 // A tuple index may not have a suffix
2409 self.expect_no_suffix(sp, "tuple index", suf);
2411 let dot = self.last_span.hi;
2415 let index = n.as_str().parse::<usize>().ok();
2418 let id = spanned(dot, hi, n);
2419 let field = self.mk_tup_field(e, id);
2420 e = self.mk_expr(lo, hi, field, None);
2423 let last_span = self.last_span;
2424 self.span_err(last_span, "invalid tuple or tuple struct index");
2428 token::Literal(token::Float(n), _suf) => {
2430 let last_span = self.last_span;
2431 let fstr = n.as_str();
2432 let mut err = self.diagnostic().struct_span_err(last_span,
2433 &format!("unexpected token: `{}`", n.as_str()));
2434 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2435 let float = match fstr.parse::<f64>().ok() {
2439 err.fileline_help(last_span,
2440 &format!("try parenthesizing the first index; e.g., `(foo.{}){}`",
2441 float.trunc() as usize,
2442 format!(".{}", fstr.splitn(2, ".").last().unwrap())));
2445 self.abort_if_errors();
2448 _ => return Err(self.unexpected())
2452 if self.expr_is_complete(&*e) { break; }
2455 token::OpenDelim(token::Paren) => {
2456 let es = try!(self.parse_unspanned_seq(
2457 &token::OpenDelim(token::Paren),
2458 &token::CloseDelim(token::Paren),
2459 seq_sep_trailing_allowed(token::Comma),
2460 |p| Ok(try!(p.parse_expr()))
2462 hi = self.last_span.hi;
2464 let nd = self.mk_call(e, es);
2465 e = self.mk_expr(lo, hi, nd, None);
2469 // Could be either an index expression or a slicing expression.
2470 token::OpenDelim(token::Bracket) => {
2472 let ix = try!(self.parse_expr());
2474 try!(self.commit_expr_expecting(&*ix, token::CloseDelim(token::Bracket)));
2475 let index = self.mk_index(e, ix);
2476 e = self.mk_expr(lo, hi, index, None)
2484 // Parse unquoted tokens after a `$` in a token tree
2485 fn parse_unquoted(&mut self) -> PResult<'a, TokenTree> {
2486 let mut sp = self.span;
2487 let (name, namep) = match self.token {
2491 if self.token == token::OpenDelim(token::Paren) {
2492 let Spanned { node: seq, span: seq_span } = try!(self.parse_seq(
2493 &token::OpenDelim(token::Paren),
2494 &token::CloseDelim(token::Paren),
2496 |p| p.parse_token_tree()
2498 let (sep, repeat) = try!(self.parse_sep_and_kleene_op());
2499 let name_num = macro_parser::count_names(&seq);
2500 return Ok(TokenTree::Sequence(mk_sp(sp.lo, seq_span.hi),
2501 Rc::new(SequenceRepetition {
2505 num_captures: name_num
2507 } else if self.token.is_keyword_allow_following_colon(keywords::Crate) {
2509 return Ok(TokenTree::Token(sp, SpecialVarNt(SpecialMacroVar::CrateMacroVar)));
2511 sp = mk_sp(sp.lo, self.span.hi);
2512 let namep = match self.token { token::Ident(_, p) => p, _ => token::Plain };
2513 let name = try!(self.parse_ident());
2517 token::SubstNt(name, namep) => {
2523 // continue by trying to parse the `:ident` after `$name`
2524 if self.token == token::Colon && self.look_ahead(1, |t| t.is_ident() &&
2525 !t.is_strict_keyword() &&
2526 !t.is_reserved_keyword()) {
2528 sp = mk_sp(sp.lo, self.span.hi);
2529 let kindp = match self.token { token::Ident(_, p) => p, _ => token::Plain };
2530 let nt_kind = try!(self.parse_ident());
2531 Ok(TokenTree::Token(sp, MatchNt(name, nt_kind, namep, kindp)))
2533 Ok(TokenTree::Token(sp, SubstNt(name, namep)))
2537 pub fn check_unknown_macro_variable(&mut self) -> PResult<'a, ()> {
2538 if self.quote_depth == 0 {
2540 token::SubstNt(name, _) =>
2541 return Err(self.fatal(&format!("unknown macro variable `{}`",
2549 /// Parse an optional separator followed by a Kleene-style
2550 /// repetition token (+ or *).
2551 pub fn parse_sep_and_kleene_op(&mut self)
2552 -> PResult<'a, (Option<token::Token>, ast::KleeneOp)> {
2553 fn parse_kleene_op<'a>(parser: &mut Parser<'a>) -> PResult<'a, Option<ast::KleeneOp>> {
2554 match parser.token {
2555 token::BinOp(token::Star) => {
2556 try!(parser.bump());
2557 Ok(Some(ast::ZeroOrMore))
2559 token::BinOp(token::Plus) => {
2560 try!(parser.bump());
2561 Ok(Some(ast::OneOrMore))
2567 match try!(parse_kleene_op(self)) {
2568 Some(kleene_op) => return Ok((None, kleene_op)),
2572 let separator = try!(self.bump_and_get());
2573 match try!(parse_kleene_op(self)) {
2574 Some(zerok) => Ok((Some(separator), zerok)),
2575 None => return Err(self.fatal("expected `*` or `+`"))
2579 /// parse a single token tree from the input.
2580 pub fn parse_token_tree(&mut self) -> PResult<'a, TokenTree> {
2581 // FIXME #6994: currently, this is too eager. It
2582 // parses token trees but also identifies TokenType::Sequence's
2583 // and token::SubstNt's; it's too early to know yet
2584 // whether something will be a nonterminal or a seq
2586 maybe_whole!(deref self, NtTT);
2588 // this is the fall-through for the 'match' below.
2589 // invariants: the current token is not a left-delimiter,
2590 // not an EOF, and not the desired right-delimiter (if
2591 // it were, parse_seq_to_before_end would have prevented
2592 // reaching this point.
2593 fn parse_non_delim_tt_tok<'b>(p: &mut Parser<'b>) -> PResult<'b, TokenTree> {
2594 maybe_whole!(deref p, NtTT);
2596 token::CloseDelim(_) => {
2597 let token_str = p.this_token_to_string();
2598 let mut err = p.fatal(
2599 &format!("incorrect close delimiter: `{}`", token_str));
2600 // This is a conservative error: only report the last unclosed delimiter. The
2601 // previous unclosed delimiters could actually be closed! The parser just hasn't
2602 // gotten to them yet.
2603 if let Some(&sp) = p.open_braces.last() {
2604 err.span_note(sp, "unclosed delimiter");
2608 /* we ought to allow different depths of unquotation */
2609 token::Dollar | token::SubstNt(..) if p.quote_depth > 0 => {
2613 Ok(TokenTree::Token(p.span, try!(p.bump_and_get())))
2620 let open_braces = self.open_braces.clone();
2621 let mut err: DiagnosticBuilder<'a> =
2622 self.fatal("this file contains an un-closed delimiter");
2623 for sp in &open_braces {
2624 err.span_help(*sp, "did you mean to close this delimiter?");
2628 token::OpenDelim(delim) => {
2629 // The span for beginning of the delimited section
2630 let pre_span = self.span;
2632 // Parse the open delimiter.
2633 self.open_braces.push(self.span);
2634 let open_span = self.span;
2637 // Parse the token trees within the delimiters
2638 let tts = try!(self.parse_seq_to_before_end(
2639 &token::CloseDelim(delim),
2641 |p| p.parse_token_tree()
2644 // Parse the close delimiter.
2645 let close_span = self.span;
2647 self.open_braces.pop().unwrap();
2649 // Expand to cover the entire delimited token tree
2650 let span = Span { hi: close_span.hi, ..pre_span };
2652 Ok(TokenTree::Delimited(span, Rc::new(Delimited {
2654 open_span: open_span,
2656 close_span: close_span,
2659 _ => parse_non_delim_tt_tok(self),
2663 // parse a stream of tokens into a list of TokenTree's,
2665 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2666 let mut tts = Vec::new();
2667 while self.token != token::Eof {
2668 tts.push(try!(self.parse_token_tree()));
2673 /// Parse a prefix-unary-operator expr
2674 pub fn parse_prefix_expr(&mut self,
2675 already_parsed_attrs: Option<ThinAttributes>)
2676 -> PResult<'a, P<Expr>> {
2677 let attrs = try!(self.parse_or_use_outer_attributes(already_parsed_attrs));
2678 let lo = self.span.lo;
2680 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2681 let ex = match self.token {
2684 let e = try!(self.parse_prefix_expr(None));
2686 self.mk_unary(UnNot, e)
2688 token::BinOp(token::Minus) => {
2690 let e = try!(self.parse_prefix_expr(None));
2692 self.mk_unary(UnNeg, e)
2694 token::BinOp(token::Star) => {
2696 let e = try!(self.parse_prefix_expr(None));
2698 self.mk_unary(UnDeref, e)
2700 token::BinOp(token::And) | token::AndAnd => {
2701 try!(self.expect_and());
2702 let m = try!(self.parse_mutability());
2703 let e = try!(self.parse_prefix_expr(None));
2707 token::Ident(..) if self.token.is_keyword(keywords::In) => {
2709 let place = try!(self.parse_expr_res(
2710 Restrictions::RESTRICTION_NO_STRUCT_LITERAL,
2713 let blk = try!(self.parse_block());
2714 let span = blk.span;
2716 let blk_expr = self.mk_expr(span.lo, span.hi, ExprBlock(blk),
2718 ExprInPlace(place, blk_expr)
2720 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
2722 let subexpression = try!(self.parse_prefix_expr(None));
2723 hi = subexpression.span.hi;
2724 ExprBox(subexpression)
2726 _ => return self.parse_dot_or_call_expr(Some(attrs))
2728 return Ok(self.mk_expr(lo, hi, ex, attrs));
2731 /// Parse an associative expression
2733 /// This parses an expression accounting for associativity and precedence of the operators in
2735 pub fn parse_assoc_expr(&mut self,
2736 already_parsed_attrs: Option<ThinAttributes>)
2737 -> PResult<'a, P<Expr>> {
2738 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
2741 /// Parse an associative expression with operators of at least `min_prec` precedence
2742 pub fn parse_assoc_expr_with(&mut self,
2745 -> PResult<'a, P<Expr>> {
2746 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
2749 let attrs = match lhs {
2750 LhsExpr::AttributesParsed(attrs) => Some(attrs),
2753 if self.token == token::DotDot {
2754 return self.parse_prefix_range_expr(attrs);
2756 try!(self.parse_prefix_expr(attrs))
2759 if self.expr_is_complete(&*lhs) {
2760 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
2763 self.expected_tokens.push(TokenType::Operator);
2764 while let Some(op) = AssocOp::from_token(&self.token) {
2765 let cur_op_span = self.span;
2766 let restrictions = if op.is_assign_like() {
2767 self.restrictions & Restrictions::RESTRICTION_NO_STRUCT_LITERAL
2771 if op.precedence() < min_prec {
2775 if op.is_comparison() {
2776 self.check_no_chained_comparison(&*lhs, &op);
2779 if op == AssocOp::As {
2780 let rhs = try!(self.parse_ty());
2781 lhs = self.mk_expr(lhs.span.lo, rhs.span.hi,
2782 ExprCast(lhs, rhs), None);
2784 } else if op == AssocOp::Colon {
2785 let rhs = try!(self.parse_ty());
2786 lhs = self.mk_expr(lhs.span.lo, rhs.span.hi,
2787 ExprType(lhs, rhs), None);
2789 } else if op == AssocOp::DotDot {
2790 // If we didn’t have to handle `x..`, it would be pretty easy to generalise
2791 // it to the Fixity::None code.
2793 // We have 2 alternatives here: `x..y` and `x..` The other two variants are
2794 // handled with `parse_prefix_range_expr` call above.
2795 let rhs = if self.is_at_start_of_range_notation_rhs() {
2796 let rhs = self.parse_assoc_expr_with(op.precedence() + 1,
2797 LhsExpr::NotYetParsed);
2808 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
2813 let r = self.mk_range(Some(lhs), rhs);
2814 lhs = self.mk_expr(lhs_span.lo, rhs_span.hi, r, None);
2818 let rhs = try!(match op.fixity() {
2819 Fixity::Right => self.with_res(
2820 restrictions - Restrictions::RESTRICTION_STMT_EXPR,
2822 this.parse_assoc_expr_with(op.precedence(),
2823 LhsExpr::NotYetParsed)
2825 Fixity::Left => self.with_res(
2826 restrictions - Restrictions::RESTRICTION_STMT_EXPR,
2828 this.parse_assoc_expr_with(op.precedence() + 1,
2829 LhsExpr::NotYetParsed)
2831 // We currently have no non-associative operators that are not handled above by
2832 // the special cases. The code is here only for future convenience.
2833 Fixity::None => self.with_res(
2834 restrictions - Restrictions::RESTRICTION_STMT_EXPR,
2836 this.parse_assoc_expr_with(op.precedence() + 1,
2837 LhsExpr::NotYetParsed)
2842 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
2843 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
2844 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
2845 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
2846 AssocOp::Greater | AssocOp::GreaterEqual => {
2847 let ast_op = op.to_ast_binop().unwrap();
2848 let (lhs_span, rhs_span) = (lhs.span, rhs.span);
2849 let binary = self.mk_binary(codemap::respan(cur_op_span, ast_op), lhs, rhs);
2850 self.mk_expr(lhs_span.lo, rhs_span.hi, binary, None)
2853 self.mk_expr(lhs.span.lo, rhs.span.hi, ExprAssign(lhs, rhs), None),
2855 self.mk_expr(lhs.span.lo, rhs.span.hi, ExprInPlace(lhs, rhs), None),
2856 AssocOp::AssignOp(k) => {
2858 token::Plus => BiAdd,
2859 token::Minus => BiSub,
2860 token::Star => BiMul,
2861 token::Slash => BiDiv,
2862 token::Percent => BiRem,
2863 token::Caret => BiBitXor,
2864 token::And => BiBitAnd,
2865 token::Or => BiBitOr,
2866 token::Shl => BiShl,
2869 let (lhs_span, rhs_span) = (lhs.span, rhs.span);
2870 let aopexpr = self.mk_assign_op(codemap::respan(cur_op_span, aop), lhs, rhs);
2871 self.mk_expr(lhs_span.lo, rhs_span.hi, aopexpr, None)
2873 AssocOp::As | AssocOp::Colon | AssocOp::DotDot => {
2874 self.bug("As, Colon or DotDot branch reached")
2878 if op.fixity() == Fixity::None { break }
2883 /// Produce an error if comparison operators are chained (RFC #558).
2884 /// We only need to check lhs, not rhs, because all comparison ops
2885 /// have same precedence and are left-associative
2886 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
2887 debug_assert!(outer_op.is_comparison());
2889 ExprBinary(op, _, _) if op.node.is_comparison() => {
2890 // respan to include both operators
2891 let op_span = mk_sp(op.span.lo, self.span.hi);
2892 let mut err = self.diagnostic().struct_span_err(op_span,
2893 "chained comparison operators require parentheses");
2894 if op.node == BiLt && *outer_op == AssocOp::Greater {
2895 err.fileline_help(op_span,
2896 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
2904 /// Parse prefix-forms of range notation: `..expr` and `..`
2905 fn parse_prefix_range_expr(&mut self,
2906 already_parsed_attrs: Option<ThinAttributes>)
2907 -> PResult<'a, P<Expr>> {
2908 debug_assert!(self.token == token::DotDot);
2909 let attrs = try!(self.parse_or_use_outer_attributes(already_parsed_attrs));
2910 let lo = self.span.lo;
2911 let mut hi = self.span.hi;
2913 let opt_end = if self.is_at_start_of_range_notation_rhs() {
2914 // RHS must be parsed with more associativity than DotDot.
2915 let next_prec = AssocOp::from_token(&token::DotDot).unwrap().precedence() + 1;
2916 Some(try!(self.parse_assoc_expr_with(next_prec,
2917 LhsExpr::NotYetParsed)
2925 let r = self.mk_range(None, opt_end);
2926 Ok(self.mk_expr(lo, hi, r, attrs))
2929 fn is_at_start_of_range_notation_rhs(&self) -> bool {
2930 if self.token.can_begin_expr() {
2931 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
2932 if self.token == token::OpenDelim(token::Brace) {
2933 return !self.restrictions.contains(Restrictions::RESTRICTION_NO_STRUCT_LITERAL);
2941 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
2942 pub fn parse_if_expr(&mut self, attrs: ThinAttributes) -> PResult<'a, P<Expr>> {
2943 if self.check_keyword(keywords::Let) {
2944 return self.parse_if_let_expr(attrs);
2946 let lo = self.last_span.lo;
2947 let cond = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
2948 let thn = try!(self.parse_block());
2949 let mut els: Option<P<Expr>> = None;
2950 let mut hi = thn.span.hi;
2951 if try!(self.eat_keyword(keywords::Else) ){
2952 let elexpr = try!(self.parse_else_expr());
2953 hi = elexpr.span.hi;
2956 Ok(self.mk_expr(lo, hi, ExprIf(cond, thn, els), attrs))
2959 /// Parse an 'if let' expression ('if' token already eaten)
2960 pub fn parse_if_let_expr(&mut self, attrs: ThinAttributes)
2961 -> PResult<'a, P<Expr>> {
2962 let lo = self.last_span.lo;
2963 try!(self.expect_keyword(keywords::Let));
2964 let pat = try!(self.parse_pat());
2965 try!(self.expect(&token::Eq));
2966 let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
2967 let thn = try!(self.parse_block());
2968 let (hi, els) = if try!(self.eat_keyword(keywords::Else) ){
2969 let expr = try!(self.parse_else_expr());
2970 (expr.span.hi, Some(expr))
2974 Ok(self.mk_expr(lo, hi, ExprIfLet(pat, expr, thn, els), attrs))
2978 pub fn parse_lambda_expr(&mut self, lo: BytePos,
2979 capture_clause: CaptureClause,
2980 attrs: ThinAttributes)
2981 -> PResult<'a, P<Expr>>
2983 let decl = try!(self.parse_fn_block_decl());
2984 let body = match decl.output {
2985 DefaultReturn(_) => {
2986 // If no explicit return type is given, parse any
2987 // expr and wrap it up in a dummy block:
2988 let body_expr = try!(self.parse_expr());
2990 id: ast::DUMMY_NODE_ID,
2992 span: body_expr.span,
2993 expr: Some(body_expr),
2994 rules: DefaultBlock,
2998 // If an explicit return type is given, require a
2999 // block to appear (RFC 968).
3000 try!(self.parse_block())
3007 ExprClosure(capture_clause, decl, body), attrs))
3010 // `else` token already eaten
3011 pub fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3012 if try!(self.eat_keyword(keywords::If) ){
3013 return self.parse_if_expr(None);
3015 let blk = try!(self.parse_block());
3016 return Ok(self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk), None));
3020 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3021 pub fn parse_for_expr(&mut self, opt_ident: Option<ast::Ident>,
3023 attrs: ThinAttributes) -> PResult<'a, P<Expr>> {
3024 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3026 let pat = try!(self.parse_pat());
3027 try!(self.expect_keyword(keywords::In));
3028 let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3029 let (iattrs, loop_block) = try!(self.parse_inner_attrs_and_block());
3030 let attrs = attrs.append(iattrs.into_thin_attrs());
3032 let hi = self.last_span.hi;
3034 Ok(self.mk_expr(span_lo, hi,
3035 ExprForLoop(pat, expr, loop_block, opt_ident),
3039 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3040 pub fn parse_while_expr(&mut self, opt_ident: Option<ast::Ident>,
3042 attrs: ThinAttributes) -> PResult<'a, P<Expr>> {
3043 if self.token.is_keyword(keywords::Let) {
3044 return self.parse_while_let_expr(opt_ident, span_lo, attrs);
3046 let cond = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3047 let (iattrs, body) = try!(self.parse_inner_attrs_and_block());
3048 let attrs = attrs.append(iattrs.into_thin_attrs());
3049 let hi = body.span.hi;
3050 return Ok(self.mk_expr(span_lo, hi, ExprWhile(cond, body, opt_ident),
3054 /// Parse a 'while let' expression ('while' token already eaten)
3055 pub fn parse_while_let_expr(&mut self, opt_ident: Option<ast::Ident>,
3057 attrs: ThinAttributes) -> PResult<'a, P<Expr>> {
3058 try!(self.expect_keyword(keywords::Let));
3059 let pat = try!(self.parse_pat());
3060 try!(self.expect(&token::Eq));
3061 let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3062 let (iattrs, body) = try!(self.parse_inner_attrs_and_block());
3063 let attrs = attrs.append(iattrs.into_thin_attrs());
3064 let hi = body.span.hi;
3065 return Ok(self.mk_expr(span_lo, hi, ExprWhileLet(pat, expr, body, opt_ident), attrs));
3068 // parse `loop {...}`, `loop` token already eaten
3069 pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::Ident>,
3071 attrs: ThinAttributes) -> PResult<'a, P<Expr>> {
3072 let (iattrs, body) = try!(self.parse_inner_attrs_and_block());
3073 let attrs = attrs.append(iattrs.into_thin_attrs());
3074 let hi = body.span.hi;
3075 Ok(self.mk_expr(span_lo, hi, ExprLoop(body, opt_ident), attrs))
3078 // `match` token already eaten
3079 fn parse_match_expr(&mut self, attrs: ThinAttributes) -> PResult<'a, P<Expr>> {
3080 let match_span = self.last_span;
3081 let lo = self.last_span.lo;
3082 let discriminant = try!(self.parse_expr_res(
3083 Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3084 if let Err(mut e) = self.commit_expr_expecting(&*discriminant,
3085 token::OpenDelim(token::Brace)) {
3086 if self.token == token::Token::Semi {
3087 e.span_note(match_span, "did you mean to remove this `match` keyword?");
3091 let attrs = attrs.append(
3092 try!(self.parse_inner_attributes()).into_thin_attrs());
3093 let mut arms: Vec<Arm> = Vec::new();
3094 while self.token != token::CloseDelim(token::Brace) {
3095 arms.push(try!(self.parse_arm()));
3097 let hi = self.span.hi;
3099 return Ok(self.mk_expr(lo, hi, ExprMatch(discriminant, arms), attrs));
3102 pub fn parse_arm(&mut self) -> PResult<'a, Arm> {
3103 maybe_whole!(no_clone self, NtArm);
3105 let attrs = try!(self.parse_outer_attributes());
3106 let pats = try!(self.parse_pats());
3107 let mut guard = None;
3108 if try!(self.eat_keyword(keywords::If) ){
3109 guard = Some(try!(self.parse_expr()));
3111 try!(self.expect(&token::FatArrow));
3112 let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_STMT_EXPR, None));
3115 !classify::expr_is_simple_block(&*expr)
3116 && self.token != token::CloseDelim(token::Brace);
3119 try!(self.commit_expr(&*expr, &[token::Comma], &[token::CloseDelim(token::Brace)]));
3121 try!(self.eat(&token::Comma));
3132 /// Parse an expression
3133 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3134 self.parse_expr_res(Restrictions::empty(), None)
3137 /// Evaluate the closure with restrictions in place.
3139 /// After the closure is evaluated, restrictions are reset.
3140 pub fn with_res<F>(&mut self, r: Restrictions, f: F) -> PResult<'a, P<Expr>>
3141 where F: FnOnce(&mut Self) -> PResult<'a, P<Expr>>
3143 let old = self.restrictions;
3144 self.restrictions = r;
3146 self.restrictions = old;
3151 /// Parse an expression, subject to the given restrictions
3152 pub fn parse_expr_res(&mut self, r: Restrictions,
3153 already_parsed_attrs: Option<ThinAttributes>)
3154 -> PResult<'a, P<Expr>> {
3155 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3158 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3159 fn parse_initializer(&mut self) -> PResult<'a, Option<P<Expr>>> {
3160 if self.check(&token::Eq) {
3162 Ok(Some(try!(self.parse_expr())))
3168 /// Parse patterns, separated by '|' s
3169 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3170 let mut pats = Vec::new();
3172 pats.push(try!(self.parse_pat()));
3173 if self.check(&token::BinOp(token::Or)) { try!(self.bump());}
3174 else { return Ok(pats); }
3178 fn parse_pat_tuple_elements(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3179 let mut fields = vec![];
3180 if !self.check(&token::CloseDelim(token::Paren)) {
3181 fields.push(try!(self.parse_pat()));
3182 if self.look_ahead(1, |t| *t != token::CloseDelim(token::Paren)) {
3183 while try!(self.eat(&token::Comma)) &&
3184 !self.check(&token::CloseDelim(token::Paren)) {
3185 fields.push(try!(self.parse_pat()));
3188 if fields.len() == 1 {
3189 try!(self.expect(&token::Comma));
3195 fn parse_pat_vec_elements(
3197 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3198 let mut before = Vec::new();
3199 let mut slice = None;
3200 let mut after = Vec::new();
3201 let mut first = true;
3202 let mut before_slice = true;
3204 while self.token != token::CloseDelim(token::Bracket) {
3208 try!(self.expect(&token::Comma));
3210 if self.token == token::CloseDelim(token::Bracket)
3211 && (before_slice || !after.is_empty()) {
3217 if self.check(&token::DotDot) {
3220 if self.check(&token::Comma) ||
3221 self.check(&token::CloseDelim(token::Bracket)) {
3222 slice = Some(P(ast::Pat {
3223 id: ast::DUMMY_NODE_ID,
3227 before_slice = false;
3233 let subpat = try!(self.parse_pat());
3234 if before_slice && self.check(&token::DotDot) {
3236 slice = Some(subpat);
3237 before_slice = false;
3238 } else if before_slice {
3239 before.push(subpat);
3245 Ok((before, slice, after))
3248 /// Parse the fields of a struct-like pattern
3249 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<codemap::Spanned<ast::FieldPat>> , bool)> {
3250 let mut fields = Vec::new();
3251 let mut etc = false;
3252 let mut first = true;
3253 while self.token != token::CloseDelim(token::Brace) {
3257 try!(self.expect(&token::Comma));
3258 // accept trailing commas
3259 if self.check(&token::CloseDelim(token::Brace)) { break }
3262 let lo = self.span.lo;
3265 if self.check(&token::DotDot) {
3267 if self.token != token::CloseDelim(token::Brace) {
3268 let token_str = self.this_token_to_string();
3269 return Err(self.fatal(&format!("expected `{}`, found `{}`", "}",
3276 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3277 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3278 // Parsing a pattern of the form "fieldname: pat"
3279 let fieldname = try!(self.parse_ident());
3281 let pat = try!(self.parse_pat());
3283 (pat, fieldname, false)
3285 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3286 let is_box = try!(self.eat_keyword(keywords::Box));
3287 let boxed_span_lo = self.span.lo;
3288 let is_ref = try!(self.eat_keyword(keywords::Ref));
3289 let is_mut = try!(self.eat_keyword(keywords::Mut));
3290 let fieldname = try!(self.parse_ident());
3291 hi = self.last_span.hi;
3293 let bind_type = match (is_ref, is_mut) {
3294 (true, true) => BindingMode::ByRef(MutMutable),
3295 (true, false) => BindingMode::ByRef(MutImmutable),
3296 (false, true) => BindingMode::ByValue(MutMutable),
3297 (false, false) => BindingMode::ByValue(MutImmutable),
3299 let fieldpath = codemap::Spanned{span:self.last_span, node:fieldname};
3300 let fieldpat = P(ast::Pat{
3301 id: ast::DUMMY_NODE_ID,
3302 node: PatIdent(bind_type, fieldpath, None),
3303 span: mk_sp(boxed_span_lo, hi),
3306 let subpat = if is_box {
3308 id: ast::DUMMY_NODE_ID,
3309 node: PatBox(fieldpat),
3310 span: mk_sp(lo, hi),
3315 (subpat, fieldname, true)
3318 fields.push(codemap::Spanned { span: mk_sp(lo, hi),
3319 node: ast::FieldPat { ident: fieldname,
3321 is_shorthand: is_shorthand }});
3323 return Ok((fields, etc));
3326 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
3327 if self.is_path_start() {
3328 let lo = self.span.lo;
3329 let (qself, path) = if try!(self.eat_lt()) {
3330 // Parse a qualified path
3332 try!(self.parse_qualified_path(NoTypesAllowed));
3335 // Parse an unqualified path
3336 (None, try!(self.parse_path(LifetimeAndTypesWithColons)))
3338 let hi = self.last_span.hi;
3339 Ok(self.mk_expr(lo, hi, ExprPath(qself, path), None))
3341 self.parse_pat_literal_maybe_minus()
3345 fn is_path_start(&self) -> bool {
3346 (self.token == token::Lt || self.token == token::ModSep
3347 || self.token.is_ident() || self.token.is_path())
3348 && !self.token.is_keyword(keywords::True) && !self.token.is_keyword(keywords::False)
3351 /// Parse a pattern.
3352 pub fn parse_pat(&mut self) -> PResult<'a, P<Pat>> {
3353 maybe_whole!(self, NtPat);
3355 let lo = self.span.lo;
3358 token::Underscore => {
3363 token::BinOp(token::And) | token::AndAnd => {
3364 // Parse &pat / &mut pat
3365 try!(self.expect_and());
3366 let mutbl = try!(self.parse_mutability());
3367 if let token::Lifetime(ident) = self.token {
3368 return Err(self.fatal(&format!("unexpected lifetime `{}` in pattern", ident)));
3371 let subpat = try!(self.parse_pat());
3372 pat = PatRegion(subpat, mutbl);
3374 token::OpenDelim(token::Paren) => {
3375 // Parse (pat,pat,pat,...) as tuple pattern
3377 let fields = try!(self.parse_pat_tuple_elements());
3378 try!(self.expect(&token::CloseDelim(token::Paren)));
3379 pat = PatTup(fields);
3381 token::OpenDelim(token::Bracket) => {
3382 // Parse [pat,pat,...] as slice pattern
3384 let (before, slice, after) = try!(self.parse_pat_vec_elements());
3385 try!(self.expect(&token::CloseDelim(token::Bracket)));
3386 pat = PatVec(before, slice, after);
3389 // At this point, token != _, &, &&, (, [
3390 if try!(self.eat_keyword(keywords::Mut)) {
3391 // Parse mut ident @ pat
3392 pat = try!(self.parse_pat_ident(BindingMode::ByValue(MutMutable)));
3393 } else if try!(self.eat_keyword(keywords::Ref)) {
3394 // Parse ref ident @ pat / ref mut ident @ pat
3395 let mutbl = try!(self.parse_mutability());
3396 pat = try!(self.parse_pat_ident(BindingMode::ByRef(mutbl)));
3397 } else if try!(self.eat_keyword(keywords::Box)) {
3399 let subpat = try!(self.parse_pat());
3400 pat = PatBox(subpat);
3401 } else if self.is_path_start() {
3402 // Parse pattern starting with a path
3403 if self.token.is_plain_ident() && self.look_ahead(1, |t| *t != token::DotDotDot &&
3404 *t != token::OpenDelim(token::Brace) &&
3405 *t != token::OpenDelim(token::Paren) &&
3406 // Contrary to its definition, a plain ident can be followed by :: in macros
3407 *t != token::ModSep) {
3408 // Plain idents have some extra abilities here compared to general paths
3409 if self.look_ahead(1, |t| *t == token::Not) {
3410 // Parse macro invocation
3411 let ident = try!(self.parse_ident());
3412 let ident_span = self.last_span;
3413 let path = ident_to_path(ident_span, ident);
3415 let delim = try!(self.expect_open_delim());
3416 let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
3417 seq_sep_none(), |p| p.parse_token_tree()));
3418 let mac = Mac_ { path: path, tts: tts, ctxt: EMPTY_CTXT };
3419 pat = PatMac(codemap::Spanned {node: mac,
3420 span: mk_sp(lo, self.last_span.hi)});
3422 // Parse ident @ pat
3423 // This can give false positives and parse nullary enums,
3424 // they are dealt with later in resolve
3425 pat = try!(self.parse_pat_ident(BindingMode::ByValue(MutImmutable)));
3428 let (qself, path) = if try!(self.eat_lt()) {
3429 // Parse a qualified path
3431 try!(self.parse_qualified_path(NoTypesAllowed));
3434 // Parse an unqualified path
3435 (None, try!(self.parse_path(LifetimeAndTypesWithColons)))
3438 token::DotDotDot => {
3440 let hi = self.last_span.hi;
3441 let begin = self.mk_expr(lo, hi, ExprPath(qself, path), None);
3443 let end = try!(self.parse_pat_range_end());
3444 pat = PatRange(begin, end);
3446 token::OpenDelim(token::Brace) => {
3447 if qself.is_some() {
3448 return Err(self.fatal("unexpected `{` after qualified path"));
3450 // Parse struct pattern
3452 let (fields, etc) = try!(self.parse_pat_fields());
3454 pat = PatStruct(path, fields, etc);
3456 token::OpenDelim(token::Paren) => {
3457 if qself.is_some() {
3458 return Err(self.fatal("unexpected `(` after qualified path"));
3460 // Parse tuple struct or enum pattern
3461 if self.look_ahead(1, |t| *t == token::DotDot) {
3462 // This is a "top constructor only" pat
3465 try!(self.expect(&token::CloseDelim(token::Paren)));
3466 pat = PatEnum(path, None);
3468 let args = try!(self.parse_enum_variant_seq(
3469 &token::OpenDelim(token::Paren),
3470 &token::CloseDelim(token::Paren),
3471 seq_sep_trailing_allowed(token::Comma),
3472 |p| p.parse_pat()));
3473 pat = PatEnum(path, Some(args));
3478 // Parse qualified path
3479 Some(qself) => PatQPath(qself, path),
3480 // Parse nullary enum
3481 None => PatEnum(path, Some(vec![]))
3487 // Try to parse everything else as literal with optional minus
3488 let begin = try!(self.parse_pat_literal_maybe_minus());
3489 if try!(self.eat(&token::DotDotDot)) {
3490 let end = try!(self.parse_pat_range_end());
3491 pat = PatRange(begin, end);
3493 pat = PatLit(begin);
3499 let hi = self.last_span.hi;
3501 id: ast::DUMMY_NODE_ID,
3503 span: mk_sp(lo, hi),
3507 /// Parse ident or ident @ pat
3508 /// used by the copy foo and ref foo patterns to give a good
3509 /// error message when parsing mistakes like ref foo(a,b)
3510 fn parse_pat_ident(&mut self,
3511 binding_mode: ast::BindingMode)
3512 -> PResult<'a, ast::Pat_> {
3513 if !self.token.is_plain_ident() {
3514 let span = self.span;
3515 let tok_str = self.this_token_to_string();
3516 return Err(self.span_fatal(span,
3517 &format!("expected identifier, found `{}`", tok_str)))
3519 let ident = try!(self.parse_ident());
3520 let last_span = self.last_span;
3521 let name = codemap::Spanned{span: last_span, node: ident};
3522 let sub = if try!(self.eat(&token::At) ){
3523 Some(try!(self.parse_pat()))
3528 // just to be friendly, if they write something like
3530 // we end up here with ( as the current token. This shortly
3531 // leads to a parse error. Note that if there is no explicit
3532 // binding mode then we do not end up here, because the lookahead
3533 // will direct us over to parse_enum_variant()
3534 if self.token == token::OpenDelim(token::Paren) {
3535 let last_span = self.last_span;
3536 return Err(self.span_fatal(
3538 "expected identifier, found enum pattern"))
3541 Ok(PatIdent(binding_mode, name, sub))
3544 /// Parse a local variable declaration
3545 fn parse_local(&mut self, attrs: ThinAttributes) -> PResult<'a, P<Local>> {
3546 let lo = self.span.lo;
3547 let pat = try!(self.parse_pat());
3550 if try!(self.eat(&token::Colon) ){
3551 ty = Some(try!(self.parse_ty_sum()));
3553 let init = try!(self.parse_initializer());
3558 id: ast::DUMMY_NODE_ID,
3559 span: mk_sp(lo, self.last_span.hi),
3564 /// Parse a "let" stmt
3565 fn parse_let(&mut self, attrs: ThinAttributes) -> PResult<'a, P<Decl>> {
3566 let lo = self.span.lo;
3567 let local = try!(self.parse_local(attrs));
3568 Ok(P(spanned(lo, self.last_span.hi, DeclLocal(local))))
3571 /// Parse a structure field
3572 fn parse_name_and_ty(&mut self, pr: Visibility,
3573 attrs: Vec<Attribute> ) -> PResult<'a, StructField> {
3575 Inherited => self.span.lo,
3576 Public => self.last_span.lo,
3578 if !self.token.is_plain_ident() {
3579 return Err(self.fatal("expected ident"));
3581 let name = try!(self.parse_ident());
3582 try!(self.expect(&token::Colon));
3583 let ty = try!(self.parse_ty_sum());
3584 Ok(spanned(lo, self.last_span.hi, ast::StructField_ {
3585 kind: NamedField(name, pr),
3586 id: ast::DUMMY_NODE_ID,
3592 /// Emit an expected item after attributes error.
3593 fn expected_item_err(&self, attrs: &[Attribute]) {
3594 let message = match attrs.last() {
3595 Some(&Attribute { node: ast::Attribute_ { is_sugared_doc: true, .. }, .. }) => {
3596 "expected item after doc comment"
3598 _ => "expected item after attributes",
3601 self.span_err(self.last_span, message);
3604 /// Parse a statement. may include decl.
3605 pub fn parse_stmt(&mut self) -> PResult<'a, Option<P<Stmt>>> {
3606 Ok(try!(self.parse_stmt_()).map(P))
3609 fn parse_stmt_(&mut self) -> PResult<'a, Option<Stmt>> {
3610 maybe_whole!(Some deref self, NtStmt);
3612 let attrs = try!(self.parse_outer_attributes());
3613 let lo = self.span.lo;
3615 Ok(Some(if self.check_keyword(keywords::Let) {
3616 try!(self.expect_keyword(keywords::Let));
3617 let decl = try!(self.parse_let(attrs.into_thin_attrs()));
3618 let hi = decl.span.hi;
3619 let stmt = StmtDecl(decl, ast::DUMMY_NODE_ID);
3620 spanned(lo, hi, stmt)
3621 } else if self.token.is_ident()
3622 && !self.token.is_any_keyword()
3623 && self.look_ahead(1, |t| *t == token::Not) {
3624 // it's a macro invocation:
3626 // Potential trouble: if we allow macros with paths instead of
3627 // idents, we'd need to look ahead past the whole path here...
3628 let pth = try!(self.parse_path(NoTypesAllowed));
3631 let id = match self.token {
3632 token::OpenDelim(_) => token::special_idents::invalid, // no special identifier
3633 _ => try!(self.parse_ident()),
3636 // check that we're pointing at delimiters (need to check
3637 // again after the `if`, because of `parse_ident`
3638 // consuming more tokens).
3639 let delim = match self.token {
3640 token::OpenDelim(delim) => delim,
3642 // we only expect an ident if we didn't parse one
3644 let ident_str = if id.name == token::special_idents::invalid.name {
3649 let tok_str = self.this_token_to_string();
3650 return Err(self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
3656 let tts = try!(self.parse_unspanned_seq(
3657 &token::OpenDelim(delim),
3658 &token::CloseDelim(delim),
3660 |p| p.parse_token_tree()
3662 let hi = self.last_span.hi;
3664 let style = if delim == token::Brace {
3667 MacStmtWithoutBraces
3670 if id.name == token::special_idents::invalid.name {
3671 let stmt = StmtMac(P(spanned(lo,
3673 Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT })),
3675 attrs.into_thin_attrs());
3676 spanned(lo, hi, stmt)
3678 // if it has a special ident, it's definitely an item
3680 // Require a semicolon or braces.
3681 if style != MacStmtWithBraces {
3682 if !try!(self.eat(&token::Semi) ){
3683 let last_span = self.last_span;
3684 self.span_err(last_span,
3685 "macros that expand to items must \
3686 either be surrounded with braces or \
3687 followed by a semicolon");
3690 spanned(lo, hi, StmtDecl(
3691 P(spanned(lo, hi, DeclItem(
3693 lo, hi, id /*id is good here*/,
3694 ItemMac(spanned(lo, hi,
3695 Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT })),
3696 Inherited, attrs)))),
3697 ast::DUMMY_NODE_ID))
3700 // FIXME: Bad copy of attrs
3701 match try!(self.parse_item_(attrs.clone(), false, true)) {
3704 let decl = P(spanned(lo, hi, DeclItem(i)));
3705 spanned(lo, hi, StmtDecl(decl, ast::DUMMY_NODE_ID))
3708 let unused_attrs = |attrs: &[_], s: &mut Self| {
3709 if attrs.len() > 0 {
3711 "expected statement after outer attribute");
3715 // Do not attempt to parse an expression if we're done here.
3716 if self.token == token::Semi {
3717 unused_attrs(&attrs, self);
3722 if self.token == token::CloseDelim(token::Brace) {
3723 unused_attrs(&attrs, self);
3727 // Remainder are line-expr stmts.
3728 let e = try!(self.parse_expr_res(
3729 Restrictions::RESTRICTION_STMT_EXPR, Some(attrs.into_thin_attrs())));
3731 let stmt = StmtExpr(e, ast::DUMMY_NODE_ID);
3732 spanned(lo, hi, stmt)
3738 /// Is this expression a successfully-parsed statement?
3739 fn expr_is_complete(&mut self, e: &Expr) -> bool {
3740 self.restrictions.contains(Restrictions::RESTRICTION_STMT_EXPR) &&
3741 !classify::expr_requires_semi_to_be_stmt(e)
3744 /// Parse a block. No inner attrs are allowed.
3745 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
3746 maybe_whole!(no_clone self, NtBlock);
3748 let lo = self.span.lo;
3750 if !try!(self.eat(&token::OpenDelim(token::Brace)) ){
3752 let tok = self.this_token_to_string();
3753 return Err(self.span_fatal_help(sp,
3754 &format!("expected `{{`, found `{}`", tok),
3755 "place this code inside a block"));
3758 self.parse_block_tail(lo, DefaultBlock)
3761 /// Parse a block. Inner attrs are allowed.
3762 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
3763 maybe_whole!(pair_empty self, NtBlock);
3765 let lo = self.span.lo;
3766 try!(self.expect(&token::OpenDelim(token::Brace)));
3767 Ok((try!(self.parse_inner_attributes()),
3768 try!(self.parse_block_tail(lo, DefaultBlock))))
3771 /// Parse the rest of a block expression or function body
3772 /// Precondition: already parsed the '{'.
3773 fn parse_block_tail(&mut self, lo: BytePos, s: BlockCheckMode) -> PResult<'a, P<Block>> {
3774 let mut stmts = vec![];
3775 let mut expr = None;
3777 while !try!(self.eat(&token::CloseDelim(token::Brace))) {
3778 let Spanned {node, span} = if let Some(s) = try!(self.parse_stmt_()) {
3781 // Found only `;` or `}`.
3786 try!(self.handle_expression_like_statement(e, span, &mut stmts, &mut expr));
3788 StmtMac(mac, MacStmtWithoutBraces, attrs) => {
3789 // statement macro without braces; might be an
3790 // expr depending on whether a semicolon follows
3793 stmts.push(P(Spanned {
3794 node: StmtMac(mac, MacStmtWithSemicolon, attrs),
3795 span: mk_sp(span.lo, self.span.hi),
3800 let e = self.mk_mac_expr(span.lo, span.hi,
3801 mac.and_then(|m| m.node),
3803 let e = try!(self.parse_dot_or_call_expr_with(e, attrs));
3804 let e = try!(self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e)));
3805 try!(self.handle_expression_like_statement(
3813 StmtMac(m, style, attrs) => {
3814 // statement macro; might be an expr
3817 stmts.push(P(Spanned {
3818 node: StmtMac(m, MacStmtWithSemicolon, attrs),
3819 span: mk_sp(span.lo, self.span.hi),
3823 token::CloseDelim(token::Brace) => {
3824 // if a block ends in `m!(arg)` without
3825 // a `;`, it must be an expr
3826 expr = Some(self.mk_mac_expr(span.lo, span.hi,
3827 m.and_then(|x| x.node),
3831 stmts.push(P(Spanned {
3832 node: StmtMac(m, style, attrs),
3838 _ => { // all other kinds of statements:
3839 let mut hi = span.hi;
3840 if classify::stmt_ends_with_semi(&node) {
3841 try!(self.commit_stmt_expecting(token::Semi));
3842 hi = self.last_span.hi;
3845 stmts.push(P(Spanned {
3847 span: mk_sp(span.lo, hi)
3856 id: ast::DUMMY_NODE_ID,
3858 span: mk_sp(lo, self.last_span.hi),
3862 fn handle_expression_like_statement(
3866 stmts: &mut Vec<P<Stmt>>,
3867 last_block_expr: &mut Option<P<Expr>>) -> PResult<'a, ()> {
3868 // expression without semicolon
3869 if classify::expr_requires_semi_to_be_stmt(&*e) {
3870 // Just check for errors and recover; do not eat semicolon yet.
3871 try!(self.commit_stmt(&[],
3872 &[token::Semi, token::CloseDelim(token::Brace)]));
3878 let span_with_semi = Span {
3880 hi: self.last_span.hi,
3881 expn_id: span.expn_id,
3883 stmts.push(P(Spanned {
3884 node: StmtSemi(e, ast::DUMMY_NODE_ID),
3885 span: span_with_semi,
3888 token::CloseDelim(token::Brace) => *last_block_expr = Some(e),
3890 stmts.push(P(Spanned {
3891 node: StmtExpr(e, ast::DUMMY_NODE_ID),
3899 // Parses a sequence of bounds if a `:` is found,
3900 // otherwise returns empty list.
3901 fn parse_colon_then_ty_param_bounds(&mut self,
3902 mode: BoundParsingMode)
3903 -> PResult<'a, TyParamBounds>
3905 if !try!(self.eat(&token::Colon) ){
3908 self.parse_ty_param_bounds(mode)
3912 // matches bounds = ( boundseq )?
3913 // where boundseq = ( polybound + boundseq ) | polybound
3914 // and polybound = ( 'for' '<' 'region '>' )? bound
3915 // and bound = 'region | trait_ref
3916 fn parse_ty_param_bounds(&mut self,
3917 mode: BoundParsingMode)
3918 -> PResult<'a, TyParamBounds>
3920 let mut result = vec!();
3922 let question_span = self.span;
3923 let ate_question = try!(self.eat(&token::Question));
3925 token::Lifetime(lifetime) => {
3927 self.span_err(question_span,
3928 "`?` may only modify trait bounds, not lifetime bounds");
3930 result.push(RegionTyParamBound(ast::Lifetime {
3931 id: ast::DUMMY_NODE_ID,
3937 token::ModSep | token::Ident(..) => {
3938 let poly_trait_ref = try!(self.parse_poly_trait_ref());
3939 let modifier = if ate_question {
3940 if mode == BoundParsingMode::Modified {
3941 TraitBoundModifier::Maybe
3943 self.span_err(question_span,
3945 TraitBoundModifier::None
3948 TraitBoundModifier::None
3950 result.push(TraitTyParamBound(poly_trait_ref, modifier))
3955 if !try!(self.eat(&token::BinOp(token::Plus)) ){
3960 return Ok(P::from_vec(result));
3963 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
3964 fn parse_ty_param(&mut self) -> PResult<'a, TyParam> {
3965 let span = self.span;
3966 let ident = try!(self.parse_ident());
3968 let bounds = try!(self.parse_colon_then_ty_param_bounds(BoundParsingMode::Modified));
3970 let default = if self.check(&token::Eq) {
3972 Some(try!(self.parse_ty_sum()))
3979 id: ast::DUMMY_NODE_ID,
3986 /// Parse a set of optional generic type parameter declarations. Where
3987 /// clauses are not parsed here, and must be added later via
3988 /// `parse_where_clause()`.
3990 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
3991 /// | ( < lifetimes , typaramseq ( , )? > )
3992 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
3993 pub fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
3994 maybe_whole!(self, NtGenerics);
3996 if try!(self.eat(&token::Lt) ){
3997 let lifetime_defs = try!(self.parse_lifetime_defs());
3998 let mut seen_default = false;
3999 let ty_params = try!(self.parse_seq_to_gt(Some(token::Comma), |p| {
4000 try!(p.forbid_lifetime());
4001 let ty_param = try!(p.parse_ty_param());
4002 if ty_param.default.is_some() {
4003 seen_default = true;
4004 } else if seen_default {
4005 let last_span = p.last_span;
4006 p.span_err(last_span,
4007 "type parameters with a default must be trailing");
4012 lifetimes: lifetime_defs,
4013 ty_params: ty_params,
4014 where_clause: WhereClause {
4015 id: ast::DUMMY_NODE_ID,
4016 predicates: Vec::new(),
4020 Ok(ast::Generics::default())
4024 fn parse_generic_values_after_lt(&mut self) -> PResult<'a, (Vec<ast::Lifetime>,
4026 Vec<P<TypeBinding>>)> {
4027 let span_lo = self.span.lo;
4028 let lifetimes = try!(self.parse_lifetimes(token::Comma));
4030 let missing_comma = !lifetimes.is_empty() &&
4031 !self.token.is_like_gt() &&
4033 .as_ref().map_or(true,
4034 |x| &**x != &token::Comma);
4038 let msg = format!("expected `,` or `>` after lifetime \
4040 self.this_token_to_string());
4041 let mut err = self.diagnostic().struct_span_err(self.span, &msg);
4043 let span_hi = self.span.hi;
4044 let span_hi = if self.parse_ty().is_ok() {
4050 let msg = format!("did you mean a single argument type &'a Type, \
4051 or did you mean the comma-separated arguments \
4053 err.span_note(mk_sp(span_lo, span_hi), &msg);
4056 self.abort_if_errors()
4059 // First parse types.
4060 let (types, returned) = try!(self.parse_seq_to_gt_or_return(
4063 try!(p.forbid_lifetime());
4064 if p.look_ahead(1, |t| t == &token::Eq) {
4067 Ok(Some(try!(p.parse_ty_sum())))
4072 // If we found the `>`, don't continue.
4074 return Ok((lifetimes, types.into_vec(), Vec::new()));
4077 // Then parse type bindings.
4078 let bindings = try!(self.parse_seq_to_gt(
4081 try!(p.forbid_lifetime());
4083 let ident = try!(p.parse_ident());
4084 let found_eq = try!(p.eat(&token::Eq));
4087 p.span_warn(span, "whoops, no =?");
4089 let ty = try!(p.parse_ty());
4090 let hi = ty.span.hi;
4091 let span = mk_sp(lo, hi);
4092 return Ok(P(TypeBinding{id: ast::DUMMY_NODE_ID,
4099 Ok((lifetimes, types.into_vec(), bindings.into_vec()))
4102 fn forbid_lifetime(&mut self) -> PResult<'a, ()> {
4103 if self.token.is_lifetime() {
4104 let span = self.span;
4105 return Err(self.span_fatal(span, "lifetime parameters must be declared \
4106 prior to type parameters"))
4111 /// Parses an optional `where` clause and places it in `generics`.
4114 /// where T : Trait<U, V> + 'b, 'a : 'b
4116 pub fn parse_where_clause(&mut self) -> PResult<'a, ast::WhereClause> {
4117 maybe_whole!(self, NtWhereClause);
4119 let mut where_clause = WhereClause {
4120 id: ast::DUMMY_NODE_ID,
4121 predicates: Vec::new(),
4124 if !try!(self.eat_keyword(keywords::Where)) {
4125 return Ok(where_clause);
4128 let mut parsed_something = false;
4130 let lo = self.span.lo;
4132 token::OpenDelim(token::Brace) => {
4136 token::Lifetime(..) => {
4137 let bounded_lifetime =
4138 try!(self.parse_lifetime());
4140 try!(self.eat(&token::Colon));
4143 try!(self.parse_lifetimes(token::BinOp(token::Plus)));
4145 let hi = self.last_span.hi;
4146 let span = mk_sp(lo, hi);
4148 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
4149 ast::WhereRegionPredicate {
4151 lifetime: bounded_lifetime,
4156 parsed_something = true;
4160 let bound_lifetimes = if try!(self.eat_keyword(keywords::For) ){
4161 // Higher ranked constraint.
4162 try!(self.expect(&token::Lt));
4163 let lifetime_defs = try!(self.parse_lifetime_defs());
4164 try!(self.expect_gt());
4170 let bounded_ty = try!(self.parse_ty());
4172 if try!(self.eat(&token::Colon) ){
4173 let bounds = try!(self.parse_ty_param_bounds(BoundParsingMode::Bare));
4174 let hi = self.last_span.hi;
4175 let span = mk_sp(lo, hi);
4177 if bounds.is_empty() {
4179 "each predicate in a `where` clause must have \
4180 at least one bound in it");
4183 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
4184 ast::WhereBoundPredicate {
4186 bound_lifetimes: bound_lifetimes,
4187 bounded_ty: bounded_ty,
4191 parsed_something = true;
4192 } else if try!(self.eat(&token::Eq) ){
4193 // let ty = try!(self.parse_ty());
4194 let hi = self.last_span.hi;
4195 let span = mk_sp(lo, hi);
4196 // where_clause.predicates.push(
4197 // ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
4198 // id: ast::DUMMY_NODE_ID,
4200 // path: panic!("NYI"), //bounded_ty,
4203 // parsed_something = true;
4206 "equality constraints are not yet supported \
4207 in where clauses (#20041)");
4209 let last_span = self.last_span;
4210 self.span_err(last_span,
4211 "unexpected token in `where` clause");
4216 if !try!(self.eat(&token::Comma) ){
4221 if !parsed_something {
4222 let last_span = self.last_span;
4223 self.span_err(last_span,
4224 "a `where` clause must have at least one predicate \
4231 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
4232 -> PResult<'a, (Vec<Arg> , bool)> {
4234 let mut args: Vec<Option<Arg>> =
4235 try!(self.parse_unspanned_seq(
4236 &token::OpenDelim(token::Paren),
4237 &token::CloseDelim(token::Paren),
4238 seq_sep_trailing_allowed(token::Comma),
4240 if p.token == token::DotDotDot {
4243 if p.token != token::CloseDelim(token::Paren) {
4245 return Err(p.span_fatal(span,
4246 "`...` must be last in argument list for variadic function"))
4250 return Err(p.span_fatal(span,
4251 "only foreign functions are allowed to be variadic"))
4255 Ok(Some(try!(p.parse_arg_general(named_args))))
4260 let variadic = match args.pop() {
4263 // Need to put back that last arg
4270 if variadic && args.is_empty() {
4272 "variadic function must be declared with at least one named argument");
4275 let args = args.into_iter().map(|x| x.unwrap()).collect();
4277 Ok((args, variadic))
4280 /// Parse the argument list and result type of a function declaration
4281 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> {
4283 let (args, variadic) = try!(self.parse_fn_args(true, allow_variadic));
4284 let ret_ty = try!(self.parse_ret_ty());
4293 fn is_self_ident(&mut self) -> bool {
4295 token::Ident(id, token::Plain) => id.name == special_idents::self_.name,
4300 fn expect_self_ident(&mut self) -> PResult<'a, ast::Ident> {
4302 token::Ident(id, token::Plain) if id.name == special_idents::self_.name => {
4307 let token_str = self.this_token_to_string();
4308 return Err(self.fatal(&format!("expected `self`, found `{}`",
4314 fn is_self_type_ident(&mut self) -> bool {
4316 token::Ident(id, token::Plain) => id.name == special_idents::type_self.name,
4321 fn expect_self_type_ident(&mut self) -> PResult<'a, ast::Ident> {
4323 token::Ident(id, token::Plain) if id.name == special_idents::type_self.name => {
4328 let token_str = self.this_token_to_string();
4329 Err(self.fatal(&format!("expected `Self`, found `{}`",
4335 /// Parse the argument list and result type of a function
4336 /// that may have a self type.
4337 fn parse_fn_decl_with_self<F>(&mut self,
4338 parse_arg_fn: F) -> PResult<'a, (ExplicitSelf, P<FnDecl>)> where
4339 F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
4341 fn maybe_parse_borrowed_explicit_self<'b>(this: &mut Parser<'b>)
4342 -> PResult<'b, ast::ExplicitSelf_> {
4343 // The following things are possible to see here:
4348 // fn(&'lt mut self)
4350 // We already know that the current token is `&`.
4352 if this.look_ahead(1, |t| t.is_keyword(keywords::SelfValue)) {
4354 Ok(SelfRegion(None, MutImmutable, try!(this.expect_self_ident())))
4355 } else if this.look_ahead(1, |t| t.is_mutability()) &&
4356 this.look_ahead(2, |t| t.is_keyword(keywords::SelfValue)) {
4358 let mutability = try!(this.parse_mutability());
4359 Ok(SelfRegion(None, mutability, try!(this.expect_self_ident())))
4360 } else if this.look_ahead(1, |t| t.is_lifetime()) &&
4361 this.look_ahead(2, |t| t.is_keyword(keywords::SelfValue)) {
4363 let lifetime = try!(this.parse_lifetime());
4364 Ok(SelfRegion(Some(lifetime), MutImmutable, try!(this.expect_self_ident())))
4365 } else if this.look_ahead(1, |t| t.is_lifetime()) &&
4366 this.look_ahead(2, |t| t.is_mutability()) &&
4367 this.look_ahead(3, |t| t.is_keyword(keywords::SelfValue)) {
4369 let lifetime = try!(this.parse_lifetime());
4370 let mutability = try!(this.parse_mutability());
4371 Ok(SelfRegion(Some(lifetime), mutability, try!(this.expect_self_ident())))
4377 try!(self.expect(&token::OpenDelim(token::Paren)));
4379 // A bit of complexity and lookahead is needed here in order to be
4380 // backwards compatible.
4381 let lo = self.span.lo;
4382 let mut self_ident_lo = self.span.lo;
4383 let mut self_ident_hi = self.span.hi;
4385 let mut mutbl_self = MutImmutable;
4386 let explicit_self = match self.token {
4387 token::BinOp(token::And) => {
4388 let eself = try!(maybe_parse_borrowed_explicit_self(self));
4389 self_ident_lo = self.last_span.lo;
4390 self_ident_hi = self.last_span.hi;
4393 token::BinOp(token::Star) => {
4394 // Possibly "*self" or "*mut self" -- not supported. Try to avoid
4395 // emitting cryptic "unexpected token" errors.
4397 let _mutability = if self.token.is_mutability() {
4398 try!(self.parse_mutability())
4402 if self.is_self_ident() {
4403 let span = self.span;
4404 self.span_err(span, "cannot pass self by raw pointer");
4407 // error case, making bogus self ident:
4408 SelfValue(special_idents::self_)
4410 token::Ident(..) => {
4411 if self.is_self_ident() {
4412 let self_ident = try!(self.expect_self_ident());
4414 // Determine whether this is the fully explicit form, `self:
4416 if try!(self.eat(&token::Colon) ){
4417 SelfExplicit(try!(self.parse_ty_sum()), self_ident)
4419 SelfValue(self_ident)
4421 } else if self.token.is_mutability() &&
4422 self.look_ahead(1, |t| t.is_keyword(keywords::SelfValue)) {
4423 mutbl_self = try!(self.parse_mutability());
4424 let self_ident = try!(self.expect_self_ident());
4426 // Determine whether this is the fully explicit form,
4428 if try!(self.eat(&token::Colon) ){
4429 SelfExplicit(try!(self.parse_ty_sum()), self_ident)
4431 SelfValue(self_ident)
4440 let explicit_self_sp = mk_sp(self_ident_lo, self_ident_hi);
4442 // shared fall-through for the three cases below. borrowing prevents simply
4443 // writing this as a closure
4444 macro_rules! parse_remaining_arguments {
4447 // If we parsed a self type, expect a comma before the argument list.
4451 let sep = seq_sep_trailing_allowed(token::Comma);
4452 let mut fn_inputs = try!(self.parse_seq_to_before_end(
4453 &token::CloseDelim(token::Paren),
4457 fn_inputs.insert(0, Arg::new_self(explicit_self_sp, mutbl_self, $self_id));
4460 token::CloseDelim(token::Paren) => {
4461 vec!(Arg::new_self(explicit_self_sp, mutbl_self, $self_id))
4464 let token_str = self.this_token_to_string();
4465 return Err(self.fatal(&format!("expected `,` or `)`, found `{}`",
4472 let fn_inputs = match explicit_self {
4474 let sep = seq_sep_trailing_allowed(token::Comma);
4475 try!(self.parse_seq_to_before_end(&token::CloseDelim(token::Paren),
4478 SelfValue(id) => parse_remaining_arguments!(id),
4479 SelfRegion(_,_,id) => parse_remaining_arguments!(id),
4480 SelfExplicit(_,id) => parse_remaining_arguments!(id),
4484 try!(self.expect(&token::CloseDelim(token::Paren)));
4486 let hi = self.span.hi;
4488 let ret_ty = try!(self.parse_ret_ty());
4490 let fn_decl = P(FnDecl {
4496 Ok((spanned(lo, hi, explicit_self), fn_decl))
4499 // parse the |arg, arg| header on a lambda
4500 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
4501 let inputs_captures = {
4502 if try!(self.eat(&token::OrOr) ){
4505 try!(self.expect(&token::BinOp(token::Or)));
4506 try!(self.parse_obsolete_closure_kind());
4507 let args = try!(self.parse_seq_to_before_end(
4508 &token::BinOp(token::Or),
4509 seq_sep_trailing_allowed(token::Comma),
4510 |p| p.parse_fn_block_arg()
4516 let output = try!(self.parse_ret_ty());
4519 inputs: inputs_captures,
4525 /// Parse the name and optional generic types of a function header.
4526 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
4527 let id = try!(self.parse_ident());
4528 let generics = try!(self.parse_generics());
4532 fn mk_item(&mut self, lo: BytePos, hi: BytePos, ident: Ident,
4533 node: Item_, vis: Visibility,
4534 attrs: Vec<Attribute>) -> P<Item> {
4538 id: ast::DUMMY_NODE_ID,
4545 /// Parse an item-position function declaration.
4546 fn parse_item_fn(&mut self,
4548 constness: Constness,
4550 -> PResult<'a, ItemInfo> {
4551 let (ident, mut generics) = try!(self.parse_fn_header());
4552 let decl = try!(self.parse_fn_decl(false));
4553 generics.where_clause = try!(self.parse_where_clause());
4554 let (inner_attrs, body) = try!(self.parse_inner_attrs_and_block());
4555 Ok((ident, ItemFn(decl, unsafety, constness, abi, generics, body), Some(inner_attrs)))
4558 /// true if we are looking at `const ID`, false for things like `const fn` etc
4559 pub fn is_const_item(&mut self) -> bool {
4560 self.token.is_keyword(keywords::Const) &&
4561 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
4562 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
4565 /// parses all the "front matter" for a `fn` declaration, up to
4566 /// and including the `fn` keyword:
4570 /// - `const unsafe fn`
4573 pub fn parse_fn_front_matter(&mut self)
4574 -> PResult<'a, (ast::Constness, ast::Unsafety, abi::Abi)> {
4575 let is_const_fn = try!(self.eat_keyword(keywords::Const));
4576 let unsafety = try!(self.parse_unsafety());
4577 let (constness, unsafety, abi) = if is_const_fn {
4578 (Constness::Const, unsafety, abi::Rust)
4580 let abi = if try!(self.eat_keyword(keywords::Extern)) {
4581 try!(self.parse_opt_abi()).unwrap_or(abi::C)
4585 (Constness::NotConst, unsafety, abi)
4587 try!(self.expect_keyword(keywords::Fn));
4588 Ok((constness, unsafety, abi))
4591 /// Parse an impl item.
4592 pub fn parse_impl_item(&mut self) -> PResult<'a, P<ImplItem>> {
4593 maybe_whole!(no_clone self, NtImplItem);
4595 let mut attrs = try!(self.parse_outer_attributes());
4596 let lo = self.span.lo;
4597 let vis = try!(self.parse_visibility());
4598 let (name, node) = if try!(self.eat_keyword(keywords::Type)) {
4599 let name = try!(self.parse_ident());
4600 try!(self.expect(&token::Eq));
4601 let typ = try!(self.parse_ty_sum());
4602 try!(self.expect(&token::Semi));
4603 (name, ast::ImplItemKind::Type(typ))
4604 } else if self.is_const_item() {
4605 try!(self.expect_keyword(keywords::Const));
4606 let name = try!(self.parse_ident());
4607 try!(self.expect(&token::Colon));
4608 let typ = try!(self.parse_ty_sum());
4609 try!(self.expect(&token::Eq));
4610 let expr = try!(self.parse_expr());
4611 try!(self.commit_expr_expecting(&expr, token::Semi));
4612 (name, ast::ImplItemKind::Const(typ, expr))
4614 let (name, inner_attrs, node) = try!(self.parse_impl_method(vis));
4615 attrs.extend(inner_attrs);
4620 id: ast::DUMMY_NODE_ID,
4621 span: mk_sp(lo, self.last_span.hi),
4629 fn complain_if_pub_macro(&mut self, visa: Visibility, span: Span) {
4632 let is_macro_rules: bool = match self.token {
4633 token::Ident(sid, _) => sid.name == intern("macro_rules"),
4637 self.diagnostic().struct_span_err(span, "can't qualify macro_rules \
4638 invocation with `pub`")
4639 .fileline_help(span, "did you mean #[macro_export]?")
4642 self.diagnostic().struct_span_err(span, "can't qualify macro \
4643 invocation with `pub`")
4644 .fileline_help(span, "try adjusting the macro to put `pub` \
4645 inside the invocation")
4653 /// Parse a method or a macro invocation in a trait impl.
4654 fn parse_impl_method(&mut self, vis: Visibility)
4655 -> PResult<'a, (Ident, Vec<ast::Attribute>, ast::ImplItemKind)> {
4656 // code copied from parse_macro_use_or_failure... abstraction!
4657 if !self.token.is_any_keyword()
4658 && self.look_ahead(1, |t| *t == token::Not)
4659 && (self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren))
4660 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) {
4663 let last_span = self.last_span;
4664 self.complain_if_pub_macro(vis, last_span);
4666 let lo = self.span.lo;
4667 let pth = try!(self.parse_path(NoTypesAllowed));
4668 try!(self.expect(&token::Not));
4670 // eat a matched-delimiter token tree:
4671 let delim = try!(self.expect_open_delim());
4672 let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
4674 |p| p.parse_token_tree()));
4675 let m_ = Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT };
4676 let m: ast::Mac = codemap::Spanned { node: m_,
4678 self.last_span.hi) };
4679 if delim != token::Brace {
4680 try!(self.expect(&token::Semi))
4682 Ok((token::special_idents::invalid, vec![], ast::ImplItemKind::Macro(m)))
4684 let (constness, unsafety, abi) = try!(self.parse_fn_front_matter());
4685 let ident = try!(self.parse_ident());
4686 let mut generics = try!(self.parse_generics());
4687 let (explicit_self, decl) = try!(self.parse_fn_decl_with_self(|p| {
4690 generics.where_clause = try!(self.parse_where_clause());
4691 let (inner_attrs, body) = try!(self.parse_inner_attrs_and_block());
4692 Ok((ident, inner_attrs, ast::ImplItemKind::Method(ast::MethodSig {
4695 explicit_self: explicit_self,
4697 constness: constness,
4703 /// Parse trait Foo { ... }
4704 fn parse_item_trait(&mut self, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
4706 let ident = try!(self.parse_ident());
4707 let mut tps = try!(self.parse_generics());
4709 // Parse supertrait bounds.
4710 let bounds = try!(self.parse_colon_then_ty_param_bounds(BoundParsingMode::Bare));
4712 tps.where_clause = try!(self.parse_where_clause());
4714 let meths = try!(self.parse_trait_items());
4715 Ok((ident, ItemTrait(unsafety, tps, bounds, meths), None))
4718 /// Parses items implementations variants
4719 /// impl<T> Foo { ... }
4720 /// impl<T> ToString for &'static T { ... }
4721 /// impl Send for .. {}
4722 fn parse_item_impl(&mut self, unsafety: ast::Unsafety) -> PResult<'a, ItemInfo> {
4723 let impl_span = self.span;
4725 // First, parse type parameters if necessary.
4726 let mut generics = try!(self.parse_generics());
4728 // Special case: if the next identifier that follows is '(', don't
4729 // allow this to be parsed as a trait.
4730 let could_be_trait = self.token != token::OpenDelim(token::Paren);
4732 let neg_span = self.span;
4733 let polarity = if try!(self.eat(&token::Not) ){
4734 ast::ImplPolarity::Negative
4736 ast::ImplPolarity::Positive
4740 let mut ty = try!(self.parse_ty_sum());
4742 // Parse traits, if necessary.
4743 let opt_trait = if could_be_trait && try!(self.eat_keyword(keywords::For) ){
4744 // New-style trait. Reinterpret the type as a trait.
4746 TyPath(None, ref path) => {
4748 path: (*path).clone(),
4753 self.span_err(ty.span, "not a trait");
4759 ast::ImplPolarity::Negative => {
4760 // This is a negated type implementation
4761 // `impl !MyType {}`, which is not allowed.
4762 self.span_err(neg_span, "inherent implementation can't be negated");
4769 if opt_trait.is_some() && try!(self.eat(&token::DotDot) ){
4770 if generics.is_parameterized() {
4771 self.span_err(impl_span, "default trait implementations are not \
4772 allowed to have generics");
4775 try!(self.expect(&token::OpenDelim(token::Brace)));
4776 try!(self.expect(&token::CloseDelim(token::Brace)));
4777 Ok((ast_util::impl_pretty_name(&opt_trait, None),
4778 ItemDefaultImpl(unsafety, opt_trait.unwrap()), None))
4780 if opt_trait.is_some() {
4781 ty = try!(self.parse_ty_sum());
4783 generics.where_clause = try!(self.parse_where_clause());
4785 try!(self.expect(&token::OpenDelim(token::Brace)));
4786 let attrs = try!(self.parse_inner_attributes());
4788 let mut impl_items = vec![];
4789 while !try!(self.eat(&token::CloseDelim(token::Brace))) {
4790 impl_items.push(try!(self.parse_impl_item()));
4793 Ok((ast_util::impl_pretty_name(&opt_trait, Some(&*ty)),
4794 ItemImpl(unsafety, polarity, generics, opt_trait, ty, impl_items),
4799 /// Parse a::B<String,i32>
4800 fn parse_trait_ref(&mut self) -> PResult<'a, TraitRef> {
4802 path: try!(self.parse_path(LifetimeAndTypesWithoutColons)),
4803 ref_id: ast::DUMMY_NODE_ID,
4807 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<ast::LifetimeDef>> {
4808 if try!(self.eat_keyword(keywords::For) ){
4809 try!(self.expect(&token::Lt));
4810 let lifetime_defs = try!(self.parse_lifetime_defs());
4811 try!(self.expect_gt());
4818 /// Parse for<'l> a::B<String,i32>
4819 fn parse_poly_trait_ref(&mut self) -> PResult<'a, PolyTraitRef> {
4820 let lo = self.span.lo;
4821 let lifetime_defs = try!(self.parse_late_bound_lifetime_defs());
4823 Ok(ast::PolyTraitRef {
4824 bound_lifetimes: lifetime_defs,
4825 trait_ref: try!(self.parse_trait_ref()),
4826 span: mk_sp(lo, self.last_span.hi),
4830 /// Parse struct Foo { ... }
4831 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
4832 let class_name = try!(self.parse_ident());
4833 let mut generics = try!(self.parse_generics());
4835 // There is a special case worth noting here, as reported in issue #17904.
4836 // If we are parsing a tuple struct it is the case that the where clause
4837 // should follow the field list. Like so:
4839 // struct Foo<T>(T) where T: Copy;
4841 // If we are parsing a normal record-style struct it is the case
4842 // that the where clause comes before the body, and after the generics.
4843 // So if we look ahead and see a brace or a where-clause we begin
4844 // parsing a record style struct.
4846 // Otherwise if we look ahead and see a paren we parse a tuple-style
4849 let vdata = if self.token.is_keyword(keywords::Where) {
4850 generics.where_clause = try!(self.parse_where_clause());
4851 if try!(self.eat(&token::Semi)) {
4852 // If we see a: `struct Foo<T> where T: Copy;` style decl.
4853 VariantData::Unit(ast::DUMMY_NODE_ID)
4855 // If we see: `struct Foo<T> where T: Copy { ... }`
4856 VariantData::Struct(try!(self.parse_record_struct_body(ParsePub::Yes)),
4859 // No `where` so: `struct Foo<T>;`
4860 } else if try!(self.eat(&token::Semi) ){
4861 VariantData::Unit(ast::DUMMY_NODE_ID)
4862 // Record-style struct definition
4863 } else if self.token == token::OpenDelim(token::Brace) {
4864 VariantData::Struct(try!(self.parse_record_struct_body(ParsePub::Yes)),
4866 // Tuple-style struct definition with optional where-clause.
4867 } else if self.token == token::OpenDelim(token::Paren) {
4868 let body = VariantData::Tuple(try!(self.parse_tuple_struct_body(ParsePub::Yes)),
4869 ast::DUMMY_NODE_ID);
4870 generics.where_clause = try!(self.parse_where_clause());
4871 try!(self.expect(&token::Semi));
4874 let token_str = self.this_token_to_string();
4875 return Err(self.fatal(&format!("expected `where`, `{{`, `(`, or `;` after struct \
4876 name, found `{}`", token_str)))
4879 Ok((class_name, ItemStruct(vdata, generics), None))
4882 pub fn parse_record_struct_body(&mut self,
4883 parse_pub: ParsePub)
4884 -> PResult<'a, Vec<StructField>> {
4885 let mut fields = Vec::new();
4886 if try!(self.eat(&token::OpenDelim(token::Brace)) ){
4887 while self.token != token::CloseDelim(token::Brace) {
4888 fields.push(try!(self.parse_struct_decl_field(parse_pub)));
4893 let token_str = self.this_token_to_string();
4894 return Err(self.fatal(&format!("expected `where`, or `{{` after struct \
4902 pub fn parse_tuple_struct_body(&mut self,
4903 parse_pub: ParsePub)
4904 -> PResult<'a, Vec<StructField>> {
4905 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
4906 // Unit like structs are handled in parse_item_struct function
4907 let fields = try!(self.parse_unspanned_seq(
4908 &token::OpenDelim(token::Paren),
4909 &token::CloseDelim(token::Paren),
4910 seq_sep_trailing_allowed(token::Comma),
4912 let attrs = try!(p.parse_outer_attributes());
4914 let struct_field_ = ast::StructField_ {
4915 kind: UnnamedField (
4916 if parse_pub == ParsePub::Yes {
4917 try!(p.parse_visibility())
4922 id: ast::DUMMY_NODE_ID,
4923 ty: try!(p.parse_ty_sum()),
4926 Ok(spanned(lo, p.span.hi, struct_field_))
4932 /// Parse a structure field declaration
4933 pub fn parse_single_struct_field(&mut self,
4935 attrs: Vec<Attribute> )
4936 -> PResult<'a, StructField> {
4937 let a_var = try!(self.parse_name_and_ty(vis, attrs));
4942 token::CloseDelim(token::Brace) => {}
4944 let span = self.span;
4945 let token_str = self.this_token_to_string();
4946 return Err(self.span_fatal_help(span,
4947 &format!("expected `,`, or `}}`, found `{}`",
4949 "struct fields should be separated by commas"))
4955 /// Parse an element of a struct definition
4956 fn parse_struct_decl_field(&mut self, parse_pub: ParsePub) -> PResult<'a, StructField> {
4958 let attrs = try!(self.parse_outer_attributes());
4960 if try!(self.eat_keyword(keywords::Pub) ){
4961 if parse_pub == ParsePub::No {
4962 let span = self.last_span;
4963 self.span_err(span, "`pub` is not allowed here");
4965 return self.parse_single_struct_field(Public, attrs);
4968 return self.parse_single_struct_field(Inherited, attrs);
4971 /// Parse visibility: PUB or nothing
4972 fn parse_visibility(&mut self) -> PResult<'a, Visibility> {
4973 if try!(self.eat_keyword(keywords::Pub)) { Ok(Public) }
4974 else { Ok(Inherited) }
4977 /// Given a termination token, parse all of the items in a module
4978 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: BytePos) -> PResult<'a, Mod> {
4979 let mut items = vec![];
4980 while let Some(item) = try!(self.parse_item()) {
4984 if !try!(self.eat(term)) {
4985 let token_str = self.this_token_to_string();
4986 return Err(self.fatal(&format!("expected item, found `{}`", token_str)));
4989 let hi = if self.span == codemap::DUMMY_SP {
4996 inner: mk_sp(inner_lo, hi),
5001 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
5002 let id = try!(self.parse_ident());
5003 try!(self.expect(&token::Colon));
5004 let ty = try!(self.parse_ty_sum());
5005 try!(self.expect(&token::Eq));
5006 let e = try!(self.parse_expr());
5007 try!(self.commit_expr_expecting(&*e, token::Semi));
5008 let item = match m {
5009 Some(m) => ItemStatic(ty, m, e),
5010 None => ItemConst(ty, e),
5012 Ok((id, item, None))
5015 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
5016 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
5017 let id_span = self.span;
5018 let id = try!(self.parse_ident());
5019 if self.check(&token::Semi) {
5021 // This mod is in an external file. Let's go get it!
5022 let (m, attrs) = try!(self.eval_src_mod(id, outer_attrs, id_span));
5023 Ok((id, m, Some(attrs)))
5025 self.push_mod_path(id, outer_attrs);
5026 try!(self.expect(&token::OpenDelim(token::Brace)));
5027 let mod_inner_lo = self.span.lo;
5028 let old_owns_directory = self.owns_directory;
5029 self.owns_directory = true;
5030 let attrs = try!(self.parse_inner_attributes());
5031 let m = try!(self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo));
5032 self.owns_directory = old_owns_directory;
5033 self.pop_mod_path();
5034 Ok((id, ItemMod(m), Some(attrs)))
5038 fn push_mod_path(&mut self, id: Ident, attrs: &[Attribute]) {
5039 let default_path = self.id_to_interned_str(id);
5040 let file_path = match ::attr::first_attr_value_str_by_name(attrs, "path") {
5042 None => default_path,
5044 self.mod_path_stack.push(file_path)
5047 fn pop_mod_path(&mut self) {
5048 self.mod_path_stack.pop().unwrap();
5051 pub fn submod_path_from_attr(attrs: &[ast::Attribute], dir_path: &Path) -> Option<PathBuf> {
5052 ::attr::first_attr_value_str_by_name(attrs, "path").map(|d| dir_path.join(&*d))
5055 /// Returns either a path to a module, or .
5056 pub fn default_submod_path(id: ast::Ident, dir_path: &Path, codemap: &CodeMap) -> ModulePath
5058 let mod_name = id.to_string();
5059 let default_path_str = format!("{}.rs", mod_name);
5060 let secondary_path_str = format!("{}/mod.rs", mod_name);
5061 let default_path = dir_path.join(&default_path_str);
5062 let secondary_path = dir_path.join(&secondary_path_str);
5063 let default_exists = codemap.file_exists(&default_path);
5064 let secondary_exists = codemap.file_exists(&secondary_path);
5066 let result = match (default_exists, secondary_exists) {
5067 (true, false) => Ok(ModulePathSuccess { path: default_path, owns_directory: false }),
5068 (false, true) => Ok(ModulePathSuccess { path: secondary_path, owns_directory: true }),
5069 (false, false) => Err(ModulePathError {
5070 err_msg: format!("file not found for module `{}`", mod_name),
5071 help_msg: format!("name the file either {} or {} inside the directory {:?}",
5074 dir_path.display()),
5076 (true, true) => Err(ModulePathError {
5077 err_msg: format!("file for module `{}` found at both {} and {}",
5080 secondary_path_str),
5081 help_msg: "delete or rename one of them to remove the ambiguity".to_owned(),
5087 path_exists: default_exists || secondary_exists,
5092 fn submod_path(&mut self,
5094 outer_attrs: &[ast::Attribute],
5095 id_sp: Span) -> PResult<'a, ModulePathSuccess> {
5096 let mut prefix = PathBuf::from(&self.sess.codemap().span_to_filename(self.span));
5098 let mut dir_path = prefix;
5099 for part in &self.mod_path_stack {
5100 dir_path.push(&**part);
5103 if let Some(p) = Parser::submod_path_from_attr(outer_attrs, &dir_path) {
5104 return Ok(ModulePathSuccess { path: p, owns_directory: true });
5107 let paths = Parser::default_submod_path(id, &dir_path, self.sess.codemap());
5109 if !self.owns_directory {
5110 let mut err = self.diagnostic().struct_span_err(id_sp,
5111 "cannot declare a new module at this location");
5112 let this_module = match self.mod_path_stack.last() {
5113 Some(name) => name.to_string(),
5114 None => self.root_module_name.as_ref().unwrap().clone(),
5116 err.span_note(id_sp,
5117 &format!("maybe move this module `{0}` to its own directory \
5120 if paths.path_exists {
5121 err.span_note(id_sp,
5122 &format!("... or maybe `use` the module `{}` instead \
5123 of possibly redeclaring it",
5127 self.abort_if_errors();
5130 match paths.result {
5131 Ok(succ) => Ok(succ),
5132 Err(err) => Err(self.span_fatal_help(id_sp, &err.err_msg, &err.help_msg)),
5136 /// Read a module from a source file.
5137 fn eval_src_mod(&mut self,
5139 outer_attrs: &[ast::Attribute],
5141 -> PResult<'a, (ast::Item_, Vec<ast::Attribute> )> {
5142 let ModulePathSuccess { path, owns_directory } = try!(self.submod_path(id,
5146 self.eval_src_mod_from_path(path,
5152 fn eval_src_mod_from_path(&mut self,
5154 owns_directory: bool,
5156 id_sp: Span) -> PResult<'a, (ast::Item_, Vec<ast::Attribute> )> {
5157 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
5158 match included_mod_stack.iter().position(|p| *p == path) {
5160 let mut err = String::from("circular modules: ");
5161 let len = included_mod_stack.len();
5162 for p in &included_mod_stack[i.. len] {
5163 err.push_str(&p.to_string_lossy());
5164 err.push_str(" -> ");
5166 err.push_str(&path.to_string_lossy());
5167 return Err(self.span_fatal(id_sp, &err[..]));
5171 included_mod_stack.push(path.clone());
5172 drop(included_mod_stack);
5174 let mut p0 = new_sub_parser_from_file(self.sess,
5180 let mod_inner_lo = p0.span.lo;
5181 let mod_attrs = try!(p0.parse_inner_attributes());
5182 let m0 = try!(p0.parse_mod_items(&token::Eof, mod_inner_lo));
5183 self.sess.included_mod_stack.borrow_mut().pop();
5184 Ok((ast::ItemMod(m0), mod_attrs))
5187 /// Parse a function declaration from a foreign module
5188 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: BytePos,
5189 attrs: Vec<Attribute>) -> PResult<'a, P<ForeignItem>> {
5190 try!(self.expect_keyword(keywords::Fn));
5192 let (ident, mut generics) = try!(self.parse_fn_header());
5193 let decl = try!(self.parse_fn_decl(true));
5194 generics.where_clause = try!(self.parse_where_clause());
5195 let hi = self.span.hi;
5196 try!(self.expect(&token::Semi));
5197 Ok(P(ast::ForeignItem {
5200 node: ForeignItemFn(decl, generics),
5201 id: ast::DUMMY_NODE_ID,
5202 span: mk_sp(lo, hi),
5207 /// Parse a static item from a foreign module
5208 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: BytePos,
5209 attrs: Vec<Attribute>) -> PResult<'a, P<ForeignItem>> {
5210 try!(self.expect_keyword(keywords::Static));
5211 let mutbl = try!(self.eat_keyword(keywords::Mut));
5213 let ident = try!(self.parse_ident());
5214 try!(self.expect(&token::Colon));
5215 let ty = try!(self.parse_ty_sum());
5216 let hi = self.span.hi;
5217 try!(self.expect(&token::Semi));
5221 node: ForeignItemStatic(ty, mutbl),
5222 id: ast::DUMMY_NODE_ID,
5223 span: mk_sp(lo, hi),
5228 /// Parse extern crate links
5232 /// extern crate foo;
5233 /// extern crate bar as foo;
5234 fn parse_item_extern_crate(&mut self,
5236 visibility: Visibility,
5237 attrs: Vec<Attribute>)
5238 -> PResult<'a, P<Item>> {
5240 let crate_name = try!(self.parse_ident());
5241 let (maybe_path, ident) = if let Some(ident) = try!(self.parse_rename()) {
5242 (Some(crate_name.name), ident)
5246 try!(self.expect(&token::Semi));
5248 let last_span = self.last_span;
5250 if visibility == ast::Public {
5251 self.span_warn(mk_sp(lo, last_span.hi),
5252 "`pub extern crate` does not work as expected and should not be used. \
5253 Likely to become an error. Prefer `extern crate` and `pub use`.");
5259 ItemExternCrate(maybe_path),
5264 /// Parse `extern` for foreign ABIs
5267 /// `extern` is expected to have been
5268 /// consumed before calling this method
5274 fn parse_item_foreign_mod(&mut self,
5276 opt_abi: Option<abi::Abi>,
5277 visibility: Visibility,
5278 mut attrs: Vec<Attribute>)
5279 -> PResult<'a, P<Item>> {
5280 try!(self.expect(&token::OpenDelim(token::Brace)));
5282 let abi = opt_abi.unwrap_or(abi::C);
5284 attrs.extend(try!(self.parse_inner_attributes()));
5286 let mut foreign_items = vec![];
5287 while let Some(item) = try!(self.parse_foreign_item()) {
5288 foreign_items.push(item);
5290 try!(self.expect(&token::CloseDelim(token::Brace)));
5292 let last_span = self.last_span;
5293 let m = ast::ForeignMod {
5295 items: foreign_items
5299 special_idents::invalid,
5305 /// Parse type Foo = Bar;
5306 fn parse_item_type(&mut self) -> PResult<'a, ItemInfo> {
5307 let ident = try!(self.parse_ident());
5308 let mut tps = try!(self.parse_generics());
5309 tps.where_clause = try!(self.parse_where_clause());
5310 try!(self.expect(&token::Eq));
5311 let ty = try!(self.parse_ty_sum());
5312 try!(self.expect(&token::Semi));
5313 Ok((ident, ItemTy(ty, tps), None))
5316 /// Parse the part of an "enum" decl following the '{'
5317 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
5318 let mut variants = Vec::new();
5319 let mut all_nullary = true;
5320 let mut any_disr = None;
5321 while self.token != token::CloseDelim(token::Brace) {
5322 let variant_attrs = try!(self.parse_outer_attributes());
5323 let vlo = self.span.lo;
5326 let mut disr_expr = None;
5327 let ident = try!(self.parse_ident());
5328 if self.check(&token::OpenDelim(token::Brace)) {
5329 // Parse a struct variant.
5330 all_nullary = false;
5331 struct_def = VariantData::Struct(try!(self.parse_record_struct_body(ParsePub::No)),
5332 ast::DUMMY_NODE_ID);
5333 } else if self.check(&token::OpenDelim(token::Paren)) {
5334 all_nullary = false;
5335 struct_def = VariantData::Tuple(try!(self.parse_tuple_struct_body(ParsePub::No)),
5336 ast::DUMMY_NODE_ID);
5337 } else if try!(self.eat(&token::Eq) ){
5338 disr_expr = Some(try!(self.parse_expr()));
5339 any_disr = disr_expr.as_ref().map(|expr| expr.span);
5340 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5342 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5345 let vr = ast::Variant_ {
5347 attrs: variant_attrs,
5349 disr_expr: disr_expr,
5351 variants.push(P(spanned(vlo, self.last_span.hi, vr)));
5353 if !try!(self.eat(&token::Comma)) { break; }
5355 try!(self.expect(&token::CloseDelim(token::Brace)));
5357 Some(disr_span) if !all_nullary =>
5358 self.span_err(disr_span,
5359 "discriminator values can only be used with a c-like enum"),
5363 Ok(ast::EnumDef { variants: variants })
5366 /// Parse an "enum" declaration
5367 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
5368 let id = try!(self.parse_ident());
5369 let mut generics = try!(self.parse_generics());
5370 generics.where_clause = try!(self.parse_where_clause());
5371 try!(self.expect(&token::OpenDelim(token::Brace)));
5373 let enum_definition = try!(self.parse_enum_def(&generics));
5374 Ok((id, ItemEnum(enum_definition, generics), None))
5377 /// Parses a string as an ABI spec on an extern type or module. Consumes
5378 /// the `extern` keyword, if one is found.
5379 fn parse_opt_abi(&mut self) -> PResult<'a, Option<abi::Abi>> {
5381 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
5383 self.expect_no_suffix(sp, "ABI spec", suf);
5385 match abi::lookup(&s.as_str()) {
5386 Some(abi) => Ok(Some(abi)),
5388 let last_span = self.last_span;
5391 &format!("invalid ABI: expected one of [{}], \
5393 abi::all_names().join(", "),
5404 /// Parse one of the items allowed by the flags.
5405 /// NB: this function no longer parses the items inside an
5407 fn parse_item_(&mut self, attrs: Vec<Attribute>,
5408 macros_allowed: bool, attributes_allowed: bool) -> PResult<'a, Option<P<Item>>> {
5409 let nt_item = match self.token {
5410 token::Interpolated(token::NtItem(ref item)) => {
5411 Some((**item).clone())
5418 let mut attrs = attrs;
5419 mem::swap(&mut item.attrs, &mut attrs);
5420 item.attrs.extend(attrs);
5421 return Ok(Some(P(item)));
5426 let lo = self.span.lo;
5428 let visibility = try!(self.parse_visibility());
5430 if try!(self.eat_keyword(keywords::Use) ){
5432 let item_ = ItemUse(try!(self.parse_view_path()));
5433 try!(self.expect(&token::Semi));
5435 let last_span = self.last_span;
5436 let item = self.mk_item(lo,
5438 token::special_idents::invalid,
5442 return Ok(Some(item));
5445 if try!(self.eat_keyword(keywords::Extern)) {
5446 if try!(self.eat_keyword(keywords::Crate)) {
5447 return Ok(Some(try!(self.parse_item_extern_crate(lo, visibility, attrs))));
5450 let opt_abi = try!(self.parse_opt_abi());
5452 if try!(self.eat_keyword(keywords::Fn) ){
5453 // EXTERN FUNCTION ITEM
5454 let abi = opt_abi.unwrap_or(abi::C);
5455 let (ident, item_, extra_attrs) =
5456 try!(self.parse_item_fn(Unsafety::Normal, Constness::NotConst, abi));
5457 let last_span = self.last_span;
5458 let item = self.mk_item(lo,
5463 maybe_append(attrs, extra_attrs));
5464 return Ok(Some(item));
5465 } else if self.check(&token::OpenDelim(token::Brace)) {
5466 return Ok(Some(try!(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs))));
5469 try!(self.expect_one_of(&[], &[]));
5472 if try!(self.eat_keyword(keywords::Static) ){
5474 let m = if try!(self.eat_keyword(keywords::Mut)) {MutMutable} else {MutImmutable};
5475 let (ident, item_, extra_attrs) = try!(self.parse_item_const(Some(m)));
5476 let last_span = self.last_span;
5477 let item = self.mk_item(lo,
5482 maybe_append(attrs, extra_attrs));
5483 return Ok(Some(item));
5485 if try!(self.eat_keyword(keywords::Const) ){
5486 if self.check_keyword(keywords::Fn)
5487 || (self.check_keyword(keywords::Unsafe)
5488 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
5489 // CONST FUNCTION ITEM
5490 let unsafety = if try!(self.eat_keyword(keywords::Unsafe) ){
5496 let (ident, item_, extra_attrs) =
5497 try!(self.parse_item_fn(unsafety, Constness::Const, abi::Rust));
5498 let last_span = self.last_span;
5499 let item = self.mk_item(lo,
5504 maybe_append(attrs, extra_attrs));
5505 return Ok(Some(item));
5509 if try!(self.eat_keyword(keywords::Mut) ){
5510 let last_span = self.last_span;
5511 self.diagnostic().struct_span_err(last_span, "const globals cannot be mutable")
5512 .fileline_help(last_span, "did you mean to declare a static?")
5515 let (ident, item_, extra_attrs) = try!(self.parse_item_const(None));
5516 let last_span = self.last_span;
5517 let item = self.mk_item(lo,
5522 maybe_append(attrs, extra_attrs));
5523 return Ok(Some(item));
5525 if self.check_keyword(keywords::Unsafe) &&
5526 self.look_ahead(1, |t| t.is_keyword(keywords::Trait))
5528 // UNSAFE TRAIT ITEM
5529 try!(self.expect_keyword(keywords::Unsafe));
5530 try!(self.expect_keyword(keywords::Trait));
5531 let (ident, item_, extra_attrs) =
5532 try!(self.parse_item_trait(ast::Unsafety::Unsafe));
5533 let last_span = self.last_span;
5534 let item = self.mk_item(lo,
5539 maybe_append(attrs, extra_attrs));
5540 return Ok(Some(item));
5542 if self.check_keyword(keywords::Unsafe) &&
5543 self.look_ahead(1, |t| t.is_keyword(keywords::Impl))
5546 try!(self.expect_keyword(keywords::Unsafe));
5547 try!(self.expect_keyword(keywords::Impl));
5548 let (ident, item_, extra_attrs) = try!(self.parse_item_impl(ast::Unsafety::Unsafe));
5549 let last_span = self.last_span;
5550 let item = self.mk_item(lo,
5555 maybe_append(attrs, extra_attrs));
5556 return Ok(Some(item));
5558 if self.check_keyword(keywords::Fn) {
5561 let (ident, item_, extra_attrs) =
5562 try!(self.parse_item_fn(Unsafety::Normal, Constness::NotConst, abi::Rust));
5563 let last_span = self.last_span;
5564 let item = self.mk_item(lo,
5569 maybe_append(attrs, extra_attrs));
5570 return Ok(Some(item));
5572 if self.check_keyword(keywords::Unsafe)
5573 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
5574 // UNSAFE FUNCTION ITEM
5576 let abi = if try!(self.eat_keyword(keywords::Extern) ){
5577 try!(self.parse_opt_abi()).unwrap_or(abi::C)
5581 try!(self.expect_keyword(keywords::Fn));
5582 let (ident, item_, extra_attrs) =
5583 try!(self.parse_item_fn(Unsafety::Unsafe, Constness::NotConst, abi));
5584 let last_span = self.last_span;
5585 let item = self.mk_item(lo,
5590 maybe_append(attrs, extra_attrs));
5591 return Ok(Some(item));
5593 if try!(self.eat_keyword(keywords::Mod) ){
5595 let (ident, item_, extra_attrs) =
5596 try!(self.parse_item_mod(&attrs[..]));
5597 let last_span = self.last_span;
5598 let item = self.mk_item(lo,
5603 maybe_append(attrs, extra_attrs));
5604 return Ok(Some(item));
5606 if try!(self.eat_keyword(keywords::Type) ){
5608 let (ident, item_, extra_attrs) = try!(self.parse_item_type());
5609 let last_span = self.last_span;
5610 let item = self.mk_item(lo,
5615 maybe_append(attrs, extra_attrs));
5616 return Ok(Some(item));
5618 if try!(self.eat_keyword(keywords::Enum) ){
5620 let (ident, item_, extra_attrs) = try!(self.parse_item_enum());
5621 let last_span = self.last_span;
5622 let item = self.mk_item(lo,
5627 maybe_append(attrs, extra_attrs));
5628 return Ok(Some(item));
5630 if try!(self.eat_keyword(keywords::Trait) ){
5632 let (ident, item_, extra_attrs) =
5633 try!(self.parse_item_trait(ast::Unsafety::Normal));
5634 let last_span = self.last_span;
5635 let item = self.mk_item(lo,
5640 maybe_append(attrs, extra_attrs));
5641 return Ok(Some(item));
5643 if try!(self.eat_keyword(keywords::Impl) ){
5645 let (ident, item_, extra_attrs) = try!(self.parse_item_impl(ast::Unsafety::Normal));
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 try!(self.eat_keyword(keywords::Struct) ){
5657 let (ident, item_, extra_attrs) = try!(self.parse_item_struct());
5658 let last_span = self.last_span;
5659 let item = self.mk_item(lo,
5664 maybe_append(attrs, extra_attrs));
5665 return Ok(Some(item));
5667 self.parse_macro_use_or_failure(attrs,macros_allowed,attributes_allowed,lo,visibility)
5670 /// Parse a foreign item.
5671 fn parse_foreign_item(&mut self) -> PResult<'a, Option<P<ForeignItem>>> {
5672 let attrs = try!(self.parse_outer_attributes());
5673 let lo = self.span.lo;
5674 let visibility = try!(self.parse_visibility());
5676 if self.check_keyword(keywords::Static) {
5677 // FOREIGN STATIC ITEM
5678 return Ok(Some(try!(self.parse_item_foreign_static(visibility, lo, attrs))));
5680 if self.check_keyword(keywords::Fn) || self.check_keyword(keywords::Unsafe) {
5681 // FOREIGN FUNCTION ITEM
5682 return Ok(Some(try!(self.parse_item_foreign_fn(visibility, lo, attrs))));
5685 // FIXME #5668: this will occur for a macro invocation:
5686 match try!(self.parse_macro_use_or_failure(attrs, true, false, lo, visibility)) {
5688 return Err(self.span_fatal(item.span, "macros cannot expand to foreign items"));
5694 /// This is the fall-through for parsing items.
5695 fn parse_macro_use_or_failure(
5697 attrs: Vec<Attribute> ,
5698 macros_allowed: bool,
5699 attributes_allowed: bool,
5701 visibility: Visibility
5702 ) -> PResult<'a, Option<P<Item>>> {
5703 if macros_allowed && !self.token.is_any_keyword()
5704 && self.look_ahead(1, |t| *t == token::Not)
5705 && (self.look_ahead(2, |t| t.is_plain_ident())
5706 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren))
5707 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) {
5708 // MACRO INVOCATION ITEM
5710 let last_span = self.last_span;
5711 self.complain_if_pub_macro(visibility, last_span);
5713 let mac_lo = self.span.lo;
5716 let pth = try!(self.parse_path(NoTypesAllowed));
5717 try!(self.expect(&token::Not));
5719 // a 'special' identifier (like what `macro_rules!` uses)
5720 // is optional. We should eventually unify invoc syntax
5722 let id = if self.token.is_plain_ident() {
5723 try!(self.parse_ident())
5725 token::special_idents::invalid // no special identifier
5727 // eat a matched-delimiter token tree:
5728 let delim = try!(self.expect_open_delim());
5729 let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
5731 |p| p.parse_token_tree()));
5732 // single-variant-enum... :
5733 let m = Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT };
5734 let m: ast::Mac = codemap::Spanned { node: m,
5736 self.last_span.hi) };
5738 if delim != token::Brace {
5739 if !try!(self.eat(&token::Semi) ){
5740 let last_span = self.last_span;
5741 self.span_err(last_span,
5742 "macros that expand to items must either \
5743 be surrounded with braces or followed by \
5748 let item_ = ItemMac(m);
5749 let last_span = self.last_span;
5750 let item = self.mk_item(lo,
5756 return Ok(Some(item));
5759 // FAILURE TO PARSE ITEM
5763 let last_span = self.last_span;
5764 return Err(self.span_fatal(last_span, "unmatched visibility `pub`"));
5768 if !attributes_allowed && !attrs.is_empty() {
5769 self.expected_item_err(&attrs);
5774 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
5775 let attrs = try!(self.parse_outer_attributes());
5776 self.parse_item_(attrs, true, false)
5780 /// Matches view_path : MOD? non_global_path as IDENT
5781 /// | MOD? non_global_path MOD_SEP LBRACE RBRACE
5782 /// | MOD? non_global_path MOD_SEP LBRACE ident_seq RBRACE
5783 /// | MOD? non_global_path MOD_SEP STAR
5784 /// | MOD? non_global_path
5785 fn parse_view_path(&mut self) -> PResult<'a, P<ViewPath>> {
5786 let lo = self.span.lo;
5788 // Allow a leading :: because the paths are absolute either way.
5789 // This occurs with "use $crate::..." in macros.
5790 try!(self.eat(&token::ModSep));
5792 if self.check(&token::OpenDelim(token::Brace)) {
5794 let idents = try!(self.parse_unspanned_seq(
5795 &token::OpenDelim(token::Brace),
5796 &token::CloseDelim(token::Brace),
5797 seq_sep_trailing_allowed(token::Comma),
5798 |p| p.parse_path_list_item()));
5799 let path = ast::Path {
5800 span: mk_sp(lo, self.span.hi),
5802 segments: Vec::new()
5804 return Ok(P(spanned(lo, self.span.hi, ViewPathList(path, idents))));
5807 let first_ident = try!(self.parse_ident());
5808 let mut path = vec!(first_ident);
5809 if let token::ModSep = self.token {
5810 // foo::bar or foo::{a,b,c} or foo::*
5811 while self.check(&token::ModSep) {
5815 token::Ident(..) => {
5816 let ident = try!(self.parse_ident());
5820 // foo::bar::{a,b,c}
5821 token::OpenDelim(token::Brace) => {
5822 let idents = try!(self.parse_unspanned_seq(
5823 &token::OpenDelim(token::Brace),
5824 &token::CloseDelim(token::Brace),
5825 seq_sep_trailing_allowed(token::Comma),
5826 |p| p.parse_path_list_item()
5828 let path = ast::Path {
5829 span: mk_sp(lo, self.span.hi),
5831 segments: path.into_iter().map(|identifier| {
5833 identifier: identifier,
5834 parameters: ast::PathParameters::none(),
5838 return Ok(P(spanned(lo, self.span.hi, ViewPathList(path, idents))));
5842 token::BinOp(token::Star) => {
5844 let path = ast::Path {
5845 span: mk_sp(lo, self.span.hi),
5847 segments: path.into_iter().map(|identifier| {
5849 identifier: identifier,
5850 parameters: ast::PathParameters::none(),
5854 return Ok(P(spanned(lo, self.span.hi, ViewPathGlob(path))));
5857 // fall-through for case foo::bar::;
5859 self.span_err(self.span, "expected identifier or `{` or `*`, found `;`");
5866 let mut rename_to = path[path.len() - 1];
5867 let path = ast::Path {
5868 span: mk_sp(lo, self.last_span.hi),
5870 segments: path.into_iter().map(|identifier| {
5872 identifier: identifier,
5873 parameters: ast::PathParameters::none(),
5877 rename_to = try!(self.parse_rename()).unwrap_or(rename_to);
5878 Ok(P(spanned(lo, self.last_span.hi, ViewPathSimple(rename_to, path))))
5881 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
5882 if try!(self.eat_keyword(keywords::As)) {
5883 self.parse_ident().map(Some)
5889 /// Parses a source module as a crate. This is the main
5890 /// entry point for the parser.
5891 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
5892 let lo = self.span.lo;
5894 attrs: try!(self.parse_inner_attributes()),
5895 module: try!(self.parse_mod_items(&token::Eof, lo)),
5896 config: self.cfg.clone(),
5897 span: mk_sp(lo, self.span.lo),
5898 exported_macros: Vec::new(),
5902 pub fn parse_optional_str(&mut self)
5903 -> PResult<'a, Option<(InternedString,
5905 Option<ast::Name>)>> {
5906 let ret = match self.token {
5907 token::Literal(token::Str_(s), suf) => {
5908 (self.id_to_interned_str(ast::Ident::with_empty_ctxt(s)), ast::CookedStr, suf)
5910 token::Literal(token::StrRaw(s, n), suf) => {
5911 (self.id_to_interned_str(ast::Ident::with_empty_ctxt(s)), ast::RawStr(n), suf)
5913 _ => return Ok(None)
5919 pub fn parse_str(&mut self) -> PResult<'a, (InternedString, StrStyle)> {
5920 match try!(self.parse_optional_str()) {
5921 Some((s, style, suf)) => {
5922 let sp = self.last_span;
5923 self.expect_no_suffix(sp, "string literal", suf);
5926 _ => Err(self.fatal("expected string literal"))