1 // Copyright 2012-2013 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.
15 use ast::{Sigil, BorrowedSigil, ManagedSigil, OwnedSigil};
16 use ast::{CallSugar, NoSugar};
17 use ast::{BareFnTy, ClosureTy};
18 use ast::{RegionTyParamBound, TraitTyParamBound};
19 use ast::{Provided, Public, Purity};
20 use ast::{Mod, BiAdd, Arg, Arm, Attribute, BindByRef, BindByValue};
21 use ast::{BiBitAnd, BiBitOr, BiBitXor, Block};
22 use ast::{BlockCheckMode, UnBox};
23 use ast::{Crate, CrateConfig, Decl, DeclItem};
24 use ast::{DeclLocal, DefaultBlock, UnDeref, BiDiv, EMPTY_CTXT, EnumDef, ExplicitSelf};
25 use ast::{Expr, Expr_, ExprAddrOf, ExprMatch, ExprAgain};
26 use ast::{ExprAssign, ExprAssignOp, ExprBinary, ExprBlock, ExprBox};
27 use ast::{ExprBreak, ExprCall, ExprCast};
28 use ast::{ExprField, ExprFnBlock, ExprIf, ExprIndex};
29 use ast::{ExprLit, ExprLogLevel, ExprLoop, ExprMac};
30 use ast::{ExprMethodCall, ExprParen, ExprPath, ExprProc};
31 use ast::{ExprRepeat, ExprRet, ExprStruct, ExprTup, ExprUnary};
32 use ast::{ExprVec, ExprVstore, ExprVstoreSlice, ExprVstoreBox};
33 use ast::{ExprVstoreMutSlice, ExprWhile, ExprForLoop, ExternFn, Field, FnDecl};
34 use ast::{ExprVstoreUniq, Onceness, Once, Many};
35 use ast::{ForeignItem, ForeignItemStatic, ForeignItemFn, ForeignMod};
36 use ast::{Ident, ImpureFn, Inherited, Item, Item_, ItemStatic};
37 use ast::{ItemEnum, ItemFn, ItemForeignMod, ItemImpl};
38 use ast::{ItemMac, ItemMod, ItemStruct, ItemTrait, ItemTy, Lit, Lit_};
39 use ast::{LitBool, LitFloat, LitFloatUnsuffixed, LitInt, LitChar};
40 use ast::{LitIntUnsuffixed, LitNil, LitStr, LitUint, Local};
41 use ast::{MutImmutable, MutMutable, Mac_, MacInvocTT, Matcher, MatchNonterminal};
42 use ast::{MatchSeq, MatchTok, Method, MutTy, BiMul, Mutability};
43 use ast::{NamedField, UnNeg, NoReturn, UnNot, P, Pat, PatEnum};
44 use ast::{PatIdent, PatLit, PatRange, PatRegion, PatStruct};
45 use ast::{PatTup, PatUniq, PatWild, PatWildMulti, Private};
46 use ast::{BiRem, Required};
47 use ast::{RetStyle, Return, BiShl, BiShr, Stmt, StmtDecl};
48 use ast::{StmtExpr, StmtSemi, StmtMac, StructDef, StructField};
49 use ast::{StructVariantKind, BiSub};
51 use ast::{SelfBox, SelfRegion, SelfStatic, SelfUniq, SelfValue};
52 use ast::{TokenTree, TraitMethod, TraitRef, TTDelim, TTSeq, TTTok};
53 use ast::{TTNonterminal, TupleVariantKind, Ty, Ty_, TyBot, TyBox};
54 use ast::{TypeField, TyFixedLengthVec, TyClosure, TyBareFn, TyTypeof};
55 use ast::{TyInfer, TypeMethod};
56 use ast::{TyNil, TyParam, TyParamBound, TyPath, TyPtr, TyRptr};
57 use ast::{TyTup, TyU32, TyUniq, TyVec, UnUniq};
58 use ast::{UnnamedField, UnsafeBlock, UnsafeFn, ViewItem};
59 use ast::{ViewItem_, ViewItemExternMod, ViewItemUse};
60 use ast::{ViewPath, ViewPathGlob, ViewPathList, ViewPathSimple};
63 use ast_util::{as_prec, lit_is_str, operator_prec};
65 use codemap::{Span, BytePos, Spanned, spanned, mk_sp};
67 use parse::attr::ParserAttr;
69 use parse::common::{SeqSep, seq_sep_none};
70 use parse::common::{seq_sep_trailing_disallowed, seq_sep_trailing_allowed};
71 use parse::lexer::Reader;
72 use parse::lexer::TokenAndSpan;
73 use parse::obsolete::*;
74 use parse::token::{INTERPOLATED, InternedString, can_begin_expr, get_ident};
75 use parse::token::{get_ident_interner, ident_to_str, is_ident};
76 use parse::token::{is_ident_or_path, is_plain_ident, keywords};
77 use parse::token::{special_idents, token_to_binop};
79 use parse::{new_sub_parser_from_file, ParseSess};
84 use std::hashmap::HashSet;
88 #[allow(non_camel_case_types)]
94 RESTRICT_NO_BAR_OR_DOUBLEBAR_OP,
97 type ItemInfo = (Ident, Item_, Option<~[Attribute]>);
99 /// How to parse a path. There are four different kinds of paths, all of which
100 /// are parsed somewhat differently.
102 pub enum PathParsingMode {
103 /// A path with no type parameters; e.g. `foo::bar::Baz`
105 /// A path with a lifetime and type parameters, with no double colons
106 /// before the type parameters; e.g. `foo::bar<'a>::Baz<T>`
107 LifetimeAndTypesWithoutColons,
108 /// A path with a lifetime and type parameters with double colons before
109 /// the type parameters; e.g. `foo::bar::<'a>::Baz::<T>`
110 LifetimeAndTypesWithColons,
111 /// A path with a lifetime and type parameters with bounds before the last
112 /// set of type parameters only; e.g. `foo::bar<'a>::Baz:X+Y<T>` This
113 /// form does not use extra double colons.
114 LifetimeAndTypesAndBounds,
117 /// A pair of a path segment and group of type parameter bounds. (See `ast.rs`
118 /// for the definition of a path segment.)
119 struct PathSegmentAndBoundSet {
120 segment: ast::PathSegment,
121 bound_set: Option<OptVec<TyParamBound>>,
124 /// A path paired with optional type bounds.
125 pub struct PathAndBounds {
127 bounds: Option<OptVec<TyParamBound>>,
130 enum ItemOrViewItem {
131 // Indicates a failure to parse any kind of item. The attributes are
133 IoviNone(~[Attribute]),
135 IoviForeignItem(@ForeignItem),
136 IoviViewItem(ViewItem)
139 /* The expr situation is not as complex as I thought it would be.
140 The important thing is to make sure that lookahead doesn't balk
141 at INTERPOLATED tokens */
142 macro_rules! maybe_whole_expr (
145 let mut maybe_path = match ($p).token {
146 INTERPOLATED(token::NtPath(ref pt)) => Some((**pt).clone()),
149 let ret = match ($p).token {
150 INTERPOLATED(token::NtExpr(e)) => {
153 INTERPOLATED(token::NtPath(_)) => {
154 let pt = maybe_path.take_unwrap();
155 Some($p.mk_expr(($p).span.lo, ($p).span.hi, ExprPath(pt)))
170 macro_rules! maybe_whole (
171 ($p:expr, $constructor:ident) => (
173 let __found__ = match ($p).token {
174 INTERPOLATED(token::$constructor(_)) => {
175 Some(($p).bump_and_get())
180 Some(INTERPOLATED(token::$constructor(x))) => {
187 (no_clone $p:expr, $constructor:ident) => (
189 let __found__ = match ($p).token {
190 INTERPOLATED(token::$constructor(_)) => {
191 Some(($p).bump_and_get())
196 Some(INTERPOLATED(token::$constructor(x))) => {
203 (deref $p:expr, $constructor:ident) => (
205 let __found__ = match ($p).token {
206 INTERPOLATED(token::$constructor(_)) => {
207 Some(($p).bump_and_get())
212 Some(INTERPOLATED(token::$constructor(x))) => {
219 (Some $p:expr, $constructor:ident) => (
221 let __found__ = match ($p).token {
222 INTERPOLATED(token::$constructor(_)) => {
223 Some(($p).bump_and_get())
228 Some(INTERPOLATED(token::$constructor(x))) => {
229 return Some(x.clone()),
235 (iovi $p:expr, $constructor:ident) => (
237 let __found__ = match ($p).token {
238 INTERPOLATED(token::$constructor(_)) => {
239 Some(($p).bump_and_get())
244 Some(INTERPOLATED(token::$constructor(x))) => {
245 return IoviItem(x.clone())
251 (pair_empty $p:expr, $constructor:ident) => (
253 let __found__ = match ($p).token {
254 INTERPOLATED(token::$constructor(_)) => {
255 Some(($p).bump_and_get())
260 Some(INTERPOLATED(token::$constructor(x))) => {
270 fn maybe_append(lhs: ~[Attribute], rhs: Option<~[Attribute]>)
274 Some(ref attrs) => vec::append(lhs, (*attrs))
279 struct ParsedItemsAndViewItems {
280 attrs_remaining: ~[Attribute],
281 view_items: ~[ViewItem],
283 foreign_items: ~[@ForeignItem]
286 /* ident is handled by common.rs */
288 pub fn Parser(sess: @ParseSess, cfg: ast::CrateConfig, rdr: @Reader)
290 let tok0 = rdr.next_token();
291 let interner = get_ident_interner();
293 let placeholder = TokenAndSpan {
294 tok: token::UNDERSCORE,
316 restriction: UNRESTRICTED,
318 obsolete_set: HashSet::new(),
321 non_copyable: util::NonCopyable
328 // the current token:
330 // the span of the current token:
332 // the span of the prior token:
334 // the previous token or None (only stashed sometimes).
335 last_token: Option<~token::Token>,
336 buffer: [TokenAndSpan, ..4],
339 tokens_consumed: uint,
340 restriction: restriction,
341 quote_depth: uint, // not (yet) related to the quasiquoter
343 interner: @token::IdentInterner,
344 /// The set of seen errors about obsolete syntax. Used to suppress
345 /// extra detail when the same error is seen twice
346 obsolete_set: HashSet<ObsoleteSyntax>,
347 /// Used to determine the path to externally loaded source files
348 mod_path_stack: ~[InternedString],
349 /// Stack of spans of open delimiters. Used for error message.
350 open_braces: ~[Span],
351 /* do not copy the parser; its state is tied to outside state */
352 priv non_copyable: util::NonCopyable
355 fn is_plain_ident_or_underscore(t: &token::Token) -> bool {
356 is_plain_ident(t) || *t == token::UNDERSCORE
360 // convert a token to a string using self's reader
361 pub fn token_to_str(token: &token::Token) -> ~str {
362 token::to_str(get_ident_interner(), token)
365 // convert the current token to a string using self's reader
366 pub fn this_token_to_str(&mut self) -> ~str {
367 Parser::token_to_str(&self.token)
370 pub fn unexpected_last(&mut self, t: &token::Token) -> ! {
371 let token_str = Parser::token_to_str(t);
372 self.span_fatal(self.last_span, format!("unexpected token: `{}`",
376 pub fn unexpected(&mut self) -> ! {
377 let this_token = self.this_token_to_str();
378 self.fatal(format!("unexpected token: `{}`", this_token));
381 // expect and consume the token t. Signal an error if
382 // the next token is not t.
383 pub fn expect(&mut self, t: &token::Token) {
384 if self.token == *t {
387 let token_str = Parser::token_to_str(t);
388 let this_token_str = self.this_token_to_str();
389 self.fatal(format!("expected `{}` but found `{}`",
395 // Expect next token to be edible or inedible token. If edible,
396 // then consume it; if inedible, then return without consuming
397 // anything. Signal a fatal error if next token is unexpected.
398 pub fn expect_one_of(&mut self,
399 edible: &[token::Token],
400 inedible: &[token::Token]) {
401 fn tokens_to_str(tokens: &[token::Token]) -> ~str {
402 let mut i = tokens.iter();
403 // This might be a sign we need a connect method on Iterator.
404 let b = i.next().map_or(~"", |t| Parser::token_to_str(t));
405 i.fold(b, |b,a| b + "`, `" + Parser::token_to_str(a))
407 if edible.contains(&self.token) {
409 } else if inedible.contains(&self.token) {
410 // leave it in the input
412 let expected = vec::append(edible.to_owned(), inedible);
413 let expect = tokens_to_str(expected);
414 let actual = self.this_token_to_str();
416 if expected.len() != 1 {
417 format!("expected one of `{}` but found `{}`", expect, actual)
419 format!("expected `{}` but found `{}`", expect, actual)
425 // Check for erroneous `ident { }`; if matches, signal error and
426 // recover (without consuming any expected input token). Returns
427 // true if and only if input was consumed for recovery.
428 pub fn check_for_erroneous_unit_struct_expecting(&mut self, expected: &[token::Token]) -> bool {
429 if self.token == token::LBRACE
430 && expected.iter().all(|t| *t != token::LBRACE)
431 && self.look_ahead(1, |t| *t == token::RBRACE) {
432 // matched; signal non-fatal error and recover.
433 self.span_err(self.span,
434 "Unit-like struct construction is written with no trailing `{ }`");
435 self.eat(&token::LBRACE);
436 self.eat(&token::RBRACE);
443 // Commit to parsing a complete expression `e` expected to be
444 // followed by some token from the set edible + inedible. Recover
445 // from anticipated input errors, discarding erroneous characters.
446 pub fn commit_expr(&mut self, e: @Expr, edible: &[token::Token], inedible: &[token::Token]) {
447 debug!("commit_expr {:?}", e);
450 // might be unit-struct construction; check for recoverableinput error.
451 let expected = vec::append(edible.to_owned(), inedible);
452 self.check_for_erroneous_unit_struct_expecting(expected);
456 self.expect_one_of(edible, inedible)
459 pub fn commit_expr_expecting(&mut self, e: @Expr, edible: token::Token) {
460 self.commit_expr(e, &[edible], &[])
463 // Commit to parsing a complete statement `s`, which expects to be
464 // followed by some token from the set edible + inedible. Check
465 // for recoverable input errors, discarding erroneous characters.
466 pub fn commit_stmt(&mut self, s: @Stmt, edible: &[token::Token], inedible: &[token::Token]) {
467 debug!("commit_stmt {:?}", s);
468 let _s = s; // unused, but future checks might want to inspect `s`.
469 if self.last_token.as_ref().map_or(false, |t| is_ident_or_path(*t)) {
470 let expected = vec::append(edible.to_owned(), inedible);
471 self.check_for_erroneous_unit_struct_expecting(expected);
473 self.expect_one_of(edible, inedible)
476 pub fn commit_stmt_expecting(&mut self, s: @Stmt, edible: token::Token) {
477 self.commit_stmt(s, &[edible], &[])
480 pub fn parse_ident(&mut self) -> ast::Ident {
481 self.check_strict_keywords();
482 self.check_reserved_keywords();
484 token::IDENT(i, _) => {
488 token::INTERPOLATED(token::NtIdent(..)) => {
489 self.bug("ident interpolation not converted to real token");
492 let token_str = self.this_token_to_str();
493 self.fatal(format!( "expected ident, found `{}`", token_str))
498 pub fn parse_path_list_ident(&mut self) -> ast::PathListIdent {
499 let lo = self.span.lo;
500 let ident = self.parse_ident();
501 let hi = self.last_span.hi;
502 spanned(lo, hi, ast::PathListIdent_ { name: ident,
503 id: ast::DUMMY_NODE_ID })
506 // consume token 'tok' if it exists. Returns true if the given
507 // token was present, false otherwise.
508 pub fn eat(&mut self, tok: &token::Token) -> bool {
509 let is_present = self.token == *tok;
510 if is_present { self.bump() }
514 pub fn is_keyword(&mut self, kw: keywords::Keyword) -> bool {
515 token::is_keyword(kw, &self.token)
518 // if the next token is the given keyword, eat it and return
519 // true. Otherwise, return false.
520 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
521 let is_kw = match self.token {
522 token::IDENT(sid, false) => kw.to_ident().name == sid.name,
525 if is_kw { self.bump() }
529 // if the given word is not a keyword, signal an error.
530 // if the next token is not the given word, signal an error.
531 // otherwise, eat it.
532 pub fn expect_keyword(&mut self, kw: keywords::Keyword) {
533 if !self.eat_keyword(kw) {
534 let id_str = self.id_to_str(kw.to_ident()).to_str();
535 let token_str = self.this_token_to_str();
536 self.fatal(format!("expected `{}`, found `{}`",
542 // signal an error if the given string is a strict keyword
543 pub fn check_strict_keywords(&mut self) {
544 if token::is_strict_keyword(&self.token) {
545 let token_str = self.this_token_to_str();
546 self.span_err(self.span,
547 format!("found `{}` in ident position", token_str));
551 // signal an error if the current token is a reserved keyword
552 pub fn check_reserved_keywords(&mut self) {
553 if token::is_reserved_keyword(&self.token) {
554 let token_str = self.this_token_to_str();
555 self.fatal(format!("`{}` is a reserved keyword", token_str))
559 // Expect and consume a `|`. If `||` is seen, replace it with a single
560 // `|` and continue. If a `|` is not seen, signal an error.
561 fn expect_or(&mut self) {
563 token::BINOP(token::OR) => self.bump(),
565 let lo = self.span.lo + BytePos(1);
566 self.replace_token(token::BINOP(token::OR), lo, self.span.hi)
569 let token_str = self.this_token_to_str();
571 Parser::token_to_str(&token::BINOP(token::OR));
572 self.fatal(format!("expected `{}`, found `{}`",
579 // Parse a sequence bracketed by `|` and `|`, stopping before the `|`.
580 fn parse_seq_to_before_or<T>(
583 f: |&mut Parser| -> T)
585 let mut first = true;
586 let mut vector = ~[];
587 while self.token != token::BINOP(token::OR) &&
588 self.token != token::OROR {
600 // expect and consume a GT. if a >> is seen, replace it
601 // with a single > and continue. If a GT is not seen,
603 pub fn expect_gt(&mut self) {
605 token::GT => self.bump(),
606 token::BINOP(token::SHR) => {
607 let lo = self.span.lo + BytePos(1);
608 self.replace_token(token::GT, lo, self.span.hi)
611 let gt_str = Parser::token_to_str(&token::GT);
612 let this_token_str = self.this_token_to_str();
613 self.fatal(format!("expected `{}`, found `{}`",
620 // parse a sequence bracketed by '<' and '>', stopping
622 pub fn parse_seq_to_before_gt<T>(
624 sep: Option<token::Token>,
625 f: |&mut Parser| -> T)
627 let mut first = true;
628 let mut v = opt_vec::Empty;
629 while self.token != token::GT
630 && self.token != token::BINOP(token::SHR) {
633 if first { first = false; }
634 else { self.expect(t); }
643 pub fn parse_seq_to_gt<T>(
645 sep: Option<token::Token>,
646 f: |&mut Parser| -> T)
648 let v = self.parse_seq_to_before_gt(sep, f);
653 // parse a sequence, including the closing delimiter. The function
654 // f must consume tokens until reaching the next separator or
656 pub fn parse_seq_to_end<T>(
660 f: |&mut Parser| -> T)
662 let val = self.parse_seq_to_before_end(ket, sep, f);
667 // parse a sequence, not including the closing delimiter. The function
668 // f must consume tokens until reaching the next separator or
670 pub fn parse_seq_to_before_end<T>(
674 f: |&mut Parser| -> T)
676 let mut first: bool = true;
677 let mut v: ~[T] = ~[];
678 while self.token != *ket {
681 if first { first = false; }
682 else { self.expect(t); }
686 if sep.trailing_sep_allowed && self.token == *ket { break; }
692 // parse a sequence, including the closing delimiter. The function
693 // f must consume tokens until reaching the next separator or
695 pub fn parse_unspanned_seq<T>(
700 f: |&mut Parser| -> T)
703 let result = self.parse_seq_to_before_end(ket, sep, f);
708 // NB: Do not use this function unless you actually plan to place the
709 // spanned list in the AST.
715 f: |&mut Parser| -> T)
717 let lo = self.span.lo;
719 let result = self.parse_seq_to_before_end(ket, sep, f);
720 let hi = self.span.hi;
722 spanned(lo, hi, result)
725 // advance the parser by one token
726 pub fn bump(&mut self) {
727 self.last_span = self.span;
728 // Stash token for error recovery (sometimes; clone is not necessarily cheap).
729 self.last_token = if is_ident_or_path(&self.token) {
730 Some(~self.token.clone())
734 let next = if self.buffer_start == self.buffer_end {
735 self.reader.next_token()
737 // Avoid token copies with `util::replace`.
738 let buffer_start = self.buffer_start as uint;
739 let next_index = (buffer_start + 1) & 3 as uint;
740 self.buffer_start = next_index as int;
742 let placeholder = TokenAndSpan {
743 tok: token::UNDERSCORE,
746 util::replace(&mut self.buffer[buffer_start], placeholder)
749 self.token = next.tok;
750 self.tokens_consumed += 1u;
753 // Advance the parser by one token and return the bumped token.
754 pub fn bump_and_get(&mut self) -> token::Token {
755 let old_token = util::replace(&mut self.token, token::UNDERSCORE);
760 // EFFECT: replace the current token and span with the given one
761 pub fn replace_token(&mut self,
766 self.span = mk_sp(lo, hi);
768 pub fn buffer_length(&mut self) -> int {
769 if self.buffer_start <= self.buffer_end {
770 return self.buffer_end - self.buffer_start;
772 return (4 - self.buffer_start) + self.buffer_end;
774 pub fn look_ahead<R>(&mut self, distance: uint, f: |&token::Token| -> R)
776 let dist = distance as int;
777 while self.buffer_length() < dist {
778 self.buffer[self.buffer_end] = self.reader.next_token();
779 self.buffer_end = (self.buffer_end + 1) & 3;
781 f(&self.buffer[(self.buffer_start + dist - 1) & 3].tok)
783 pub fn fatal(&mut self, m: &str) -> ! {
784 self.sess.span_diagnostic.span_fatal(self.span, m)
786 pub fn span_fatal(&mut self, sp: Span, m: &str) -> ! {
787 self.sess.span_diagnostic.span_fatal(sp, m)
789 pub fn span_note(&mut self, sp: Span, m: &str) {
790 self.sess.span_diagnostic.span_note(sp, m)
792 pub fn bug(&mut self, m: &str) -> ! {
793 self.sess.span_diagnostic.span_bug(self.span, m)
795 pub fn warn(&mut self, m: &str) {
796 self.sess.span_diagnostic.span_warn(self.span, m)
798 pub fn span_err(&mut self, sp: Span, m: &str) {
799 self.sess.span_diagnostic.span_err(sp, m)
801 pub fn abort_if_errors(&mut self) {
802 self.sess.span_diagnostic.handler().abort_if_errors();
805 pub fn id_to_str(&mut self, id: Ident) -> @str {
806 get_ident_interner().get(id.name)
809 pub fn id_to_interned_str(&mut self, id: Ident) -> InternedString {
813 // Is the current token one of the keywords that signals a bare function
815 pub fn token_is_bare_fn_keyword(&mut self) -> bool {
816 if token::is_keyword(keywords::Fn, &self.token) {
820 if token::is_keyword(keywords::Unsafe, &self.token) ||
821 token::is_keyword(keywords::Once, &self.token) {
822 return self.look_ahead(1, |t| token::is_keyword(keywords::Fn, t))
828 // Is the current token one of the keywords that signals a closure type?
829 pub fn token_is_closure_keyword(&mut self) -> bool {
830 token::is_keyword(keywords::Unsafe, &self.token) ||
831 token::is_keyword(keywords::Once, &self.token)
834 // Is the current token one of the keywords that signals an old-style
835 // closure type (with explicit sigil)?
836 pub fn token_is_old_style_closure_keyword(&mut self) -> bool {
837 token::is_keyword(keywords::Unsafe, &self.token) ||
838 token::is_keyword(keywords::Once, &self.token) ||
839 token::is_keyword(keywords::Fn, &self.token)
842 pub fn token_is_lifetime(tok: &token::Token) -> bool {
844 token::LIFETIME(..) => true,
849 pub fn get_lifetime(&mut self) -> ast::Ident {
851 token::LIFETIME(ref ident) => *ident,
852 _ => self.bug("not a lifetime"),
856 // parse a TyBareFn type:
857 pub fn parse_ty_bare_fn(&mut self) -> Ty_ {
860 [extern "ABI"] [unsafe] fn <'lt> (S) -> T
861 ^~~~^ ^~~~~~~^ ^~~~^ ^~^ ^
872 let opt_abis = self.parse_opt_abis();
873 let abis = opt_abis.unwrap_or(AbiSet::Rust());
874 let purity = self.parse_unsafety();
875 self.expect_keyword(keywords::Fn);
876 let (decl, lifetimes) = self.parse_ty_fn_decl(true);
877 return TyBareFn(@BareFnTy {
880 lifetimes: lifetimes,
885 // Parses a procedure type (`proc`). The initial `proc` keyword must
886 // already have been parsed.
887 pub fn parse_proc_type(&mut self) -> Ty_ {
888 let (decl, lifetimes) = self.parse_ty_fn_decl(false);
889 TyClosure(@ClosureTy {
896 lifetimes: lifetimes,
900 // parse a TyClosure type
901 pub fn parse_ty_closure(&mut self,
902 opt_sigil: Option<ast::Sigil>,
903 mut region: Option<ast::Lifetime>)
907 (&|~|@) ['r] [unsafe] [once] fn [:Bounds] <'lt> (S) -> T
908 ^~~~~~^ ^~~^ ^~~~~~~^ ^~~~~^ ^~~~~~~~^ ^~~~^ ^~^ ^
910 | | | | | | | Return type
911 | | | | | | Argument types
913 | | | | Closure bounds
914 | | | Once-ness (a.k.a., affine)
921 // At this point, the allocation type and lifetime bound have been
924 let purity = self.parse_unsafety();
925 let onceness = parse_onceness(self);
927 let (sigil, decl, lifetimes, bounds) = match opt_sigil {
929 // Old-style closure syntax (`fn(A)->B`).
930 self.expect_keyword(keywords::Fn);
931 let bounds = self.parse_optional_ty_param_bounds();
932 let (decl, lifetimes) = self.parse_ty_fn_decl(false);
933 (sigil, decl, lifetimes, bounds)
936 // New-style closure syntax (`<'lt>|A|:K -> B`).
937 let lifetimes = if self.eat(&token::LT) {
938 let lifetimes = self.parse_lifetimes();
941 // Re-parse the region here. What a hack.
942 if region.is_some() {
943 self.span_err(self.last_span,
944 "lifetime declarations must precede \
945 the lifetime associated with a \
948 region = self.parse_opt_lifetime();
955 let inputs = if self.eat(&token::OROR) {
959 let inputs = self.parse_seq_to_before_or(
961 |p| p.parse_arg_general(false));
966 let bounds = self.parse_optional_ty_param_bounds();
968 let (return_style, output) = self.parse_ret_ty();
969 let decl = P(FnDecl {
976 (BorrowedSigil, decl, lifetimes, bounds)
980 return TyClosure(@ClosureTy {
987 lifetimes: lifetimes,
990 fn parse_onceness(this: &mut Parser) -> Onceness {
991 if this.eat_keyword(keywords::Once) {
999 pub fn parse_unsafety(&mut self) -> Purity {
1000 if self.eat_keyword(keywords::Unsafe) {
1007 // parse a function type (following the 'fn')
1008 pub fn parse_ty_fn_decl(&mut self, allow_variadic: bool)
1009 -> (P<FnDecl>, OptVec<ast::Lifetime>) {
1020 let lifetimes = if self.eat(&token::LT) {
1021 let lifetimes = self.parse_lifetimes();
1028 let (inputs, variadic) = self.parse_fn_args(false, allow_variadic);
1029 let (ret_style, ret_ty) = self.parse_ret_ty();
1030 let decl = P(FnDecl {
1039 // parse the methods in a trait declaration
1040 pub fn parse_trait_methods(&mut self) -> ~[TraitMethod] {
1041 self.parse_unspanned_seq(
1046 let attrs = p.parse_outer_attributes();
1049 let vis_span = p.span;
1050 let vis = p.parse_visibility();
1051 let pur = p.parse_fn_purity();
1052 // NB: at the moment, trait methods are public by default; this
1054 let ident = p.parse_ident();
1056 let generics = p.parse_generics();
1058 let (explicit_self, d) = p.parse_fn_decl_with_self(|p| {
1059 // This is somewhat dubious; We don't want to allow argument
1060 // names to be left off if there is a definition...
1061 p.parse_arg_general(false)
1064 let hi = p.last_span.hi;
1068 debug!("parse_trait_methods(): parsing required method");
1069 // NB: at the moment, visibility annotations on required
1070 // methods are ignored; this could change.
1071 if vis != ast::Inherited {
1072 p.obsolete(vis_span, ObsoleteTraitFuncVisibility);
1074 Required(TypeMethod {
1080 explicit_self: explicit_self,
1081 id: ast::DUMMY_NODE_ID,
1086 debug!("parse_trait_methods(): parsing provided method");
1087 let (inner_attrs, body) =
1088 p.parse_inner_attrs_and_block();
1089 let attrs = vec::append(attrs, inner_attrs);
1090 Provided(@ast::Method {
1094 explicit_self: explicit_self,
1098 id: ast::DUMMY_NODE_ID,
1099 span: mk_sp(lo, hi),
1105 let token_str = p.this_token_to_str();
1106 p.fatal(format!("expected `;` or `\\{` but found `{}`",
1113 // parse a possibly mutable type
1114 pub fn parse_mt(&mut self) -> MutTy {
1115 let mutbl = self.parse_mutability();
1116 let t = self.parse_ty(false);
1117 MutTy { ty: t, mutbl: mutbl }
1120 // parse [mut/const/imm] ID : TY
1121 // now used only by obsolete record syntax parser...
1122 pub fn parse_ty_field(&mut self) -> TypeField {
1123 let lo = self.span.lo;
1124 let mutbl = self.parse_mutability();
1125 let id = self.parse_ident();
1126 self.expect(&token::COLON);
1127 let ty = self.parse_ty(false);
1128 let hi = ty.span.hi;
1131 mt: MutTy { ty: ty, mutbl: mutbl },
1132 span: mk_sp(lo, hi),
1136 // parse optional return type [ -> TY ] in function decl
1137 pub fn parse_ret_ty(&mut self) -> (RetStyle, P<Ty>) {
1138 return if self.eat(&token::RARROW) {
1139 let lo = self.span.lo;
1140 if self.eat(&token::NOT) {
1144 id: ast::DUMMY_NODE_ID,
1146 span: mk_sp(lo, self.last_span.hi)
1150 (Return, self.parse_ty(false))
1153 let pos = self.span.lo;
1157 id: ast::DUMMY_NODE_ID,
1159 span: mk_sp(pos, pos),
1166 // Useless second parameter for compatibility with quasiquote macros.
1168 pub fn parse_ty(&mut self, _: bool) -> P<Ty> {
1169 maybe_whole!(no_clone self, NtTy);
1171 let lo = self.span.lo;
1173 let t = if self.token == token::LPAREN {
1175 if self.token == token::RPAREN {
1179 // (t) is a parenthesized ty
1180 // (t,) is the type of a tuple with only one field,
1182 let mut ts = ~[self.parse_ty(false)];
1183 let mut one_tuple = false;
1184 while self.token == token::COMMA {
1186 if self.token != token::RPAREN {
1187 ts.push(self.parse_ty(false));
1194 if ts.len() == 1 && !one_tuple {
1195 self.expect(&token::RPAREN);
1200 self.expect(&token::RPAREN);
1203 } else if self.token == token::AT {
1206 self.parse_box_or_uniq_pointee(ManagedSigil)
1207 } else if self.token == token::TILDE {
1210 self.parse_box_or_uniq_pointee(OwnedSigil)
1211 } else if self.token == token::BINOP(token::STAR) {
1212 // STAR POINTER (bare pointer?)
1214 TyPtr(self.parse_mt())
1215 } else if self.token == token::LBRACKET {
1217 self.expect(&token::LBRACKET);
1218 let t = self.parse_ty(false);
1220 // Parse the `, ..e` in `[ int, ..e ]`
1221 // where `e` is a const expression
1222 let t = match self.maybe_parse_fixed_vstore() {
1224 Some(suffix) => TyFixedLengthVec(t, suffix)
1226 self.expect(&token::RBRACKET);
1228 } else if self.token == token::BINOP(token::AND) {
1231 self.parse_borrowed_pointee()
1232 } else if self.is_keyword(keywords::Extern) ||
1233 self.token_is_bare_fn_keyword() {
1235 self.parse_ty_bare_fn()
1236 } else if self.token_is_closure_keyword() ||
1237 self.token == token::BINOP(token::OR) ||
1238 self.token == token::OROR ||
1239 self.token == token::LT ||
1240 Parser::token_is_lifetime(&self.token) {
1243 // FIXME(pcwalton): Eventually `token::LT` will not unambiguously
1244 // introduce a closure, once procs can have lifetime bounds. We
1245 // will need to refactor the grammar a little bit at that point.
1247 let lifetime = self.parse_opt_lifetime();
1248 let result = self.parse_ty_closure(None, lifetime);
1250 } else if self.eat_keyword(keywords::Typeof) {
1252 // In order to not be ambiguous, the type must be surrounded by parens.
1253 self.expect(&token::LPAREN);
1254 let e = self.parse_expr();
1255 self.expect(&token::RPAREN);
1257 } else if self.eat_keyword(keywords::Proc) {
1258 self.parse_proc_type()
1259 } else if self.token == token::MOD_SEP
1260 || is_ident_or_path(&self.token) {
1265 } = self.parse_path(LifetimeAndTypesAndBounds);
1266 TyPath(path, bounds, ast::DUMMY_NODE_ID)
1268 let msg = format!("expected type, found token {:?}", self.token);
1272 let sp = mk_sp(lo, self.last_span.hi);
1273 P(Ty {id: ast::DUMMY_NODE_ID, node: t, span: sp})
1276 // parse the type following a @ or a ~
1277 pub fn parse_box_or_uniq_pointee(&mut self,
1280 // ~'foo fn() or ~fn() are parsed directly as obsolete fn types:
1282 token::LIFETIME(..) => {
1283 let lifetime = self.parse_lifetime();
1284 self.obsolete(self.last_span, ObsoleteBoxedClosure);
1285 return self.parse_ty_closure(Some(sigil), Some(lifetime));
1288 token::IDENT(..) => {
1289 if self.token_is_old_style_closure_keyword() {
1290 self.obsolete(self.last_span, ObsoleteBoxedClosure);
1291 return self.parse_ty_closure(Some(sigil), None);
1297 // other things are parsed as @/~ + a type. Note that constructs like
1298 // @[] and @str will be resolved during typeck to slices and so forth,
1299 // rather than boxed ptrs. But the special casing of str/vec is not
1300 // reflected in the AST type.
1301 if sigil == OwnedSigil {
1302 TyUniq(self.parse_ty(false))
1304 TyBox(self.parse_ty(false))
1308 pub fn parse_borrowed_pointee(&mut self) -> Ty_ {
1309 // look for `&'lt` or `&'foo ` and interpret `foo` as the region name:
1310 let opt_lifetime = self.parse_opt_lifetime();
1312 if self.token_is_old_style_closure_keyword() {
1313 self.obsolete(self.last_span, ObsoleteClosureType);
1314 return self.parse_ty_closure(Some(BorrowedSigil), opt_lifetime);
1317 let mt = self.parse_mt();
1318 return TyRptr(opt_lifetime, mt);
1321 pub fn is_named_argument(&mut self) -> bool {
1322 let offset = match self.token {
1323 token::BINOP(token::AND) => 1,
1325 _ if token::is_keyword(keywords::Mut, &self.token) => 1,
1329 debug!("parser is_named_argument offset:{}", offset);
1332 is_plain_ident_or_underscore(&self.token)
1333 && self.look_ahead(1, |t| *t == token::COLON)
1335 self.look_ahead(offset, |t| is_plain_ident_or_underscore(t))
1336 && self.look_ahead(offset + 1, |t| *t == token::COLON)
1340 // This version of parse arg doesn't necessarily require
1341 // identifier names.
1342 pub fn parse_arg_general(&mut self, require_name: bool) -> Arg {
1343 let pat = if require_name || self.is_named_argument() {
1344 debug!("parse_arg_general parse_pat (require_name:{:?})",
1346 let pat = self.parse_pat();
1348 self.expect(&token::COLON);
1351 debug!("parse_arg_general ident_to_pat");
1352 ast_util::ident_to_pat(ast::DUMMY_NODE_ID,
1354 special_idents::invalid)
1357 let t = self.parse_ty(false);
1362 id: ast::DUMMY_NODE_ID,
1366 // parse a single function argument
1367 pub fn parse_arg(&mut self) -> Arg {
1368 self.parse_arg_general(true)
1371 // parse an argument in a lambda header e.g. |arg, arg|
1372 pub fn parse_fn_block_arg(&mut self) -> Arg {
1373 let pat = self.parse_pat();
1374 let t = if self.eat(&token::COLON) {
1375 self.parse_ty(false)
1378 id: ast::DUMMY_NODE_ID,
1380 span: mk_sp(self.span.lo, self.span.hi),
1386 id: ast::DUMMY_NODE_ID
1390 pub fn maybe_parse_fixed_vstore(&mut self) -> Option<@ast::Expr> {
1391 if self.token == token::COMMA &&
1392 self.look_ahead(1, |t| *t == token::DOTDOT) {
1395 Some(self.parse_expr())
1401 // matches token_lit = LIT_INT | ...
1402 pub fn lit_from_token(&mut self, tok: &token::Token) -> Lit_ {
1404 token::LIT_CHAR(i) => LitChar(i),
1405 token::LIT_INT(i, it) => LitInt(i, it),
1406 token::LIT_UINT(u, ut) => LitUint(u, ut),
1407 token::LIT_INT_UNSUFFIXED(i) => LitIntUnsuffixed(i),
1408 token::LIT_FLOAT(s, ft) => {
1409 LitFloat(self.id_to_interned_str(s), ft)
1411 token::LIT_FLOAT_UNSUFFIXED(s) => {
1412 LitFloatUnsuffixed(self.id_to_interned_str(s))
1414 token::LIT_STR(s) => {
1415 LitStr(self.id_to_interned_str(s), ast::CookedStr)
1417 token::LIT_STR_RAW(s, n) => {
1418 LitStr(self.id_to_interned_str(s), ast::RawStr(n))
1420 token::LPAREN => { self.expect(&token::RPAREN); LitNil },
1421 _ => { self.unexpected_last(tok); }
1425 // matches lit = true | false | token_lit
1426 pub fn parse_lit(&mut self) -> Lit {
1427 let lo = self.span.lo;
1428 let lit = if self.eat_keyword(keywords::True) {
1430 } else if self.eat_keyword(keywords::False) {
1433 let token = self.bump_and_get();
1434 let lit = self.lit_from_token(&token);
1437 codemap::Spanned { node: lit, span: mk_sp(lo, self.last_span.hi) }
1440 // matches '-' lit | lit
1441 pub fn parse_literal_maybe_minus(&mut self) -> @Expr {
1442 let minus_lo = self.span.lo;
1443 let minus_present = self.eat(&token::BINOP(token::MINUS));
1445 let lo = self.span.lo;
1446 let literal = @self.parse_lit();
1447 let hi = self.span.hi;
1448 let expr = self.mk_expr(lo, hi, ExprLit(literal));
1451 let minus_hi = self.span.hi;
1452 let unary = self.mk_unary(UnNeg, expr);
1453 self.mk_expr(minus_lo, minus_hi, unary)
1459 /// Parses a path and optional type parameter bounds, depending on the
1460 /// mode. The `mode` parameter determines whether lifetimes, types, and/or
1461 /// bounds are permitted and whether `::` must precede type parameter
1463 pub fn parse_path(&mut self, mode: PathParsingMode) -> PathAndBounds {
1464 // Check for a whole path...
1465 let found = match self.token {
1466 INTERPOLATED(token::NtPath(_)) => Some(self.bump_and_get()),
1470 Some(INTERPOLATED(token::NtPath(~path))) => {
1471 return PathAndBounds {
1479 let lo = self.span.lo;
1480 let is_global = self.eat(&token::MOD_SEP);
1482 // Parse any number of segments and bound sets. A segment is an
1483 // identifier followed by an optional lifetime and a set of types.
1484 // A bound set is a set of type parameter bounds.
1485 let mut segments = ~[];
1487 // First, parse an identifier.
1488 let identifier = self.parse_ident();
1490 // Next, parse a colon and bounded type parameters, if applicable.
1491 let bound_set = if mode == LifetimeAndTypesAndBounds {
1492 self.parse_optional_ty_param_bounds()
1497 // Parse the '::' before type parameters if it's required. If
1498 // it is required and wasn't present, then we're done.
1499 if mode == LifetimeAndTypesWithColons &&
1500 !self.eat(&token::MOD_SEP) {
1501 segments.push(PathSegmentAndBoundSet {
1502 segment: ast::PathSegment {
1503 identifier: identifier,
1504 lifetimes: opt_vec::Empty,
1505 types: opt_vec::Empty,
1507 bound_set: bound_set
1512 // Parse the `<` before the lifetime and types, if applicable.
1513 let (any_lifetime_or_types, lifetimes, types) = {
1514 if mode != NoTypesAllowed && self.eat(&token::LT) {
1515 let (lifetimes, types) =
1516 self.parse_generic_values_after_lt();
1517 (true, lifetimes, opt_vec::from(types))
1519 (false, opt_vec::Empty, opt_vec::Empty)
1523 // Assemble and push the result.
1524 segments.push(PathSegmentAndBoundSet {
1525 segment: ast::PathSegment {
1526 identifier: identifier,
1527 lifetimes: lifetimes,
1530 bound_set: bound_set
1533 // We're done if we don't see a '::', unless the mode required
1534 // a double colon to get here in the first place.
1535 if !(mode == LifetimeAndTypesWithColons &&
1536 !any_lifetime_or_types) {
1537 if !self.eat(&token::MOD_SEP) {
1543 // Assemble the span.
1544 let span = mk_sp(lo, self.last_span.hi);
1546 // Assemble the path segments.
1547 let mut path_segments = ~[];
1548 let mut bounds = None;
1549 let last_segment_index = segments.len() - 1;
1550 for (i, segment_and_bounds) in segments.move_iter().enumerate() {
1551 let PathSegmentAndBoundSet {
1553 bound_set: bound_set
1554 } = segment_and_bounds;
1555 path_segments.push(segment);
1557 if bound_set.is_some() {
1558 if i != last_segment_index {
1560 "type parameter bounds are allowed only \
1561 before the last segment in a path")
1568 // Assemble the result.
1569 let path_and_bounds = PathAndBounds {
1573 segments: path_segments,
1581 /// parses 0 or 1 lifetime
1582 pub fn parse_opt_lifetime(&mut self) -> Option<ast::Lifetime> {
1584 token::LIFETIME(..) => {
1585 Some(self.parse_lifetime())
1593 /// Parses a single lifetime
1594 // matches lifetime = LIFETIME
1595 pub fn parse_lifetime(&mut self) -> ast::Lifetime {
1597 token::LIFETIME(i) => {
1598 let span = self.span;
1600 return ast::Lifetime {
1601 id: ast::DUMMY_NODE_ID,
1607 self.fatal(format!("Expected a lifetime name"));
1612 // matches lifetimes = ( lifetime ) | ( lifetime , lifetimes )
1613 // actually, it matches the empty one too, but putting that in there
1614 // messes up the grammar....
1615 pub fn parse_lifetimes(&mut self) -> OptVec<ast::Lifetime> {
1618 * Parses zero or more comma separated lifetimes.
1619 * Expects each lifetime to be followed by either
1620 * a comma or `>`. Used when parsing type parameter
1621 * lists, where we expect something like `<'a, 'b, T>`.
1624 let mut res = opt_vec::Empty;
1627 token::LIFETIME(_) => {
1628 res.push(self.parse_lifetime());
1636 token::COMMA => { self.bump();}
1637 token::GT => { return res; }
1638 token::BINOP(token::SHR) => { return res; }
1640 let msg = format!("expected `,` or `>` after lifetime \
1649 pub fn token_is_mutability(tok: &token::Token) -> bool {
1650 token::is_keyword(keywords::Mut, tok) ||
1651 token::is_keyword(keywords::Const, tok)
1654 // parse mutability declaration (mut/const/imm)
1655 pub fn parse_mutability(&mut self) -> Mutability {
1656 if self.eat_keyword(keywords::Mut) {
1658 } else if self.eat_keyword(keywords::Const) {
1659 self.obsolete(self.last_span, ObsoleteConstPointer);
1666 // parse ident COLON expr
1667 pub fn parse_field(&mut self) -> Field {
1668 let lo = self.span.lo;
1669 let i = self.parse_ident();
1670 let hi = self.last_span.hi;
1671 self.expect(&token::COLON);
1672 let e = self.parse_expr();
1674 ident: spanned(lo, hi, i),
1676 span: mk_sp(lo, e.span.hi),
1680 pub fn mk_expr(&mut self, lo: BytePos, hi: BytePos, node: Expr_) -> @Expr {
1682 id: ast::DUMMY_NODE_ID,
1684 span: mk_sp(lo, hi),
1688 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: @Expr) -> ast::Expr_ {
1689 ExprUnary(ast::DUMMY_NODE_ID, unop, expr)
1692 pub fn mk_binary(&mut self, binop: ast::BinOp, lhs: @Expr, rhs: @Expr) -> ast::Expr_ {
1693 ExprBinary(ast::DUMMY_NODE_ID, binop, lhs, rhs)
1696 pub fn mk_call(&mut self, f: @Expr, args: ~[@Expr], sugar: CallSugar) -> ast::Expr_ {
1697 ExprCall(f, args, sugar)
1700 fn mk_method_call(&mut self, ident: Ident, tps: ~[P<Ty>], args: ~[@Expr],
1701 sugar: CallSugar) -> ast::Expr_ {
1702 ExprMethodCall(ast::DUMMY_NODE_ID, ident, tps, args, sugar)
1705 pub fn mk_index(&mut self, expr: @Expr, idx: @Expr) -> ast::Expr_ {
1706 ExprIndex(ast::DUMMY_NODE_ID, expr, idx)
1709 pub fn mk_field(&mut self, expr: @Expr, ident: Ident, tys: ~[P<Ty>]) -> ast::Expr_ {
1710 ExprField(expr, ident, tys)
1713 pub fn mk_assign_op(&mut self, binop: ast::BinOp, lhs: @Expr, rhs: @Expr) -> ast::Expr_ {
1714 ExprAssignOp(ast::DUMMY_NODE_ID, binop, lhs, rhs)
1717 pub fn mk_mac_expr(&mut self, lo: BytePos, hi: BytePos, m: Mac_) -> @Expr {
1719 id: ast::DUMMY_NODE_ID,
1720 node: ExprMac(codemap::Spanned {node: m, span: mk_sp(lo, hi)}),
1721 span: mk_sp(lo, hi),
1725 pub fn mk_lit_u32(&mut self, i: u32) -> @Expr {
1726 let span = &self.span;
1727 let lv_lit = @codemap::Spanned {
1728 node: LitUint(i as u64, TyU32),
1733 id: ast::DUMMY_NODE_ID,
1734 node: ExprLit(lv_lit),
1739 // at the bottom (top?) of the precedence hierarchy,
1740 // parse things like parenthesized exprs,
1741 // macros, return, etc.
1742 pub fn parse_bottom_expr(&mut self) -> @Expr {
1743 maybe_whole_expr!(self);
1745 let lo = self.span.lo;
1746 let mut hi = self.span.hi;
1750 if self.token == token::LPAREN {
1752 // (e) is parenthesized e
1753 // (e,) is a tuple with only one field, e
1754 let mut trailing_comma = false;
1755 if self.token == token::RPAREN {
1758 let lit = @spanned(lo, hi, LitNil);
1759 return self.mk_expr(lo, hi, ExprLit(lit));
1761 let mut es = ~[self.parse_expr()];
1762 self.commit_expr(*es.last().unwrap(), &[], &[token::COMMA, token::RPAREN]);
1763 while self.token == token::COMMA {
1765 if self.token != token::RPAREN {
1766 es.push(self.parse_expr());
1767 self.commit_expr(*es.last().unwrap(), &[], &[token::COMMA, token::RPAREN]);
1770 trailing_comma = true;
1774 self.commit_expr_expecting(*es.last().unwrap(), token::RPAREN);
1776 return if es.len() == 1 && !trailing_comma {
1777 self.mk_expr(lo, self.span.hi, ExprParen(es[0]))
1780 self.mk_expr(lo, hi, ExprTup(es))
1782 } else if self.token == token::LBRACE {
1784 let blk = self.parse_block_tail(lo, DefaultBlock);
1785 return self.mk_expr(blk.span.lo, blk.span.hi,
1787 } else if token::is_bar(&self.token) {
1788 return self.parse_lambda_expr();
1789 } else if self.eat_keyword(keywords::Proc) {
1790 let decl = self.parse_proc_decl();
1791 let body = self.parse_expr();
1792 let fakeblock = P(ast::Block {
1796 id: ast::DUMMY_NODE_ID,
1797 rules: DefaultBlock,
1801 return self.mk_expr(lo, body.span.hi, ExprProc(decl, fakeblock));
1802 } else if self.eat_keyword(keywords::Self) {
1803 let path = ast_util::ident_to_path(mk_sp(lo, hi), special_idents::self_);
1804 ex = ExprPath(path);
1806 } else if self.eat_keyword(keywords::If) {
1807 return self.parse_if_expr();
1808 } else if self.eat_keyword(keywords::For) {
1809 return self.parse_for_expr(None);
1810 } else if self.eat_keyword(keywords::While) {
1811 return self.parse_while_expr();
1812 } else if Parser::token_is_lifetime(&self.token) {
1813 let lifetime = self.get_lifetime();
1815 self.expect(&token::COLON);
1816 if self.eat_keyword(keywords::For) {
1817 return self.parse_for_expr(Some(lifetime))
1818 } else if self.eat_keyword(keywords::Loop) {
1819 return self.parse_loop_expr(Some(lifetime))
1821 self.fatal("expected `for` or `loop` after a label")
1823 } else if self.eat_keyword(keywords::Loop) {
1824 return self.parse_loop_expr(None);
1825 } else if self.eat_keyword(keywords::Continue) {
1826 let lo = self.span.lo;
1827 let ex = if Parser::token_is_lifetime(&self.token) {
1828 let lifetime = self.get_lifetime();
1830 ExprAgain(Some(lifetime.name))
1834 let hi = self.span.hi;
1835 return self.mk_expr(lo, hi, ex);
1836 } else if self.eat_keyword(keywords::Match) {
1837 return self.parse_match_expr();
1838 } else if self.eat_keyword(keywords::Unsafe) {
1839 return self.parse_block_expr(lo, UnsafeBlock(ast::UserProvided));
1840 } else if self.token == token::LBRACKET {
1842 let mutbl = MutImmutable;
1844 if self.token == token::RBRACKET {
1847 ex = ExprVec(~[], mutbl);
1850 let first_expr = self.parse_expr();
1851 if self.token == token::COMMA &&
1852 self.look_ahead(1, |t| *t == token::DOTDOT) {
1853 // Repeating vector syntax: [ 0, ..512 ]
1856 let count = self.parse_expr();
1857 self.expect(&token::RBRACKET);
1858 ex = ExprRepeat(first_expr, count, mutbl);
1859 } else if self.token == token::COMMA {
1860 // Vector with two or more elements.
1862 let remaining_exprs = self.parse_seq_to_end(
1864 seq_sep_trailing_allowed(token::COMMA),
1867 ex = ExprVec(~[first_expr] + remaining_exprs, mutbl);
1869 // Vector with one element.
1870 self.expect(&token::RBRACKET);
1871 ex = ExprVec(~[first_expr], mutbl);
1874 hi = self.last_span.hi;
1875 } else if self.eat_keyword(keywords::__LogLevel) {
1876 // LOG LEVEL expression
1877 self.expect(&token::LPAREN);
1880 self.expect(&token::RPAREN);
1881 } else if self.eat_keyword(keywords::Return) {
1882 // RETURN expression
1883 if can_begin_expr(&self.token) {
1884 let e = self.parse_expr();
1886 ex = ExprRet(Some(e));
1887 } else { ex = ExprRet(None); }
1888 } else if self.eat_keyword(keywords::Break) {
1890 if Parser::token_is_lifetime(&self.token) {
1891 let lifetime = self.get_lifetime();
1893 ex = ExprBreak(Some(lifetime.name));
1895 ex = ExprBreak(None);
1898 } else if self.token == token::MOD_SEP ||
1899 is_ident(&self.token) && !self.is_keyword(keywords::True) &&
1900 !self.is_keyword(keywords::False) {
1901 let pth = self.parse_path(LifetimeAndTypesWithColons).path;
1903 // `!`, as an operator, is prefix, so we know this isn't that
1904 if self.token == token::NOT {
1905 // MACRO INVOCATION expression
1908 token::LPAREN | token::LBRACE => {}
1909 _ => self.fatal("expected open delimiter")
1912 let ket = token::flip_delimiter(&self.token);
1915 let tts = self.parse_seq_to_end(&ket,
1917 |p| p.parse_token_tree());
1918 let hi = self.span.hi;
1920 return self.mk_mac_expr(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT));
1921 } else if self.token == token::LBRACE {
1922 // This might be a struct literal.
1923 if self.looking_at_struct_literal() {
1924 // It's a struct literal.
1926 let mut fields = ~[];
1927 let mut base = None;
1929 while self.token != token::RBRACE {
1930 if self.eat(&token::DOTDOT) {
1931 base = Some(self.parse_expr());
1935 fields.push(self.parse_field());
1936 self.commit_expr(fields.last().unwrap().expr,
1937 &[token::COMMA], &[token::RBRACE]);
1941 self.expect(&token::RBRACE);
1942 ex = ExprStruct(pth, fields, base);
1943 return self.mk_expr(lo, hi, ex);
1950 // other literal expression
1951 let lit = self.parse_lit();
1956 return self.mk_expr(lo, hi, ex);
1959 // parse a block or unsafe block
1960 pub fn parse_block_expr(&mut self, lo: BytePos, blk_mode: BlockCheckMode)
1962 self.expect(&token::LBRACE);
1963 let blk = self.parse_block_tail(lo, blk_mode);
1964 return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk));
1967 // parse a.b or a(13) or a[4] or just a
1968 pub fn parse_dot_or_call_expr(&mut self) -> @Expr {
1969 let b = self.parse_bottom_expr();
1970 self.parse_dot_or_call_expr_with(b)
1973 pub fn parse_dot_or_call_expr_with(&mut self, e0: @Expr) -> @Expr {
1979 if self.eat(&token::DOT) {
1981 token::IDENT(i, _) => {
1984 let (_, tys) = if self.eat(&token::MOD_SEP) {
1985 self.expect(&token::LT);
1986 self.parse_generic_values_after_lt()
1988 (opt_vec::Empty, ~[])
1991 // expr.f() method call
1994 let mut es = self.parse_unspanned_seq(
1997 seq_sep_trailing_disallowed(token::COMMA),
2003 let nd = self.mk_method_call(i, tys, es, NoSugar);
2004 e = self.mk_expr(lo, hi, nd);
2007 let field = self.mk_field(e, i, tys);
2008 e = self.mk_expr(lo, hi, field)
2012 _ => self.unexpected()
2016 if self.expr_is_complete(e) { break; }
2020 let es = self.parse_unspanned_seq(
2023 seq_sep_trailing_allowed(token::COMMA),
2026 hi = self.last_span.hi;
2028 let nd = self.mk_call(e, es, NoSugar);
2029 e = self.mk_expr(lo, hi, nd);
2033 token::LBRACKET => {
2035 let ix = self.parse_expr();
2037 self.commit_expr_expecting(ix, token::RBRACKET);
2038 let index = self.mk_index(e, ix);
2039 e = self.mk_expr(lo, hi, index)
2048 // parse an optional separator followed by a kleene-style
2049 // repetition token (+ or *).
2050 pub fn parse_sep_and_zerok(&mut self) -> (Option<token::Token>, bool) {
2051 fn parse_zerok(parser: &mut Parser) -> Option<bool> {
2052 match parser.token {
2053 token::BINOP(token::STAR) | token::BINOP(token::PLUS) => {
2054 let zerok = parser.token == token::BINOP(token::STAR);
2062 match parse_zerok(self) {
2063 Some(zerok) => return (None, zerok),
2067 let separator = self.bump_and_get();
2068 match parse_zerok(self) {
2069 Some(zerok) => (Some(separator), zerok),
2070 None => self.fatal("expected `*` or `+`")
2074 // parse a single token tree from the input.
2075 pub fn parse_token_tree(&mut self) -> TokenTree {
2076 // FIXME #6994: currently, this is too eager. It
2077 // parses token trees but also identifies TTSeq's
2078 // and TTNonterminal's; it's too early to know yet
2079 // whether something will be a nonterminal or a seq
2081 maybe_whole!(deref self, NtTT);
2083 // this is the fall-through for the 'match' below.
2084 // invariants: the current token is not a left-delimiter,
2085 // not an EOF, and not the desired right-delimiter (if
2086 // it were, parse_seq_to_before_end would have prevented
2087 // reaching this point.
2088 fn parse_non_delim_tt_tok(p: &mut Parser) -> TokenTree {
2089 maybe_whole!(deref p, NtTT);
2091 token::RPAREN | token::RBRACE | token::RBRACKET => {
2092 // This is a conservative error: only report the last unclosed delimiter. The
2093 // previous unclosed delimiters could actually be closed! The parser just hasn't
2094 // gotten to them yet.
2095 match p.open_braces.last() {
2097 Some(&sp) => p.span_note(sp, "unclosed delimiter"),
2099 let token_str = p.this_token_to_str();
2100 p.fatal(format!("incorrect close delimiter: `{}`",
2103 /* we ought to allow different depths of unquotation */
2104 token::DOLLAR if p.quote_depth > 0u => {
2108 if p.token == token::LPAREN {
2109 let seq = p.parse_seq(
2113 |p| p.parse_token_tree()
2115 let (s, z) = p.parse_sep_and_zerok();
2116 let seq = match seq {
2117 Spanned { node, .. } => node,
2119 TTSeq(mk_sp(sp.lo, p.span.hi), @seq, s, z)
2121 TTNonterminal(sp, p.parse_ident())
2130 // turn the next token into a TTTok:
2131 fn parse_any_tt_tok(p: &mut Parser) -> TokenTree {
2132 TTTok(p.span, p.bump_and_get())
2137 let open_braces = self.open_braces.clone();
2138 for sp in open_braces.iter() {
2139 self.span_note(*sp, "Did you mean to close this delimiter?");
2141 // There shouldn't really be a span, but it's easier for the test runner
2142 // if we give it one
2143 self.fatal("This file contains an un-closed delimiter ");
2145 token::LPAREN | token::LBRACE | token::LBRACKET => {
2146 let close_delim = token::flip_delimiter(&self.token);
2148 // Parse the open delimiter.
2149 self.open_braces.push(self.span);
2150 let mut result = ~[parse_any_tt_tok(self)];
2153 self.parse_seq_to_before_end(&close_delim,
2155 |p| p.parse_token_tree());
2156 result.push_all_move(trees);
2158 // Parse the close delimiter.
2159 result.push(parse_any_tt_tok(self));
2160 self.open_braces.pop().unwrap();
2164 _ => parse_non_delim_tt_tok(self)
2168 // parse a stream of tokens into a list of TokenTree's,
2170 pub fn parse_all_token_trees(&mut self) -> ~[TokenTree] {
2172 while self.token != token::EOF {
2173 tts.push(self.parse_token_tree());
2178 pub fn parse_matchers(&mut self) -> ~[Matcher] {
2179 // unification of Matcher's and TokenTree's would vastly improve
2180 // the interpolation of Matcher's
2181 maybe_whole!(self, NtMatchers);
2182 let name_idx = @Cell::new(0u);
2184 token::LBRACE | token::LPAREN | token::LBRACKET => {
2185 let other_delimiter = token::flip_delimiter(&self.token);
2187 self.parse_matcher_subseq_upto(name_idx, &other_delimiter)
2189 _ => self.fatal("expected open delimiter")
2193 // This goofy function is necessary to correctly match parens in Matcher's.
2194 // Otherwise, `$( ( )` would be a valid Matcher, and `$( () )` would be
2195 // invalid. It's similar to common::parse_seq.
2196 pub fn parse_matcher_subseq_upto(&mut self,
2197 name_idx: @Cell<uint>,
2200 let mut ret_val = ~[];
2201 let mut lparens = 0u;
2203 while self.token != *ket || lparens > 0u {
2204 if self.token == token::LPAREN { lparens += 1u; }
2205 if self.token == token::RPAREN { lparens -= 1u; }
2206 ret_val.push(self.parse_matcher(name_idx));
2214 pub fn parse_matcher(&mut self, name_idx: @Cell<uint>) -> Matcher {
2215 let lo = self.span.lo;
2217 let m = if self.token == token::DOLLAR {
2219 if self.token == token::LPAREN {
2220 let name_idx_lo = name_idx.get();
2222 let ms = self.parse_matcher_subseq_upto(name_idx,
2225 self.fatal("repetition body must be nonempty");
2227 let (sep, zerok) = self.parse_sep_and_zerok();
2228 MatchSeq(ms, sep, zerok, name_idx_lo, name_idx.get())
2230 let bound_to = self.parse_ident();
2231 self.expect(&token::COLON);
2232 let nt_name = self.parse_ident();
2233 let m = MatchNonterminal(bound_to, nt_name, name_idx.get());
2234 name_idx.set(name_idx.get() + 1u);
2238 MatchTok(self.bump_and_get())
2241 return spanned(lo, self.span.hi, m);
2244 // parse a prefix-operator expr
2245 pub fn parse_prefix_expr(&mut self) -> @Expr {
2246 let lo = self.span.lo;
2253 let e = self.parse_prefix_expr();
2255 ex = self.mk_unary(UnNot, e);
2257 token::BINOP(b) => {
2261 let e = self.parse_prefix_expr();
2263 ex = self.mk_unary(UnNeg, e);
2267 let e = self.parse_prefix_expr();
2269 ex = self.mk_unary(UnDeref, e);
2273 let _lt = self.parse_opt_lifetime();
2274 let m = self.parse_mutability();
2275 let e = self.parse_prefix_expr();
2277 // HACK: turn &[...] into a &-vec
2279 ExprVec(..) if m == MutImmutable => {
2280 ExprVstore(e, ExprVstoreSlice)
2282 ExprLit(lit) if lit_is_str(lit) && m == MutImmutable => {
2283 ExprVstore(e, ExprVstoreSlice)
2285 ExprVec(..) if m == MutMutable => {
2286 ExprVstore(e, ExprVstoreMutSlice)
2288 _ => ExprAddrOf(m, e)
2291 _ => return self.parse_dot_or_call_expr()
2296 let e = self.parse_prefix_expr();
2298 // HACK: turn @[...] into a @-vec
2301 ExprRepeat(..) => ExprVstore(e, ExprVstoreBox),
2302 ExprLit(lit) if lit_is_str(lit) => ExprVstore(e, ExprVstoreBox),
2303 _ => self.mk_unary(UnBox, e)
2309 let e = self.parse_prefix_expr();
2311 // HACK: turn ~[...] into a ~-vec
2313 ExprVec(..) | ExprRepeat(..) => ExprVstore(e, ExprVstoreUniq),
2314 ExprLit(lit) if lit_is_str(lit) => {
2315 ExprVstore(e, ExprVstoreUniq)
2317 _ => self.mk_unary(UnUniq, e)
2320 token::IDENT(_, _) if self.is_keyword(keywords::Box) => {
2323 // Check for a place: `box(PLACE) EXPR`.
2324 if self.eat(&token::LPAREN) {
2325 // Support `box() EXPR` as the default.
2326 if !self.eat(&token::RPAREN) {
2327 let place = self.parse_expr();
2328 self.expect(&token::RPAREN);
2329 let subexpression = self.parse_prefix_expr();
2330 hi = subexpression.span.hi;
2331 ex = ExprBox(place, subexpression);
2332 return self.mk_expr(lo, hi, ex);
2336 // Otherwise, we use the unique pointer default.
2337 let subexpression = self.parse_prefix_expr();
2338 hi = subexpression.span.hi;
2339 // HACK: turn `box [...]` into a boxed-vec
2340 ex = match subexpression.node {
2341 ExprVec(..) | ExprRepeat(..) => {
2342 ExprVstore(subexpression, ExprVstoreUniq)
2344 ExprLit(lit) if lit_is_str(lit) => {
2345 ExprVstore(subexpression, ExprVstoreUniq)
2347 _ => self.mk_unary(UnUniq, subexpression)
2350 _ => return self.parse_dot_or_call_expr()
2352 return self.mk_expr(lo, hi, ex);
2355 // parse an expression of binops
2356 pub fn parse_binops(&mut self) -> @Expr {
2357 let prefix_expr = self.parse_prefix_expr();
2358 self.parse_more_binops(prefix_expr, 0)
2361 // parse an expression of binops of at least min_prec precedence
2362 pub fn parse_more_binops(&mut self, lhs: @Expr, min_prec: uint) -> @Expr {
2363 if self.expr_is_complete(lhs) { return lhs; }
2365 // Prevent dynamic borrow errors later on by limiting the
2366 // scope of the borrows.
2368 let token: &token::Token = &self.token;
2369 let restriction: &restriction = &self.restriction;
2370 match (token, restriction) {
2371 (&token::BINOP(token::OR), &RESTRICT_NO_BAR_OP) => return lhs,
2372 (&token::BINOP(token::OR),
2373 &RESTRICT_NO_BAR_OR_DOUBLEBAR_OP) => return lhs,
2374 (&token::OROR, &RESTRICT_NO_BAR_OR_DOUBLEBAR_OP) => return lhs,
2379 let cur_opt = token_to_binop(&self.token);
2382 let cur_prec = operator_prec(cur_op);
2383 if cur_prec > min_prec {
2385 let expr = self.parse_prefix_expr();
2386 let rhs = self.parse_more_binops(expr, cur_prec);
2387 let binary = self.mk_binary(cur_op, lhs, rhs);
2388 let bin = self.mk_expr(lhs.span.lo, rhs.span.hi, binary);
2389 self.parse_more_binops(bin, min_prec)
2395 if as_prec > min_prec && self.eat_keyword(keywords::As) {
2396 let rhs = self.parse_ty(true);
2397 let _as = self.mk_expr(lhs.span.lo,
2399 ExprCast(lhs, rhs));
2400 self.parse_more_binops(_as, min_prec)
2408 // parse an assignment expression....
2409 // actually, this seems to be the main entry point for
2410 // parsing an arbitrary expression.
2411 pub fn parse_assign_expr(&mut self) -> @Expr {
2412 let lo = self.span.lo;
2413 let lhs = self.parse_binops();
2417 let rhs = self.parse_expr();
2418 self.mk_expr(lo, rhs.span.hi, ExprAssign(lhs, rhs))
2420 token::BINOPEQ(op) => {
2422 let rhs = self.parse_expr();
2423 let aop = match op {
2424 token::PLUS => BiAdd,
2425 token::MINUS => BiSub,
2426 token::STAR => BiMul,
2427 token::SLASH => BiDiv,
2428 token::PERCENT => BiRem,
2429 token::CARET => BiBitXor,
2430 token::AND => BiBitAnd,
2431 token::OR => BiBitOr,
2432 token::SHL => BiShl,
2435 let assign_op = self.mk_assign_op(aop, lhs, rhs);
2436 self.mk_expr(lo, rhs.span.hi, assign_op)
2439 self.obsolete(self.span, ObsoleteSwap);
2441 // Ignore what we get, this is an error anyway
2443 self.mk_expr(lo, self.span.hi, ExprBreak(None))
2451 // parse an 'if' expression ('if' token already eaten)
2452 pub fn parse_if_expr(&mut self) -> @Expr {
2453 let lo = self.last_span.lo;
2454 let cond = self.parse_expr();
2455 let thn = self.parse_block();
2456 let mut els: Option<@Expr> = None;
2457 let mut hi = thn.span.hi;
2458 if self.eat_keyword(keywords::Else) {
2459 let elexpr = self.parse_else_expr();
2461 hi = elexpr.span.hi;
2463 self.mk_expr(lo, hi, ExprIf(cond, thn, els))
2466 // `|args| { ... }` or `{ ...}` like in `do` expressions
2467 pub fn parse_lambda_block_expr(&mut self) -> @Expr {
2468 self.parse_lambda_expr_(
2471 token::BINOP(token::OR) | token::OROR => {
2472 p.parse_fn_block_decl()
2475 // No argument list - `do foo {`
2479 id: ast::DUMMY_NODE_ID,
2490 let blk = p.parse_block();
2491 p.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk))
2496 pub fn parse_lambda_expr(&mut self) -> @Expr {
2497 self.parse_lambda_expr_(|p| p.parse_fn_block_decl(),
2501 // parse something of the form |args| expr
2502 // this is used both in parsing a lambda expr
2503 // and in parsing a block expr as e.g. in for...
2504 pub fn parse_lambda_expr_(&mut self,
2505 parse_decl: |&mut Parser| -> P<FnDecl>,
2506 parse_body: |&mut Parser| -> @Expr)
2508 let lo = self.last_span.lo;
2509 let decl = parse_decl(self);
2510 let body = parse_body(self);
2511 let fakeblock = P(ast::Block {
2515 id: ast::DUMMY_NODE_ID,
2516 rules: DefaultBlock,
2520 return self.mk_expr(lo, body.span.hi, ExprFnBlock(decl, fakeblock));
2523 pub fn parse_else_expr(&mut self) -> @Expr {
2524 if self.eat_keyword(keywords::If) {
2525 return self.parse_if_expr();
2527 let blk = self.parse_block();
2528 return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk));
2532 // parse a 'for' .. 'in' expression ('for' token already eaten)
2533 pub fn parse_for_expr(&mut self, opt_ident: Option<ast::Ident>) -> @Expr {
2534 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
2536 let lo = self.last_span.lo;
2537 let pat = self.parse_pat();
2538 self.expect_keyword(keywords::In);
2539 let expr = self.parse_expr();
2540 let loop_block = self.parse_block();
2541 let hi = self.span.hi;
2543 self.mk_expr(lo, hi, ExprForLoop(pat, expr, loop_block, opt_ident))
2546 pub fn parse_while_expr(&mut self) -> @Expr {
2547 let lo = self.last_span.lo;
2548 let cond = self.parse_expr();
2549 let body = self.parse_block();
2550 let hi = body.span.hi;
2551 return self.mk_expr(lo, hi, ExprWhile(cond, body));
2554 pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::Ident>) -> @Expr {
2555 // loop headers look like 'loop {' or 'loop unsafe {'
2556 let is_loop_header =
2557 self.token == token::LBRACE
2558 || (is_ident(&self.token)
2559 && self.look_ahead(1, |t| *t == token::LBRACE));
2562 // This is a loop body
2563 let lo = self.last_span.lo;
2564 let body = self.parse_block();
2565 let hi = body.span.hi;
2566 return self.mk_expr(lo, hi, ExprLoop(body, opt_ident));
2568 // This is an obsolete 'continue' expression
2569 if opt_ident.is_some() {
2570 self.span_err(self.last_span,
2571 "a label may not be used with a `loop` expression");
2574 self.obsolete(self.last_span, ObsoleteLoopAsContinue);
2575 let lo = self.span.lo;
2576 let ex = if Parser::token_is_lifetime(&self.token) {
2577 let lifetime = self.get_lifetime();
2579 ExprAgain(Some(lifetime.name))
2583 let hi = self.span.hi;
2584 return self.mk_expr(lo, hi, ex);
2588 // For distingishing between struct literals and blocks
2589 fn looking_at_struct_literal(&mut self) -> bool {
2590 self.token == token::LBRACE &&
2591 ((self.look_ahead(1, |t| token::is_plain_ident(t)) &&
2592 self.look_ahead(2, |t| *t == token::COLON))
2593 || self.look_ahead(1, |t| *t == token::DOTDOT))
2596 fn parse_match_expr(&mut self) -> @Expr {
2597 let lo = self.last_span.lo;
2598 let discriminant = self.parse_expr();
2599 self.commit_expr_expecting(discriminant, token::LBRACE);
2600 let mut arms: ~[Arm] = ~[];
2601 while self.token != token::RBRACE {
2602 let pats = self.parse_pats();
2603 let mut guard = None;
2604 if self.eat_keyword(keywords::If) {
2605 guard = Some(self.parse_expr());
2607 self.expect(&token::FAT_ARROW);
2608 let expr = self.parse_expr_res(RESTRICT_STMT_EXPR);
2611 !classify::expr_is_simple_block(expr)
2612 && self.token != token::RBRACE;
2615 self.commit_expr(expr, &[token::COMMA], &[token::RBRACE]);
2617 self.eat(&token::COMMA);
2620 let blk = P(ast::Block {
2624 id: ast::DUMMY_NODE_ID,
2625 rules: DefaultBlock,
2629 arms.push(ast::Arm { pats: pats, guard: guard, body: blk });
2631 let hi = self.span.hi;
2633 return self.mk_expr(lo, hi, ExprMatch(discriminant, arms));
2636 // parse an expression
2637 pub fn parse_expr(&mut self) -> @Expr {
2638 return self.parse_expr_res(UNRESTRICTED);
2641 // parse an expression, subject to the given restriction
2642 fn parse_expr_res(&mut self, r: restriction) -> @Expr {
2643 let old = self.restriction;
2644 self.restriction = r;
2645 let e = self.parse_assign_expr();
2646 self.restriction = old;
2650 // parse the RHS of a local variable declaration (e.g. '= 14;')
2651 fn parse_initializer(&mut self) -> Option<@Expr> {
2652 if self.token == token::EQ {
2654 Some(self.parse_expr())
2660 // parse patterns, separated by '|' s
2661 fn parse_pats(&mut self) -> ~[@Pat] {
2664 pats.push(self.parse_pat());
2665 if self.token == token::BINOP(token::OR) { self.bump(); }
2666 else { return pats; }
2670 fn parse_pat_vec_elements(
2672 ) -> (~[@Pat], Option<@Pat>, ~[@Pat]) {
2673 let mut before = ~[];
2674 let mut slice = None;
2675 let mut after = ~[];
2676 let mut first = true;
2677 let mut before_slice = true;
2679 while self.token != token::RBRACKET {
2680 if first { first = false; }
2681 else { self.expect(&token::COMMA); }
2683 let mut is_slice = false;
2685 if self.token == token::DOTDOT {
2688 before_slice = false;
2693 if self.token == token::COMMA || self.token == token::RBRACKET {
2694 slice = Some(@ast::Pat {
2695 id: ast::DUMMY_NODE_ID,
2700 let subpat = self.parse_pat();
2702 ast::Pat { id, node: PatWild, span } => {
2703 self.obsolete(self.span, ObsoleteVecDotDotWildcard);
2704 slice = Some(@ast::Pat {
2710 ast::Pat { node: PatIdent(_, _, _), .. } => {
2711 slice = Some(subpat);
2713 ast::Pat { span, .. } => self.span_fatal(
2714 span, "expected an identifier or nothing"
2719 let subpat = self.parse_pat();
2721 before.push(subpat);
2728 (before, slice, after)
2731 // parse the fields of a struct-like pattern
2732 fn parse_pat_fields(&mut self) -> (~[ast::FieldPat], bool) {
2733 let mut fields = ~[];
2734 let mut etc = false;
2735 let mut first = true;
2736 while self.token != token::RBRACE {
2740 self.expect(&token::COMMA);
2741 // accept trailing commas
2742 if self.token == token::RBRACE { break }
2745 etc = self.token == token::UNDERSCORE || self.token == token::DOTDOT;
2746 if self.token == token::UNDERSCORE {
2747 self.obsolete(self.span, ObsoleteStructWildcard);
2751 if self.token != token::RBRACE {
2752 let token_str = self.this_token_to_str();
2753 self.fatal(format!("expected `\\}`, found `{}`",
2760 let lo1 = self.last_span.lo;
2761 let bind_type = if self.eat_keyword(keywords::Mut) {
2762 BindByValue(MutMutable)
2763 } else if self.eat_keyword(keywords::Ref) {
2764 BindByRef(self.parse_mutability())
2766 BindByValue(MutImmutable)
2769 let fieldname = self.parse_ident();
2770 let hi1 = self.last_span.lo;
2771 let fieldpath = ast_util::ident_to_path(mk_sp(lo1, hi1),
2774 if self.token == token::COLON {
2776 BindByRef(..) | BindByValue(MutMutable) => {
2777 let token_str = self.this_token_to_str();
2778 self.fatal(format!("unexpected `{}`", token_str))
2784 subpat = self.parse_pat();
2786 subpat = @ast::Pat {
2787 id: ast::DUMMY_NODE_ID,
2788 node: PatIdent(bind_type, fieldpath, None),
2789 span: self.last_span
2792 fields.push(ast::FieldPat { ident: fieldname, pat: subpat });
2794 return (fields, etc);
2798 pub fn parse_pat(&mut self) -> @Pat {
2799 maybe_whole!(self, NtPat);
2801 let lo = self.span.lo;
2806 token::UNDERSCORE => {
2809 hi = self.last_span.hi;
2811 id: ast::DUMMY_NODE_ID,
2819 let sub = self.parse_pat();
2821 // HACK: parse @"..." as a literal of a vstore @str
2822 pat = match sub.node {
2825 ExprLit(lit) if lit_is_str(lit) => {
2827 id: ast::DUMMY_NODE_ID,
2828 node: ExprVstore(e, ExprVstoreBox),
2829 span: mk_sp(lo, hi),
2834 self.obsolete(self.span, ObsoleteManagedPattern);
2840 self.obsolete(self.span, ObsoleteManagedPattern);
2844 hi = self.last_span.hi;
2846 id: ast::DUMMY_NODE_ID,
2854 let sub = self.parse_pat();
2856 // HACK: parse ~"..." as a literal of a vstore ~str
2857 pat = match sub.node {
2860 ExprLit(lit) if lit_is_str(lit) => {
2862 id: ast::DUMMY_NODE_ID,
2863 node: ExprVstore(e, ExprVstoreUniq),
2864 span: mk_sp(lo, hi),
2873 hi = self.last_span.hi;
2875 id: ast::DUMMY_NODE_ID,
2880 token::BINOP(token::AND) => {
2882 let lo = self.span.lo;
2884 let sub = self.parse_pat();
2886 // HACK: parse &"..." as a literal of a borrowed str
2887 pat = match sub.node {
2890 ExprLit(lit) if lit_is_str(lit) => {
2892 id: ast::DUMMY_NODE_ID,
2893 node: ExprVstore(e, ExprVstoreSlice),
2898 _ => PatRegion(sub),
2901 _ => PatRegion(sub),
2903 hi = self.last_span.hi;
2905 id: ast::DUMMY_NODE_ID,
2911 // parse (pat,pat,pat,...) as tuple
2913 if self.token == token::RPAREN {
2916 let lit = @codemap::Spanned {
2918 span: mk_sp(lo, hi)};
2919 let expr = self.mk_expr(lo, hi, ExprLit(lit));
2922 let mut fields = ~[self.parse_pat()];
2923 if self.look_ahead(1, |t| *t != token::RPAREN) {
2924 while self.token == token::COMMA {
2926 if self.token == token::RPAREN { break; }
2927 fields.push(self.parse_pat());
2930 if fields.len() == 1 { self.expect(&token::COMMA); }
2931 self.expect(&token::RPAREN);
2932 pat = PatTup(fields);
2934 hi = self.last_span.hi;
2936 id: ast::DUMMY_NODE_ID,
2941 token::LBRACKET => {
2942 // parse [pat,pat,...] as vector pattern
2944 let (before, slice, after) =
2945 self.parse_pat_vec_elements();
2947 self.expect(&token::RBRACKET);
2948 pat = ast::PatVec(before, slice, after);
2949 hi = self.last_span.hi;
2951 id: ast::DUMMY_NODE_ID,
2959 if !is_ident_or_path(&self.token)
2960 || self.is_keyword(keywords::True)
2961 || self.is_keyword(keywords::False) {
2962 // Parse an expression pattern or exp .. exp.
2964 // These expressions are limited to literals (possibly
2965 // preceded by unary-minus) or identifiers.
2966 let val = self.parse_literal_maybe_minus();
2967 if self.eat(&token::DOTDOT) {
2968 let end = if is_ident_or_path(&self.token) {
2969 let path = self.parse_path(LifetimeAndTypesWithColons)
2971 let hi = self.span.hi;
2972 self.mk_expr(lo, hi, ExprPath(path))
2974 self.parse_literal_maybe_minus()
2976 pat = PatRange(val, end);
2980 } else if self.eat_keyword(keywords::Mut) {
2981 pat = self.parse_pat_ident(BindByValue(MutMutable));
2982 } else if self.eat_keyword(keywords::Ref) {
2984 let mutbl = self.parse_mutability();
2985 pat = self.parse_pat_ident(BindByRef(mutbl));
2987 let can_be_enum_or_struct = self.look_ahead(1, |t| {
2989 token::LPAREN | token::LBRACKET | token::LT |
2990 token::LBRACE | token::MOD_SEP => true,
2995 if self.look_ahead(1, |t| *t == token::DOTDOT) {
2996 let start = self.parse_expr_res(RESTRICT_NO_BAR_OP);
2997 self.eat(&token::DOTDOT);
2998 let end = self.parse_expr_res(RESTRICT_NO_BAR_OP);
2999 pat = PatRange(start, end);
3000 } else if is_plain_ident(&self.token) && !can_be_enum_or_struct {
3001 let name = self.parse_path(NoTypesAllowed).path;
3003 if self.eat(&token::AT) {
3005 sub = Some(self.parse_pat());
3010 pat = PatIdent(BindByValue(MutImmutable), name, sub);
3012 // parse an enum pat
3013 let enum_path = self.parse_path(LifetimeAndTypesWithColons)
3019 self.parse_pat_fields();
3021 pat = PatStruct(enum_path, fields, etc);
3024 let mut args: ~[@Pat] = ~[];
3027 let is_star = self.look_ahead(1, |t| {
3029 token::BINOP(token::STAR) => true,
3033 let is_dotdot = self.look_ahead(1, |t| {
3035 token::DOTDOT => true,
3039 if is_star | is_dotdot {
3040 // This is a "top constructor only" pat
3043 self.obsolete(self.span, ObsoleteEnumWildcard);
3046 self.expect(&token::RPAREN);
3047 pat = PatEnum(enum_path, None);
3049 args = self.parse_unspanned_seq(
3052 seq_sep_trailing_disallowed(token::COMMA),
3055 pat = PatEnum(enum_path, Some(args));
3059 if enum_path.segments.len() == 1 {
3060 // it could still be either an enum
3061 // or an identifier pattern, resolve
3062 // will sort it out:
3063 pat = PatIdent(BindByValue(MutImmutable),
3067 pat = PatEnum(enum_path, Some(args));
3075 hi = self.last_span.hi;
3077 id: ast::DUMMY_NODE_ID,
3079 span: mk_sp(lo, hi),
3083 // parse ident or ident @ pat
3084 // used by the copy foo and ref foo patterns to give a good
3085 // error message when parsing mistakes like ref foo(a,b)
3086 fn parse_pat_ident(&mut self,
3087 binding_mode: ast::BindingMode)
3089 if !is_plain_ident(&self.token) {
3090 self.span_fatal(self.last_span,
3091 "expected identifier, found path");
3093 // why a path here, and not just an identifier?
3094 let name = self.parse_path(NoTypesAllowed).path;
3095 let sub = if self.eat(&token::AT) {
3096 Some(self.parse_pat())
3101 // just to be friendly, if they write something like
3103 // we end up here with ( as the current token. This shortly
3104 // leads to a parse error. Note that if there is no explicit
3105 // binding mode then we do not end up here, because the lookahead
3106 // will direct us over to parse_enum_variant()
3107 if self.token == token::LPAREN {
3110 "expected identifier, found enum pattern");
3113 PatIdent(binding_mode, name, sub)
3116 // parse a local variable declaration
3117 fn parse_local(&mut self) -> @Local {
3118 let lo = self.span.lo;
3119 let pat = self.parse_pat();
3122 id: ast::DUMMY_NODE_ID,
3124 span: mk_sp(lo, lo),
3126 if self.eat(&token::COLON) { ty = self.parse_ty(false); }
3127 let init = self.parse_initializer();
3132 id: ast::DUMMY_NODE_ID,
3133 span: mk_sp(lo, self.last_span.hi),
3137 // parse a "let" stmt
3138 fn parse_let(&mut self) -> @Decl {
3139 let lo = self.span.lo;
3140 let local = self.parse_local();
3141 while self.eat(&token::COMMA) {
3142 let _ = self.parse_local();
3143 self.obsolete(self.span, ObsoleteMultipleLocalDecl);
3145 return @spanned(lo, self.last_span.hi, DeclLocal(local));
3148 // parse a structure field
3149 fn parse_name_and_ty(&mut self, pr: Visibility,
3150 attrs: ~[Attribute]) -> StructField {
3151 let lo = self.span.lo;
3152 if !is_plain_ident(&self.token) {
3153 self.fatal("expected ident");
3155 let name = self.parse_ident();
3156 self.expect(&token::COLON);
3157 let ty = self.parse_ty(false);
3158 spanned(lo, self.last_span.hi, ast::StructField_ {
3159 kind: NamedField(name, pr),
3160 id: ast::DUMMY_NODE_ID,
3166 // parse a statement. may include decl.
3167 // precondition: any attributes are parsed already
3168 pub fn parse_stmt(&mut self, item_attrs: ~[Attribute]) -> @Stmt {
3169 maybe_whole!(self, NtStmt);
3171 fn check_expected_item(p: &mut Parser, found_attrs: bool) {
3172 // If we have attributes then we should have an item
3174 p.span_err(p.last_span, "expected item after attributes");
3178 let lo = self.span.lo;
3179 if self.is_keyword(keywords::Let) {
3180 check_expected_item(self, !item_attrs.is_empty());
3181 self.expect_keyword(keywords::Let);
3182 let decl = self.parse_let();
3183 return @spanned(lo, decl.span.hi, StmtDecl(decl, ast::DUMMY_NODE_ID));
3184 } else if is_ident(&self.token)
3185 && !token::is_any_keyword(&self.token)
3186 && self.look_ahead(1, |t| *t == token::NOT) {
3187 // parse a macro invocation. Looks like there's serious
3188 // overlap here; if this clause doesn't catch it (and it
3189 // won't, for brace-delimited macros) it will fall through
3190 // to the macro clause of parse_item_or_view_item. This
3191 // could use some cleanup, it appears to me.
3193 // whoops! I now have a guess: I'm guessing the "parens-only"
3194 // rule here is deliberate, to allow macro users to use parens
3195 // for things that should be parsed as stmt_mac, and braces
3196 // for things that should expand into items. Tricky, and
3197 // somewhat awkward... and probably undocumented. Of course,
3198 // I could just be wrong.
3200 check_expected_item(self, !item_attrs.is_empty());
3202 // Potential trouble: if we allow macros with paths instead of
3203 // idents, we'd need to look ahead past the whole path here...
3204 let pth = self.parse_path(NoTypesAllowed).path;
3207 let id = if self.token == token::LPAREN {
3208 token::special_idents::invalid // no special identifier
3213 let tts = self.parse_unspanned_seq(
3217 |p| p.parse_token_tree()
3219 let hi = self.span.hi;
3221 if id == token::special_idents::invalid {
3222 return @spanned(lo, hi, StmtMac(
3223 spanned(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT)), false));
3225 // if it has a special ident, it's definitely an item
3226 return @spanned(lo, hi, StmtDecl(
3227 @spanned(lo, hi, DeclItem(
3229 lo, hi, id /*id is good here*/,
3230 ItemMac(spanned(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT))),
3231 Inherited, ~[/*no attrs*/]))),
3232 ast::DUMMY_NODE_ID));
3236 let found_attrs = !item_attrs.is_empty();
3237 match self.parse_item_or_view_item(item_attrs, false) {
3240 let decl = @spanned(lo, hi, DeclItem(i));
3241 return @spanned(lo, hi, StmtDecl(decl, ast::DUMMY_NODE_ID));
3243 IoviViewItem(vi) => {
3244 self.span_fatal(vi.span,
3245 "view items must be declared at the top of the block");
3247 IoviForeignItem(_) => {
3248 self.fatal("foreign items are not allowed here");
3250 IoviNone(_) => { /* fallthrough */ }
3253 check_expected_item(self, found_attrs);
3255 // Remainder are line-expr stmts.
3256 let e = self.parse_expr_res(RESTRICT_STMT_EXPR);
3257 return @spanned(lo, e.span.hi, StmtExpr(e, ast::DUMMY_NODE_ID));
3261 // is this expression a successfully-parsed statement?
3262 fn expr_is_complete(&mut self, e: @Expr) -> bool {
3263 return self.restriction == RESTRICT_STMT_EXPR &&
3264 !classify::expr_requires_semi_to_be_stmt(e);
3267 // parse a block. No inner attrs are allowed.
3268 pub fn parse_block(&mut self) -> P<Block> {
3269 maybe_whole!(no_clone self, NtBlock);
3271 let lo = self.span.lo;
3272 if self.eat_keyword(keywords::Unsafe) {
3273 self.obsolete(self.span, ObsoleteUnsafeBlock);
3275 self.expect(&token::LBRACE);
3277 return self.parse_block_tail_(lo, DefaultBlock, ~[]);
3280 // parse a block. Inner attrs are allowed.
3281 fn parse_inner_attrs_and_block(&mut self)
3282 -> (~[Attribute], P<Block>) {
3284 maybe_whole!(pair_empty self, NtBlock);
3286 let lo = self.span.lo;
3287 if self.eat_keyword(keywords::Unsafe) {
3288 self.obsolete(self.span, ObsoleteUnsafeBlock);
3290 self.expect(&token::LBRACE);
3291 let (inner, next) = self.parse_inner_attrs_and_next();
3293 (inner, self.parse_block_tail_(lo, DefaultBlock, next))
3296 // Precondition: already parsed the '{' or '#{'
3297 // I guess that also means "already parsed the 'impure'" if
3298 // necessary, and this should take a qualifier.
3299 // some blocks start with "#{"...
3300 fn parse_block_tail(&mut self, lo: BytePos, s: BlockCheckMode) -> P<Block> {
3301 self.parse_block_tail_(lo, s, ~[])
3304 // parse the rest of a block expression or function body
3305 fn parse_block_tail_(&mut self, lo: BytePos, s: BlockCheckMode,
3306 first_item_attrs: ~[Attribute]) -> P<Block> {
3307 let mut stmts = ~[];
3308 let mut expr = None;
3310 // wouldn't it be more uniform to parse view items only, here?
3311 let ParsedItemsAndViewItems {
3312 attrs_remaining: attrs_remaining,
3313 view_items: view_items,
3316 } = self.parse_items_and_view_items(first_item_attrs,
3319 for item in items.iter() {
3320 let decl = @spanned(item.span.lo, item.span.hi, DeclItem(*item));
3321 stmts.push(@spanned(item.span.lo, item.span.hi,
3322 StmtDecl(decl, ast::DUMMY_NODE_ID)));
3325 let mut attributes_box = attrs_remaining;
3327 while self.token != token::RBRACE {
3328 // parsing items even when they're not allowed lets us give
3329 // better error messages and recover more gracefully.
3330 attributes_box.push_all(self.parse_outer_attributes());
3333 if !attributes_box.is_empty() {
3334 self.span_err(self.last_span, "expected item after attributes");
3335 attributes_box = ~[];
3337 self.bump(); // empty
3340 // fall through and out.
3343 let stmt = self.parse_stmt(attributes_box);
3344 attributes_box = ~[];
3346 StmtExpr(e, stmt_id) => {
3347 // expression without semicolon
3348 if classify::stmt_ends_with_semi(stmt) {
3349 // Just check for errors and recover; do not eat semicolon yet.
3350 self.commit_stmt(stmt, &[], &[token::SEMI, token::RBRACE]);
3356 stmts.push(@codemap::Spanned {
3357 node: StmtSemi(e, stmt_id),
3369 StmtMac(ref m, _) => {
3370 // statement macro; might be an expr
3377 // if a block ends in `m!(arg)` without
3378 // a `;`, it must be an expr
3381 self.mk_mac_expr(stmt.span.lo,
3393 stmts.push(@codemap::Spanned {
3394 node: StmtMac((*m).clone(), true),
3399 _ => { // all other kinds of statements:
3402 if classify::stmt_ends_with_semi(stmt) {
3403 self.commit_stmt_expecting(stmt, token::SEMI);
3411 if !attributes_box.is_empty() {
3412 self.span_err(self.last_span, "expected item after attributes");
3415 let hi = self.span.hi;
3418 view_items: view_items,
3421 id: ast::DUMMY_NODE_ID,
3423 span: mk_sp(lo, hi),
3427 // matches optbounds = ( ( : ( boundseq )? )? )
3428 // where boundseq = ( bound + boundseq ) | bound
3429 // and bound = 'static | ty
3430 // Returns "None" if there's no colon (e.g. "T");
3431 // Returns "Some(Empty)" if there's a colon but nothing after (e.g. "T:")
3432 // Returns "Some(stuff)" otherwise (e.g. "T:stuff").
3433 // NB: The None/Some distinction is important for issue #7264.
3434 fn parse_optional_ty_param_bounds(&mut self) -> Option<OptVec<TyParamBound>> {
3435 if !self.eat(&token::COLON) {
3439 let mut result = opt_vec::Empty;
3442 token::LIFETIME(lifetime) => {
3443 if "static" == self.id_to_str(lifetime) {
3444 result.push(RegionTyParamBound);
3446 self.span_err(self.span,
3447 "`'static` is the only permissible region bound here");
3451 token::MOD_SEP | token::IDENT(..) => {
3452 let tref = self.parse_trait_ref();
3453 result.push(TraitTyParamBound(tref));
3458 if !self.eat(&token::BINOP(token::PLUS)) {
3463 return Some(result);
3466 // matches typaram = IDENT optbounds ( EQ ty )?
3467 fn parse_ty_param(&mut self) -> TyParam {
3468 let ident = self.parse_ident();
3469 let opt_bounds = self.parse_optional_ty_param_bounds();
3470 // For typarams we don't care about the difference b/w "<T>" and "<T:>".
3471 let bounds = opt_bounds.unwrap_or_default();
3473 let default = if self.token == token::EQ {
3475 Some(self.parse_ty(false))
3481 id: ast::DUMMY_NODE_ID,
3487 // parse a set of optional generic type parameter declarations
3488 // matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
3489 // | ( < lifetimes , typaramseq ( , )? > )
3490 // where typaramseq = ( typaram ) | ( typaram , typaramseq )
3491 pub fn parse_generics(&mut self) -> ast::Generics {
3492 if self.eat(&token::LT) {
3493 let lifetimes = self.parse_lifetimes();
3494 let mut seen_default = false;
3495 let ty_params = self.parse_seq_to_gt(Some(token::COMMA), |p| {
3496 let ty_param = p.parse_ty_param();
3497 if ty_param.default.is_some() {
3498 seen_default = true;
3499 } else if seen_default {
3500 p.span_err(p.last_span,
3501 "type parameters with a default must be trailing");
3505 ast::Generics { lifetimes: lifetimes, ty_params: ty_params }
3507 ast_util::empty_generics()
3511 fn parse_generic_values_after_lt(&mut self) -> (OptVec<ast::Lifetime>, ~[P<Ty>]) {
3512 let lifetimes = self.parse_lifetimes();
3513 let result = self.parse_seq_to_gt(
3515 |p| p.parse_ty(false));
3516 (lifetimes, opt_vec::take_vec(result))
3519 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
3522 let mut args: ~[Option<Arg>] =
3523 self.parse_unspanned_seq(
3526 seq_sep_trailing_allowed(token::COMMA),
3528 if p.token == token::DOTDOTDOT {
3531 if p.token != token::RPAREN {
3532 p.span_fatal(p.span,
3533 "`...` must be last in argument list for variadic function");
3536 p.span_fatal(p.span,
3537 "only foreign functions are allowed to be variadic");
3541 Some(p.parse_arg_general(named_args))
3546 let variadic = match args.pop() {
3549 // Need to put back that last arg
3556 if variadic && args.is_empty() {
3558 "variadic function must be declared with at least one named argument");
3561 let args = args.move_iter().map(|x| x.unwrap()).collect();
3566 // parse the argument list and result type of a function declaration
3567 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> P<FnDecl> {
3569 let (args, variadic) = self.parse_fn_args(true, allow_variadic);
3570 let (ret_style, ret_ty) = self.parse_ret_ty();
3580 fn is_self_ident(&mut self) -> bool {
3582 token::IDENT(id, false) => id.name == special_idents::self_.name,
3587 fn expect_self_ident(&mut self) {
3588 if !self.is_self_ident() {
3589 let token_str = self.this_token_to_str();
3590 self.fatal(format!("expected `self` but found `{}`", token_str))
3595 // parse the argument list and result type of a function
3596 // that may have a self type.
3597 fn parse_fn_decl_with_self(&mut self, parse_arg_fn: |&mut Parser| -> Arg)
3598 -> (ExplicitSelf, P<FnDecl>) {
3599 fn maybe_parse_explicit_self(explicit_self: ast::ExplicitSelf_,
3601 -> ast::ExplicitSelf_ {
3602 // We need to make sure it isn't a type
3603 if p.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) {
3605 p.expect_self_ident();
3612 fn maybe_parse_borrowed_explicit_self(this: &mut Parser)
3613 -> ast::ExplicitSelf_ {
3614 // The following things are possible to see here:
3619 // fn(&'lt mut self)
3621 // We already know that the current token is `&`.
3623 if this.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) {
3625 this.expect_self_ident();
3626 SelfRegion(None, MutImmutable)
3627 } else if this.look_ahead(1, |t| Parser::token_is_mutability(t)) &&
3629 |t| token::is_keyword(keywords::Self,
3632 let mutability = this.parse_mutability();
3633 this.expect_self_ident();
3634 SelfRegion(None, mutability)
3635 } else if this.look_ahead(1, |t| Parser::token_is_lifetime(t)) &&
3637 |t| token::is_keyword(keywords::Self,
3640 let lifetime = this.parse_lifetime();
3641 this.expect_self_ident();
3642 SelfRegion(Some(lifetime), MutImmutable)
3643 } else if this.look_ahead(1, |t| Parser::token_is_lifetime(t)) &&
3644 this.look_ahead(2, |t| {
3645 Parser::token_is_mutability(t)
3647 this.look_ahead(3, |t| token::is_keyword(keywords::Self,
3650 let lifetime = this.parse_lifetime();
3651 let mutability = this.parse_mutability();
3652 this.expect_self_ident();
3653 SelfRegion(Some(lifetime), mutability)
3659 self.expect(&token::LPAREN);
3661 // A bit of complexity and lookahead is needed here in order to be
3662 // backwards compatible.
3663 let lo = self.span.lo;
3664 let mut mutbl_self = MutImmutable;
3665 let explicit_self = match self.token {
3666 token::BINOP(token::AND) => {
3667 maybe_parse_borrowed_explicit_self(self)
3670 maybe_parse_explicit_self(SelfBox, self)
3673 maybe_parse_explicit_self(SelfUniq, self)
3675 token::IDENT(..) if self.is_self_ident() => {
3679 token::BINOP(token::STAR) => {
3680 // Possibly "*self" or "*mut self" -- not supported. Try to avoid
3681 // emitting cryptic "unexpected token" errors.
3683 let _mutability = if Parser::token_is_mutability(&self.token) {
3684 self.parse_mutability()
3685 } else { MutImmutable };
3686 if self.is_self_ident() {
3687 self.span_err(self.span, "cannot pass self by unsafe pointer");
3692 _ if Parser::token_is_mutability(&self.token) &&
3693 self.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) => {
3694 mutbl_self = self.parse_mutability();
3695 self.expect_self_ident();
3698 _ if Parser::token_is_mutability(&self.token) &&
3699 self.look_ahead(1, |t| *t == token::TILDE) &&
3700 self.look_ahead(2, |t| token::is_keyword(keywords::Self, t)) => {
3701 mutbl_self = self.parse_mutability();
3703 self.expect_self_ident();
3709 let explicit_self_sp = mk_sp(lo, self.span.hi);
3711 // If we parsed a self type, expect a comma before the argument list.
3712 let fn_inputs = if explicit_self != SelfStatic {
3716 let sep = seq_sep_trailing_disallowed(token::COMMA);
3717 let mut fn_inputs = self.parse_seq_to_before_end(
3722 fn_inputs.unshift(Arg::new_self(explicit_self_sp, mutbl_self));
3726 ~[Arg::new_self(explicit_self_sp, mutbl_self)]
3729 let token_str = self.this_token_to_str();
3730 self.fatal(format!("expected `,` or `)`, found `{}`",
3735 let sep = seq_sep_trailing_disallowed(token::COMMA);
3736 self.parse_seq_to_before_end(&token::RPAREN, sep, parse_arg_fn)
3739 self.expect(&token::RPAREN);
3741 let hi = self.span.hi;
3743 let (ret_style, ret_ty) = self.parse_ret_ty();
3745 let fn_decl = P(FnDecl {
3752 (spanned(lo, hi, explicit_self), fn_decl)
3755 // parse the |arg, arg| header on a lambda
3756 fn parse_fn_block_decl(&mut self) -> P<FnDecl> {
3757 let inputs_captures = {
3758 if self.eat(&token::OROR) {
3761 self.parse_unspanned_seq(
3762 &token::BINOP(token::OR),
3763 &token::BINOP(token::OR),
3764 seq_sep_trailing_disallowed(token::COMMA),
3765 |p| p.parse_fn_block_arg()
3769 let output = if self.eat(&token::RARROW) {
3770 self.parse_ty(false)
3773 id: ast::DUMMY_NODE_ID,
3780 inputs: inputs_captures,
3787 // Parses the `(arg, arg) -> return_type` header on a procedure.
3788 fn parse_proc_decl(&mut self) -> P<FnDecl> {
3790 self.parse_unspanned_seq(&token::LPAREN,
3792 seq_sep_trailing_allowed(token::COMMA),
3793 |p| p.parse_fn_block_arg());
3795 let output = if self.eat(&token::RARROW) {
3796 self.parse_ty(false)
3799 id: ast::DUMMY_NODE_ID,
3813 // parse the name and optional generic types of a function header.
3814 fn parse_fn_header(&mut self) -> (Ident, ast::Generics) {
3815 let id = self.parse_ident();
3816 let generics = self.parse_generics();
3820 fn mk_item(&mut self, lo: BytePos, hi: BytePos, ident: Ident,
3821 node: Item_, vis: Visibility,
3822 attrs: ~[Attribute]) -> @Item {
3826 id: ast::DUMMY_NODE_ID,
3833 // parse an item-position function declaration.
3834 fn parse_item_fn(&mut self, purity: Purity, abis: AbiSet) -> ItemInfo {
3835 let (ident, generics) = self.parse_fn_header();
3836 let decl = self.parse_fn_decl(false);
3837 let (inner_attrs, body) = self.parse_inner_attrs_and_block();
3838 (ident, ItemFn(decl, purity, abis, generics, body), Some(inner_attrs))
3841 // parse a method in a trait impl, starting with `attrs` attributes.
3842 fn parse_method(&mut self, already_parsed_attrs: Option<~[Attribute]>) -> @Method {
3843 let next_attrs = self.parse_outer_attributes();
3844 let attrs = match already_parsed_attrs {
3845 Some(mut a) => { a.push_all_move(next_attrs); a }
3849 let lo = self.span.lo;
3851 let visa = self.parse_visibility();
3852 let pur = self.parse_fn_purity();
3853 let ident = self.parse_ident();
3854 let generics = self.parse_generics();
3855 let (explicit_self, decl) = self.parse_fn_decl_with_self(|p| {
3859 let (inner_attrs, body) = self.parse_inner_attrs_and_block();
3860 let hi = body.span.hi;
3861 let attrs = vec::append(attrs, inner_attrs);
3866 explicit_self: explicit_self,
3870 id: ast::DUMMY_NODE_ID,
3871 span: mk_sp(lo, hi),
3876 // parse trait Foo { ... }
3877 fn parse_item_trait(&mut self) -> ItemInfo {
3878 let ident = self.parse_ident();
3879 let tps = self.parse_generics();
3881 // Parse traits, if necessary.
3883 if self.token == token::COLON {
3885 traits = self.parse_trait_ref_list(&token::LBRACE);
3890 let meths = self.parse_trait_methods();
3891 (ident, ItemTrait(tps, traits, meths), None)
3894 // Parses two variants (with the region/type params always optional):
3895 // impl<T> Foo { ... }
3896 // impl<T> ToStr for ~[T] { ... }
3897 fn parse_item_impl(&mut self) -> ItemInfo {
3898 // First, parse type parameters if necessary.
3899 let generics = self.parse_generics();
3901 // This is a new-style impl declaration.
3902 // FIXME: clownshoes
3903 let ident = special_idents::clownshoes_extensions;
3905 // Special case: if the next identifier that follows is '(', don't
3906 // allow this to be parsed as a trait.
3907 let could_be_trait = self.token != token::LPAREN;
3910 let mut ty = self.parse_ty(false);
3912 // Parse traits, if necessary.
3913 let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) {
3914 // New-style trait. Reinterpret the type as a trait.
3915 let opt_trait_ref = match ty.node {
3916 TyPath(ref path, None, node_id) => {
3918 path: /* bad */ (*path).clone(),
3923 self.span_err(ty.span,
3924 "bounded traits are only valid in type position");
3928 self.span_err(ty.span, "not a trait");
3933 ty = self.parse_ty(false);
3939 let mut meths = ~[];
3940 self.expect(&token::LBRACE);
3941 let (inner_attrs, next) = self.parse_inner_attrs_and_next();
3942 let mut method_attrs = Some(next);
3943 while !self.eat(&token::RBRACE) {
3944 meths.push(self.parse_method(method_attrs));
3945 method_attrs = None;
3948 (ident, ItemImpl(generics, opt_trait, ty, meths), Some(inner_attrs))
3951 // parse a::B<~str,int>
3952 fn parse_trait_ref(&mut self) -> TraitRef {
3954 path: self.parse_path(LifetimeAndTypesWithoutColons).path,
3955 ref_id: ast::DUMMY_NODE_ID,
3959 // parse B + C<~str,int> + D
3960 fn parse_trait_ref_list(&mut self, ket: &token::Token) -> ~[TraitRef] {
3961 self.parse_seq_to_before_end(
3963 seq_sep_trailing_disallowed(token::BINOP(token::PLUS)),
3964 |p| p.parse_trait_ref()
3968 // parse struct Foo { ... }
3969 fn parse_item_struct(&mut self) -> ItemInfo {
3970 let class_name = self.parse_ident();
3971 let generics = self.parse_generics();
3973 let mut fields: ~[StructField];
3976 if self.eat(&token::LBRACE) {
3977 // It's a record-like struct.
3978 is_tuple_like = false;
3980 while self.token != token::RBRACE {
3981 fields.push(self.parse_struct_decl_field());
3983 if fields.len() == 0 {
3984 self.fatal(format!("Unit-like struct definition should be written as `struct {};`",
3985 get_ident_interner().get(class_name.name)));
3988 } else if self.token == token::LPAREN {
3989 // It's a tuple-like struct.
3990 is_tuple_like = true;
3991 fields = self.parse_unspanned_seq(
3994 seq_sep_trailing_allowed(token::COMMA),
3996 let attrs = p.parse_outer_attributes();
3998 let struct_field_ = ast::StructField_ {
4000 id: ast::DUMMY_NODE_ID,
4001 ty: p.parse_ty(false),
4004 spanned(lo, p.span.hi, struct_field_)
4006 self.expect(&token::SEMI);
4007 } else if self.eat(&token::SEMI) {
4008 // It's a unit-like struct.
4009 is_tuple_like = true;
4012 let token_str = self.this_token_to_str();
4013 self.fatal(format!("expected `\\{`, `(`, or `;` after struct \
4014 name but found `{}`",
4018 let _ = ast::DUMMY_NODE_ID; // FIXME: Workaround for crazy bug.
4019 let new_id = ast::DUMMY_NODE_ID;
4021 ItemStruct(@ast::StructDef {
4023 ctor_id: if is_tuple_like { Some(new_id) } else { None }
4028 // parse a structure field declaration
4029 pub fn parse_single_struct_field(&mut self,
4031 attrs: ~[Attribute])
4033 let a_var = self.parse_name_and_ty(vis, attrs);
4040 let token_str = self.this_token_to_str();
4041 self.span_fatal(self.span,
4042 format!("expected `,`, or `\\}` but found `{}`",
4049 // parse an element of a struct definition
4050 fn parse_struct_decl_field(&mut self) -> StructField {
4052 let attrs = self.parse_outer_attributes();
4054 if self.eat_keyword(keywords::Priv) {
4055 return self.parse_single_struct_field(Private, attrs);
4058 if self.eat_keyword(keywords::Pub) {
4059 return self.parse_single_struct_field(Public, attrs);
4062 return self.parse_single_struct_field(Inherited, attrs);
4065 // parse visiility: PUB, PRIV, or nothing
4066 fn parse_visibility(&mut self) -> Visibility {
4067 if self.eat_keyword(keywords::Pub) { Public }
4068 else if self.eat_keyword(keywords::Priv) { Private }
4072 // given a termination token and a vector of already-parsed
4073 // attributes (of length 0 or 1), parse all of the items in a module
4074 fn parse_mod_items(&mut self,
4076 first_item_attrs: ~[Attribute])
4078 // parse all of the items up to closing or an attribute.
4079 // view items are legal here.
4080 let ParsedItemsAndViewItems {
4081 attrs_remaining: attrs_remaining,
4082 view_items: view_items,
4083 items: starting_items,
4085 } = self.parse_items_and_view_items(first_item_attrs, true, true);
4086 let mut items: ~[@Item] = starting_items;
4087 let attrs_remaining_len = attrs_remaining.len();
4089 // don't think this other loop is even necessary....
4091 let mut first = true;
4092 while self.token != term {
4093 let mut attrs = self.parse_outer_attributes();
4095 attrs = attrs_remaining + attrs;
4098 debug!("parse_mod_items: parse_item_or_view_item(attrs={:?})",
4100 match self.parse_item_or_view_item(attrs,
4101 true /* macros allowed */) {
4102 IoviItem(item) => items.push(item),
4103 IoviViewItem(view_item) => {
4104 self.span_fatal(view_item.span,
4105 "view items must be declared at the top of \
4109 let token_str = self.this_token_to_str();
4110 self.fatal(format!("expected item but found `{}`",
4116 if first && attrs_remaining_len > 0u {
4117 // We parsed attributes for the first item but didn't find it
4118 self.span_err(self.last_span, "expected item after attributes");
4121 ast::Mod { view_items: view_items, items: items }
4124 fn parse_item_const(&mut self) -> ItemInfo {
4125 let m = if self.eat_keyword(keywords::Mut) {MutMutable} else {MutImmutable};
4126 let id = self.parse_ident();
4127 self.expect(&token::COLON);
4128 let ty = self.parse_ty(false);
4129 self.expect(&token::EQ);
4130 let e = self.parse_expr();
4131 self.commit_expr_expecting(e, token::SEMI);
4132 (id, ItemStatic(ty, m, e), None)
4135 // parse a `mod <foo> { ... }` or `mod <foo>;` item
4136 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> ItemInfo {
4137 let id_span = self.span;
4138 let id = self.parse_ident();
4139 if self.token == token::SEMI {
4141 // This mod is in an external file. Let's go get it!
4142 let (m, attrs) = self.eval_src_mod(id, outer_attrs, id_span);
4143 (id, m, Some(attrs))
4145 self.push_mod_path(id, outer_attrs);
4146 self.expect(&token::LBRACE);
4147 let (inner, next) = self.parse_inner_attrs_and_next();
4148 let m = self.parse_mod_items(token::RBRACE, next);
4149 self.expect(&token::RBRACE);
4150 self.pop_mod_path();
4151 (id, ItemMod(m), Some(inner))
4155 fn push_mod_path(&mut self, id: Ident, attrs: &[Attribute]) {
4156 let default_path = self.id_to_interned_str(id);
4157 let file_path = match ::attr::first_attr_value_str_by_name(attrs,
4160 None => default_path,
4162 self.mod_path_stack.push(file_path)
4165 fn pop_mod_path(&mut self) {
4166 self.mod_path_stack.pop().unwrap();
4169 // read a module from a source file.
4170 fn eval_src_mod(&mut self,
4172 outer_attrs: &[ast::Attribute],
4174 -> (ast::Item_, ~[ast::Attribute]) {
4175 let mut prefix = Path::new(self.sess.cm.span_to_filename(self.span));
4177 let mod_path = Path::new(".").join_many(self.mod_path_stack);
4178 let dir_path = prefix.join(&mod_path);
4179 let file_path = match ::attr::first_attr_value_str_by_name(
4180 outer_attrs, "path") {
4181 Some(d) => dir_path.join(d),
4183 let mod_name = token::interner_get(id.name).to_owned();
4184 let default_path_str = mod_name + ".rs";
4185 let secondary_path_str = mod_name + "/mod.rs";
4186 let default_path = dir_path.join(default_path_str.as_slice());
4187 let secondary_path = dir_path.join(secondary_path_str.as_slice());
4188 let default_exists = default_path.exists();
4189 let secondary_exists = secondary_path.exists();
4190 match (default_exists, secondary_exists) {
4191 (true, false) => default_path,
4192 (false, true) => secondary_path,
4194 self.span_fatal(id_sp, format!("file not found for module `{}`", mod_name));
4197 self.span_fatal(id_sp,
4198 format!("file for module `{}` found at both {} and {}",
4199 mod_name, default_path_str, secondary_path_str));
4205 self.eval_src_mod_from_path(file_path,
4206 outer_attrs.to_owned(),
4210 fn eval_src_mod_from_path(&mut self,
4212 outer_attrs: ~[ast::Attribute],
4213 id_sp: Span) -> (ast::Item_, ~[ast::Attribute]) {
4215 let mut included_mod_stack = self.sess
4218 let maybe_i = included_mod_stack.get()
4220 .position(|p| *p == path);
4223 let mut err = ~"circular modules: ";
4224 let len = included_mod_stack.get().len();
4225 for p in included_mod_stack.get().slice(i, len).iter() {
4226 p.display().with_str(|s| err.push_str(s));
4227 err.push_str(" -> ");
4229 path.display().with_str(|s| err.push_str(s));
4230 self.span_fatal(id_sp, err);
4234 included_mod_stack.get().push(path.clone());
4238 new_sub_parser_from_file(self.sess,
4242 let (inner, next) = p0.parse_inner_attrs_and_next();
4243 let mod_attrs = vec::append(outer_attrs, inner);
4244 let first_item_outer_attrs = next;
4245 let m0 = p0.parse_mod_items(token::EOF, first_item_outer_attrs);
4247 let mut included_mod_stack = self.sess
4250 included_mod_stack.get().pop();
4252 return (ast::ItemMod(m0), mod_attrs);
4255 // parse a function declaration from a foreign module
4256 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility,
4257 attrs: ~[Attribute]) -> @ForeignItem {
4258 let lo = self.span.lo;
4260 // Parse obsolete purity.
4261 let purity = self.parse_fn_purity();
4262 if purity != ImpureFn {
4263 self.obsolete(self.last_span, ObsoleteUnsafeExternFn);
4266 let (ident, generics) = self.parse_fn_header();
4267 let decl = self.parse_fn_decl(true);
4268 let hi = self.span.hi;
4269 self.expect(&token::SEMI);
4270 @ast::ForeignItem { ident: ident,
4272 node: ForeignItemFn(decl, generics),
4273 id: ast::DUMMY_NODE_ID,
4274 span: mk_sp(lo, hi),
4278 // parse a static item from a foreign module
4279 fn parse_item_foreign_static(&mut self, vis: ast::Visibility,
4280 attrs: ~[Attribute]) -> @ForeignItem {
4281 let lo = self.span.lo;
4283 self.expect_keyword(keywords::Static);
4284 let mutbl = self.eat_keyword(keywords::Mut);
4286 let ident = self.parse_ident();
4287 self.expect(&token::COLON);
4288 let ty = self.parse_ty(false);
4289 let hi = self.span.hi;
4290 self.expect(&token::SEMI);
4291 @ast::ForeignItem { ident: ident,
4293 node: ForeignItemStatic(ty, mutbl),
4294 id: ast::DUMMY_NODE_ID,
4295 span: mk_sp(lo, hi),
4299 // parse safe/unsafe and fn
4300 fn parse_fn_purity(&mut self) -> Purity {
4301 if self.eat_keyword(keywords::Fn) { ImpureFn }
4302 else if self.eat_keyword(keywords::Unsafe) {
4303 self.expect_keyword(keywords::Fn);
4306 else { self.unexpected(); }
4310 // at this point, this is essentially a wrapper for
4311 // parse_foreign_items.
4312 fn parse_foreign_mod_items(&mut self,
4314 first_item_attrs: ~[Attribute])
4316 let ParsedItemsAndViewItems {
4317 attrs_remaining: attrs_remaining,
4318 view_items: view_items,
4320 foreign_items: foreign_items
4321 } = self.parse_foreign_items(first_item_attrs, true);
4322 if ! attrs_remaining.is_empty() {
4323 self.span_err(self.last_span,
4324 "expected item after attributes");
4326 assert!(self.token == token::RBRACE);
4329 view_items: view_items,
4330 items: foreign_items
4334 // parse extern foo; or extern mod foo { ... } or extern { ... }
4335 fn parse_item_foreign_mod(&mut self,
4337 opt_abis: Option<AbiSet>,
4338 visibility: Visibility,
4339 attrs: ~[Attribute],
4340 items_allowed: bool)
4342 let mut must_be_named_mod = false;
4343 if self.is_keyword(keywords::Mod) {
4344 must_be_named_mod = true;
4345 self.expect_keyword(keywords::Mod);
4346 } else if self.token != token::LBRACE {
4347 let token_str = self.this_token_to_str();
4348 self.span_fatal(self.span,
4349 format!("expected `\\{` or `mod` but found `{}`",
4353 let (named, maybe_path, ident) = match self.token {
4354 token::IDENT(..) => {
4355 let the_ident = self.parse_ident();
4356 let path = if self.token == token::EQ {
4358 Some(self.parse_str())
4361 (true, path, the_ident)
4364 if must_be_named_mod {
4365 let token_str = self.this_token_to_str();
4366 self.span_fatal(self.span,
4367 format!("expected foreign module name but \
4373 special_idents::clownshoes_foreign_mod)
4377 // extern mod foo { ... } or extern { ... }
4378 if items_allowed && self.eat(&token::LBRACE) {
4379 // `extern mod foo { ... }` is obsolete.
4381 self.obsolete(self.last_span, ObsoleteNamedExternModule);
4384 let abis = opt_abis.unwrap_or(AbiSet::C());
4386 let (inner, next) = self.parse_inner_attrs_and_next();
4387 let m = self.parse_foreign_mod_items(abis, next);
4388 self.expect(&token::RBRACE);
4390 let item = self.mk_item(lo,
4395 maybe_append(attrs, Some(inner)));
4396 return IoviItem(item);
4399 if opt_abis.is_some() {
4400 self.span_err(self.span, "an ABI may not be specified here");
4404 if self.token == token::LPAREN {
4405 // `extern mod foo (name = "bar"[,vers = "version"]) is obsolete,
4406 // `extern mod foo = "bar#[version]";` should be used.
4407 // Parse obsolete options to avoid wired parser errors
4408 self.parse_optional_meta();
4409 self.obsolete(self.span, ObsoleteExternModAttributesInParens);
4412 self.expect(&token::SEMI);
4413 IoviViewItem(ast::ViewItem {
4414 node: ViewItemExternMod(ident, maybe_path, ast::DUMMY_NODE_ID),
4417 span: mk_sp(lo, self.last_span.hi)
4421 // parse type Foo = Bar;
4422 fn parse_item_type(&mut self) -> ItemInfo {
4423 let ident = self.parse_ident();
4424 let tps = self.parse_generics();
4425 self.expect(&token::EQ);
4426 let ty = self.parse_ty(false);
4427 self.expect(&token::SEMI);
4428 (ident, ItemTy(ty, tps), None)
4431 // parse a structure-like enum variant definition
4432 // this should probably be renamed or refactored...
4433 fn parse_struct_def(&mut self) -> @StructDef {
4434 let mut fields: ~[StructField] = ~[];
4435 while self.token != token::RBRACE {
4436 fields.push(self.parse_struct_decl_field());
4440 return @ast::StructDef {
4446 // parse the part of an "enum" decl following the '{'
4447 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> EnumDef {
4448 let mut variants = ~[];
4449 let mut all_nullary = true;
4450 let mut have_disr = false;
4451 while self.token != token::RBRACE {
4452 let variant_attrs = self.parse_outer_attributes();
4453 let vlo = self.span.lo;
4455 let vis = self.parse_visibility();
4460 let mut disr_expr = None;
4461 ident = self.parse_ident();
4462 if self.eat(&token::LBRACE) {
4463 // Parse a struct variant.
4464 all_nullary = false;
4465 kind = StructVariantKind(self.parse_struct_def());
4466 } else if self.token == token::LPAREN {
4467 all_nullary = false;
4468 let arg_tys = self.parse_unspanned_seq(
4471 seq_sep_trailing_disallowed(token::COMMA),
4472 |p| p.parse_ty(false)
4474 for ty in arg_tys.move_iter() {
4475 args.push(ast::VariantArg {
4477 id: ast::DUMMY_NODE_ID,
4480 kind = TupleVariantKind(args);
4481 } else if self.eat(&token::EQ) {
4483 disr_expr = Some(self.parse_expr());
4484 kind = TupleVariantKind(args);
4486 kind = TupleVariantKind(~[]);
4489 let vr = ast::Variant_ {
4491 attrs: variant_attrs,
4493 id: ast::DUMMY_NODE_ID,
4494 disr_expr: disr_expr,
4497 variants.push(P(spanned(vlo, self.last_span.hi, vr)));
4499 if !self.eat(&token::COMMA) { break; }
4501 self.expect(&token::RBRACE);
4502 if have_disr && !all_nullary {
4503 self.fatal("discriminator values can only be used with a c-like \
4507 ast::EnumDef { variants: variants }
4510 // parse an "enum" declaration
4511 fn parse_item_enum(&mut self) -> ItemInfo {
4512 let id = self.parse_ident();
4513 let generics = self.parse_generics();
4514 self.expect(&token::LBRACE);
4516 let enum_definition = self.parse_enum_def(&generics);
4517 (id, ItemEnum(enum_definition, generics), None)
4520 fn fn_expr_lookahead(tok: &token::Token) -> bool {
4522 token::LPAREN | token::AT | token::TILDE | token::BINOP(_) => true,
4527 // Parses a string as an ABI spec on an extern type or module. Consumes
4528 // the `extern` keyword, if one is found.
4529 fn parse_opt_abis(&mut self) -> Option<AbiSet> {
4530 if !self.eat_keyword(keywords::Extern) {
4536 | token::LIT_STR_RAW(s, _) => {
4538 let the_string = ident_to_str(&s);
4539 let mut abis = AbiSet::empty();
4540 for word in the_string.words() {
4541 match abi::lookup(word) {
4543 if abis.contains(abi) {
4546 format!("ABI `{}` appears twice",
4556 format!("illegal ABI: \
4557 expected one of [{}], \
4559 abi::all_names().connect(", "),
4573 // parse one of the items or view items allowed by the
4574 // flags; on failure, return IoviNone.
4575 // NB: this function no longer parses the items inside an
4577 fn parse_item_or_view_item(&mut self,
4578 attrs: ~[Attribute],
4579 macros_allowed: bool)
4582 INTERPOLATED(token::NtItem(item)) => {
4584 let new_attrs = vec::append(attrs, item.attrs);
4585 return IoviItem(@Item {
4593 let lo = self.span.lo;
4595 let visibility = self.parse_visibility();
4597 // must be a view item:
4598 if self.eat_keyword(keywords::Use) {
4599 // USE ITEM (IoviViewItem)
4600 let view_item = self.parse_use();
4601 self.expect(&token::SEMI);
4602 return IoviViewItem(ast::ViewItem {
4606 span: mk_sp(lo, self.last_span.hi)
4609 // either a view item or an item:
4610 if self.is_keyword(keywords::Extern) {
4611 let opt_abis = self.parse_opt_abis();
4613 if self.eat_keyword(keywords::Fn) {
4614 // EXTERN FUNCTION ITEM
4615 let abis = opt_abis.unwrap_or(AbiSet::C());
4616 let (ident, item_, extra_attrs) =
4617 self.parse_item_fn(ExternFn, abis);
4618 let item = self.mk_item(lo,
4623 maybe_append(attrs, extra_attrs));
4624 return IoviItem(item);
4626 // EXTERN MODULE ITEM (IoviViewItem)
4627 return self.parse_item_foreign_mod(lo, opt_abis, visibility, attrs,
4631 // the rest are all guaranteed to be items:
4632 if self.is_keyword(keywords::Static) {
4635 let (ident, item_, extra_attrs) = self.parse_item_const();
4636 let item = self.mk_item(lo,
4641 maybe_append(attrs, extra_attrs));
4642 return IoviItem(item);
4644 if self.is_keyword(keywords::Fn) &&
4645 self.look_ahead(1, |f| !Parser::fn_expr_lookahead(f)) {
4648 let (ident, item_, extra_attrs) =
4649 self.parse_item_fn(ImpureFn, AbiSet::Rust());
4650 let item = self.mk_item(lo,
4655 maybe_append(attrs, extra_attrs));
4656 return IoviItem(item);
4658 if self.is_keyword(keywords::Unsafe)
4659 && self.look_ahead(1u, |t| *t != token::LBRACE) {
4660 // UNSAFE FUNCTION ITEM
4662 self.expect_keyword(keywords::Fn);
4663 let (ident, item_, extra_attrs) =
4664 self.parse_item_fn(UnsafeFn, AbiSet::Rust());
4665 let item = self.mk_item(lo,
4670 maybe_append(attrs, extra_attrs));
4671 return IoviItem(item);
4673 if self.eat_keyword(keywords::Mod) {
4675 let (ident, item_, extra_attrs) = self.parse_item_mod(attrs);
4676 let item = self.mk_item(lo,
4681 maybe_append(attrs, extra_attrs));
4682 return IoviItem(item);
4684 if self.eat_keyword(keywords::Type) {
4686 let (ident, item_, extra_attrs) = self.parse_item_type();
4687 let item = self.mk_item(lo,
4692 maybe_append(attrs, extra_attrs));
4693 return IoviItem(item);
4695 if self.eat_keyword(keywords::Enum) {
4697 let (ident, item_, extra_attrs) = self.parse_item_enum();
4698 let item = self.mk_item(lo,
4703 maybe_append(attrs, extra_attrs));
4704 return IoviItem(item);
4706 if self.eat_keyword(keywords::Trait) {
4708 let (ident, item_, extra_attrs) = self.parse_item_trait();
4709 let item = self.mk_item(lo,
4714 maybe_append(attrs, extra_attrs));
4715 return IoviItem(item);
4717 if self.eat_keyword(keywords::Impl) {
4719 let (ident, item_, extra_attrs) = self.parse_item_impl();
4720 let item = self.mk_item(lo,
4725 maybe_append(attrs, extra_attrs));
4726 return IoviItem(item);
4728 if self.eat_keyword(keywords::Struct) {
4730 let (ident, item_, extra_attrs) = self.parse_item_struct();
4731 let item = self.mk_item(lo,
4736 maybe_append(attrs, extra_attrs));
4737 return IoviItem(item);
4739 self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility)
4742 // parse a foreign item; on failure, return IoviNone.
4743 fn parse_foreign_item(&mut self,
4744 attrs: ~[Attribute],
4745 macros_allowed: bool)
4747 maybe_whole!(iovi self, NtItem);
4748 let lo = self.span.lo;
4750 let visibility = self.parse_visibility();
4752 if self.is_keyword(keywords::Static) {
4753 // FOREIGN STATIC ITEM
4754 let item = self.parse_item_foreign_static(visibility, attrs);
4755 return IoviForeignItem(item);
4757 if self.is_keyword(keywords::Fn) || self.is_keyword(keywords::Unsafe) {
4758 // FOREIGN FUNCTION ITEM
4759 let item = self.parse_item_foreign_fn(visibility, attrs);
4760 return IoviForeignItem(item);
4762 self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility)
4765 // this is the fall-through for parsing items.
4766 fn parse_macro_use_or_failure(
4768 attrs: ~[Attribute],
4769 macros_allowed: bool,
4771 visibility: Visibility
4772 ) -> ItemOrViewItem {
4773 if macros_allowed && !token::is_any_keyword(&self.token)
4774 && self.look_ahead(1, |t| *t == token::NOT)
4775 && (self.look_ahead(2, |t| is_plain_ident(t))
4776 || self.look_ahead(2, |t| *t == token::LPAREN)
4777 || self.look_ahead(2, |t| *t == token::LBRACE)) {
4778 // MACRO INVOCATION ITEM
4781 let pth = self.parse_path(NoTypesAllowed).path;
4782 self.expect(&token::NOT);
4784 // a 'special' identifier (like what `macro_rules!` uses)
4785 // is optional. We should eventually unify invoc syntax
4787 let id = if is_plain_ident(&self.token) {
4790 token::special_idents::invalid // no special identifier
4792 // eat a matched-delimiter token tree:
4793 let tts = match self.token {
4794 token::LPAREN | token::LBRACE => {
4795 let ket = token::flip_delimiter(&self.token);
4797 self.parse_seq_to_end(&ket,
4799 |p| p.parse_token_tree())
4801 _ => self.fatal("expected open delimiter")
4803 // single-variant-enum... :
4804 let m = ast::MacInvocTT(pth, tts, EMPTY_CTXT);
4805 let m: ast::Mac = codemap::Spanned { node: m,
4806 span: mk_sp(self.span.lo,
4808 let item_ = ItemMac(m);
4809 let item = self.mk_item(lo,
4815 return IoviItem(item);
4818 // FAILURE TO PARSE ITEM
4819 if visibility != Inherited {
4820 let mut s = ~"unmatched visibility `";
4821 if visibility == Public {
4827 self.span_fatal(self.last_span, s);
4829 return IoviNone(attrs);
4832 pub fn parse_item(&mut self, attrs: ~[Attribute]) -> Option<@Item> {
4833 match self.parse_item_or_view_item(attrs, true) {
4834 IoviNone(_) => None,
4836 self.fatal("view items are not allowed here"),
4837 IoviForeignItem(_) =>
4838 self.fatal("foreign items are not allowed here"),
4839 IoviItem(item) => Some(item)
4843 // parse, e.g., "use a::b::{z,y}"
4844 fn parse_use(&mut self) -> ViewItem_ {
4845 return ViewItemUse(self.parse_view_paths());
4849 // matches view_path : MOD? IDENT EQ non_global_path
4850 // | MOD? non_global_path MOD_SEP LBRACE RBRACE
4851 // | MOD? non_global_path MOD_SEP LBRACE ident_seq RBRACE
4852 // | MOD? non_global_path MOD_SEP STAR
4853 // | MOD? non_global_path
4854 fn parse_view_path(&mut self) -> @ViewPath {
4855 let lo = self.span.lo;
4857 if self.token == token::LBRACE {
4859 let idents = self.parse_unspanned_seq(
4860 &token::LBRACE, &token::RBRACE,
4861 seq_sep_trailing_allowed(token::COMMA),
4862 |p| p.parse_path_list_ident());
4863 let path = ast::Path {
4864 span: mk_sp(lo, self.span.hi),
4868 return @spanned(lo, self.span.hi,
4869 ViewPathList(path, idents, ast::DUMMY_NODE_ID));
4872 let first_ident = self.parse_ident();
4873 let mut path = ~[first_ident];
4874 debug!("parsed view path: {}", self.id_to_str(first_ident));
4879 let path_lo = self.span.lo;
4880 path = ~[self.parse_ident()];
4881 while self.token == token::MOD_SEP {
4883 let id = self.parse_ident();
4886 let path = ast::Path {
4887 span: mk_sp(path_lo, self.span.hi),
4889 segments: path.move_iter().map(|identifier| {
4891 identifier: identifier,
4892 lifetimes: opt_vec::Empty,
4893 types: opt_vec::Empty,
4897 return @spanned(lo, self.span.hi,
4898 ViewPathSimple(first_ident, path,
4899 ast::DUMMY_NODE_ID));
4903 // foo::bar or foo::{a,b,c} or foo::*
4904 while self.token == token::MOD_SEP {
4908 token::IDENT(i, _) => {
4913 // foo::bar::{a,b,c}
4915 let idents = self.parse_unspanned_seq(
4918 seq_sep_trailing_allowed(token::COMMA),
4919 |p| p.parse_path_list_ident()
4921 let path = ast::Path {
4922 span: mk_sp(lo, self.span.hi),
4924 segments: path.move_iter().map(|identifier| {
4926 identifier: identifier,
4927 lifetimes: opt_vec::Empty,
4928 types: opt_vec::Empty,
4932 return @spanned(lo, self.span.hi,
4933 ViewPathList(path, idents, ast::DUMMY_NODE_ID));
4937 token::BINOP(token::STAR) => {
4939 let path = ast::Path {
4940 span: mk_sp(lo, self.span.hi),
4942 segments: path.move_iter().map(|identifier| {
4944 identifier: identifier,
4945 lifetimes: opt_vec::Empty,
4946 types: opt_vec::Empty,
4950 return @spanned(lo, self.span.hi,
4951 ViewPathGlob(path, ast::DUMMY_NODE_ID));
4960 let last = path[path.len() - 1u];
4961 let path = ast::Path {
4962 span: mk_sp(lo, self.span.hi),
4964 segments: path.move_iter().map(|identifier| {
4966 identifier: identifier,
4967 lifetimes: opt_vec::Empty,
4968 types: opt_vec::Empty,
4974 ViewPathSimple(last, path, ast::DUMMY_NODE_ID));
4977 // matches view_paths = view_path | view_path , view_paths
4978 fn parse_view_paths(&mut self) -> ~[@ViewPath] {
4979 let mut vp = ~[self.parse_view_path()];
4980 while self.token == token::COMMA {
4982 self.obsolete(self.last_span, ObsoleteMultipleImport);
4983 vp.push(self.parse_view_path());
4988 // Parses a sequence of items. Stops when it finds program
4989 // text that can't be parsed as an item
4990 // - mod_items uses extern_mod_allowed = true
4991 // - block_tail_ uses extern_mod_allowed = false
4992 fn parse_items_and_view_items(&mut self,
4993 first_item_attrs: ~[Attribute],
4994 mut extern_mod_allowed: bool,
4995 macros_allowed: bool)
4996 -> ParsedItemsAndViewItems {
4997 let mut attrs = vec::append(first_item_attrs,
4998 self.parse_outer_attributes());
4999 // First, parse view items.
5000 let mut view_items : ~[ast::ViewItem] = ~[];
5001 let mut items = ~[];
5003 // I think this code would probably read better as a single
5004 // loop with a mutable three-state-variable (for extern mods,
5005 // view items, and regular items) ... except that because
5006 // of macros, I'd like to delay that entire check until later.
5008 match self.parse_item_or_view_item(attrs, macros_allowed) {
5009 IoviNone(attrs) => {
5010 return ParsedItemsAndViewItems {
5011 attrs_remaining: attrs,
5012 view_items: view_items,
5017 IoviViewItem(view_item) => {
5018 match view_item.node {
5019 ViewItemUse(..) => {
5020 // `extern mod` must precede `use`.
5021 extern_mod_allowed = false;
5023 ViewItemExternMod(..) if !extern_mod_allowed => {
5024 self.span_err(view_item.span,
5025 "\"extern mod\" declarations are not allowed here");
5027 ViewItemExternMod(..) => {}
5029 view_items.push(view_item);
5033 attrs = self.parse_outer_attributes();
5036 IoviForeignItem(_) => {
5040 attrs = self.parse_outer_attributes();
5043 // Next, parse items.
5045 match self.parse_item_or_view_item(attrs, macros_allowed) {
5046 IoviNone(returned_attrs) => {
5047 attrs = returned_attrs;
5050 IoviViewItem(view_item) => {
5051 attrs = self.parse_outer_attributes();
5052 self.span_err(view_item.span,
5053 "`use` and `extern mod` declarations must precede items");
5056 attrs = self.parse_outer_attributes();
5059 IoviForeignItem(_) => {
5065 ParsedItemsAndViewItems {
5066 attrs_remaining: attrs,
5067 view_items: view_items,
5073 // Parses a sequence of foreign items. Stops when it finds program
5074 // text that can't be parsed as an item
5075 fn parse_foreign_items(&mut self, first_item_attrs: ~[Attribute],
5076 macros_allowed: bool)
5077 -> ParsedItemsAndViewItems {
5078 let mut attrs = vec::append(first_item_attrs,
5079 self.parse_outer_attributes());
5080 let mut foreign_items = ~[];
5082 match self.parse_foreign_item(attrs, macros_allowed) {
5083 IoviNone(returned_attrs) => {
5084 if self.token == token::RBRACE {
5085 attrs = returned_attrs;
5090 IoviViewItem(view_item) => {
5091 // I think this can't occur:
5092 self.span_err(view_item.span,
5093 "`use` and `extern mod` declarations must precede items");
5096 // FIXME #5668: this will occur for a macro invocation:
5097 self.span_fatal(item.span, "macros cannot expand to foreign items");
5099 IoviForeignItem(foreign_item) => {
5100 foreign_items.push(foreign_item);
5103 attrs = self.parse_outer_attributes();
5106 ParsedItemsAndViewItems {
5107 attrs_remaining: attrs,
5110 foreign_items: foreign_items
5114 // Parses a source module as a crate. This is the main
5115 // entry point for the parser.
5116 pub fn parse_crate_mod(&mut self) -> Crate {
5117 let lo = self.span.lo;
5118 // parse the crate's inner attrs, maybe (oops) one
5119 // of the attrs of an item:
5120 let (inner, next) = self.parse_inner_attrs_and_next();
5121 let first_item_outer_attrs = next;
5122 // parse the items inside the crate:
5123 let m = self.parse_mod_items(token::EOF, first_item_outer_attrs);
5128 config: self.cfg.clone(),
5129 span: mk_sp(lo, self.span.lo)
5133 pub fn parse_optional_str(&mut self) -> Option<(@str, ast::StrStyle)> {
5134 let (s, style) = match self.token {
5135 token::LIT_STR(s) => (s, ast::CookedStr),
5136 token::LIT_STR_RAW(s, n) => (s, ast::RawStr(n)),
5140 Some((ident_to_str(&s), style))
5143 pub fn parse_str(&mut self) -> (@str, StrStyle) {
5144 match self.parse_optional_str() {
5146 _ => self.fatal("expected string literal")