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, is_ident, is_ident_or_path};
76 use parse::token::{is_plain_ident, keywords, special_idents, token_to_binop};
78 use parse::{new_sub_parser_from_file, ParseSess};
83 use std::hashmap::HashSet;
87 #[allow(non_camel_case_types)]
93 RESTRICT_NO_BAR_OR_DOUBLEBAR_OP,
96 type ItemInfo = (Ident, Item_, Option<~[Attribute]>);
98 /// How to parse a path. There are four different kinds of paths, all of which
99 /// are parsed somewhat differently.
101 pub enum PathParsingMode {
102 /// A path with no type parameters; e.g. `foo::bar::Baz`
104 /// A path with a lifetime and type parameters, with no double colons
105 /// before the type parameters; e.g. `foo::bar<'a>::Baz<T>`
106 LifetimeAndTypesWithoutColons,
107 /// A path with a lifetime and type parameters with double colons before
108 /// the type parameters; e.g. `foo::bar::<'a>::Baz::<T>`
109 LifetimeAndTypesWithColons,
110 /// A path with a lifetime and type parameters with bounds before the last
111 /// set of type parameters only; e.g. `foo::bar<'a>::Baz:X+Y<T>` This
112 /// form does not use extra double colons.
113 LifetimeAndTypesAndBounds,
116 /// A pair of a path segment and group of type parameter bounds. (See `ast.rs`
117 /// for the definition of a path segment.)
118 struct PathSegmentAndBoundSet {
119 segment: ast::PathSegment,
120 bound_set: Option<OptVec<TyParamBound>>,
123 /// A path paired with optional type bounds.
124 pub struct PathAndBounds {
126 bounds: Option<OptVec<TyParamBound>>,
129 enum ItemOrViewItem {
130 // Indicates a failure to parse any kind of item. The attributes are
132 IoviNone(~[Attribute]),
134 IoviForeignItem(@ForeignItem),
135 IoviViewItem(ViewItem)
138 /* The expr situation is not as complex as I thought it would be.
139 The important thing is to make sure that lookahead doesn't balk
140 at INTERPOLATED tokens */
141 macro_rules! maybe_whole_expr (
144 let mut maybe_path = match ($p).token {
145 INTERPOLATED(token::NtPath(ref pt)) => Some((**pt).clone()),
148 let ret = match ($p).token {
149 INTERPOLATED(token::NtExpr(e)) => {
152 INTERPOLATED(token::NtPath(_)) => {
153 let pt = maybe_path.take_unwrap();
154 Some($p.mk_expr(($p).span.lo, ($p).span.hi, ExprPath(pt)))
169 macro_rules! maybe_whole (
170 ($p:expr, $constructor:ident) => (
172 let __found__ = match ($p).token {
173 INTERPOLATED(token::$constructor(_)) => {
174 Some(($p).bump_and_get())
179 Some(INTERPOLATED(token::$constructor(x))) => {
186 (no_clone $p:expr, $constructor:ident) => (
188 let __found__ = match ($p).token {
189 INTERPOLATED(token::$constructor(_)) => {
190 Some(($p).bump_and_get())
195 Some(INTERPOLATED(token::$constructor(x))) => {
202 (deref $p:expr, $constructor:ident) => (
204 let __found__ = match ($p).token {
205 INTERPOLATED(token::$constructor(_)) => {
206 Some(($p).bump_and_get())
211 Some(INTERPOLATED(token::$constructor(x))) => {
218 (Some $p:expr, $constructor:ident) => (
220 let __found__ = match ($p).token {
221 INTERPOLATED(token::$constructor(_)) => {
222 Some(($p).bump_and_get())
227 Some(INTERPOLATED(token::$constructor(x))) => {
228 return Some(x.clone()),
234 (iovi $p:expr, $constructor:ident) => (
236 let __found__ = match ($p).token {
237 INTERPOLATED(token::$constructor(_)) => {
238 Some(($p).bump_and_get())
243 Some(INTERPOLATED(token::$constructor(x))) => {
244 return IoviItem(x.clone())
250 (pair_empty $p:expr, $constructor:ident) => (
252 let __found__ = match ($p).token {
253 INTERPOLATED(token::$constructor(_)) => {
254 Some(($p).bump_and_get())
259 Some(INTERPOLATED(token::$constructor(x))) => {
269 fn maybe_append(lhs: ~[Attribute], rhs: Option<~[Attribute]>)
273 Some(ref attrs) => vec::append(lhs, (*attrs))
278 struct ParsedItemsAndViewItems {
279 attrs_remaining: ~[Attribute],
280 view_items: ~[ViewItem],
282 foreign_items: ~[@ForeignItem]
285 /* ident is handled by common.rs */
287 pub fn Parser(sess: @ParseSess, cfg: ast::CrateConfig, rdr: @Reader)
289 let tok0 = rdr.next_token();
290 let interner = get_ident_interner();
292 let placeholder = TokenAndSpan {
293 tok: token::UNDERSCORE,
315 restriction: UNRESTRICTED,
317 obsolete_set: HashSet::new(),
320 non_copyable: util::NonCopyable
327 // the current token:
329 // the span of the current token:
331 // the span of the prior token:
333 // the previous token or None (only stashed sometimes).
334 last_token: Option<~token::Token>,
335 buffer: [TokenAndSpan, ..4],
338 tokens_consumed: uint,
339 restriction: restriction,
340 quote_depth: uint, // not (yet) related to the quasiquoter
342 interner: @token::IdentInterner,
343 /// The set of seen errors about obsolete syntax. Used to suppress
344 /// extra detail when the same error is seen twice
345 obsolete_set: HashSet<ObsoleteSyntax>,
346 /// Used to determine the path to externally loaded source files
347 mod_path_stack: ~[InternedString],
348 /// Stack of spans of open delimiters. Used for error message.
349 open_braces: ~[Span],
350 /* do not copy the parser; its state is tied to outside state */
351 priv non_copyable: util::NonCopyable
354 fn is_plain_ident_or_underscore(t: &token::Token) -> bool {
355 is_plain_ident(t) || *t == token::UNDERSCORE
359 // convert a token to a string using self's reader
360 pub fn token_to_str(token: &token::Token) -> ~str {
361 token::to_str(get_ident_interner(), token)
364 // convert the current token to a string using self's reader
365 pub fn this_token_to_str(&mut self) -> ~str {
366 Parser::token_to_str(&self.token)
369 pub fn unexpected_last(&mut self, t: &token::Token) -> ! {
370 let token_str = Parser::token_to_str(t);
371 self.span_fatal(self.last_span, format!("unexpected token: `{}`",
375 pub fn unexpected(&mut self) -> ! {
376 let this_token = self.this_token_to_str();
377 self.fatal(format!("unexpected token: `{}`", this_token));
380 // expect and consume the token t. Signal an error if
381 // the next token is not t.
382 pub fn expect(&mut self, t: &token::Token) {
383 if self.token == *t {
386 let token_str = Parser::token_to_str(t);
387 let this_token_str = self.this_token_to_str();
388 self.fatal(format!("expected `{}` but found `{}`",
394 // Expect next token to be edible or inedible token. If edible,
395 // then consume it; if inedible, then return without consuming
396 // anything. Signal a fatal error if next token is unexpected.
397 pub fn expect_one_of(&mut self,
398 edible: &[token::Token],
399 inedible: &[token::Token]) {
400 fn tokens_to_str(tokens: &[token::Token]) -> ~str {
401 let mut i = tokens.iter();
402 // This might be a sign we need a connect method on Iterator.
403 let b = i.next().map_or(~"", |t| Parser::token_to_str(t));
404 i.fold(b, |b,a| b + "`, `" + Parser::token_to_str(a))
406 if edible.contains(&self.token) {
408 } else if inedible.contains(&self.token) {
409 // leave it in the input
411 let expected = vec::append(edible.to_owned(), inedible);
412 let expect = tokens_to_str(expected);
413 let actual = self.this_token_to_str();
415 if expected.len() != 1 {
416 format!("expected one of `{}` but found `{}`", expect, actual)
418 format!("expected `{}` but found `{}`", expect, actual)
424 // Check for erroneous `ident { }`; if matches, signal error and
425 // recover (without consuming any expected input token). Returns
426 // true if and only if input was consumed for recovery.
427 pub fn check_for_erroneous_unit_struct_expecting(&mut self, expected: &[token::Token]) -> bool {
428 if self.token == token::LBRACE
429 && expected.iter().all(|t| *t != token::LBRACE)
430 && self.look_ahead(1, |t| *t == token::RBRACE) {
431 // matched; signal non-fatal error and recover.
432 self.span_err(self.span,
433 "Unit-like struct construction is written with no trailing `{ }`");
434 self.eat(&token::LBRACE);
435 self.eat(&token::RBRACE);
442 // Commit to parsing a complete expression `e` expected to be
443 // followed by some token from the set edible + inedible. Recover
444 // from anticipated input errors, discarding erroneous characters.
445 pub fn commit_expr(&mut self, e: @Expr, edible: &[token::Token], inedible: &[token::Token]) {
446 debug!("commit_expr {:?}", e);
449 // might be unit-struct construction; check for recoverableinput error.
450 let expected = vec::append(edible.to_owned(), inedible);
451 self.check_for_erroneous_unit_struct_expecting(expected);
455 self.expect_one_of(edible, inedible)
458 pub fn commit_expr_expecting(&mut self, e: @Expr, edible: token::Token) {
459 self.commit_expr(e, &[edible], &[])
462 // Commit to parsing a complete statement `s`, which expects to be
463 // followed by some token from the set edible + inedible. Check
464 // for recoverable input errors, discarding erroneous characters.
465 pub fn commit_stmt(&mut self, s: @Stmt, edible: &[token::Token], inedible: &[token::Token]) {
466 debug!("commit_stmt {:?}", s);
467 let _s = s; // unused, but future checks might want to inspect `s`.
468 if self.last_token.as_ref().map_or(false, |t| is_ident_or_path(*t)) {
469 let expected = vec::append(edible.to_owned(), inedible);
470 self.check_for_erroneous_unit_struct_expecting(expected);
472 self.expect_one_of(edible, inedible)
475 pub fn commit_stmt_expecting(&mut self, s: @Stmt, edible: token::Token) {
476 self.commit_stmt(s, &[edible], &[])
479 pub fn parse_ident(&mut self) -> ast::Ident {
480 self.check_strict_keywords();
481 self.check_reserved_keywords();
483 token::IDENT(i, _) => {
487 token::INTERPOLATED(token::NtIdent(..)) => {
488 self.bug("ident interpolation not converted to real token");
491 let token_str = self.this_token_to_str();
492 self.fatal(format!( "expected ident, found `{}`", token_str))
497 pub fn parse_path_list_ident(&mut self) -> ast::PathListIdent {
498 let lo = self.span.lo;
499 let ident = self.parse_ident();
500 let hi = self.last_span.hi;
501 spanned(lo, hi, ast::PathListIdent_ { name: ident,
502 id: ast::DUMMY_NODE_ID })
505 // consume token 'tok' if it exists. Returns true if the given
506 // token was present, false otherwise.
507 pub fn eat(&mut self, tok: &token::Token) -> bool {
508 let is_present = self.token == *tok;
509 if is_present { self.bump() }
513 pub fn is_keyword(&mut self, kw: keywords::Keyword) -> bool {
514 token::is_keyword(kw, &self.token)
517 // if the next token is the given keyword, eat it and return
518 // true. Otherwise, return false.
519 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
520 let is_kw = match self.token {
521 token::IDENT(sid, false) => kw.to_ident().name == sid.name,
524 if is_kw { self.bump() }
528 // if the given word is not a keyword, signal an error.
529 // if the next token is not the given word, signal an error.
530 // otherwise, eat it.
531 pub fn expect_keyword(&mut self, kw: keywords::Keyword) {
532 if !self.eat_keyword(kw) {
533 let id_ident = kw.to_ident();
534 let id_interned_str = token::get_ident(id_ident.name);
535 let token_str = self.this_token_to_str();
536 self.fatal(format!("expected `{}`, found `{}`",
537 id_interned_str.get(),
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_interned_str(&mut self, id: Ident) -> InternedString {
809 // Is the current token one of the keywords that signals a bare function
811 pub fn token_is_bare_fn_keyword(&mut self) -> bool {
812 if token::is_keyword(keywords::Fn, &self.token) {
816 if token::is_keyword(keywords::Unsafe, &self.token) ||
817 token::is_keyword(keywords::Once, &self.token) {
818 return self.look_ahead(1, |t| token::is_keyword(keywords::Fn, t))
824 // Is the current token one of the keywords that signals a closure type?
825 pub fn token_is_closure_keyword(&mut self) -> bool {
826 token::is_keyword(keywords::Unsafe, &self.token) ||
827 token::is_keyword(keywords::Once, &self.token)
830 // Is the current token one of the keywords that signals an old-style
831 // closure type (with explicit sigil)?
832 pub fn token_is_old_style_closure_keyword(&mut self) -> bool {
833 token::is_keyword(keywords::Unsafe, &self.token) ||
834 token::is_keyword(keywords::Once, &self.token) ||
835 token::is_keyword(keywords::Fn, &self.token)
838 pub fn token_is_lifetime(tok: &token::Token) -> bool {
840 token::LIFETIME(..) => true,
845 pub fn get_lifetime(&mut self) -> ast::Ident {
847 token::LIFETIME(ref ident) => *ident,
848 _ => self.bug("not a lifetime"),
852 // parse a TyBareFn type:
853 pub fn parse_ty_bare_fn(&mut self) -> Ty_ {
856 [extern "ABI"] [unsafe] fn <'lt> (S) -> T
857 ^~~~^ ^~~~~~~^ ^~~~^ ^~^ ^
868 let opt_abis = self.parse_opt_abis();
869 let abis = opt_abis.unwrap_or(AbiSet::Rust());
870 let purity = self.parse_unsafety();
871 self.expect_keyword(keywords::Fn);
872 let (decl, lifetimes) = self.parse_ty_fn_decl(true);
873 return TyBareFn(@BareFnTy {
876 lifetimes: lifetimes,
881 // Parses a procedure type (`proc`). The initial `proc` keyword must
882 // already have been parsed.
883 pub fn parse_proc_type(&mut self) -> Ty_ {
884 let (decl, lifetimes) = self.parse_ty_fn_decl(false);
885 TyClosure(@ClosureTy {
892 lifetimes: lifetimes,
896 // parse a TyClosure type
897 pub fn parse_ty_closure(&mut self,
898 opt_sigil: Option<ast::Sigil>,
899 mut region: Option<ast::Lifetime>)
903 (&|~|@) ['r] [unsafe] [once] fn [:Bounds] <'lt> (S) -> T
904 ^~~~~~^ ^~~^ ^~~~~~~^ ^~~~~^ ^~~~~~~~^ ^~~~^ ^~^ ^
906 | | | | | | | Return type
907 | | | | | | Argument types
909 | | | | Closure bounds
910 | | | Once-ness (a.k.a., affine)
917 // At this point, the allocation type and lifetime bound have been
920 let purity = self.parse_unsafety();
921 let onceness = parse_onceness(self);
923 let (sigil, decl, lifetimes, bounds) = match opt_sigil {
925 // Old-style closure syntax (`fn(A)->B`).
926 self.expect_keyword(keywords::Fn);
927 let bounds = self.parse_optional_ty_param_bounds();
928 let (decl, lifetimes) = self.parse_ty_fn_decl(false);
929 (sigil, decl, lifetimes, bounds)
932 // New-style closure syntax (`<'lt>|A|:K -> B`).
933 let lifetimes = if self.eat(&token::LT) {
934 let lifetimes = self.parse_lifetimes();
937 // Re-parse the region here. What a hack.
938 if region.is_some() {
939 self.span_err(self.last_span,
940 "lifetime declarations must precede \
941 the lifetime associated with a \
944 region = self.parse_opt_lifetime();
951 let inputs = if self.eat(&token::OROR) {
955 let inputs = self.parse_seq_to_before_or(
957 |p| p.parse_arg_general(false));
962 let bounds = self.parse_optional_ty_param_bounds();
964 let (return_style, output) = self.parse_ret_ty();
965 let decl = P(FnDecl {
972 (BorrowedSigil, decl, lifetimes, bounds)
976 return TyClosure(@ClosureTy {
983 lifetimes: lifetimes,
986 fn parse_onceness(this: &mut Parser) -> Onceness {
987 if this.eat_keyword(keywords::Once) {
995 pub fn parse_unsafety(&mut self) -> Purity {
996 if self.eat_keyword(keywords::Unsafe) {
1003 // parse a function type (following the 'fn')
1004 pub fn parse_ty_fn_decl(&mut self, allow_variadic: bool)
1005 -> (P<FnDecl>, OptVec<ast::Lifetime>) {
1016 let lifetimes = if self.eat(&token::LT) {
1017 let lifetimes = self.parse_lifetimes();
1024 let (inputs, variadic) = self.parse_fn_args(false, allow_variadic);
1025 let (ret_style, ret_ty) = self.parse_ret_ty();
1026 let decl = P(FnDecl {
1035 // parse the methods in a trait declaration
1036 pub fn parse_trait_methods(&mut self) -> ~[TraitMethod] {
1037 self.parse_unspanned_seq(
1042 let attrs = p.parse_outer_attributes();
1045 let vis_span = p.span;
1046 let vis = p.parse_visibility();
1047 let pur = p.parse_fn_purity();
1048 // NB: at the moment, trait methods are public by default; this
1050 let ident = p.parse_ident();
1052 let generics = p.parse_generics();
1054 let (explicit_self, d) = p.parse_fn_decl_with_self(|p| {
1055 // This is somewhat dubious; We don't want to allow argument
1056 // names to be left off if there is a definition...
1057 p.parse_arg_general(false)
1060 let hi = p.last_span.hi;
1064 debug!("parse_trait_methods(): parsing required method");
1065 // NB: at the moment, visibility annotations on required
1066 // methods are ignored; this could change.
1067 if vis != ast::Inherited {
1068 p.obsolete(vis_span, ObsoleteTraitFuncVisibility);
1070 Required(TypeMethod {
1076 explicit_self: explicit_self,
1077 id: ast::DUMMY_NODE_ID,
1082 debug!("parse_trait_methods(): parsing provided method");
1083 let (inner_attrs, body) =
1084 p.parse_inner_attrs_and_block();
1085 let attrs = vec::append(attrs, inner_attrs);
1086 Provided(@ast::Method {
1090 explicit_self: explicit_self,
1094 id: ast::DUMMY_NODE_ID,
1095 span: mk_sp(lo, hi),
1101 let token_str = p.this_token_to_str();
1102 p.fatal(format!("expected `;` or `\\{` but found `{}`",
1109 // parse a possibly mutable type
1110 pub fn parse_mt(&mut self) -> MutTy {
1111 let mutbl = self.parse_mutability();
1112 let t = self.parse_ty(false);
1113 MutTy { ty: t, mutbl: mutbl }
1116 // parse [mut/const/imm] ID : TY
1117 // now used only by obsolete record syntax parser...
1118 pub fn parse_ty_field(&mut self) -> TypeField {
1119 let lo = self.span.lo;
1120 let mutbl = self.parse_mutability();
1121 let id = self.parse_ident();
1122 self.expect(&token::COLON);
1123 let ty = self.parse_ty(false);
1124 let hi = ty.span.hi;
1127 mt: MutTy { ty: ty, mutbl: mutbl },
1128 span: mk_sp(lo, hi),
1132 // parse optional return type [ -> TY ] in function decl
1133 pub fn parse_ret_ty(&mut self) -> (RetStyle, P<Ty>) {
1134 return if self.eat(&token::RARROW) {
1135 let lo = self.span.lo;
1136 if self.eat(&token::NOT) {
1140 id: ast::DUMMY_NODE_ID,
1142 span: mk_sp(lo, self.last_span.hi)
1146 (Return, self.parse_ty(false))
1149 let pos = self.span.lo;
1153 id: ast::DUMMY_NODE_ID,
1155 span: mk_sp(pos, pos),
1162 // Useless second parameter for compatibility with quasiquote macros.
1164 pub fn parse_ty(&mut self, _: bool) -> P<Ty> {
1165 maybe_whole!(no_clone self, NtTy);
1167 let lo = self.span.lo;
1169 let t = if self.token == token::LPAREN {
1171 if self.token == token::RPAREN {
1175 // (t) is a parenthesized ty
1176 // (t,) is the type of a tuple with only one field,
1178 let mut ts = ~[self.parse_ty(false)];
1179 let mut one_tuple = false;
1180 while self.token == token::COMMA {
1182 if self.token != token::RPAREN {
1183 ts.push(self.parse_ty(false));
1190 if ts.len() == 1 && !one_tuple {
1191 self.expect(&token::RPAREN);
1196 self.expect(&token::RPAREN);
1199 } else if self.token == token::AT {
1202 self.parse_box_or_uniq_pointee(ManagedSigil)
1203 } else if self.token == token::TILDE {
1206 self.parse_box_or_uniq_pointee(OwnedSigil)
1207 } else if self.token == token::BINOP(token::STAR) {
1208 // STAR POINTER (bare pointer?)
1210 TyPtr(self.parse_mt())
1211 } else if self.token == token::LBRACKET {
1213 self.expect(&token::LBRACKET);
1214 let t = self.parse_ty(false);
1216 // Parse the `, ..e` in `[ int, ..e ]`
1217 // where `e` is a const expression
1218 let t = match self.maybe_parse_fixed_vstore() {
1220 Some(suffix) => TyFixedLengthVec(t, suffix)
1222 self.expect(&token::RBRACKET);
1224 } else if self.token == token::BINOP(token::AND) {
1227 self.parse_borrowed_pointee()
1228 } else if self.is_keyword(keywords::Extern) ||
1229 self.token_is_bare_fn_keyword() {
1231 self.parse_ty_bare_fn()
1232 } else if self.token_is_closure_keyword() ||
1233 self.token == token::BINOP(token::OR) ||
1234 self.token == token::OROR ||
1235 self.token == token::LT ||
1236 Parser::token_is_lifetime(&self.token) {
1239 // FIXME(pcwalton): Eventually `token::LT` will not unambiguously
1240 // introduce a closure, once procs can have lifetime bounds. We
1241 // will need to refactor the grammar a little bit at that point.
1243 let lifetime = self.parse_opt_lifetime();
1244 let result = self.parse_ty_closure(None, lifetime);
1246 } else if self.eat_keyword(keywords::Typeof) {
1248 // In order to not be ambiguous, the type must be surrounded by parens.
1249 self.expect(&token::LPAREN);
1250 let e = self.parse_expr();
1251 self.expect(&token::RPAREN);
1253 } else if self.eat_keyword(keywords::Proc) {
1254 self.parse_proc_type()
1255 } else if self.token == token::MOD_SEP
1256 || is_ident_or_path(&self.token) {
1261 } = self.parse_path(LifetimeAndTypesAndBounds);
1262 TyPath(path, bounds, ast::DUMMY_NODE_ID)
1264 let msg = format!("expected type, found token {:?}", self.token);
1268 let sp = mk_sp(lo, self.last_span.hi);
1269 P(Ty {id: ast::DUMMY_NODE_ID, node: t, span: sp})
1272 // parse the type following a @ or a ~
1273 pub fn parse_box_or_uniq_pointee(&mut self,
1276 // ~'foo fn() or ~fn() are parsed directly as obsolete fn types:
1278 token::LIFETIME(..) => {
1279 let lifetime = self.parse_lifetime();
1280 self.obsolete(self.last_span, ObsoleteBoxedClosure);
1281 return self.parse_ty_closure(Some(sigil), Some(lifetime));
1284 token::IDENT(..) => {
1285 if self.token_is_old_style_closure_keyword() {
1286 self.obsolete(self.last_span, ObsoleteBoxedClosure);
1287 return self.parse_ty_closure(Some(sigil), None);
1293 // other things are parsed as @/~ + a type. Note that constructs like
1294 // @[] and @str will be resolved during typeck to slices and so forth,
1295 // rather than boxed ptrs. But the special casing of str/vec is not
1296 // reflected in the AST type.
1297 if sigil == OwnedSigil {
1298 TyUniq(self.parse_ty(false))
1300 TyBox(self.parse_ty(false))
1304 pub fn parse_borrowed_pointee(&mut self) -> Ty_ {
1305 // look for `&'lt` or `&'foo ` and interpret `foo` as the region name:
1306 let opt_lifetime = self.parse_opt_lifetime();
1308 if self.token_is_old_style_closure_keyword() {
1309 self.obsolete(self.last_span, ObsoleteClosureType);
1310 return self.parse_ty_closure(Some(BorrowedSigil), opt_lifetime);
1313 let mt = self.parse_mt();
1314 return TyRptr(opt_lifetime, mt);
1317 pub fn is_named_argument(&mut self) -> bool {
1318 let offset = match self.token {
1319 token::BINOP(token::AND) => 1,
1321 _ if token::is_keyword(keywords::Mut, &self.token) => 1,
1325 debug!("parser is_named_argument offset:{}", offset);
1328 is_plain_ident_or_underscore(&self.token)
1329 && self.look_ahead(1, |t| *t == token::COLON)
1331 self.look_ahead(offset, |t| is_plain_ident_or_underscore(t))
1332 && self.look_ahead(offset + 1, |t| *t == token::COLON)
1336 // This version of parse arg doesn't necessarily require
1337 // identifier names.
1338 pub fn parse_arg_general(&mut self, require_name: bool) -> Arg {
1339 let pat = if require_name || self.is_named_argument() {
1340 debug!("parse_arg_general parse_pat (require_name:{:?})",
1342 let pat = self.parse_pat();
1344 self.expect(&token::COLON);
1347 debug!("parse_arg_general ident_to_pat");
1348 ast_util::ident_to_pat(ast::DUMMY_NODE_ID,
1350 special_idents::invalid)
1353 let t = self.parse_ty(false);
1358 id: ast::DUMMY_NODE_ID,
1362 // parse a single function argument
1363 pub fn parse_arg(&mut self) -> Arg {
1364 self.parse_arg_general(true)
1367 // parse an argument in a lambda header e.g. |arg, arg|
1368 pub fn parse_fn_block_arg(&mut self) -> Arg {
1369 let pat = self.parse_pat();
1370 let t = if self.eat(&token::COLON) {
1371 self.parse_ty(false)
1374 id: ast::DUMMY_NODE_ID,
1376 span: mk_sp(self.span.lo, self.span.hi),
1382 id: ast::DUMMY_NODE_ID
1386 pub fn maybe_parse_fixed_vstore(&mut self) -> Option<@ast::Expr> {
1387 if self.token == token::COMMA &&
1388 self.look_ahead(1, |t| *t == token::DOTDOT) {
1391 Some(self.parse_expr())
1397 // matches token_lit = LIT_INT | ...
1398 pub fn lit_from_token(&mut self, tok: &token::Token) -> Lit_ {
1400 token::LIT_CHAR(i) => LitChar(i),
1401 token::LIT_INT(i, it) => LitInt(i, it),
1402 token::LIT_UINT(u, ut) => LitUint(u, ut),
1403 token::LIT_INT_UNSUFFIXED(i) => LitIntUnsuffixed(i),
1404 token::LIT_FLOAT(s, ft) => {
1405 LitFloat(self.id_to_interned_str(s), ft)
1407 token::LIT_FLOAT_UNSUFFIXED(s) => {
1408 LitFloatUnsuffixed(self.id_to_interned_str(s))
1410 token::LIT_STR(s) => {
1411 LitStr(self.id_to_interned_str(s), ast::CookedStr)
1413 token::LIT_STR_RAW(s, n) => {
1414 LitStr(self.id_to_interned_str(s), ast::RawStr(n))
1416 token::LPAREN => { self.expect(&token::RPAREN); LitNil },
1417 _ => { self.unexpected_last(tok); }
1421 // matches lit = true | false | token_lit
1422 pub fn parse_lit(&mut self) -> Lit {
1423 let lo = self.span.lo;
1424 let lit = if self.eat_keyword(keywords::True) {
1426 } else if self.eat_keyword(keywords::False) {
1429 let token = self.bump_and_get();
1430 let lit = self.lit_from_token(&token);
1433 codemap::Spanned { node: lit, span: mk_sp(lo, self.last_span.hi) }
1436 // matches '-' lit | lit
1437 pub fn parse_literal_maybe_minus(&mut self) -> @Expr {
1438 let minus_lo = self.span.lo;
1439 let minus_present = self.eat(&token::BINOP(token::MINUS));
1441 let lo = self.span.lo;
1442 let literal = @self.parse_lit();
1443 let hi = self.span.hi;
1444 let expr = self.mk_expr(lo, hi, ExprLit(literal));
1447 let minus_hi = self.span.hi;
1448 let unary = self.mk_unary(UnNeg, expr);
1449 self.mk_expr(minus_lo, minus_hi, unary)
1455 /// Parses a path and optional type parameter bounds, depending on the
1456 /// mode. The `mode` parameter determines whether lifetimes, types, and/or
1457 /// bounds are permitted and whether `::` must precede type parameter
1459 pub fn parse_path(&mut self, mode: PathParsingMode) -> PathAndBounds {
1460 // Check for a whole path...
1461 let found = match self.token {
1462 INTERPOLATED(token::NtPath(_)) => Some(self.bump_and_get()),
1466 Some(INTERPOLATED(token::NtPath(~path))) => {
1467 return PathAndBounds {
1475 let lo = self.span.lo;
1476 let is_global = self.eat(&token::MOD_SEP);
1478 // Parse any number of segments and bound sets. A segment is an
1479 // identifier followed by an optional lifetime and a set of types.
1480 // A bound set is a set of type parameter bounds.
1481 let mut segments = ~[];
1483 // First, parse an identifier.
1484 let identifier = self.parse_ident();
1486 // Next, parse a colon and bounded type parameters, if applicable.
1487 let bound_set = if mode == LifetimeAndTypesAndBounds {
1488 self.parse_optional_ty_param_bounds()
1493 // Parse the '::' before type parameters if it's required. If
1494 // it is required and wasn't present, then we're done.
1495 if mode == LifetimeAndTypesWithColons &&
1496 !self.eat(&token::MOD_SEP) {
1497 segments.push(PathSegmentAndBoundSet {
1498 segment: ast::PathSegment {
1499 identifier: identifier,
1500 lifetimes: opt_vec::Empty,
1501 types: opt_vec::Empty,
1503 bound_set: bound_set
1508 // Parse the `<` before the lifetime and types, if applicable.
1509 let (any_lifetime_or_types, lifetimes, types) = {
1510 if mode != NoTypesAllowed && self.eat(&token::LT) {
1511 let (lifetimes, types) =
1512 self.parse_generic_values_after_lt();
1513 (true, lifetimes, opt_vec::from(types))
1515 (false, opt_vec::Empty, opt_vec::Empty)
1519 // Assemble and push the result.
1520 segments.push(PathSegmentAndBoundSet {
1521 segment: ast::PathSegment {
1522 identifier: identifier,
1523 lifetimes: lifetimes,
1526 bound_set: bound_set
1529 // We're done if we don't see a '::', unless the mode required
1530 // a double colon to get here in the first place.
1531 if !(mode == LifetimeAndTypesWithColons &&
1532 !any_lifetime_or_types) {
1533 if !self.eat(&token::MOD_SEP) {
1539 // Assemble the span.
1540 let span = mk_sp(lo, self.last_span.hi);
1542 // Assemble the path segments.
1543 let mut path_segments = ~[];
1544 let mut bounds = None;
1545 let last_segment_index = segments.len() - 1;
1546 for (i, segment_and_bounds) in segments.move_iter().enumerate() {
1547 let PathSegmentAndBoundSet {
1549 bound_set: bound_set
1550 } = segment_and_bounds;
1551 path_segments.push(segment);
1553 if bound_set.is_some() {
1554 if i != last_segment_index {
1556 "type parameter bounds are allowed only \
1557 before the last segment in a path")
1564 // Assemble the result.
1565 let path_and_bounds = PathAndBounds {
1569 segments: path_segments,
1577 /// parses 0 or 1 lifetime
1578 pub fn parse_opt_lifetime(&mut self) -> Option<ast::Lifetime> {
1580 token::LIFETIME(..) => {
1581 Some(self.parse_lifetime())
1589 /// Parses a single lifetime
1590 // matches lifetime = LIFETIME
1591 pub fn parse_lifetime(&mut self) -> ast::Lifetime {
1593 token::LIFETIME(i) => {
1594 let span = self.span;
1596 return ast::Lifetime {
1597 id: ast::DUMMY_NODE_ID,
1603 self.fatal(format!("Expected a lifetime name"));
1608 // matches lifetimes = ( lifetime ) | ( lifetime , lifetimes )
1609 // actually, it matches the empty one too, but putting that in there
1610 // messes up the grammar....
1611 pub fn parse_lifetimes(&mut self) -> OptVec<ast::Lifetime> {
1614 * Parses zero or more comma separated lifetimes.
1615 * Expects each lifetime to be followed by either
1616 * a comma or `>`. Used when parsing type parameter
1617 * lists, where we expect something like `<'a, 'b, T>`.
1620 let mut res = opt_vec::Empty;
1623 token::LIFETIME(_) => {
1624 res.push(self.parse_lifetime());
1632 token::COMMA => { self.bump();}
1633 token::GT => { return res; }
1634 token::BINOP(token::SHR) => { return res; }
1636 let msg = format!("expected `,` or `>` after lifetime \
1645 pub fn token_is_mutability(tok: &token::Token) -> bool {
1646 token::is_keyword(keywords::Mut, tok) ||
1647 token::is_keyword(keywords::Const, tok)
1650 // parse mutability declaration (mut/const/imm)
1651 pub fn parse_mutability(&mut self) -> Mutability {
1652 if self.eat_keyword(keywords::Mut) {
1654 } else if self.eat_keyword(keywords::Const) {
1655 self.obsolete(self.last_span, ObsoleteConstPointer);
1662 // parse ident COLON expr
1663 pub fn parse_field(&mut self) -> Field {
1664 let lo = self.span.lo;
1665 let i = self.parse_ident();
1666 let hi = self.last_span.hi;
1667 self.expect(&token::COLON);
1668 let e = self.parse_expr();
1670 ident: spanned(lo, hi, i),
1672 span: mk_sp(lo, e.span.hi),
1676 pub fn mk_expr(&mut self, lo: BytePos, hi: BytePos, node: Expr_) -> @Expr {
1678 id: ast::DUMMY_NODE_ID,
1680 span: mk_sp(lo, hi),
1684 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: @Expr) -> ast::Expr_ {
1685 ExprUnary(ast::DUMMY_NODE_ID, unop, expr)
1688 pub fn mk_binary(&mut self, binop: ast::BinOp, lhs: @Expr, rhs: @Expr) -> ast::Expr_ {
1689 ExprBinary(ast::DUMMY_NODE_ID, binop, lhs, rhs)
1692 pub fn mk_call(&mut self, f: @Expr, args: ~[@Expr], sugar: CallSugar) -> ast::Expr_ {
1693 ExprCall(f, args, sugar)
1696 fn mk_method_call(&mut self, ident: Ident, tps: ~[P<Ty>], args: ~[@Expr],
1697 sugar: CallSugar) -> ast::Expr_ {
1698 ExprMethodCall(ast::DUMMY_NODE_ID, ident, tps, args, sugar)
1701 pub fn mk_index(&mut self, expr: @Expr, idx: @Expr) -> ast::Expr_ {
1702 ExprIndex(ast::DUMMY_NODE_ID, expr, idx)
1705 pub fn mk_field(&mut self, expr: @Expr, ident: Ident, tys: ~[P<Ty>]) -> ast::Expr_ {
1706 ExprField(expr, ident, tys)
1709 pub fn mk_assign_op(&mut self, binop: ast::BinOp, lhs: @Expr, rhs: @Expr) -> ast::Expr_ {
1710 ExprAssignOp(ast::DUMMY_NODE_ID, binop, lhs, rhs)
1713 pub fn mk_mac_expr(&mut self, lo: BytePos, hi: BytePos, m: Mac_) -> @Expr {
1715 id: ast::DUMMY_NODE_ID,
1716 node: ExprMac(codemap::Spanned {node: m, span: mk_sp(lo, hi)}),
1717 span: mk_sp(lo, hi),
1721 pub fn mk_lit_u32(&mut self, i: u32) -> @Expr {
1722 let span = &self.span;
1723 let lv_lit = @codemap::Spanned {
1724 node: LitUint(i as u64, TyU32),
1729 id: ast::DUMMY_NODE_ID,
1730 node: ExprLit(lv_lit),
1735 // at the bottom (top?) of the precedence hierarchy,
1736 // parse things like parenthesized exprs,
1737 // macros, return, etc.
1738 pub fn parse_bottom_expr(&mut self) -> @Expr {
1739 maybe_whole_expr!(self);
1741 let lo = self.span.lo;
1742 let mut hi = self.span.hi;
1746 if self.token == token::LPAREN {
1748 // (e) is parenthesized e
1749 // (e,) is a tuple with only one field, e
1750 let mut trailing_comma = false;
1751 if self.token == token::RPAREN {
1754 let lit = @spanned(lo, hi, LitNil);
1755 return self.mk_expr(lo, hi, ExprLit(lit));
1757 let mut es = ~[self.parse_expr()];
1758 self.commit_expr(*es.last().unwrap(), &[], &[token::COMMA, token::RPAREN]);
1759 while self.token == token::COMMA {
1761 if self.token != token::RPAREN {
1762 es.push(self.parse_expr());
1763 self.commit_expr(*es.last().unwrap(), &[], &[token::COMMA, token::RPAREN]);
1766 trailing_comma = true;
1770 self.commit_expr_expecting(*es.last().unwrap(), token::RPAREN);
1772 return if es.len() == 1 && !trailing_comma {
1773 self.mk_expr(lo, self.span.hi, ExprParen(es[0]))
1776 self.mk_expr(lo, hi, ExprTup(es))
1778 } else if self.token == token::LBRACE {
1780 let blk = self.parse_block_tail(lo, DefaultBlock);
1781 return self.mk_expr(blk.span.lo, blk.span.hi,
1783 } else if token::is_bar(&self.token) {
1784 return self.parse_lambda_expr();
1785 } else if self.eat_keyword(keywords::Proc) {
1786 let decl = self.parse_proc_decl();
1787 let body = self.parse_expr();
1788 let fakeblock = P(ast::Block {
1792 id: ast::DUMMY_NODE_ID,
1793 rules: DefaultBlock,
1797 return self.mk_expr(lo, body.span.hi, ExprProc(decl, fakeblock));
1798 } else if self.eat_keyword(keywords::Self) {
1799 let path = ast_util::ident_to_path(mk_sp(lo, hi), special_idents::self_);
1800 ex = ExprPath(path);
1802 } else if self.eat_keyword(keywords::If) {
1803 return self.parse_if_expr();
1804 } else if self.eat_keyword(keywords::For) {
1805 return self.parse_for_expr(None);
1806 } else if self.eat_keyword(keywords::While) {
1807 return self.parse_while_expr();
1808 } else if Parser::token_is_lifetime(&self.token) {
1809 let lifetime = self.get_lifetime();
1811 self.expect(&token::COLON);
1812 if self.eat_keyword(keywords::For) {
1813 return self.parse_for_expr(Some(lifetime))
1814 } else if self.eat_keyword(keywords::Loop) {
1815 return self.parse_loop_expr(Some(lifetime))
1817 self.fatal("expected `for` or `loop` after a label")
1819 } else if self.eat_keyword(keywords::Loop) {
1820 return self.parse_loop_expr(None);
1821 } else if self.eat_keyword(keywords::Continue) {
1822 let lo = self.span.lo;
1823 let ex = if Parser::token_is_lifetime(&self.token) {
1824 let lifetime = self.get_lifetime();
1826 ExprAgain(Some(lifetime.name))
1830 let hi = self.span.hi;
1831 return self.mk_expr(lo, hi, ex);
1832 } else if self.eat_keyword(keywords::Match) {
1833 return self.parse_match_expr();
1834 } else if self.eat_keyword(keywords::Unsafe) {
1835 return self.parse_block_expr(lo, UnsafeBlock(ast::UserProvided));
1836 } else if self.token == token::LBRACKET {
1838 let mutbl = MutImmutable;
1840 if self.token == token::RBRACKET {
1843 ex = ExprVec(~[], mutbl);
1846 let first_expr = self.parse_expr();
1847 if self.token == token::COMMA &&
1848 self.look_ahead(1, |t| *t == token::DOTDOT) {
1849 // Repeating vector syntax: [ 0, ..512 ]
1852 let count = self.parse_expr();
1853 self.expect(&token::RBRACKET);
1854 ex = ExprRepeat(first_expr, count, mutbl);
1855 } else if self.token == token::COMMA {
1856 // Vector with two or more elements.
1858 let remaining_exprs = self.parse_seq_to_end(
1860 seq_sep_trailing_allowed(token::COMMA),
1863 ex = ExprVec(~[first_expr] + remaining_exprs, mutbl);
1865 // Vector with one element.
1866 self.expect(&token::RBRACKET);
1867 ex = ExprVec(~[first_expr], mutbl);
1870 hi = self.last_span.hi;
1871 } else if self.eat_keyword(keywords::__LogLevel) {
1872 // LOG LEVEL expression
1873 self.expect(&token::LPAREN);
1876 self.expect(&token::RPAREN);
1877 } else if self.eat_keyword(keywords::Return) {
1878 // RETURN expression
1879 if can_begin_expr(&self.token) {
1880 let e = self.parse_expr();
1882 ex = ExprRet(Some(e));
1883 } else { ex = ExprRet(None); }
1884 } else if self.eat_keyword(keywords::Break) {
1886 if Parser::token_is_lifetime(&self.token) {
1887 let lifetime = self.get_lifetime();
1889 ex = ExprBreak(Some(lifetime.name));
1891 ex = ExprBreak(None);
1894 } else if self.token == token::MOD_SEP ||
1895 is_ident(&self.token) && !self.is_keyword(keywords::True) &&
1896 !self.is_keyword(keywords::False) {
1897 let pth = self.parse_path(LifetimeAndTypesWithColons).path;
1899 // `!`, as an operator, is prefix, so we know this isn't that
1900 if self.token == token::NOT {
1901 // MACRO INVOCATION expression
1904 token::LPAREN | token::LBRACE => {}
1905 _ => self.fatal("expected open delimiter")
1908 let ket = token::flip_delimiter(&self.token);
1911 let tts = self.parse_seq_to_end(&ket,
1913 |p| p.parse_token_tree());
1914 let hi = self.span.hi;
1916 return self.mk_mac_expr(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT));
1917 } else if self.token == token::LBRACE {
1918 // This might be a struct literal.
1919 if self.looking_at_struct_literal() {
1920 // It's a struct literal.
1922 let mut fields = ~[];
1923 let mut base = None;
1925 while self.token != token::RBRACE {
1926 if self.eat(&token::DOTDOT) {
1927 base = Some(self.parse_expr());
1931 fields.push(self.parse_field());
1932 self.commit_expr(fields.last().unwrap().expr,
1933 &[token::COMMA], &[token::RBRACE]);
1937 self.expect(&token::RBRACE);
1938 ex = ExprStruct(pth, fields, base);
1939 return self.mk_expr(lo, hi, ex);
1946 // other literal expression
1947 let lit = self.parse_lit();
1952 return self.mk_expr(lo, hi, ex);
1955 // parse a block or unsafe block
1956 pub fn parse_block_expr(&mut self, lo: BytePos, blk_mode: BlockCheckMode)
1958 self.expect(&token::LBRACE);
1959 let blk = self.parse_block_tail(lo, blk_mode);
1960 return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk));
1963 // parse a.b or a(13) or a[4] or just a
1964 pub fn parse_dot_or_call_expr(&mut self) -> @Expr {
1965 let b = self.parse_bottom_expr();
1966 self.parse_dot_or_call_expr_with(b)
1969 pub fn parse_dot_or_call_expr_with(&mut self, e0: @Expr) -> @Expr {
1975 if self.eat(&token::DOT) {
1977 token::IDENT(i, _) => {
1980 let (_, tys) = if self.eat(&token::MOD_SEP) {
1981 self.expect(&token::LT);
1982 self.parse_generic_values_after_lt()
1984 (opt_vec::Empty, ~[])
1987 // expr.f() method call
1990 let mut es = self.parse_unspanned_seq(
1993 seq_sep_trailing_disallowed(token::COMMA),
1999 let nd = self.mk_method_call(i, tys, es, NoSugar);
2000 e = self.mk_expr(lo, hi, nd);
2003 let field = self.mk_field(e, i, tys);
2004 e = self.mk_expr(lo, hi, field)
2008 _ => self.unexpected()
2012 if self.expr_is_complete(e) { break; }
2016 let es = self.parse_unspanned_seq(
2019 seq_sep_trailing_allowed(token::COMMA),
2022 hi = self.last_span.hi;
2024 let nd = self.mk_call(e, es, NoSugar);
2025 e = self.mk_expr(lo, hi, nd);
2029 token::LBRACKET => {
2031 let ix = self.parse_expr();
2033 self.commit_expr_expecting(ix, token::RBRACKET);
2034 let index = self.mk_index(e, ix);
2035 e = self.mk_expr(lo, hi, index)
2044 // parse an optional separator followed by a kleene-style
2045 // repetition token (+ or *).
2046 pub fn parse_sep_and_zerok(&mut self) -> (Option<token::Token>, bool) {
2047 fn parse_zerok(parser: &mut Parser) -> Option<bool> {
2048 match parser.token {
2049 token::BINOP(token::STAR) | token::BINOP(token::PLUS) => {
2050 let zerok = parser.token == token::BINOP(token::STAR);
2058 match parse_zerok(self) {
2059 Some(zerok) => return (None, zerok),
2063 let separator = self.bump_and_get();
2064 match parse_zerok(self) {
2065 Some(zerok) => (Some(separator), zerok),
2066 None => self.fatal("expected `*` or `+`")
2070 // parse a single token tree from the input.
2071 pub fn parse_token_tree(&mut self) -> TokenTree {
2072 // FIXME #6994: currently, this is too eager. It
2073 // parses token trees but also identifies TTSeq's
2074 // and TTNonterminal's; it's too early to know yet
2075 // whether something will be a nonterminal or a seq
2077 maybe_whole!(deref self, NtTT);
2079 // this is the fall-through for the 'match' below.
2080 // invariants: the current token is not a left-delimiter,
2081 // not an EOF, and not the desired right-delimiter (if
2082 // it were, parse_seq_to_before_end would have prevented
2083 // reaching this point.
2084 fn parse_non_delim_tt_tok(p: &mut Parser) -> TokenTree {
2085 maybe_whole!(deref p, NtTT);
2087 token::RPAREN | token::RBRACE | token::RBRACKET => {
2088 // This is a conservative error: only report the last unclosed delimiter. The
2089 // previous unclosed delimiters could actually be closed! The parser just hasn't
2090 // gotten to them yet.
2091 match p.open_braces.last() {
2093 Some(&sp) => p.span_note(sp, "unclosed delimiter"),
2095 let token_str = p.this_token_to_str();
2096 p.fatal(format!("incorrect close delimiter: `{}`",
2099 /* we ought to allow different depths of unquotation */
2100 token::DOLLAR if p.quote_depth > 0u => {
2104 if p.token == token::LPAREN {
2105 let seq = p.parse_seq(
2109 |p| p.parse_token_tree()
2111 let (s, z) = p.parse_sep_and_zerok();
2112 let seq = match seq {
2113 Spanned { node, .. } => node,
2115 TTSeq(mk_sp(sp.lo, p.span.hi), @seq, s, z)
2117 TTNonterminal(sp, p.parse_ident())
2126 // turn the next token into a TTTok:
2127 fn parse_any_tt_tok(p: &mut Parser) -> TokenTree {
2128 TTTok(p.span, p.bump_and_get())
2133 let open_braces = self.open_braces.clone();
2134 for sp in open_braces.iter() {
2135 self.span_note(*sp, "Did you mean to close this delimiter?");
2137 // There shouldn't really be a span, but it's easier for the test runner
2138 // if we give it one
2139 self.fatal("This file contains an un-closed delimiter ");
2141 token::LPAREN | token::LBRACE | token::LBRACKET => {
2142 let close_delim = token::flip_delimiter(&self.token);
2144 // Parse the open delimiter.
2145 self.open_braces.push(self.span);
2146 let mut result = ~[parse_any_tt_tok(self)];
2149 self.parse_seq_to_before_end(&close_delim,
2151 |p| p.parse_token_tree());
2152 result.push_all_move(trees);
2154 // Parse the close delimiter.
2155 result.push(parse_any_tt_tok(self));
2156 self.open_braces.pop().unwrap();
2160 _ => parse_non_delim_tt_tok(self)
2164 // parse a stream of tokens into a list of TokenTree's,
2166 pub fn parse_all_token_trees(&mut self) -> ~[TokenTree] {
2168 while self.token != token::EOF {
2169 tts.push(self.parse_token_tree());
2174 pub fn parse_matchers(&mut self) -> ~[Matcher] {
2175 // unification of Matcher's and TokenTree's would vastly improve
2176 // the interpolation of Matcher's
2177 maybe_whole!(self, NtMatchers);
2178 let name_idx = @Cell::new(0u);
2180 token::LBRACE | token::LPAREN | token::LBRACKET => {
2181 let other_delimiter = token::flip_delimiter(&self.token);
2183 self.parse_matcher_subseq_upto(name_idx, &other_delimiter)
2185 _ => self.fatal("expected open delimiter")
2189 // This goofy function is necessary to correctly match parens in Matcher's.
2190 // Otherwise, `$( ( )` would be a valid Matcher, and `$( () )` would be
2191 // invalid. It's similar to common::parse_seq.
2192 pub fn parse_matcher_subseq_upto(&mut self,
2193 name_idx: @Cell<uint>,
2196 let mut ret_val = ~[];
2197 let mut lparens = 0u;
2199 while self.token != *ket || lparens > 0u {
2200 if self.token == token::LPAREN { lparens += 1u; }
2201 if self.token == token::RPAREN { lparens -= 1u; }
2202 ret_val.push(self.parse_matcher(name_idx));
2210 pub fn parse_matcher(&mut self, name_idx: @Cell<uint>) -> Matcher {
2211 let lo = self.span.lo;
2213 let m = if self.token == token::DOLLAR {
2215 if self.token == token::LPAREN {
2216 let name_idx_lo = name_idx.get();
2218 let ms = self.parse_matcher_subseq_upto(name_idx,
2221 self.fatal("repetition body must be nonempty");
2223 let (sep, zerok) = self.parse_sep_and_zerok();
2224 MatchSeq(ms, sep, zerok, name_idx_lo, name_idx.get())
2226 let bound_to = self.parse_ident();
2227 self.expect(&token::COLON);
2228 let nt_name = self.parse_ident();
2229 let m = MatchNonterminal(bound_to, nt_name, name_idx.get());
2230 name_idx.set(name_idx.get() + 1u);
2234 MatchTok(self.bump_and_get())
2237 return spanned(lo, self.span.hi, m);
2240 // parse a prefix-operator expr
2241 pub fn parse_prefix_expr(&mut self) -> @Expr {
2242 let lo = self.span.lo;
2249 let e = self.parse_prefix_expr();
2251 ex = self.mk_unary(UnNot, e);
2253 token::BINOP(b) => {
2257 let e = self.parse_prefix_expr();
2259 ex = self.mk_unary(UnNeg, e);
2263 let e = self.parse_prefix_expr();
2265 ex = self.mk_unary(UnDeref, e);
2269 let _lt = self.parse_opt_lifetime();
2270 let m = self.parse_mutability();
2271 let e = self.parse_prefix_expr();
2273 // HACK: turn &[...] into a &-vec
2275 ExprVec(..) if m == MutImmutable => {
2276 ExprVstore(e, ExprVstoreSlice)
2278 ExprLit(lit) if lit_is_str(lit) && m == MutImmutable => {
2279 ExprVstore(e, ExprVstoreSlice)
2281 ExprVec(..) if m == MutMutable => {
2282 ExprVstore(e, ExprVstoreMutSlice)
2284 _ => ExprAddrOf(m, e)
2287 _ => return self.parse_dot_or_call_expr()
2292 let e = self.parse_prefix_expr();
2294 // HACK: turn @[...] into a @-vec
2297 ExprRepeat(..) => ExprVstore(e, ExprVstoreBox),
2298 ExprLit(lit) if lit_is_str(lit) => ExprVstore(e, ExprVstoreBox),
2299 _ => self.mk_unary(UnBox, e)
2305 let e = self.parse_prefix_expr();
2307 // HACK: turn ~[...] into a ~-vec
2309 ExprVec(..) | ExprRepeat(..) => ExprVstore(e, ExprVstoreUniq),
2310 ExprLit(lit) if lit_is_str(lit) => {
2311 ExprVstore(e, ExprVstoreUniq)
2313 _ => self.mk_unary(UnUniq, e)
2316 token::IDENT(_, _) if self.is_keyword(keywords::Box) => {
2319 // Check for a place: `box(PLACE) EXPR`.
2320 if self.eat(&token::LPAREN) {
2321 // Support `box() EXPR` as the default.
2322 if !self.eat(&token::RPAREN) {
2323 let place = self.parse_expr();
2324 self.expect(&token::RPAREN);
2325 let subexpression = self.parse_prefix_expr();
2326 hi = subexpression.span.hi;
2327 ex = ExprBox(place, subexpression);
2328 return self.mk_expr(lo, hi, ex);
2332 // Otherwise, we use the unique pointer default.
2333 let subexpression = self.parse_prefix_expr();
2334 hi = subexpression.span.hi;
2335 // HACK: turn `box [...]` into a boxed-vec
2336 ex = match subexpression.node {
2337 ExprVec(..) | ExprRepeat(..) => {
2338 ExprVstore(subexpression, ExprVstoreUniq)
2340 ExprLit(lit) if lit_is_str(lit) => {
2341 ExprVstore(subexpression, ExprVstoreUniq)
2343 _ => self.mk_unary(UnUniq, subexpression)
2346 _ => return self.parse_dot_or_call_expr()
2348 return self.mk_expr(lo, hi, ex);
2351 // parse an expression of binops
2352 pub fn parse_binops(&mut self) -> @Expr {
2353 let prefix_expr = self.parse_prefix_expr();
2354 self.parse_more_binops(prefix_expr, 0)
2357 // parse an expression of binops of at least min_prec precedence
2358 pub fn parse_more_binops(&mut self, lhs: @Expr, min_prec: uint) -> @Expr {
2359 if self.expr_is_complete(lhs) { return lhs; }
2361 // Prevent dynamic borrow errors later on by limiting the
2362 // scope of the borrows.
2364 let token: &token::Token = &self.token;
2365 let restriction: &restriction = &self.restriction;
2366 match (token, restriction) {
2367 (&token::BINOP(token::OR), &RESTRICT_NO_BAR_OP) => return lhs,
2368 (&token::BINOP(token::OR),
2369 &RESTRICT_NO_BAR_OR_DOUBLEBAR_OP) => return lhs,
2370 (&token::OROR, &RESTRICT_NO_BAR_OR_DOUBLEBAR_OP) => return lhs,
2375 let cur_opt = token_to_binop(&self.token);
2378 let cur_prec = operator_prec(cur_op);
2379 if cur_prec > min_prec {
2381 let expr = self.parse_prefix_expr();
2382 let rhs = self.parse_more_binops(expr, cur_prec);
2383 let binary = self.mk_binary(cur_op, lhs, rhs);
2384 let bin = self.mk_expr(lhs.span.lo, rhs.span.hi, binary);
2385 self.parse_more_binops(bin, min_prec)
2391 if as_prec > min_prec && self.eat_keyword(keywords::As) {
2392 let rhs = self.parse_ty(true);
2393 let _as = self.mk_expr(lhs.span.lo,
2395 ExprCast(lhs, rhs));
2396 self.parse_more_binops(_as, min_prec)
2404 // parse an assignment expression....
2405 // actually, this seems to be the main entry point for
2406 // parsing an arbitrary expression.
2407 pub fn parse_assign_expr(&mut self) -> @Expr {
2408 let lo = self.span.lo;
2409 let lhs = self.parse_binops();
2413 let rhs = self.parse_expr();
2414 self.mk_expr(lo, rhs.span.hi, ExprAssign(lhs, rhs))
2416 token::BINOPEQ(op) => {
2418 let rhs = self.parse_expr();
2419 let aop = match op {
2420 token::PLUS => BiAdd,
2421 token::MINUS => BiSub,
2422 token::STAR => BiMul,
2423 token::SLASH => BiDiv,
2424 token::PERCENT => BiRem,
2425 token::CARET => BiBitXor,
2426 token::AND => BiBitAnd,
2427 token::OR => BiBitOr,
2428 token::SHL => BiShl,
2431 let assign_op = self.mk_assign_op(aop, lhs, rhs);
2432 self.mk_expr(lo, rhs.span.hi, assign_op)
2435 self.obsolete(self.span, ObsoleteSwap);
2437 // Ignore what we get, this is an error anyway
2439 self.mk_expr(lo, self.span.hi, ExprBreak(None))
2447 // parse an 'if' expression ('if' token already eaten)
2448 pub fn parse_if_expr(&mut self) -> @Expr {
2449 let lo = self.last_span.lo;
2450 let cond = self.parse_expr();
2451 let thn = self.parse_block();
2452 let mut els: Option<@Expr> = None;
2453 let mut hi = thn.span.hi;
2454 if self.eat_keyword(keywords::Else) {
2455 let elexpr = self.parse_else_expr();
2457 hi = elexpr.span.hi;
2459 self.mk_expr(lo, hi, ExprIf(cond, thn, els))
2462 // `|args| { ... }` or `{ ...}` like in `do` expressions
2463 pub fn parse_lambda_block_expr(&mut self) -> @Expr {
2464 self.parse_lambda_expr_(
2467 token::BINOP(token::OR) | token::OROR => {
2468 p.parse_fn_block_decl()
2471 // No argument list - `do foo {`
2475 id: ast::DUMMY_NODE_ID,
2486 let blk = p.parse_block();
2487 p.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk))
2492 pub fn parse_lambda_expr(&mut self) -> @Expr {
2493 self.parse_lambda_expr_(|p| p.parse_fn_block_decl(),
2497 // parse something of the form |args| expr
2498 // this is used both in parsing a lambda expr
2499 // and in parsing a block expr as e.g. in for...
2500 pub fn parse_lambda_expr_(&mut self,
2501 parse_decl: |&mut Parser| -> P<FnDecl>,
2502 parse_body: |&mut Parser| -> @Expr)
2504 let lo = self.last_span.lo;
2505 let decl = parse_decl(self);
2506 let body = parse_body(self);
2507 let fakeblock = P(ast::Block {
2511 id: ast::DUMMY_NODE_ID,
2512 rules: DefaultBlock,
2516 return self.mk_expr(lo, body.span.hi, ExprFnBlock(decl, fakeblock));
2519 pub fn parse_else_expr(&mut self) -> @Expr {
2520 if self.eat_keyword(keywords::If) {
2521 return self.parse_if_expr();
2523 let blk = self.parse_block();
2524 return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk));
2528 // parse a 'for' .. 'in' expression ('for' token already eaten)
2529 pub fn parse_for_expr(&mut self, opt_ident: Option<ast::Ident>) -> @Expr {
2530 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
2532 let lo = self.last_span.lo;
2533 let pat = self.parse_pat();
2534 self.expect_keyword(keywords::In);
2535 let expr = self.parse_expr();
2536 let loop_block = self.parse_block();
2537 let hi = self.span.hi;
2539 self.mk_expr(lo, hi, ExprForLoop(pat, expr, loop_block, opt_ident))
2542 pub fn parse_while_expr(&mut self) -> @Expr {
2543 let lo = self.last_span.lo;
2544 let cond = self.parse_expr();
2545 let body = self.parse_block();
2546 let hi = body.span.hi;
2547 return self.mk_expr(lo, hi, ExprWhile(cond, body));
2550 pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::Ident>) -> @Expr {
2551 // loop headers look like 'loop {' or 'loop unsafe {'
2552 let is_loop_header =
2553 self.token == token::LBRACE
2554 || (is_ident(&self.token)
2555 && self.look_ahead(1, |t| *t == token::LBRACE));
2558 // This is a loop body
2559 let lo = self.last_span.lo;
2560 let body = self.parse_block();
2561 let hi = body.span.hi;
2562 return self.mk_expr(lo, hi, ExprLoop(body, opt_ident));
2564 // This is an obsolete 'continue' expression
2565 if opt_ident.is_some() {
2566 self.span_err(self.last_span,
2567 "a label may not be used with a `loop` expression");
2570 self.obsolete(self.last_span, ObsoleteLoopAsContinue);
2571 let lo = self.span.lo;
2572 let ex = if Parser::token_is_lifetime(&self.token) {
2573 let lifetime = self.get_lifetime();
2575 ExprAgain(Some(lifetime.name))
2579 let hi = self.span.hi;
2580 return self.mk_expr(lo, hi, ex);
2584 // For distingishing between struct literals and blocks
2585 fn looking_at_struct_literal(&mut self) -> bool {
2586 self.token == token::LBRACE &&
2587 ((self.look_ahead(1, |t| token::is_plain_ident(t)) &&
2588 self.look_ahead(2, |t| *t == token::COLON))
2589 || self.look_ahead(1, |t| *t == token::DOTDOT))
2592 fn parse_match_expr(&mut self) -> @Expr {
2593 let lo = self.last_span.lo;
2594 let discriminant = self.parse_expr();
2595 self.commit_expr_expecting(discriminant, token::LBRACE);
2596 let mut arms: ~[Arm] = ~[];
2597 while self.token != token::RBRACE {
2598 let pats = self.parse_pats();
2599 let mut guard = None;
2600 if self.eat_keyword(keywords::If) {
2601 guard = Some(self.parse_expr());
2603 self.expect(&token::FAT_ARROW);
2604 let expr = self.parse_expr_res(RESTRICT_STMT_EXPR);
2607 !classify::expr_is_simple_block(expr)
2608 && self.token != token::RBRACE;
2611 self.commit_expr(expr, &[token::COMMA], &[token::RBRACE]);
2613 self.eat(&token::COMMA);
2616 let blk = P(ast::Block {
2620 id: ast::DUMMY_NODE_ID,
2621 rules: DefaultBlock,
2625 arms.push(ast::Arm { pats: pats, guard: guard, body: blk });
2627 let hi = self.span.hi;
2629 return self.mk_expr(lo, hi, ExprMatch(discriminant, arms));
2632 // parse an expression
2633 pub fn parse_expr(&mut self) -> @Expr {
2634 return self.parse_expr_res(UNRESTRICTED);
2637 // parse an expression, subject to the given restriction
2638 fn parse_expr_res(&mut self, r: restriction) -> @Expr {
2639 let old = self.restriction;
2640 self.restriction = r;
2641 let e = self.parse_assign_expr();
2642 self.restriction = old;
2646 // parse the RHS of a local variable declaration (e.g. '= 14;')
2647 fn parse_initializer(&mut self) -> Option<@Expr> {
2648 if self.token == token::EQ {
2650 Some(self.parse_expr())
2656 // parse patterns, separated by '|' s
2657 fn parse_pats(&mut self) -> ~[@Pat] {
2660 pats.push(self.parse_pat());
2661 if self.token == token::BINOP(token::OR) { self.bump(); }
2662 else { return pats; }
2666 fn parse_pat_vec_elements(
2668 ) -> (~[@Pat], Option<@Pat>, ~[@Pat]) {
2669 let mut before = ~[];
2670 let mut slice = None;
2671 let mut after = ~[];
2672 let mut first = true;
2673 let mut before_slice = true;
2675 while self.token != token::RBRACKET {
2676 if first { first = false; }
2677 else { self.expect(&token::COMMA); }
2679 let mut is_slice = false;
2681 if self.token == token::DOTDOT {
2684 before_slice = false;
2689 if self.token == token::COMMA || self.token == token::RBRACKET {
2690 slice = Some(@ast::Pat {
2691 id: ast::DUMMY_NODE_ID,
2696 let subpat = self.parse_pat();
2698 ast::Pat { id, node: PatWild, span } => {
2699 self.obsolete(self.span, ObsoleteVecDotDotWildcard);
2700 slice = Some(@ast::Pat {
2706 ast::Pat { node: PatIdent(_, _, _), .. } => {
2707 slice = Some(subpat);
2709 ast::Pat { span, .. } => self.span_fatal(
2710 span, "expected an identifier or nothing"
2715 let subpat = self.parse_pat();
2717 before.push(subpat);
2724 (before, slice, after)
2727 // parse the fields of a struct-like pattern
2728 fn parse_pat_fields(&mut self) -> (~[ast::FieldPat], bool) {
2729 let mut fields = ~[];
2730 let mut etc = false;
2731 let mut first = true;
2732 while self.token != token::RBRACE {
2736 self.expect(&token::COMMA);
2737 // accept trailing commas
2738 if self.token == token::RBRACE { break }
2741 etc = self.token == token::UNDERSCORE || self.token == token::DOTDOT;
2742 if self.token == token::UNDERSCORE {
2743 self.obsolete(self.span, ObsoleteStructWildcard);
2747 if self.token != token::RBRACE {
2748 let token_str = self.this_token_to_str();
2749 self.fatal(format!("expected `\\}`, found `{}`",
2756 let lo1 = self.last_span.lo;
2757 let bind_type = if self.eat_keyword(keywords::Mut) {
2758 BindByValue(MutMutable)
2759 } else if self.eat_keyword(keywords::Ref) {
2760 BindByRef(self.parse_mutability())
2762 BindByValue(MutImmutable)
2765 let fieldname = self.parse_ident();
2766 let hi1 = self.last_span.lo;
2767 let fieldpath = ast_util::ident_to_path(mk_sp(lo1, hi1),
2770 if self.token == token::COLON {
2772 BindByRef(..) | BindByValue(MutMutable) => {
2773 let token_str = self.this_token_to_str();
2774 self.fatal(format!("unexpected `{}`", token_str))
2780 subpat = self.parse_pat();
2782 subpat = @ast::Pat {
2783 id: ast::DUMMY_NODE_ID,
2784 node: PatIdent(bind_type, fieldpath, None),
2785 span: self.last_span
2788 fields.push(ast::FieldPat { ident: fieldname, pat: subpat });
2790 return (fields, etc);
2794 pub fn parse_pat(&mut self) -> @Pat {
2795 maybe_whole!(self, NtPat);
2797 let lo = self.span.lo;
2802 token::UNDERSCORE => {
2805 hi = self.last_span.hi;
2807 id: ast::DUMMY_NODE_ID,
2815 let sub = self.parse_pat();
2817 // HACK: parse @"..." as a literal of a vstore @str
2818 pat = match sub.node {
2821 ExprLit(lit) if lit_is_str(lit) => {
2823 id: ast::DUMMY_NODE_ID,
2824 node: ExprVstore(e, ExprVstoreBox),
2825 span: mk_sp(lo, hi),
2830 self.obsolete(self.span, ObsoleteManagedPattern);
2836 self.obsolete(self.span, ObsoleteManagedPattern);
2840 hi = self.last_span.hi;
2842 id: ast::DUMMY_NODE_ID,
2850 let sub = self.parse_pat();
2852 // HACK: parse ~"..." as a literal of a vstore ~str
2853 pat = match sub.node {
2856 ExprLit(lit) if lit_is_str(lit) => {
2858 id: ast::DUMMY_NODE_ID,
2859 node: ExprVstore(e, ExprVstoreUniq),
2860 span: mk_sp(lo, hi),
2869 hi = self.last_span.hi;
2871 id: ast::DUMMY_NODE_ID,
2876 token::BINOP(token::AND) => {
2878 let lo = self.span.lo;
2880 let sub = self.parse_pat();
2882 // HACK: parse &"..." as a literal of a borrowed str
2883 pat = match sub.node {
2886 ExprLit(lit) if lit_is_str(lit) => {
2888 id: ast::DUMMY_NODE_ID,
2889 node: ExprVstore(e, ExprVstoreSlice),
2894 _ => PatRegion(sub),
2897 _ => PatRegion(sub),
2899 hi = self.last_span.hi;
2901 id: ast::DUMMY_NODE_ID,
2907 // parse (pat,pat,pat,...) as tuple
2909 if self.token == token::RPAREN {
2912 let lit = @codemap::Spanned {
2914 span: mk_sp(lo, hi)};
2915 let expr = self.mk_expr(lo, hi, ExprLit(lit));
2918 let mut fields = ~[self.parse_pat()];
2919 if self.look_ahead(1, |t| *t != token::RPAREN) {
2920 while self.token == token::COMMA {
2922 if self.token == token::RPAREN { break; }
2923 fields.push(self.parse_pat());
2926 if fields.len() == 1 { self.expect(&token::COMMA); }
2927 self.expect(&token::RPAREN);
2928 pat = PatTup(fields);
2930 hi = self.last_span.hi;
2932 id: ast::DUMMY_NODE_ID,
2937 token::LBRACKET => {
2938 // parse [pat,pat,...] as vector pattern
2940 let (before, slice, after) =
2941 self.parse_pat_vec_elements();
2943 self.expect(&token::RBRACKET);
2944 pat = ast::PatVec(before, slice, after);
2945 hi = self.last_span.hi;
2947 id: ast::DUMMY_NODE_ID,
2955 if !is_ident_or_path(&self.token)
2956 || self.is_keyword(keywords::True)
2957 || self.is_keyword(keywords::False) {
2958 // Parse an expression pattern or exp .. exp.
2960 // These expressions are limited to literals (possibly
2961 // preceded by unary-minus) or identifiers.
2962 let val = self.parse_literal_maybe_minus();
2963 if self.eat(&token::DOTDOT) {
2964 let end = if is_ident_or_path(&self.token) {
2965 let path = self.parse_path(LifetimeAndTypesWithColons)
2967 let hi = self.span.hi;
2968 self.mk_expr(lo, hi, ExprPath(path))
2970 self.parse_literal_maybe_minus()
2972 pat = PatRange(val, end);
2976 } else if self.eat_keyword(keywords::Mut) {
2977 pat = self.parse_pat_ident(BindByValue(MutMutable));
2978 } else if self.eat_keyword(keywords::Ref) {
2980 let mutbl = self.parse_mutability();
2981 pat = self.parse_pat_ident(BindByRef(mutbl));
2983 let can_be_enum_or_struct = self.look_ahead(1, |t| {
2985 token::LPAREN | token::LBRACKET | token::LT |
2986 token::LBRACE | token::MOD_SEP => true,
2991 if self.look_ahead(1, |t| *t == token::DOTDOT) {
2992 let start = self.parse_expr_res(RESTRICT_NO_BAR_OP);
2993 self.eat(&token::DOTDOT);
2994 let end = self.parse_expr_res(RESTRICT_NO_BAR_OP);
2995 pat = PatRange(start, end);
2996 } else if is_plain_ident(&self.token) && !can_be_enum_or_struct {
2997 let name = self.parse_path(NoTypesAllowed).path;
2999 if self.eat(&token::AT) {
3001 sub = Some(self.parse_pat());
3006 pat = PatIdent(BindByValue(MutImmutable), name, sub);
3008 // parse an enum pat
3009 let enum_path = self.parse_path(LifetimeAndTypesWithColons)
3015 self.parse_pat_fields();
3017 pat = PatStruct(enum_path, fields, etc);
3020 let mut args: ~[@Pat] = ~[];
3023 let is_star = self.look_ahead(1, |t| {
3025 token::BINOP(token::STAR) => true,
3029 let is_dotdot = self.look_ahead(1, |t| {
3031 token::DOTDOT => true,
3035 if is_star | is_dotdot {
3036 // This is a "top constructor only" pat
3039 self.obsolete(self.span, ObsoleteEnumWildcard);
3042 self.expect(&token::RPAREN);
3043 pat = PatEnum(enum_path, None);
3045 args = self.parse_unspanned_seq(
3048 seq_sep_trailing_disallowed(token::COMMA),
3051 pat = PatEnum(enum_path, Some(args));
3055 if enum_path.segments.len() == 1 {
3056 // it could still be either an enum
3057 // or an identifier pattern, resolve
3058 // will sort it out:
3059 pat = PatIdent(BindByValue(MutImmutable),
3063 pat = PatEnum(enum_path, Some(args));
3071 hi = self.last_span.hi;
3073 id: ast::DUMMY_NODE_ID,
3075 span: mk_sp(lo, hi),
3079 // parse ident or ident @ pat
3080 // used by the copy foo and ref foo patterns to give a good
3081 // error message when parsing mistakes like ref foo(a,b)
3082 fn parse_pat_ident(&mut self,
3083 binding_mode: ast::BindingMode)
3085 if !is_plain_ident(&self.token) {
3086 self.span_fatal(self.last_span,
3087 "expected identifier, found path");
3089 // why a path here, and not just an identifier?
3090 let name = self.parse_path(NoTypesAllowed).path;
3091 let sub = if self.eat(&token::AT) {
3092 Some(self.parse_pat())
3097 // just to be friendly, if they write something like
3099 // we end up here with ( as the current token. This shortly
3100 // leads to a parse error. Note that if there is no explicit
3101 // binding mode then we do not end up here, because the lookahead
3102 // will direct us over to parse_enum_variant()
3103 if self.token == token::LPAREN {
3106 "expected identifier, found enum pattern");
3109 PatIdent(binding_mode, name, sub)
3112 // parse a local variable declaration
3113 fn parse_local(&mut self) -> @Local {
3114 let lo = self.span.lo;
3115 let pat = self.parse_pat();
3118 id: ast::DUMMY_NODE_ID,
3120 span: mk_sp(lo, lo),
3122 if self.eat(&token::COLON) { ty = self.parse_ty(false); }
3123 let init = self.parse_initializer();
3128 id: ast::DUMMY_NODE_ID,
3129 span: mk_sp(lo, self.last_span.hi),
3133 // parse a "let" stmt
3134 fn parse_let(&mut self) -> @Decl {
3135 let lo = self.span.lo;
3136 let local = self.parse_local();
3137 while self.eat(&token::COMMA) {
3138 let _ = self.parse_local();
3139 self.obsolete(self.span, ObsoleteMultipleLocalDecl);
3141 return @spanned(lo, self.last_span.hi, DeclLocal(local));
3144 // parse a structure field
3145 fn parse_name_and_ty(&mut self, pr: Visibility,
3146 attrs: ~[Attribute]) -> StructField {
3147 let lo = self.span.lo;
3148 if !is_plain_ident(&self.token) {
3149 self.fatal("expected ident");
3151 let name = self.parse_ident();
3152 self.expect(&token::COLON);
3153 let ty = self.parse_ty(false);
3154 spanned(lo, self.last_span.hi, ast::StructField_ {
3155 kind: NamedField(name, pr),
3156 id: ast::DUMMY_NODE_ID,
3162 // parse a statement. may include decl.
3163 // precondition: any attributes are parsed already
3164 pub fn parse_stmt(&mut self, item_attrs: ~[Attribute]) -> @Stmt {
3165 maybe_whole!(self, NtStmt);
3167 fn check_expected_item(p: &mut Parser, found_attrs: bool) {
3168 // If we have attributes then we should have an item
3170 p.span_err(p.last_span, "expected item after attributes");
3174 let lo = self.span.lo;
3175 if self.is_keyword(keywords::Let) {
3176 check_expected_item(self, !item_attrs.is_empty());
3177 self.expect_keyword(keywords::Let);
3178 let decl = self.parse_let();
3179 return @spanned(lo, decl.span.hi, StmtDecl(decl, ast::DUMMY_NODE_ID));
3180 } else if is_ident(&self.token)
3181 && !token::is_any_keyword(&self.token)
3182 && self.look_ahead(1, |t| *t == token::NOT) {
3183 // parse a macro invocation. Looks like there's serious
3184 // overlap here; if this clause doesn't catch it (and it
3185 // won't, for brace-delimited macros) it will fall through
3186 // to the macro clause of parse_item_or_view_item. This
3187 // could use some cleanup, it appears to me.
3189 // whoops! I now have a guess: I'm guessing the "parens-only"
3190 // rule here is deliberate, to allow macro users to use parens
3191 // for things that should be parsed as stmt_mac, and braces
3192 // for things that should expand into items. Tricky, and
3193 // somewhat awkward... and probably undocumented. Of course,
3194 // I could just be wrong.
3196 check_expected_item(self, !item_attrs.is_empty());
3198 // Potential trouble: if we allow macros with paths instead of
3199 // idents, we'd need to look ahead past the whole path here...
3200 let pth = self.parse_path(NoTypesAllowed).path;
3203 let id = if self.token == token::LPAREN {
3204 token::special_idents::invalid // no special identifier
3209 let tts = self.parse_unspanned_seq(
3213 |p| p.parse_token_tree()
3215 let hi = self.span.hi;
3217 if id == token::special_idents::invalid {
3218 return @spanned(lo, hi, StmtMac(
3219 spanned(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT)), false));
3221 // if it has a special ident, it's definitely an item
3222 return @spanned(lo, hi, StmtDecl(
3223 @spanned(lo, hi, DeclItem(
3225 lo, hi, id /*id is good here*/,
3226 ItemMac(spanned(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT))),
3227 Inherited, ~[/*no attrs*/]))),
3228 ast::DUMMY_NODE_ID));
3232 let found_attrs = !item_attrs.is_empty();
3233 match self.parse_item_or_view_item(item_attrs, false) {
3236 let decl = @spanned(lo, hi, DeclItem(i));
3237 return @spanned(lo, hi, StmtDecl(decl, ast::DUMMY_NODE_ID));
3239 IoviViewItem(vi) => {
3240 self.span_fatal(vi.span,
3241 "view items must be declared at the top of the block");
3243 IoviForeignItem(_) => {
3244 self.fatal("foreign items are not allowed here");
3246 IoviNone(_) => { /* fallthrough */ }
3249 check_expected_item(self, found_attrs);
3251 // Remainder are line-expr stmts.
3252 let e = self.parse_expr_res(RESTRICT_STMT_EXPR);
3253 return @spanned(lo, e.span.hi, StmtExpr(e, ast::DUMMY_NODE_ID));
3257 // is this expression a successfully-parsed statement?
3258 fn expr_is_complete(&mut self, e: @Expr) -> bool {
3259 return self.restriction == RESTRICT_STMT_EXPR &&
3260 !classify::expr_requires_semi_to_be_stmt(e);
3263 // parse a block. No inner attrs are allowed.
3264 pub fn parse_block(&mut self) -> P<Block> {
3265 maybe_whole!(no_clone self, NtBlock);
3267 let lo = self.span.lo;
3268 if self.eat_keyword(keywords::Unsafe) {
3269 self.obsolete(self.span, ObsoleteUnsafeBlock);
3271 self.expect(&token::LBRACE);
3273 return self.parse_block_tail_(lo, DefaultBlock, ~[]);
3276 // parse a block. Inner attrs are allowed.
3277 fn parse_inner_attrs_and_block(&mut self)
3278 -> (~[Attribute], P<Block>) {
3280 maybe_whole!(pair_empty self, NtBlock);
3282 let lo = self.span.lo;
3283 if self.eat_keyword(keywords::Unsafe) {
3284 self.obsolete(self.span, ObsoleteUnsafeBlock);
3286 self.expect(&token::LBRACE);
3287 let (inner, next) = self.parse_inner_attrs_and_next();
3289 (inner, self.parse_block_tail_(lo, DefaultBlock, next))
3292 // Precondition: already parsed the '{' or '#{'
3293 // I guess that also means "already parsed the 'impure'" if
3294 // necessary, and this should take a qualifier.
3295 // some blocks start with "#{"...
3296 fn parse_block_tail(&mut self, lo: BytePos, s: BlockCheckMode) -> P<Block> {
3297 self.parse_block_tail_(lo, s, ~[])
3300 // parse the rest of a block expression or function body
3301 fn parse_block_tail_(&mut self, lo: BytePos, s: BlockCheckMode,
3302 first_item_attrs: ~[Attribute]) -> P<Block> {
3303 let mut stmts = ~[];
3304 let mut expr = None;
3306 // wouldn't it be more uniform to parse view items only, here?
3307 let ParsedItemsAndViewItems {
3308 attrs_remaining: attrs_remaining,
3309 view_items: view_items,
3312 } = self.parse_items_and_view_items(first_item_attrs,
3315 for item in items.iter() {
3316 let decl = @spanned(item.span.lo, item.span.hi, DeclItem(*item));
3317 stmts.push(@spanned(item.span.lo, item.span.hi,
3318 StmtDecl(decl, ast::DUMMY_NODE_ID)));
3321 let mut attributes_box = attrs_remaining;
3323 while self.token != token::RBRACE {
3324 // parsing items even when they're not allowed lets us give
3325 // better error messages and recover more gracefully.
3326 attributes_box.push_all(self.parse_outer_attributes());
3329 if !attributes_box.is_empty() {
3330 self.span_err(self.last_span, "expected item after attributes");
3331 attributes_box = ~[];
3333 self.bump(); // empty
3336 // fall through and out.
3339 let stmt = self.parse_stmt(attributes_box);
3340 attributes_box = ~[];
3342 StmtExpr(e, stmt_id) => {
3343 // expression without semicolon
3344 if classify::stmt_ends_with_semi(stmt) {
3345 // Just check for errors and recover; do not eat semicolon yet.
3346 self.commit_stmt(stmt, &[], &[token::SEMI, token::RBRACE]);
3352 stmts.push(@codemap::Spanned {
3353 node: StmtSemi(e, stmt_id),
3365 StmtMac(ref m, _) => {
3366 // statement macro; might be an expr
3373 // if a block ends in `m!(arg)` without
3374 // a `;`, it must be an expr
3377 self.mk_mac_expr(stmt.span.lo,
3389 stmts.push(@codemap::Spanned {
3390 node: StmtMac((*m).clone(), true),
3395 _ => { // all other kinds of statements:
3398 if classify::stmt_ends_with_semi(stmt) {
3399 self.commit_stmt_expecting(stmt, token::SEMI);
3407 if !attributes_box.is_empty() {
3408 self.span_err(self.last_span, "expected item after attributes");
3411 let hi = self.span.hi;
3414 view_items: view_items,
3417 id: ast::DUMMY_NODE_ID,
3419 span: mk_sp(lo, hi),
3423 // matches optbounds = ( ( : ( boundseq )? )? )
3424 // where boundseq = ( bound + boundseq ) | bound
3425 // and bound = 'static | ty
3426 // Returns "None" if there's no colon (e.g. "T");
3427 // Returns "Some(Empty)" if there's a colon but nothing after (e.g. "T:")
3428 // Returns "Some(stuff)" otherwise (e.g. "T:stuff").
3429 // NB: The None/Some distinction is important for issue #7264.
3430 fn parse_optional_ty_param_bounds(&mut self) -> Option<OptVec<TyParamBound>> {
3431 if !self.eat(&token::COLON) {
3435 let mut result = opt_vec::Empty;
3438 token::LIFETIME(lifetime) => {
3439 let lifetime_interned_string =
3440 token::get_ident(lifetime.name);
3441 if lifetime_interned_string.equiv(&("static")) {
3442 result.push(RegionTyParamBound);
3444 self.span_err(self.span,
3445 "`'static` is the only permissible region bound here");
3449 token::MOD_SEP | token::IDENT(..) => {
3450 let tref = self.parse_trait_ref();
3451 result.push(TraitTyParamBound(tref));
3456 if !self.eat(&token::BINOP(token::PLUS)) {
3461 return Some(result);
3464 // matches typaram = IDENT optbounds ( EQ ty )?
3465 fn parse_ty_param(&mut self) -> TyParam {
3466 let ident = self.parse_ident();
3467 let opt_bounds = self.parse_optional_ty_param_bounds();
3468 // For typarams we don't care about the difference b/w "<T>" and "<T:>".
3469 let bounds = opt_bounds.unwrap_or_default();
3471 let default = if self.token == token::EQ {
3473 Some(self.parse_ty(false))
3479 id: ast::DUMMY_NODE_ID,
3485 // parse a set of optional generic type parameter declarations
3486 // matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
3487 // | ( < lifetimes , typaramseq ( , )? > )
3488 // where typaramseq = ( typaram ) | ( typaram , typaramseq )
3489 pub fn parse_generics(&mut self) -> ast::Generics {
3490 if self.eat(&token::LT) {
3491 let lifetimes = self.parse_lifetimes();
3492 let mut seen_default = false;
3493 let ty_params = self.parse_seq_to_gt(Some(token::COMMA), |p| {
3494 let ty_param = p.parse_ty_param();
3495 if ty_param.default.is_some() {
3496 seen_default = true;
3497 } else if seen_default {
3498 p.span_err(p.last_span,
3499 "type parameters with a default must be trailing");
3503 ast::Generics { lifetimes: lifetimes, ty_params: ty_params }
3505 ast_util::empty_generics()
3509 fn parse_generic_values_after_lt(&mut self) -> (OptVec<ast::Lifetime>, ~[P<Ty>]) {
3510 let lifetimes = self.parse_lifetimes();
3511 let result = self.parse_seq_to_gt(
3513 |p| p.parse_ty(false));
3514 (lifetimes, opt_vec::take_vec(result))
3517 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
3520 let mut args: ~[Option<Arg>] =
3521 self.parse_unspanned_seq(
3524 seq_sep_trailing_allowed(token::COMMA),
3526 if p.token == token::DOTDOTDOT {
3529 if p.token != token::RPAREN {
3530 p.span_fatal(p.span,
3531 "`...` must be last in argument list for variadic function");
3534 p.span_fatal(p.span,
3535 "only foreign functions are allowed to be variadic");
3539 Some(p.parse_arg_general(named_args))
3544 let variadic = match args.pop() {
3547 // Need to put back that last arg
3554 if variadic && args.is_empty() {
3556 "variadic function must be declared with at least one named argument");
3559 let args = args.move_iter().map(|x| x.unwrap()).collect();
3564 // parse the argument list and result type of a function declaration
3565 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> P<FnDecl> {
3567 let (args, variadic) = self.parse_fn_args(true, allow_variadic);
3568 let (ret_style, ret_ty) = self.parse_ret_ty();
3578 fn is_self_ident(&mut self) -> bool {
3580 token::IDENT(id, false) => id.name == special_idents::self_.name,
3585 fn expect_self_ident(&mut self) {
3586 if !self.is_self_ident() {
3587 let token_str = self.this_token_to_str();
3588 self.fatal(format!("expected `self` but found `{}`", token_str))
3593 // parse the argument list and result type of a function
3594 // that may have a self type.
3595 fn parse_fn_decl_with_self(&mut self, parse_arg_fn: |&mut Parser| -> Arg)
3596 -> (ExplicitSelf, P<FnDecl>) {
3597 fn maybe_parse_explicit_self(explicit_self: ast::ExplicitSelf_,
3599 -> ast::ExplicitSelf_ {
3600 // We need to make sure it isn't a type
3601 if p.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) {
3603 p.expect_self_ident();
3610 fn maybe_parse_borrowed_explicit_self(this: &mut Parser)
3611 -> ast::ExplicitSelf_ {
3612 // The following things are possible to see here:
3617 // fn(&'lt mut self)
3619 // We already know that the current token is `&`.
3621 if this.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) {
3623 this.expect_self_ident();
3624 SelfRegion(None, MutImmutable)
3625 } else if this.look_ahead(1, |t| Parser::token_is_mutability(t)) &&
3627 |t| token::is_keyword(keywords::Self,
3630 let mutability = this.parse_mutability();
3631 this.expect_self_ident();
3632 SelfRegion(None, mutability)
3633 } else if this.look_ahead(1, |t| Parser::token_is_lifetime(t)) &&
3635 |t| token::is_keyword(keywords::Self,
3638 let lifetime = this.parse_lifetime();
3639 this.expect_self_ident();
3640 SelfRegion(Some(lifetime), MutImmutable)
3641 } else if this.look_ahead(1, |t| Parser::token_is_lifetime(t)) &&
3642 this.look_ahead(2, |t| {
3643 Parser::token_is_mutability(t)
3645 this.look_ahead(3, |t| token::is_keyword(keywords::Self,
3648 let lifetime = this.parse_lifetime();
3649 let mutability = this.parse_mutability();
3650 this.expect_self_ident();
3651 SelfRegion(Some(lifetime), mutability)
3657 self.expect(&token::LPAREN);
3659 // A bit of complexity and lookahead is needed here in order to be
3660 // backwards compatible.
3661 let lo = self.span.lo;
3662 let mut mutbl_self = MutImmutable;
3663 let explicit_self = match self.token {
3664 token::BINOP(token::AND) => {
3665 maybe_parse_borrowed_explicit_self(self)
3668 maybe_parse_explicit_self(SelfBox, self)
3671 maybe_parse_explicit_self(SelfUniq, self)
3673 token::IDENT(..) if self.is_self_ident() => {
3677 token::BINOP(token::STAR) => {
3678 // Possibly "*self" or "*mut self" -- not supported. Try to avoid
3679 // emitting cryptic "unexpected token" errors.
3681 let _mutability = if Parser::token_is_mutability(&self.token) {
3682 self.parse_mutability()
3683 } else { MutImmutable };
3684 if self.is_self_ident() {
3685 self.span_err(self.span, "cannot pass self by unsafe pointer");
3690 _ if Parser::token_is_mutability(&self.token) &&
3691 self.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) => {
3692 mutbl_self = self.parse_mutability();
3693 self.expect_self_ident();
3696 _ if Parser::token_is_mutability(&self.token) &&
3697 self.look_ahead(1, |t| *t == token::TILDE) &&
3698 self.look_ahead(2, |t| token::is_keyword(keywords::Self, t)) => {
3699 mutbl_self = self.parse_mutability();
3701 self.expect_self_ident();
3707 let explicit_self_sp = mk_sp(lo, self.span.hi);
3709 // If we parsed a self type, expect a comma before the argument list.
3710 let fn_inputs = if explicit_self != SelfStatic {
3714 let sep = seq_sep_trailing_disallowed(token::COMMA);
3715 let mut fn_inputs = self.parse_seq_to_before_end(
3720 fn_inputs.unshift(Arg::new_self(explicit_self_sp, mutbl_self));
3724 ~[Arg::new_self(explicit_self_sp, mutbl_self)]
3727 let token_str = self.this_token_to_str();
3728 self.fatal(format!("expected `,` or `)`, found `{}`",
3733 let sep = seq_sep_trailing_disallowed(token::COMMA);
3734 self.parse_seq_to_before_end(&token::RPAREN, sep, parse_arg_fn)
3737 self.expect(&token::RPAREN);
3739 let hi = self.span.hi;
3741 let (ret_style, ret_ty) = self.parse_ret_ty();
3743 let fn_decl = P(FnDecl {
3750 (spanned(lo, hi, explicit_self), fn_decl)
3753 // parse the |arg, arg| header on a lambda
3754 fn parse_fn_block_decl(&mut self) -> P<FnDecl> {
3755 let inputs_captures = {
3756 if self.eat(&token::OROR) {
3759 self.parse_unspanned_seq(
3760 &token::BINOP(token::OR),
3761 &token::BINOP(token::OR),
3762 seq_sep_trailing_disallowed(token::COMMA),
3763 |p| p.parse_fn_block_arg()
3767 let output = if self.eat(&token::RARROW) {
3768 self.parse_ty(false)
3771 id: ast::DUMMY_NODE_ID,
3778 inputs: inputs_captures,
3785 // Parses the `(arg, arg) -> return_type` header on a procedure.
3786 fn parse_proc_decl(&mut self) -> P<FnDecl> {
3788 self.parse_unspanned_seq(&token::LPAREN,
3790 seq_sep_trailing_allowed(token::COMMA),
3791 |p| p.parse_fn_block_arg());
3793 let output = if self.eat(&token::RARROW) {
3794 self.parse_ty(false)
3797 id: ast::DUMMY_NODE_ID,
3811 // parse the name and optional generic types of a function header.
3812 fn parse_fn_header(&mut self) -> (Ident, ast::Generics) {
3813 let id = self.parse_ident();
3814 let generics = self.parse_generics();
3818 fn mk_item(&mut self, lo: BytePos, hi: BytePos, ident: Ident,
3819 node: Item_, vis: Visibility,
3820 attrs: ~[Attribute]) -> @Item {
3824 id: ast::DUMMY_NODE_ID,
3831 // parse an item-position function declaration.
3832 fn parse_item_fn(&mut self, purity: Purity, abis: AbiSet) -> ItemInfo {
3833 let (ident, generics) = self.parse_fn_header();
3834 let decl = self.parse_fn_decl(false);
3835 let (inner_attrs, body) = self.parse_inner_attrs_and_block();
3836 (ident, ItemFn(decl, purity, abis, generics, body), Some(inner_attrs))
3839 // parse a method in a trait impl, starting with `attrs` attributes.
3840 fn parse_method(&mut self, already_parsed_attrs: Option<~[Attribute]>) -> @Method {
3841 let next_attrs = self.parse_outer_attributes();
3842 let attrs = match already_parsed_attrs {
3843 Some(mut a) => { a.push_all_move(next_attrs); a }
3847 let lo = self.span.lo;
3849 let visa = self.parse_visibility();
3850 let pur = self.parse_fn_purity();
3851 let ident = self.parse_ident();
3852 let generics = self.parse_generics();
3853 let (explicit_self, decl) = self.parse_fn_decl_with_self(|p| {
3857 let (inner_attrs, body) = self.parse_inner_attrs_and_block();
3858 let hi = body.span.hi;
3859 let attrs = vec::append(attrs, inner_attrs);
3864 explicit_self: explicit_self,
3868 id: ast::DUMMY_NODE_ID,
3869 span: mk_sp(lo, hi),
3874 // parse trait Foo { ... }
3875 fn parse_item_trait(&mut self) -> ItemInfo {
3876 let ident = self.parse_ident();
3877 let tps = self.parse_generics();
3879 // Parse traits, if necessary.
3881 if self.token == token::COLON {
3883 traits = self.parse_trait_ref_list(&token::LBRACE);
3888 let meths = self.parse_trait_methods();
3889 (ident, ItemTrait(tps, traits, meths), None)
3892 // Parses two variants (with the region/type params always optional):
3893 // impl<T> Foo { ... }
3894 // impl<T> ToStr for ~[T] { ... }
3895 fn parse_item_impl(&mut self) -> ItemInfo {
3896 // First, parse type parameters if necessary.
3897 let generics = self.parse_generics();
3899 // This is a new-style impl declaration.
3900 // FIXME: clownshoes
3901 let ident = special_idents::clownshoes_extensions;
3903 // Special case: if the next identifier that follows is '(', don't
3904 // allow this to be parsed as a trait.
3905 let could_be_trait = self.token != token::LPAREN;
3908 let mut ty = self.parse_ty(false);
3910 // Parse traits, if necessary.
3911 let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) {
3912 // New-style trait. Reinterpret the type as a trait.
3913 let opt_trait_ref = match ty.node {
3914 TyPath(ref path, None, node_id) => {
3916 path: /* bad */ (*path).clone(),
3921 self.span_err(ty.span,
3922 "bounded traits are only valid in type position");
3926 self.span_err(ty.span, "not a trait");
3931 ty = self.parse_ty(false);
3937 let mut meths = ~[];
3938 self.expect(&token::LBRACE);
3939 let (inner_attrs, next) = self.parse_inner_attrs_and_next();
3940 let mut method_attrs = Some(next);
3941 while !self.eat(&token::RBRACE) {
3942 meths.push(self.parse_method(method_attrs));
3943 method_attrs = None;
3946 (ident, ItemImpl(generics, opt_trait, ty, meths), Some(inner_attrs))
3949 // parse a::B<~str,int>
3950 fn parse_trait_ref(&mut self) -> TraitRef {
3952 path: self.parse_path(LifetimeAndTypesWithoutColons).path,
3953 ref_id: ast::DUMMY_NODE_ID,
3957 // parse B + C<~str,int> + D
3958 fn parse_trait_ref_list(&mut self, ket: &token::Token) -> ~[TraitRef] {
3959 self.parse_seq_to_before_end(
3961 seq_sep_trailing_disallowed(token::BINOP(token::PLUS)),
3962 |p| p.parse_trait_ref()
3966 // parse struct Foo { ... }
3967 fn parse_item_struct(&mut self) -> ItemInfo {
3968 let class_name = self.parse_ident();
3969 let generics = self.parse_generics();
3971 let mut fields: ~[StructField];
3974 if self.eat(&token::LBRACE) {
3975 // It's a record-like struct.
3976 is_tuple_like = false;
3978 while self.token != token::RBRACE {
3979 fields.push(self.parse_struct_decl_field());
3981 if fields.len() == 0 {
3982 let string = get_ident_interner().get(class_name.name);
3983 self.fatal(format!("Unit-like struct definition should be written as `struct {};`",
3984 string.as_slice()));
3987 } else if self.token == token::LPAREN {
3988 // It's a tuple-like struct.
3989 is_tuple_like = true;
3990 fields = self.parse_unspanned_seq(
3993 seq_sep_trailing_allowed(token::COMMA),
3995 let attrs = p.parse_outer_attributes();
3997 let struct_field_ = ast::StructField_ {
3999 id: ast::DUMMY_NODE_ID,
4000 ty: p.parse_ty(false),
4003 spanned(lo, p.span.hi, struct_field_)
4005 self.expect(&token::SEMI);
4006 } else if self.eat(&token::SEMI) {
4007 // It's a unit-like struct.
4008 is_tuple_like = true;
4011 let token_str = self.this_token_to_str();
4012 self.fatal(format!("expected `\\{`, `(`, or `;` after struct \
4013 name but found `{}`",
4017 let _ = ast::DUMMY_NODE_ID; // FIXME: Workaround for crazy bug.
4018 let new_id = ast::DUMMY_NODE_ID;
4020 ItemStruct(@ast::StructDef {
4022 ctor_id: if is_tuple_like { Some(new_id) } else { None }
4027 // parse a structure field declaration
4028 pub fn parse_single_struct_field(&mut self,
4030 attrs: ~[Attribute])
4032 let a_var = self.parse_name_and_ty(vis, attrs);
4039 let token_str = self.this_token_to_str();
4040 self.span_fatal(self.span,
4041 format!("expected `,`, or `\\}` but found `{}`",
4048 // parse an element of a struct definition
4049 fn parse_struct_decl_field(&mut self) -> StructField {
4051 let attrs = self.parse_outer_attributes();
4053 if self.eat_keyword(keywords::Priv) {
4054 return self.parse_single_struct_field(Private, attrs);
4057 if self.eat_keyword(keywords::Pub) {
4058 return self.parse_single_struct_field(Public, attrs);
4061 return self.parse_single_struct_field(Inherited, attrs);
4064 // parse visiility: PUB, PRIV, or nothing
4065 fn parse_visibility(&mut self) -> Visibility {
4066 if self.eat_keyword(keywords::Pub) { Public }
4067 else if self.eat_keyword(keywords::Priv) { Private }
4071 // given a termination token and a vector of already-parsed
4072 // attributes (of length 0 or 1), parse all of the items in a module
4073 fn parse_mod_items(&mut self,
4075 first_item_attrs: ~[Attribute])
4077 // parse all of the items up to closing or an attribute.
4078 // view items are legal here.
4079 let ParsedItemsAndViewItems {
4080 attrs_remaining: attrs_remaining,
4081 view_items: view_items,
4082 items: starting_items,
4084 } = self.parse_items_and_view_items(first_item_attrs, true, true);
4085 let mut items: ~[@Item] = starting_items;
4086 let attrs_remaining_len = attrs_remaining.len();
4088 // don't think this other loop is even necessary....
4090 let mut first = true;
4091 while self.token != term {
4092 let mut attrs = self.parse_outer_attributes();
4094 attrs = attrs_remaining + attrs;
4097 debug!("parse_mod_items: parse_item_or_view_item(attrs={:?})",
4099 match self.parse_item_or_view_item(attrs,
4100 true /* macros allowed */) {
4101 IoviItem(item) => items.push(item),
4102 IoviViewItem(view_item) => {
4103 self.span_fatal(view_item.span,
4104 "view items must be declared at the top of \
4108 let token_str = self.this_token_to_str();
4109 self.fatal(format!("expected item but found `{}`",
4115 if first && attrs_remaining_len > 0u {
4116 // We parsed attributes for the first item but didn't find it
4117 self.span_err(self.last_span, "expected item after attributes");
4120 ast::Mod { view_items: view_items, items: items }
4123 fn parse_item_const(&mut self) -> ItemInfo {
4124 let m = if self.eat_keyword(keywords::Mut) {MutMutable} else {MutImmutable};
4125 let id = self.parse_ident();
4126 self.expect(&token::COLON);
4127 let ty = self.parse_ty(false);
4128 self.expect(&token::EQ);
4129 let e = self.parse_expr();
4130 self.commit_expr_expecting(e, token::SEMI);
4131 (id, ItemStatic(ty, m, e), None)
4134 // parse a `mod <foo> { ... }` or `mod <foo>;` item
4135 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> ItemInfo {
4136 let id_span = self.span;
4137 let id = self.parse_ident();
4138 if self.token == token::SEMI {
4140 // This mod is in an external file. Let's go get it!
4141 let (m, attrs) = self.eval_src_mod(id, outer_attrs, id_span);
4142 (id, m, Some(attrs))
4144 self.push_mod_path(id, outer_attrs);
4145 self.expect(&token::LBRACE);
4146 let (inner, next) = self.parse_inner_attrs_and_next();
4147 let m = self.parse_mod_items(token::RBRACE, next);
4148 self.expect(&token::RBRACE);
4149 self.pop_mod_path();
4150 (id, ItemMod(m), Some(inner))
4154 fn push_mod_path(&mut self, id: Ident, attrs: &[Attribute]) {
4155 let default_path = self.id_to_interned_str(id);
4156 let file_path = match ::attr::first_attr_value_str_by_name(attrs,
4159 None => default_path,
4161 self.mod_path_stack.push(file_path)
4164 fn pop_mod_path(&mut self) {
4165 self.mod_path_stack.pop().unwrap();
4168 // read a module from a source file.
4169 fn eval_src_mod(&mut self,
4171 outer_attrs: &[ast::Attribute],
4173 -> (ast::Item_, ~[ast::Attribute]) {
4174 let mut prefix = Path::new(self.sess.cm.span_to_filename(self.span));
4176 let mod_path = Path::new(".").join_many(self.mod_path_stack);
4177 let dir_path = prefix.join(&mod_path);
4178 let file_path = match ::attr::first_attr_value_str_by_name(
4179 outer_attrs, "path") {
4180 Some(d) => dir_path.join(d),
4182 let mod_string = token::get_ident(id.name);
4183 let mod_name = mod_string.get().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 identifier_string = token::get_ident(s.name);
4539 let the_string = identifier_string.get();
4540 let mut abis = AbiSet::empty();
4541 for word in the_string.words() {
4542 match abi::lookup(word) {
4544 if abis.contains(abi) {
4547 format!("ABI `{}` appears twice",
4557 format!("illegal ABI: \
4558 expected one of [{}], \
4560 abi::all_names().connect(", "),
4574 // parse one of the items or view items allowed by the
4575 // flags; on failure, return IoviNone.
4576 // NB: this function no longer parses the items inside an
4578 fn parse_item_or_view_item(&mut self,
4579 attrs: ~[Attribute],
4580 macros_allowed: bool)
4583 INTERPOLATED(token::NtItem(item)) => {
4585 let new_attrs = vec::append(attrs, item.attrs);
4586 return IoviItem(@Item {
4594 let lo = self.span.lo;
4596 let visibility = self.parse_visibility();
4598 // must be a view item:
4599 if self.eat_keyword(keywords::Use) {
4600 // USE ITEM (IoviViewItem)
4601 let view_item = self.parse_use();
4602 self.expect(&token::SEMI);
4603 return IoviViewItem(ast::ViewItem {
4607 span: mk_sp(lo, self.last_span.hi)
4610 // either a view item or an item:
4611 if self.is_keyword(keywords::Extern) {
4612 let opt_abis = self.parse_opt_abis();
4614 if self.eat_keyword(keywords::Fn) {
4615 // EXTERN FUNCTION ITEM
4616 let abis = opt_abis.unwrap_or(AbiSet::C());
4617 let (ident, item_, extra_attrs) =
4618 self.parse_item_fn(ExternFn, abis);
4619 let item = self.mk_item(lo,
4624 maybe_append(attrs, extra_attrs));
4625 return IoviItem(item);
4627 // EXTERN MODULE ITEM (IoviViewItem)
4628 return self.parse_item_foreign_mod(lo, opt_abis, visibility, attrs,
4632 // the rest are all guaranteed to be items:
4633 if self.is_keyword(keywords::Static) {
4636 let (ident, item_, extra_attrs) = self.parse_item_const();
4637 let item = self.mk_item(lo,
4642 maybe_append(attrs, extra_attrs));
4643 return IoviItem(item);
4645 if self.is_keyword(keywords::Fn) &&
4646 self.look_ahead(1, |f| !Parser::fn_expr_lookahead(f)) {
4649 let (ident, item_, extra_attrs) =
4650 self.parse_item_fn(ImpureFn, AbiSet::Rust());
4651 let item = self.mk_item(lo,
4656 maybe_append(attrs, extra_attrs));
4657 return IoviItem(item);
4659 if self.is_keyword(keywords::Unsafe)
4660 && self.look_ahead(1u, |t| *t != token::LBRACE) {
4661 // UNSAFE FUNCTION ITEM
4663 self.expect_keyword(keywords::Fn);
4664 let (ident, item_, extra_attrs) =
4665 self.parse_item_fn(UnsafeFn, AbiSet::Rust());
4666 let item = self.mk_item(lo,
4671 maybe_append(attrs, extra_attrs));
4672 return IoviItem(item);
4674 if self.eat_keyword(keywords::Mod) {
4676 let (ident, item_, extra_attrs) = self.parse_item_mod(attrs);
4677 let item = self.mk_item(lo,
4682 maybe_append(attrs, extra_attrs));
4683 return IoviItem(item);
4685 if self.eat_keyword(keywords::Type) {
4687 let (ident, item_, extra_attrs) = self.parse_item_type();
4688 let item = self.mk_item(lo,
4693 maybe_append(attrs, extra_attrs));
4694 return IoviItem(item);
4696 if self.eat_keyword(keywords::Enum) {
4698 let (ident, item_, extra_attrs) = self.parse_item_enum();
4699 let item = self.mk_item(lo,
4704 maybe_append(attrs, extra_attrs));
4705 return IoviItem(item);
4707 if self.eat_keyword(keywords::Trait) {
4709 let (ident, item_, extra_attrs) = self.parse_item_trait();
4710 let item = self.mk_item(lo,
4715 maybe_append(attrs, extra_attrs));
4716 return IoviItem(item);
4718 if self.eat_keyword(keywords::Impl) {
4720 let (ident, item_, extra_attrs) = self.parse_item_impl();
4721 let item = self.mk_item(lo,
4726 maybe_append(attrs, extra_attrs));
4727 return IoviItem(item);
4729 if self.eat_keyword(keywords::Struct) {
4731 let (ident, item_, extra_attrs) = self.parse_item_struct();
4732 let item = self.mk_item(lo,
4737 maybe_append(attrs, extra_attrs));
4738 return IoviItem(item);
4740 self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility)
4743 // parse a foreign item; on failure, return IoviNone.
4744 fn parse_foreign_item(&mut self,
4745 attrs: ~[Attribute],
4746 macros_allowed: bool)
4748 maybe_whole!(iovi self, NtItem);
4749 let lo = self.span.lo;
4751 let visibility = self.parse_visibility();
4753 if self.is_keyword(keywords::Static) {
4754 // FOREIGN STATIC ITEM
4755 let item = self.parse_item_foreign_static(visibility, attrs);
4756 return IoviForeignItem(item);
4758 if self.is_keyword(keywords::Fn) || self.is_keyword(keywords::Unsafe) {
4759 // FOREIGN FUNCTION ITEM
4760 let item = self.parse_item_foreign_fn(visibility, attrs);
4761 return IoviForeignItem(item);
4763 self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility)
4766 // this is the fall-through for parsing items.
4767 fn parse_macro_use_or_failure(
4769 attrs: ~[Attribute],
4770 macros_allowed: bool,
4772 visibility: Visibility
4773 ) -> ItemOrViewItem {
4774 if macros_allowed && !token::is_any_keyword(&self.token)
4775 && self.look_ahead(1, |t| *t == token::NOT)
4776 && (self.look_ahead(2, |t| is_plain_ident(t))
4777 || self.look_ahead(2, |t| *t == token::LPAREN)
4778 || self.look_ahead(2, |t| *t == token::LBRACE)) {
4779 // MACRO INVOCATION ITEM
4782 let pth = self.parse_path(NoTypesAllowed).path;
4783 self.expect(&token::NOT);
4785 // a 'special' identifier (like what `macro_rules!` uses)
4786 // is optional. We should eventually unify invoc syntax
4788 let id = if is_plain_ident(&self.token) {
4791 token::special_idents::invalid // no special identifier
4793 // eat a matched-delimiter token tree:
4794 let tts = match self.token {
4795 token::LPAREN | token::LBRACE => {
4796 let ket = token::flip_delimiter(&self.token);
4798 self.parse_seq_to_end(&ket,
4800 |p| p.parse_token_tree())
4802 _ => self.fatal("expected open delimiter")
4804 // single-variant-enum... :
4805 let m = ast::MacInvocTT(pth, tts, EMPTY_CTXT);
4806 let m: ast::Mac = codemap::Spanned { node: m,
4807 span: mk_sp(self.span.lo,
4809 let item_ = ItemMac(m);
4810 let item = self.mk_item(lo,
4816 return IoviItem(item);
4819 // FAILURE TO PARSE ITEM
4820 if visibility != Inherited {
4821 let mut s = ~"unmatched visibility `";
4822 if visibility == Public {
4828 self.span_fatal(self.last_span, s);
4830 return IoviNone(attrs);
4833 pub fn parse_item(&mut self, attrs: ~[Attribute]) -> Option<@Item> {
4834 match self.parse_item_or_view_item(attrs, true) {
4835 IoviNone(_) => None,
4837 self.fatal("view items are not allowed here"),
4838 IoviForeignItem(_) =>
4839 self.fatal("foreign items are not allowed here"),
4840 IoviItem(item) => Some(item)
4844 // parse, e.g., "use a::b::{z,y}"
4845 fn parse_use(&mut self) -> ViewItem_ {
4846 return ViewItemUse(self.parse_view_paths());
4850 // matches view_path : MOD? IDENT EQ non_global_path
4851 // | MOD? non_global_path MOD_SEP LBRACE RBRACE
4852 // | MOD? non_global_path MOD_SEP LBRACE ident_seq RBRACE
4853 // | MOD? non_global_path MOD_SEP STAR
4854 // | MOD? non_global_path
4855 fn parse_view_path(&mut self) -> @ViewPath {
4856 let lo = self.span.lo;
4858 if self.token == token::LBRACE {
4860 let idents = self.parse_unspanned_seq(
4861 &token::LBRACE, &token::RBRACE,
4862 seq_sep_trailing_allowed(token::COMMA),
4863 |p| p.parse_path_list_ident());
4864 let path = ast::Path {
4865 span: mk_sp(lo, self.span.hi),
4869 return @spanned(lo, self.span.hi,
4870 ViewPathList(path, idents, ast::DUMMY_NODE_ID));
4873 let first_ident = self.parse_ident();
4874 let mut path = ~[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)
5134 -> Option<(InternedString, ast::StrStyle)> {
5135 let (s, style) = match self.token {
5136 token::LIT_STR(s) => (self.id_to_interned_str(s), ast::CookedStr),
5137 token::LIT_STR_RAW(s, n) => {
5138 (self.id_to_interned_str(s), ast::RawStr(n))
5146 pub fn parse_str(&mut self) -> (InternedString, StrStyle) {
5147 match self.parse_optional_str() {
5149 _ => self.fatal("expected string literal")