1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 pub use self::PathParsingMode::*;
15 use ast::{RegionTyParamBound, TraitTyParamBound, TraitBoundModifier};
16 use ast::{Public, Unsafety};
17 use ast::{Mod, BiAdd, Arg, Arm, Attribute, BindingMode};
18 use ast::{BiBitAnd, BiBitOr, BiBitXor, BiRem, BiLt, Block};
19 use ast::{BlockCheckMode, CaptureByRef, CaptureByValue, CaptureClause};
20 use ast::{Constness, ConstTraitItem, Crate, CrateConfig};
21 use ast::{Decl, DeclItem, DeclLocal, DefaultBlock, DefaultReturn};
22 use ast::{UnDeref, BiDiv, EMPTY_CTXT, EnumDef, ExplicitSelf};
23 use ast::{Expr, Expr_, ExprAddrOf, ExprMatch, ExprAgain};
24 use ast::{ExprAssign, ExprAssignOp, ExprBinary, ExprBlock, ExprBox};
25 use ast::{ExprBreak, ExprCall, ExprCast, ExprInPlace};
26 use ast::{ExprField, ExprTupField, ExprClosure, ExprIf, ExprIfLet, ExprIndex};
27 use ast::{ExprLit, ExprLoop, ExprMac, ExprRange};
28 use ast::{ExprMethodCall, ExprParen, ExprPath};
29 use ast::{ExprRepeat, ExprRet, ExprStruct, ExprTup, ExprType, ExprUnary};
30 use ast::{ExprVec, ExprWhile, ExprWhileLet, ExprForLoop, Field, FnDecl};
31 use ast::{ForeignItem, ForeignItemStatic, ForeignItemFn, FunctionRetTy};
32 use ast::{Ident, Inherited, ImplItem, Item, Item_, ItemStatic};
33 use ast::{ItemEnum, ItemFn, ItemForeignMod, ItemImpl, ItemConst};
34 use ast::{ItemMac, ItemMod, ItemStruct, ItemTrait, ItemTy, ItemDefaultImpl};
35 use ast::{ItemExternCrate, ItemUse};
37 use ast::{LitBool, LitChar, LitByte, LitByteStr};
38 use ast::{LitStr, LitInt, Local};
39 use ast::{MacStmtWithBraces, MacStmtWithSemicolon, MacStmtWithoutBraces};
40 use ast::{MutImmutable, MutMutable, Mac_};
41 use ast::{MutTy, BiMul, Mutability};
42 use ast::{NamedField, UnNeg, NoReturn, UnNot};
43 use ast::{Pat, PatBox, PatEnum, PatIdent, PatLit, PatQPath, PatMac, PatRange};
44 use ast::{PatRegion, PatStruct, PatTup, PatVec, PatWild};
45 use ast::{PolyTraitRef, QSelf};
46 use ast::{Return, BiShl, BiShr, Stmt, StmtDecl};
47 use ast::{StmtExpr, StmtSemi, StmtMac, VariantData, StructField};
48 use ast::{BiSub, StrStyle};
49 use ast::{SelfExplicit, SelfRegion, SelfStatic, SelfValue};
50 use ast::{Delimited, SequenceRepetition, TokenTree, TraitItem, TraitRef};
51 use ast::{Ty, Ty_, TypeBinding, TyMac};
52 use ast::{TyFixedLengthVec, TyBareFn, TyTypeof, TyInfer};
53 use ast::{TyParam, TyParamBounds, TyParen, TyPath, TyPtr};
54 use ast::{TyRptr, TyTup, TyU32, TyVec};
55 use ast::TypeTraitItem;
56 use ast::{UnnamedField, UnsafeBlock};
57 use ast::{ViewPath, ViewPathGlob, ViewPathList, ViewPathSimple};
58 use ast::{Visibility, WhereClause};
59 use attr::{ThinAttributes, ThinAttributesExt, AttributesExt};
61 use ast_util::{self, ident_to_path};
62 use codemap::{self, Span, BytePos, Spanned, spanned, mk_sp, CodeMap};
63 use errors::{self, DiagnosticBuilder};
64 use ext::tt::macro_parser;
67 use parse::common::{SeqSep, seq_sep_none, seq_sep_trailing_allowed};
68 use parse::lexer::{Reader, TokenAndSpan};
69 use parse::obsolete::{ParserObsoleteMethods, ObsoleteSyntax};
70 use parse::token::{self, intern, MatchNt, SubstNt, SpecialVarNt, InternedString};
71 use parse::token::{keywords, special_idents, SpecialMacroVar};
72 use parse::{new_sub_parser_from_file, ParseSess};
73 use util::parser::{AssocOp, Fixity};
78 use std::collections::HashSet;
79 use std::io::prelude::*;
81 use std::path::{Path, PathBuf};
86 flags Restrictions: u8 {
87 const RESTRICTION_STMT_EXPR = 1 << 0,
88 const RESTRICTION_NO_STRUCT_LITERAL = 1 << 1,
92 type ItemInfo = (Ident, Item_, Option<Vec<Attribute> >);
94 /// How to parse a path. There are four different kinds of paths, all of which
95 /// are parsed somewhat differently.
96 #[derive(Copy, Clone, PartialEq)]
97 pub enum PathParsingMode {
98 /// A path with no type parameters; e.g. `foo::bar::Baz`
100 /// A path with a lifetime and type parameters, with no double colons
101 /// before the type parameters; e.g. `foo::bar<'a>::Baz<T>`
102 LifetimeAndTypesWithoutColons,
103 /// A path with a lifetime and type parameters with double colons before
104 /// the type parameters; e.g. `foo::bar::<'a>::Baz::<T>`
105 LifetimeAndTypesWithColons,
108 /// How to parse a bound, whether to allow bound modifiers such as `?`.
109 #[derive(Copy, Clone, PartialEq)]
110 pub enum BoundParsingMode {
115 /// `pub` should be parsed in struct fields and not parsed in variant fields
116 #[derive(Clone, Copy, PartialEq)]
122 /// Possibly accept an `token::Interpolated` expression (a pre-parsed expression
123 /// dropped into the token stream, which happens while parsing the result of
124 /// macro expansion). Placement of these is not as complex as I feared it would
125 /// be. The important thing is to make sure that lookahead doesn't balk at
126 /// `token::Interpolated` tokens.
127 macro_rules! maybe_whole_expr {
130 let found = match $p.token {
131 token::Interpolated(token::NtExpr(ref e)) => {
134 token::Interpolated(token::NtPath(_)) => {
135 // FIXME: The following avoids an issue with lexical borrowck scopes,
136 // but the clone is unfortunate.
137 let pt = match $p.token {
138 token::Interpolated(token::NtPath(ref pt)) => (**pt).clone(),
142 Some($p.mk_expr(span.lo, span.hi, ExprPath(None, pt), None))
144 token::Interpolated(token::NtBlock(_)) => {
145 // FIXME: The following avoids an issue with lexical borrowck scopes,
146 // but the clone is unfortunate.
147 let b = match $p.token {
148 token::Interpolated(token::NtBlock(ref b)) => (*b).clone(),
152 Some($p.mk_expr(span.lo, span.hi, ExprBlock(b), None))
167 /// As maybe_whole_expr, but for things other than expressions
168 macro_rules! maybe_whole {
169 ($p:expr, $constructor:ident) => (
171 let found = match ($p).token {
172 token::Interpolated(token::$constructor(_)) => {
173 Some(($p).bump_and_get())
177 if let Some(token::Interpolated(token::$constructor(x))) = found {
178 return Ok(x.clone());
182 (no_clone $p:expr, $constructor:ident) => (
184 let found = match ($p).token {
185 token::Interpolated(token::$constructor(_)) => {
186 Some(($p).bump_and_get())
190 if let Some(token::Interpolated(token::$constructor(x))) = found {
195 (deref $p:expr, $constructor:ident) => (
197 let found = match ($p).token {
198 token::Interpolated(token::$constructor(_)) => {
199 Some(($p).bump_and_get())
203 if let Some(token::Interpolated(token::$constructor(x))) = found {
204 return Ok((*x).clone());
208 (Some deref $p:expr, $constructor:ident) => (
210 let found = match ($p).token {
211 token::Interpolated(token::$constructor(_)) => {
212 Some(($p).bump_and_get())
216 if let Some(token::Interpolated(token::$constructor(x))) = found {
217 return Ok(Some((*x).clone()));
221 (pair_empty $p:expr, $constructor:ident) => (
223 let found = match ($p).token {
224 token::Interpolated(token::$constructor(_)) => {
225 Some(($p).bump_and_get())
229 if let Some(token::Interpolated(token::$constructor(x))) = found {
230 return Ok((Vec::new(), x));
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<T>(&self, t: &token::Token) -> PResult<'a, T> {
396 let token_str = Parser::token_to_string(t);
397 let last_span = self.last_span;
398 Err(self.span_fatal(last_span, &format!("unexpected token: `{}`", token_str)))
401 pub fn unexpected<T>(&mut self) -> PResult<'a, T> {
402 match self.expect_one_of(&[], &[]) {
404 Ok(_) => unreachable!(),
408 /// Expect and consume the token t. Signal an error if
409 /// the next token is not t.
410 pub fn expect(&mut self, t: &token::Token) -> PResult<'a, ()> {
411 if self.expected_tokens.is_empty() {
412 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) {
453 } else if inedible.contains(&self.token) {
454 // leave it in the input
457 let mut expected = edible.iter()
458 .map(|x| TokenType::Token(x.clone()))
459 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
460 .chain(self.expected_tokens.iter().cloned())
461 .collect::<Vec<_>>();
462 expected.sort_by(|a, b| a.to_string().cmp(&b.to_string()));
464 let expect = tokens_to_string(&expected[..]);
465 let actual = self.this_token_to_string();
467 &(if expected.len() > 1 {
468 (format!("expected one of {}, found `{}`",
471 } else if expected.is_empty() {
472 (format!("unexpected token: `{}`",
475 (format!("expected {}, found `{}`",
483 /// Check for erroneous `ident { }`; if matches, signal error and
484 /// recover (without consuming any expected input token). Returns
485 /// true if and only if input was consumed for recovery.
486 pub fn check_for_erroneous_unit_struct_expecting(&mut self,
487 expected: &[token::Token])
489 if self.token == token::OpenDelim(token::Brace)
490 && expected.iter().all(|t| *t != token::OpenDelim(token::Brace))
491 && self.look_ahead(1, |t| *t == token::CloseDelim(token::Brace)) {
492 // matched; signal non-fatal error and recover.
493 let span = self.span;
494 self.span_err(span, "unit-like struct construction is written with no trailing `{ }`");
495 self.eat(&token::OpenDelim(token::Brace));
496 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 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 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 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 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) -> bool {
599 let is_present = self.check(tok);
600 if is_present { 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) -> bool {
612 if self.check_keyword(kw) {
620 pub fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> 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 !self.eat_keyword(kw) {
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) {
653 if self.token.is_reserved_keyword() {
654 let token_str = self.this_token_to_string();
655 self.fatal(&format!("`{}` is a reserved keyword", token_str)).emit()
659 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
660 /// `&` and continue. If an `&` is not seen, signal an error.
661 fn expect_and(&mut self) -> PResult<'a, ()> {
662 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
664 token::BinOp(token::And) => {
669 let span = self.span;
670 let lo = span.lo + BytePos(1);
671 Ok(self.replace_token(token::BinOp(token::And), lo, span.hi))
673 _ => self.unexpected()
677 pub fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
679 None => {/* everything ok */}
681 let text = suf.as_str();
683 self.span_bug(sp, "found empty literal suffix in Some")
685 self.span_err(sp, &*format!("{} with a suffix is invalid", kind));
691 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
692 /// `<` and continue. If a `<` is not seen, return false.
694 /// This is meant to be used when parsing generics on a path to get the
696 fn eat_lt(&mut self) -> bool {
697 self.expected_tokens.push(TokenType::Token(token::Lt));
703 token::BinOp(token::Shl) => {
704 let span = self.span;
705 let lo = span.lo + BytePos(1);
706 self.replace_token(token::Lt, lo, span.hi);
713 fn expect_lt(&mut self) -> PResult<'a, ()> {
721 /// Expect and consume a GT. if a >> is seen, replace it
722 /// with a single > and continue. If a GT is not seen,
724 pub fn expect_gt(&mut self) -> PResult<'a, ()> {
725 self.expected_tokens.push(TokenType::Token(token::Gt));
731 token::BinOp(token::Shr) => {
732 let span = self.span;
733 let lo = span.lo + BytePos(1);
734 Ok(self.replace_token(token::Gt, lo, span.hi))
736 token::BinOpEq(token::Shr) => {
737 let span = self.span;
738 let lo = span.lo + BytePos(1);
739 Ok(self.replace_token(token::Ge, lo, span.hi))
742 let span = self.span;
743 let lo = span.lo + BytePos(1);
744 Ok(self.replace_token(token::Eq, lo, span.hi))
747 let gt_str = Parser::token_to_string(&token::Gt);
748 let this_token_str = self.this_token_to_string();
749 Err(self.fatal(&format!("expected `{}`, found `{}`",
756 pub fn parse_seq_to_before_gt_or_return<T, F>(&mut self,
757 sep: Option<token::Token>,
759 -> PResult<'a, (P<[T]>, bool)>
760 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
762 let mut v = Vec::new();
763 // This loop works by alternating back and forth between parsing types
764 // and commas. For example, given a string `A, B,>`, the parser would
765 // first parse `A`, then a comma, then `B`, then a comma. After that it
766 // would encounter a `>` and stop. This lets the parser handle trailing
767 // commas in generic parameters, because it can stop either after
768 // parsing a type or after parsing a comma.
770 if self.check(&token::Gt)
771 || self.token == token::BinOp(token::Shr)
772 || self.token == token::Ge
773 || self.token == token::BinOpEq(token::Shr) {
778 match try!(f(self)) {
779 Some(result) => v.push(result),
780 None => return Ok((P::from_vec(v), true))
783 if let Some(t) = sep.as_ref() {
784 try!(self.expect(t));
789 return Ok((P::from_vec(v), false));
792 /// Parse a sequence bracketed by '<' and '>', stopping
794 pub fn parse_seq_to_before_gt<T, F>(&mut self,
795 sep: Option<token::Token>,
797 -> PResult<'a, P<[T]>> where
798 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
800 let (result, returned) = try!(self.parse_seq_to_before_gt_or_return(sep,
801 |p| Ok(Some(try!(f(p))))));
806 pub fn parse_seq_to_gt<T, F>(&mut self,
807 sep: Option<token::Token>,
809 -> PResult<'a, P<[T]>> where
810 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
812 let v = try!(self.parse_seq_to_before_gt(sep, f));
813 try!(self.expect_gt());
817 pub fn parse_seq_to_gt_or_return<T, F>(&mut self,
818 sep: Option<token::Token>,
820 -> PResult<'a, (P<[T]>, bool)> where
821 F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
823 let (v, returned) = try!(self.parse_seq_to_before_gt_or_return(sep, f));
825 try!(self.expect_gt());
827 return Ok((v, returned));
830 /// Parse a sequence, including the closing delimiter. The function
831 /// f must consume tokens until reaching the next separator or
833 pub fn parse_seq_to_end<T, F>(&mut self,
837 -> PResult<'a, Vec<T>> where
838 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
840 let val = try!(self.parse_seq_to_before_end(ket, sep, f));
845 /// Parse a sequence, not including the closing delimiter. The function
846 /// f must consume tokens until reaching the next separator or
848 pub fn parse_seq_to_before_end<T, F>(&mut self,
852 -> PResult<'a, Vec<T>> where
853 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
855 let mut first: bool = true;
857 while self.token != *ket {
860 if first { first = false; }
861 else { try!(self.expect(t)); }
865 if sep.trailing_sep_allowed && self.check(ket) { break; }
866 v.push(try!(f(self)));
871 /// Parse a sequence, including the closing delimiter. The function
872 /// f must consume tokens until reaching the next separator or
874 pub fn parse_unspanned_seq<T, F>(&mut self,
879 -> PResult<'a, Vec<T>> where
880 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
882 try!(self.expect(bra));
883 let result = try!(self.parse_seq_to_before_end(ket, sep, f));
888 /// Parse a sequence parameter of enum variant. For consistency purposes,
889 /// these should not be empty.
890 pub fn parse_enum_variant_seq<T, F>(&mut self,
895 -> PResult<'a, Vec<T>> where
896 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
898 let result = try!(self.parse_unspanned_seq(bra, ket, sep, f));
899 if result.is_empty() {
900 let last_span = self.last_span;
901 self.span_err(last_span,
902 "nullary enum variants are written with no trailing `( )`");
907 // NB: Do not use this function unless you actually plan to place the
908 // spanned list in the AST.
909 pub fn parse_seq<T, F>(&mut self,
914 -> PResult<'a, Spanned<Vec<T>>> where
915 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
917 let lo = self.span.lo;
918 try!(self.expect(bra));
919 let result = try!(self.parse_seq_to_before_end(ket, sep, f));
920 let hi = self.span.hi;
922 Ok(spanned(lo, hi, result))
925 /// Advance the parser by one token
926 pub fn bump(&mut self) {
927 self.last_span = self.span;
928 // Stash token for error recovery (sometimes; clone is not necessarily cheap).
929 self.last_token = if self.token.is_ident() ||
930 self.token.is_path() ||
931 self.token == token::Comma {
932 Some(Box::new(self.token.clone()))
936 let next = if self.buffer_start == self.buffer_end {
937 self.reader.real_token()
939 // Avoid token copies with `replace`.
940 let buffer_start = self.buffer_start as usize;
941 let next_index = (buffer_start + 1) & 3;
942 self.buffer_start = next_index as isize;
944 let placeholder = TokenAndSpan {
945 tok: token::Underscore,
948 mem::replace(&mut self.buffer[buffer_start], placeholder)
951 self.token = next.tok;
952 self.tokens_consumed += 1;
953 self.expected_tokens.clear();
954 // check after each token
955 self.check_unknown_macro_variable();
958 /// Advance the parser by one token and return the bumped token.
959 pub fn bump_and_get(&mut self) -> token::Token {
960 let old_token = mem::replace(&mut self.token, token::Underscore);
965 /// EFFECT: replace the current token and span with the given one
966 pub fn replace_token(&mut self,
970 self.last_span = mk_sp(self.span.lo, lo);
972 self.span = mk_sp(lo, hi);
974 pub fn buffer_length(&mut self) -> isize {
975 if self.buffer_start <= self.buffer_end {
976 return self.buffer_end - self.buffer_start;
978 return (4 - self.buffer_start) + self.buffer_end;
980 pub fn look_ahead<R, F>(&mut self, distance: usize, f: F) -> R where
981 F: FnOnce(&token::Token) -> R,
983 let dist = distance as isize;
984 while self.buffer_length() < dist {
985 self.buffer[self.buffer_end as usize] = self.reader.real_token();
986 self.buffer_end = (self.buffer_end + 1) & 3;
988 f(&self.buffer[((self.buffer_start + dist - 1) & 3) as usize].tok)
990 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
991 self.sess.span_diagnostic.struct_span_fatal(self.span, m)
993 pub fn span_fatal(&self, sp: Span, m: &str) -> DiagnosticBuilder<'a> {
994 self.sess.span_diagnostic.struct_span_fatal(sp, m)
996 pub fn span_fatal_help(&self, sp: Span, m: &str, help: &str) -> DiagnosticBuilder<'a> {
997 let mut err = self.sess.span_diagnostic.struct_span_fatal(sp, m);
998 err.fileline_help(sp, help);
1001 pub fn bug(&self, m: &str) -> ! {
1002 self.sess.span_diagnostic.span_bug(self.span, m)
1004 pub fn warn(&self, m: &str) {
1005 self.sess.span_diagnostic.span_warn(self.span, m)
1007 pub fn span_warn(&self, sp: Span, m: &str) {
1008 self.sess.span_diagnostic.span_warn(sp, m)
1010 pub fn span_err(&self, sp: Span, m: &str) {
1011 self.sess.span_diagnostic.span_err(sp, m)
1013 pub fn span_bug(&self, sp: Span, m: &str) -> ! {
1014 self.sess.span_diagnostic.span_bug(sp, m)
1016 pub fn abort_if_errors(&self) {
1017 self.sess.span_diagnostic.abort_if_errors();
1020 pub fn diagnostic(&self) -> &'a errors::Handler {
1021 &self.sess.span_diagnostic
1024 pub fn id_to_interned_str(&mut self, id: Ident) -> InternedString {
1028 /// Is the current token one of the keywords that signals a bare function
1030 pub fn token_is_bare_fn_keyword(&mut self) -> bool {
1031 self.check_keyword(keywords::Fn) ||
1032 self.check_keyword(keywords::Unsafe) ||
1033 self.check_keyword(keywords::Extern)
1036 pub fn get_lifetime(&mut self) -> ast::Ident {
1038 token::Lifetime(ref ident) => *ident,
1039 _ => self.bug("not a lifetime"),
1043 pub fn parse_for_in_type(&mut self) -> PResult<'a, Ty_> {
1045 Parses whatever can come after a `for` keyword in a type.
1046 The `for` has already been consumed.
1050 - for <'lt> |S| -> T
1054 - for <'lt> [unsafe] [extern "ABI"] fn (S) -> T
1055 - for <'lt> path::foo(a, b)
1060 let lo = self.span.lo;
1062 let lifetime_defs = try!(self.parse_late_bound_lifetime_defs());
1064 // examine next token to decide to do
1065 if self.token_is_bare_fn_keyword() {
1066 self.parse_ty_bare_fn(lifetime_defs)
1068 let hi = self.span.hi;
1069 let trait_ref = try!(self.parse_trait_ref());
1070 let poly_trait_ref = ast::PolyTraitRef { bound_lifetimes: lifetime_defs,
1071 trait_ref: trait_ref,
1072 span: mk_sp(lo, hi)};
1073 let other_bounds = if self.eat(&token::BinOp(token::Plus)) {
1074 try!(self.parse_ty_param_bounds(BoundParsingMode::Bare))
1079 Some(TraitTyParamBound(poly_trait_ref, TraitBoundModifier::None)).into_iter()
1080 .chain(other_bounds.into_vec())
1082 Ok(ast::TyPolyTraitRef(all_bounds))
1086 pub fn parse_ty_path(&mut self) -> PResult<'a, Ty_> {
1087 Ok(TyPath(None, try!(self.parse_path(LifetimeAndTypesWithoutColons))))
1090 /// parse a TyBareFn type:
1091 pub fn parse_ty_bare_fn(&mut self, lifetime_defs: Vec<ast::LifetimeDef>) -> PResult<'a, Ty_> {
1094 [unsafe] [extern "ABI"] fn <'lt> (S) -> T
1095 ^~~~^ ^~~~^ ^~~~^ ^~^ ^
1098 | | | Argument types
1104 let unsafety = try!(self.parse_unsafety());
1105 let abi = if self.eat_keyword(keywords::Extern) {
1106 try!(self.parse_opt_abi()).unwrap_or(abi::C)
1111 try!(self.expect_keyword(keywords::Fn));
1112 let (inputs, variadic) = try!(self.parse_fn_args(false, true));
1113 let ret_ty = try!(self.parse_ret_ty());
1114 let decl = P(FnDecl {
1119 Ok(TyBareFn(P(BareFnTy {
1122 lifetimes: lifetime_defs,
1127 /// Parses an obsolete closure kind (`&:`, `&mut:`, or `:`).
1128 pub fn parse_obsolete_closure_kind(&mut self) -> PResult<'a, ()> {
1129 let lo = self.span.lo;
1131 self.check(&token::BinOp(token::And)) &&
1132 self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
1133 self.look_ahead(2, |t| *t == token::Colon)
1139 self.token == token::BinOp(token::And) &&
1140 self.look_ahead(1, |t| *t == token::Colon)
1145 self.eat(&token::Colon)
1152 let span = mk_sp(lo, self.span.hi);
1153 self.obsolete(span, ObsoleteSyntax::ClosureKind);
1157 pub fn parse_unsafety(&mut self) -> PResult<'a, Unsafety> {
1158 if self.eat_keyword(keywords::Unsafe) {
1159 return Ok(Unsafety::Unsafe);
1161 return Ok(Unsafety::Normal);
1165 /// Parse the items in a trait declaration
1166 pub fn parse_trait_items(&mut self) -> PResult<'a, Vec<P<TraitItem>>> {
1167 self.parse_unspanned_seq(
1168 &token::OpenDelim(token::Brace),
1169 &token::CloseDelim(token::Brace),
1171 |p| -> PResult<'a, P<TraitItem>> {
1172 maybe_whole!(no_clone p, NtTraitItem);
1173 let mut attrs = try!(p.parse_outer_attributes());
1176 let (name, node) = if p.eat_keyword(keywords::Type) {
1177 let TyParam {ident, bounds, default, ..} = try!(p.parse_ty_param());
1178 try!(p.expect(&token::Semi));
1179 (ident, TypeTraitItem(bounds, default))
1180 } else if p.is_const_item() {
1181 try!(p.expect_keyword(keywords::Const));
1182 let ident = try!(p.parse_ident());
1183 try!(p.expect(&token::Colon));
1184 let ty = try!(p.parse_ty_sum());
1185 let default = if p.check(&token::Eq) {
1187 let expr = try!(p.parse_expr());
1188 try!(p.commit_expr_expecting(&expr, token::Semi));
1191 try!(p.expect(&token::Semi));
1194 (ident, ConstTraitItem(ty, default))
1196 let (constness, unsafety, abi) = try!(p.parse_fn_front_matter());
1198 let ident = try!(p.parse_ident());
1199 let mut generics = try!(p.parse_generics());
1201 let (explicit_self, d) = try!(p.parse_fn_decl_with_self(|p: &mut Parser<'a>|{
1202 // This is somewhat dubious; We don't want to allow
1203 // argument names to be left off if there is a
1205 p.parse_arg_general(false)
1208 generics.where_clause = try!(p.parse_where_clause());
1209 let sig = ast::MethodSig {
1211 constness: constness,
1215 explicit_self: explicit_self,
1218 let body = match p.token {
1221 debug!("parse_trait_methods(): parsing required method");
1224 token::OpenDelim(token::Brace) => {
1225 debug!("parse_trait_methods(): parsing provided method");
1226 let (inner_attrs, body) =
1227 try!(p.parse_inner_attrs_and_block());
1228 attrs.extend(inner_attrs.iter().cloned());
1233 let token_str = p.this_token_to_string();
1234 return Err(p.fatal(&format!("expected `;` or `{{`, found `{}`",
1238 (ident, ast::MethodTraitItem(sig, body))
1242 id: ast::DUMMY_NODE_ID,
1246 span: mk_sp(lo, p.last_span.hi),
1251 /// Parse a possibly mutable type
1252 pub fn parse_mt(&mut self) -> PResult<'a, MutTy> {
1253 let mutbl = try!(self.parse_mutability());
1254 let t = try!(self.parse_ty());
1255 Ok(MutTy { ty: t, mutbl: mutbl })
1258 /// Parse optional return type [ -> TY ] in function decl
1259 pub fn parse_ret_ty(&mut self) -> PResult<'a, FunctionRetTy> {
1260 if self.eat(&token::RArrow) {
1261 if self.eat(&token::Not) {
1262 Ok(NoReturn(self.last_span))
1264 Ok(Return(try!(self.parse_ty())))
1267 let pos = self.span.lo;
1268 Ok(DefaultReturn(mk_sp(pos, pos)))
1272 /// Parse a type in a context where `T1+T2` is allowed.
1273 pub fn parse_ty_sum(&mut self) -> PResult<'a, P<Ty>> {
1274 let lo = self.span.lo;
1275 let lhs = try!(self.parse_ty());
1277 if !self.eat(&token::BinOp(token::Plus)) {
1281 let bounds = try!(self.parse_ty_param_bounds(BoundParsingMode::Bare));
1283 // In type grammar, `+` is treated like a binary operator,
1284 // and hence both L and R side are required.
1285 if bounds.is_empty() {
1286 let last_span = self.last_span;
1287 self.span_err(last_span,
1288 "at least one type parameter bound \
1289 must be specified");
1292 let sp = mk_sp(lo, self.last_span.hi);
1293 let sum = ast::TyObjectSum(lhs, bounds);
1294 Ok(P(Ty {id: ast::DUMMY_NODE_ID, node: sum, span: sp}))
1298 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1299 maybe_whole!(no_clone self, NtTy);
1301 let lo = self.span.lo;
1303 let t = if self.check(&token::OpenDelim(token::Paren)) {
1306 // (t) is a parenthesized ty
1307 // (t,) is the type of a tuple with only one field,
1309 let mut ts = vec![];
1310 let mut last_comma = false;
1311 while self.token != token::CloseDelim(token::Paren) {
1312 ts.push(try!(self.parse_ty_sum()));
1313 if self.check(&token::Comma) {
1322 try!(self.expect(&token::CloseDelim(token::Paren)));
1323 if ts.len() == 1 && !last_comma {
1324 TyParen(ts.into_iter().nth(0).unwrap())
1328 } else if self.check(&token::BinOp(token::Star)) {
1329 // STAR POINTER (bare pointer?)
1331 TyPtr(try!(self.parse_ptr()))
1332 } else if self.check(&token::OpenDelim(token::Bracket)) {
1334 try!(self.expect(&token::OpenDelim(token::Bracket)));
1335 let t = try!(self.parse_ty_sum());
1337 // Parse the `; e` in `[ i32; e ]`
1338 // where `e` is a const expression
1339 let t = match try!(self.maybe_parse_fixed_length_of_vec()) {
1341 Some(suffix) => TyFixedLengthVec(t, suffix)
1343 try!(self.expect(&token::CloseDelim(token::Bracket)));
1345 } else if self.check(&token::BinOp(token::And)) ||
1346 self.token == token::AndAnd {
1348 try!(self.expect_and());
1349 try!(self.parse_borrowed_pointee())
1350 } else if self.check_keyword(keywords::For) {
1351 try!(self.parse_for_in_type())
1352 } else if self.token_is_bare_fn_keyword() {
1354 try!(self.parse_ty_bare_fn(Vec::new()))
1355 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1357 // In order to not be ambiguous, the type must be surrounded by parens.
1358 try!(self.expect(&token::OpenDelim(token::Paren)));
1359 let e = try!(self.parse_expr());
1360 try!(self.expect(&token::CloseDelim(token::Paren)));
1362 } else if self.eat_lt() {
1365 try!(self.parse_qualified_path(NoTypesAllowed));
1367 TyPath(Some(qself), path)
1368 } else if self.check(&token::ModSep) ||
1369 self.token.is_ident() ||
1370 self.token.is_path() {
1371 let path = try!(self.parse_path(LifetimeAndTypesWithoutColons));
1372 if self.check(&token::Not) {
1375 let delim = try!(self.expect_open_delim());
1376 let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
1378 |p| p.parse_token_tree()));
1379 let hi = self.span.hi;
1380 TyMac(spanned(lo, hi, Mac_ { path: path, tts: tts, ctxt: EMPTY_CTXT }))
1385 } else if self.eat(&token::Underscore) {
1386 // TYPE TO BE INFERRED
1389 let this_token_str = self.this_token_to_string();
1390 let msg = format!("expected type, found `{}`", this_token_str);
1391 return Err(self.fatal(&msg[..]));
1394 let sp = mk_sp(lo, self.last_span.hi);
1395 Ok(P(Ty {id: ast::DUMMY_NODE_ID, node: t, span: sp}))
1398 pub fn parse_borrowed_pointee(&mut self) -> PResult<'a, Ty_> {
1399 // look for `&'lt` or `&'foo ` and interpret `foo` as the region name:
1400 let opt_lifetime = try!(self.parse_opt_lifetime());
1402 let mt = try!(self.parse_mt());
1403 return Ok(TyRptr(opt_lifetime, mt));
1406 pub fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1407 let mutbl = if self.eat_keyword(keywords::Mut) {
1409 } else if self.eat_keyword(keywords::Const) {
1412 let span = self.last_span;
1414 "bare raw pointers are no longer allowed, you should \
1415 likely use `*mut T`, but otherwise `*T` is now \
1416 known as `*const T`");
1419 let t = try!(self.parse_ty());
1420 Ok(MutTy { ty: t, mutbl: mutbl })
1423 pub fn is_named_argument(&mut self) -> bool {
1424 let offset = match self.token {
1425 token::BinOp(token::And) => 1,
1427 _ if self.token.is_keyword(keywords::Mut) => 1,
1431 debug!("parser is_named_argument offset:{}", offset);
1434 is_plain_ident_or_underscore(&self.token)
1435 && self.look_ahead(1, |t| *t == token::Colon)
1437 self.look_ahead(offset, |t| is_plain_ident_or_underscore(t))
1438 && self.look_ahead(offset + 1, |t| *t == token::Colon)
1442 /// This version of parse arg doesn't necessarily require
1443 /// identifier names.
1444 pub fn parse_arg_general(&mut self, require_name: bool) -> PResult<'a, Arg> {
1445 maybe_whole!(no_clone self, NtArg);
1447 let pat = if require_name || self.is_named_argument() {
1448 debug!("parse_arg_general parse_pat (require_name:{})",
1450 let pat = try!(self.parse_pat());
1452 try!(self.expect(&token::Colon));
1455 debug!("parse_arg_general ident_to_pat");
1456 ast_util::ident_to_pat(ast::DUMMY_NODE_ID,
1458 special_idents::invalid)
1461 let t = try!(self.parse_ty_sum());
1466 id: ast::DUMMY_NODE_ID,
1470 /// Parse a single function argument
1471 pub fn parse_arg(&mut self) -> PResult<'a, Arg> {
1472 self.parse_arg_general(true)
1475 /// Parse an argument in a lambda header e.g. |arg, arg|
1476 pub fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1477 let pat = try!(self.parse_pat());
1478 let t = if self.eat(&token::Colon) {
1479 try!(self.parse_ty_sum())
1482 id: ast::DUMMY_NODE_ID,
1484 span: mk_sp(self.span.lo, self.span.hi),
1490 id: ast::DUMMY_NODE_ID
1494 pub fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1495 if self.check(&token::Semi) {
1497 Ok(Some(try!(self.parse_expr())))
1503 /// Matches token_lit = LIT_INTEGER | ...
1504 pub fn lit_from_token(&self, tok: &token::Token) -> PResult<'a, Lit_> {
1506 token::Interpolated(token::NtExpr(ref v)) => {
1508 ExprLit(ref lit) => { Ok(lit.node.clone()) }
1509 _ => { return self.unexpected_last(tok); }
1512 token::Literal(lit, suf) => {
1513 let (suffix_illegal, out) = match lit {
1514 token::Byte(i) => (true, LitByte(parse::byte_lit(&i.as_str()).0)),
1515 token::Char(i) => (true, LitChar(parse::char_lit(&i.as_str()).0)),
1517 // there are some valid suffixes for integer and
1518 // float literals, so all the handling is done
1520 token::Integer(s) => {
1521 (false, parse::integer_lit(&s.as_str(),
1522 suf.as_ref().map(|s| s.as_str()),
1523 &self.sess.span_diagnostic,
1526 token::Float(s) => {
1527 (false, parse::float_lit(&s.as_str(),
1528 suf.as_ref().map(|s| s.as_str()),
1529 &self.sess.span_diagnostic,
1535 LitStr(token::intern_and_get_ident(&parse::str_lit(&s.as_str())),
1538 token::StrRaw(s, n) => {
1541 token::intern_and_get_ident(&parse::raw_str_lit(&s.as_str())),
1544 token::ByteStr(i) =>
1545 (true, LitByteStr(parse::byte_str_lit(&i.as_str()))),
1546 token::ByteStrRaw(i, _) =>
1548 LitByteStr(Rc::new(i.to_string().into_bytes()))),
1552 let sp = self.last_span;
1553 self.expect_no_suffix(sp, &*format!("{} literal", lit.short_name()), suf)
1558 _ => { return self.unexpected_last(tok); }
1562 /// Matches lit = true | false | token_lit
1563 pub fn parse_lit(&mut self) -> PResult<'a, Lit> {
1564 let lo = self.span.lo;
1565 let lit = if self.eat_keyword(keywords::True) {
1567 } else if self.eat_keyword(keywords::False) {
1570 let token = self.bump_and_get();
1571 let lit = try!(self.lit_from_token(&token));
1574 Ok(codemap::Spanned { node: lit, span: mk_sp(lo, self.last_span.hi) })
1577 /// matches '-' lit | lit
1578 pub fn parse_pat_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1579 let minus_lo = self.span.lo;
1580 let minus_present = self.eat(&token::BinOp(token::Minus));
1581 let lo = self.span.lo;
1582 let literal = P(try!(self.parse_lit()));
1583 let hi = self.last_span.hi;
1584 let expr = self.mk_expr(lo, hi, ExprLit(literal), None);
1587 let minus_hi = self.last_span.hi;
1588 let unary = self.mk_unary(UnNeg, expr);
1589 Ok(self.mk_expr(minus_lo, minus_hi, unary, None))
1595 /// Parses qualified path.
1597 /// Assumes that the leading `<` has been parsed already.
1599 /// Qualifed paths are a part of the universal function call
1602 /// `qualified_path = <type [as trait_ref]>::path`
1604 /// See `parse_path` for `mode` meaning.
1609 /// `<T as U>::F::a::<S>`
1610 pub fn parse_qualified_path(&mut self, mode: PathParsingMode)
1611 -> PResult<'a, (QSelf, ast::Path)> {
1612 let span = self.last_span;
1613 let self_type = try!(self.parse_ty_sum());
1614 let mut path = if self.eat_keyword(keywords::As) {
1615 try!(self.parse_path(LifetimeAndTypesWithoutColons))
1626 position: path.segments.len()
1629 try!(self.expect(&token::Gt));
1630 try!(self.expect(&token::ModSep));
1632 let segments = match mode {
1633 LifetimeAndTypesWithoutColons => {
1634 try!(self.parse_path_segments_without_colons())
1636 LifetimeAndTypesWithColons => {
1637 try!(self.parse_path_segments_with_colons())
1640 try!(self.parse_path_segments_without_types())
1643 path.segments.extend(segments);
1645 path.span.hi = self.last_span.hi;
1650 /// Parses a path and optional type parameter bounds, depending on the
1651 /// mode. The `mode` parameter determines whether lifetimes, types, and/or
1652 /// bounds are permitted and whether `::` must precede type parameter
1654 pub fn parse_path(&mut self, mode: PathParsingMode) -> PResult<'a, ast::Path> {
1655 // Check for a whole path...
1656 let found = match self.token {
1657 token::Interpolated(token::NtPath(_)) => Some(self.bump_and_get()),
1660 if let Some(token::Interpolated(token::NtPath(path))) = found {
1664 let lo = self.span.lo;
1665 let is_global = self.eat(&token::ModSep);
1667 // Parse any number of segments and bound sets. A segment is an
1668 // identifier followed by an optional lifetime and a set of types.
1669 // A bound set is a set of type parameter bounds.
1670 let segments = match mode {
1671 LifetimeAndTypesWithoutColons => {
1672 try!(self.parse_path_segments_without_colons())
1674 LifetimeAndTypesWithColons => {
1675 try!(self.parse_path_segments_with_colons())
1678 try!(self.parse_path_segments_without_types())
1682 // Assemble the span.
1683 let span = mk_sp(lo, self.last_span.hi);
1685 // Assemble the result.
1694 /// - `a::b<T,U>::c<V,W>`
1695 /// - `a::b<T,U>::c(V) -> W`
1696 /// - `a::b<T,U>::c(V)`
1697 pub fn parse_path_segments_without_colons(&mut self) -> PResult<'a, Vec<ast::PathSegment>> {
1698 let mut segments = Vec::new();
1700 // First, parse an identifier.
1701 let identifier = try!(self.parse_ident_or_self_type());
1703 // Parse types, optionally.
1704 let parameters = if self.eat_lt() {
1705 let (lifetimes, types, bindings) = try!(self.parse_generic_values_after_lt());
1707 ast::PathParameters::AngleBracketed(ast::AngleBracketedParameterData {
1708 lifetimes: lifetimes,
1709 types: P::from_vec(types),
1710 bindings: P::from_vec(bindings),
1712 } else if self.eat(&token::OpenDelim(token::Paren)) {
1713 let lo = self.last_span.lo;
1715 let inputs = try!(self.parse_seq_to_end(
1716 &token::CloseDelim(token::Paren),
1717 seq_sep_trailing_allowed(token::Comma),
1718 |p| p.parse_ty_sum()));
1720 let output_ty = if self.eat(&token::RArrow) {
1721 Some(try!(self.parse_ty()))
1726 let hi = self.last_span.hi;
1728 ast::PathParameters::Parenthesized(ast::ParenthesizedParameterData {
1729 span: mk_sp(lo, hi),
1734 ast::PathParameters::none()
1737 // Assemble and push the result.
1738 segments.push(ast::PathSegment { identifier: identifier,
1739 parameters: parameters });
1741 // Continue only if we see a `::`
1742 if !self.eat(&token::ModSep) {
1743 return Ok(segments);
1749 /// - `a::b::<T,U>::c`
1750 pub fn parse_path_segments_with_colons(&mut self) -> PResult<'a, Vec<ast::PathSegment>> {
1751 let mut segments = Vec::new();
1753 // First, parse an identifier.
1754 let identifier = try!(self.parse_ident_or_self_type());
1756 // If we do not see a `::`, stop.
1757 if !self.eat(&token::ModSep) {
1758 segments.push(ast::PathSegment {
1759 identifier: identifier,
1760 parameters: ast::PathParameters::none()
1762 return Ok(segments);
1765 // Check for a type segment.
1767 // Consumed `a::b::<`, go look for types
1768 let (lifetimes, types, bindings) = try!(self.parse_generic_values_after_lt());
1769 let parameters = ast::AngleBracketedParameterData {
1770 lifetimes: lifetimes,
1771 types: P::from_vec(types),
1772 bindings: P::from_vec(bindings),
1774 segments.push(ast::PathSegment {
1775 identifier: identifier,
1776 parameters: ast::PathParameters::AngleBracketed(parameters),
1779 // Consumed `a::b::<T,U>`, check for `::` before proceeding
1780 if !self.eat(&token::ModSep) {
1781 return Ok(segments);
1784 // Consumed `a::`, go look for `b`
1785 segments.push(ast::PathSegment {
1786 identifier: identifier,
1787 parameters: ast::PathParameters::none(),
1796 pub fn parse_path_segments_without_types(&mut self) -> PResult<'a, Vec<ast::PathSegment>> {
1797 let mut segments = Vec::new();
1799 // First, parse an identifier.
1800 let identifier = try!(self.parse_ident_or_self_type());
1802 // Assemble and push the result.
1803 segments.push(ast::PathSegment {
1804 identifier: identifier,
1805 parameters: ast::PathParameters::none()
1808 // If we do not see a `::`, stop.
1809 if !self.eat(&token::ModSep) {
1810 return Ok(segments);
1815 /// parses 0 or 1 lifetime
1816 pub fn parse_opt_lifetime(&mut self) -> PResult<'a, Option<ast::Lifetime>> {
1818 token::Lifetime(..) => {
1819 Ok(Some(try!(self.parse_lifetime())))
1827 /// Parses a single lifetime
1828 /// Matches lifetime = LIFETIME
1829 pub fn parse_lifetime(&mut self) -> PResult<'a, ast::Lifetime> {
1831 token::Lifetime(i) => {
1832 let span = self.span;
1834 return Ok(ast::Lifetime {
1835 id: ast::DUMMY_NODE_ID,
1841 return Err(self.fatal("expected a lifetime name"));
1846 /// Parses `lifetime_defs = [ lifetime_defs { ',' lifetime_defs } ]` where `lifetime_def =
1847 /// lifetime [':' lifetimes]`
1848 pub fn parse_lifetime_defs(&mut self) -> PResult<'a, Vec<ast::LifetimeDef>> {
1850 let mut res = Vec::new();
1853 token::Lifetime(_) => {
1854 let lifetime = try!(self.parse_lifetime());
1856 if self.eat(&token::Colon) {
1857 try!(self.parse_lifetimes(token::BinOp(token::Plus)))
1861 res.push(ast::LifetimeDef { lifetime: lifetime,
1871 token::Comma => { self.bump();}
1872 token::Gt => { return Ok(res); }
1873 token::BinOp(token::Shr) => { return Ok(res); }
1875 let this_token_str = self.this_token_to_string();
1876 let msg = format!("expected `,` or `>` after lifetime \
1879 return Err(self.fatal(&msg[..]));
1885 /// matches lifetimes = ( lifetime ) | ( lifetime , lifetimes ) actually, it matches the empty
1886 /// one too, but putting that in there messes up the grammar....
1888 /// Parses zero or more comma separated lifetimes. Expects each lifetime to be followed by
1889 /// either a comma or `>`. Used when parsing type parameter lists, where we expect something
1890 /// like `<'a, 'b, T>`.
1891 pub fn parse_lifetimes(&mut self, sep: token::Token) -> PResult<'a, Vec<ast::Lifetime>> {
1893 let mut res = Vec::new();
1896 token::Lifetime(_) => {
1897 res.push(try!(self.parse_lifetime()));
1904 if self.token != sep {
1912 /// Parse mutability declaration (mut/const/imm)
1913 pub fn parse_mutability(&mut self) -> PResult<'a, Mutability> {
1914 if self.eat_keyword(keywords::Mut) {
1921 /// Parse ident COLON expr
1922 pub fn parse_field(&mut self) -> PResult<'a, Field> {
1923 let lo = self.span.lo;
1924 let i = try!(self.parse_ident());
1925 let hi = self.last_span.hi;
1926 try!(self.expect(&token::Colon));
1927 let e = try!(self.parse_expr());
1929 ident: spanned(lo, hi, i),
1930 span: mk_sp(lo, e.span.hi),
1935 pub fn mk_expr(&mut self, lo: BytePos, hi: BytePos,
1936 node: Expr_, attrs: ThinAttributes) -> P<Expr> {
1938 id: ast::DUMMY_NODE_ID,
1940 span: mk_sp(lo, hi),
1945 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::Expr_ {
1946 ExprUnary(unop, expr)
1949 pub fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::Expr_ {
1950 ExprBinary(binop, lhs, rhs)
1953 pub fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::Expr_ {
1957 fn mk_method_call(&mut self,
1958 ident: ast::SpannedIdent,
1962 ExprMethodCall(ident, tps, args)
1965 pub fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::Expr_ {
1966 ExprIndex(expr, idx)
1969 pub fn mk_range(&mut self,
1970 start: Option<P<Expr>>,
1971 end: Option<P<Expr>>)
1973 ExprRange(start, end)
1976 pub fn mk_field(&mut self, expr: P<Expr>, ident: ast::SpannedIdent) -> ast::Expr_ {
1977 ExprField(expr, ident)
1980 pub fn mk_tup_field(&mut self, expr: P<Expr>, idx: codemap::Spanned<usize>) -> ast::Expr_ {
1981 ExprTupField(expr, idx)
1984 pub fn mk_assign_op(&mut self, binop: ast::BinOp,
1985 lhs: P<Expr>, rhs: P<Expr>) -> ast::Expr_ {
1986 ExprAssignOp(binop, lhs, rhs)
1989 pub fn mk_mac_expr(&mut self, lo: BytePos, hi: BytePos,
1990 m: Mac_, attrs: ThinAttributes) -> P<Expr> {
1992 id: ast::DUMMY_NODE_ID,
1993 node: ExprMac(codemap::Spanned {node: m, span: mk_sp(lo, hi)}),
1994 span: mk_sp(lo, hi),
1999 pub fn mk_lit_u32(&mut self, i: u32, attrs: ThinAttributes) -> P<Expr> {
2000 let span = &self.span;
2001 let lv_lit = P(codemap::Spanned {
2002 node: LitInt(i as u64, ast::UnsignedIntLit(TyU32)),
2007 id: ast::DUMMY_NODE_ID,
2008 node: ExprLit(lv_lit),
2014 fn expect_open_delim(&mut self) -> PResult<'a, token::DelimToken> {
2015 self.expected_tokens.push(TokenType::Token(token::Gt));
2017 token::OpenDelim(delim) => {
2021 _ => Err(self.fatal("expected open delimiter")),
2025 /// At the bottom (top?) of the precedence hierarchy,
2026 /// parse things like parenthesized exprs,
2027 /// macros, return, etc.
2029 /// NB: This does not parse outer attributes,
2030 /// and is private because it only works
2031 /// correctly if called from parse_dot_or_call_expr().
2032 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2033 maybe_whole_expr!(self);
2035 // Outer attributes are already parsed and will be
2036 // added to the return value after the fact.
2038 // Therefore, prevent sub-parser from parsing
2039 // attributes by giving them a empty "already parsed" list.
2040 let mut attrs = None;
2042 let lo = self.span.lo;
2043 let mut hi = self.span.hi;
2047 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2049 token::OpenDelim(token::Paren) => {
2052 let attrs = try!(self.parse_inner_attributes())
2056 // (e) is parenthesized e
2057 // (e,) is a tuple with only one field, e
2058 let mut es = vec![];
2059 let mut trailing_comma = false;
2060 while self.token != token::CloseDelim(token::Paren) {
2061 es.push(try!(self.parse_expr()));
2062 try!(self.commit_expr(&**es.last().unwrap(), &[],
2063 &[token::Comma, token::CloseDelim(token::Paren)]));
2064 if self.check(&token::Comma) {
2065 trailing_comma = true;
2069 trailing_comma = false;
2075 hi = self.last_span.hi;
2076 return if es.len() == 1 && !trailing_comma {
2077 Ok(self.mk_expr(lo, hi, ExprParen(es.into_iter().nth(0).unwrap()), attrs))
2079 Ok(self.mk_expr(lo, hi, ExprTup(es), attrs))
2082 token::OpenDelim(token::Brace) => {
2083 return self.parse_block_expr(lo, DefaultBlock, attrs);
2085 token::BinOp(token::Or) | token::OrOr => {
2086 let lo = self.span.lo;
2087 return self.parse_lambda_expr(lo, CaptureByRef, attrs);
2089 token::Ident(id @ ast::Ident {
2090 name: token::SELF_KEYWORD_NAME,
2092 }, token::Plain) => {
2094 let path = ast_util::ident_to_path(mk_sp(lo, hi), id);
2095 ex = ExprPath(None, path);
2096 hi = self.last_span.hi;
2098 token::OpenDelim(token::Bracket) => {
2101 let inner_attrs = try!(self.parse_inner_attributes())
2103 attrs.update(|attrs| attrs.append(inner_attrs));
2105 if self.check(&token::CloseDelim(token::Bracket)) {
2108 ex = ExprVec(Vec::new());
2111 let first_expr = try!(self.parse_expr());
2112 if self.check(&token::Semi) {
2113 // Repeating array syntax: [ 0; 512 ]
2115 let count = try!(self.parse_expr());
2116 try!(self.expect(&token::CloseDelim(token::Bracket)));
2117 ex = ExprRepeat(first_expr, count);
2118 } else if self.check(&token::Comma) {
2119 // Vector with two or more elements.
2121 let remaining_exprs = try!(self.parse_seq_to_end(
2122 &token::CloseDelim(token::Bracket),
2123 seq_sep_trailing_allowed(token::Comma),
2124 |p| Ok(try!(p.parse_expr()))
2126 let mut exprs = vec!(first_expr);
2127 exprs.extend(remaining_exprs);
2128 ex = ExprVec(exprs);
2130 // Vector with one element.
2131 try!(self.expect(&token::CloseDelim(token::Bracket)));
2132 ex = ExprVec(vec!(first_expr));
2135 hi = self.last_span.hi;
2140 try!(self.parse_qualified_path(LifetimeAndTypesWithColons));
2142 return Ok(self.mk_expr(lo, hi, ExprPath(Some(qself), path), attrs));
2144 if self.eat_keyword(keywords::Move) {
2145 let lo = self.last_span.lo;
2146 return self.parse_lambda_expr(lo, CaptureByValue, attrs);
2148 if self.eat_keyword(keywords::If) {
2149 return self.parse_if_expr(attrs);
2151 if self.eat_keyword(keywords::For) {
2152 let lo = self.last_span.lo;
2153 return self.parse_for_expr(None, lo, attrs);
2155 if self.eat_keyword(keywords::While) {
2156 let lo = self.last_span.lo;
2157 return self.parse_while_expr(None, lo, attrs);
2159 if self.token.is_lifetime() {
2160 let lifetime = self.get_lifetime();
2161 let lo = self.span.lo;
2163 try!(self.expect(&token::Colon));
2164 if self.eat_keyword(keywords::While) {
2165 return self.parse_while_expr(Some(lifetime), lo, attrs)
2167 if self.eat_keyword(keywords::For) {
2168 return self.parse_for_expr(Some(lifetime), lo, attrs)
2170 if self.eat_keyword(keywords::Loop) {
2171 return self.parse_loop_expr(Some(lifetime), lo, attrs)
2173 return Err(self.fatal("expected `while`, `for`, or `loop` after a label"))
2175 if self.eat_keyword(keywords::Loop) {
2176 let lo = self.last_span.lo;
2177 return self.parse_loop_expr(None, lo, attrs);
2179 if self.eat_keyword(keywords::Continue) {
2180 let ex = if self.token.is_lifetime() {
2181 let ex = ExprAgain(Some(Spanned{
2182 node: self.get_lifetime(),
2190 let hi = self.last_span.hi;
2191 return Ok(self.mk_expr(lo, hi, ex, attrs));
2193 if self.eat_keyword(keywords::Match) {
2194 return self.parse_match_expr(attrs);
2196 if self.eat_keyword(keywords::Unsafe) {
2197 return self.parse_block_expr(
2199 UnsafeBlock(ast::UserProvided),
2202 if self.eat_keyword(keywords::Return) {
2203 if self.token.can_begin_expr() {
2204 let e = try!(self.parse_expr());
2206 ex = ExprRet(Some(e));
2210 } else if self.eat_keyword(keywords::Break) {
2211 if self.token.is_lifetime() {
2212 ex = ExprBreak(Some(Spanned {
2213 node: self.get_lifetime(),
2218 ex = ExprBreak(None);
2220 hi = self.last_span.hi;
2221 } else if self.check(&token::ModSep) ||
2222 self.token.is_ident() &&
2223 !self.check_keyword(keywords::True) &&
2224 !self.check_keyword(keywords::False) {
2226 try!(self.parse_path(LifetimeAndTypesWithColons));
2228 // `!`, as an operator, is prefix, so we know this isn't that
2229 if self.check(&token::Not) {
2230 // MACRO INVOCATION expression
2233 let delim = try!(self.expect_open_delim());
2234 let tts = try!(self.parse_seq_to_end(
2235 &token::CloseDelim(delim),
2237 |p| p.parse_token_tree()));
2238 let hi = self.last_span.hi;
2240 return Ok(self.mk_mac_expr(lo,
2242 Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT },
2245 if self.check(&token::OpenDelim(token::Brace)) {
2246 // This is a struct literal, unless we're prohibited
2247 // from parsing struct literals here.
2248 let prohibited = self.restrictions.contains(
2249 Restrictions::RESTRICTION_NO_STRUCT_LITERAL
2252 // It's a struct literal.
2254 let mut fields = Vec::new();
2255 let mut base = None;
2257 let attrs = attrs.append(
2258 try!(self.parse_inner_attributes())
2259 .into_thin_attrs());
2261 while self.token != token::CloseDelim(token::Brace) {
2262 if self.eat(&token::DotDot) {
2263 base = Some(try!(self.parse_expr()));
2267 fields.push(try!(self.parse_field()));
2268 try!(self.commit_expr(&*fields.last().unwrap().expr,
2270 &[token::CloseDelim(token::Brace)]));
2274 try!(self.expect(&token::CloseDelim(token::Brace)));
2275 ex = ExprStruct(pth, fields, base);
2276 return Ok(self.mk_expr(lo, hi, ex, attrs));
2281 ex = ExprPath(None, pth);
2283 // other literal expression
2284 let lit = try!(self.parse_lit());
2286 ex = ExprLit(P(lit));
2291 return Ok(self.mk_expr(lo, hi, ex, attrs));
2294 fn parse_or_use_outer_attributes(&mut self,
2295 already_parsed_attrs: Option<ThinAttributes>)
2296 -> PResult<'a, ThinAttributes> {
2297 if let Some(attrs) = already_parsed_attrs {
2300 self.parse_outer_attributes().map(|a| a.into_thin_attrs())
2304 /// Parse a block or unsafe block
2305 pub fn parse_block_expr(&mut self, lo: BytePos, blk_mode: BlockCheckMode,
2306 attrs: ThinAttributes)
2307 -> PResult<'a, P<Expr>> {
2309 let outer_attrs = attrs;
2310 try!(self.expect(&token::OpenDelim(token::Brace)));
2312 let inner_attrs = try!(self.parse_inner_attributes()).into_thin_attrs();
2313 let attrs = outer_attrs.append(inner_attrs);
2315 let blk = try!(self.parse_block_tail(lo, blk_mode));
2316 return Ok(self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk), attrs));
2319 /// parse a.b or a(13) or a[4] or just a
2320 pub fn parse_dot_or_call_expr(&mut self,
2321 already_parsed_attrs: Option<ThinAttributes>)
2322 -> PResult<'a, P<Expr>> {
2323 let attrs = try!(self.parse_or_use_outer_attributes(already_parsed_attrs));
2325 let b = try!(self.parse_bottom_expr());
2326 self.parse_dot_or_call_expr_with(b, attrs)
2329 pub fn parse_dot_or_call_expr_with(&mut self,
2331 attrs: ThinAttributes)
2332 -> PResult<'a, P<Expr>> {
2333 // Stitch the list of outer attributes onto the return value.
2334 // A little bit ugly, but the best way given the current code
2336 self.parse_dot_or_call_expr_with_(e0)
2338 expr.map(|mut expr| {
2339 expr.attrs.update(|a| a.prepend(attrs));
2341 ExprIf(..) | ExprIfLet(..) => {
2342 if !expr.attrs.as_attr_slice().is_empty() {
2343 // Just point to the first attribute in there...
2344 let span = expr.attrs.as_attr_slice()[0].span;
2347 "attributes are not yet allowed on `if` \
2358 // Assuming we have just parsed `.foo` (i.e., a dot and an ident), continue
2359 // parsing into an expression.
2360 fn parse_dot_suffix(&mut self, ident: Ident, ident_span: Span, self_value: P<Expr>) -> PResult<'a, P<Expr>> {
2361 let (_, tys, bindings) = if self.eat(&token::ModSep) {
2362 try!(self.expect_lt());
2363 try!(self.parse_generic_values_after_lt())
2365 (Vec::new(), Vec::new(), Vec::new())
2368 if !bindings.is_empty() {
2369 let last_span = self.last_span;
2370 self.span_err(last_span, "type bindings are only permitted on trait paths");
2373 let lo = self_value.span.lo;
2375 Ok(match self.token {
2376 // 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 let hi = self.last_span.hi;
2386 es.insert(0, self_value);
2387 let id = spanned(ident_span.lo, ident_span.hi, ident);
2388 let nd = self.mk_method_call(id, tys, es);
2389 self.mk_expr(lo, hi, nd, None)
2393 if !tys.is_empty() {
2394 let last_span = self.last_span;
2395 self.span_err(last_span,
2396 "field expressions may not \
2397 have type parameters");
2400 let id = spanned(ident_span.lo, ident_span.hi, ident);
2401 let field = self.mk_field(self_value, id);
2402 self.mk_expr(lo, ident_span.hi, field, None)
2407 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>) -> PResult<'a, P<Expr>> {
2413 if self.eat(&token::Dot) {
2415 token::Ident(i, _) => {
2416 let dot_pos = self.last_span.hi;
2420 e = try!(self.parse_dot_suffix(i, mk_sp(dot_pos, hi), e));
2422 token::Literal(token::Integer(n), suf) => {
2425 // A tuple index may not have a suffix
2426 self.expect_no_suffix(sp, "tuple index", suf);
2428 let dot = self.last_span.hi;
2432 let index = n.as_str().parse::<usize>().ok();
2435 let id = spanned(dot, hi, n);
2436 let field = self.mk_tup_field(e, id);
2437 e = self.mk_expr(lo, hi, field, None);
2440 let last_span = self.last_span;
2441 self.span_err(last_span, "invalid tuple or tuple struct index");
2445 token::Literal(token::Float(n), _suf) => {
2447 let last_span = self.last_span;
2448 let fstr = n.as_str();
2449 let mut err = self.diagnostic().struct_span_err(last_span,
2450 &format!("unexpected token: `{}`", n.as_str()));
2451 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2452 let float = match fstr.parse::<f64>().ok() {
2456 err.fileline_help(last_span,
2457 &format!("try parenthesizing the first index; e.g., `(foo.{}){}`",
2458 float.trunc() as usize,
2459 format!(".{}", fstr.splitn(2, ".").last().unwrap())));
2462 self.abort_if_errors();
2466 // TODO special case lifetime
2467 // FIXME Could factor this out into non_fatal_unexpected or something.
2468 let actual = self.this_token_to_string();
2469 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
2471 let dot_pos = self.last_span.hi;
2472 e = try!(self.parse_dot_suffix(special_idents::invalid,
2473 mk_sp(dot_pos, dot_pos),
2479 if self.expr_is_complete(&*e) { break; }
2482 token::OpenDelim(token::Paren) => {
2483 let es = try!(self.parse_unspanned_seq(
2484 &token::OpenDelim(token::Paren),
2485 &token::CloseDelim(token::Paren),
2486 seq_sep_trailing_allowed(token::Comma),
2487 |p| Ok(try!(p.parse_expr()))
2489 hi = self.last_span.hi;
2491 let nd = self.mk_call(e, es);
2492 e = self.mk_expr(lo, hi, nd, None);
2496 // Could be either an index expression or a slicing expression.
2497 token::OpenDelim(token::Bracket) => {
2499 let ix = try!(self.parse_expr());
2501 try!(self.commit_expr_expecting(&*ix, token::CloseDelim(token::Bracket)));
2502 let index = self.mk_index(e, ix);
2503 e = self.mk_expr(lo, hi, index, None)
2511 // Parse unquoted tokens after a `$` in a token tree
2512 fn parse_unquoted(&mut self) -> PResult<'a, TokenTree> {
2513 let mut sp = self.span;
2514 let (name, namep) = match self.token {
2518 if self.token == token::OpenDelim(token::Paren) {
2519 let Spanned { node: seq, span: seq_span } = try!(self.parse_seq(
2520 &token::OpenDelim(token::Paren),
2521 &token::CloseDelim(token::Paren),
2523 |p| p.parse_token_tree()
2525 let (sep, repeat) = try!(self.parse_sep_and_kleene_op());
2526 let name_num = macro_parser::count_names(&seq);
2527 return Ok(TokenTree::Sequence(mk_sp(sp.lo, seq_span.hi),
2528 Rc::new(SequenceRepetition {
2532 num_captures: name_num
2534 } else if self.token.is_keyword_allow_following_colon(keywords::Crate) {
2536 return Ok(TokenTree::Token(sp, SpecialVarNt(SpecialMacroVar::CrateMacroVar)));
2538 sp = mk_sp(sp.lo, self.span.hi);
2539 let namep = match self.token { token::Ident(_, p) => p, _ => token::Plain };
2540 let name = try!(self.parse_ident());
2544 token::SubstNt(name, namep) => {
2550 // continue by trying to parse the `:ident` after `$name`
2551 if self.token == token::Colon && self.look_ahead(1, |t| t.is_ident() &&
2552 !t.is_strict_keyword() &&
2553 !t.is_reserved_keyword()) {
2555 sp = mk_sp(sp.lo, self.span.hi);
2556 let kindp = match self.token { token::Ident(_, p) => p, _ => token::Plain };
2557 let nt_kind = try!(self.parse_ident());
2558 Ok(TokenTree::Token(sp, MatchNt(name, nt_kind, namep, kindp)))
2560 Ok(TokenTree::Token(sp, SubstNt(name, namep)))
2564 pub fn check_unknown_macro_variable(&mut self) {
2565 if self.quote_depth == 0 {
2567 token::SubstNt(name, _) =>
2568 self.fatal(&format!("unknown macro variable `{}`", name)).emit(),
2574 /// Parse an optional separator followed by a Kleene-style
2575 /// repetition token (+ or *).
2576 pub fn parse_sep_and_kleene_op(&mut self)
2577 -> PResult<'a, (Option<token::Token>, ast::KleeneOp)> {
2578 fn parse_kleene_op<'a>(parser: &mut Parser<'a>) -> PResult<'a, Option<ast::KleeneOp>> {
2579 match parser.token {
2580 token::BinOp(token::Star) => {
2582 Ok(Some(ast::ZeroOrMore))
2584 token::BinOp(token::Plus) => {
2586 Ok(Some(ast::OneOrMore))
2592 match try!(parse_kleene_op(self)) {
2593 Some(kleene_op) => return Ok((None, kleene_op)),
2597 let separator = self.bump_and_get();
2598 match try!(parse_kleene_op(self)) {
2599 Some(zerok) => Ok((Some(separator), zerok)),
2600 None => return Err(self.fatal("expected `*` or `+`"))
2604 /// parse a single token tree from the input.
2605 pub fn parse_token_tree(&mut self) -> PResult<'a, TokenTree> {
2606 // FIXME #6994: currently, this is too eager. It
2607 // parses token trees but also identifies TokenType::Sequence's
2608 // and token::SubstNt's; it's too early to know yet
2609 // whether something will be a nonterminal or a seq
2611 maybe_whole!(deref self, NtTT);
2613 // this is the fall-through for the 'match' below.
2614 // invariants: the current token is not a left-delimiter,
2615 // not an EOF, and not the desired right-delimiter (if
2616 // it were, parse_seq_to_before_end would have prevented
2617 // reaching this point.
2618 fn parse_non_delim_tt_tok<'b>(p: &mut Parser<'b>) -> PResult<'b, TokenTree> {
2619 maybe_whole!(deref p, NtTT);
2621 token::CloseDelim(_) => {
2622 let token_str = p.this_token_to_string();
2623 let mut err = p.fatal(
2624 &format!("incorrect close delimiter: `{}`", token_str));
2625 // This is a conservative error: only report the last unclosed delimiter. The
2626 // previous unclosed delimiters could actually be closed! The parser just hasn't
2627 // gotten to them yet.
2628 if let Some(&sp) = p.open_braces.last() {
2629 err.span_note(sp, "unclosed delimiter");
2633 /* we ought to allow different depths of unquotation */
2634 token::Dollar | token::SubstNt(..) if p.quote_depth > 0 => {
2638 Ok(TokenTree::Token(p.span, p.bump_and_get()))
2645 let open_braces = self.open_braces.clone();
2646 let mut err: DiagnosticBuilder<'a> =
2647 self.fatal("this file contains an un-closed delimiter");
2648 for sp in &open_braces {
2649 err.span_help(*sp, "did you mean to close this delimiter?");
2653 token::OpenDelim(delim) => {
2654 // The span for beginning of the delimited section
2655 let pre_span = self.span;
2657 // Parse the open delimiter.
2658 self.open_braces.push(self.span);
2659 let open_span = self.span;
2662 // Parse the token trees within the delimiters
2663 let tts = try!(self.parse_seq_to_before_end(
2664 &token::CloseDelim(delim),
2666 |p| p.parse_token_tree()
2669 // Parse the close delimiter.
2670 let close_span = self.span;
2672 self.open_braces.pop().unwrap();
2674 // Expand to cover the entire delimited token tree
2675 let span = Span { hi: close_span.hi, ..pre_span };
2677 Ok(TokenTree::Delimited(span, Rc::new(Delimited {
2679 open_span: open_span,
2681 close_span: close_span,
2684 _ => parse_non_delim_tt_tok(self),
2688 // parse a stream of tokens into a list of TokenTree's,
2690 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2691 let mut tts = Vec::new();
2692 while self.token != token::Eof {
2693 tts.push(try!(self.parse_token_tree()));
2698 /// Parse a prefix-unary-operator expr
2699 pub fn parse_prefix_expr(&mut self,
2700 already_parsed_attrs: Option<ThinAttributes>)
2701 -> PResult<'a, P<Expr>> {
2702 let attrs = try!(self.parse_or_use_outer_attributes(already_parsed_attrs));
2703 let lo = self.span.lo;
2705 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2706 let ex = match self.token {
2709 let e = try!(self.parse_prefix_expr(None));
2711 self.mk_unary(UnNot, e)
2713 token::BinOp(token::Minus) => {
2715 let e = try!(self.parse_prefix_expr(None));
2717 self.mk_unary(UnNeg, e)
2719 token::BinOp(token::Star) => {
2721 let e = try!(self.parse_prefix_expr(None));
2723 self.mk_unary(UnDeref, e)
2725 token::BinOp(token::And) | token::AndAnd => {
2726 try!(self.expect_and());
2727 let m = try!(self.parse_mutability());
2728 let e = try!(self.parse_prefix_expr(None));
2732 token::Ident(..) if self.token.is_keyword(keywords::In) => {
2734 let place = try!(self.parse_expr_res(
2735 Restrictions::RESTRICTION_NO_STRUCT_LITERAL,
2738 let blk = try!(self.parse_block());
2739 let span = blk.span;
2741 let blk_expr = self.mk_expr(span.lo, span.hi, ExprBlock(blk),
2743 ExprInPlace(place, blk_expr)
2745 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
2747 let subexpression = try!(self.parse_prefix_expr(None));
2748 hi = subexpression.span.hi;
2749 ExprBox(subexpression)
2751 _ => return self.parse_dot_or_call_expr(Some(attrs))
2753 return Ok(self.mk_expr(lo, hi, ex, attrs));
2756 /// Parse an associative expression
2758 /// This parses an expression accounting for associativity and precedence of the operators in
2760 pub fn parse_assoc_expr(&mut self,
2761 already_parsed_attrs: Option<ThinAttributes>)
2762 -> PResult<'a, P<Expr>> {
2763 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
2766 /// Parse an associative expression with operators of at least `min_prec` precedence
2767 pub fn parse_assoc_expr_with(&mut self,
2770 -> PResult<'a, P<Expr>> {
2771 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
2774 let attrs = match lhs {
2775 LhsExpr::AttributesParsed(attrs) => Some(attrs),
2778 if self.token == token::DotDot {
2779 return self.parse_prefix_range_expr(attrs);
2781 try!(self.parse_prefix_expr(attrs))
2784 if self.expr_is_complete(&*lhs) {
2785 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
2788 self.expected_tokens.push(TokenType::Operator);
2789 while let Some(op) = AssocOp::from_token(&self.token) {
2790 let cur_op_span = self.span;
2791 let restrictions = if op.is_assign_like() {
2792 self.restrictions & Restrictions::RESTRICTION_NO_STRUCT_LITERAL
2796 if op.precedence() < min_prec {
2800 if op.is_comparison() {
2801 self.check_no_chained_comparison(&*lhs, &op);
2804 if op == AssocOp::As {
2805 let rhs = try!(self.parse_ty());
2806 lhs = self.mk_expr(lhs.span.lo, rhs.span.hi,
2807 ExprCast(lhs, rhs), None);
2809 } else if op == AssocOp::Colon {
2810 let rhs = try!(self.parse_ty());
2811 lhs = self.mk_expr(lhs.span.lo, rhs.span.hi,
2812 ExprType(lhs, rhs), None);
2814 } else if op == AssocOp::DotDot {
2815 // If we didn’t have to handle `x..`, it would be pretty easy to generalise
2816 // it to the Fixity::None code.
2818 // We have 2 alternatives here: `x..y` and `x..` The other two variants are
2819 // handled with `parse_prefix_range_expr` call above.
2820 let rhs = if self.is_at_start_of_range_notation_rhs() {
2821 let rhs = self.parse_assoc_expr_with(op.precedence() + 1,
2822 LhsExpr::NotYetParsed);
2833 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
2838 let r = self.mk_range(Some(lhs), rhs);
2839 lhs = self.mk_expr(lhs_span.lo, rhs_span.hi, r, None);
2843 let rhs = try!(match op.fixity() {
2844 Fixity::Right => self.with_res(
2845 restrictions - Restrictions::RESTRICTION_STMT_EXPR,
2847 this.parse_assoc_expr_with(op.precedence(),
2848 LhsExpr::NotYetParsed)
2850 Fixity::Left => self.with_res(
2851 restrictions - Restrictions::RESTRICTION_STMT_EXPR,
2853 this.parse_assoc_expr_with(op.precedence() + 1,
2854 LhsExpr::NotYetParsed)
2856 // We currently have no non-associative operators that are not handled above by
2857 // the special cases. The code is here only for future convenience.
2858 Fixity::None => self.with_res(
2859 restrictions - Restrictions::RESTRICTION_STMT_EXPR,
2861 this.parse_assoc_expr_with(op.precedence() + 1,
2862 LhsExpr::NotYetParsed)
2867 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
2868 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
2869 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
2870 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
2871 AssocOp::Greater | AssocOp::GreaterEqual => {
2872 let ast_op = op.to_ast_binop().unwrap();
2873 let (lhs_span, rhs_span) = (lhs.span, rhs.span);
2874 let binary = self.mk_binary(codemap::respan(cur_op_span, ast_op), lhs, rhs);
2875 self.mk_expr(lhs_span.lo, rhs_span.hi, binary, None)
2878 self.mk_expr(lhs.span.lo, rhs.span.hi, ExprAssign(lhs, rhs), None),
2880 self.mk_expr(lhs.span.lo, rhs.span.hi, ExprInPlace(lhs, rhs), None),
2881 AssocOp::AssignOp(k) => {
2883 token::Plus => BiAdd,
2884 token::Minus => BiSub,
2885 token::Star => BiMul,
2886 token::Slash => BiDiv,
2887 token::Percent => BiRem,
2888 token::Caret => BiBitXor,
2889 token::And => BiBitAnd,
2890 token::Or => BiBitOr,
2891 token::Shl => BiShl,
2894 let (lhs_span, rhs_span) = (lhs.span, rhs.span);
2895 let aopexpr = self.mk_assign_op(codemap::respan(cur_op_span, aop), lhs, rhs);
2896 self.mk_expr(lhs_span.lo, rhs_span.hi, aopexpr, None)
2898 AssocOp::As | AssocOp::Colon | AssocOp::DotDot => {
2899 self.bug("As, Colon or DotDot branch reached")
2903 if op.fixity() == Fixity::None { break }
2908 /// Produce an error if comparison operators are chained (RFC #558).
2909 /// We only need to check lhs, not rhs, because all comparison ops
2910 /// have same precedence and are left-associative
2911 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
2912 debug_assert!(outer_op.is_comparison());
2914 ExprBinary(op, _, _) if op.node.is_comparison() => {
2915 // respan to include both operators
2916 let op_span = mk_sp(op.span.lo, self.span.hi);
2917 let mut err = self.diagnostic().struct_span_err(op_span,
2918 "chained comparison operators require parentheses");
2919 if op.node == BiLt && *outer_op == AssocOp::Greater {
2920 err.fileline_help(op_span,
2921 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
2929 /// Parse prefix-forms of range notation: `..expr` and `..`
2930 fn parse_prefix_range_expr(&mut self,
2931 already_parsed_attrs: Option<ThinAttributes>)
2932 -> PResult<'a, P<Expr>> {
2933 debug_assert!(self.token == token::DotDot);
2934 let attrs = try!(self.parse_or_use_outer_attributes(already_parsed_attrs));
2935 let lo = self.span.lo;
2936 let mut hi = self.span.hi;
2938 let opt_end = if self.is_at_start_of_range_notation_rhs() {
2939 // RHS must be parsed with more associativity than DotDot.
2940 let next_prec = AssocOp::from_token(&token::DotDot).unwrap().precedence() + 1;
2941 Some(try!(self.parse_assoc_expr_with(next_prec,
2942 LhsExpr::NotYetParsed)
2950 let r = self.mk_range(None, opt_end);
2951 Ok(self.mk_expr(lo, hi, r, attrs))
2954 fn is_at_start_of_range_notation_rhs(&self) -> bool {
2955 if self.token.can_begin_expr() {
2956 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
2957 if self.token == token::OpenDelim(token::Brace) {
2958 return !self.restrictions.contains(Restrictions::RESTRICTION_NO_STRUCT_LITERAL);
2966 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
2967 pub fn parse_if_expr(&mut self, attrs: ThinAttributes) -> PResult<'a, P<Expr>> {
2968 if self.check_keyword(keywords::Let) {
2969 return self.parse_if_let_expr(attrs);
2971 let lo = self.last_span.lo;
2972 let cond = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
2973 let thn = try!(self.parse_block());
2974 let mut els: Option<P<Expr>> = None;
2975 let mut hi = thn.span.hi;
2976 if self.eat_keyword(keywords::Else) {
2977 let elexpr = try!(self.parse_else_expr());
2978 hi = elexpr.span.hi;
2981 Ok(self.mk_expr(lo, hi, ExprIf(cond, thn, els), attrs))
2984 /// Parse an 'if let' expression ('if' token already eaten)
2985 pub fn parse_if_let_expr(&mut self, attrs: ThinAttributes)
2986 -> PResult<'a, P<Expr>> {
2987 let lo = self.last_span.lo;
2988 try!(self.expect_keyword(keywords::Let));
2989 let pat = try!(self.parse_pat());
2990 try!(self.expect(&token::Eq));
2991 let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
2992 let thn = try!(self.parse_block());
2993 let (hi, els) = if self.eat_keyword(keywords::Else) {
2994 let expr = try!(self.parse_else_expr());
2995 (expr.span.hi, Some(expr))
2999 Ok(self.mk_expr(lo, hi, ExprIfLet(pat, expr, thn, els), attrs))
3003 pub fn parse_lambda_expr(&mut self, lo: BytePos,
3004 capture_clause: CaptureClause,
3005 attrs: ThinAttributes)
3006 -> PResult<'a, P<Expr>>
3008 let decl = try!(self.parse_fn_block_decl());
3009 let body = match decl.output {
3010 DefaultReturn(_) => {
3011 // If no explicit return type is given, parse any
3012 // expr and wrap it up in a dummy block:
3013 let body_expr = try!(self.parse_expr());
3015 id: ast::DUMMY_NODE_ID,
3017 span: body_expr.span,
3018 expr: Some(body_expr),
3019 rules: DefaultBlock,
3023 // If an explicit return type is given, require a
3024 // block to appear (RFC 968).
3025 try!(self.parse_block())
3032 ExprClosure(capture_clause, decl, body), attrs))
3035 // `else` token already eaten
3036 pub fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3037 if self.eat_keyword(keywords::If) {
3038 return self.parse_if_expr(None);
3040 let blk = try!(self.parse_block());
3041 return Ok(self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk), None));
3045 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3046 pub fn parse_for_expr(&mut self, opt_ident: Option<ast::Ident>,
3048 attrs: ThinAttributes) -> PResult<'a, P<Expr>> {
3049 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3051 let pat = try!(self.parse_pat());
3052 try!(self.expect_keyword(keywords::In));
3053 let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3054 let (iattrs, loop_block) = try!(self.parse_inner_attrs_and_block());
3055 let attrs = attrs.append(iattrs.into_thin_attrs());
3057 let hi = self.last_span.hi;
3059 Ok(self.mk_expr(span_lo, hi,
3060 ExprForLoop(pat, expr, loop_block, opt_ident),
3064 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3065 pub fn parse_while_expr(&mut self, opt_ident: Option<ast::Ident>,
3067 attrs: ThinAttributes) -> PResult<'a, P<Expr>> {
3068 if self.token.is_keyword(keywords::Let) {
3069 return self.parse_while_let_expr(opt_ident, span_lo, attrs);
3071 let cond = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
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 return Ok(self.mk_expr(span_lo, hi, ExprWhile(cond, body, opt_ident),
3079 /// Parse a 'while let' expression ('while' token already eaten)
3080 pub fn parse_while_let_expr(&mut self, opt_ident: Option<ast::Ident>,
3082 attrs: ThinAttributes) -> PResult<'a, P<Expr>> {
3083 try!(self.expect_keyword(keywords::Let));
3084 let pat = try!(self.parse_pat());
3085 try!(self.expect(&token::Eq));
3086 let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3087 let (iattrs, body) = try!(self.parse_inner_attrs_and_block());
3088 let attrs = attrs.append(iattrs.into_thin_attrs());
3089 let hi = body.span.hi;
3090 return Ok(self.mk_expr(span_lo, hi, ExprWhileLet(pat, expr, body, opt_ident), attrs));
3093 // parse `loop {...}`, `loop` token already eaten
3094 pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::Ident>,
3096 attrs: ThinAttributes) -> PResult<'a, P<Expr>> {
3097 let (iattrs, body) = try!(self.parse_inner_attrs_and_block());
3098 let attrs = attrs.append(iattrs.into_thin_attrs());
3099 let hi = body.span.hi;
3100 Ok(self.mk_expr(span_lo, hi, ExprLoop(body, opt_ident), attrs))
3103 // `match` token already eaten
3104 fn parse_match_expr(&mut self, attrs: ThinAttributes) -> PResult<'a, P<Expr>> {
3105 let match_span = self.last_span;
3106 let lo = self.last_span.lo;
3107 let discriminant = try!(self.parse_expr_res(
3108 Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3109 if let Err(mut e) = self.commit_expr_expecting(&*discriminant,
3110 token::OpenDelim(token::Brace)) {
3111 if self.token == token::Token::Semi {
3112 e.span_note(match_span, "did you mean to remove this `match` keyword?");
3116 let attrs = attrs.append(
3117 try!(self.parse_inner_attributes()).into_thin_attrs());
3118 let mut arms: Vec<Arm> = Vec::new();
3119 while self.token != token::CloseDelim(token::Brace) {
3120 arms.push(try!(self.parse_arm()));
3122 let hi = self.span.hi;
3124 return Ok(self.mk_expr(lo, hi, ExprMatch(discriminant, arms), attrs));
3127 pub fn parse_arm(&mut self) -> PResult<'a, Arm> {
3128 maybe_whole!(no_clone self, NtArm);
3130 let attrs = try!(self.parse_outer_attributes());
3131 let pats = try!(self.parse_pats());
3132 let mut guard = None;
3133 if self.eat_keyword(keywords::If) {
3134 guard = Some(try!(self.parse_expr()));
3136 try!(self.expect(&token::FatArrow));
3137 let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_STMT_EXPR, None));
3140 !classify::expr_is_simple_block(&*expr)
3141 && self.token != token::CloseDelim(token::Brace);
3144 try!(self.commit_expr(&*expr, &[token::Comma], &[token::CloseDelim(token::Brace)]));
3146 self.eat(&token::Comma);
3157 /// Parse an expression
3158 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3159 self.parse_expr_res(Restrictions::empty(), None)
3162 /// Evaluate the closure with restrictions in place.
3164 /// After the closure is evaluated, restrictions are reset.
3165 pub fn with_res<F>(&mut self, r: Restrictions, f: F) -> PResult<'a, P<Expr>>
3166 where F: FnOnce(&mut Self) -> PResult<'a, P<Expr>>
3168 let old = self.restrictions;
3169 self.restrictions = r;
3171 self.restrictions = old;
3176 /// Parse an expression, subject to the given restrictions
3177 pub fn parse_expr_res(&mut self, r: Restrictions,
3178 already_parsed_attrs: Option<ThinAttributes>)
3179 -> PResult<'a, P<Expr>> {
3180 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3183 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3184 fn parse_initializer(&mut self) -> PResult<'a, Option<P<Expr>>> {
3185 if self.check(&token::Eq) {
3187 Ok(Some(try!(self.parse_expr())))
3193 /// Parse patterns, separated by '|' s
3194 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3195 let mut pats = Vec::new();
3197 pats.push(try!(self.parse_pat()));
3198 if self.check(&token::BinOp(token::Or)) { self.bump();}
3199 else { return Ok(pats); }
3203 fn parse_pat_tuple_elements(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3204 let mut fields = vec![];
3205 if !self.check(&token::CloseDelim(token::Paren)) {
3206 fields.push(try!(self.parse_pat()));
3207 if self.look_ahead(1, |t| *t != token::CloseDelim(token::Paren)) {
3208 while self.eat(&token::Comma) &&
3209 !self.check(&token::CloseDelim(token::Paren)) {
3210 fields.push(try!(self.parse_pat()));
3213 if fields.len() == 1 {
3214 try!(self.expect(&token::Comma));
3220 fn parse_pat_vec_elements(
3222 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3223 let mut before = Vec::new();
3224 let mut slice = None;
3225 let mut after = Vec::new();
3226 let mut first = true;
3227 let mut before_slice = true;
3229 while self.token != token::CloseDelim(token::Bracket) {
3233 try!(self.expect(&token::Comma));
3235 if self.token == token::CloseDelim(token::Bracket)
3236 && (before_slice || !after.is_empty()) {
3242 if self.check(&token::DotDot) {
3245 if self.check(&token::Comma) ||
3246 self.check(&token::CloseDelim(token::Bracket)) {
3247 slice = Some(P(ast::Pat {
3248 id: ast::DUMMY_NODE_ID,
3252 before_slice = false;
3258 let subpat = try!(self.parse_pat());
3259 if before_slice && self.check(&token::DotDot) {
3261 slice = Some(subpat);
3262 before_slice = false;
3263 } else if before_slice {
3264 before.push(subpat);
3270 Ok((before, slice, after))
3273 /// Parse the fields of a struct-like pattern
3274 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<codemap::Spanned<ast::FieldPat>> , bool)> {
3275 let mut fields = Vec::new();
3276 let mut etc = false;
3277 let mut first = true;
3278 while self.token != token::CloseDelim(token::Brace) {
3282 try!(self.expect(&token::Comma));
3283 // accept trailing commas
3284 if self.check(&token::CloseDelim(token::Brace)) { break }
3287 let lo = self.span.lo;
3290 if self.check(&token::DotDot) {
3292 if self.token != token::CloseDelim(token::Brace) {
3293 let token_str = self.this_token_to_string();
3294 return Err(self.fatal(&format!("expected `{}`, found `{}`", "}",
3301 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3302 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3303 // Parsing a pattern of the form "fieldname: pat"
3304 let fieldname = try!(self.parse_ident());
3306 let pat = try!(self.parse_pat());
3308 (pat, fieldname, false)
3310 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3311 let is_box = self.eat_keyword(keywords::Box);
3312 let boxed_span_lo = self.span.lo;
3313 let is_ref = self.eat_keyword(keywords::Ref);
3314 let is_mut = self.eat_keyword(keywords::Mut);
3315 let fieldname = try!(self.parse_ident());
3316 hi = self.last_span.hi;
3318 let bind_type = match (is_ref, is_mut) {
3319 (true, true) => BindingMode::ByRef(MutMutable),
3320 (true, false) => BindingMode::ByRef(MutImmutable),
3321 (false, true) => BindingMode::ByValue(MutMutable),
3322 (false, false) => BindingMode::ByValue(MutImmutable),
3324 let fieldpath = codemap::Spanned{span:self.last_span, node:fieldname};
3325 let fieldpat = P(ast::Pat{
3326 id: ast::DUMMY_NODE_ID,
3327 node: PatIdent(bind_type, fieldpath, None),
3328 span: mk_sp(boxed_span_lo, hi),
3331 let subpat = if is_box {
3333 id: ast::DUMMY_NODE_ID,
3334 node: PatBox(fieldpat),
3335 span: mk_sp(lo, hi),
3340 (subpat, fieldname, true)
3343 fields.push(codemap::Spanned { span: mk_sp(lo, hi),
3344 node: ast::FieldPat { ident: fieldname,
3346 is_shorthand: is_shorthand }});
3348 return Ok((fields, etc));
3351 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
3352 if self.is_path_start() {
3353 let lo = self.span.lo;
3354 let (qself, path) = if self.eat_lt() {
3355 // Parse a qualified path
3357 try!(self.parse_qualified_path(NoTypesAllowed));
3360 // Parse an unqualified path
3361 (None, try!(self.parse_path(LifetimeAndTypesWithColons)))
3363 let hi = self.last_span.hi;
3364 Ok(self.mk_expr(lo, hi, ExprPath(qself, path), None))
3366 self.parse_pat_literal_maybe_minus()
3370 fn is_path_start(&self) -> bool {
3371 (self.token == token::Lt || self.token == token::ModSep
3372 || self.token.is_ident() || self.token.is_path())
3373 && !self.token.is_keyword(keywords::True) && !self.token.is_keyword(keywords::False)
3376 /// Parse a pattern.
3377 pub fn parse_pat(&mut self) -> PResult<'a, P<Pat>> {
3378 maybe_whole!(self, NtPat);
3380 let lo = self.span.lo;
3383 token::Underscore => {
3388 token::BinOp(token::And) | token::AndAnd => {
3389 // Parse &pat / &mut pat
3390 try!(self.expect_and());
3391 let mutbl = try!(self.parse_mutability());
3392 if let token::Lifetime(ident) = self.token {
3393 return Err(self.fatal(&format!("unexpected lifetime `{}` in pattern", ident)));
3396 let subpat = try!(self.parse_pat());
3397 pat = PatRegion(subpat, mutbl);
3399 token::OpenDelim(token::Paren) => {
3400 // Parse (pat,pat,pat,...) as tuple pattern
3402 let fields = try!(self.parse_pat_tuple_elements());
3403 try!(self.expect(&token::CloseDelim(token::Paren)));
3404 pat = PatTup(fields);
3406 token::OpenDelim(token::Bracket) => {
3407 // Parse [pat,pat,...] as slice pattern
3409 let (before, slice, after) = try!(self.parse_pat_vec_elements());
3410 try!(self.expect(&token::CloseDelim(token::Bracket)));
3411 pat = PatVec(before, slice, after);
3414 // At this point, token != _, &, &&, (, [
3415 if self.eat_keyword(keywords::Mut) {
3416 // Parse mut ident @ pat
3417 pat = try!(self.parse_pat_ident(BindingMode::ByValue(MutMutable)));
3418 } else if self.eat_keyword(keywords::Ref) {
3419 // Parse ref ident @ pat / ref mut ident @ pat
3420 let mutbl = try!(self.parse_mutability());
3421 pat = try!(self.parse_pat_ident(BindingMode::ByRef(mutbl)));
3422 } else if self.eat_keyword(keywords::Box) {
3424 let subpat = try!(self.parse_pat());
3425 pat = PatBox(subpat);
3426 } else if self.is_path_start() {
3427 // Parse pattern starting with a path
3428 if self.token.is_plain_ident() && self.look_ahead(1, |t| *t != token::DotDotDot &&
3429 *t != token::OpenDelim(token::Brace) &&
3430 *t != token::OpenDelim(token::Paren) &&
3431 // Contrary to its definition, a plain ident can be followed by :: in macros
3432 *t != token::ModSep) {
3433 // Plain idents have some extra abilities here compared to general paths
3434 if self.look_ahead(1, |t| *t == token::Not) {
3435 // Parse macro invocation
3436 let ident = try!(self.parse_ident());
3437 let ident_span = self.last_span;
3438 let path = ident_to_path(ident_span, ident);
3440 let delim = try!(self.expect_open_delim());
3441 let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
3442 seq_sep_none(), |p| p.parse_token_tree()));
3443 let mac = Mac_ { path: path, tts: tts, ctxt: EMPTY_CTXT };
3444 pat = PatMac(codemap::Spanned {node: mac,
3445 span: mk_sp(lo, self.last_span.hi)});
3447 // Parse ident @ pat
3448 // This can give false positives and parse nullary enums,
3449 // they are dealt with later in resolve
3450 pat = try!(self.parse_pat_ident(BindingMode::ByValue(MutImmutable)));
3453 let (qself, path) = if self.eat_lt() {
3454 // Parse a qualified path
3456 try!(self.parse_qualified_path(NoTypesAllowed));
3459 // Parse an unqualified path
3460 (None, try!(self.parse_path(LifetimeAndTypesWithColons)))
3463 token::DotDotDot => {
3465 let hi = self.last_span.hi;
3466 let begin = self.mk_expr(lo, hi, ExprPath(qself, path), None);
3468 let end = try!(self.parse_pat_range_end());
3469 pat = PatRange(begin, end);
3471 token::OpenDelim(token::Brace) => {
3472 if qself.is_some() {
3473 return Err(self.fatal("unexpected `{` after qualified path"));
3475 // Parse struct pattern
3477 let (fields, etc) = try!(self.parse_pat_fields());
3479 pat = PatStruct(path, fields, etc);
3481 token::OpenDelim(token::Paren) => {
3482 if qself.is_some() {
3483 return Err(self.fatal("unexpected `(` after qualified path"));
3485 // Parse tuple struct or enum pattern
3486 if self.look_ahead(1, |t| *t == token::DotDot) {
3487 // This is a "top constructor only" pat
3490 try!(self.expect(&token::CloseDelim(token::Paren)));
3491 pat = PatEnum(path, None);
3493 let args = try!(self.parse_enum_variant_seq(
3494 &token::OpenDelim(token::Paren),
3495 &token::CloseDelim(token::Paren),
3496 seq_sep_trailing_allowed(token::Comma),
3497 |p| p.parse_pat()));
3498 pat = PatEnum(path, Some(args));
3503 // Parse qualified path
3504 Some(qself) => PatQPath(qself, path),
3505 // Parse nullary enum
3506 None => PatEnum(path, Some(vec![]))
3512 // Try to parse everything else as literal with optional minus
3513 let begin = try!(self.parse_pat_literal_maybe_minus());
3514 if self.eat(&token::DotDotDot) {
3515 let end = try!(self.parse_pat_range_end());
3516 pat = PatRange(begin, end);
3518 pat = PatLit(begin);
3524 let hi = self.last_span.hi;
3526 id: ast::DUMMY_NODE_ID,
3528 span: mk_sp(lo, hi),
3532 /// Parse ident or ident @ pat
3533 /// used by the copy foo and ref foo patterns to give a good
3534 /// error message when parsing mistakes like ref foo(a,b)
3535 fn parse_pat_ident(&mut self,
3536 binding_mode: ast::BindingMode)
3537 -> PResult<'a, ast::Pat_> {
3538 if !self.token.is_plain_ident() {
3539 let span = self.span;
3540 let tok_str = self.this_token_to_string();
3541 return Err(self.span_fatal(span,
3542 &format!("expected identifier, found `{}`", tok_str)))
3544 let ident = try!(self.parse_ident());
3545 let last_span = self.last_span;
3546 let name = codemap::Spanned{span: last_span, node: ident};
3547 let sub = if self.eat(&token::At) {
3548 Some(try!(self.parse_pat()))
3553 // just to be friendly, if they write something like
3555 // we end up here with ( as the current token. This shortly
3556 // leads to a parse error. Note that if there is no explicit
3557 // binding mode then we do not end up here, because the lookahead
3558 // will direct us over to parse_enum_variant()
3559 if self.token == token::OpenDelim(token::Paren) {
3560 let last_span = self.last_span;
3561 return Err(self.span_fatal(
3563 "expected identifier, found enum pattern"))
3566 Ok(PatIdent(binding_mode, name, sub))
3569 /// Parse a local variable declaration
3570 fn parse_local(&mut self, attrs: ThinAttributes) -> PResult<'a, P<Local>> {
3571 let lo = self.span.lo;
3572 let pat = try!(self.parse_pat());
3575 if self.eat(&token::Colon) {
3576 ty = Some(try!(self.parse_ty_sum()));
3578 let init = try!(self.parse_initializer());
3583 id: ast::DUMMY_NODE_ID,
3584 span: mk_sp(lo, self.last_span.hi),
3589 /// Parse a "let" stmt
3590 fn parse_let(&mut self, attrs: ThinAttributes) -> PResult<'a, P<Decl>> {
3591 let lo = self.span.lo;
3592 let local = try!(self.parse_local(attrs));
3593 Ok(P(spanned(lo, self.last_span.hi, DeclLocal(local))))
3596 /// Parse a structure field
3597 fn parse_name_and_ty(&mut self, pr: Visibility,
3598 attrs: Vec<Attribute> ) -> PResult<'a, StructField> {
3600 Inherited => self.span.lo,
3601 Public => self.last_span.lo,
3603 if !self.token.is_plain_ident() {
3604 return Err(self.fatal("expected ident"));
3606 let name = try!(self.parse_ident());
3607 try!(self.expect(&token::Colon));
3608 let ty = try!(self.parse_ty_sum());
3609 Ok(spanned(lo, self.last_span.hi, ast::StructField_ {
3610 kind: NamedField(name, pr),
3611 id: ast::DUMMY_NODE_ID,
3617 /// Emit an expected item after attributes error.
3618 fn expected_item_err(&self, attrs: &[Attribute]) {
3619 let message = match attrs.last() {
3620 Some(&Attribute { node: ast::Attribute_ { is_sugared_doc: true, .. }, .. }) => {
3621 "expected item after doc comment"
3623 _ => "expected item after attributes",
3626 self.span_err(self.last_span, message);
3629 /// Parse a statement. may include decl.
3630 pub fn parse_stmt(&mut self) -> PResult<'a, Option<P<Stmt>>> {
3631 Ok(try!(self.parse_stmt_()).map(P))
3634 fn parse_stmt_(&mut self) -> PResult<'a, Option<Stmt>> {
3635 maybe_whole!(Some deref self, NtStmt);
3637 let attrs = try!(self.parse_outer_attributes());
3638 let lo = self.span.lo;
3640 Ok(Some(if self.check_keyword(keywords::Let) {
3641 try!(self.expect_keyword(keywords::Let));
3642 let decl = try!(self.parse_let(attrs.into_thin_attrs()));
3643 let hi = decl.span.hi;
3644 let stmt = StmtDecl(decl, ast::DUMMY_NODE_ID);
3645 spanned(lo, hi, stmt)
3646 } else if self.token.is_ident()
3647 && !self.token.is_any_keyword()
3648 && self.look_ahead(1, |t| *t == token::Not) {
3649 // it's a macro invocation:
3651 // Potential trouble: if we allow macros with paths instead of
3652 // idents, we'd need to look ahead past the whole path here...
3653 let pth = try!(self.parse_path(NoTypesAllowed));
3656 let id = match self.token {
3657 token::OpenDelim(_) => token::special_idents::invalid, // no special identifier
3658 _ => try!(self.parse_ident()),
3661 // check that we're pointing at delimiters (need to check
3662 // again after the `if`, because of `parse_ident`
3663 // consuming more tokens).
3664 let delim = match self.token {
3665 token::OpenDelim(delim) => delim,
3667 // we only expect an ident if we didn't parse one
3669 let ident_str = if id.name == token::special_idents::invalid.name {
3674 let tok_str = self.this_token_to_string();
3675 return Err(self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
3681 let tts = try!(self.parse_unspanned_seq(
3682 &token::OpenDelim(delim),
3683 &token::CloseDelim(delim),
3685 |p| p.parse_token_tree()
3687 let hi = self.last_span.hi;
3689 let style = if delim == token::Brace {
3692 MacStmtWithoutBraces
3695 if id.name == token::special_idents::invalid.name {
3696 let stmt = StmtMac(P(spanned(lo,
3698 Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT })),
3700 attrs.into_thin_attrs());
3701 spanned(lo, hi, stmt)
3703 // if it has a special ident, it's definitely an item
3705 // Require a semicolon or braces.
3706 if style != MacStmtWithBraces {
3707 if !self.eat(&token::Semi) {
3708 let last_span = self.last_span;
3709 self.span_err(last_span,
3710 "macros that expand to items must \
3711 either be surrounded with braces or \
3712 followed by a semicolon");
3715 spanned(lo, hi, StmtDecl(
3716 P(spanned(lo, hi, DeclItem(
3718 lo, hi, id /*id is good here*/,
3719 ItemMac(spanned(lo, hi,
3720 Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT })),
3721 Inherited, attrs)))),
3722 ast::DUMMY_NODE_ID))
3725 // FIXME: Bad copy of attrs
3726 match try!(self.parse_item_(attrs.clone(), false, true)) {
3729 let decl = P(spanned(lo, hi, DeclItem(i)));
3730 spanned(lo, hi, StmtDecl(decl, ast::DUMMY_NODE_ID))
3733 let unused_attrs = |attrs: &[_], s: &mut Self| {
3734 if attrs.len() > 0 {
3736 "expected statement after outer attribute");
3740 // Do not attempt to parse an expression if we're done here.
3741 if self.token == token::Semi {
3742 unused_attrs(&attrs, self);
3747 if self.token == token::CloseDelim(token::Brace) {
3748 unused_attrs(&attrs, self);
3752 // Remainder are line-expr stmts.
3753 let e = try!(self.parse_expr_res(
3754 Restrictions::RESTRICTION_STMT_EXPR, Some(attrs.into_thin_attrs())));
3756 let stmt = StmtExpr(e, ast::DUMMY_NODE_ID);
3757 spanned(lo, hi, stmt)
3763 /// Is this expression a successfully-parsed statement?
3764 fn expr_is_complete(&mut self, e: &Expr) -> bool {
3765 self.restrictions.contains(Restrictions::RESTRICTION_STMT_EXPR) &&
3766 !classify::expr_requires_semi_to_be_stmt(e)
3769 /// Parse a block. No inner attrs are allowed.
3770 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
3771 maybe_whole!(no_clone self, NtBlock);
3773 let lo = self.span.lo;
3775 if !self.eat(&token::OpenDelim(token::Brace)) {
3777 let tok = self.this_token_to_string();
3778 return Err(self.span_fatal_help(sp,
3779 &format!("expected `{{`, found `{}`", tok),
3780 "place this code inside a block"));
3783 self.parse_block_tail(lo, DefaultBlock)
3786 /// Parse a block. Inner attrs are allowed.
3787 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
3788 maybe_whole!(pair_empty self, NtBlock);
3790 let lo = self.span.lo;
3791 try!(self.expect(&token::OpenDelim(token::Brace)));
3792 Ok((try!(self.parse_inner_attributes()),
3793 try!(self.parse_block_tail(lo, DefaultBlock))))
3796 /// Parse the rest of a block expression or function body
3797 /// Precondition: already parsed the '{'.
3798 fn parse_block_tail(&mut self, lo: BytePos, s: BlockCheckMode) -> PResult<'a, P<Block>> {
3799 let mut stmts = vec![];
3800 let mut expr = None;
3802 while !self.eat(&token::CloseDelim(token::Brace)) {
3803 let Spanned {node, span} = if let Some(s) = try!(self.parse_stmt_()) {
3806 // Found only `;` or `}`.
3811 try!(self.handle_expression_like_statement(e, span, &mut stmts, &mut expr));
3813 StmtMac(mac, MacStmtWithoutBraces, attrs) => {
3814 // statement macro without braces; might be an
3815 // expr depending on whether a semicolon follows
3818 stmts.push(P(Spanned {
3819 node: StmtMac(mac, MacStmtWithSemicolon, attrs),
3820 span: mk_sp(span.lo, self.span.hi),
3825 let e = self.mk_mac_expr(span.lo, span.hi,
3826 mac.and_then(|m| m.node),
3828 let e = try!(self.parse_dot_or_call_expr_with(e, attrs));
3829 let e = try!(self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e)));
3830 try!(self.handle_expression_like_statement(
3838 StmtMac(m, style, attrs) => {
3839 // statement macro; might be an expr
3842 stmts.push(P(Spanned {
3843 node: StmtMac(m, MacStmtWithSemicolon, attrs),
3844 span: mk_sp(span.lo, self.span.hi),
3848 token::CloseDelim(token::Brace) => {
3849 // if a block ends in `m!(arg)` without
3850 // a `;`, it must be an expr
3851 expr = Some(self.mk_mac_expr(span.lo, span.hi,
3852 m.and_then(|x| x.node),
3856 stmts.push(P(Spanned {
3857 node: StmtMac(m, style, attrs),
3863 _ => { // all other kinds of statements:
3864 let mut hi = span.hi;
3865 if classify::stmt_ends_with_semi(&node) {
3866 try!(self.commit_stmt_expecting(token::Semi));
3867 hi = self.last_span.hi;
3870 stmts.push(P(Spanned {
3872 span: mk_sp(span.lo, hi)
3881 id: ast::DUMMY_NODE_ID,
3883 span: mk_sp(lo, self.last_span.hi),
3887 fn handle_expression_like_statement(
3891 stmts: &mut Vec<P<Stmt>>,
3892 last_block_expr: &mut Option<P<Expr>>) -> PResult<'a, ()> {
3893 // expression without semicolon
3894 if classify::expr_requires_semi_to_be_stmt(&*e) {
3895 // Just check for errors and recover; do not eat semicolon yet.
3896 try!(self.commit_stmt(&[],
3897 &[token::Semi, token::CloseDelim(token::Brace)]));
3903 let span_with_semi = Span {
3905 hi: self.last_span.hi,
3906 expn_id: span.expn_id,
3908 stmts.push(P(Spanned {
3909 node: StmtSemi(e, ast::DUMMY_NODE_ID),
3910 span: span_with_semi,
3913 token::CloseDelim(token::Brace) => *last_block_expr = Some(e),
3915 stmts.push(P(Spanned {
3916 node: StmtExpr(e, ast::DUMMY_NODE_ID),
3924 // Parses a sequence of bounds if a `:` is found,
3925 // otherwise returns empty list.
3926 fn parse_colon_then_ty_param_bounds(&mut self,
3927 mode: BoundParsingMode)
3928 -> PResult<'a, TyParamBounds>
3930 if !self.eat(&token::Colon) {
3933 self.parse_ty_param_bounds(mode)
3937 // matches bounds = ( boundseq )?
3938 // where boundseq = ( polybound + boundseq ) | polybound
3939 // and polybound = ( 'for' '<' 'region '>' )? bound
3940 // and bound = 'region | trait_ref
3941 fn parse_ty_param_bounds(&mut self,
3942 mode: BoundParsingMode)
3943 -> PResult<'a, TyParamBounds>
3945 let mut result = vec!();
3947 let question_span = self.span;
3948 let ate_question = self.eat(&token::Question);
3950 token::Lifetime(lifetime) => {
3952 self.span_err(question_span,
3953 "`?` may only modify trait bounds, not lifetime bounds");
3955 result.push(RegionTyParamBound(ast::Lifetime {
3956 id: ast::DUMMY_NODE_ID,
3962 token::ModSep | token::Ident(..) => {
3963 let poly_trait_ref = try!(self.parse_poly_trait_ref());
3964 let modifier = if ate_question {
3965 if mode == BoundParsingMode::Modified {
3966 TraitBoundModifier::Maybe
3968 self.span_err(question_span,
3970 TraitBoundModifier::None
3973 TraitBoundModifier::None
3975 result.push(TraitTyParamBound(poly_trait_ref, modifier))
3980 if !self.eat(&token::BinOp(token::Plus)) {
3985 return Ok(P::from_vec(result));
3988 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
3989 fn parse_ty_param(&mut self) -> PResult<'a, TyParam> {
3990 let span = self.span;
3991 let ident = try!(self.parse_ident());
3993 let bounds = try!(self.parse_colon_then_ty_param_bounds(BoundParsingMode::Modified));
3995 let default = if self.check(&token::Eq) {
3997 Some(try!(self.parse_ty_sum()))
4004 id: ast::DUMMY_NODE_ID,
4011 /// Parse a set of optional generic type parameter declarations. Where
4012 /// clauses are not parsed here, and must be added later via
4013 /// `parse_where_clause()`.
4015 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
4016 /// | ( < lifetimes , typaramseq ( , )? > )
4017 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
4018 pub fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
4019 maybe_whole!(self, NtGenerics);
4021 if self.eat(&token::Lt) {
4022 let lifetime_defs = try!(self.parse_lifetime_defs());
4023 let mut seen_default = false;
4024 let ty_params = try!(self.parse_seq_to_gt(Some(token::Comma), |p| {
4025 try!(p.forbid_lifetime());
4026 let ty_param = try!(p.parse_ty_param());
4027 if ty_param.default.is_some() {
4028 seen_default = true;
4029 } else if seen_default {
4030 let last_span = p.last_span;
4031 p.span_err(last_span,
4032 "type parameters with a default must be trailing");
4037 lifetimes: lifetime_defs,
4038 ty_params: ty_params,
4039 where_clause: WhereClause {
4040 id: ast::DUMMY_NODE_ID,
4041 predicates: Vec::new(),
4045 Ok(ast::Generics::default())
4049 fn parse_generic_values_after_lt(&mut self) -> PResult<'a, (Vec<ast::Lifetime>,
4051 Vec<P<TypeBinding>>)> {
4052 let span_lo = self.span.lo;
4053 let lifetimes = try!(self.parse_lifetimes(token::Comma));
4055 let missing_comma = !lifetimes.is_empty() &&
4056 !self.token.is_like_gt() &&
4058 .as_ref().map_or(true,
4059 |x| &**x != &token::Comma);
4063 let msg = format!("expected `,` or `>` after lifetime \
4065 self.this_token_to_string());
4066 let mut err = self.diagnostic().struct_span_err(self.span, &msg);
4068 let span_hi = self.span.hi;
4069 let span_hi = match self.parse_ty() {
4070 Ok(..) => self.span.hi,
4071 Err(ref mut err) => {
4077 let msg = format!("did you mean a single argument type &'a Type, \
4078 or did you mean the comma-separated arguments \
4080 err.span_note(mk_sp(span_lo, span_hi), &msg);
4083 self.abort_if_errors()
4086 // First parse types.
4087 let (types, returned) = try!(self.parse_seq_to_gt_or_return(
4090 try!(p.forbid_lifetime());
4091 if p.look_ahead(1, |t| t == &token::Eq) {
4094 Ok(Some(try!(p.parse_ty_sum())))
4099 // If we found the `>`, don't continue.
4101 return Ok((lifetimes, types.into_vec(), Vec::new()));
4104 // Then parse type bindings.
4105 let bindings = try!(self.parse_seq_to_gt(
4108 try!(p.forbid_lifetime());
4110 let ident = try!(p.parse_ident());
4111 let found_eq = p.eat(&token::Eq);
4114 p.span_warn(span, "whoops, no =?");
4116 let ty = try!(p.parse_ty());
4117 let hi = ty.span.hi;
4118 let span = mk_sp(lo, hi);
4119 return Ok(P(TypeBinding{id: ast::DUMMY_NODE_ID,
4126 Ok((lifetimes, types.into_vec(), bindings.into_vec()))
4129 fn forbid_lifetime(&mut self) -> PResult<'a, ()> {
4130 if self.token.is_lifetime() {
4131 let span = self.span;
4132 return Err(self.span_fatal(span, "lifetime parameters must be declared \
4133 prior to type parameters"))
4138 /// Parses an optional `where` clause and places it in `generics`.
4141 /// where T : Trait<U, V> + 'b, 'a : 'b
4143 pub fn parse_where_clause(&mut self) -> PResult<'a, ast::WhereClause> {
4144 maybe_whole!(self, NtWhereClause);
4146 let mut where_clause = WhereClause {
4147 id: ast::DUMMY_NODE_ID,
4148 predicates: Vec::new(),
4151 if !self.eat_keyword(keywords::Where) {
4152 return Ok(where_clause);
4155 let mut parsed_something = false;
4157 let lo = self.span.lo;
4159 token::OpenDelim(token::Brace) => {
4163 token::Lifetime(..) => {
4164 let bounded_lifetime =
4165 try!(self.parse_lifetime());
4167 self.eat(&token::Colon);
4170 try!(self.parse_lifetimes(token::BinOp(token::Plus)));
4172 let hi = self.last_span.hi;
4173 let span = mk_sp(lo, hi);
4175 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
4176 ast::WhereRegionPredicate {
4178 lifetime: bounded_lifetime,
4183 parsed_something = true;
4187 let bound_lifetimes = if self.eat_keyword(keywords::For) {
4188 // Higher ranked constraint.
4189 try!(self.expect(&token::Lt));
4190 let lifetime_defs = try!(self.parse_lifetime_defs());
4191 try!(self.expect_gt());
4197 let bounded_ty = try!(self.parse_ty());
4199 if self.eat(&token::Colon) {
4200 let bounds = try!(self.parse_ty_param_bounds(BoundParsingMode::Bare));
4201 let hi = self.last_span.hi;
4202 let span = mk_sp(lo, hi);
4204 if bounds.is_empty() {
4206 "each predicate in a `where` clause must have \
4207 at least one bound in it");
4210 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
4211 ast::WhereBoundPredicate {
4213 bound_lifetimes: bound_lifetimes,
4214 bounded_ty: bounded_ty,
4218 parsed_something = true;
4219 } else if self.eat(&token::Eq) {
4220 // let ty = try!(self.parse_ty());
4221 let hi = self.last_span.hi;
4222 let span = mk_sp(lo, hi);
4223 // where_clause.predicates.push(
4224 // ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
4225 // id: ast::DUMMY_NODE_ID,
4227 // path: panic!("NYI"), //bounded_ty,
4230 // parsed_something = true;
4233 "equality constraints are not yet supported \
4234 in where clauses (#20041)");
4236 let last_span = self.last_span;
4237 self.span_err(last_span,
4238 "unexpected token in `where` clause");
4243 if !self.eat(&token::Comma) {
4248 if !parsed_something {
4249 let last_span = self.last_span;
4250 self.span_err(last_span,
4251 "a `where` clause must have at least one predicate \
4258 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
4259 -> PResult<'a, (Vec<Arg> , bool)> {
4261 let mut args: Vec<Option<Arg>> =
4262 try!(self.parse_unspanned_seq(
4263 &token::OpenDelim(token::Paren),
4264 &token::CloseDelim(token::Paren),
4265 seq_sep_trailing_allowed(token::Comma),
4267 if p.token == token::DotDotDot {
4270 if p.token != token::CloseDelim(token::Paren) {
4272 return Err(p.span_fatal(span,
4273 "`...` must be last in argument list for variadic function"))
4277 return Err(p.span_fatal(span,
4278 "only foreign functions are allowed to be variadic"))
4282 Ok(Some(try!(p.parse_arg_general(named_args))))
4287 let variadic = match args.pop() {
4290 // Need to put back that last arg
4297 if variadic && args.is_empty() {
4299 "variadic function must be declared with at least one named argument");
4302 let args = args.into_iter().map(|x| x.unwrap()).collect();
4304 Ok((args, variadic))
4307 /// Parse the argument list and result type of a function declaration
4308 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> {
4310 let (args, variadic) = try!(self.parse_fn_args(true, allow_variadic));
4311 let ret_ty = try!(self.parse_ret_ty());
4320 fn is_self_ident(&mut self) -> bool {
4322 token::Ident(id, token::Plain) => id.name == special_idents::self_.name,
4327 fn expect_self_ident(&mut self) -> PResult<'a, ast::Ident> {
4329 token::Ident(id, token::Plain) if id.name == special_idents::self_.name => {
4334 let token_str = self.this_token_to_string();
4335 return Err(self.fatal(&format!("expected `self`, found `{}`",
4341 fn is_self_type_ident(&mut self) -> bool {
4343 token::Ident(id, token::Plain) => id.name == special_idents::type_self.name,
4348 fn expect_self_type_ident(&mut self) -> PResult<'a, ast::Ident> {
4350 token::Ident(id, token::Plain) if id.name == special_idents::type_self.name => {
4355 let token_str = self.this_token_to_string();
4356 Err(self.fatal(&format!("expected `Self`, found `{}`",
4362 /// Parse the argument list and result type of a function
4363 /// that may have a self type.
4364 fn parse_fn_decl_with_self<F>(&mut self,
4365 parse_arg_fn: F) -> PResult<'a, (ExplicitSelf, P<FnDecl>)> where
4366 F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
4368 fn maybe_parse_borrowed_explicit_self<'b>(this: &mut Parser<'b>)
4369 -> PResult<'b, ast::ExplicitSelf_> {
4370 // The following things are possible to see here:
4375 // fn(&'lt mut self)
4377 // We already know that the current token is `&`.
4379 if this.look_ahead(1, |t| t.is_keyword(keywords::SelfValue)) {
4381 Ok(SelfRegion(None, MutImmutable, try!(this.expect_self_ident())))
4382 } else if this.look_ahead(1, |t| t.is_mutability()) &&
4383 this.look_ahead(2, |t| t.is_keyword(keywords::SelfValue)) {
4385 let mutability = try!(this.parse_mutability());
4386 Ok(SelfRegion(None, mutability, try!(this.expect_self_ident())))
4387 } else if this.look_ahead(1, |t| t.is_lifetime()) &&
4388 this.look_ahead(2, |t| t.is_keyword(keywords::SelfValue)) {
4390 let lifetime = try!(this.parse_lifetime());
4391 Ok(SelfRegion(Some(lifetime), MutImmutable, try!(this.expect_self_ident())))
4392 } else if this.look_ahead(1, |t| t.is_lifetime()) &&
4393 this.look_ahead(2, |t| t.is_mutability()) &&
4394 this.look_ahead(3, |t| t.is_keyword(keywords::SelfValue)) {
4396 let lifetime = try!(this.parse_lifetime());
4397 let mutability = try!(this.parse_mutability());
4398 Ok(SelfRegion(Some(lifetime), mutability, try!(this.expect_self_ident())))
4404 try!(self.expect(&token::OpenDelim(token::Paren)));
4406 // A bit of complexity and lookahead is needed here in order to be
4407 // backwards compatible.
4408 let lo = self.span.lo;
4409 let mut self_ident_lo = self.span.lo;
4410 let mut self_ident_hi = self.span.hi;
4412 let mut mutbl_self = MutImmutable;
4413 let explicit_self = match self.token {
4414 token::BinOp(token::And) => {
4415 let eself = try!(maybe_parse_borrowed_explicit_self(self));
4416 self_ident_lo = self.last_span.lo;
4417 self_ident_hi = self.last_span.hi;
4420 token::BinOp(token::Star) => {
4421 // Possibly "*self" or "*mut self" -- not supported. Try to avoid
4422 // emitting cryptic "unexpected token" errors.
4424 let _mutability = if self.token.is_mutability() {
4425 try!(self.parse_mutability())
4429 if self.is_self_ident() {
4430 let span = self.span;
4431 self.span_err(span, "cannot pass self by raw pointer");
4434 // error case, making bogus self ident:
4435 SelfValue(special_idents::self_)
4437 token::Ident(..) => {
4438 if self.is_self_ident() {
4439 let self_ident = try!(self.expect_self_ident());
4441 // Determine whether this is the fully explicit form, `self:
4443 if self.eat(&token::Colon) {
4444 SelfExplicit(try!(self.parse_ty_sum()), self_ident)
4446 SelfValue(self_ident)
4448 } else if self.token.is_mutability() &&
4449 self.look_ahead(1, |t| t.is_keyword(keywords::SelfValue)) {
4450 mutbl_self = try!(self.parse_mutability());
4451 let self_ident = try!(self.expect_self_ident());
4453 // Determine whether this is the fully explicit form,
4455 if self.eat(&token::Colon) {
4456 SelfExplicit(try!(self.parse_ty_sum()), self_ident)
4458 SelfValue(self_ident)
4467 let explicit_self_sp = mk_sp(self_ident_lo, self_ident_hi);
4469 // shared fall-through for the three cases below. borrowing prevents simply
4470 // writing this as a closure
4471 macro_rules! parse_remaining_arguments {
4474 // If we parsed a self type, expect a comma before the argument list.
4478 let sep = seq_sep_trailing_allowed(token::Comma);
4479 let mut fn_inputs = try!(self.parse_seq_to_before_end(
4480 &token::CloseDelim(token::Paren),
4484 fn_inputs.insert(0, Arg::new_self(explicit_self_sp, mutbl_self, $self_id));
4487 token::CloseDelim(token::Paren) => {
4488 vec!(Arg::new_self(explicit_self_sp, mutbl_self, $self_id))
4491 let token_str = self.this_token_to_string();
4492 return Err(self.fatal(&format!("expected `,` or `)`, found `{}`",
4499 let fn_inputs = match explicit_self {
4501 let sep = seq_sep_trailing_allowed(token::Comma);
4502 try!(self.parse_seq_to_before_end(&token::CloseDelim(token::Paren),
4505 SelfValue(id) => parse_remaining_arguments!(id),
4506 SelfRegion(_,_,id) => parse_remaining_arguments!(id),
4507 SelfExplicit(_,id) => parse_remaining_arguments!(id),
4511 try!(self.expect(&token::CloseDelim(token::Paren)));
4513 let hi = self.span.hi;
4515 let ret_ty = try!(self.parse_ret_ty());
4517 let fn_decl = P(FnDecl {
4523 Ok((spanned(lo, hi, explicit_self), fn_decl))
4526 // parse the |arg, arg| header on a lambda
4527 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
4528 let inputs_captures = {
4529 if self.eat(&token::OrOr) {
4532 try!(self.expect(&token::BinOp(token::Or)));
4533 try!(self.parse_obsolete_closure_kind());
4534 let args = try!(self.parse_seq_to_before_end(
4535 &token::BinOp(token::Or),
4536 seq_sep_trailing_allowed(token::Comma),
4537 |p| p.parse_fn_block_arg()
4543 let output = try!(self.parse_ret_ty());
4546 inputs: inputs_captures,
4552 /// Parse the name and optional generic types of a function header.
4553 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
4554 let id = try!(self.parse_ident());
4555 let generics = try!(self.parse_generics());
4559 fn mk_item(&mut self, lo: BytePos, hi: BytePos, ident: Ident,
4560 node: Item_, vis: Visibility,
4561 attrs: Vec<Attribute>) -> P<Item> {
4565 id: ast::DUMMY_NODE_ID,
4572 /// Parse an item-position function declaration.
4573 fn parse_item_fn(&mut self,
4575 constness: Constness,
4577 -> PResult<'a, ItemInfo> {
4578 let (ident, mut generics) = try!(self.parse_fn_header());
4579 let decl = try!(self.parse_fn_decl(false));
4580 generics.where_clause = try!(self.parse_where_clause());
4581 let (inner_attrs, body) = try!(self.parse_inner_attrs_and_block());
4582 Ok((ident, ItemFn(decl, unsafety, constness, abi, generics, body), Some(inner_attrs)))
4585 /// true if we are looking at `const ID`, false for things like `const fn` etc
4586 pub fn is_const_item(&mut self) -> bool {
4587 self.token.is_keyword(keywords::Const) &&
4588 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
4589 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
4592 /// parses all the "front matter" for a `fn` declaration, up to
4593 /// and including the `fn` keyword:
4597 /// - `const unsafe fn`
4600 pub fn parse_fn_front_matter(&mut self)
4601 -> PResult<'a, (ast::Constness, ast::Unsafety, abi::Abi)> {
4602 let is_const_fn = self.eat_keyword(keywords::Const);
4603 let unsafety = try!(self.parse_unsafety());
4604 let (constness, unsafety, abi) = if is_const_fn {
4605 (Constness::Const, unsafety, abi::Rust)
4607 let abi = if self.eat_keyword(keywords::Extern) {
4608 try!(self.parse_opt_abi()).unwrap_or(abi::C)
4612 (Constness::NotConst, unsafety, abi)
4614 try!(self.expect_keyword(keywords::Fn));
4615 Ok((constness, unsafety, abi))
4618 /// Parse an impl item.
4619 pub fn parse_impl_item(&mut self) -> PResult<'a, P<ImplItem>> {
4620 maybe_whole!(no_clone self, NtImplItem);
4622 let mut attrs = try!(self.parse_outer_attributes());
4623 let lo = self.span.lo;
4624 let vis = try!(self.parse_visibility());
4625 let (name, node) = if self.eat_keyword(keywords::Type) {
4626 let name = try!(self.parse_ident());
4627 try!(self.expect(&token::Eq));
4628 let typ = try!(self.parse_ty_sum());
4629 try!(self.expect(&token::Semi));
4630 (name, ast::ImplItemKind::Type(typ))
4631 } else if self.is_const_item() {
4632 try!(self.expect_keyword(keywords::Const));
4633 let name = try!(self.parse_ident());
4634 try!(self.expect(&token::Colon));
4635 let typ = try!(self.parse_ty_sum());
4636 try!(self.expect(&token::Eq));
4637 let expr = try!(self.parse_expr());
4638 try!(self.commit_expr_expecting(&expr, token::Semi));
4639 (name, ast::ImplItemKind::Const(typ, expr))
4641 let (name, inner_attrs, node) = try!(self.parse_impl_method(vis));
4642 attrs.extend(inner_attrs);
4647 id: ast::DUMMY_NODE_ID,
4648 span: mk_sp(lo, self.last_span.hi),
4656 fn complain_if_pub_macro(&mut self, visa: Visibility, span: Span) {
4659 let is_macro_rules: bool = match self.token {
4660 token::Ident(sid, _) => sid.name == intern("macro_rules"),
4664 self.diagnostic().struct_span_err(span, "can't qualify macro_rules \
4665 invocation with `pub`")
4666 .fileline_help(span, "did you mean #[macro_export]?")
4669 self.diagnostic().struct_span_err(span, "can't qualify macro \
4670 invocation with `pub`")
4671 .fileline_help(span, "try adjusting the macro to put `pub` \
4672 inside the invocation")
4680 /// Parse a method or a macro invocation in a trait impl.
4681 fn parse_impl_method(&mut self, vis: Visibility)
4682 -> PResult<'a, (Ident, Vec<ast::Attribute>, ast::ImplItemKind)> {
4683 // code copied from parse_macro_use_or_failure... abstraction!
4684 if !self.token.is_any_keyword()
4685 && self.look_ahead(1, |t| *t == token::Not)
4686 && (self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren))
4687 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) {
4690 let last_span = self.last_span;
4691 self.complain_if_pub_macro(vis, last_span);
4693 let lo = self.span.lo;
4694 let pth = try!(self.parse_path(NoTypesAllowed));
4695 try!(self.expect(&token::Not));
4697 // eat a matched-delimiter token tree:
4698 let delim = try!(self.expect_open_delim());
4699 let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
4701 |p| p.parse_token_tree()));
4702 let m_ = Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT };
4703 let m: ast::Mac = codemap::Spanned { node: m_,
4705 self.last_span.hi) };
4706 if delim != token::Brace {
4707 try!(self.expect(&token::Semi))
4709 Ok((token::special_idents::invalid, vec![], ast::ImplItemKind::Macro(m)))
4711 let (constness, unsafety, abi) = try!(self.parse_fn_front_matter());
4712 let ident = try!(self.parse_ident());
4713 let mut generics = try!(self.parse_generics());
4714 let (explicit_self, decl) = try!(self.parse_fn_decl_with_self(|p| {
4717 generics.where_clause = try!(self.parse_where_clause());
4718 let (inner_attrs, body) = try!(self.parse_inner_attrs_and_block());
4719 Ok((ident, inner_attrs, ast::ImplItemKind::Method(ast::MethodSig {
4722 explicit_self: explicit_self,
4724 constness: constness,
4730 /// Parse trait Foo { ... }
4731 fn parse_item_trait(&mut self, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
4733 let ident = try!(self.parse_ident());
4734 let mut tps = try!(self.parse_generics());
4736 // Parse supertrait bounds.
4737 let bounds = try!(self.parse_colon_then_ty_param_bounds(BoundParsingMode::Bare));
4739 tps.where_clause = try!(self.parse_where_clause());
4741 let meths = try!(self.parse_trait_items());
4742 Ok((ident, ItemTrait(unsafety, tps, bounds, meths), None))
4745 /// Parses items implementations variants
4746 /// impl<T> Foo { ... }
4747 /// impl<T> ToString for &'static T { ... }
4748 /// impl Send for .. {}
4749 fn parse_item_impl(&mut self, unsafety: ast::Unsafety) -> PResult<'a, ItemInfo> {
4750 let impl_span = self.span;
4752 // First, parse type parameters if necessary.
4753 let mut generics = try!(self.parse_generics());
4755 // Special case: if the next identifier that follows is '(', don't
4756 // allow this to be parsed as a trait.
4757 let could_be_trait = self.token != token::OpenDelim(token::Paren);
4759 let neg_span = self.span;
4760 let polarity = if self.eat(&token::Not) {
4761 ast::ImplPolarity::Negative
4763 ast::ImplPolarity::Positive
4767 let mut ty = try!(self.parse_ty_sum());
4769 // Parse traits, if necessary.
4770 let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) {
4771 // New-style trait. Reinterpret the type as a trait.
4773 TyPath(None, ref path) => {
4775 path: (*path).clone(),
4780 self.span_err(ty.span, "not a trait");
4786 ast::ImplPolarity::Negative => {
4787 // This is a negated type implementation
4788 // `impl !MyType {}`, which is not allowed.
4789 self.span_err(neg_span, "inherent implementation can't be negated");
4796 if opt_trait.is_some() && self.eat(&token::DotDot) {
4797 if generics.is_parameterized() {
4798 self.span_err(impl_span, "default trait implementations are not \
4799 allowed to have generics");
4802 try!(self.expect(&token::OpenDelim(token::Brace)));
4803 try!(self.expect(&token::CloseDelim(token::Brace)));
4804 Ok((ast_util::impl_pretty_name(&opt_trait, None),
4805 ItemDefaultImpl(unsafety, opt_trait.unwrap()), None))
4807 if opt_trait.is_some() {
4808 ty = try!(self.parse_ty_sum());
4810 generics.where_clause = try!(self.parse_where_clause());
4812 try!(self.expect(&token::OpenDelim(token::Brace)));
4813 let attrs = try!(self.parse_inner_attributes());
4815 let mut impl_items = vec![];
4816 while !self.eat(&token::CloseDelim(token::Brace)) {
4817 impl_items.push(try!(self.parse_impl_item()));
4820 Ok((ast_util::impl_pretty_name(&opt_trait, Some(&*ty)),
4821 ItemImpl(unsafety, polarity, generics, opt_trait, ty, impl_items),
4826 /// Parse a::B<String,i32>
4827 fn parse_trait_ref(&mut self) -> PResult<'a, TraitRef> {
4829 path: try!(self.parse_path(LifetimeAndTypesWithoutColons)),
4830 ref_id: ast::DUMMY_NODE_ID,
4834 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<ast::LifetimeDef>> {
4835 if self.eat_keyword(keywords::For) {
4836 try!(self.expect(&token::Lt));
4837 let lifetime_defs = try!(self.parse_lifetime_defs());
4838 try!(self.expect_gt());
4845 /// Parse for<'l> a::B<String,i32>
4846 fn parse_poly_trait_ref(&mut self) -> PResult<'a, PolyTraitRef> {
4847 let lo = self.span.lo;
4848 let lifetime_defs = try!(self.parse_late_bound_lifetime_defs());
4850 Ok(ast::PolyTraitRef {
4851 bound_lifetimes: lifetime_defs,
4852 trait_ref: try!(self.parse_trait_ref()),
4853 span: mk_sp(lo, self.last_span.hi),
4857 /// Parse struct Foo { ... }
4858 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
4859 let class_name = try!(self.parse_ident());
4860 let mut generics = try!(self.parse_generics());
4862 // There is a special case worth noting here, as reported in issue #17904.
4863 // If we are parsing a tuple struct it is the case that the where clause
4864 // should follow the field list. Like so:
4866 // struct Foo<T>(T) where T: Copy;
4868 // If we are parsing a normal record-style struct it is the case
4869 // that the where clause comes before the body, and after the generics.
4870 // So if we look ahead and see a brace or a where-clause we begin
4871 // parsing a record style struct.
4873 // Otherwise if we look ahead and see a paren we parse a tuple-style
4876 let vdata = if self.token.is_keyword(keywords::Where) {
4877 generics.where_clause = try!(self.parse_where_clause());
4878 if self.eat(&token::Semi) {
4879 // If we see a: `struct Foo<T> where T: Copy;` style decl.
4880 VariantData::Unit(ast::DUMMY_NODE_ID)
4882 // If we see: `struct Foo<T> where T: Copy { ... }`
4883 VariantData::Struct(try!(self.parse_record_struct_body(ParsePub::Yes)),
4886 // No `where` so: `struct Foo<T>;`
4887 } else if self.eat(&token::Semi) {
4888 VariantData::Unit(ast::DUMMY_NODE_ID)
4889 // Record-style struct definition
4890 } else if self.token == token::OpenDelim(token::Brace) {
4891 VariantData::Struct(try!(self.parse_record_struct_body(ParsePub::Yes)),
4893 // Tuple-style struct definition with optional where-clause.
4894 } else if self.token == token::OpenDelim(token::Paren) {
4895 let body = VariantData::Tuple(try!(self.parse_tuple_struct_body(ParsePub::Yes)),
4896 ast::DUMMY_NODE_ID);
4897 generics.where_clause = try!(self.parse_where_clause());
4898 try!(self.expect(&token::Semi));
4901 let token_str = self.this_token_to_string();
4902 return Err(self.fatal(&format!("expected `where`, `{{`, `(`, or `;` after struct \
4903 name, found `{}`", token_str)))
4906 Ok((class_name, ItemStruct(vdata, generics), None))
4909 pub fn parse_record_struct_body(&mut self,
4910 parse_pub: ParsePub)
4911 -> PResult<'a, Vec<StructField>> {
4912 let mut fields = Vec::new();
4913 if self.eat(&token::OpenDelim(token::Brace)) {
4914 while self.token != token::CloseDelim(token::Brace) {
4915 fields.push(try!(self.parse_struct_decl_field(parse_pub)));
4920 let token_str = self.this_token_to_string();
4921 return Err(self.fatal(&format!("expected `where`, or `{{` after struct \
4929 pub fn parse_tuple_struct_body(&mut self,
4930 parse_pub: ParsePub)
4931 -> PResult<'a, Vec<StructField>> {
4932 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
4933 // Unit like structs are handled in parse_item_struct function
4934 let fields = try!(self.parse_unspanned_seq(
4935 &token::OpenDelim(token::Paren),
4936 &token::CloseDelim(token::Paren),
4937 seq_sep_trailing_allowed(token::Comma),
4939 let attrs = try!(p.parse_outer_attributes());
4941 let struct_field_ = ast::StructField_ {
4942 kind: UnnamedField (
4943 if parse_pub == ParsePub::Yes {
4944 try!(p.parse_visibility())
4949 id: ast::DUMMY_NODE_ID,
4950 ty: try!(p.parse_ty_sum()),
4953 Ok(spanned(lo, p.span.hi, struct_field_))
4959 /// Parse a structure field declaration
4960 pub fn parse_single_struct_field(&mut self,
4962 attrs: Vec<Attribute> )
4963 -> PResult<'a, StructField> {
4964 let a_var = try!(self.parse_name_and_ty(vis, attrs));
4969 token::CloseDelim(token::Brace) => {}
4971 let span = self.span;
4972 let token_str = self.this_token_to_string();
4973 return Err(self.span_fatal_help(span,
4974 &format!("expected `,`, or `}}`, found `{}`",
4976 "struct fields should be separated by commas"))
4982 /// Parse an element of a struct definition
4983 fn parse_struct_decl_field(&mut self, parse_pub: ParsePub) -> PResult<'a, StructField> {
4985 let attrs = try!(self.parse_outer_attributes());
4987 if self.eat_keyword(keywords::Pub) {
4988 if parse_pub == ParsePub::No {
4989 let span = self.last_span;
4990 self.span_err(span, "`pub` is not allowed here");
4992 return self.parse_single_struct_field(Public, attrs);
4995 return self.parse_single_struct_field(Inherited, attrs);
4998 /// Parse visibility: PUB or nothing
4999 fn parse_visibility(&mut self) -> PResult<'a, Visibility> {
5000 if self.eat_keyword(keywords::Pub) { Ok(Public) }
5001 else { Ok(Inherited) }
5004 /// Given a termination token, parse all of the items in a module
5005 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: BytePos) -> PResult<'a, Mod> {
5006 let mut items = vec![];
5007 while let Some(item) = try!(self.parse_item()) {
5011 if !self.eat(term) {
5012 let token_str = self.this_token_to_string();
5013 return Err(self.fatal(&format!("expected item, found `{}`", token_str)));
5016 let hi = if self.span == codemap::DUMMY_SP {
5023 inner: mk_sp(inner_lo, hi),
5028 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
5029 let id = try!(self.parse_ident());
5030 try!(self.expect(&token::Colon));
5031 let ty = try!(self.parse_ty_sum());
5032 try!(self.expect(&token::Eq));
5033 let e = try!(self.parse_expr());
5034 try!(self.commit_expr_expecting(&*e, token::Semi));
5035 let item = match m {
5036 Some(m) => ItemStatic(ty, m, e),
5037 None => ItemConst(ty, e),
5039 Ok((id, item, None))
5042 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
5043 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
5044 let id_span = self.span;
5045 let id = try!(self.parse_ident());
5046 if self.check(&token::Semi) {
5048 // This mod is in an external file. Let's go get it!
5049 let (m, attrs) = try!(self.eval_src_mod(id, outer_attrs, id_span));
5050 Ok((id, m, Some(attrs)))
5052 self.push_mod_path(id, outer_attrs);
5053 try!(self.expect(&token::OpenDelim(token::Brace)));
5054 let mod_inner_lo = self.span.lo;
5055 let old_owns_directory = self.owns_directory;
5056 self.owns_directory = true;
5057 let attrs = try!(self.parse_inner_attributes());
5058 let m = try!(self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo));
5059 self.owns_directory = old_owns_directory;
5060 self.pop_mod_path();
5061 Ok((id, ItemMod(m), Some(attrs)))
5065 fn push_mod_path(&mut self, id: Ident, attrs: &[Attribute]) {
5066 let default_path = self.id_to_interned_str(id);
5067 let file_path = match ::attr::first_attr_value_str_by_name(attrs, "path") {
5069 None => default_path,
5071 self.mod_path_stack.push(file_path)
5074 fn pop_mod_path(&mut self) {
5075 self.mod_path_stack.pop().unwrap();
5078 pub fn submod_path_from_attr(attrs: &[ast::Attribute], dir_path: &Path) -> Option<PathBuf> {
5079 ::attr::first_attr_value_str_by_name(attrs, "path").map(|d| dir_path.join(&*d))
5082 /// Returns either a path to a module, or .
5083 pub fn default_submod_path(id: ast::Ident, dir_path: &Path, codemap: &CodeMap) -> ModulePath
5085 let mod_name = id.to_string();
5086 let default_path_str = format!("{}.rs", mod_name);
5087 let secondary_path_str = format!("{}/mod.rs", mod_name);
5088 let default_path = dir_path.join(&default_path_str);
5089 let secondary_path = dir_path.join(&secondary_path_str);
5090 let default_exists = codemap.file_exists(&default_path);
5091 let secondary_exists = codemap.file_exists(&secondary_path);
5093 let result = match (default_exists, secondary_exists) {
5094 (true, false) => Ok(ModulePathSuccess { path: default_path, owns_directory: false }),
5095 (false, true) => Ok(ModulePathSuccess { path: secondary_path, owns_directory: true }),
5096 (false, false) => Err(ModulePathError {
5097 err_msg: format!("file not found for module `{}`", mod_name),
5098 help_msg: format!("name the file either {} or {} inside the directory {:?}",
5101 dir_path.display()),
5103 (true, true) => Err(ModulePathError {
5104 err_msg: format!("file for module `{}` found at both {} and {}",
5107 secondary_path_str),
5108 help_msg: "delete or rename one of them to remove the ambiguity".to_owned(),
5114 path_exists: default_exists || secondary_exists,
5119 fn submod_path(&mut self,
5121 outer_attrs: &[ast::Attribute],
5122 id_sp: Span) -> PResult<'a, ModulePathSuccess> {
5123 let mut prefix = PathBuf::from(&self.sess.codemap().span_to_filename(self.span));
5125 let mut dir_path = prefix;
5126 for part in &self.mod_path_stack {
5127 dir_path.push(&**part);
5130 if let Some(p) = Parser::submod_path_from_attr(outer_attrs, &dir_path) {
5131 return Ok(ModulePathSuccess { path: p, owns_directory: true });
5134 let paths = Parser::default_submod_path(id, &dir_path, self.sess.codemap());
5136 if !self.owns_directory {
5137 let mut err = self.diagnostic().struct_span_err(id_sp,
5138 "cannot declare a new module at this location");
5139 let this_module = match self.mod_path_stack.last() {
5140 Some(name) => name.to_string(),
5141 None => self.root_module_name.as_ref().unwrap().clone(),
5143 err.span_note(id_sp,
5144 &format!("maybe move this module `{0}` to its own directory \
5147 if paths.path_exists {
5148 err.span_note(id_sp,
5149 &format!("... or maybe `use` the module `{}` instead \
5150 of possibly redeclaring it",
5154 self.abort_if_errors();
5157 match paths.result {
5158 Ok(succ) => Ok(succ),
5159 Err(err) => Err(self.span_fatal_help(id_sp, &err.err_msg, &err.help_msg)),
5163 /// Read a module from a source file.
5164 fn eval_src_mod(&mut self,
5166 outer_attrs: &[ast::Attribute],
5168 -> PResult<'a, (ast::Item_, Vec<ast::Attribute> )> {
5169 let ModulePathSuccess { path, owns_directory } = try!(self.submod_path(id,
5173 self.eval_src_mod_from_path(path,
5179 fn eval_src_mod_from_path(&mut self,
5181 owns_directory: bool,
5183 id_sp: Span) -> PResult<'a, (ast::Item_, Vec<ast::Attribute> )> {
5184 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
5185 match included_mod_stack.iter().position(|p| *p == path) {
5187 let mut err = String::from("circular modules: ");
5188 let len = included_mod_stack.len();
5189 for p in &included_mod_stack[i.. len] {
5190 err.push_str(&p.to_string_lossy());
5191 err.push_str(" -> ");
5193 err.push_str(&path.to_string_lossy());
5194 return Err(self.span_fatal(id_sp, &err[..]));
5198 included_mod_stack.push(path.clone());
5199 drop(included_mod_stack);
5201 let mut p0 = new_sub_parser_from_file(self.sess,
5207 let mod_inner_lo = p0.span.lo;
5208 let mod_attrs = try!(p0.parse_inner_attributes());
5209 let m0 = try!(p0.parse_mod_items(&token::Eof, mod_inner_lo));
5210 self.sess.included_mod_stack.borrow_mut().pop();
5211 Ok((ast::ItemMod(m0), mod_attrs))
5214 /// Parse a function declaration from a foreign module
5215 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: BytePos,
5216 attrs: Vec<Attribute>) -> PResult<'a, P<ForeignItem>> {
5217 try!(self.expect_keyword(keywords::Fn));
5219 let (ident, mut generics) = try!(self.parse_fn_header());
5220 let decl = try!(self.parse_fn_decl(true));
5221 generics.where_clause = try!(self.parse_where_clause());
5222 let hi = self.span.hi;
5223 try!(self.expect(&token::Semi));
5224 Ok(P(ast::ForeignItem {
5227 node: ForeignItemFn(decl, generics),
5228 id: ast::DUMMY_NODE_ID,
5229 span: mk_sp(lo, hi),
5234 /// Parse a static item from a foreign module
5235 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: BytePos,
5236 attrs: Vec<Attribute>) -> PResult<'a, P<ForeignItem>> {
5237 try!(self.expect_keyword(keywords::Static));
5238 let mutbl = self.eat_keyword(keywords::Mut);
5240 let ident = try!(self.parse_ident());
5241 try!(self.expect(&token::Colon));
5242 let ty = try!(self.parse_ty_sum());
5243 let hi = self.span.hi;
5244 try!(self.expect(&token::Semi));
5248 node: ForeignItemStatic(ty, mutbl),
5249 id: ast::DUMMY_NODE_ID,
5250 span: mk_sp(lo, hi),
5255 /// Parse extern crate links
5259 /// extern crate foo;
5260 /// extern crate bar as foo;
5261 fn parse_item_extern_crate(&mut self,
5263 visibility: Visibility,
5264 attrs: Vec<Attribute>)
5265 -> PResult<'a, P<Item>> {
5267 let crate_name = try!(self.parse_ident());
5268 let (maybe_path, ident) = if let Some(ident) = try!(self.parse_rename()) {
5269 (Some(crate_name.name), ident)
5273 try!(self.expect(&token::Semi));
5275 let last_span = self.last_span;
5277 if visibility == ast::Public {
5278 self.span_warn(mk_sp(lo, last_span.hi),
5279 "`pub extern crate` does not work as expected and should not be used. \
5280 Likely to become an error. Prefer `extern crate` and `pub use`.");
5286 ItemExternCrate(maybe_path),
5291 /// Parse `extern` for foreign ABIs
5294 /// `extern` is expected to have been
5295 /// consumed before calling this method
5301 fn parse_item_foreign_mod(&mut self,
5303 opt_abi: Option<abi::Abi>,
5304 visibility: Visibility,
5305 mut attrs: Vec<Attribute>)
5306 -> PResult<'a, P<Item>> {
5307 try!(self.expect(&token::OpenDelim(token::Brace)));
5309 let abi = opt_abi.unwrap_or(abi::C);
5311 attrs.extend(try!(self.parse_inner_attributes()));
5313 let mut foreign_items = vec![];
5314 while let Some(item) = try!(self.parse_foreign_item()) {
5315 foreign_items.push(item);
5317 try!(self.expect(&token::CloseDelim(token::Brace)));
5319 let last_span = self.last_span;
5320 let m = ast::ForeignMod {
5322 items: foreign_items
5326 special_idents::invalid,
5332 /// Parse type Foo = Bar;
5333 fn parse_item_type(&mut self) -> PResult<'a, ItemInfo> {
5334 let ident = try!(self.parse_ident());
5335 let mut tps = try!(self.parse_generics());
5336 tps.where_clause = try!(self.parse_where_clause());
5337 try!(self.expect(&token::Eq));
5338 let ty = try!(self.parse_ty_sum());
5339 try!(self.expect(&token::Semi));
5340 Ok((ident, ItemTy(ty, tps), None))
5343 /// Parse the part of an "enum" decl following the '{'
5344 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
5345 let mut variants = Vec::new();
5346 let mut all_nullary = true;
5347 let mut any_disr = None;
5348 while self.token != token::CloseDelim(token::Brace) {
5349 let variant_attrs = try!(self.parse_outer_attributes());
5350 let vlo = self.span.lo;
5353 let mut disr_expr = None;
5354 let ident = try!(self.parse_ident());
5355 if self.check(&token::OpenDelim(token::Brace)) {
5356 // Parse a struct variant.
5357 all_nullary = false;
5358 struct_def = VariantData::Struct(try!(self.parse_record_struct_body(ParsePub::No)),
5359 ast::DUMMY_NODE_ID);
5360 } else if self.check(&token::OpenDelim(token::Paren)) {
5361 all_nullary = false;
5362 struct_def = VariantData::Tuple(try!(self.parse_tuple_struct_body(ParsePub::No)),
5363 ast::DUMMY_NODE_ID);
5364 } else if self.eat(&token::Eq) {
5365 disr_expr = Some(try!(self.parse_expr()));
5366 any_disr = disr_expr.as_ref().map(|expr| expr.span);
5367 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5369 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5372 let vr = ast::Variant_ {
5374 attrs: variant_attrs,
5376 disr_expr: disr_expr,
5378 variants.push(P(spanned(vlo, self.last_span.hi, vr)));
5380 if !self.eat(&token::Comma) { break; }
5382 try!(self.expect(&token::CloseDelim(token::Brace)));
5384 Some(disr_span) if !all_nullary =>
5385 self.span_err(disr_span,
5386 "discriminator values can only be used with a c-like enum"),
5390 Ok(ast::EnumDef { variants: variants })
5393 /// Parse an "enum" declaration
5394 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
5395 let id = try!(self.parse_ident());
5396 let mut generics = try!(self.parse_generics());
5397 generics.where_clause = try!(self.parse_where_clause());
5398 try!(self.expect(&token::OpenDelim(token::Brace)));
5400 let enum_definition = try!(self.parse_enum_def(&generics));
5401 Ok((id, ItemEnum(enum_definition, generics), None))
5404 /// Parses a string as an ABI spec on an extern type or module. Consumes
5405 /// the `extern` keyword, if one is found.
5406 fn parse_opt_abi(&mut self) -> PResult<'a, Option<abi::Abi>> {
5408 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
5410 self.expect_no_suffix(sp, "ABI spec", suf);
5412 match abi::lookup(&s.as_str()) {
5413 Some(abi) => Ok(Some(abi)),
5415 let last_span = self.last_span;
5418 &format!("invalid ABI: expected one of [{}], \
5420 abi::all_names().join(", "),
5431 /// Parse one of the items allowed by the flags.
5432 /// NB: this function no longer parses the items inside an
5434 fn parse_item_(&mut self, attrs: Vec<Attribute>,
5435 macros_allowed: bool, attributes_allowed: bool) -> PResult<'a, Option<P<Item>>> {
5436 let nt_item = match self.token {
5437 token::Interpolated(token::NtItem(ref item)) => {
5438 Some((**item).clone())
5445 let mut attrs = attrs;
5446 mem::swap(&mut item.attrs, &mut attrs);
5447 item.attrs.extend(attrs);
5448 return Ok(Some(P(item)));
5453 let lo = self.span.lo;
5455 let visibility = try!(self.parse_visibility());
5457 if self.eat_keyword(keywords::Use) {
5459 let item_ = ItemUse(try!(self.parse_view_path()));
5460 try!(self.expect(&token::Semi));
5462 let last_span = self.last_span;
5463 let item = self.mk_item(lo,
5465 token::special_idents::invalid,
5469 return Ok(Some(item));
5472 if self.eat_keyword(keywords::Extern) {
5473 if self.eat_keyword(keywords::Crate) {
5474 return Ok(Some(try!(self.parse_item_extern_crate(lo, visibility, attrs))));
5477 let opt_abi = try!(self.parse_opt_abi());
5479 if self.eat_keyword(keywords::Fn) {
5480 // EXTERN FUNCTION ITEM
5481 let abi = opt_abi.unwrap_or(abi::C);
5482 let (ident, item_, extra_attrs) =
5483 try!(self.parse_item_fn(Unsafety::Normal, Constness::NotConst, abi));
5484 let last_span = self.last_span;
5485 let item = self.mk_item(lo,
5490 maybe_append(attrs, extra_attrs));
5491 return Ok(Some(item));
5492 } else if self.check(&token::OpenDelim(token::Brace)) {
5493 return Ok(Some(try!(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs))));
5496 try!(self.unexpected());
5499 if self.eat_keyword(keywords::Static) {
5501 let m = if self.eat_keyword(keywords::Mut) {MutMutable} else {MutImmutable};
5502 let (ident, item_, extra_attrs) = try!(self.parse_item_const(Some(m)));
5503 let last_span = self.last_span;
5504 let item = self.mk_item(lo,
5509 maybe_append(attrs, extra_attrs));
5510 return Ok(Some(item));
5512 if self.eat_keyword(keywords::Const) {
5513 if self.check_keyword(keywords::Fn)
5514 || (self.check_keyword(keywords::Unsafe)
5515 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
5516 // CONST FUNCTION ITEM
5517 let unsafety = if self.eat_keyword(keywords::Unsafe) {
5523 let (ident, item_, extra_attrs) =
5524 try!(self.parse_item_fn(unsafety, Constness::Const, abi::Rust));
5525 let last_span = self.last_span;
5526 let item = self.mk_item(lo,
5531 maybe_append(attrs, extra_attrs));
5532 return Ok(Some(item));
5536 if self.eat_keyword(keywords::Mut) {
5537 let last_span = self.last_span;
5538 self.diagnostic().struct_span_err(last_span, "const globals cannot be mutable")
5539 .fileline_help(last_span, "did you mean to declare a static?")
5542 let (ident, item_, extra_attrs) = try!(self.parse_item_const(None));
5543 let last_span = self.last_span;
5544 let item = self.mk_item(lo,
5549 maybe_append(attrs, extra_attrs));
5550 return Ok(Some(item));
5552 if self.check_keyword(keywords::Unsafe) &&
5553 self.look_ahead(1, |t| t.is_keyword(keywords::Trait))
5555 // UNSAFE TRAIT ITEM
5556 try!(self.expect_keyword(keywords::Unsafe));
5557 try!(self.expect_keyword(keywords::Trait));
5558 let (ident, item_, extra_attrs) =
5559 try!(self.parse_item_trait(ast::Unsafety::Unsafe));
5560 let last_span = self.last_span;
5561 let item = self.mk_item(lo,
5566 maybe_append(attrs, extra_attrs));
5567 return Ok(Some(item));
5569 if self.check_keyword(keywords::Unsafe) &&
5570 self.look_ahead(1, |t| t.is_keyword(keywords::Impl))
5573 try!(self.expect_keyword(keywords::Unsafe));
5574 try!(self.expect_keyword(keywords::Impl));
5575 let (ident, item_, extra_attrs) = try!(self.parse_item_impl(ast::Unsafety::Unsafe));
5576 let last_span = self.last_span;
5577 let item = self.mk_item(lo,
5582 maybe_append(attrs, extra_attrs));
5583 return Ok(Some(item));
5585 if self.check_keyword(keywords::Fn) {
5588 let (ident, item_, extra_attrs) =
5589 try!(self.parse_item_fn(Unsafety::Normal, Constness::NotConst, abi::Rust));
5590 let last_span = self.last_span;
5591 let item = self.mk_item(lo,
5596 maybe_append(attrs, extra_attrs));
5597 return Ok(Some(item));
5599 if self.check_keyword(keywords::Unsafe)
5600 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
5601 // UNSAFE FUNCTION ITEM
5603 let abi = if self.eat_keyword(keywords::Extern) {
5604 try!(self.parse_opt_abi()).unwrap_or(abi::C)
5608 try!(self.expect_keyword(keywords::Fn));
5609 let (ident, item_, extra_attrs) =
5610 try!(self.parse_item_fn(Unsafety::Unsafe, Constness::NotConst, abi));
5611 let last_span = self.last_span;
5612 let item = self.mk_item(lo,
5617 maybe_append(attrs, extra_attrs));
5618 return Ok(Some(item));
5620 if self.eat_keyword(keywords::Mod) {
5622 let (ident, item_, extra_attrs) =
5623 try!(self.parse_item_mod(&attrs[..]));
5624 let last_span = self.last_span;
5625 let item = self.mk_item(lo,
5630 maybe_append(attrs, extra_attrs));
5631 return Ok(Some(item));
5633 if self.eat_keyword(keywords::Type) {
5635 let (ident, item_, extra_attrs) = try!(self.parse_item_type());
5636 let last_span = self.last_span;
5637 let item = self.mk_item(lo,
5642 maybe_append(attrs, extra_attrs));
5643 return Ok(Some(item));
5645 if self.eat_keyword(keywords::Enum) {
5647 let (ident, item_, extra_attrs) = try!(self.parse_item_enum());
5648 let last_span = self.last_span;
5649 let item = self.mk_item(lo,
5654 maybe_append(attrs, extra_attrs));
5655 return Ok(Some(item));
5657 if self.eat_keyword(keywords::Trait) {
5659 let (ident, item_, extra_attrs) =
5660 try!(self.parse_item_trait(ast::Unsafety::Normal));
5661 let last_span = self.last_span;
5662 let item = self.mk_item(lo,
5667 maybe_append(attrs, extra_attrs));
5668 return Ok(Some(item));
5670 if self.eat_keyword(keywords::Impl) {
5672 let (ident, item_, extra_attrs) = try!(self.parse_item_impl(ast::Unsafety::Normal));
5673 let last_span = self.last_span;
5674 let item = self.mk_item(lo,
5679 maybe_append(attrs, extra_attrs));
5680 return Ok(Some(item));
5682 if self.eat_keyword(keywords::Struct) {
5684 let (ident, item_, extra_attrs) = try!(self.parse_item_struct());
5685 let last_span = self.last_span;
5686 let item = self.mk_item(lo,
5691 maybe_append(attrs, extra_attrs));
5692 return Ok(Some(item));
5694 self.parse_macro_use_or_failure(attrs,macros_allowed,attributes_allowed,lo,visibility)
5697 /// Parse a foreign item.
5698 fn parse_foreign_item(&mut self) -> PResult<'a, Option<P<ForeignItem>>> {
5699 let attrs = try!(self.parse_outer_attributes());
5700 let lo = self.span.lo;
5701 let visibility = try!(self.parse_visibility());
5703 if self.check_keyword(keywords::Static) {
5704 // FOREIGN STATIC ITEM
5705 return Ok(Some(try!(self.parse_item_foreign_static(visibility, lo, attrs))));
5707 if self.check_keyword(keywords::Fn) || self.check_keyword(keywords::Unsafe) {
5708 // FOREIGN FUNCTION ITEM
5709 return Ok(Some(try!(self.parse_item_foreign_fn(visibility, lo, attrs))));
5712 // FIXME #5668: this will occur for a macro invocation:
5713 match try!(self.parse_macro_use_or_failure(attrs, true, false, lo, visibility)) {
5715 return Err(self.span_fatal(item.span, "macros cannot expand to foreign items"));
5721 /// This is the fall-through for parsing items.
5722 fn parse_macro_use_or_failure(
5724 attrs: Vec<Attribute> ,
5725 macros_allowed: bool,
5726 attributes_allowed: bool,
5728 visibility: Visibility
5729 ) -> PResult<'a, Option<P<Item>>> {
5730 if macros_allowed && !self.token.is_any_keyword()
5731 && self.look_ahead(1, |t| *t == token::Not)
5732 && (self.look_ahead(2, |t| t.is_plain_ident())
5733 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren))
5734 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) {
5735 // MACRO INVOCATION ITEM
5737 let last_span = self.last_span;
5738 self.complain_if_pub_macro(visibility, last_span);
5740 let mac_lo = self.span.lo;
5743 let pth = try!(self.parse_path(NoTypesAllowed));
5744 try!(self.expect(&token::Not));
5746 // a 'special' identifier (like what `macro_rules!` uses)
5747 // is optional. We should eventually unify invoc syntax
5749 let id = if self.token.is_plain_ident() {
5750 try!(self.parse_ident())
5752 token::special_idents::invalid // no special identifier
5754 // eat a matched-delimiter token tree:
5755 let delim = try!(self.expect_open_delim());
5756 let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
5758 |p| p.parse_token_tree()));
5759 // single-variant-enum... :
5760 let m = Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT };
5761 let m: ast::Mac = codemap::Spanned { node: m,
5763 self.last_span.hi) };
5765 if delim != token::Brace {
5766 if !self.eat(&token::Semi) {
5767 let last_span = self.last_span;
5768 self.span_err(last_span,
5769 "macros that expand to items must either \
5770 be surrounded with braces or followed by \
5775 let item_ = ItemMac(m);
5776 let last_span = self.last_span;
5777 let item = self.mk_item(lo,
5783 return Ok(Some(item));
5786 // FAILURE TO PARSE ITEM
5790 let last_span = self.last_span;
5791 return Err(self.span_fatal(last_span, "unmatched visibility `pub`"));
5795 if !attributes_allowed && !attrs.is_empty() {
5796 self.expected_item_err(&attrs);
5801 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
5802 let attrs = try!(self.parse_outer_attributes());
5803 self.parse_item_(attrs, true, false)
5807 /// Matches view_path : MOD? non_global_path as IDENT
5808 /// | MOD? non_global_path MOD_SEP LBRACE RBRACE
5809 /// | MOD? non_global_path MOD_SEP LBRACE ident_seq RBRACE
5810 /// | MOD? non_global_path MOD_SEP STAR
5811 /// | MOD? non_global_path
5812 fn parse_view_path(&mut self) -> PResult<'a, P<ViewPath>> {
5813 let lo = self.span.lo;
5815 // Allow a leading :: because the paths are absolute either way.
5816 // This occurs with "use $crate::..." in macros.
5817 self.eat(&token::ModSep);
5819 if self.check(&token::OpenDelim(token::Brace)) {
5821 let idents = try!(self.parse_unspanned_seq(
5822 &token::OpenDelim(token::Brace),
5823 &token::CloseDelim(token::Brace),
5824 seq_sep_trailing_allowed(token::Comma),
5825 |p| p.parse_path_list_item()));
5826 let path = ast::Path {
5827 span: mk_sp(lo, self.span.hi),
5829 segments: Vec::new()
5831 return Ok(P(spanned(lo, self.span.hi, ViewPathList(path, idents))));
5834 let first_ident = try!(self.parse_ident());
5835 let mut path = vec!(first_ident);
5836 if let token::ModSep = self.token {
5837 // foo::bar or foo::{a,b,c} or foo::*
5838 while self.check(&token::ModSep) {
5842 token::Ident(..) => {
5843 let ident = try!(self.parse_ident());
5847 // foo::bar::{a,b,c}
5848 token::OpenDelim(token::Brace) => {
5849 let idents = try!(self.parse_unspanned_seq(
5850 &token::OpenDelim(token::Brace),
5851 &token::CloseDelim(token::Brace),
5852 seq_sep_trailing_allowed(token::Comma),
5853 |p| p.parse_path_list_item()
5855 let path = ast::Path {
5856 span: mk_sp(lo, self.span.hi),
5858 segments: path.into_iter().map(|identifier| {
5860 identifier: identifier,
5861 parameters: ast::PathParameters::none(),
5865 return Ok(P(spanned(lo, self.span.hi, ViewPathList(path, idents))));
5869 token::BinOp(token::Star) => {
5871 let path = ast::Path {
5872 span: mk_sp(lo, self.span.hi),
5874 segments: path.into_iter().map(|identifier| {
5876 identifier: identifier,
5877 parameters: ast::PathParameters::none(),
5881 return Ok(P(spanned(lo, self.span.hi, ViewPathGlob(path))));
5884 // fall-through for case foo::bar::;
5886 self.span_err(self.span, "expected identifier or `{` or `*`, found `;`");
5893 let mut rename_to = path[path.len() - 1];
5894 let path = ast::Path {
5895 span: mk_sp(lo, self.last_span.hi),
5897 segments: path.into_iter().map(|identifier| {
5899 identifier: identifier,
5900 parameters: ast::PathParameters::none(),
5904 rename_to = try!(self.parse_rename()).unwrap_or(rename_to);
5905 Ok(P(spanned(lo, self.last_span.hi, ViewPathSimple(rename_to, path))))
5908 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
5909 if self.eat_keyword(keywords::As) {
5910 self.parse_ident().map(Some)
5916 /// Parses a source module as a crate. This is the main
5917 /// entry point for the parser.
5918 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
5919 let lo = self.span.lo;
5921 attrs: try!(self.parse_inner_attributes()),
5922 module: try!(self.parse_mod_items(&token::Eof, lo)),
5923 config: self.cfg.clone(),
5924 span: mk_sp(lo, self.span.lo),
5925 exported_macros: Vec::new(),
5929 pub fn parse_optional_str(&mut self)
5930 -> Option<(InternedString,
5932 Option<ast::Name>)> {
5933 let ret = match self.token {
5934 token::Literal(token::Str_(s), suf) => {
5935 (self.id_to_interned_str(ast::Ident::with_empty_ctxt(s)), ast::CookedStr, suf)
5937 token::Literal(token::StrRaw(s, n), suf) => {
5938 (self.id_to_interned_str(ast::Ident::with_empty_ctxt(s)), ast::RawStr(n), suf)
5946 pub fn parse_str(&mut self) -> PResult<'a, (InternedString, StrStyle)> {
5947 match self.parse_optional_str() {
5948 Some((s, style, suf)) => {
5949 let sp = self.last_span;
5950 self.expect_no_suffix(sp, "string literal", suf);
5953 _ => Err(self.fatal("expected string literal"))