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.
14 use ast::{AssociatedType, BareFnTy, ClosureTy};
15 use ast::{RegionTyParamBound, TraitTyParamBound};
16 use ast::{ProvidedMethod, Public, FnStyle};
17 use ast::{Mod, BiAdd, Arg, Arm, Attribute, BindByRef, BindByValue};
18 use ast::{BiBitAnd, BiBitOr, BiBitXor, BiRem, Block};
19 use ast::{BlockCheckMode, UnBox};
20 use ast::{CaptureByRef, CaptureByValue, CaptureClause};
21 use ast::{Crate, CrateConfig, Decl, DeclItem};
22 use ast::{DeclLocal, DefaultBlock, 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};
26 use ast::{ExprField, ExprTupField, ExprFnBlock, ExprIf, ExprIndex, ExprSlice};
27 use ast::{ExprLit, ExprLoop, ExprMac};
28 use ast::{ExprMethodCall, ExprParen, ExprPath, ExprProc};
29 use ast::{ExprRepeat, ExprRet, ExprStruct, ExprTup, ExprUnary, ExprUnboxedFn};
30 use ast::{ExprVec, ExprWhile, ExprForLoop, Field, FnDecl};
31 use ast::{Once, Many};
32 use ast::{FnUnboxedClosureKind, FnMutUnboxedClosureKind};
33 use ast::{FnOnceUnboxedClosureKind};
34 use ast::{ForeignItem, ForeignItemStatic, ForeignItemFn, ForeignMod};
35 use ast::{Ident, NormalFn, Inherited, ImplItem, Item, Item_, ItemStatic};
36 use ast::{ItemEnum, ItemFn, ItemForeignMod, ItemImpl};
37 use ast::{ItemMac, ItemMod, ItemStruct, ItemTrait, ItemTy, Lit, Lit_};
38 use ast::{LitBool, LitChar, LitByte, LitBinary};
39 use ast::{LitNil, LitStr, LitInt, Local, LocalLet};
40 use ast::{MutImmutable, MutMutable, Mac_, MacInvocTT, Matcher, MatchNonterminal};
41 use ast::{MatchSeq, MatchTok, Method, MutTy, BiMul, Mutability};
42 use ast::{MethodImplItem, NamedField, UnNeg, NoReturn, UnNot};
43 use ast::{Pat, PatEnum, PatIdent, PatLit, PatRange, PatRegion, PatStruct};
44 use ast::{PatTup, PatBox, PatWild, PatWildMulti, PatWildSingle};
45 use ast::{QPath, RequiredMethod};
46 use ast::{RetStyle, Return, BiShl, BiShr, Stmt, StmtDecl};
47 use ast::{StmtExpr, StmtSemi, StmtMac, StructDef, StructField};
48 use ast::{StructVariantKind, BiSub};
50 use ast::{SelfExplicit, SelfRegion, SelfStatic, SelfValue};
51 use ast::{TokenTree, TraitItem, TraitRef, TTDelim, TTSeq, TTTok};
52 use ast::{TTNonterminal, TupleVariantKind, Ty, Ty_, TyBot, TyBox};
53 use ast::{TypeField, TyFixedLengthVec, TyClosure, TyProc, TyBareFn};
54 use ast::{TyTypeof, TyInfer, TypeMethod};
55 use ast::{TyNil, TyParam, TyParamBound, TyParen, TyPath, TyPtr, TyQPath};
56 use ast::{TyRptr, TyTup, TyU32, TyUnboxedFn, TyUniq, TyVec, UnUniq};
57 use ast::{TypeImplItem, TypeTraitItem, Typedef, UnboxedClosureKind};
58 use ast::{UnboxedFnBound, UnboxedFnTy, UnboxedFnTyParamBound};
59 use ast::{UnnamedField, UnsafeBlock};
60 use ast::{UnsafeFn, ViewItem, ViewItem_, ViewItemExternCrate, ViewItemUse};
61 use ast::{ViewPath, ViewPathGlob, ViewPathList, ViewPathSimple};
62 use ast::{Visibility, WhereClause, WherePredicate};
64 use ast_util::{as_prec, ident_to_path, operator_prec};
67 use codemap::{Span, BytePos, Spanned, spanned, mk_sp};
70 use parse::attr::ParserAttr;
72 use parse::common::{SeqSep, seq_sep_none};
73 use parse::common::{seq_sep_trailing_allowed};
74 use parse::lexer::Reader;
75 use parse::lexer::TokenAndSpan;
76 use parse::obsolete::*;
77 use parse::token::{INTERPOLATED, InternedString, can_begin_expr};
78 use parse::token::{is_ident, is_ident_or_path, is_plain_ident};
79 use parse::token::{keywords, special_idents, token_to_binop};
81 use parse::{new_sub_parser_from_file, ParseSess};
83 use owned_slice::OwnedSlice;
85 use std::collections::HashSet;
86 use std::io::fs::PathExtensions;
87 use std::mem::replace;
93 flags Restrictions: u8 {
94 static Unrestricted = 0b0000,
95 static RestrictionStmtExpr = 0b0001,
96 static RestrictionNoBarOp = 0b0010,
97 static RestrictionNoStructLiteral = 0b0100
101 type ItemInfo = (Ident, Item_, Option<Vec<Attribute> >);
103 /// How to parse a path. There are four different kinds of paths, all of which
104 /// are parsed somewhat differently.
105 #[deriving(PartialEq)]
106 pub enum PathParsingMode {
107 /// A path with no type parameters; e.g. `foo::bar::Baz`
109 /// A path with a lifetime and type parameters, with no double colons
110 /// before the type parameters; e.g. `foo::bar<'a>::Baz<T>`
111 LifetimeAndTypesWithoutColons,
112 /// A path with a lifetime and type parameters with double colons before
113 /// the type parameters; e.g. `foo::bar::<'a>::Baz::<T>`
114 LifetimeAndTypesWithColons,
115 /// A path with a lifetime and type parameters with bounds before the last
116 /// set of type parameters only; e.g. `foo::bar<'a>::Baz+X+Y<T>` This
117 /// form does not use extra double colons.
118 LifetimeAndTypesAndBounds,
121 /// A path paired with optional type bounds.
122 pub struct PathAndBounds {
124 pub bounds: Option<ast::TyParamBounds>,
127 enum ItemOrViewItem {
128 /// Indicates a failure to parse any kind of item. The attributes are
130 IoviNone(Vec<Attribute>),
132 IoviForeignItem(P<ForeignItem>),
133 IoviViewItem(ViewItem)
137 /// Possibly accept an `INTERPOLATED` expression (a pre-parsed expression
138 /// dropped into the token stream, which happens while parsing the
139 /// result of macro expansion)
140 /// Placement of these is not as complex as I feared it would be.
141 /// The important thing is to make sure that lookahead doesn't balk
142 /// at INTERPOLATED tokens
143 macro_rules! maybe_whole_expr (
146 let found = match $p.token {
147 INTERPOLATED(token::NtExpr(ref e)) => {
150 INTERPOLATED(token::NtPath(_)) => {
151 // FIXME: The following avoids an issue with lexical borrowck scopes,
152 // but the clone is unfortunate.
153 let pt = match $p.token {
154 INTERPOLATED(token::NtPath(ref pt)) => (**pt).clone(),
158 Some($p.mk_expr(span.lo, span.hi, ExprPath(pt)))
160 INTERPOLATED(token::NtBlock(_)) => {
161 // FIXME: The following avoids an issue with lexical borrowck scopes,
162 // but the clone is unfortunate.
163 let b = match $p.token {
164 INTERPOLATED(token::NtBlock(ref b)) => (*b).clone(),
168 Some($p.mk_expr(span.lo, span.hi, ExprBlock(b)))
183 /// As maybe_whole_expr, but for things other than expressions
184 macro_rules! maybe_whole (
185 ($p:expr, $constructor:ident) => (
187 let found = match ($p).token {
188 INTERPOLATED(token::$constructor(_)) => {
189 Some(($p).bump_and_get())
194 Some(INTERPOLATED(token::$constructor(x))) => {
201 (no_clone $p:expr, $constructor:ident) => (
203 let found = match ($p).token {
204 INTERPOLATED(token::$constructor(_)) => {
205 Some(($p).bump_and_get())
210 Some(INTERPOLATED(token::$constructor(x))) => {
217 (deref $p:expr, $constructor:ident) => (
219 let found = match ($p).token {
220 INTERPOLATED(token::$constructor(_)) => {
221 Some(($p).bump_and_get())
226 Some(INTERPOLATED(token::$constructor(x))) => {
233 (Some $p:expr, $constructor:ident) => (
235 let found = match ($p).token {
236 INTERPOLATED(token::$constructor(_)) => {
237 Some(($p).bump_and_get())
242 Some(INTERPOLATED(token::$constructor(x))) => {
243 return Some(x.clone()),
249 (iovi $p:expr, $constructor:ident) => (
251 let found = match ($p).token {
252 INTERPOLATED(token::$constructor(_)) => {
253 Some(($p).bump_and_get())
258 Some(INTERPOLATED(token::$constructor(x))) => {
259 return IoviItem(x.clone())
265 (pair_empty $p:expr, $constructor:ident) => (
267 let found = match ($p).token {
268 INTERPOLATED(token::$constructor(_)) => {
269 Some(($p).bump_and_get())
274 Some(INTERPOLATED(token::$constructor(x))) => {
275 return (Vec::new(), x)
284 fn maybe_append(lhs: Vec<Attribute> , rhs: Option<Vec<Attribute> >)
288 Some(ref attrs) => lhs.append(attrs.as_slice())
293 struct ParsedItemsAndViewItems {
294 attrs_remaining: Vec<Attribute>,
295 view_items: Vec<ViewItem>,
296 items: Vec<P<Item>> ,
297 foreign_items: Vec<P<ForeignItem>>
300 /* ident is handled by common.rs */
302 pub struct Parser<'a> {
303 pub sess: &'a ParseSess,
304 /// the current token:
305 pub token: token::Token,
306 /// the span of the current token:
308 /// the span of the prior token:
310 pub cfg: CrateConfig,
311 /// the previous token or None (only stashed sometimes).
312 pub last_token: Option<Box<token::Token>>,
313 pub buffer: [TokenAndSpan, ..4],
314 pub buffer_start: int,
316 pub tokens_consumed: uint,
317 pub restrictions: Restrictions,
318 pub quote_depth: uint, // not (yet) related to the quasiquoter
319 pub reader: Box<Reader+'a>,
320 pub interner: Rc<token::IdentInterner>,
321 /// The set of seen errors about obsolete syntax. Used to suppress
322 /// extra detail when the same error is seen twice
323 pub obsolete_set: HashSet<ObsoleteSyntax>,
324 /// Used to determine the path to externally loaded source files
325 pub mod_path_stack: Vec<InternedString>,
326 /// Stack of spans of open delimiters. Used for error message.
327 pub open_braces: Vec<Span>,
328 /// Flag if this parser "owns" the directory that it is currently parsing
329 /// in. This will affect how nested files are looked up.
330 pub owns_directory: bool,
331 /// Name of the root module this parser originated from. If `None`, then the
332 /// name is not known. This does not change while the parser is descending
333 /// into modules, and sub-parsers have new values for this name.
334 pub root_module_name: Option<String>,
337 fn is_plain_ident_or_underscore(t: &token::Token) -> bool {
338 is_plain_ident(t) || *t == token::UNDERSCORE
341 /// Get a token the parser cares about
342 fn real_token(rdr: &mut Reader) -> TokenAndSpan {
343 let mut t = rdr.next_token();
346 token::WS | token::COMMENT | token::SHEBANG(_) => {
347 t = rdr.next_token();
355 impl<'a> Parser<'a> {
356 pub fn new(sess: &'a ParseSess,
357 cfg: ast::CrateConfig,
358 mut rdr: Box<Reader+'a>)
361 let tok0 = real_token(&mut *rdr);
363 let placeholder = TokenAndSpan {
364 tok: token::UNDERSCORE,
370 interner: token::get_ident_interner(),
386 restrictions: Unrestricted,
388 obsolete_set: HashSet::new(),
389 mod_path_stack: Vec::new(),
390 open_braces: Vec::new(),
391 owns_directory: true,
392 root_module_name: None,
396 /// Convert a token to a string using self's reader
397 pub fn token_to_string(token: &token::Token) -> String {
398 token::to_string(token)
401 /// Convert the current token to a string using self's reader
402 pub fn this_token_to_string(&mut self) -> String {
403 Parser::token_to_string(&self.token)
406 pub fn unexpected_last(&mut self, t: &token::Token) -> ! {
407 let token_str = Parser::token_to_string(t);
408 let last_span = self.last_span;
409 self.span_fatal(last_span, format!("unexpected token: `{}`",
410 token_str).as_slice());
413 pub fn unexpected(&mut self) -> ! {
414 let this_token = self.this_token_to_string();
415 self.fatal(format!("unexpected token: `{}`", this_token).as_slice());
418 /// Expect and consume the token t. Signal an error if
419 /// the next token is not t.
420 pub fn expect(&mut self, t: &token::Token) {
421 if self.token == *t {
424 let token_str = Parser::token_to_string(t);
425 let this_token_str = self.this_token_to_string();
426 self.fatal(format!("expected `{}`, found `{}`",
428 this_token_str).as_slice())
432 /// Expect next token to be edible or inedible token. If edible,
433 /// then consume it; if inedible, then return without consuming
434 /// anything. Signal a fatal error if next token is unexpected.
435 pub fn expect_one_of(&mut self,
436 edible: &[token::Token],
437 inedible: &[token::Token]) {
438 fn tokens_to_string(tokens: &[token::Token]) -> String {
439 let mut i = tokens.iter();
440 // This might be a sign we need a connect method on Iterator.
442 .map_or("".to_string(), |t| Parser::token_to_string(t));
446 b.push_str(Parser::token_to_string(a).as_slice());
450 if edible.contains(&self.token) {
452 } else if inedible.contains(&self.token) {
453 // leave it in the input
455 let expected = edible.iter().map(|x| (*x).clone()).collect::<Vec<_>>().append(inedible);
456 let expect = tokens_to_string(expected.as_slice());
457 let actual = self.this_token_to_string();
459 (if expected.len() != 1 {
460 (format!("expected one of `{}`, found `{}`",
464 (format!("expected `{}`, found `{}`",
472 /// Check for erroneous `ident { }`; if matches, signal error and
473 /// recover (without consuming any expected input token). Returns
474 /// true if and only if input was consumed for recovery.
475 pub fn check_for_erroneous_unit_struct_expecting(&mut self, expected: &[token::Token]) -> bool {
476 if self.token == token::LBRACE
477 && expected.iter().all(|t| *t != token::LBRACE)
478 && self.look_ahead(1, |t| *t == token::RBRACE) {
479 // matched; signal non-fatal error and recover.
480 let span = self.span;
482 "unit-like struct construction is written with no trailing `{ }`");
483 self.eat(&token::LBRACE);
484 self.eat(&token::RBRACE);
491 /// Commit to parsing a complete expression `e` expected to be
492 /// followed by some token from the set edible + inedible. Recover
493 /// from anticipated input errors, discarding erroneous characters.
494 pub fn commit_expr(&mut self, e: &Expr, edible: &[token::Token], inedible: &[token::Token]) {
495 debug!("commit_expr {:?}", e);
498 // might be unit-struct construction; check for recoverableinput error.
499 let expected = edible.iter().map(|x| (*x).clone()).collect::<Vec<_>>()
501 self.check_for_erroneous_unit_struct_expecting(
502 expected.as_slice());
506 self.expect_one_of(edible, inedible)
509 pub fn commit_expr_expecting(&mut self, e: &Expr, edible: token::Token) {
510 self.commit_expr(e, &[edible], &[])
513 /// Commit to parsing a complete statement `s`, which expects to be
514 /// followed by some token from the set edible + inedible. Check
515 /// for recoverable input errors, discarding erroneous characters.
516 pub fn commit_stmt(&mut self, edible: &[token::Token], inedible: &[token::Token]) {
519 .map_or(false, |t| is_ident_or_path(&**t)) {
520 let expected = edible.iter().map(|x| (*x).clone()).collect::<Vec<_>>()
521 .append(inedible.as_slice());
522 self.check_for_erroneous_unit_struct_expecting(
523 expected.as_slice());
525 self.expect_one_of(edible, inedible)
528 pub fn commit_stmt_expecting(&mut self, edible: token::Token) {
529 self.commit_stmt(&[edible], &[])
532 pub fn parse_ident(&mut self) -> ast::Ident {
533 self.check_strict_keywords();
534 self.check_reserved_keywords();
536 token::IDENT(i, _) => {
540 token::INTERPOLATED(token::NtIdent(..)) => {
541 self.bug("ident interpolation not converted to real token");
544 let token_str = self.this_token_to_string();
545 self.fatal((format!("expected ident, found `{}`",
546 token_str)).as_slice())
551 pub fn parse_path_list_item(&mut self) -> ast::PathListItem {
552 let lo = self.span.lo;
553 let node = if self.eat_keyword(keywords::Mod) {
554 ast::PathListMod { id: ast::DUMMY_NODE_ID }
556 let ident = self.parse_ident();
557 ast::PathListIdent { name: ident, id: ast::DUMMY_NODE_ID }
559 let hi = self.last_span.hi;
560 spanned(lo, hi, node)
563 /// Consume token 'tok' if it exists. Returns true if the given
564 /// token was present, false otherwise.
565 pub fn eat(&mut self, tok: &token::Token) -> bool {
566 let is_present = self.token == *tok;
567 if is_present { self.bump() }
571 pub fn is_keyword(&mut self, kw: keywords::Keyword) -> bool {
572 token::is_keyword(kw, &self.token)
575 /// If the next token is the given keyword, eat it and return
576 /// true. Otherwise, return false.
577 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
579 token::IDENT(sid, false) if kw.to_name() == sid.name => {
587 /// If the given word is not a keyword, signal an error.
588 /// If the next token is not the given word, signal an error.
589 /// Otherwise, eat it.
590 pub fn expect_keyword(&mut self, kw: keywords::Keyword) {
591 if !self.eat_keyword(kw) {
592 let id_interned_str = token::get_name(kw.to_name());
593 let token_str = self.this_token_to_string();
594 self.fatal(format!("expected `{}`, found `{}`",
595 id_interned_str, token_str).as_slice())
599 /// Signal an error if the given string is a strict keyword
600 pub fn check_strict_keywords(&mut self) {
601 if token::is_strict_keyword(&self.token) {
602 let token_str = self.this_token_to_string();
603 let span = self.span;
605 format!("expected identifier, found keyword `{}`",
606 token_str).as_slice());
610 /// Signal an error if the current token is a reserved keyword
611 pub fn check_reserved_keywords(&mut self) {
612 if token::is_reserved_keyword(&self.token) {
613 let token_str = self.this_token_to_string();
614 self.fatal(format!("`{}` is a reserved keyword",
615 token_str).as_slice())
619 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
620 /// `&` and continue. If an `&` is not seen, signal an error.
621 fn expect_and(&mut self) {
623 token::BINOP(token::AND) => self.bump(),
625 let span = self.span;
626 let lo = span.lo + BytePos(1);
627 self.replace_token(token::BINOP(token::AND), lo, span.hi)
630 let token_str = self.this_token_to_string();
632 Parser::token_to_string(&token::BINOP(token::AND));
633 self.fatal(format!("expected `{}`, found `{}`",
635 token_str).as_slice())
640 /// Expect and consume a `|`. If `||` is seen, replace it with a single
641 /// `|` and continue. If a `|` is not seen, signal an error.
642 fn expect_or(&mut self) {
644 token::BINOP(token::OR) => self.bump(),
646 let span = self.span;
647 let lo = span.lo + BytePos(1);
648 self.replace_token(token::BINOP(token::OR), lo, span.hi)
651 let found_token = self.this_token_to_string();
653 Parser::token_to_string(&token::BINOP(token::OR));
654 self.fatal(format!("expected `{}`, found `{}`",
656 found_token).as_slice())
661 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
662 /// `<` and continue. If a `<` is not seen, return false.
664 /// This is meant to be used when parsing generics on a path to get the
665 /// starting token. The `force` parameter is used to forcefully break up a
666 /// `<<` token. If `force` is false, then `<<` is only broken when a lifetime
667 /// shows up next. For example, consider the expression:
669 /// foo as bar << test
671 /// The parser needs to know if `bar <<` is the start of a generic path or if
672 /// it's a left-shift token. If `test` were a lifetime, then it's impossible
673 /// for the token to be a left-shift, but if it's not a lifetime, then it's
674 /// considered a left-shift.
676 /// The reason for this is that the only current ambiguity with `<<` is when
677 /// parsing closure types:
679 /// foo::<<'a> ||>();
680 /// impl Foo<<'a> ||>() { ... }
681 fn eat_lt(&mut self, force: bool) -> bool {
683 token::LT => { self.bump(); true }
684 token::BINOP(token::SHL) => {
685 let next_lifetime = self.look_ahead(1, |t| match *t {
686 token::LIFETIME(..) => true,
689 if force || next_lifetime {
690 let span = self.span;
691 let lo = span.lo + BytePos(1);
692 self.replace_token(token::LT, lo, span.hi);
702 fn expect_lt(&mut self) {
703 if !self.eat_lt(true) {
704 let found_token = self.this_token_to_string();
705 let token_str = Parser::token_to_string(&token::LT);
706 self.fatal(format!("expected `{}`, found `{}`",
708 found_token).as_slice())
712 /// Parse a sequence bracketed by `|` and `|`, stopping before the `|`.
713 fn parse_seq_to_before_or<T>(
716 f: |&mut Parser| -> T)
718 let mut first = true;
719 let mut vector = Vec::new();
720 while self.token != token::BINOP(token::OR) &&
721 self.token != token::OROR {
733 /// Expect and consume a GT. if a >> is seen, replace it
734 /// with a single > and continue. If a GT is not seen,
736 pub fn expect_gt(&mut self) {
738 token::GT => self.bump(),
739 token::BINOP(token::SHR) => {
740 let span = self.span;
741 let lo = span.lo + BytePos(1);
742 self.replace_token(token::GT, lo, span.hi)
744 token::BINOPEQ(token::SHR) => {
745 let span = self.span;
746 let lo = span.lo + BytePos(1);
747 self.replace_token(token::GE, lo, span.hi)
750 let span = self.span;
751 let lo = span.lo + BytePos(1);
752 self.replace_token(token::EQ, lo, span.hi)
755 let gt_str = Parser::token_to_string(&token::GT);
756 let this_token_str = self.this_token_to_string();
757 self.fatal(format!("expected `{}`, found `{}`",
759 this_token_str).as_slice())
764 /// Parse a sequence bracketed by '<' and '>', stopping
766 pub fn parse_seq_to_before_gt<T>(
768 sep: Option<token::Token>,
769 f: |&mut Parser| -> T)
771 let mut v = Vec::new();
772 // This loop works by alternating back and forth between parsing types
773 // and commas. For example, given a string `A, B,>`, the parser would
774 // first parse `A`, then a comma, then `B`, then a comma. After that it
775 // would encounter a `>` and stop. This lets the parser handle trailing
776 // commas in generic parameters, because it can stop either after
777 // parsing a type or after parsing a comma.
778 for i in iter::count(0u, 1) {
779 if self.token == token::GT
780 || self.token == token::BINOP(token::SHR)
781 || self.token == token::GE
782 || self.token == token::BINOPEQ(token::SHR) {
789 sep.as_ref().map(|t| self.expect(t));
792 return OwnedSlice::from_vec(v);
795 pub fn parse_seq_to_gt<T>(
797 sep: Option<token::Token>,
798 f: |&mut Parser| -> T)
800 let v = self.parse_seq_to_before_gt(sep, f);
805 /// Parse a sequence, including the closing delimiter. The function
806 /// f must consume tokens until reaching the next separator or
808 pub fn parse_seq_to_end<T>(
812 f: |&mut Parser| -> T)
814 let val = self.parse_seq_to_before_end(ket, sep, f);
819 /// Parse a sequence, not including the closing delimiter. The function
820 /// f must consume tokens until reaching the next separator or
822 pub fn parse_seq_to_before_end<T>(
826 f: |&mut Parser| -> T)
828 let mut first: bool = true;
830 while self.token != *ket {
833 if first { first = false; }
834 else { self.expect(t); }
838 if sep.trailing_sep_allowed && self.token == *ket { break; }
844 /// Parse a sequence, including the closing delimiter. The function
845 /// f must consume tokens until reaching the next separator or
847 pub fn parse_unspanned_seq<T>(
852 f: |&mut Parser| -> T)
855 let result = self.parse_seq_to_before_end(ket, sep, f);
860 /// Parse a sequence parameter of enum variant. For consistency purposes,
861 /// these should not be empty.
862 pub fn parse_enum_variant_seq<T>(
867 f: |&mut Parser| -> T)
869 let result = self.parse_unspanned_seq(bra, ket, sep, f);
870 if result.is_empty() {
871 let last_span = self.last_span;
872 self.span_err(last_span,
873 "nullary enum variants are written with no trailing `( )`");
878 // NB: Do not use this function unless you actually plan to place the
879 // spanned list in the AST.
885 f: |&mut Parser| -> T)
886 -> Spanned<Vec<T> > {
887 let lo = self.span.lo;
889 let result = self.parse_seq_to_before_end(ket, sep, f);
890 let hi = self.span.hi;
892 spanned(lo, hi, result)
895 /// Advance the parser by one token
896 pub fn bump(&mut self) {
897 self.last_span = self.span;
898 // Stash token for error recovery (sometimes; clone is not necessarily cheap).
899 self.last_token = if is_ident_or_path(&self.token) {
900 Some(box self.token.clone())
904 let next = if self.buffer_start == self.buffer_end {
905 real_token(&mut *self.reader)
907 // Avoid token copies with `replace`.
908 let buffer_start = self.buffer_start as uint;
909 let next_index = (buffer_start + 1) & 3 as uint;
910 self.buffer_start = next_index as int;
912 let placeholder = TokenAndSpan {
913 tok: token::UNDERSCORE,
916 replace(&mut self.buffer[buffer_start], placeholder)
919 self.token = next.tok;
920 self.tokens_consumed += 1u;
923 /// Advance the parser by one token and return the bumped token.
924 pub fn bump_and_get(&mut self) -> token::Token {
925 let old_token = replace(&mut self.token, token::UNDERSCORE);
930 /// EFFECT: replace the current token and span with the given one
931 pub fn replace_token(&mut self,
935 self.last_span = mk_sp(self.span.lo, lo);
937 self.span = mk_sp(lo, hi);
939 pub fn buffer_length(&mut self) -> int {
940 if self.buffer_start <= self.buffer_end {
941 return self.buffer_end - self.buffer_start;
943 return (4 - self.buffer_start) + self.buffer_end;
945 pub fn look_ahead<R>(&mut self, distance: uint, f: |&token::Token| -> R)
947 let dist = distance as int;
948 while self.buffer_length() < dist {
949 self.buffer[self.buffer_end as uint] = real_token(&mut *self.reader);
950 self.buffer_end = (self.buffer_end + 1) & 3;
952 f(&self.buffer[((self.buffer_start + dist - 1) & 3) as uint].tok)
954 pub fn fatal(&mut self, m: &str) -> ! {
955 self.sess.span_diagnostic.span_fatal(self.span, m)
957 pub fn span_fatal(&mut self, sp: Span, m: &str) -> ! {
958 self.sess.span_diagnostic.span_fatal(sp, m)
960 pub fn span_note(&mut self, sp: Span, m: &str) {
961 self.sess.span_diagnostic.span_note(sp, m)
963 pub fn bug(&mut self, m: &str) -> ! {
964 self.sess.span_diagnostic.span_bug(self.span, m)
966 pub fn warn(&mut self, m: &str) {
967 self.sess.span_diagnostic.span_warn(self.span, m)
969 pub fn span_warn(&mut self, sp: Span, m: &str) {
970 self.sess.span_diagnostic.span_warn(sp, m)
972 pub fn span_err(&mut self, sp: Span, m: &str) {
973 self.sess.span_diagnostic.span_err(sp, m)
975 pub fn abort_if_errors(&mut self) {
976 self.sess.span_diagnostic.handler().abort_if_errors();
979 pub fn id_to_interned_str(&mut self, id: Ident) -> InternedString {
983 /// Is the current token one of the keywords that signals a bare function
985 pub fn token_is_bare_fn_keyword(&mut self) -> bool {
986 if token::is_keyword(keywords::Fn, &self.token) {
990 if token::is_keyword(keywords::Unsafe, &self.token) ||
991 token::is_keyword(keywords::Once, &self.token) {
992 return self.look_ahead(1, |t| token::is_keyword(keywords::Fn, t))
998 /// Is the current token one of the keywords that signals a closure type?
999 pub fn token_is_closure_keyword(&mut self) -> bool {
1000 token::is_keyword(keywords::Unsafe, &self.token) ||
1001 token::is_keyword(keywords::Once, &self.token)
1004 /// Is the current token one of the keywords that signals an old-style
1005 /// closure type (with explicit sigil)?
1006 pub fn token_is_old_style_closure_keyword(&mut self) -> bool {
1007 token::is_keyword(keywords::Unsafe, &self.token) ||
1008 token::is_keyword(keywords::Once, &self.token) ||
1009 token::is_keyword(keywords::Fn, &self.token)
1012 pub fn token_is_lifetime(tok: &token::Token) -> bool {
1014 token::LIFETIME(..) => true,
1019 pub fn get_lifetime(&mut self) -> ast::Ident {
1021 token::LIFETIME(ref ident) => *ident,
1022 _ => self.bug("not a lifetime"),
1026 /// parse a TyBareFn type:
1027 pub fn parse_ty_bare_fn(&mut self) -> Ty_ {
1030 [unsafe] [extern "ABI"] fn <'lt> (S) -> T
1031 ^~~~^ ^~~~^ ^~~~^ ^~^ ^
1034 | | | Argument types
1040 let fn_style = self.parse_unsafety();
1041 let abi = if self.eat_keyword(keywords::Extern) {
1042 self.parse_opt_abi().unwrap_or(abi::C)
1047 self.expect_keyword(keywords::Fn);
1048 let (decl, lifetimes) = self.parse_ty_fn_decl(true);
1049 TyBareFn(P(BareFnTy {
1052 lifetimes: lifetimes,
1057 /// Parses a procedure type (`proc`). The initial `proc` keyword must
1058 /// already have been parsed.
1059 pub fn parse_proc_type(&mut self) -> Ty_ {
1062 proc <'lt> (S) [:Bounds] -> T
1063 ^~~^ ^~~~^ ^ ^~~~~~~~^ ^
1073 let lifetime_defs = if self.eat(&token::LT) {
1074 let lifetime_defs = self.parse_lifetime_defs();
1081 let (inputs, variadic) = self.parse_fn_args(false, false);
1082 let bounds = self.parse_colon_then_ty_param_bounds();
1083 let (ret_style, ret_ty) = self.parse_ret_ty();
1084 let decl = P(FnDecl {
1090 TyProc(P(ClosureTy {
1095 lifetimes: lifetime_defs,
1099 /// Parses an optional unboxed closure kind (`&:`, `&mut:`, or `:`).
1100 pub fn parse_optional_unboxed_closure_kind(&mut self)
1101 -> Option<UnboxedClosureKind> {
1102 if self.token == token::BINOP(token::AND) &&
1103 self.look_ahead(1, |t| {
1104 token::is_keyword(keywords::Mut, t)
1106 self.look_ahead(2, |t| *t == token::COLON) {
1110 return Some(FnMutUnboxedClosureKind)
1113 if self.token == token::BINOP(token::AND) &&
1114 self.look_ahead(1, |t| *t == token::COLON) {
1117 return Some(FnUnboxedClosureKind)
1120 if self.eat(&token::COLON) {
1121 return Some(FnOnceUnboxedClosureKind)
1127 /// Parse a TyClosure type
1128 pub fn parse_ty_closure(&mut self) -> Ty_ {
1131 [unsafe] [once] <'lt> |S| [:Bounds] -> T
1132 ^~~~~~~^ ^~~~~^ ^~~~^ ^ ^~~~~~~~^ ^
1134 | | | | | Return type
1135 | | | | Closure bounds
1136 | | | Argument types
1138 | Once-ness (a.k.a., affine)
1143 let fn_style = self.parse_unsafety();
1144 let onceness = if self.eat_keyword(keywords::Once) {Once} else {Many};
1146 let lifetime_defs = if self.eat(&token::LT) {
1147 let lifetime_defs = self.parse_lifetime_defs();
1155 let (optional_unboxed_closure_kind, inputs) = if self.eat(&token::OROR) {
1160 let optional_unboxed_closure_kind =
1161 self.parse_optional_unboxed_closure_kind();
1163 let inputs = self.parse_seq_to_before_or(
1165 |p| p.parse_arg_general(false));
1167 (optional_unboxed_closure_kind, inputs)
1170 let bounds = self.parse_colon_then_ty_param_bounds();
1172 let (return_style, output) = self.parse_ret_ty();
1173 let decl = P(FnDecl {
1180 match optional_unboxed_closure_kind {
1181 Some(unboxed_closure_kind) => {
1182 TyUnboxedFn(P(UnboxedFnTy {
1183 kind: unboxed_closure_kind,
1188 TyClosure(P(ClosureTy {
1193 lifetimes: lifetime_defs,
1199 pub fn parse_unsafety(&mut self) -> FnStyle {
1200 if self.eat_keyword(keywords::Unsafe) {
1207 /// Parse a function type (following the 'fn')
1208 pub fn parse_ty_fn_decl(&mut self, allow_variadic: bool)
1209 -> (P<FnDecl>, Vec<ast::LifetimeDef>) {
1220 let lifetime_defs = if self.eat(&token::LT) {
1221 let lifetime_defs = self.parse_lifetime_defs();
1228 let (inputs, variadic) = self.parse_fn_args(false, allow_variadic);
1229 let (ret_style, ret_ty) = self.parse_ret_ty();
1230 let decl = P(FnDecl {
1236 (decl, lifetime_defs)
1239 /// Parses `type Foo;` in a trait declaration only. The `type` keyword has
1240 /// already been parsed.
1241 fn parse_associated_type(&mut self, attrs: Vec<Attribute>)
1243 let lo = self.span.lo;
1244 let ident = self.parse_ident();
1245 let hi = self.span.hi;
1246 self.expect(&token::SEMI);
1248 id: ast::DUMMY_NODE_ID,
1249 span: mk_sp(lo, hi),
1255 /// Parses `type Foo = TYPE;` in an implementation declaration only. The
1256 /// `type` keyword has already been parsed.
1257 fn parse_typedef(&mut self, attrs: Vec<Attribute>, vis: Visibility)
1259 let lo = self.span.lo;
1260 let ident = self.parse_ident();
1261 self.expect(&token::EQ);
1262 let typ = self.parse_ty(true);
1263 let hi = self.span.hi;
1264 self.expect(&token::SEMI);
1266 id: ast::DUMMY_NODE_ID,
1267 span: mk_sp(lo, hi),
1275 /// Parse the items in a trait declaration
1276 pub fn parse_trait_items(&mut self) -> Vec<TraitItem> {
1277 self.parse_unspanned_seq(
1282 let attrs = p.parse_outer_attributes();
1284 if p.eat_keyword(keywords::Type) {
1285 TypeTraitItem(P(p.parse_associated_type(attrs)))
1289 let vis = p.parse_visibility();
1290 let abi = if p.eat_keyword(keywords::Extern) {
1291 p.parse_opt_abi().unwrap_or(abi::C)
1292 } else if attr::contains_name(attrs.as_slice(),
1293 "rust_call_abi_hack") {
1294 // FIXME(stage0, pcwalton): Remove this awful hack after a
1295 // snapshot, and change to `extern "rust-call" fn`.
1301 let style = p.parse_fn_style();
1302 let ident = p.parse_ident();
1303 let mut generics = p.parse_generics();
1305 let (explicit_self, d) = p.parse_fn_decl_with_self(|p| {
1306 // This is somewhat dubious; We don't want to allow
1307 // argument names to be left off if there is a
1309 p.parse_arg_general(false)
1312 p.parse_where_clause(&mut generics);
1314 let hi = p.last_span.hi;
1318 debug!("parse_trait_methods(): parsing required method");
1319 RequiredMethod(TypeMethod {
1326 explicit_self: explicit_self,
1327 id: ast::DUMMY_NODE_ID,
1328 span: mk_sp(lo, hi),
1333 debug!("parse_trait_methods(): parsing provided method");
1334 let (inner_attrs, body) =
1335 p.parse_inner_attrs_and_block();
1336 let attrs = attrs.append(inner_attrs.as_slice());
1337 ProvidedMethod(P(ast::Method {
1339 id: ast::DUMMY_NODE_ID,
1340 span: mk_sp(lo, hi),
1341 node: ast::MethDecl(ident,
1353 let token_str = p.this_token_to_string();
1354 p.fatal((format!("expected `;` or `{{`, found `{}`",
1355 token_str)).as_slice())
1362 /// Parse a possibly mutable type
1363 pub fn parse_mt(&mut self) -> MutTy {
1364 let mutbl = self.parse_mutability();
1365 let t = self.parse_ty(true);
1366 MutTy { ty: t, mutbl: mutbl }
1369 /// Parse [mut/const/imm] ID : TY
1370 /// now used only by obsolete record syntax parser...
1371 pub fn parse_ty_field(&mut self) -> TypeField {
1372 let lo = self.span.lo;
1373 let mutbl = self.parse_mutability();
1374 let id = self.parse_ident();
1375 self.expect(&token::COLON);
1376 let ty = self.parse_ty(true);
1377 let hi = ty.span.hi;
1380 mt: MutTy { ty: ty, mutbl: mutbl },
1381 span: mk_sp(lo, hi),
1385 /// Parse optional return type [ -> TY ] in function decl
1386 pub fn parse_ret_ty(&mut self) -> (RetStyle, P<Ty>) {
1387 return if self.eat(&token::RARROW) {
1388 let lo = self.span.lo;
1389 if self.eat(&token::NOT) {
1393 id: ast::DUMMY_NODE_ID,
1395 span: mk_sp(lo, self.last_span.hi)
1399 (Return, self.parse_ty(true))
1402 let pos = self.span.lo;
1406 id: ast::DUMMY_NODE_ID,
1408 span: mk_sp(pos, pos),
1416 /// The second parameter specifies whether the `+` binary operator is
1417 /// allowed in the type grammar.
1418 pub fn parse_ty(&mut self, plus_allowed: bool) -> P<Ty> {
1419 maybe_whole!(no_clone self, NtTy);
1421 let lo = self.span.lo;
1423 let t = if self.token == token::LPAREN {
1425 if self.token == token::RPAREN {
1429 // (t) is a parenthesized ty
1430 // (t,) is the type of a tuple with only one field,
1432 let mut ts = vec!(self.parse_ty(true));
1433 let mut one_tuple = false;
1434 while self.token == token::COMMA {
1436 if self.token != token::RPAREN {
1437 ts.push(self.parse_ty(true));
1444 if ts.len() == 1 && !one_tuple {
1445 self.expect(&token::RPAREN);
1446 TyParen(ts.into_iter().nth(0).unwrap())
1449 self.expect(&token::RPAREN);
1453 } else if self.token == token::AT {
1456 let span = self.last_span;
1457 self.obsolete(span, ObsoleteManagedType);
1458 TyBox(self.parse_ty(plus_allowed))
1459 } else if self.token == token::TILDE {
1462 let last_span = self.last_span;
1464 token::LBRACKET => self.obsolete(last_span, ObsoleteOwnedVector),
1465 _ => self.obsolete(last_span, ObsoleteOwnedType)
1467 TyUniq(self.parse_ty(false))
1468 } else if self.token == token::BINOP(token::STAR) {
1469 // STAR POINTER (bare pointer?)
1471 TyPtr(self.parse_ptr())
1472 } else if self.token == token::LBRACKET {
1474 self.expect(&token::LBRACKET);
1475 let t = self.parse_ty(true);
1477 // Parse the `, ..e` in `[ int, ..e ]`
1478 // where `e` is a const expression
1479 let t = match self.maybe_parse_fixed_vstore() {
1481 Some(suffix) => TyFixedLengthVec(t, suffix)
1483 self.expect(&token::RBRACKET);
1485 } else if self.token == token::BINOP(token::AND) ||
1486 self.token == token::ANDAND {
1489 self.parse_borrowed_pointee()
1490 } else if self.is_keyword(keywords::Extern) ||
1491 self.is_keyword(keywords::Unsafe) ||
1492 self.token_is_bare_fn_keyword() {
1494 self.parse_ty_bare_fn()
1495 } else if self.token_is_closure_keyword() ||
1496 self.token == token::BINOP(token::OR) ||
1497 self.token == token::OROR ||
1498 (self.token == token::LT &&
1499 self.look_ahead(1, |t| {
1500 *t == token::GT || Parser::token_is_lifetime(t)
1504 self.parse_ty_closure()
1505 } else if self.eat_keyword(keywords::Typeof) {
1507 // In order to not be ambiguous, the type must be surrounded by parens.
1508 self.expect(&token::LPAREN);
1509 let e = self.parse_expr();
1510 self.expect(&token::RPAREN);
1512 } else if self.eat_keyword(keywords::Proc) {
1513 self.parse_proc_type()
1514 } else if self.token == token::LT {
1517 let for_type = self.parse_ty(true);
1518 self.expect_keyword(keywords::As);
1519 let trait_name = self.parse_path(LifetimeAndTypesWithoutColons);
1520 self.expect(&token::GT);
1521 self.expect(&token::MOD_SEP);
1522 let item_name = self.parse_ident();
1525 trait_name: trait_name.path,
1526 item_name: item_name,
1528 } else if self.token == token::MOD_SEP
1529 || is_ident_or_path(&self.token) {
1531 let mode = if plus_allowed {
1532 LifetimeAndTypesAndBounds
1534 LifetimeAndTypesWithoutColons
1539 } = self.parse_path(mode);
1540 TyPath(path, bounds, ast::DUMMY_NODE_ID)
1541 } else if self.eat(&token::UNDERSCORE) {
1542 // TYPE TO BE INFERRED
1545 let msg = format!("expected type, found token {:?}", self.token);
1546 self.fatal(msg.as_slice());
1549 let sp = mk_sp(lo, self.last_span.hi);
1550 P(Ty {id: ast::DUMMY_NODE_ID, node: t, span: sp})
1553 pub fn parse_borrowed_pointee(&mut self) -> Ty_ {
1554 // look for `&'lt` or `&'foo ` and interpret `foo` as the region name:
1555 let opt_lifetime = self.parse_opt_lifetime();
1557 let mt = self.parse_mt();
1558 return TyRptr(opt_lifetime, mt);
1561 pub fn parse_ptr(&mut self) -> MutTy {
1562 let mutbl = if self.eat_keyword(keywords::Mut) {
1564 } else if self.eat_keyword(keywords::Const) {
1567 let span = self.last_span;
1569 "bare raw pointers are no longer allowed, you should \
1570 likely use `*mut T`, but otherwise `*T` is now \
1571 known as `*const T`");
1574 let t = self.parse_ty(true);
1575 MutTy { ty: t, mutbl: mutbl }
1578 pub fn is_named_argument(&mut self) -> bool {
1579 let offset = match self.token {
1580 token::BINOP(token::AND) => 1,
1582 _ if token::is_keyword(keywords::Mut, &self.token) => 1,
1586 debug!("parser is_named_argument offset:{}", offset);
1589 is_plain_ident_or_underscore(&self.token)
1590 && self.look_ahead(1, |t| *t == token::COLON)
1592 self.look_ahead(offset, |t| is_plain_ident_or_underscore(t))
1593 && self.look_ahead(offset + 1, |t| *t == token::COLON)
1597 /// This version of parse arg doesn't necessarily require
1598 /// identifier names.
1599 pub fn parse_arg_general(&mut self, require_name: bool) -> Arg {
1600 let pat = if require_name || self.is_named_argument() {
1601 debug!("parse_arg_general parse_pat (require_name:{:?})",
1603 let pat = self.parse_pat();
1605 self.expect(&token::COLON);
1608 debug!("parse_arg_general ident_to_pat");
1609 ast_util::ident_to_pat(ast::DUMMY_NODE_ID,
1611 special_idents::invalid)
1614 let t = self.parse_ty(true);
1619 id: ast::DUMMY_NODE_ID,
1623 /// Parse a single function argument
1624 pub fn parse_arg(&mut self) -> Arg {
1625 self.parse_arg_general(true)
1628 /// Parse an argument in a lambda header e.g. |arg, arg|
1629 pub fn parse_fn_block_arg(&mut self) -> Arg {
1630 let pat = self.parse_pat();
1631 let t = if self.eat(&token::COLON) {
1635 id: ast::DUMMY_NODE_ID,
1637 span: mk_sp(self.span.lo, self.span.hi),
1643 id: ast::DUMMY_NODE_ID
1647 pub fn maybe_parse_fixed_vstore(&mut self) -> Option<P<ast::Expr>> {
1648 if self.token == token::COMMA &&
1649 self.look_ahead(1, |t| *t == token::DOTDOT) {
1652 Some(self.parse_expr())
1658 /// Matches token_lit = LIT_INTEGER | ...
1659 pub fn lit_from_token(&mut self, tok: &token::Token) -> Lit_ {
1661 token::LIT_BYTE(i) => LitByte(parse::byte_lit(i.as_str()).val0()),
1662 token::LIT_CHAR(i) => LitChar(parse::char_lit(i.as_str()).val0()),
1663 token::LIT_INTEGER(s) => parse::integer_lit(s.as_str(),
1664 &self.sess.span_diagnostic, self.span),
1665 token::LIT_FLOAT(s) => parse::float_lit(s.as_str()),
1666 token::LIT_STR(s) => {
1667 LitStr(token::intern_and_get_ident(parse::str_lit(s.as_str()).as_slice()),
1670 token::LIT_STR_RAW(s, n) => {
1671 LitStr(token::intern_and_get_ident(parse::raw_str_lit(s.as_str()).as_slice()),
1674 token::LIT_BINARY(i) =>
1675 LitBinary(parse::binary_lit(i.as_str())),
1676 token::LIT_BINARY_RAW(i, _) =>
1677 LitBinary(Rc::new(i.as_str().as_bytes().iter().map(|&x| x).collect())),
1678 token::LPAREN => { self.expect(&token::RPAREN); LitNil },
1679 _ => { self.unexpected_last(tok); }
1683 /// Matches lit = true | false | token_lit
1684 pub fn parse_lit(&mut self) -> Lit {
1685 let lo = self.span.lo;
1686 let lit = if self.eat_keyword(keywords::True) {
1688 } else if self.eat_keyword(keywords::False) {
1691 let token = self.bump_and_get();
1692 let lit = self.lit_from_token(&token);
1695 codemap::Spanned { node: lit, span: mk_sp(lo, self.last_span.hi) }
1698 /// matches '-' lit | lit
1699 pub fn parse_literal_maybe_minus(&mut self) -> P<Expr> {
1700 let minus_lo = self.span.lo;
1701 let minus_present = self.eat(&token::BINOP(token::MINUS));
1703 let lo = self.span.lo;
1704 let literal = P(self.parse_lit());
1705 let hi = self.span.hi;
1706 let expr = self.mk_expr(lo, hi, ExprLit(literal));
1709 let minus_hi = self.span.hi;
1710 let unary = self.mk_unary(UnNeg, expr);
1711 self.mk_expr(minus_lo, minus_hi, unary)
1717 /// Parses a path and optional type parameter bounds, depending on the
1718 /// mode. The `mode` parameter determines whether lifetimes, types, and/or
1719 /// bounds are permitted and whether `::` must precede type parameter
1721 pub fn parse_path(&mut self, mode: PathParsingMode) -> PathAndBounds {
1722 // Check for a whole path...
1723 let found = match self.token {
1724 INTERPOLATED(token::NtPath(_)) => Some(self.bump_and_get()),
1728 Some(INTERPOLATED(token::NtPath(box path))) => {
1729 return PathAndBounds {
1737 let lo = self.span.lo;
1738 let is_global = self.eat(&token::MOD_SEP);
1740 // Parse any number of segments and bound sets. A segment is an
1741 // identifier followed by an optional lifetime and a set of types.
1742 // A bound set is a set of type parameter bounds.
1743 let mut segments = Vec::new();
1745 // First, parse an identifier.
1746 let identifier = self.parse_ident();
1748 // Parse the '::' before type parameters if it's required. If
1749 // it is required and wasn't present, then we're done.
1750 if mode == LifetimeAndTypesWithColons &&
1751 !self.eat(&token::MOD_SEP) {
1752 segments.push(ast::PathSegment {
1753 identifier: identifier,
1754 lifetimes: Vec::new(),
1755 types: OwnedSlice::empty(),
1760 // Parse the `<` before the lifetime and types, if applicable.
1761 let (any_lifetime_or_types, lifetimes, types) = {
1762 if mode != NoTypesAllowed && self.eat_lt(false) {
1763 let (lifetimes, types) =
1764 self.parse_generic_values_after_lt();
1765 (true, lifetimes, OwnedSlice::from_vec(types))
1767 (false, Vec::new(), OwnedSlice::empty())
1771 // Assemble and push the result.
1772 segments.push(ast::PathSegment {
1773 identifier: identifier,
1774 lifetimes: lifetimes,
1778 // We're done if we don't see a '::', unless the mode required
1779 // a double colon to get here in the first place.
1780 if !(mode == LifetimeAndTypesWithColons &&
1781 !any_lifetime_or_types) {
1782 if !self.eat(&token::MOD_SEP) {
1788 // Next, parse a plus and bounded type parameters, if
1789 // applicable. We need to remember whether the separate was
1790 // present for later, because in some contexts it's a parse
1793 if mode == LifetimeAndTypesAndBounds &&
1794 self.eat(&token::BINOP(token::PLUS))
1796 let bounds = self.parse_ty_param_bounds();
1798 // For some reason that I do not fully understand, we
1799 // do not permit an empty list in the case where it is
1800 // introduced by a `+`, but we do for `:` and other
1801 // separators. -nmatsakis
1802 if bounds.len() == 0 {
1803 let last_span = self.last_span;
1804 self.span_err(last_span,
1805 "at least one type parameter bound \
1806 must be specified");
1815 // Assemble the span.
1816 let span = mk_sp(lo, self.last_span.hi);
1818 // Assemble the result.
1829 /// parses 0 or 1 lifetime
1830 pub fn parse_opt_lifetime(&mut self) -> Option<ast::Lifetime> {
1832 token::LIFETIME(..) => {
1833 Some(self.parse_lifetime())
1841 /// Parses a single lifetime
1842 /// Matches lifetime = LIFETIME
1843 pub fn parse_lifetime(&mut self) -> ast::Lifetime {
1845 token::LIFETIME(i) => {
1846 let span = self.span;
1848 return ast::Lifetime {
1849 id: ast::DUMMY_NODE_ID,
1855 self.fatal(format!("expected a lifetime name").as_slice());
1860 pub fn parse_lifetime_defs(&mut self) -> Vec<ast::LifetimeDef> {
1862 * Parses `lifetime_defs = [ lifetime_defs { ',' lifetime_defs } ]`
1863 * where `lifetime_def = lifetime [':' lifetimes]`
1866 let mut res = Vec::new();
1869 token::LIFETIME(_) => {
1870 let lifetime = self.parse_lifetime();
1872 if self.eat(&token::COLON) {
1873 self.parse_lifetimes(token::BINOP(token::PLUS))
1877 res.push(ast::LifetimeDef { lifetime: lifetime,
1887 token::COMMA => { self.bump(); }
1888 token::GT => { return res; }
1889 token::BINOP(token::SHR) => { return res; }
1891 let msg = format!("expected `,` or `>` after lifetime \
1894 self.fatal(msg.as_slice());
1900 // matches lifetimes = ( lifetime ) | ( lifetime , lifetimes )
1901 // actually, it matches the empty one too, but putting that in there
1902 // messes up the grammar....
1903 pub fn parse_lifetimes(&mut self, sep: token::Token) -> Vec<ast::Lifetime> {
1905 * Parses zero or more comma separated lifetimes.
1906 * Expects each lifetime to be followed by either
1907 * a comma or `>`. Used when parsing type parameter
1908 * lists, where we expect something like `<'a, 'b, T>`.
1911 let mut res = Vec::new();
1914 token::LIFETIME(_) => {
1915 res.push(self.parse_lifetime());
1922 if self.token != sep {
1930 pub fn token_is_mutability(tok: &token::Token) -> bool {
1931 token::is_keyword(keywords::Mut, tok) ||
1932 token::is_keyword(keywords::Const, tok)
1935 /// Parse mutability declaration (mut/const/imm)
1936 pub fn parse_mutability(&mut self) -> Mutability {
1937 if self.eat_keyword(keywords::Mut) {
1944 /// Parse ident COLON expr
1945 pub fn parse_field(&mut self) -> Field {
1946 let lo = self.span.lo;
1947 let i = self.parse_ident();
1948 let hi = self.last_span.hi;
1949 self.expect(&token::COLON);
1950 let e = self.parse_expr();
1952 ident: spanned(lo, hi, i),
1953 span: mk_sp(lo, e.span.hi),
1958 pub fn mk_expr(&mut self, lo: BytePos, hi: BytePos, node: Expr_) -> P<Expr> {
1960 id: ast::DUMMY_NODE_ID,
1962 span: mk_sp(lo, hi),
1966 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::Expr_ {
1967 ExprUnary(unop, expr)
1970 pub fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::Expr_ {
1971 ExprBinary(binop, lhs, rhs)
1974 pub fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::Expr_ {
1978 fn mk_method_call(&mut self,
1979 ident: ast::SpannedIdent,
1983 ExprMethodCall(ident, tps, args)
1986 pub fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::Expr_ {
1987 ExprIndex(expr, idx)
1990 pub fn mk_slice(&mut self, expr: P<Expr>,
1991 start: Option<P<Expr>>,
1992 end: Option<P<Expr>>,
1995 ExprSlice(expr, start, end, mutbl)
1998 pub fn mk_field(&mut self, expr: P<Expr>, ident: ast::SpannedIdent,
1999 tys: Vec<P<Ty>>) -> ast::Expr_ {
2000 ExprField(expr, ident, tys)
2003 pub fn mk_tup_field(&mut self, expr: P<Expr>, idx: codemap::Spanned<uint>,
2004 tys: Vec<P<Ty>>) -> ast::Expr_ {
2005 ExprTupField(expr, idx, tys)
2008 pub fn mk_assign_op(&mut self, binop: ast::BinOp,
2009 lhs: P<Expr>, rhs: P<Expr>) -> ast::Expr_ {
2010 ExprAssignOp(binop, lhs, rhs)
2013 pub fn mk_mac_expr(&mut self, lo: BytePos, hi: BytePos, m: Mac_) -> P<Expr> {
2015 id: ast::DUMMY_NODE_ID,
2016 node: ExprMac(codemap::Spanned {node: m, span: mk_sp(lo, hi)}),
2017 span: mk_sp(lo, hi),
2021 pub fn mk_lit_u32(&mut self, i: u32) -> P<Expr> {
2022 let span = &self.span;
2023 let lv_lit = P(codemap::Spanned {
2024 node: LitInt(i as u64, ast::UnsignedIntLit(TyU32)),
2029 id: ast::DUMMY_NODE_ID,
2030 node: ExprLit(lv_lit),
2035 /// At the bottom (top?) of the precedence hierarchy,
2036 /// parse things like parenthesized exprs,
2037 /// macros, return, etc.
2038 pub fn parse_bottom_expr(&mut self) -> P<Expr> {
2039 maybe_whole_expr!(self);
2041 let lo = self.span.lo;
2042 let mut hi = self.span.hi;
2049 // (e) is parenthesized e
2050 // (e,) is a tuple with only one field, e
2051 let mut trailing_comma = false;
2052 if self.token == token::RPAREN {
2055 let lit = P(spanned(lo, hi, LitNil));
2056 return self.mk_expr(lo, hi, ExprLit(lit));
2058 let mut es = vec!(self.parse_expr());
2059 self.commit_expr(&**es.last().unwrap(), &[], &[token::COMMA, token::RPAREN]);
2060 while self.token == token::COMMA {
2062 if self.token != token::RPAREN {
2063 es.push(self.parse_expr());
2064 self.commit_expr(&**es.last().unwrap(), &[],
2065 &[token::COMMA, token::RPAREN]);
2067 trailing_comma = true;
2071 self.commit_expr_expecting(&**es.last().unwrap(), token::RPAREN);
2073 return if es.len() == 1 && !trailing_comma {
2074 self.mk_expr(lo, hi, ExprParen(es.into_iter().nth(0).unwrap()))
2076 self.mk_expr(lo, hi, ExprTup(es))
2081 let blk = self.parse_block_tail(lo, DefaultBlock);
2082 return self.mk_expr(blk.span.lo, blk.span.hi,
2085 token::BINOP(token::OR) | token::OROR => {
2086 return self.parse_lambda_expr(CaptureByValue);
2088 // FIXME #13626: Should be able to stick in
2089 // token::SELF_KEYWORD_NAME
2090 token::IDENT(id @ ast::Ident{
2091 name: ast::Name(token::SELF_KEYWORD_NAME_NUM),
2095 let path = ast_util::ident_to_path(mk_sp(lo, hi), id);
2096 ex = ExprPath(path);
2097 hi = self.last_span.hi;
2099 token::LBRACKET => {
2102 if self.token == token::RBRACKET {
2105 ex = ExprVec(Vec::new());
2108 let first_expr = self.parse_expr();
2109 if self.token == token::COMMA &&
2110 self.look_ahead(1, |t| *t == token::DOTDOT) {
2111 // Repeating vector syntax: [ 0, ..512 ]
2114 let count = self.parse_expr();
2115 self.expect(&token::RBRACKET);
2116 ex = ExprRepeat(first_expr, count);
2117 } else if self.token == token::COMMA {
2118 // Vector with two or more elements.
2120 let remaining_exprs = self.parse_seq_to_end(
2122 seq_sep_trailing_allowed(token::COMMA),
2125 let mut exprs = vec!(first_expr);
2126 exprs.push_all_move(remaining_exprs);
2127 ex = ExprVec(exprs);
2129 // Vector with one element.
2130 self.expect(&token::RBRACKET);
2131 ex = ExprVec(vec!(first_expr));
2134 hi = self.last_span.hi;
2137 if self.eat_keyword(keywords::Ref) {
2138 return self.parse_lambda_expr(CaptureByRef);
2140 if self.eat_keyword(keywords::Proc) {
2141 let decl = self.parse_proc_decl();
2142 let body = self.parse_expr();
2143 let fakeblock = P(ast::Block {
2144 id: ast::DUMMY_NODE_ID,
2145 view_items: Vec::new(),
2147 rules: DefaultBlock,
2151 return self.mk_expr(lo, fakeblock.span.hi, ExprProc(decl, fakeblock));
2153 if self.eat_keyword(keywords::If) {
2154 return self.parse_if_expr();
2156 if self.eat_keyword(keywords::For) {
2157 return self.parse_for_expr(None);
2159 if self.eat_keyword(keywords::While) {
2160 return self.parse_while_expr(None);
2162 if Parser::token_is_lifetime(&self.token) {
2163 let lifetime = self.get_lifetime();
2165 self.expect(&token::COLON);
2166 if self.eat_keyword(keywords::While) {
2167 return self.parse_while_expr(Some(lifetime))
2169 if self.eat_keyword(keywords::For) {
2170 return self.parse_for_expr(Some(lifetime))
2172 if self.eat_keyword(keywords::Loop) {
2173 return self.parse_loop_expr(Some(lifetime))
2175 self.fatal("expected `while`, `for`, or `loop` after a label")
2177 if self.eat_keyword(keywords::Loop) {
2178 return self.parse_loop_expr(None);
2180 if self.eat_keyword(keywords::Continue) {
2181 let lo = self.span.lo;
2182 let ex = if Parser::token_is_lifetime(&self.token) {
2183 let lifetime = self.get_lifetime();
2185 ExprAgain(Some(lifetime))
2189 let hi = self.span.hi;
2190 return self.mk_expr(lo, hi, ex);
2192 if self.eat_keyword(keywords::Match) {
2193 return self.parse_match_expr();
2195 if self.eat_keyword(keywords::Unsafe) {
2196 return self.parse_block_expr(
2198 UnsafeBlock(ast::UserProvided));
2200 if self.eat_keyword(keywords::Return) {
2201 // RETURN expression
2202 if can_begin_expr(&self.token) {
2203 let e = self.parse_expr();
2205 ex = ExprRet(Some(e));
2209 } else if self.eat_keyword(keywords::Break) {
2211 if Parser::token_is_lifetime(&self.token) {
2212 let lifetime = self.get_lifetime();
2214 ex = ExprBreak(Some(lifetime));
2216 ex = ExprBreak(None);
2219 } else if self.token == token::MOD_SEP ||
2220 is_ident(&self.token) &&
2221 !self.is_keyword(keywords::True) &&
2222 !self.is_keyword(keywords::False) {
2224 self.parse_path(LifetimeAndTypesWithColons).path;
2226 // `!`, as an operator, is prefix, so we know this isn't that
2227 if self.token == token::NOT {
2228 // MACRO INVOCATION expression
2231 let ket = token::close_delimiter_for(&self.token)
2232 .unwrap_or_else(|| {
2233 self.fatal("expected open delimiter")
2237 let tts = self.parse_seq_to_end(
2240 |p| p.parse_token_tree());
2241 let hi = self.span.hi;
2243 return self.mk_mac_expr(lo,
2249 if self.token == token::LBRACE {
2250 // This is a struct literal, unless we're prohibited
2251 // from parsing struct literals here.
2252 if !self.restrictions.contains(RestrictionNoStructLiteral) {
2253 // It's a struct literal.
2255 let mut fields = Vec::new();
2256 let mut base = None;
2258 while self.token != token::RBRACE {
2259 if self.eat(&token::DOTDOT) {
2260 base = Some(self.parse_expr());
2264 fields.push(self.parse_field());
2265 self.commit_expr(&*fields.last().unwrap().expr,
2270 if fields.len() == 0 && base.is_none() {
2271 let last_span = self.last_span;
2272 self.span_err(last_span,
2273 "structure literal must either \
2274 have at least one field or use \
2275 functional structure update \
2280 self.expect(&token::RBRACE);
2281 ex = ExprStruct(pth, fields, base);
2282 return self.mk_expr(lo, hi, ex);
2289 // other literal expression
2290 let lit = self.parse_lit();
2292 ex = ExprLit(P(lit));
2297 return self.mk_expr(lo, hi, ex);
2300 /// Parse a block or unsafe block
2301 pub fn parse_block_expr(&mut self, lo: BytePos, blk_mode: BlockCheckMode)
2303 self.expect(&token::LBRACE);
2304 let blk = self.parse_block_tail(lo, blk_mode);
2305 return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk));
2308 /// parse a.b or a(13) or a[4] or just a
2309 pub fn parse_dot_or_call_expr(&mut self) -> P<Expr> {
2310 let b = self.parse_bottom_expr();
2311 self.parse_dot_or_call_expr_with(b)
2314 pub fn parse_dot_or_call_expr_with(&mut self, e0: P<Expr>) -> P<Expr> {
2320 if self.eat(&token::DOT) {
2322 token::IDENT(i, _) => {
2323 let dot = self.last_span.hi;
2326 let (_, tys) = if self.eat(&token::MOD_SEP) {
2328 self.parse_generic_values_after_lt()
2330 (Vec::new(), Vec::new())
2333 // expr.f() method call
2336 let mut es = self.parse_unspanned_seq(
2339 seq_sep_trailing_allowed(token::COMMA),
2342 hi = self.last_span.hi;
2345 let id = spanned(dot, hi, i);
2346 let nd = self.mk_method_call(id, tys, es);
2347 e = self.mk_expr(lo, hi, nd);
2350 let id = spanned(dot, hi, i);
2351 let field = self.mk_field(e, id, tys);
2352 e = self.mk_expr(lo, hi, field)
2356 token::LIT_INTEGER(n) => {
2357 let index = n.as_str();
2358 let dot = self.last_span.hi;
2361 let (_, tys) = if self.eat(&token::MOD_SEP) {
2363 self.parse_generic_values_after_lt()
2365 (Vec::new(), Vec::new())
2368 let num = from_str::<uint>(index);
2371 let id = spanned(dot, hi, n);
2372 let field = self.mk_tup_field(e, id, tys);
2373 e = self.mk_expr(lo, hi, field);
2376 let last_span = self.last_span;
2377 self.span_err(last_span, "invalid tuple or tuple struct index");
2381 token::LIT_FLOAT(n) => {
2383 let last_span = self.last_span;
2384 self.span_err(last_span,
2385 format!("unexpected token: `{}`", n.as_str()).as_slice());
2386 self.span_note(last_span,
2387 "try parenthesizing the first index; e.g., `(foo.0).1`");
2388 self.abort_if_errors();
2391 _ => self.unexpected()
2395 if self.expr_is_complete(&*e) { break; }
2399 let es = self.parse_unspanned_seq(
2402 seq_sep_trailing_allowed(token::COMMA),
2405 hi = self.last_span.hi;
2407 let nd = self.mk_call(e, es);
2408 e = self.mk_expr(lo, hi, nd);
2412 // Could be either an index expression or a slicing expression.
2413 // Any slicing non-terminal can have a mutable version with `mut`
2414 // after the opening square bracket.
2415 token::LBRACKET => {
2417 let mutbl = if self.eat_keyword(keywords::Mut) {
2424 token::RBRACKET => {
2427 let slice = self.mk_slice(e, None, None, mutbl);
2428 e = self.mk_expr(lo, hi, slice)
2435 token::RBRACKET => {
2438 let slice = self.mk_slice(e, None, None, mutbl);
2439 e = self.mk_expr(lo, hi, slice);
2441 self.span_err(e.span, "incorrect slicing expression: `[..]`");
2442 self.span_note(e.span,
2443 "use `expr[]` to construct a slice of the whole of expr");
2448 let e2 = self.parse_expr();
2449 self.commit_expr_expecting(&*e2, token::RBRACKET);
2450 let slice = self.mk_slice(e, None, Some(e2), mutbl);
2451 e = self.mk_expr(lo, hi, slice)
2455 // e[e] | e[e..] | e[e..e]
2457 let ix = self.parse_expr();
2462 let e2 = match self.token {
2464 token::RBRACKET => {
2470 let e2 = self.parse_expr();
2471 self.commit_expr_expecting(&*e2, token::RBRACKET);
2476 let slice = self.mk_slice(e, Some(ix), e2, mutbl);
2477 e = self.mk_expr(lo, hi, slice)
2481 if mutbl == ast::MutMutable {
2482 self.span_err(e.span,
2483 "`mut` keyword is invalid in index expressions");
2486 self.commit_expr_expecting(&*ix, token::RBRACKET);
2487 let index = self.mk_index(e, ix);
2488 e = self.mk_expr(lo, hi, index)
2501 /// Parse an optional separator followed by a kleene-style
2502 /// repetition token (+ or *).
2503 pub fn parse_sep_and_zerok(&mut self) -> (Option<token::Token>, bool) {
2504 fn parse_zerok(parser: &mut Parser) -> Option<bool> {
2505 match parser.token {
2506 token::BINOP(token::STAR) | token::BINOP(token::PLUS) => {
2507 let zerok = parser.token == token::BINOP(token::STAR);
2515 match parse_zerok(self) {
2516 Some(zerok) => return (None, zerok),
2520 let separator = self.bump_and_get();
2521 match parse_zerok(self) {
2522 Some(zerok) => (Some(separator), zerok),
2523 None => self.fatal("expected `*` or `+`")
2527 /// parse a single token tree from the input.
2528 pub fn parse_token_tree(&mut self) -> TokenTree {
2529 // FIXME #6994: currently, this is too eager. It
2530 // parses token trees but also identifies TTSeq's
2531 // and TTNonterminal's; it's too early to know yet
2532 // whether something will be a nonterminal or a seq
2534 maybe_whole!(deref self, NtTT);
2536 // this is the fall-through for the 'match' below.
2537 // invariants: the current token is not a left-delimiter,
2538 // not an EOF, and not the desired right-delimiter (if
2539 // it were, parse_seq_to_before_end would have prevented
2540 // reaching this point.
2541 fn parse_non_delim_tt_tok(p: &mut Parser) -> TokenTree {
2542 maybe_whole!(deref p, NtTT);
2544 token::RPAREN | token::RBRACE | token::RBRACKET => {
2545 // This is a conservative error: only report the last unclosed delimiter. The
2546 // previous unclosed delimiters could actually be closed! The parser just hasn't
2547 // gotten to them yet.
2548 match p.open_braces.last() {
2550 Some(&sp) => p.span_note(sp, "unclosed delimiter"),
2552 let token_str = p.this_token_to_string();
2553 p.fatal(format!("incorrect close delimiter: `{}`",
2554 token_str).as_slice())
2556 /* we ought to allow different depths of unquotation */
2557 token::DOLLAR if p.quote_depth > 0u => {
2561 if p.token == token::LPAREN {
2562 let seq = p.parse_seq(
2566 |p| p.parse_token_tree()
2568 let (s, z) = p.parse_sep_and_zerok();
2569 let seq = match seq {
2570 Spanned { node, .. } => node,
2572 TTSeq(mk_sp(sp.lo, p.span.hi), Rc::new(seq), s, z)
2574 TTNonterminal(sp, p.parse_ident())
2583 // turn the next token into a TTTok:
2584 fn parse_any_tt_tok(p: &mut Parser) -> TokenTree {
2585 TTTok(p.span, p.bump_and_get())
2588 match (&self.token, token::close_delimiter_for(&self.token)) {
2589 (&token::EOF, _) => {
2590 let open_braces = self.open_braces.clone();
2591 for sp in open_braces.iter() {
2592 self.span_note(*sp, "Did you mean to close this delimiter?");
2594 // There shouldn't really be a span, but it's easier for the test runner
2595 // if we give it one
2596 self.fatal("this file contains an un-closed delimiter ");
2598 (_, Some(close_delim)) => {
2599 // Parse the open delimiter.
2600 self.open_braces.push(self.span);
2601 let mut result = vec!(parse_any_tt_tok(self));
2604 self.parse_seq_to_before_end(&close_delim,
2606 |p| p.parse_token_tree());
2607 result.push_all_move(trees);
2609 // Parse the close delimiter.
2610 result.push(parse_any_tt_tok(self));
2611 self.open_braces.pop().unwrap();
2613 TTDelim(Rc::new(result))
2615 _ => parse_non_delim_tt_tok(self)
2619 // parse a stream of tokens into a list of TokenTree's,
2621 pub fn parse_all_token_trees(&mut self) -> Vec<TokenTree> {
2622 let mut tts = Vec::new();
2623 while self.token != token::EOF {
2624 tts.push(self.parse_token_tree());
2629 pub fn parse_matchers(&mut self) -> Vec<Matcher> {
2630 // unification of Matcher's and TokenTree's would vastly improve
2631 // the interpolation of Matcher's
2632 maybe_whole!(self, NtMatchers);
2633 let mut name_idx = 0u;
2634 match token::close_delimiter_for(&self.token) {
2635 Some(other_delimiter) => {
2637 self.parse_matcher_subseq_upto(&mut name_idx, &other_delimiter)
2639 None => self.fatal("expected open delimiter")
2643 /// This goofy function is necessary to correctly match parens in Matcher's.
2644 /// Otherwise, `$( ( )` would be a valid Matcher, and `$( () )` would be
2645 /// invalid. It's similar to common::parse_seq.
2646 pub fn parse_matcher_subseq_upto(&mut self,
2647 name_idx: &mut uint,
2650 let mut ret_val = Vec::new();
2651 let mut lparens = 0u;
2653 while self.token != *ket || lparens > 0u {
2654 if self.token == token::LPAREN { lparens += 1u; }
2655 if self.token == token::RPAREN { lparens -= 1u; }
2656 ret_val.push(self.parse_matcher(name_idx));
2664 pub fn parse_matcher(&mut self, name_idx: &mut uint) -> Matcher {
2665 let lo = self.span.lo;
2667 let m = if self.token == token::DOLLAR {
2669 if self.token == token::LPAREN {
2670 let name_idx_lo = *name_idx;
2672 let ms = self.parse_matcher_subseq_upto(name_idx,
2675 self.fatal("repetition body must be nonempty");
2677 let (sep, zerok) = self.parse_sep_and_zerok();
2678 MatchSeq(ms, sep, zerok, name_idx_lo, *name_idx)
2680 let bound_to = self.parse_ident();
2681 self.expect(&token::COLON);
2682 let nt_name = self.parse_ident();
2683 let m = MatchNonterminal(bound_to, nt_name, *name_idx);
2688 MatchTok(self.bump_and_get())
2691 return spanned(lo, self.span.hi, m);
2694 /// Parse a prefix-operator expr
2695 pub fn parse_prefix_expr(&mut self) -> P<Expr> {
2696 let lo = self.span.lo;
2703 let e = self.parse_prefix_expr();
2705 ex = self.mk_unary(UnNot, e);
2707 token::BINOP(token::MINUS) => {
2709 let e = self.parse_prefix_expr();
2711 ex = self.mk_unary(UnNeg, e);
2713 token::BINOP(token::STAR) => {
2715 let e = self.parse_prefix_expr();
2717 ex = self.mk_unary(UnDeref, e);
2719 token::BINOP(token::AND) | token::ANDAND => {
2721 let m = self.parse_mutability();
2722 let e = self.parse_prefix_expr();
2724 ex = ExprAddrOf(m, e);
2728 let span = self.last_span;
2729 self.obsolete(span, ObsoleteManagedExpr);
2730 let e = self.parse_prefix_expr();
2732 ex = self.mk_unary(UnBox, e);
2736 let last_span = self.last_span;
2738 token::LBRACKET => self.obsolete(last_span, ObsoleteOwnedVector),
2739 _ => self.obsolete(last_span, ObsoleteOwnedExpr)
2742 let e = self.parse_prefix_expr();
2744 ex = self.mk_unary(UnUniq, e);
2746 token::IDENT(_, _) => {
2747 if !self.is_keyword(keywords::Box) {
2748 return self.parse_dot_or_call_expr();
2753 // Check for a place: `box(PLACE) EXPR`.
2754 if self.eat(&token::LPAREN) {
2755 // Support `box() EXPR` as the default.
2756 if !self.eat(&token::RPAREN) {
2757 let place = self.parse_expr();
2758 self.expect(&token::RPAREN);
2759 let subexpression = self.parse_prefix_expr();
2760 hi = subexpression.span.hi;
2761 ex = ExprBox(place, subexpression);
2762 return self.mk_expr(lo, hi, ex);
2766 // Otherwise, we use the unique pointer default.
2767 let subexpression = self.parse_prefix_expr();
2768 hi = subexpression.span.hi;
2769 ex = self.mk_unary(UnUniq, subexpression);
2771 _ => return self.parse_dot_or_call_expr()
2773 return self.mk_expr(lo, hi, ex);
2776 /// Parse an expression of binops
2777 pub fn parse_binops(&mut self) -> P<Expr> {
2778 let prefix_expr = self.parse_prefix_expr();
2779 self.parse_more_binops(prefix_expr, 0)
2782 /// Parse an expression of binops of at least min_prec precedence
2783 pub fn parse_more_binops(&mut self, lhs: P<Expr>, min_prec: uint) -> P<Expr> {
2784 if self.expr_is_complete(&*lhs) { return lhs; }
2786 // Prevent dynamic borrow errors later on by limiting the
2787 // scope of the borrows.
2788 if self.token == token::BINOP(token::OR) &&
2789 self.restrictions.contains(RestrictionNoBarOp) {
2793 let cur_opt = token_to_binop(&self.token);
2796 let cur_prec = operator_prec(cur_op);
2797 if cur_prec > min_prec {
2799 let expr = self.parse_prefix_expr();
2800 let rhs = self.parse_more_binops(expr, cur_prec);
2801 let lhs_span = lhs.span;
2802 let rhs_span = rhs.span;
2803 let binary = self.mk_binary(cur_op, lhs, rhs);
2804 let bin = self.mk_expr(lhs_span.lo, rhs_span.hi, binary);
2805 self.parse_more_binops(bin, min_prec)
2811 if as_prec > min_prec && self.eat_keyword(keywords::As) {
2812 let rhs = self.parse_ty(false);
2813 let _as = self.mk_expr(lhs.span.lo,
2815 ExprCast(lhs, rhs));
2816 self.parse_more_binops(_as, min_prec)
2824 /// Parse an assignment expression....
2825 /// actually, this seems to be the main entry point for
2826 /// parsing an arbitrary expression.
2827 pub fn parse_assign_expr(&mut self) -> P<Expr> {
2828 let lo = self.span.lo;
2829 let lhs = self.parse_binops();
2830 let restrictions = self.restrictions & RestrictionNoStructLiteral;
2834 let rhs = self.parse_expr_res(restrictions);
2835 self.mk_expr(lo, rhs.span.hi, ExprAssign(lhs, rhs))
2837 token::BINOPEQ(op) => {
2839 let rhs = self.parse_expr_res(restrictions);
2840 let aop = match op {
2841 token::PLUS => BiAdd,
2842 token::MINUS => BiSub,
2843 token::STAR => BiMul,
2844 token::SLASH => BiDiv,
2845 token::PERCENT => BiRem,
2846 token::CARET => BiBitXor,
2847 token::AND => BiBitAnd,
2848 token::OR => BiBitOr,
2849 token::SHL => BiShl,
2852 let rhs_span = rhs.span;
2853 let assign_op = self.mk_assign_op(aop, lhs, rhs);
2854 self.mk_expr(lo, rhs_span.hi, assign_op)
2862 /// Parse an 'if' expression ('if' token already eaten)
2863 pub fn parse_if_expr(&mut self) -> P<Expr> {
2864 let lo = self.last_span.lo;
2865 let cond = self.parse_expr_res(RestrictionNoStructLiteral);
2866 let thn = self.parse_block();
2867 let mut els: Option<P<Expr>> = None;
2868 let mut hi = thn.span.hi;
2869 if self.eat_keyword(keywords::Else) {
2870 let elexpr = self.parse_else_expr();
2871 hi = elexpr.span.hi;
2874 self.mk_expr(lo, hi, ExprIf(cond, thn, els))
2878 pub fn parse_lambda_expr(&mut self, capture_clause: CaptureClause)
2880 let lo = self.span.lo;
2881 let (decl, optional_unboxed_closure_kind) =
2882 self.parse_fn_block_decl();
2883 let body = self.parse_expr();
2884 let fakeblock = P(ast::Block {
2885 id: ast::DUMMY_NODE_ID,
2886 view_items: Vec::new(),
2890 rules: DefaultBlock,
2893 match optional_unboxed_closure_kind {
2894 Some(unboxed_closure_kind) => {
2897 ExprUnboxedFn(capture_clause,
2898 unboxed_closure_kind,
2905 ExprFnBlock(capture_clause, decl, fakeblock))
2910 pub fn parse_else_expr(&mut self) -> P<Expr> {
2911 if self.eat_keyword(keywords::If) {
2912 return self.parse_if_expr();
2914 let blk = self.parse_block();
2915 return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk));
2919 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
2920 pub fn parse_for_expr(&mut self, opt_ident: Option<ast::Ident>) -> P<Expr> {
2921 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
2923 let lo = self.last_span.lo;
2924 let pat = self.parse_pat();
2925 self.expect_keyword(keywords::In);
2926 let expr = self.parse_expr_res(RestrictionNoStructLiteral);
2927 let loop_block = self.parse_block();
2928 let hi = self.span.hi;
2930 self.mk_expr(lo, hi, ExprForLoop(pat, expr, loop_block, opt_ident))
2933 pub fn parse_while_expr(&mut self, opt_ident: Option<ast::Ident>) -> P<Expr> {
2934 let lo = self.last_span.lo;
2935 let cond = self.parse_expr_res(RestrictionNoStructLiteral);
2936 let body = self.parse_block();
2937 let hi = body.span.hi;
2938 return self.mk_expr(lo, hi, ExprWhile(cond, body, opt_ident));
2941 pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::Ident>) -> P<Expr> {
2942 let lo = self.last_span.lo;
2943 let body = self.parse_block();
2944 let hi = body.span.hi;
2945 self.mk_expr(lo, hi, ExprLoop(body, opt_ident))
2948 fn parse_match_expr(&mut self) -> P<Expr> {
2949 let lo = self.last_span.lo;
2950 let discriminant = self.parse_expr_res(RestrictionNoStructLiteral);
2951 self.commit_expr_expecting(&*discriminant, token::LBRACE);
2952 let mut arms: Vec<Arm> = Vec::new();
2953 while self.token != token::RBRACE {
2954 arms.push(self.parse_arm());
2956 let hi = self.span.hi;
2958 return self.mk_expr(lo, hi, ExprMatch(discriminant, arms));
2961 pub fn parse_arm(&mut self) -> Arm {
2962 let attrs = self.parse_outer_attributes();
2963 let pats = self.parse_pats();
2964 let mut guard = None;
2965 if self.eat_keyword(keywords::If) {
2966 guard = Some(self.parse_expr());
2968 self.expect(&token::FAT_ARROW);
2969 let expr = self.parse_expr_res(RestrictionStmtExpr);
2972 !classify::expr_is_simple_block(&*expr)
2973 && self.token != token::RBRACE;
2976 self.commit_expr(&*expr, &[token::COMMA], &[token::RBRACE]);
2978 self.eat(&token::COMMA);
2989 /// Parse an expression
2990 pub fn parse_expr(&mut self) -> P<Expr> {
2991 return self.parse_expr_res(Unrestricted);
2994 /// Parse an expression, subject to the given restrictions
2995 pub fn parse_expr_res(&mut self, r: Restrictions) -> P<Expr> {
2996 let old = self.restrictions;
2997 self.restrictions = r;
2998 let e = self.parse_assign_expr();
2999 self.restrictions = old;
3003 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3004 fn parse_initializer(&mut self) -> Option<P<Expr>> {
3005 if self.token == token::EQ {
3007 Some(self.parse_expr())
3013 /// Parse patterns, separated by '|' s
3014 fn parse_pats(&mut self) -> Vec<P<Pat>> {
3015 let mut pats = Vec::new();
3017 pats.push(self.parse_pat());
3018 if self.token == token::BINOP(token::OR) { self.bump(); }
3019 else { return pats; }
3023 fn parse_pat_vec_elements(
3025 ) -> (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>) {
3026 let mut before = Vec::new();
3027 let mut slice = None;
3028 let mut after = Vec::new();
3029 let mut first = true;
3030 let mut before_slice = true;
3032 while self.token != token::RBRACKET {
3036 self.expect(&token::COMMA);
3040 if self.token == token::DOTDOT {
3043 if self.token == token::COMMA ||
3044 self.token == token::RBRACKET {
3045 slice = Some(P(ast::Pat {
3046 id: ast::DUMMY_NODE_ID,
3047 node: PatWild(PatWildMulti),
3050 before_slice = false;
3052 let _ = self.parse_pat();
3053 let span = self.span;
3054 self.obsolete(span, ObsoleteSubsliceMatch);
3060 let subpat = self.parse_pat();
3061 if before_slice && self.token == token::DOTDOT {
3063 slice = Some(subpat);
3064 before_slice = false;
3065 } else if before_slice {
3066 before.push(subpat);
3072 (before, slice, after)
3075 /// Parse the fields of a struct-like pattern
3076 fn parse_pat_fields(&mut self) -> (Vec<ast::FieldPat> , bool) {
3077 let mut fields = Vec::new();
3078 let mut etc = false;
3079 let mut first = true;
3080 while self.token != token::RBRACE {
3084 self.expect(&token::COMMA);
3085 // accept trailing commas
3086 if self.token == token::RBRACE { break }
3089 if self.token == token::DOTDOT {
3091 if self.token != token::RBRACE {
3092 let token_str = self.this_token_to_string();
3093 self.fatal(format!("expected `{}`, found `{}`", "}",
3094 token_str).as_slice())
3100 let bind_type = if self.eat_keyword(keywords::Mut) {
3101 BindByValue(MutMutable)
3102 } else if self.eat_keyword(keywords::Ref) {
3103 BindByRef(self.parse_mutability())
3105 BindByValue(MutImmutable)
3108 let fieldname = self.parse_ident();
3110 let subpat = if self.token == token::COLON {
3112 BindByRef(..) | BindByValue(MutMutable) => {
3113 let token_str = self.this_token_to_string();
3114 self.fatal(format!("unexpected `{}`",
3115 token_str).as_slice())
3123 let fieldpath = codemap::Spanned{span:self.last_span, node: fieldname};
3125 id: ast::DUMMY_NODE_ID,
3126 node: PatIdent(bind_type, fieldpath, None),
3127 span: self.last_span
3130 fields.push(ast::FieldPat { ident: fieldname, pat: subpat });
3132 return (fields, etc);
3135 /// Parse a pattern.
3136 pub fn parse_pat(&mut self) -> P<Pat> {
3137 maybe_whole!(self, NtPat);
3139 let lo = self.span.lo;
3144 token::UNDERSCORE => {
3146 pat = PatWild(PatWildSingle);
3147 hi = self.last_span.hi;
3149 id: ast::DUMMY_NODE_ID,
3157 let sub = self.parse_pat();
3159 let last_span = self.last_span;
3161 self.obsolete(last_span, ObsoleteOwnedPattern);
3163 id: ast::DUMMY_NODE_ID,
3168 token::BINOP(token::AND) | token::ANDAND => {
3170 let lo = self.span.lo;
3172 let sub = self.parse_pat();
3173 pat = PatRegion(sub);
3174 hi = self.last_span.hi;
3176 id: ast::DUMMY_NODE_ID,
3182 // parse (pat,pat,pat,...) as tuple
3184 if self.token == token::RPAREN {
3187 let lit = P(codemap::Spanned {
3189 span: mk_sp(lo, hi)});
3190 let expr = self.mk_expr(lo, hi, ExprLit(lit));
3193 let mut fields = vec!(self.parse_pat());
3194 if self.look_ahead(1, |t| *t != token::RPAREN) {
3195 while self.token == token::COMMA {
3197 if self.token == token::RPAREN { break; }
3198 fields.push(self.parse_pat());
3201 if fields.len() == 1 { self.expect(&token::COMMA); }
3202 self.expect(&token::RPAREN);
3203 pat = PatTup(fields);
3205 hi = self.last_span.hi;
3207 id: ast::DUMMY_NODE_ID,
3212 token::LBRACKET => {
3213 // parse [pat,pat,...] as vector pattern
3215 let (before, slice, after) =
3216 self.parse_pat_vec_elements();
3218 self.expect(&token::RBRACKET);
3219 pat = ast::PatVec(before, slice, after);
3220 hi = self.last_span.hi;
3222 id: ast::DUMMY_NODE_ID,
3229 // at this point, token != _, ~, &, &&, (, [
3231 if (!is_ident_or_path(&self.token) && self.token != token::MOD_SEP)
3232 || self.is_keyword(keywords::True)
3233 || self.is_keyword(keywords::False) {
3234 // Parse an expression pattern or exp .. exp.
3236 // These expressions are limited to literals (possibly
3237 // preceded by unary-minus) or identifiers.
3238 let val = self.parse_literal_maybe_minus();
3239 // FIXME(#17295) remove the DOTDOT option.
3240 if (self.token == token::DOTDOTDOT || self.token == token::DOTDOT) &&
3241 self.look_ahead(1, |t| {
3242 *t != token::COMMA && *t != token::RBRACKET
3245 let end = if is_ident_or_path(&self.token) {
3246 let path = self.parse_path(LifetimeAndTypesWithColons)
3248 let hi = self.span.hi;
3249 self.mk_expr(lo, hi, ExprPath(path))
3251 self.parse_literal_maybe_minus()
3253 pat = PatRange(val, end);
3257 } else if self.eat_keyword(keywords::Mut) {
3258 pat = self.parse_pat_ident(BindByValue(MutMutable));
3259 } else if self.eat_keyword(keywords::Ref) {
3261 let mutbl = self.parse_mutability();
3262 pat = self.parse_pat_ident(BindByRef(mutbl));
3263 } else if self.eat_keyword(keywords::Box) {
3266 // FIXME(#13910): Rename to `PatBox` and extend to full DST
3268 let sub = self.parse_pat();
3270 hi = self.last_span.hi;
3272 id: ast::DUMMY_NODE_ID,
3277 let can_be_enum_or_struct = self.look_ahead(1, |t| {
3279 token::LPAREN | token::LBRACKET | token::LT |
3280 token::LBRACE | token::MOD_SEP => true,
3285 // FIXME(#17295) remove the DOTDOT option.
3286 if self.look_ahead(1, |t| *t == token::DOTDOTDOT || *t == token::DOTDOT) &&
3287 self.look_ahead(2, |t| {
3288 *t != token::COMMA && *t != token::RBRACKET
3290 let start = self.parse_expr_res(RestrictionNoBarOp);
3291 // FIXME(#17295) remove the DOTDOT option (self.eat(&token::DOTDOTDOT)).
3292 if self.token == token::DOTDOTDOT || self.token == token::DOTDOT {
3295 let end = self.parse_expr_res(RestrictionNoBarOp);
3296 pat = PatRange(start, end);
3297 } else if is_plain_ident(&self.token) && !can_be_enum_or_struct {
3298 let id = self.parse_ident();
3299 let id_span = self.last_span;
3300 let pth1 = codemap::Spanned{span:id_span, node: id};
3301 if self.eat(&token::NOT) {
3303 let ket = token::close_delimiter_for(&self.token)
3304 .unwrap_or_else(|| self.fatal("expected open delimiter"));
3307 let tts = self.parse_seq_to_end(&ket,
3309 |p| p.parse_token_tree());
3311 let mac = MacInvocTT(ident_to_path(id_span,id), tts, EMPTY_CTXT);
3312 pat = ast::PatMac(codemap::Spanned {node: mac, span: self.span});
3314 let sub = if self.eat(&token::AT) {
3316 Some(self.parse_pat())
3321 pat = PatIdent(BindByValue(MutImmutable), pth1, sub);
3324 // parse an enum pat
3325 let enum_path = self.parse_path(LifetimeAndTypesWithColons)
3331 self.parse_pat_fields();
3333 pat = PatStruct(enum_path, fields, etc);
3336 let mut args: Vec<P<Pat>> = Vec::new();
3339 let is_dotdot = self.look_ahead(1, |t| {
3341 token::DOTDOT => true,
3346 // This is a "top constructor only" pat
3349 self.expect(&token::RPAREN);
3350 pat = PatEnum(enum_path, None);
3352 args = self.parse_enum_variant_seq(
3355 seq_sep_trailing_allowed(token::COMMA),
3358 pat = PatEnum(enum_path, Some(args));
3362 if !enum_path.global &&
3363 enum_path.segments.len() == 1 &&
3372 // it could still be either an enum
3373 // or an identifier pattern, resolve
3374 // will sort it out:
3375 pat = PatIdent(BindByValue(MutImmutable),
3377 span: enum_path.span,
3378 node: enum_path.segments.get(0)
3382 pat = PatEnum(enum_path, Some(args));
3390 hi = self.last_span.hi;
3392 id: ast::DUMMY_NODE_ID,
3394 span: mk_sp(lo, hi),
3398 /// Parse ident or ident @ pat
3399 /// used by the copy foo and ref foo patterns to give a good
3400 /// error message when parsing mistakes like ref foo(a,b)
3401 fn parse_pat_ident(&mut self,
3402 binding_mode: ast::BindingMode)
3404 if !is_plain_ident(&self.token) {
3405 let last_span = self.last_span;
3406 self.span_fatal(last_span,
3407 "expected identifier, found path");
3409 let ident = self.parse_ident();
3410 let last_span = self.last_span;
3411 let name = codemap::Spanned{span: last_span, node: ident};
3412 let sub = if self.eat(&token::AT) {
3413 Some(self.parse_pat())
3418 // just to be friendly, if they write something like
3420 // we end up here with ( as the current token. This shortly
3421 // leads to a parse error. Note that if there is no explicit
3422 // binding mode then we do not end up here, because the lookahead
3423 // will direct us over to parse_enum_variant()
3424 if self.token == token::LPAREN {
3425 let last_span = self.last_span;
3428 "expected identifier, found enum pattern");
3431 PatIdent(binding_mode, name, sub)
3434 /// Parse a local variable declaration
3435 fn parse_local(&mut self) -> P<Local> {
3436 let lo = self.span.lo;
3437 let pat = self.parse_pat();
3440 id: ast::DUMMY_NODE_ID,
3442 span: mk_sp(lo, lo),
3444 if self.eat(&token::COLON) {
3445 ty = self.parse_ty(true);
3447 let init = self.parse_initializer();
3452 id: ast::DUMMY_NODE_ID,
3453 span: mk_sp(lo, self.last_span.hi),
3458 /// Parse a "let" stmt
3459 fn parse_let(&mut self) -> P<Decl> {
3460 let lo = self.span.lo;
3461 let local = self.parse_local();
3462 P(spanned(lo, self.last_span.hi, DeclLocal(local)))
3465 /// Parse a structure field
3466 fn parse_name_and_ty(&mut self, pr: Visibility,
3467 attrs: Vec<Attribute> ) -> StructField {
3468 let lo = self.span.lo;
3469 if !is_plain_ident(&self.token) {
3470 self.fatal("expected ident");
3472 let name = self.parse_ident();
3473 self.expect(&token::COLON);
3474 let ty = self.parse_ty(true);
3475 spanned(lo, self.last_span.hi, ast::StructField_ {
3476 kind: NamedField(name, pr),
3477 id: ast::DUMMY_NODE_ID,
3483 /// Parse a statement. may include decl.
3484 /// Precondition: any attributes are parsed already
3485 pub fn parse_stmt(&mut self, item_attrs: Vec<Attribute>) -> P<Stmt> {
3486 maybe_whole!(self, NtStmt);
3488 fn check_expected_item(p: &mut Parser, found_attrs: bool) {
3489 // If we have attributes then we should have an item
3491 let last_span = p.last_span;
3492 p.span_err(last_span, "expected item after attributes");
3496 let lo = self.span.lo;
3497 if self.is_keyword(keywords::Let) {
3498 check_expected_item(self, !item_attrs.is_empty());
3499 self.expect_keyword(keywords::Let);
3500 let decl = self.parse_let();
3501 P(spanned(lo, decl.span.hi, StmtDecl(decl, ast::DUMMY_NODE_ID)))
3502 } else if is_ident(&self.token)
3503 && !token::is_any_keyword(&self.token)
3504 && self.look_ahead(1, |t| *t == token::NOT) {
3505 // it's a macro invocation:
3507 check_expected_item(self, !item_attrs.is_empty());
3509 // Potential trouble: if we allow macros with paths instead of
3510 // idents, we'd need to look ahead past the whole path here...
3511 let pth = self.parse_path(NoTypesAllowed).path;
3514 let id = if token::close_delimiter_for(&self.token).is_some() {
3515 token::special_idents::invalid // no special identifier
3520 // check that we're pointing at delimiters (need to check
3521 // again after the `if`, because of `parse_ident`
3522 // consuming more tokens).
3523 let (bra, ket) = match token::close_delimiter_for(&self.token) {
3524 Some(ket) => (self.token.clone(), ket),
3526 // we only expect an ident if we didn't parse one
3528 let ident_str = if id.name == token::special_idents::invalid.name {
3533 let tok_str = self.this_token_to_string();
3534 self.fatal(format!("expected {}`(` or `{{`, found `{}`",
3536 tok_str).as_slice())
3540 let tts = self.parse_unspanned_seq(
3544 |p| p.parse_token_tree()
3546 let hi = self.span.hi;
3548 if id.name == token::special_idents::invalid.name {
3549 P(spanned(lo, hi, StmtMac(
3550 spanned(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT)), false)))
3552 // if it has a special ident, it's definitely an item
3553 P(spanned(lo, hi, StmtDecl(
3554 P(spanned(lo, hi, DeclItem(
3556 lo, hi, id /*id is good here*/,
3557 ItemMac(spanned(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT))),
3558 Inherited, Vec::new(/*no attrs*/))))),
3559 ast::DUMMY_NODE_ID)))
3563 let found_attrs = !item_attrs.is_empty();
3564 match self.parse_item_or_view_item(item_attrs, false) {
3567 let decl = P(spanned(lo, hi, DeclItem(i)));
3568 P(spanned(lo, hi, StmtDecl(decl, ast::DUMMY_NODE_ID)))
3570 IoviViewItem(vi) => {
3571 self.span_fatal(vi.span,
3572 "view items must be declared at the top of the block");
3574 IoviForeignItem(_) => {
3575 self.fatal("foreign items are not allowed here");
3578 check_expected_item(self, found_attrs);
3580 // Remainder are line-expr stmts.
3581 let e = self.parse_expr_res(RestrictionStmtExpr);
3582 P(spanned(lo, e.span.hi, StmtExpr(e, ast::DUMMY_NODE_ID)))
3588 /// Is this expression a successfully-parsed statement?
3589 fn expr_is_complete(&mut self, e: &Expr) -> bool {
3590 self.restrictions.contains(RestrictionStmtExpr) &&
3591 !classify::expr_requires_semi_to_be_stmt(e)
3594 /// Parse a block. No inner attrs are allowed.
3595 pub fn parse_block(&mut self) -> P<Block> {
3596 maybe_whole!(no_clone self, NtBlock);
3598 let lo = self.span.lo;
3599 self.expect(&token::LBRACE);
3601 return self.parse_block_tail_(lo, DefaultBlock, Vec::new());
3604 /// Parse a block. Inner attrs are allowed.
3605 fn parse_inner_attrs_and_block(&mut self)
3606 -> (Vec<Attribute> , P<Block>) {
3608 maybe_whole!(pair_empty self, NtBlock);
3610 let lo = self.span.lo;
3611 self.expect(&token::LBRACE);
3612 let (inner, next) = self.parse_inner_attrs_and_next();
3614 (inner, self.parse_block_tail_(lo, DefaultBlock, next))
3617 /// Precondition: already parsed the '{' or '#{'
3618 /// I guess that also means "already parsed the 'impure'" if
3619 /// necessary, and this should take a qualifier.
3620 /// Some blocks start with "#{"...
3621 fn parse_block_tail(&mut self, lo: BytePos, s: BlockCheckMode) -> P<Block> {
3622 self.parse_block_tail_(lo, s, Vec::new())
3625 /// Parse the rest of a block expression or function body
3626 fn parse_block_tail_(&mut self, lo: BytePos, s: BlockCheckMode,
3627 first_item_attrs: Vec<Attribute> ) -> P<Block> {
3628 let mut stmts = Vec::new();
3629 let mut expr = None;
3631 // wouldn't it be more uniform to parse view items only, here?
3632 let ParsedItemsAndViewItems {
3633 attrs_remaining: attrs_remaining,
3634 view_items: view_items,
3637 } = self.parse_items_and_view_items(first_item_attrs,
3640 for item in items.into_iter() {
3641 let span = item.span;
3642 let decl = P(spanned(span.lo, span.hi, DeclItem(item)));
3643 stmts.push(P(spanned(span.lo, span.hi, StmtDecl(decl, ast::DUMMY_NODE_ID))));
3646 let mut attributes_box = attrs_remaining;
3648 while self.token != token::RBRACE {
3649 // parsing items even when they're not allowed lets us give
3650 // better error messages and recover more gracefully.
3651 attributes_box.push_all(self.parse_outer_attributes().as_slice());
3654 if !attributes_box.is_empty() {
3655 let last_span = self.last_span;
3656 self.span_err(last_span, "expected item after attributes");
3657 attributes_box = Vec::new();
3659 self.bump(); // empty
3662 // fall through and out.
3665 let stmt = self.parse_stmt(attributes_box);
3666 attributes_box = Vec::new();
3667 stmt.and_then(|Spanned {node, span}| match node {
3668 StmtExpr(e, stmt_id) => {
3669 // expression without semicolon
3670 if classify::expr_requires_semi_to_be_stmt(&*e) {
3671 // Just check for errors and recover; do not eat semicolon yet.
3672 self.commit_stmt(&[], &[token::SEMI, token::RBRACE]);
3678 let span_with_semi = Span {
3680 hi: self.last_span.hi,
3681 expn_id: span.expn_id,
3683 stmts.push(P(Spanned {
3684 node: StmtSemi(e, stmt_id),
3685 span: span_with_semi,
3692 stmts.push(P(Spanned {
3693 node: StmtExpr(e, stmt_id),
3699 StmtMac(m, semi) => {
3700 // statement macro; might be an expr
3703 stmts.push(P(Spanned {
3704 node: StmtMac(m, true),
3710 // if a block ends in `m!(arg)` without
3711 // a `;`, it must be an expr
3713 self.mk_mac_expr(span.lo,
3718 stmts.push(P(Spanned {
3719 node: StmtMac(m, semi),
3725 _ => { // all other kinds of statements:
3726 if classify::stmt_ends_with_semi(&node) {
3727 self.commit_stmt_expecting(token::SEMI);
3730 stmts.push(P(Spanned {
3740 if !attributes_box.is_empty() {
3741 let last_span = self.last_span;
3742 self.span_err(last_span, "expected item after attributes");
3745 let hi = self.span.hi;
3748 view_items: view_items,
3751 id: ast::DUMMY_NODE_ID,
3753 span: mk_sp(lo, hi),
3757 // Parses a sequence of bounds if a `:` is found,
3758 // otherwise returns empty list.
3759 fn parse_colon_then_ty_param_bounds(&mut self)
3760 -> OwnedSlice<TyParamBound>
3762 if !self.eat(&token::COLON) {
3765 self.parse_ty_param_bounds()
3769 // matches bounds = ( boundseq )?
3770 // where boundseq = ( bound + boundseq ) | bound
3771 // and bound = 'region | ty
3772 // NB: The None/Some distinction is important for issue #7264.
3773 fn parse_ty_param_bounds(&mut self)
3774 -> OwnedSlice<TyParamBound>
3776 let mut result = vec!();
3779 token::LIFETIME(lifetime) => {
3780 result.push(RegionTyParamBound(ast::Lifetime {
3781 id: ast::DUMMY_NODE_ID,
3787 token::MOD_SEP | token::IDENT(..) => {
3789 self.parse_path(LifetimeAndTypesWithoutColons).path;
3790 if self.token == token::LPAREN {
3792 let inputs = self.parse_seq_to_end(
3794 seq_sep_trailing_allowed(token::COMMA),
3795 |p| p.parse_arg_general(false));
3796 let (return_style, output) = self.parse_ret_ty();
3797 result.push(UnboxedFnTyParamBound(P(UnboxedFnBound {
3805 ref_id: ast::DUMMY_NODE_ID,
3808 result.push(TraitTyParamBound(ast::TraitRef {
3810 ref_id: ast::DUMMY_NODE_ID,
3817 if !self.eat(&token::BINOP(token::PLUS)) {
3822 return OwnedSlice::from_vec(result);
3825 fn trait_ref_from_ident(ident: Ident, span: Span) -> ast::TraitRef {
3826 let segment = ast::PathSegment {
3828 lifetimes: Vec::new(),
3829 types: OwnedSlice::empty(),
3831 let path = ast::Path {
3834 segments: vec![segment],
3838 ref_id: ast::DUMMY_NODE_ID,
3842 /// Matches typaram = (unbound`?`)? IDENT optbounds ( EQ ty )?
3843 fn parse_ty_param(&mut self) -> TyParam {
3844 // This is a bit hacky. Currently we are only interested in a single
3845 // unbound, and it may only be `Sized`. To avoid backtracking and other
3846 // complications, we parse an ident, then check for `?`. If we find it,
3847 // we use the ident as the unbound, otherwise, we use it as the name of
3849 let mut span = self.span;
3850 let mut ident = self.parse_ident();
3851 let mut unbound = None;
3852 if self.eat(&token::QUESTION) {
3853 let tref = Parser::trait_ref_from_ident(ident, span);
3854 unbound = Some(TraitTyParamBound(tref));
3856 ident = self.parse_ident();
3859 let bounds = self.parse_colon_then_ty_param_bounds();
3861 let default = if self.token == token::EQ {
3863 Some(self.parse_ty(true))
3869 id: ast::DUMMY_NODE_ID,
3877 /// Parse a set of optional generic type parameter declarations. Where
3878 /// clauses are not parsed here, and must be added later via
3879 /// `parse_where_clause()`.
3881 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
3882 /// | ( < lifetimes , typaramseq ( , )? > )
3883 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
3884 pub fn parse_generics(&mut self) -> ast::Generics {
3885 if self.eat(&token::LT) {
3886 let lifetime_defs = self.parse_lifetime_defs();
3887 let mut seen_default = false;
3888 let ty_params = self.parse_seq_to_gt(Some(token::COMMA), |p| {
3889 p.forbid_lifetime();
3890 let ty_param = p.parse_ty_param();
3891 if ty_param.default.is_some() {
3892 seen_default = true;
3893 } else if seen_default {
3894 let last_span = p.last_span;
3895 p.span_err(last_span,
3896 "type parameters with a default must be trailing");
3901 lifetimes: lifetime_defs,
3902 ty_params: ty_params,
3903 where_clause: WhereClause {
3904 id: ast::DUMMY_NODE_ID,
3905 predicates: Vec::new(),
3909 ast_util::empty_generics()
3913 fn parse_generic_values_after_lt(&mut self) -> (Vec<ast::Lifetime>, Vec<P<Ty>> ) {
3914 let lifetimes = self.parse_lifetimes(token::COMMA);
3915 let result = self.parse_seq_to_gt(
3918 p.forbid_lifetime();
3922 (lifetimes, result.into_vec())
3925 fn forbid_lifetime(&mut self) {
3926 if Parser::token_is_lifetime(&self.token) {
3927 let span = self.span;
3928 self.span_fatal(span, "lifetime parameters must be declared \
3929 prior to type parameters");
3933 /// Parses an optional `where` clause and places it in `generics`.
3934 fn parse_where_clause(&mut self, generics: &mut ast::Generics) {
3935 if !self.eat_keyword(keywords::Where) {
3939 let mut parsed_something = false;
3941 let lo = self.span.lo;
3942 let ident = match self.token {
3943 token::IDENT(..) => self.parse_ident(),
3946 self.expect(&token::COLON);
3948 let bounds = self.parse_ty_param_bounds();
3949 let hi = self.span.hi;
3950 let span = mk_sp(lo, hi);
3952 if bounds.len() == 0 {
3954 "each predicate in a `where` clause must have \
3955 at least one bound in it");
3958 generics.where_clause.predicates.push(ast::WherePredicate {
3959 id: ast::DUMMY_NODE_ID,
3964 parsed_something = true;
3966 if !self.eat(&token::COMMA) {
3971 if !parsed_something {
3972 let last_span = self.last_span;
3973 self.span_err(last_span,
3974 "a `where` clause must have at least one predicate \
3979 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
3980 -> (Vec<Arg> , bool) {
3982 let mut args: Vec<Option<Arg>> =
3983 self.parse_unspanned_seq(
3986 seq_sep_trailing_allowed(token::COMMA),
3988 if p.token == token::DOTDOTDOT {
3991 if p.token != token::RPAREN {
3994 "`...` must be last in argument list for variadic function");
3999 "only foreign functions are allowed to be variadic");
4003 Some(p.parse_arg_general(named_args))
4008 let variadic = match args.pop() {
4011 // Need to put back that last arg
4018 if variadic && args.is_empty() {
4020 "variadic function must be declared with at least one named argument");
4023 let args = args.into_iter().map(|x| x.unwrap()).collect();
4028 /// Parse the argument list and result type of a function declaration
4029 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> P<FnDecl> {
4031 let (args, variadic) = self.parse_fn_args(true, allow_variadic);
4032 let (ret_style, ret_ty) = self.parse_ret_ty();
4042 fn is_self_ident(&mut self) -> bool {
4044 token::IDENT(id, false) => id.name == special_idents::self_.name,
4049 fn expect_self_ident(&mut self) -> ast::Ident {
4051 token::IDENT(id, false) if id.name == special_idents::self_.name => {
4056 let token_str = self.this_token_to_string();
4057 self.fatal(format!("expected `self`, found `{}`",
4058 token_str).as_slice())
4063 /// Parse the argument list and result type of a function
4064 /// that may have a self type.
4065 fn parse_fn_decl_with_self(&mut self, parse_arg_fn: |&mut Parser| -> Arg)
4066 -> (ExplicitSelf, P<FnDecl>) {
4067 fn maybe_parse_borrowed_explicit_self(this: &mut Parser)
4068 -> ast::ExplicitSelf_ {
4069 // The following things are possible to see here:
4074 // fn(&'lt mut self)
4076 // We already know that the current token is `&`.
4078 if this.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) {
4080 SelfRegion(None, MutImmutable, this.expect_self_ident())
4081 } else if this.look_ahead(1, |t| Parser::token_is_mutability(t)) &&
4083 |t| token::is_keyword(keywords::Self,
4086 let mutability = this.parse_mutability();
4087 SelfRegion(None, mutability, this.expect_self_ident())
4088 } else if this.look_ahead(1, |t| Parser::token_is_lifetime(t)) &&
4090 |t| token::is_keyword(keywords::Self,
4093 let lifetime = this.parse_lifetime();
4094 SelfRegion(Some(lifetime), MutImmutable, this.expect_self_ident())
4095 } else if this.look_ahead(1, |t| Parser::token_is_lifetime(t)) &&
4096 this.look_ahead(2, |t| {
4097 Parser::token_is_mutability(t)
4099 this.look_ahead(3, |t| token::is_keyword(keywords::Self,
4102 let lifetime = this.parse_lifetime();
4103 let mutability = this.parse_mutability();
4104 SelfRegion(Some(lifetime), mutability, this.expect_self_ident())
4110 self.expect(&token::LPAREN);
4112 // A bit of complexity and lookahead is needed here in order to be
4113 // backwards compatible.
4114 let lo = self.span.lo;
4115 let mut mutbl_self = MutImmutable;
4116 let explicit_self = match self.token {
4117 token::BINOP(token::AND) => {
4118 maybe_parse_borrowed_explicit_self(self)
4121 // We need to make sure it isn't a type
4122 if self.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) {
4124 drop(self.expect_self_ident());
4125 let last_span = self.last_span;
4126 self.obsolete(last_span, ObsoleteOwnedSelf)
4130 token::BINOP(token::STAR) => {
4131 // Possibly "*self" or "*mut self" -- not supported. Try to avoid
4132 // emitting cryptic "unexpected token" errors.
4134 let _mutability = if Parser::token_is_mutability(&self.token) {
4135 self.parse_mutability()
4139 if self.is_self_ident() {
4140 let span = self.span;
4141 self.span_err(span, "cannot pass self by unsafe pointer");
4144 // error case, making bogus self ident:
4145 SelfValue(special_idents::self_)
4147 token::IDENT(..) => {
4148 if self.is_self_ident() {
4149 let self_ident = self.expect_self_ident();
4151 // Determine whether this is the fully explicit form, `self:
4153 if self.eat(&token::COLON) {
4154 SelfExplicit(self.parse_ty(false), self_ident)
4156 SelfValue(self_ident)
4158 } else if Parser::token_is_mutability(&self.token) &&
4159 self.look_ahead(1, |t| {
4160 token::is_keyword(keywords::Self, t)
4162 mutbl_self = self.parse_mutability();
4163 let self_ident = self.expect_self_ident();
4165 // Determine whether this is the fully explicit form,
4167 if self.eat(&token::COLON) {
4168 SelfExplicit(self.parse_ty(false), self_ident)
4170 SelfValue(self_ident)
4172 } else if Parser::token_is_mutability(&self.token) &&
4173 self.look_ahead(1, |t| *t == token::TILDE) &&
4174 self.look_ahead(2, |t| {
4175 token::is_keyword(keywords::Self, t)
4177 mutbl_self = self.parse_mutability();
4179 drop(self.expect_self_ident());
4180 let last_span = self.last_span;
4181 self.obsolete(last_span, ObsoleteOwnedSelf);
4190 let explicit_self_sp = mk_sp(lo, self.span.hi);
4192 // shared fall-through for the three cases below. borrowing prevents simply
4193 // writing this as a closure
4194 macro_rules! parse_remaining_arguments {
4197 // If we parsed a self type, expect a comma before the argument list.
4201 let sep = seq_sep_trailing_allowed(token::COMMA);
4202 let mut fn_inputs = self.parse_seq_to_before_end(
4207 fn_inputs.unshift(Arg::new_self(explicit_self_sp, mutbl_self, $self_id));
4211 vec!(Arg::new_self(explicit_self_sp, mutbl_self, $self_id))
4214 let token_str = self.this_token_to_string();
4215 self.fatal(format!("expected `,` or `)`, found `{}`",
4216 token_str).as_slice())
4222 let fn_inputs = match explicit_self {
4224 let sep = seq_sep_trailing_allowed(token::COMMA);
4225 self.parse_seq_to_before_end(&token::RPAREN, sep, parse_arg_fn)
4227 SelfValue(id) => parse_remaining_arguments!(id),
4228 SelfRegion(_,_,id) => parse_remaining_arguments!(id),
4229 SelfExplicit(_,id) => parse_remaining_arguments!(id),
4233 self.expect(&token::RPAREN);
4235 let hi = self.span.hi;
4237 let (ret_style, ret_ty) = self.parse_ret_ty();
4239 let fn_decl = P(FnDecl {
4246 (spanned(lo, hi, explicit_self), fn_decl)
4249 // parse the |arg, arg| header on a lambda
4250 fn parse_fn_block_decl(&mut self)
4251 -> (P<FnDecl>, Option<UnboxedClosureKind>) {
4252 let (optional_unboxed_closure_kind, inputs_captures) = {
4253 if self.eat(&token::OROR) {
4256 self.expect(&token::BINOP(token::OR));
4257 let optional_unboxed_closure_kind =
4258 self.parse_optional_unboxed_closure_kind();
4259 let args = self.parse_seq_to_before_end(
4260 &token::BINOP(token::OR),
4261 seq_sep_trailing_allowed(token::COMMA),
4262 |p| p.parse_fn_block_arg()
4265 (optional_unboxed_closure_kind, args)
4268 let (style, output) = if self.token == token::RARROW {
4272 id: ast::DUMMY_NODE_ID,
4279 inputs: inputs_captures,
4283 }), optional_unboxed_closure_kind)
4286 /// Parses the `(arg, arg) -> return_type` header on a procedure.
4287 fn parse_proc_decl(&mut self) -> P<FnDecl> {
4289 self.parse_unspanned_seq(&token::LPAREN,
4291 seq_sep_trailing_allowed(token::COMMA),
4292 |p| p.parse_fn_block_arg());
4294 let (style, output) = if self.token == token::RARROW {
4298 id: ast::DUMMY_NODE_ID,
4312 /// Parse the name and optional generic types of a function header.
4313 fn parse_fn_header(&mut self) -> (Ident, ast::Generics) {
4314 let id = self.parse_ident();
4315 let generics = self.parse_generics();
4319 fn mk_item(&mut self, lo: BytePos, hi: BytePos, ident: Ident,
4320 node: Item_, vis: Visibility,
4321 attrs: Vec<Attribute>) -> P<Item> {
4325 id: ast::DUMMY_NODE_ID,
4332 /// Parse an item-position function declaration.
4333 fn parse_item_fn(&mut self, fn_style: FnStyle, abi: abi::Abi) -> ItemInfo {
4334 let (ident, mut generics) = self.parse_fn_header();
4335 let decl = self.parse_fn_decl(false);
4336 self.parse_where_clause(&mut generics);
4337 let (inner_attrs, body) = self.parse_inner_attrs_and_block();
4338 (ident, ItemFn(decl, fn_style, abi, generics, body), Some(inner_attrs))
4341 /// Parse a method in a trait impl, starting with `attrs` attributes.
4342 pub fn parse_method(&mut self,
4343 attrs: Vec<Attribute>,
4346 let lo = self.span.lo;
4348 // code copied from parse_macro_use_or_failure... abstraction!
4349 let (method_, hi, new_attrs) = {
4350 if !token::is_any_keyword(&self.token)
4351 && self.look_ahead(1, |t| *t == token::NOT)
4352 && (self.look_ahead(2, |t| *t == token::LPAREN)
4353 || self.look_ahead(2, |t| *t == token::LBRACE)) {
4355 let pth = self.parse_path(NoTypesAllowed).path;
4356 self.expect(&token::NOT);
4358 // eat a matched-delimiter token tree:
4359 let tts = match token::close_delimiter_for(&self.token) {
4362 self.parse_seq_to_end(&ket,
4364 |p| p.parse_token_tree())
4366 None => self.fatal("expected open delimiter")
4368 let m_ = ast::MacInvocTT(pth, tts, EMPTY_CTXT);
4369 let m: ast::Mac = codemap::Spanned { node: m_,
4370 span: mk_sp(self.span.lo,
4372 (ast::MethMac(m), self.span.hi, attrs)
4374 let abi = if self.eat_keyword(keywords::Extern) {
4375 self.parse_opt_abi().unwrap_or(abi::C)
4376 } else if attr::contains_name(attrs.as_slice(),
4377 "rust_call_abi_hack") {
4378 // FIXME(stage0, pcwalton): Remove this awful hack after a
4379 // snapshot, and change to `extern "rust-call" fn`.
4384 let fn_style = self.parse_fn_style();
4385 let ident = self.parse_ident();
4386 let mut generics = self.parse_generics();
4387 let (explicit_self, decl) = self.parse_fn_decl_with_self(|p| {
4390 self.parse_where_clause(&mut generics);
4391 let (inner_attrs, body) = self.parse_inner_attrs_and_block();
4392 let body_span = body.span;
4393 let new_attrs = attrs.append(inner_attrs.as_slice());
4394 (ast::MethDecl(ident,
4402 body_span.hi, new_attrs)
4407 id: ast::DUMMY_NODE_ID,
4408 span: mk_sp(lo, hi),
4413 /// Parse trait Foo { ... }
4414 fn parse_item_trait(&mut self) -> ItemInfo {
4415 let ident = self.parse_ident();
4416 let mut tps = self.parse_generics();
4417 let sized = self.parse_for_sized();
4419 // Parse supertrait bounds.
4420 let bounds = self.parse_colon_then_ty_param_bounds();
4422 self.parse_where_clause(&mut tps);
4424 let meths = self.parse_trait_items();
4425 (ident, ItemTrait(tps, sized, bounds, meths), None)
4428 fn parse_impl_items(&mut self) -> (Vec<ImplItem>, Vec<Attribute>) {
4429 let mut impl_items = Vec::new();
4430 self.expect(&token::LBRACE);
4431 let (inner_attrs, mut method_attrs) =
4432 self.parse_inner_attrs_and_next();
4433 while !self.eat(&token::RBRACE) {
4434 method_attrs.push_all_move(self.parse_outer_attributes());
4435 let vis = self.parse_visibility();
4436 if self.eat_keyword(keywords::Type) {
4437 impl_items.push(TypeImplItem(P(self.parse_typedef(
4441 impl_items.push(MethodImplItem(self.parse_method(
4445 method_attrs = self.parse_outer_attributes();
4447 (impl_items, inner_attrs)
4450 /// Parses two variants (with the region/type params always optional):
4451 /// impl<T> Foo { ... }
4452 /// impl<T> ToString for ~[T] { ... }
4453 fn parse_item_impl(&mut self) -> ItemInfo {
4454 // First, parse type parameters if necessary.
4455 let mut generics = self.parse_generics();
4457 // Special case: if the next identifier that follows is '(', don't
4458 // allow this to be parsed as a trait.
4459 let could_be_trait = self.token != token::LPAREN;
4462 let mut ty = self.parse_ty(true);
4464 // Parse traits, if necessary.
4465 let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) {
4466 // New-style trait. Reinterpret the type as a trait.
4467 let opt_trait_ref = match ty.node {
4468 TyPath(ref path, None, node_id) => {
4469 Some(TraitRef { path: (*path).clone(),
4472 TyPath(_, Some(_), _) => {
4473 self.span_err(ty.span,
4474 "bounded traits are only valid in type position");
4478 self.span_err(ty.span, "not a trait");
4483 ty = self.parse_ty(true);
4489 self.parse_where_clause(&mut generics);
4490 let (impl_items, attrs) = self.parse_impl_items();
4492 let ident = ast_util::impl_pretty_name(&opt_trait, &*ty);
4495 ItemImpl(generics, opt_trait, ty, impl_items),
4499 /// Parse struct Foo { ... }
4500 fn parse_item_struct(&mut self, is_virtual: bool) -> ItemInfo {
4501 let class_name = self.parse_ident();
4502 let mut generics = self.parse_generics();
4504 let super_struct = if self.eat(&token::COLON) {
4505 let ty = self.parse_ty(true);
4507 TyPath(_, None, _) => {
4511 self.span_err(ty.span, "not a struct");
4519 self.parse_where_clause(&mut generics);
4521 let mut fields: Vec<StructField>;
4524 if self.eat(&token::LBRACE) {
4525 // It's a record-like struct.
4526 is_tuple_like = false;
4527 fields = Vec::new();
4528 while self.token != token::RBRACE {
4529 fields.push(self.parse_struct_decl_field());
4531 if fields.len() == 0 {
4532 self.fatal(format!("unit-like struct definition should be \
4533 written as `struct {};`",
4534 token::get_ident(class_name)).as_slice());
4537 } else if self.token == token::LPAREN {
4538 // It's a tuple-like struct.
4539 is_tuple_like = true;
4540 fields = self.parse_unspanned_seq(
4543 seq_sep_trailing_allowed(token::COMMA),
4545 let attrs = p.parse_outer_attributes();
4547 let struct_field_ = ast::StructField_ {
4548 kind: UnnamedField(p.parse_visibility()),
4549 id: ast::DUMMY_NODE_ID,
4550 ty: p.parse_ty(true),
4553 spanned(lo, p.span.hi, struct_field_)
4555 if fields.len() == 0 {
4556 self.fatal(format!("unit-like struct definition should be \
4557 written as `struct {};`",
4558 token::get_ident(class_name)).as_slice());
4560 self.expect(&token::SEMI);
4561 } else if self.eat(&token::SEMI) {
4562 // It's a unit-like struct.
4563 is_tuple_like = true;
4564 fields = Vec::new();
4566 let token_str = self.this_token_to_string();
4567 self.fatal(format!("expected `{}`, `(`, or `;` after struct \
4568 name, found `{}`", "{",
4569 token_str).as_slice())
4572 let _ = ast::DUMMY_NODE_ID; // FIXME: Workaround for crazy bug.
4573 let new_id = ast::DUMMY_NODE_ID;
4575 ItemStruct(P(ast::StructDef {
4577 ctor_id: if is_tuple_like { Some(new_id) } else { None },
4578 super_struct: super_struct,
4579 is_virtual: is_virtual,
4584 /// Parse a structure field declaration
4585 pub fn parse_single_struct_field(&mut self,
4587 attrs: Vec<Attribute> )
4589 let a_var = self.parse_name_and_ty(vis, attrs);
4596 let span = self.span;
4597 let token_str = self.this_token_to_string();
4598 self.span_fatal(span,
4599 format!("expected `,`, or `}}`, found `{}`",
4600 token_str).as_slice())
4606 /// Parse an element of a struct definition
4607 fn parse_struct_decl_field(&mut self) -> StructField {
4609 let attrs = self.parse_outer_attributes();
4611 if self.eat_keyword(keywords::Pub) {
4612 return self.parse_single_struct_field(Public, attrs);
4615 return self.parse_single_struct_field(Inherited, attrs);
4618 /// Parse visibility: PUB, PRIV, or nothing
4619 fn parse_visibility(&mut self) -> Visibility {
4620 if self.eat_keyword(keywords::Pub) { Public }
4624 fn parse_for_sized(&mut self) -> Option<ast::TyParamBound> {
4625 if self.eat_keyword(keywords::For) {
4626 let span = self.span;
4627 let ident = self.parse_ident();
4628 if !self.eat(&token::QUESTION) {
4630 "expected 'Sized?' after `for` in trait item");
4633 let tref = Parser::trait_ref_from_ident(ident, span);
4634 Some(TraitTyParamBound(tref))
4640 /// Given a termination token and a vector of already-parsed
4641 /// attributes (of length 0 or 1), parse all of the items in a module
4642 fn parse_mod_items(&mut self,
4644 first_item_attrs: Vec<Attribute>,
4647 // parse all of the items up to closing or an attribute.
4648 // view items are legal here.
4649 let ParsedItemsAndViewItems {
4650 attrs_remaining: attrs_remaining,
4651 view_items: view_items,
4652 items: starting_items,
4654 } = self.parse_items_and_view_items(first_item_attrs, true, true);
4655 let mut items: Vec<P<Item>> = starting_items;
4656 let attrs_remaining_len = attrs_remaining.len();
4658 // don't think this other loop is even necessary....
4660 let mut first = true;
4661 while self.token != term {
4662 let mut attrs = self.parse_outer_attributes();
4664 attrs = attrs_remaining.clone().append(attrs.as_slice());
4667 debug!("parse_mod_items: parse_item_or_view_item(attrs={:?})",
4669 match self.parse_item_or_view_item(attrs,
4670 true /* macros allowed */) {
4671 IoviItem(item) => items.push(item),
4672 IoviViewItem(view_item) => {
4673 self.span_fatal(view_item.span,
4674 "view items must be declared at the top of \
4678 let token_str = self.this_token_to_string();
4679 self.fatal(format!("expected item, found `{}`",
4680 token_str).as_slice())
4685 if first && attrs_remaining_len > 0u {
4686 // We parsed attributes for the first item but didn't find it
4687 let last_span = self.last_span;
4688 self.span_err(last_span, "expected item after attributes");
4692 inner: mk_sp(inner_lo, self.span.lo),
4693 view_items: view_items,
4698 fn parse_item_const(&mut self) -> ItemInfo {
4699 let m = if self.eat_keyword(keywords::Mut) {MutMutable} else {MutImmutable};
4700 let id = self.parse_ident();
4701 self.expect(&token::COLON);
4702 let ty = self.parse_ty(true);
4703 self.expect(&token::EQ);
4704 let e = self.parse_expr();
4705 self.commit_expr_expecting(&*e, token::SEMI);
4706 (id, ItemStatic(ty, m, e), None)
4709 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
4710 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> ItemInfo {
4711 let id_span = self.span;
4712 let id = self.parse_ident();
4713 if self.token == token::SEMI {
4715 // This mod is in an external file. Let's go get it!
4716 let (m, attrs) = self.eval_src_mod(id, outer_attrs, id_span);
4717 (id, m, Some(attrs))
4719 self.push_mod_path(id, outer_attrs);
4720 self.expect(&token::LBRACE);
4721 let mod_inner_lo = self.span.lo;
4722 let old_owns_directory = self.owns_directory;
4723 self.owns_directory = true;
4724 let (inner, next) = self.parse_inner_attrs_and_next();
4725 let m = self.parse_mod_items(token::RBRACE, next, mod_inner_lo);
4726 self.expect(&token::RBRACE);
4727 self.owns_directory = old_owns_directory;
4728 self.pop_mod_path();
4729 (id, ItemMod(m), Some(inner))
4733 fn push_mod_path(&mut self, id: Ident, attrs: &[Attribute]) {
4734 let default_path = self.id_to_interned_str(id);
4735 let file_path = match ::attr::first_attr_value_str_by_name(attrs,
4738 None => default_path,
4740 self.mod_path_stack.push(file_path)
4743 fn pop_mod_path(&mut self) {
4744 self.mod_path_stack.pop().unwrap();
4747 /// Read a module from a source file.
4748 fn eval_src_mod(&mut self,
4750 outer_attrs: &[ast::Attribute],
4752 -> (ast::Item_, Vec<ast::Attribute> ) {
4753 let mut prefix = Path::new(self.sess.span_diagnostic.cm.span_to_filename(self.span));
4755 let mod_path = Path::new(".").join_many(self.mod_path_stack.as_slice());
4756 let dir_path = prefix.join(&mod_path);
4757 let mod_string = token::get_ident(id);
4758 let (file_path, owns_directory) = match ::attr::first_attr_value_str_by_name(
4759 outer_attrs, "path") {
4760 Some(d) => (dir_path.join(d), true),
4762 let mod_name = mod_string.get().to_string();
4763 let default_path_str = format!("{}.rs", mod_name);
4764 let secondary_path_str = format!("{}/mod.rs", mod_name);
4765 let default_path = dir_path.join(default_path_str.as_slice());
4766 let secondary_path = dir_path.join(secondary_path_str.as_slice());
4767 let default_exists = default_path.exists();
4768 let secondary_exists = secondary_path.exists();
4770 if !self.owns_directory {
4771 self.span_err(id_sp,
4772 "cannot declare a new module at this location");
4773 let this_module = match self.mod_path_stack.last() {
4774 Some(name) => name.get().to_string(),
4775 None => self.root_module_name.get_ref().clone(),
4777 self.span_note(id_sp,
4778 format!("maybe move this module `{0}` \
4779 to its own directory via \
4781 this_module).as_slice());
4782 if default_exists || secondary_exists {
4783 self.span_note(id_sp,
4784 format!("... or maybe `use` the module \
4785 `{}` instead of possibly \
4787 mod_name).as_slice());
4789 self.abort_if_errors();
4792 match (default_exists, secondary_exists) {
4793 (true, false) => (default_path, false),
4794 (false, true) => (secondary_path, true),
4796 self.span_fatal(id_sp,
4797 format!("file not found for module \
4799 mod_name).as_slice());
4804 format!("file for module `{}` found at both {} \
4808 secondary_path_str).as_slice());
4814 self.eval_src_mod_from_path(file_path, owns_directory,
4815 mod_string.get().to_string(), id_sp)
4818 fn eval_src_mod_from_path(&mut self,
4820 owns_directory: bool,
4822 id_sp: Span) -> (ast::Item_, Vec<ast::Attribute> ) {
4823 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
4824 match included_mod_stack.iter().position(|p| *p == path) {
4826 let mut err = String::from_str("circular modules: ");
4827 let len = included_mod_stack.len();
4828 for p in included_mod_stack.slice(i, len).iter() {
4829 err.push_str(p.display().as_maybe_owned().as_slice());
4830 err.push_str(" -> ");
4832 err.push_str(path.display().as_maybe_owned().as_slice());
4833 self.span_fatal(id_sp, err.as_slice());
4837 included_mod_stack.push(path.clone());
4838 drop(included_mod_stack);
4841 new_sub_parser_from_file(self.sess,
4847 let mod_inner_lo = p0.span.lo;
4848 let (mod_attrs, next) = p0.parse_inner_attrs_and_next();
4849 let first_item_outer_attrs = next;
4850 let m0 = p0.parse_mod_items(token::EOF, first_item_outer_attrs, mod_inner_lo);
4851 self.sess.included_mod_stack.borrow_mut().pop();
4852 return (ast::ItemMod(m0), mod_attrs);
4855 /// Parse a function declaration from a foreign module
4856 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility,
4857 attrs: Vec<Attribute>) -> P<ForeignItem> {
4858 let lo = self.span.lo;
4859 self.expect_keyword(keywords::Fn);
4861 let (ident, mut generics) = self.parse_fn_header();
4862 let decl = self.parse_fn_decl(true);
4863 self.parse_where_clause(&mut generics);
4864 let hi = self.span.hi;
4865 self.expect(&token::SEMI);
4866 P(ast::ForeignItem {
4869 node: ForeignItemFn(decl, generics),
4870 id: ast::DUMMY_NODE_ID,
4871 span: mk_sp(lo, hi),
4876 /// Parse a static item from a foreign module
4877 fn parse_item_foreign_static(&mut self, vis: ast::Visibility,
4878 attrs: Vec<Attribute>) -> P<ForeignItem> {
4879 let lo = self.span.lo;
4881 self.expect_keyword(keywords::Static);
4882 let mutbl = self.eat_keyword(keywords::Mut);
4884 let ident = self.parse_ident();
4885 self.expect(&token::COLON);
4886 let ty = self.parse_ty(true);
4887 let hi = self.span.hi;
4888 self.expect(&token::SEMI);
4892 node: ForeignItemStatic(ty, mutbl),
4893 id: ast::DUMMY_NODE_ID,
4894 span: mk_sp(lo, hi),
4899 /// Parse safe/unsafe and fn
4900 fn parse_fn_style(&mut self) -> FnStyle {
4901 if self.eat_keyword(keywords::Fn) { NormalFn }
4902 else if self.eat_keyword(keywords::Unsafe) {
4903 self.expect_keyword(keywords::Fn);
4906 else { self.unexpected(); }
4910 /// At this point, this is essentially a wrapper for
4911 /// parse_foreign_items.
4912 fn parse_foreign_mod_items(&mut self,
4914 first_item_attrs: Vec<Attribute> )
4916 let ParsedItemsAndViewItems {
4917 attrs_remaining: attrs_remaining,
4918 view_items: view_items,
4920 foreign_items: foreign_items
4921 } = self.parse_foreign_items(first_item_attrs, true);
4922 if ! attrs_remaining.is_empty() {
4923 let last_span = self.last_span;
4924 self.span_err(last_span,
4925 "expected item after attributes");
4927 assert!(self.token == token::RBRACE);
4930 view_items: view_items,
4931 items: foreign_items
4935 /// Parse extern crate links
4939 /// extern crate url;
4940 /// extern crate foo = "bar"; //deprecated
4941 /// extern crate "bar" as foo;
4942 fn parse_item_extern_crate(&mut self,
4944 visibility: Visibility,
4945 attrs: Vec<Attribute> )
4948 let (maybe_path, ident) = match self.token {
4949 token::IDENT(..) => {
4950 let the_ident = self.parse_ident();
4951 self.expect_one_of(&[], &[token::EQ, token::SEMI]);
4952 let path = if self.token == token::EQ {
4954 let path = self.parse_str();
4955 let span = self.span;
4956 self.obsolete(span, ObsoleteExternCrateRenaming);
4960 self.expect(&token::SEMI);
4963 token::LIT_STR(..) | token::LIT_STR_RAW(..) => {
4964 let path = self.parse_str();
4965 self.expect_keyword(keywords::As);
4966 let the_ident = self.parse_ident();
4967 self.expect(&token::SEMI);
4968 (Some(path), the_ident)
4971 let span = self.span;
4972 let token_str = self.this_token_to_string();
4973 self.span_fatal(span,
4974 format!("expected extern crate name but \
4976 token_str).as_slice());
4980 IoviViewItem(ast::ViewItem {
4981 node: ViewItemExternCrate(ident, maybe_path, ast::DUMMY_NODE_ID),
4984 span: mk_sp(lo, self.last_span.hi)
4988 /// Parse `extern` for foreign ABIs
4991 /// `extern` is expected to have been
4992 /// consumed before calling this method
4998 fn parse_item_foreign_mod(&mut self,
5000 opt_abi: Option<abi::Abi>,
5001 visibility: Visibility,
5002 attrs: Vec<Attribute> )
5005 self.expect(&token::LBRACE);
5007 let abi = opt_abi.unwrap_or(abi::C);
5009 let (inner, next) = self.parse_inner_attrs_and_next();
5010 let m = self.parse_foreign_mod_items(abi, next);
5011 self.expect(&token::RBRACE);
5013 let last_span = self.last_span;
5014 let item = self.mk_item(lo,
5016 special_idents::invalid,
5019 maybe_append(attrs, Some(inner)));
5020 return IoviItem(item);
5023 /// Parse type Foo = Bar;
5024 fn parse_item_type(&mut self) -> ItemInfo {
5025 let ident = self.parse_ident();
5026 let mut tps = self.parse_generics();
5027 self.parse_where_clause(&mut tps);
5028 self.expect(&token::EQ);
5029 let ty = self.parse_ty(true);
5030 self.expect(&token::SEMI);
5031 (ident, ItemTy(ty, tps), None)
5034 /// Parse a structure-like enum variant definition
5035 /// this should probably be renamed or refactored...
5036 fn parse_struct_def(&mut self) -> P<StructDef> {
5037 let mut fields: Vec<StructField> = Vec::new();
5038 while self.token != token::RBRACE {
5039 fields.push(self.parse_struct_decl_field());
5051 /// Parse the part of an "enum" decl following the '{'
5052 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> EnumDef {
5053 let mut variants = Vec::new();
5054 let mut all_nullary = true;
5055 let mut have_disr = false;
5056 while self.token != token::RBRACE {
5057 let variant_attrs = self.parse_outer_attributes();
5058 let vlo = self.span.lo;
5060 let vis = self.parse_visibility();
5064 let mut args = Vec::new();
5065 let mut disr_expr = None;
5066 ident = self.parse_ident();
5067 if self.eat(&token::LBRACE) {
5068 // Parse a struct variant.
5069 all_nullary = false;
5070 kind = StructVariantKind(self.parse_struct_def());
5071 } else if self.token == token::LPAREN {
5072 all_nullary = false;
5073 let arg_tys = self.parse_enum_variant_seq(
5076 seq_sep_trailing_allowed(token::COMMA),
5077 |p| p.parse_ty(true)
5079 for ty in arg_tys.into_iter() {
5080 args.push(ast::VariantArg {
5082 id: ast::DUMMY_NODE_ID,
5085 kind = TupleVariantKind(args);
5086 } else if self.eat(&token::EQ) {
5088 disr_expr = Some(self.parse_expr());
5089 kind = TupleVariantKind(args);
5091 kind = TupleVariantKind(Vec::new());
5094 let vr = ast::Variant_ {
5096 attrs: variant_attrs,
5098 id: ast::DUMMY_NODE_ID,
5099 disr_expr: disr_expr,
5102 variants.push(P(spanned(vlo, self.last_span.hi, vr)));
5104 if !self.eat(&token::COMMA) { break; }
5106 self.expect(&token::RBRACE);
5107 if have_disr && !all_nullary {
5108 self.fatal("discriminator values can only be used with a c-like \
5112 ast::EnumDef { variants: variants }
5115 /// Parse an "enum" declaration
5116 fn parse_item_enum(&mut self) -> ItemInfo {
5117 let id = self.parse_ident();
5118 let mut generics = self.parse_generics();
5119 self.parse_where_clause(&mut generics);
5120 self.expect(&token::LBRACE);
5122 let enum_definition = self.parse_enum_def(&generics);
5123 (id, ItemEnum(enum_definition, generics), None)
5126 fn fn_expr_lookahead(tok: &token::Token) -> bool {
5128 token::LPAREN | token::AT | token::TILDE | token::BINOP(_) => true,
5133 /// Parses a string as an ABI spec on an extern type or module. Consumes
5134 /// the `extern` keyword, if one is found.
5135 fn parse_opt_abi(&mut self) -> Option<abi::Abi> {
5137 token::LIT_STR(s) | token::LIT_STR_RAW(s, _) => {
5139 let the_string = s.as_str();
5140 match abi::lookup(the_string) {
5141 Some(abi) => Some(abi),
5143 let last_span = self.last_span;
5146 format!("illegal ABI: expected one of [{}], \
5148 abi::all_names().connect(", "),
5149 the_string).as_slice());
5159 /// Parse one of the items or view items allowed by the
5160 /// flags; on failure, return IoviNone.
5161 /// NB: this function no longer parses the items inside an
5163 fn parse_item_or_view_item(&mut self,
5164 attrs: Vec<Attribute> ,
5165 macros_allowed: bool)
5167 let nt_item = match self.token {
5168 INTERPOLATED(token::NtItem(ref item)) => {
5169 Some((**item).clone())
5176 let mut attrs = attrs;
5177 mem::swap(&mut item.attrs, &mut attrs);
5178 item.attrs.extend(attrs.into_iter());
5179 return IoviItem(P(item));
5184 let lo = self.span.lo;
5186 let visibility = self.parse_visibility();
5188 // must be a view item:
5189 if self.eat_keyword(keywords::Use) {
5190 // USE ITEM (IoviViewItem)
5191 let view_item = self.parse_use();
5192 self.expect(&token::SEMI);
5193 return IoviViewItem(ast::ViewItem {
5197 span: mk_sp(lo, self.last_span.hi)
5200 // either a view item or an item:
5201 if self.eat_keyword(keywords::Extern) {
5202 let next_is_mod = self.eat_keyword(keywords::Mod);
5204 if next_is_mod || self.eat_keyword(keywords::Crate) {
5206 let last_span = self.last_span;
5207 self.span_err(mk_sp(lo, last_span.hi),
5208 format!("`extern mod` is obsolete, use \
5209 `extern crate` instead \
5210 to refer to external \
5211 crates.").as_slice())
5213 return self.parse_item_extern_crate(lo, visibility, attrs);
5216 let opt_abi = self.parse_opt_abi();
5218 if self.eat_keyword(keywords::Fn) {
5219 // EXTERN FUNCTION ITEM
5220 let abi = opt_abi.unwrap_or(abi::C);
5221 let (ident, item_, extra_attrs) =
5222 self.parse_item_fn(NormalFn, abi);
5223 let last_span = self.last_span;
5224 let item = self.mk_item(lo,
5229 maybe_append(attrs, extra_attrs));
5230 return IoviItem(item);
5231 } else if self.token == token::LBRACE {
5232 return self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs);
5235 let span = self.span;
5236 let token_str = self.this_token_to_string();
5237 self.span_fatal(span,
5238 format!("expected `{}` or `fn`, found `{}`", "{",
5239 token_str).as_slice());
5242 let is_virtual = self.eat_keyword(keywords::Virtual);
5243 if is_virtual && !self.is_keyword(keywords::Struct) {
5244 let span = self.span;
5246 "`virtual` keyword may only be used with `struct`");
5249 // the rest are all guaranteed to be items:
5250 if self.is_keyword(keywords::Static) {
5253 let (ident, item_, extra_attrs) = self.parse_item_const();
5254 let last_span = self.last_span;
5255 let item = self.mk_item(lo,
5260 maybe_append(attrs, extra_attrs));
5261 return IoviItem(item);
5263 if self.is_keyword(keywords::Fn) &&
5264 self.look_ahead(1, |f| !Parser::fn_expr_lookahead(f)) {
5267 let (ident, item_, extra_attrs) =
5268 self.parse_item_fn(NormalFn, abi::Rust);
5269 let last_span = self.last_span;
5270 let item = self.mk_item(lo,
5275 maybe_append(attrs, extra_attrs));
5276 return IoviItem(item);
5278 if self.is_keyword(keywords::Unsafe)
5279 && self.look_ahead(1u, |t| *t != token::LBRACE) {
5280 // UNSAFE FUNCTION ITEM
5282 let abi = if self.eat_keyword(keywords::Extern) {
5283 self.parse_opt_abi().unwrap_or(abi::C)
5287 self.expect_keyword(keywords::Fn);
5288 let (ident, item_, extra_attrs) =
5289 self.parse_item_fn(UnsafeFn, abi);
5290 let last_span = self.last_span;
5291 let item = self.mk_item(lo,
5296 maybe_append(attrs, extra_attrs));
5297 return IoviItem(item);
5299 if self.eat_keyword(keywords::Mod) {
5301 let (ident, item_, extra_attrs) =
5302 self.parse_item_mod(attrs.as_slice());
5303 let last_span = self.last_span;
5304 let item = self.mk_item(lo,
5309 maybe_append(attrs, extra_attrs));
5310 return IoviItem(item);
5312 if self.eat_keyword(keywords::Type) {
5314 let (ident, item_, extra_attrs) = self.parse_item_type();
5315 let last_span = self.last_span;
5316 let item = self.mk_item(lo,
5321 maybe_append(attrs, extra_attrs));
5322 return IoviItem(item);
5324 if self.eat_keyword(keywords::Enum) {
5326 let (ident, item_, extra_attrs) = self.parse_item_enum();
5327 let last_span = self.last_span;
5328 let item = self.mk_item(lo,
5333 maybe_append(attrs, extra_attrs));
5334 return IoviItem(item);
5336 if self.eat_keyword(keywords::Trait) {
5338 let (ident, item_, extra_attrs) = self.parse_item_trait();
5339 let last_span = self.last_span;
5340 let item = self.mk_item(lo,
5345 maybe_append(attrs, extra_attrs));
5346 return IoviItem(item);
5348 if self.eat_keyword(keywords::Impl) {
5350 let (ident, item_, extra_attrs) = self.parse_item_impl();
5351 let last_span = self.last_span;
5352 let item = self.mk_item(lo,
5357 maybe_append(attrs, extra_attrs));
5358 return IoviItem(item);
5360 if self.eat_keyword(keywords::Struct) {
5362 let (ident, item_, extra_attrs) = self.parse_item_struct(is_virtual);
5363 let last_span = self.last_span;
5364 let item = self.mk_item(lo,
5369 maybe_append(attrs, extra_attrs));
5370 return IoviItem(item);
5372 self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility)
5375 /// Parse a foreign item; on failure, return IoviNone.
5376 fn parse_foreign_item(&mut self,
5377 attrs: Vec<Attribute> ,
5378 macros_allowed: bool)
5380 maybe_whole!(iovi self, NtItem);
5381 let lo = self.span.lo;
5383 let visibility = self.parse_visibility();
5385 if self.is_keyword(keywords::Static) {
5386 // FOREIGN STATIC ITEM
5387 let item = self.parse_item_foreign_static(visibility, attrs);
5388 return IoviForeignItem(item);
5390 if self.is_keyword(keywords::Fn) || self.is_keyword(keywords::Unsafe) {
5391 // FOREIGN FUNCTION ITEM
5392 let item = self.parse_item_foreign_fn(visibility, attrs);
5393 return IoviForeignItem(item);
5395 self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility)
5398 /// This is the fall-through for parsing items.
5399 fn parse_macro_use_or_failure(
5401 attrs: Vec<Attribute> ,
5402 macros_allowed: bool,
5404 visibility: Visibility
5405 ) -> ItemOrViewItem {
5406 if macros_allowed && !token::is_any_keyword(&self.token)
5407 && self.look_ahead(1, |t| *t == token::NOT)
5408 && (self.look_ahead(2, |t| is_plain_ident(t))
5409 || self.look_ahead(2, |t| *t == token::LPAREN)
5410 || self.look_ahead(2, |t| *t == token::LBRACE)) {
5411 // MACRO INVOCATION ITEM
5414 let pth = self.parse_path(NoTypesAllowed).path;
5415 self.expect(&token::NOT);
5417 // a 'special' identifier (like what `macro_rules!` uses)
5418 // is optional. We should eventually unify invoc syntax
5420 let id = if is_plain_ident(&self.token) {
5423 token::special_idents::invalid // no special identifier
5425 // eat a matched-delimiter token tree:
5426 let tts = match token::close_delimiter_for(&self.token) {
5429 self.parse_seq_to_end(&ket,
5431 |p| p.parse_token_tree())
5433 None => self.fatal("expected open delimiter")
5435 // single-variant-enum... :
5436 let m = ast::MacInvocTT(pth, tts, EMPTY_CTXT);
5437 let m: ast::Mac = codemap::Spanned { node: m,
5438 span: mk_sp(self.span.lo,
5440 let item_ = ItemMac(m);
5441 let last_span = self.last_span;
5442 let item = self.mk_item(lo,
5448 return IoviItem(item);
5451 // FAILURE TO PARSE ITEM
5452 if visibility != Inherited {
5453 let mut s = String::from_str("unmatched visibility `");
5454 if visibility == Public {
5460 let last_span = self.last_span;
5461 self.span_fatal(last_span, s.as_slice());
5463 return IoviNone(attrs);
5466 pub fn parse_item_with_outer_attributes(&mut self) -> Option<P<Item>> {
5467 let attrs = self.parse_outer_attributes();
5468 self.parse_item(attrs)
5471 pub fn parse_item(&mut self, attrs: Vec<Attribute>) -> Option<P<Item>> {
5472 match self.parse_item_or_view_item(attrs, true) {
5473 IoviNone(_) => None,
5475 self.fatal("view items are not allowed here"),
5476 IoviForeignItem(_) =>
5477 self.fatal("foreign items are not allowed here"),
5478 IoviItem(item) => Some(item)
5482 /// Parse, e.g., "use a::b::{z,y}"
5483 fn parse_use(&mut self) -> ViewItem_ {
5484 return ViewItemUse(self.parse_view_path());
5488 /// Matches view_path : MOD? IDENT EQ non_global_path
5489 /// | MOD? non_global_path MOD_SEP LBRACE RBRACE
5490 /// | MOD? non_global_path MOD_SEP LBRACE ident_seq RBRACE
5491 /// | MOD? non_global_path MOD_SEP STAR
5492 /// | MOD? non_global_path
5493 fn parse_view_path(&mut self) -> P<ViewPath> {
5494 let lo = self.span.lo;
5496 if self.token == token::LBRACE {
5498 let idents = self.parse_unspanned_seq(
5499 &token::LBRACE, &token::RBRACE,
5500 seq_sep_trailing_allowed(token::COMMA),
5501 |p| p.parse_path_list_item());
5502 let path = ast::Path {
5503 span: mk_sp(lo, self.span.hi),
5505 segments: Vec::new()
5507 return P(spanned(lo, self.span.hi,
5508 ViewPathList(path, idents, ast::DUMMY_NODE_ID)));
5511 let first_ident = self.parse_ident();
5512 let mut path = vec!(first_ident);
5517 let path_lo = self.span.lo;
5518 path = vec!(self.parse_ident());
5519 while self.token == token::MOD_SEP {
5521 let id = self.parse_ident();
5524 let span = mk_sp(path_lo, self.span.hi);
5525 self.obsolete(span, ObsoleteImportRenaming);
5526 let path = ast::Path {
5529 segments: path.into_iter().map(|identifier| {
5531 identifier: identifier,
5532 lifetimes: Vec::new(),
5533 types: OwnedSlice::empty(),
5537 return P(spanned(lo, self.span.hi,
5538 ViewPathSimple(first_ident, path,
5539 ast::DUMMY_NODE_ID)));
5543 // foo::bar or foo::{a,b,c} or foo::*
5544 while self.token == token::MOD_SEP {
5548 token::IDENT(i, _) => {
5553 // foo::bar::{a,b,c}
5555 let idents = self.parse_unspanned_seq(
5558 seq_sep_trailing_allowed(token::COMMA),
5559 |p| p.parse_path_list_item()
5561 let path = ast::Path {
5562 span: mk_sp(lo, self.span.hi),
5564 segments: path.into_iter().map(|identifier| {
5566 identifier: identifier,
5567 lifetimes: Vec::new(),
5568 types: OwnedSlice::empty(),
5572 return P(spanned(lo, self.span.hi,
5573 ViewPathList(path, idents, ast::DUMMY_NODE_ID)));
5577 token::BINOP(token::STAR) => {
5579 let path = ast::Path {
5580 span: mk_sp(lo, self.span.hi),
5582 segments: path.into_iter().map(|identifier| {
5584 identifier: identifier,
5585 lifetimes: Vec::new(),
5586 types: OwnedSlice::empty(),
5590 return P(spanned(lo, self.span.hi,
5591 ViewPathGlob(path, ast::DUMMY_NODE_ID)));
5600 let mut rename_to = *path.get(path.len() - 1u);
5601 let path = ast::Path {
5602 span: mk_sp(lo, self.span.hi),
5604 segments: path.into_iter().map(|identifier| {
5606 identifier: identifier,
5607 lifetimes: Vec::new(),
5608 types: OwnedSlice::empty(),
5612 if self.eat_keyword(keywords::As) {
5613 rename_to = self.parse_ident()
5615 P(spanned(lo, self.last_span.hi,
5616 ViewPathSimple(rename_to, path, ast::DUMMY_NODE_ID)))
5619 /// Parses a sequence of items. Stops when it finds program
5620 /// text that can't be parsed as an item
5621 /// - mod_items uses extern_mod_allowed = true
5622 /// - block_tail_ uses extern_mod_allowed = false
5623 fn parse_items_and_view_items(&mut self,
5624 first_item_attrs: Vec<Attribute> ,
5625 mut extern_mod_allowed: bool,
5626 macros_allowed: bool)
5627 -> ParsedItemsAndViewItems {
5628 let mut attrs = first_item_attrs.append(self.parse_outer_attributes().as_slice());
5629 // First, parse view items.
5630 let mut view_items : Vec<ast::ViewItem> = Vec::new();
5631 let mut items = Vec::new();
5633 // I think this code would probably read better as a single
5634 // loop with a mutable three-state-variable (for extern crates,
5635 // view items, and regular items) ... except that because
5636 // of macros, I'd like to delay that entire check until later.
5638 match self.parse_item_or_view_item(attrs, macros_allowed) {
5639 IoviNone(attrs) => {
5640 return ParsedItemsAndViewItems {
5641 attrs_remaining: attrs,
5642 view_items: view_items,
5644 foreign_items: Vec::new()
5647 IoviViewItem(view_item) => {
5648 match view_item.node {
5649 ViewItemUse(..) => {
5650 // `extern crate` must precede `use`.
5651 extern_mod_allowed = false;
5653 ViewItemExternCrate(..) if !extern_mod_allowed => {
5654 self.span_err(view_item.span,
5655 "\"extern crate\" declarations are \
5658 ViewItemExternCrate(..) => {}
5660 view_items.push(view_item);
5664 attrs = self.parse_outer_attributes();
5667 IoviForeignItem(_) => {
5671 attrs = self.parse_outer_attributes();
5674 // Next, parse items.
5676 match self.parse_item_or_view_item(attrs, macros_allowed) {
5677 IoviNone(returned_attrs) => {
5678 attrs = returned_attrs;
5681 IoviViewItem(view_item) => {
5682 attrs = self.parse_outer_attributes();
5683 self.span_err(view_item.span,
5684 "`use` and `extern crate` declarations must precede items");
5687 attrs = self.parse_outer_attributes();
5690 IoviForeignItem(_) => {
5696 ParsedItemsAndViewItems {
5697 attrs_remaining: attrs,
5698 view_items: view_items,
5700 foreign_items: Vec::new()
5704 /// Parses a sequence of foreign items. Stops when it finds program
5705 /// text that can't be parsed as an item
5706 fn parse_foreign_items(&mut self, first_item_attrs: Vec<Attribute> ,
5707 macros_allowed: bool)
5708 -> ParsedItemsAndViewItems {
5709 let mut attrs = first_item_attrs.append(self.parse_outer_attributes().as_slice());
5710 let mut foreign_items = Vec::new();
5712 match self.parse_foreign_item(attrs, macros_allowed) {
5713 IoviNone(returned_attrs) => {
5714 if self.token == token::RBRACE {
5715 attrs = returned_attrs;
5720 IoviViewItem(view_item) => {
5721 // I think this can't occur:
5722 self.span_err(view_item.span,
5723 "`use` and `extern crate` declarations must precede items");
5726 // FIXME #5668: this will occur for a macro invocation:
5727 self.span_fatal(item.span, "macros cannot expand to foreign items");
5729 IoviForeignItem(foreign_item) => {
5730 foreign_items.push(foreign_item);
5733 attrs = self.parse_outer_attributes();
5736 ParsedItemsAndViewItems {
5737 attrs_remaining: attrs,
5738 view_items: Vec::new(),
5740 foreign_items: foreign_items
5744 /// Parses a source module as a crate. This is the main
5745 /// entry point for the parser.
5746 pub fn parse_crate_mod(&mut self) -> Crate {
5747 let lo = self.span.lo;
5748 // parse the crate's inner attrs, maybe (oops) one
5749 // of the attrs of an item:
5750 let (inner, next) = self.parse_inner_attrs_and_next();
5751 let first_item_outer_attrs = next;
5752 // parse the items inside the crate:
5753 let m = self.parse_mod_items(token::EOF, first_item_outer_attrs, lo);
5758 config: self.cfg.clone(),
5759 span: mk_sp(lo, self.span.lo),
5760 exported_macros: Vec::new(),
5764 pub fn parse_optional_str(&mut self)
5765 -> Option<(InternedString, ast::StrStyle)> {
5766 let (s, style) = match self.token {
5767 token::LIT_STR(s) => (self.id_to_interned_str(s.ident()), ast::CookedStr),
5768 token::LIT_STR_RAW(s, n) => {
5769 (self.id_to_interned_str(s.ident()), ast::RawStr(n))
5777 pub fn parse_str(&mut self) -> (InternedString, StrStyle) {
5778 match self.parse_optional_str() {
5780 _ => self.fatal("expected string literal")