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::{BareFnTy, ClosureTy};
17 use ast::{RegionTyParamBound, TraitTyParamBound};
18 use ast::{Provided, Public, Purity};
19 use ast::{Mod, BiAdd, Arg, Arm, Attribute, BindByRef, BindByValue};
20 use ast::{BiBitAnd, BiBitOr, BiBitXor, Block};
21 use ast::{BlockCheckMode, UnBox};
22 use ast::{Crate, CrateConfig, Decl, DeclItem};
23 use ast::{DeclLocal, DefaultBlock, UnDeref, BiDiv, EMPTY_CTXT, EnumDef, ExplicitSelf};
24 use ast::{Expr, Expr_, ExprAddrOf, ExprMatch, ExprAgain};
25 use ast::{ExprAssign, ExprAssignOp, ExprBinary, ExprBlock, ExprBox};
26 use ast::{ExprBreak, ExprCall, ExprCast};
27 use ast::{ExprField, ExprFnBlock, ExprIf, ExprIndex};
28 use ast::{ExprLit, ExprLoop, ExprMac};
29 use ast::{ExprMethodCall, ExprParen, ExprPath, ExprProc};
30 use ast::{ExprRepeat, ExprRet, ExprStruct, ExprTup, ExprUnary};
31 use ast::{ExprVec, ExprVstore, ExprVstoreSlice};
32 use ast::{ExprVstoreMutSlice, ExprWhile, ExprForLoop, ExternFn, Field, FnDecl};
33 use ast::{ExprVstoreUniq, Onceness, Once, Many};
34 use ast::{ForeignItem, ForeignItemStatic, ForeignItemFn, ForeignMod};
35 use ast::{Ident, ImpureFn, Inherited, Item, Item_, ItemStatic};
36 use ast::{ItemEnum, ItemFn, ItemForeignMod, ItemImpl};
37 use ast::{ItemMac, ItemMod, ItemStruct, ItemTrait, ItemTy, Lit, Lit_};
38 use ast::{LitBool, LitFloat, LitFloatUnsuffixed, LitInt, LitChar};
39 use ast::{LitIntUnsuffixed, LitNil, LitStr, LitUint, Local};
40 use ast::{MutImmutable, MutMutable, Mac_, MacInvocTT, Matcher, MatchNonterminal};
41 use ast::{MatchSeq, MatchTok, Method, MutTy, BiMul, Mutability};
42 use ast::{NamedField, UnNeg, NoReturn, UnNot, P, Pat, PatEnum};
43 use ast::{PatIdent, PatLit, PatRange, PatRegion, PatStruct};
44 use ast::{PatTup, PatUniq, PatWild, PatWildMulti, Private};
45 use ast::{BiRem, Required};
46 use ast::{RetStyle, Return, BiShl, BiShr, Stmt, StmtDecl};
47 use ast::{StmtExpr, StmtSemi, StmtMac, StructDef, StructField};
48 use ast::{StructVariantKind, BiSub};
50 use ast::{SelfRegion, SelfStatic, SelfUniq, SelfValue};
51 use ast::{TokenTree, TraitMethod, TraitRef, TTDelim, TTSeq, TTTok};
52 use ast::{TTNonterminal, TupleVariantKind, Ty, Ty_, TyBot, TyBox};
53 use ast::{TypeField, TyFixedLengthVec, TyClosure, TyBareFn, TyTypeof};
54 use ast::{TyInfer, TypeMethod};
55 use ast::{TyNil, TyParam, TyParamBound, TyPath, TyPtr, TyRptr};
56 use ast::{TyTup, TyU32, TyUniq, TyVec, UnUniq};
57 use ast::{UnnamedField, UnsafeBlock, UnsafeFn, ViewItem};
58 use ast::{ViewItem_, ViewItemExternCrate, ViewItemUse};
59 use ast::{ViewPath, ViewPathGlob, ViewPathList, ViewPathSimple};
62 use ast_util::{as_prec, lit_is_str, operator_prec};
64 use codemap::{Span, BytePos, Spanned, spanned, mk_sp};
66 use parse::attr::ParserAttr;
68 use parse::common::{SeqSep, seq_sep_none};
69 use parse::common::{seq_sep_trailing_disallowed, seq_sep_trailing_allowed};
70 use parse::lexer::Reader;
71 use parse::lexer::TokenAndSpan;
72 use parse::obsolete::*;
73 use parse::token::{INTERPOLATED, InternedString, can_begin_expr};
74 use parse::token::{is_ident, is_ident_or_path, is_plain_ident};
75 use parse::token::{keywords, special_idents, token_to_binop};
77 use parse::{new_sub_parser_from_file, ParseSess};
78 use owned_slice::OwnedSlice;
81 use collections::HashSet;
82 use std::kinds::marker;
83 use std::mem::replace;
86 #[allow(non_camel_case_types)]
88 pub enum restriction {
92 RESTRICT_NO_BAR_OR_DOUBLEBAR_OP,
95 type ItemInfo = (Ident, Item_, Option<Vec<Attribute> >);
97 /// How to parse a path. There are four different kinds of paths, all of which
98 /// are parsed somewhat differently.
100 pub enum PathParsingMode {
101 /// A path with no type parameters; e.g. `foo::bar::Baz`
103 /// A path with a lifetime and type parameters, with no double colons
104 /// before the type parameters; e.g. `foo::bar<'a>::Baz<T>`
105 LifetimeAndTypesWithoutColons,
106 /// A path with a lifetime and type parameters with double colons before
107 /// the type parameters; e.g. `foo::bar::<'a>::Baz::<T>`
108 LifetimeAndTypesWithColons,
109 /// A path with a lifetime and type parameters with bounds before the last
110 /// set of type parameters only; e.g. `foo::bar<'a>::Baz:X+Y<T>` This
111 /// form does not use extra double colons.
112 LifetimeAndTypesAndBounds,
115 /// A pair of a path segment and group of type parameter bounds. (See `ast.rs`
116 /// for the definition of a path segment.)
117 struct PathSegmentAndBoundSet {
118 segment: ast::PathSegment,
119 bound_set: Option<OwnedSlice<TyParamBound>>,
122 /// A path paired with optional type bounds.
123 pub struct PathAndBounds {
125 bounds: Option<OwnedSlice<TyParamBound>>,
128 enum ItemOrViewItem {
129 // Indicates a failure to parse any kind of item. The attributes are
131 IoviNone(Vec<Attribute> ),
133 IoviForeignItem(@ForeignItem),
134 IoviViewItem(ViewItem)
137 /* The expr situation is not as complex as I thought it would be.
138 The important thing is to make sure that lookahead doesn't balk
139 at INTERPOLATED tokens */
140 macro_rules! maybe_whole_expr (
143 let mut maybe_path = match ($p).token {
144 INTERPOLATED(token::NtPath(ref pt)) => Some((**pt).clone()),
147 let ret = match ($p).token {
148 INTERPOLATED(token::NtExpr(e)) => {
151 INTERPOLATED(token::NtPath(_)) => {
152 let pt = maybe_path.take_unwrap();
153 Some($p.mk_expr(($p).span.lo, ($p).span.hi, ExprPath(pt)))
168 macro_rules! maybe_whole (
169 ($p:expr, $constructor:ident) => (
171 let __found__ = match ($p).token {
172 INTERPOLATED(token::$constructor(_)) => {
173 Some(($p).bump_and_get())
178 Some(INTERPOLATED(token::$constructor(x))) => {
185 (no_clone $p:expr, $constructor:ident) => (
187 let __found__ = match ($p).token {
188 INTERPOLATED(token::$constructor(_)) => {
189 Some(($p).bump_and_get())
194 Some(INTERPOLATED(token::$constructor(x))) => {
201 (deref $p:expr, $constructor:ident) => (
203 let __found__ = match ($p).token {
204 INTERPOLATED(token::$constructor(_)) => {
205 Some(($p).bump_and_get())
210 Some(INTERPOLATED(token::$constructor(x))) => {
217 (Some $p:expr, $constructor:ident) => (
219 let __found__ = match ($p).token {
220 INTERPOLATED(token::$constructor(_)) => {
221 Some(($p).bump_and_get())
226 Some(INTERPOLATED(token::$constructor(x))) => {
227 return Some(x.clone()),
233 (iovi $p:expr, $constructor:ident) => (
235 let __found__ = match ($p).token {
236 INTERPOLATED(token::$constructor(_)) => {
237 Some(($p).bump_and_get())
242 Some(INTERPOLATED(token::$constructor(x))) => {
243 return IoviItem(x.clone())
249 (pair_empty $p:expr, $constructor:ident) => (
251 let __found__ = match ($p).token {
252 INTERPOLATED(token::$constructor(_)) => {
253 Some(($p).bump_and_get())
258 Some(INTERPOLATED(token::$constructor(x))) => {
259 return (Vec::new(), x)
268 fn maybe_append(lhs: Vec<Attribute> , rhs: Option<Vec<Attribute> >)
272 Some(ref attrs) => vec::append(lhs, attrs.as_slice())
277 struct ParsedItemsAndViewItems {
278 attrs_remaining: Vec<Attribute> ,
279 view_items: Vec<ViewItem> ,
281 foreign_items: Vec<@ForeignItem> }
283 /* ident is handled by common.rs */
285 pub fn Parser<'a>(sess: &'a ParseSess, cfg: ast::CrateConfig, rdr: ~Reader:)
287 let tok0 = rdr.next_token();
289 let placeholder = TokenAndSpan {
290 tok: token::UNDERSCORE,
296 interner: token::get_ident_interner(),
312 restriction: UNRESTRICTED,
314 obsolete_set: HashSet::new(),
315 mod_path_stack: Vec::new(),
316 open_braces: Vec::new(),
321 pub struct Parser<'a> {
324 // the current token:
326 // the span of the current token:
328 // the span of the prior token:
330 // the previous token or None (only stashed sometimes).
331 last_token: Option<~token::Token>,
332 buffer: [TokenAndSpan, ..4],
335 tokens_consumed: uint,
336 restriction: restriction,
337 quote_depth: uint, // not (yet) related to the quasiquoter
339 interner: @token::IdentInterner,
340 /// The set of seen errors about obsolete syntax. Used to suppress
341 /// extra detail when the same error is seen twice
342 obsolete_set: HashSet<ObsoleteSyntax>,
343 /// Used to determine the path to externally loaded source files
344 mod_path_stack: Vec<InternedString> ,
345 /// Stack of spans of open delimiters. Used for error message.
346 open_braces: Vec<Span> ,
347 /* do not copy the parser; its state is tied to outside state */
348 priv nopod: marker::NoPod
351 fn is_plain_ident_or_underscore(t: &token::Token) -> bool {
352 is_plain_ident(t) || *t == token::UNDERSCORE
355 impl<'a> Parser<'a> {
356 // convert a token to a string using self's reader
357 pub fn token_to_str(token: &token::Token) -> ~str {
361 // convert the current token to a string using self's reader
362 pub fn this_token_to_str(&mut self) -> ~str {
363 Parser::token_to_str(&self.token)
366 pub fn unexpected_last(&mut self, t: &token::Token) -> ! {
367 let token_str = Parser::token_to_str(t);
368 self.span_fatal(self.last_span, format!("unexpected token: `{}`",
372 pub fn unexpected(&mut self) -> ! {
373 let this_token = self.this_token_to_str();
374 self.fatal(format!("unexpected token: `{}`", this_token));
377 // expect and consume the token t. Signal an error if
378 // the next token is not t.
379 pub fn expect(&mut self, t: &token::Token) {
380 if self.token == *t {
383 let token_str = Parser::token_to_str(t);
384 let this_token_str = self.this_token_to_str();
385 self.fatal(format!("expected `{}` but found `{}`",
391 // Expect next token to be edible or inedible token. If edible,
392 // then consume it; if inedible, then return without consuming
393 // anything. Signal a fatal error if next token is unexpected.
394 pub fn expect_one_of(&mut self,
395 edible: &[token::Token],
396 inedible: &[token::Token]) {
397 fn tokens_to_str(tokens: &[token::Token]) -> ~str {
398 let mut i = tokens.iter();
399 // This might be a sign we need a connect method on Iterator.
400 let b = i.next().map_or(~"", |t| Parser::token_to_str(t));
401 i.fold(b, |b,a| b + "`, `" + Parser::token_to_str(a))
403 if edible.contains(&self.token) {
405 } else if inedible.contains(&self.token) {
406 // leave it in the input
408 let expected = vec::append(edible.iter()
409 .map(|x| (*x).clone())
412 let expect = tokens_to_str(expected.as_slice());
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.iter()
451 .map(|x| (*x).clone())
454 self.check_for_erroneous_unit_struct_expecting(
455 expected.as_slice());
459 self.expect_one_of(edible, inedible)
462 pub fn commit_expr_expecting(&mut self, e: @Expr, edible: token::Token) {
463 self.commit_expr(e, &[edible], &[])
466 // Commit to parsing a complete statement `s`, which expects to be
467 // followed by some token from the set edible + inedible. Check
468 // for recoverable input errors, discarding erroneous characters.
469 pub fn commit_stmt(&mut self, s: @Stmt, edible: &[token::Token], inedible: &[token::Token]) {
470 debug!("commit_stmt {:?}", s);
471 let _s = s; // unused, but future checks might want to inspect `s`.
472 if self.last_token.as_ref().map_or(false, |t| is_ident_or_path(*t)) {
473 let expected = vec::append(edible.iter()
474 .map(|x| (*x).clone())
476 inedible.as_slice());
477 self.check_for_erroneous_unit_struct_expecting(
478 expected.as_slice());
480 self.expect_one_of(edible, inedible)
483 pub fn commit_stmt_expecting(&mut self, s: @Stmt, edible: token::Token) {
484 self.commit_stmt(s, &[edible], &[])
487 pub fn parse_ident(&mut self) -> ast::Ident {
488 self.check_strict_keywords();
489 self.check_reserved_keywords();
491 token::IDENT(i, _) => {
495 token::INTERPOLATED(token::NtIdent(..)) => {
496 self.bug("ident interpolation not converted to real token");
499 let token_str = self.this_token_to_str();
500 self.fatal(format!( "expected ident, found `{}`", token_str))
505 pub fn parse_path_list_ident(&mut self) -> ast::PathListIdent {
506 let lo = self.span.lo;
507 let ident = self.parse_ident();
508 let hi = self.last_span.hi;
509 spanned(lo, hi, ast::PathListIdent_ { name: ident,
510 id: ast::DUMMY_NODE_ID })
513 // consume token 'tok' if it exists. Returns true if the given
514 // token was present, false otherwise.
515 pub fn eat(&mut self, tok: &token::Token) -> bool {
516 let is_present = self.token == *tok;
517 if is_present { self.bump() }
521 pub fn is_keyword(&mut self, kw: keywords::Keyword) -> bool {
522 token::is_keyword(kw, &self.token)
525 // if the next token is the given keyword, eat it and return
526 // true. Otherwise, return false.
527 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
528 let is_kw = match self.token {
529 token::IDENT(sid, false) => kw.to_ident().name == sid.name,
532 if is_kw { self.bump() }
536 // if the given word is not a keyword, signal an error.
537 // if the next token is not the given word, signal an error.
538 // otherwise, eat it.
539 pub fn expect_keyword(&mut self, kw: keywords::Keyword) {
540 if !self.eat_keyword(kw) {
541 let id_interned_str = token::get_ident(kw.to_ident());
542 let token_str = self.this_token_to_str();
543 self.fatal(format!("expected `{}`, found `{}`",
544 id_interned_str, token_str))
548 // signal an error if the given string is a strict keyword
549 pub fn check_strict_keywords(&mut self) {
550 if token::is_strict_keyword(&self.token) {
551 let token_str = self.this_token_to_str();
552 self.span_err(self.span,
553 format!("found `{}` in ident position", token_str));
557 // signal an error if the current token is a reserved keyword
558 pub fn check_reserved_keywords(&mut self) {
559 if token::is_reserved_keyword(&self.token) {
560 let token_str = self.this_token_to_str();
561 self.fatal(format!("`{}` is a reserved keyword", token_str))
565 // Expect and consume a `|`. If `||` is seen, replace it with a single
566 // `|` and continue. If a `|` is not seen, signal an error.
567 fn expect_or(&mut self) {
569 token::BINOP(token::OR) => self.bump(),
571 let lo = self.span.lo + BytePos(1);
572 self.replace_token(token::BINOP(token::OR), lo, self.span.hi)
575 let token_str = self.this_token_to_str();
577 Parser::token_to_str(&token::BINOP(token::OR));
578 self.fatal(format!("expected `{}`, found `{}`",
585 // Parse a sequence bracketed by `|` and `|`, stopping before the `|`.
586 fn parse_seq_to_before_or<T>(
589 f: |&mut Parser| -> T)
591 let mut first = true;
592 let mut vector = Vec::new();
593 while self.token != token::BINOP(token::OR) &&
594 self.token != token::OROR {
606 // expect and consume a GT. if a >> is seen, replace it
607 // with a single > and continue. If a GT is not seen,
609 pub fn expect_gt(&mut self) {
611 token::GT => self.bump(),
612 token::BINOP(token::SHR) => {
613 let lo = self.span.lo + BytePos(1);
614 self.replace_token(token::GT, lo, self.span.hi)
617 let gt_str = Parser::token_to_str(&token::GT);
618 let this_token_str = self.this_token_to_str();
619 self.fatal(format!("expected `{}`, found `{}`",
626 // parse a sequence bracketed by '<' and '>', stopping
628 pub fn parse_seq_to_before_gt<T>(
630 sep: Option<token::Token>,
631 f: |&mut Parser| -> T)
633 let mut first = true;
634 let mut v = Vec::new();
635 while self.token != token::GT
636 && self.token != token::BINOP(token::SHR) {
639 if first { first = false; }
640 else { self.expect(t); }
646 return OwnedSlice::from_vec(v);
649 pub fn parse_seq_to_gt<T>(
651 sep: Option<token::Token>,
652 f: |&mut Parser| -> T)
654 let v = self.parse_seq_to_before_gt(sep, f);
659 // parse a sequence, including the closing delimiter. The function
660 // f must consume tokens until reaching the next separator or
662 pub fn parse_seq_to_end<T>(
666 f: |&mut Parser| -> T)
668 let val = self.parse_seq_to_before_end(ket, sep, f);
673 // parse a sequence, not including the closing delimiter. The function
674 // f must consume tokens until reaching the next separator or
676 pub fn parse_seq_to_before_end<T>(
680 f: |&mut Parser| -> T)
682 let mut first: bool = true;
684 while self.token != *ket {
687 if first { first = false; }
688 else { self.expect(t); }
692 if sep.trailing_sep_allowed && self.token == *ket { break; }
698 // parse a sequence, including the closing delimiter. The function
699 // f must consume tokens until reaching the next separator or
701 pub fn parse_unspanned_seq<T>(
706 f: |&mut Parser| -> T)
709 let result = self.parse_seq_to_before_end(ket, sep, f);
714 // parse a sequence parameter of enum variant. For consistency purposes,
715 // these should not be empty.
716 pub fn parse_enum_variant_seq<T>(
721 f: |&mut Parser| -> T)
723 let result = self.parse_unspanned_seq(bra, ket, sep, f);
724 if result.is_empty() {
725 self.span_err(self.last_span,
726 "nullary enum variants are written with no trailing `( )`");
731 // NB: Do not use this function unless you actually plan to place the
732 // spanned list in the AST.
738 f: |&mut Parser| -> T)
739 -> Spanned<Vec<T> > {
740 let lo = self.span.lo;
742 let result = self.parse_seq_to_before_end(ket, sep, f);
743 let hi = self.span.hi;
745 spanned(lo, hi, result)
748 // advance the parser by one token
749 pub fn bump(&mut self) {
750 self.last_span = self.span;
751 // Stash token for error recovery (sometimes; clone is not necessarily cheap).
752 self.last_token = if is_ident_or_path(&self.token) {
753 Some(~self.token.clone())
757 let next = if self.buffer_start == self.buffer_end {
758 self.reader.next_token()
760 // Avoid token copies with `replace`.
761 let buffer_start = self.buffer_start as uint;
762 let next_index = (buffer_start + 1) & 3 as uint;
763 self.buffer_start = next_index as int;
765 let placeholder = TokenAndSpan {
766 tok: token::UNDERSCORE,
769 replace(&mut self.buffer[buffer_start], placeholder)
772 self.token = next.tok;
773 self.tokens_consumed += 1u;
776 // Advance the parser by one token and return the bumped token.
777 pub fn bump_and_get(&mut self) -> token::Token {
778 let old_token = replace(&mut self.token, token::UNDERSCORE);
783 // EFFECT: replace the current token and span with the given one
784 pub fn replace_token(&mut self,
788 self.last_span = mk_sp(self.span.lo, lo);
790 self.span = mk_sp(lo, hi);
792 pub fn buffer_length(&mut self) -> int {
793 if self.buffer_start <= self.buffer_end {
794 return self.buffer_end - self.buffer_start;
796 return (4 - self.buffer_start) + self.buffer_end;
798 pub fn look_ahead<R>(&mut self, distance: uint, f: |&token::Token| -> R)
800 let dist = distance as int;
801 while self.buffer_length() < dist {
802 self.buffer[self.buffer_end] = self.reader.next_token();
803 self.buffer_end = (self.buffer_end + 1) & 3;
805 f(&self.buffer[(self.buffer_start + dist - 1) & 3].tok)
807 pub fn fatal(&mut self, m: &str) -> ! {
808 self.sess.span_diagnostic.span_fatal(self.span, m)
810 pub fn span_fatal(&mut self, sp: Span, m: &str) -> ! {
811 self.sess.span_diagnostic.span_fatal(sp, m)
813 pub fn span_note(&mut self, sp: Span, m: &str) {
814 self.sess.span_diagnostic.span_note(sp, m)
816 pub fn bug(&mut self, m: &str) -> ! {
817 self.sess.span_diagnostic.span_bug(self.span, m)
819 pub fn warn(&mut self, m: &str) {
820 self.sess.span_diagnostic.span_warn(self.span, m)
822 pub fn span_err(&mut self, sp: Span, m: &str) {
823 self.sess.span_diagnostic.span_err(sp, m)
825 pub fn abort_if_errors(&mut self) {
826 self.sess.span_diagnostic.handler().abort_if_errors();
829 pub fn id_to_interned_str(&mut self, id: Ident) -> InternedString {
833 // Is the current token one of the keywords that signals a bare function
835 pub fn token_is_bare_fn_keyword(&mut self) -> bool {
836 if token::is_keyword(keywords::Fn, &self.token) {
840 if token::is_keyword(keywords::Unsafe, &self.token) ||
841 token::is_keyword(keywords::Once, &self.token) {
842 return self.look_ahead(1, |t| token::is_keyword(keywords::Fn, t))
848 // Is the current token one of the keywords that signals a closure type?
849 pub fn token_is_closure_keyword(&mut self) -> bool {
850 token::is_keyword(keywords::Unsafe, &self.token) ||
851 token::is_keyword(keywords::Once, &self.token)
854 // Is the current token one of the keywords that signals an old-style
855 // closure type (with explicit sigil)?
856 pub fn token_is_old_style_closure_keyword(&mut self) -> bool {
857 token::is_keyword(keywords::Unsafe, &self.token) ||
858 token::is_keyword(keywords::Once, &self.token) ||
859 token::is_keyword(keywords::Fn, &self.token)
862 pub fn token_is_lifetime(tok: &token::Token) -> bool {
864 token::LIFETIME(..) => true,
869 pub fn get_lifetime(&mut self) -> ast::Ident {
871 token::LIFETIME(ref ident) => *ident,
872 _ => self.bug("not a lifetime"),
876 // parse a TyBareFn type:
877 pub fn parse_ty_bare_fn(&mut self) -> Ty_ {
880 [extern "ABI"] [unsafe] fn <'lt> (S) -> T
881 ^~~~^ ^~~~~~~^ ^~~~^ ^~^ ^
892 let abis = if self.eat_keyword(keywords::Extern) {
893 self.parse_opt_abis().unwrap_or(AbiSet::C())
898 let purity = self.parse_unsafety();
899 self.expect_keyword(keywords::Fn);
900 let (decl, lifetimes) = self.parse_ty_fn_decl(true);
901 return TyBareFn(@BareFnTy {
904 lifetimes: lifetimes,
909 // Parses a procedure type (`proc`). The initial `proc` keyword must
910 // already have been parsed.
911 pub fn parse_proc_type(&mut self) -> Ty_ {
912 let bounds = self.parse_optional_ty_param_bounds();
913 let (decl, lifetimes) = self.parse_ty_fn_decl(false);
914 TyClosure(@ClosureTy {
921 lifetimes: lifetimes,
925 // parse a TyClosure type
926 pub fn parse_ty_closure(&mut self,
927 opt_sigil: Option<ast::Sigil>,
928 mut region: Option<ast::Lifetime>)
932 (&|~|@) ['r] [unsafe] [once] fn [:Bounds] <'lt> (S) -> T
933 ^~~~~~^ ^~~^ ^~~~~~~^ ^~~~~^ ^~~~~~~~^ ^~~~^ ^~^ ^
935 | | | | | | | Return type
936 | | | | | | Argument types
938 | | | | Closure bounds
939 | | | Once-ness (a.k.a., affine)
946 // At this point, the allocation type and lifetime bound have been
949 let purity = self.parse_unsafety();
950 let onceness = parse_onceness(self);
952 let (sigil, decl, lifetimes, bounds) = match opt_sigil {
954 // Old-style closure syntax (`fn(A)->B`).
955 self.expect_keyword(keywords::Fn);
956 let bounds = self.parse_optional_ty_param_bounds();
957 let (decl, lifetimes) = self.parse_ty_fn_decl(false);
958 (sigil, decl, lifetimes, bounds)
961 // New-style closure syntax (`<'lt>|A|:K -> B`).
962 let lifetimes = if self.eat(&token::LT) {
963 let lifetimes = self.parse_lifetimes();
966 // Re-parse the region here. What a hack.
967 if region.is_some() {
968 self.span_err(self.last_span,
969 "lifetime declarations must precede \
970 the lifetime associated with a \
973 region = self.parse_opt_lifetime();
980 let inputs = if self.eat(&token::OROR) {
984 let inputs = self.parse_seq_to_before_or(
986 |p| p.parse_arg_general(false));
991 let bounds = self.parse_optional_ty_param_bounds();
993 let (return_style, output) = self.parse_ret_ty();
994 let decl = P(FnDecl {
1001 (BorrowedSigil, decl, lifetimes, bounds)
1005 return TyClosure(@ClosureTy {
1012 lifetimes: lifetimes,
1015 fn parse_onceness(this: &mut Parser) -> Onceness {
1016 if this.eat_keyword(keywords::Once) {
1024 pub fn parse_unsafety(&mut self) -> Purity {
1025 if self.eat_keyword(keywords::Unsafe) {
1032 // parse a function type (following the 'fn')
1033 pub fn parse_ty_fn_decl(&mut self, allow_variadic: bool)
1034 -> (P<FnDecl>, Vec<ast::Lifetime>) {
1045 let lifetimes = if self.eat(&token::LT) {
1046 let lifetimes = self.parse_lifetimes();
1053 let (inputs, variadic) = self.parse_fn_args(false, allow_variadic);
1054 let (ret_style, ret_ty) = self.parse_ret_ty();
1055 let decl = P(FnDecl {
1064 // parse the methods in a trait declaration
1065 pub fn parse_trait_methods(&mut self) -> Vec<TraitMethod> {
1066 self.parse_unspanned_seq(
1071 let attrs = p.parse_outer_attributes();
1074 let vis_span = p.span;
1075 let vis = p.parse_visibility();
1076 let pur = p.parse_fn_purity();
1077 // NB: at the moment, trait methods are public by default; this
1079 let ident = p.parse_ident();
1081 let generics = p.parse_generics();
1083 let (explicit_self, d) = p.parse_fn_decl_with_self(|p| {
1084 // This is somewhat dubious; We don't want to allow argument
1085 // names to be left off if there is a definition...
1086 p.parse_arg_general(false)
1089 let hi = p.last_span.hi;
1093 debug!("parse_trait_methods(): parsing required method");
1094 // NB: at the moment, visibility annotations on required
1095 // methods are ignored; this could change.
1096 if vis != ast::Inherited {
1097 p.obsolete(vis_span, ObsoleteTraitFuncVisibility);
1099 Required(TypeMethod {
1105 explicit_self: explicit_self,
1106 id: ast::DUMMY_NODE_ID,
1111 debug!("parse_trait_methods(): parsing provided method");
1112 let (inner_attrs, body) =
1113 p.parse_inner_attrs_and_block();
1114 let attrs = vec::append(attrs, inner_attrs.as_slice());
1115 Provided(@ast::Method {
1119 explicit_self: explicit_self,
1123 id: ast::DUMMY_NODE_ID,
1124 span: mk_sp(lo, hi),
1130 let token_str = p.this_token_to_str();
1131 p.fatal(format!("expected `;` or `\\{` but found `{}`",
1138 // parse a possibly mutable type
1139 pub fn parse_mt(&mut self) -> MutTy {
1140 let mutbl = self.parse_mutability();
1141 let t = self.parse_ty(false);
1142 MutTy { ty: t, mutbl: mutbl }
1145 // parse [mut/const/imm] ID : TY
1146 // now used only by obsolete record syntax parser...
1147 pub fn parse_ty_field(&mut self) -> TypeField {
1148 let lo = self.span.lo;
1149 let mutbl = self.parse_mutability();
1150 let id = self.parse_ident();
1151 self.expect(&token::COLON);
1152 let ty = self.parse_ty(false);
1153 let hi = ty.span.hi;
1156 mt: MutTy { ty: ty, mutbl: mutbl },
1157 span: mk_sp(lo, hi),
1161 // parse optional return type [ -> TY ] in function decl
1162 pub fn parse_ret_ty(&mut self) -> (RetStyle, P<Ty>) {
1163 return if self.eat(&token::RARROW) {
1164 let lo = self.span.lo;
1165 if self.eat(&token::NOT) {
1169 id: ast::DUMMY_NODE_ID,
1171 span: mk_sp(lo, self.last_span.hi)
1175 (Return, self.parse_ty(false))
1178 let pos = self.span.lo;
1182 id: ast::DUMMY_NODE_ID,
1184 span: mk_sp(pos, pos),
1191 // Useless second parameter for compatibility with quasiquote macros.
1193 pub fn parse_ty(&mut self, _: bool) -> P<Ty> {
1194 maybe_whole!(no_clone self, NtTy);
1196 let lo = self.span.lo;
1198 let t = if self.token == token::LPAREN {
1200 if self.token == token::RPAREN {
1204 // (t) is a parenthesized ty
1205 // (t,) is the type of a tuple with only one field,
1207 let mut ts = vec!(self.parse_ty(false));
1208 let mut one_tuple = false;
1209 while self.token == token::COMMA {
1211 if self.token != token::RPAREN {
1212 ts.push(self.parse_ty(false));
1219 if ts.len() == 1 && !one_tuple {
1220 self.expect(&token::RPAREN);
1225 self.expect(&token::RPAREN);
1228 } else if self.token == token::AT {
1231 self.parse_box_or_uniq_pointee(ManagedSigil)
1232 } else if self.token == token::TILDE {
1235 self.parse_box_or_uniq_pointee(OwnedSigil)
1236 } else if self.token == token::BINOP(token::STAR) {
1237 // STAR POINTER (bare pointer?)
1239 TyPtr(self.parse_mt())
1240 } else if self.token == token::LBRACKET {
1242 self.expect(&token::LBRACKET);
1243 let t = self.parse_ty(false);
1245 // Parse the `, ..e` in `[ int, ..e ]`
1246 // where `e` is a const expression
1247 let t = match self.maybe_parse_fixed_vstore() {
1249 Some(suffix) => TyFixedLengthVec(t, suffix)
1251 self.expect(&token::RBRACKET);
1253 } else if self.token == token::BINOP(token::AND) {
1256 self.parse_borrowed_pointee()
1257 } else if self.is_keyword(keywords::Extern) ||
1258 self.token_is_bare_fn_keyword() {
1260 self.parse_ty_bare_fn()
1261 } else if self.token_is_closure_keyword() ||
1262 self.token == token::BINOP(token::OR) ||
1263 self.token == token::OROR ||
1264 self.token == token::LT ||
1265 Parser::token_is_lifetime(&self.token) {
1268 // FIXME(pcwalton): Eventually `token::LT` will not unambiguously
1269 // introduce a closure, once procs can have lifetime bounds. We
1270 // will need to refactor the grammar a little bit at that point.
1272 let lifetime = self.parse_opt_lifetime();
1273 let result = self.parse_ty_closure(None, lifetime);
1275 } else if self.eat_keyword(keywords::Typeof) {
1277 // In order to not be ambiguous, the type must be surrounded by parens.
1278 self.expect(&token::LPAREN);
1279 let e = self.parse_expr();
1280 self.expect(&token::RPAREN);
1282 } else if self.eat_keyword(keywords::Proc) {
1283 self.parse_proc_type()
1284 } else if self.token == token::MOD_SEP
1285 || is_ident_or_path(&self.token) {
1290 } = self.parse_path(LifetimeAndTypesAndBounds);
1291 TyPath(path, bounds, ast::DUMMY_NODE_ID)
1292 } else if self.eat(&token::UNDERSCORE) {
1293 // TYPE TO BE INFERRED
1296 let msg = format!("expected type, found token {:?}", self.token);
1300 let sp = mk_sp(lo, self.last_span.hi);
1301 P(Ty {id: ast::DUMMY_NODE_ID, node: t, span: sp})
1304 // parse the type following a @ or a ~
1305 pub fn parse_box_or_uniq_pointee(&mut self,
1308 // ~'foo fn() or ~fn() are parsed directly as obsolete fn types:
1310 token::LIFETIME(..) => {
1311 let lifetime = self.parse_lifetime();
1312 self.obsolete(self.last_span, ObsoleteBoxedClosure);
1313 return self.parse_ty_closure(Some(sigil), Some(lifetime));
1316 token::IDENT(..) => {
1317 if self.token_is_old_style_closure_keyword() {
1318 self.obsolete(self.last_span, ObsoleteBoxedClosure);
1319 return self.parse_ty_closure(Some(sigil), None);
1325 // other things are parsed as @/~ + a type. Note that constructs like
1326 // ~[] and ~str will be resolved during typeck to slices and so forth,
1327 // rather than boxed ptrs. But the special casing of str/vec is not
1328 // reflected in the AST type.
1329 if sigil == OwnedSigil {
1330 TyUniq(self.parse_ty(false))
1332 TyBox(self.parse_ty(false))
1336 pub fn parse_borrowed_pointee(&mut self) -> Ty_ {
1337 // look for `&'lt` or `&'foo ` and interpret `foo` as the region name:
1338 let opt_lifetime = self.parse_opt_lifetime();
1340 if self.token_is_old_style_closure_keyword() {
1341 self.obsolete(self.last_span, ObsoleteClosureType);
1342 return self.parse_ty_closure(Some(BorrowedSigil), opt_lifetime);
1345 let mt = self.parse_mt();
1346 return TyRptr(opt_lifetime, mt);
1349 pub fn is_named_argument(&mut self) -> bool {
1350 let offset = match self.token {
1351 token::BINOP(token::AND) => 1,
1353 _ if token::is_keyword(keywords::Mut, &self.token) => 1,
1357 debug!("parser is_named_argument offset:{}", offset);
1360 is_plain_ident_or_underscore(&self.token)
1361 && self.look_ahead(1, |t| *t == token::COLON)
1363 self.look_ahead(offset, |t| is_plain_ident_or_underscore(t))
1364 && self.look_ahead(offset + 1, |t| *t == token::COLON)
1368 // This version of parse arg doesn't necessarily require
1369 // identifier names.
1370 pub fn parse_arg_general(&mut self, require_name: bool) -> Arg {
1371 let pat = if require_name || self.is_named_argument() {
1372 debug!("parse_arg_general parse_pat (require_name:{:?})",
1374 let pat = self.parse_pat();
1376 self.expect(&token::COLON);
1379 debug!("parse_arg_general ident_to_pat");
1380 ast_util::ident_to_pat(ast::DUMMY_NODE_ID,
1382 special_idents::invalid)
1385 let t = self.parse_ty(false);
1390 id: ast::DUMMY_NODE_ID,
1394 // parse a single function argument
1395 pub fn parse_arg(&mut self) -> Arg {
1396 self.parse_arg_general(true)
1399 // parse an argument in a lambda header e.g. |arg, arg|
1400 pub fn parse_fn_block_arg(&mut self) -> Arg {
1401 let pat = self.parse_pat();
1402 let t = if self.eat(&token::COLON) {
1403 self.parse_ty(false)
1406 id: ast::DUMMY_NODE_ID,
1408 span: mk_sp(self.span.lo, self.span.hi),
1414 id: ast::DUMMY_NODE_ID
1418 pub fn maybe_parse_fixed_vstore(&mut self) -> Option<@ast::Expr> {
1419 if self.token == token::COMMA &&
1420 self.look_ahead(1, |t| *t == token::DOTDOT) {
1423 Some(self.parse_expr())
1429 // matches token_lit = LIT_INT | ...
1430 pub fn lit_from_token(&mut self, tok: &token::Token) -> Lit_ {
1432 token::LIT_CHAR(i) => LitChar(i),
1433 token::LIT_INT(i, it) => LitInt(i, it),
1434 token::LIT_UINT(u, ut) => LitUint(u, ut),
1435 token::LIT_INT_UNSUFFIXED(i) => LitIntUnsuffixed(i),
1436 token::LIT_FLOAT(s, ft) => {
1437 LitFloat(self.id_to_interned_str(s), ft)
1439 token::LIT_FLOAT_UNSUFFIXED(s) => {
1440 LitFloatUnsuffixed(self.id_to_interned_str(s))
1442 token::LIT_STR(s) => {
1443 LitStr(self.id_to_interned_str(s), ast::CookedStr)
1445 token::LIT_STR_RAW(s, n) => {
1446 LitStr(self.id_to_interned_str(s), ast::RawStr(n))
1448 token::LPAREN => { self.expect(&token::RPAREN); LitNil },
1449 _ => { self.unexpected_last(tok); }
1453 // matches lit = true | false | token_lit
1454 pub fn parse_lit(&mut self) -> Lit {
1455 let lo = self.span.lo;
1456 let lit = if self.eat_keyword(keywords::True) {
1458 } else if self.eat_keyword(keywords::False) {
1461 let token = self.bump_and_get();
1462 let lit = self.lit_from_token(&token);
1465 codemap::Spanned { node: lit, span: mk_sp(lo, self.last_span.hi) }
1468 // matches '-' lit | lit
1469 pub fn parse_literal_maybe_minus(&mut self) -> @Expr {
1470 let minus_lo = self.span.lo;
1471 let minus_present = self.eat(&token::BINOP(token::MINUS));
1473 let lo = self.span.lo;
1474 let literal = @self.parse_lit();
1475 let hi = self.span.hi;
1476 let expr = self.mk_expr(lo, hi, ExprLit(literal));
1479 let minus_hi = self.span.hi;
1480 let unary = self.mk_unary(UnNeg, expr);
1481 self.mk_expr(minus_lo, minus_hi, unary)
1487 /// Parses a path and optional type parameter bounds, depending on the
1488 /// mode. The `mode` parameter determines whether lifetimes, types, and/or
1489 /// bounds are permitted and whether `::` must precede type parameter
1491 pub fn parse_path(&mut self, mode: PathParsingMode) -> PathAndBounds {
1492 // Check for a whole path...
1493 let found = match self.token {
1494 INTERPOLATED(token::NtPath(_)) => Some(self.bump_and_get()),
1498 Some(INTERPOLATED(token::NtPath(~path))) => {
1499 return PathAndBounds {
1507 let lo = self.span.lo;
1508 let is_global = self.eat(&token::MOD_SEP);
1510 // Parse any number of segments and bound sets. A segment is an
1511 // identifier followed by an optional lifetime and a set of types.
1512 // A bound set is a set of type parameter bounds.
1513 let mut segments = Vec::new();
1515 // First, parse an identifier.
1516 let identifier = self.parse_ident();
1518 // Next, parse a colon and bounded type parameters, if applicable.
1519 let bound_set = if mode == LifetimeAndTypesAndBounds {
1520 self.parse_optional_ty_param_bounds()
1525 // Parse the '::' before type parameters if it's required. If
1526 // it is required and wasn't present, then we're done.
1527 if mode == LifetimeAndTypesWithColons &&
1528 !self.eat(&token::MOD_SEP) {
1529 segments.push(PathSegmentAndBoundSet {
1530 segment: ast::PathSegment {
1531 identifier: identifier,
1532 lifetimes: Vec::new(),
1533 types: OwnedSlice::empty(),
1535 bound_set: bound_set
1540 // Parse the `<` before the lifetime and types, if applicable.
1541 let (any_lifetime_or_types, lifetimes, types) = {
1542 if mode != NoTypesAllowed && self.eat(&token::LT) {
1543 let (lifetimes, types) =
1544 self.parse_generic_values_after_lt();
1545 (true, lifetimes, OwnedSlice::from_vec(types))
1547 (false, Vec::new(), OwnedSlice::empty())
1551 // Assemble and push the result.
1552 segments.push(PathSegmentAndBoundSet {
1553 segment: ast::PathSegment {
1554 identifier: identifier,
1555 lifetimes: lifetimes,
1558 bound_set: bound_set
1561 // We're done if we don't see a '::', unless the mode required
1562 // a double colon to get here in the first place.
1563 if !(mode == LifetimeAndTypesWithColons &&
1564 !any_lifetime_or_types) {
1565 if !self.eat(&token::MOD_SEP) {
1571 // Assemble the span.
1572 let span = mk_sp(lo, self.last_span.hi);
1574 // Assemble the path segments.
1575 let mut path_segments = Vec::new();
1576 let mut bounds = None;
1577 let last_segment_index = segments.len() - 1;
1578 for (i, segment_and_bounds) in segments.move_iter().enumerate() {
1579 let PathSegmentAndBoundSet {
1581 bound_set: bound_set
1582 } = segment_and_bounds;
1583 path_segments.push(segment);
1585 if bound_set.is_some() {
1586 if i != last_segment_index {
1588 "type parameter bounds are allowed only \
1589 before the last segment in a path")
1596 // Assemble the result.
1597 let path_and_bounds = PathAndBounds {
1601 segments: path_segments,
1609 /// parses 0 or 1 lifetime
1610 pub fn parse_opt_lifetime(&mut self) -> Option<ast::Lifetime> {
1612 token::LIFETIME(..) => {
1613 Some(self.parse_lifetime())
1621 /// Parses a single lifetime
1622 // matches lifetime = LIFETIME
1623 pub fn parse_lifetime(&mut self) -> ast::Lifetime {
1625 token::LIFETIME(i) => {
1626 let span = self.span;
1628 return ast::Lifetime {
1629 id: ast::DUMMY_NODE_ID,
1635 self.fatal(format!("expected a lifetime name"));
1640 // matches lifetimes = ( lifetime ) | ( lifetime , lifetimes )
1641 // actually, it matches the empty one too, but putting that in there
1642 // messes up the grammar....
1643 pub fn parse_lifetimes(&mut self) -> Vec<ast::Lifetime> {
1646 * Parses zero or more comma separated lifetimes.
1647 * Expects each lifetime to be followed by either
1648 * a comma or `>`. Used when parsing type parameter
1649 * lists, where we expect something like `<'a, 'b, T>`.
1652 let mut res = Vec::new();
1655 token::LIFETIME(_) => {
1656 res.push(self.parse_lifetime());
1664 token::COMMA => { self.bump();}
1665 token::GT => { return res; }
1666 token::BINOP(token::SHR) => { return res; }
1668 let msg = format!("expected `,` or `>` after lifetime \
1677 pub fn token_is_mutability(tok: &token::Token) -> bool {
1678 token::is_keyword(keywords::Mut, tok) ||
1679 token::is_keyword(keywords::Const, tok)
1682 // parse mutability declaration (mut/const/imm)
1683 pub fn parse_mutability(&mut self) -> Mutability {
1684 if self.eat_keyword(keywords::Mut) {
1686 } else if self.eat_keyword(keywords::Const) {
1687 self.obsolete(self.last_span, ObsoleteConstPointer);
1694 // parse ident COLON expr
1695 pub fn parse_field(&mut self) -> Field {
1696 let lo = self.span.lo;
1697 let i = self.parse_ident();
1698 let hi = self.last_span.hi;
1699 self.expect(&token::COLON);
1700 let e = self.parse_expr();
1702 ident: spanned(lo, hi, i),
1704 span: mk_sp(lo, e.span.hi),
1708 pub fn mk_expr(&mut self, lo: BytePos, hi: BytePos, node: Expr_) -> @Expr {
1710 id: ast::DUMMY_NODE_ID,
1712 span: mk_sp(lo, hi),
1716 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: @Expr) -> ast::Expr_ {
1717 ExprUnary(unop, expr)
1720 pub fn mk_binary(&mut self, binop: ast::BinOp, lhs: @Expr, rhs: @Expr) -> ast::Expr_ {
1721 ExprBinary(binop, lhs, rhs)
1724 pub fn mk_call(&mut self, f: @Expr, args: Vec<@Expr> ) -> ast::Expr_ {
1728 fn mk_method_call(&mut self, ident: Ident, tps: Vec<P<Ty>> , args: Vec<@Expr> ) -> ast::Expr_ {
1729 ExprMethodCall(ident, tps, args)
1732 pub fn mk_index(&mut self, expr: @Expr, idx: @Expr) -> ast::Expr_ {
1733 ExprIndex(expr, idx)
1736 pub fn mk_field(&mut self, expr: @Expr, ident: Ident, tys: Vec<P<Ty>> ) -> ast::Expr_ {
1737 ExprField(expr, ident, tys)
1740 pub fn mk_assign_op(&mut self, binop: ast::BinOp, lhs: @Expr, rhs: @Expr) -> ast::Expr_ {
1741 ExprAssignOp(binop, lhs, rhs)
1744 pub fn mk_mac_expr(&mut self, lo: BytePos, hi: BytePos, m: Mac_) -> @Expr {
1746 id: ast::DUMMY_NODE_ID,
1747 node: ExprMac(codemap::Spanned {node: m, span: mk_sp(lo, hi)}),
1748 span: mk_sp(lo, hi),
1752 pub fn mk_lit_u32(&mut self, i: u32) -> @Expr {
1753 let span = &self.span;
1754 let lv_lit = @codemap::Spanned {
1755 node: LitUint(i as u64, TyU32),
1760 id: ast::DUMMY_NODE_ID,
1761 node: ExprLit(lv_lit),
1766 // at the bottom (top?) of the precedence hierarchy,
1767 // parse things like parenthesized exprs,
1768 // macros, return, etc.
1769 pub fn parse_bottom_expr(&mut self) -> @Expr {
1770 maybe_whole_expr!(self);
1772 let lo = self.span.lo;
1773 let mut hi = self.span.hi;
1777 if self.token == token::LPAREN {
1779 // (e) is parenthesized e
1780 // (e,) is a tuple with only one field, e
1781 let mut trailing_comma = false;
1782 if self.token == token::RPAREN {
1785 let lit = @spanned(lo, hi, LitNil);
1786 return self.mk_expr(lo, hi, ExprLit(lit));
1788 let mut es = vec!(self.parse_expr());
1789 self.commit_expr(*es.last().unwrap(), &[], &[token::COMMA, token::RPAREN]);
1790 while self.token == token::COMMA {
1792 if self.token != token::RPAREN {
1793 es.push(self.parse_expr());
1794 self.commit_expr(*es.last().unwrap(), &[], &[token::COMMA, token::RPAREN]);
1797 trailing_comma = true;
1801 self.commit_expr_expecting(*es.last().unwrap(), token::RPAREN);
1803 return if es.len() == 1 && !trailing_comma {
1804 self.mk_expr(lo, hi, ExprParen(*es.get(0)))
1807 self.mk_expr(lo, hi, ExprTup(es))
1809 } else if self.token == token::LBRACE {
1811 let blk = self.parse_block_tail(lo, DefaultBlock);
1812 return self.mk_expr(blk.span.lo, blk.span.hi,
1814 } else if token::is_bar(&self.token) {
1815 return self.parse_lambda_expr();
1816 } else if self.eat_keyword(keywords::Proc) {
1817 let decl = self.parse_proc_decl();
1818 let body = self.parse_expr();
1819 let fakeblock = P(ast::Block {
1820 view_items: Vec::new(),
1823 id: ast::DUMMY_NODE_ID,
1824 rules: DefaultBlock,
1828 return self.mk_expr(lo, body.span.hi, ExprProc(decl, fakeblock));
1829 } else if self.eat_keyword(keywords::Self) {
1830 let path = ast_util::ident_to_path(mk_sp(lo, hi), special_idents::self_);
1831 ex = ExprPath(path);
1832 hi = self.last_span.hi;
1833 } else if self.eat_keyword(keywords::If) {
1834 return self.parse_if_expr();
1835 } else if self.eat_keyword(keywords::For) {
1836 return self.parse_for_expr(None);
1837 } else if self.eat_keyword(keywords::While) {
1838 return self.parse_while_expr();
1839 } else if Parser::token_is_lifetime(&self.token) {
1840 let lifetime = self.get_lifetime();
1842 self.expect(&token::COLON);
1843 if self.eat_keyword(keywords::For) {
1844 return self.parse_for_expr(Some(lifetime))
1845 } else if self.eat_keyword(keywords::Loop) {
1846 return self.parse_loop_expr(Some(lifetime))
1848 self.fatal("expected `for` or `loop` after a label")
1850 } else if self.eat_keyword(keywords::Loop) {
1851 return self.parse_loop_expr(None);
1852 } else if self.eat_keyword(keywords::Continue) {
1853 let lo = self.span.lo;
1854 let ex = if Parser::token_is_lifetime(&self.token) {
1855 let lifetime = self.get_lifetime();
1857 ExprAgain(Some(lifetime))
1861 let hi = self.span.hi;
1862 return self.mk_expr(lo, hi, ex);
1863 } else if self.eat_keyword(keywords::Match) {
1864 return self.parse_match_expr();
1865 } else if self.eat_keyword(keywords::Unsafe) {
1866 return self.parse_block_expr(lo, UnsafeBlock(ast::UserProvided));
1867 } else if self.token == token::LBRACKET {
1869 let mutbl = MutImmutable;
1871 if self.token == token::RBRACKET {
1874 ex = ExprVec(Vec::new(), mutbl);
1877 let first_expr = self.parse_expr();
1878 if self.token == token::COMMA &&
1879 self.look_ahead(1, |t| *t == token::DOTDOT) {
1880 // Repeating vector syntax: [ 0, ..512 ]
1883 let count = self.parse_expr();
1884 self.expect(&token::RBRACKET);
1885 ex = ExprRepeat(first_expr, count, mutbl);
1886 } else if self.token == token::COMMA {
1887 // Vector with two or more elements.
1889 let remaining_exprs = self.parse_seq_to_end(
1891 seq_sep_trailing_allowed(token::COMMA),
1894 let mut exprs = vec!(first_expr);
1895 exprs.push_all_move(remaining_exprs);
1896 ex = ExprVec(exprs, mutbl);
1898 // Vector with one element.
1899 self.expect(&token::RBRACKET);
1900 ex = ExprVec(vec!(first_expr), mutbl);
1903 hi = self.last_span.hi;
1904 } else if self.eat_keyword(keywords::Return) {
1905 // RETURN expression
1906 if can_begin_expr(&self.token) {
1907 let e = self.parse_expr();
1909 ex = ExprRet(Some(e));
1910 } else { ex = ExprRet(None); }
1911 } else if self.eat_keyword(keywords::Break) {
1913 if Parser::token_is_lifetime(&self.token) {
1914 let lifetime = self.get_lifetime();
1916 ex = ExprBreak(Some(lifetime));
1918 ex = ExprBreak(None);
1921 } else if self.token == token::MOD_SEP ||
1922 is_ident(&self.token) && !self.is_keyword(keywords::True) &&
1923 !self.is_keyword(keywords::False) {
1924 let pth = self.parse_path(LifetimeAndTypesWithColons).path;
1926 // `!`, as an operator, is prefix, so we know this isn't that
1927 if self.token == token::NOT {
1928 // MACRO INVOCATION expression
1931 token::LPAREN | token::LBRACE => {}
1932 _ => self.fatal("expected open delimiter")
1935 let ket = token::flip_delimiter(&self.token);
1938 let tts = self.parse_seq_to_end(&ket,
1940 |p| p.parse_token_tree());
1941 let hi = self.span.hi;
1943 return self.mk_mac_expr(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT));
1944 } else if self.token == token::LBRACE {
1945 // This might be a struct literal.
1946 if self.looking_at_struct_literal() {
1947 // It's a struct literal.
1949 let mut fields = Vec::new();
1950 let mut base = None;
1952 while self.token != token::RBRACE {
1953 if self.eat(&token::DOTDOT) {
1954 base = Some(self.parse_expr());
1958 fields.push(self.parse_field());
1959 self.commit_expr(fields.last().unwrap().expr,
1960 &[token::COMMA], &[token::RBRACE]);
1964 self.expect(&token::RBRACE);
1965 ex = ExprStruct(pth, fields, base);
1966 return self.mk_expr(lo, hi, ex);
1973 // other literal expression
1974 let lit = self.parse_lit();
1979 return self.mk_expr(lo, hi, ex);
1982 // parse a block or unsafe block
1983 pub fn parse_block_expr(&mut self, lo: BytePos, blk_mode: BlockCheckMode)
1985 self.expect(&token::LBRACE);
1986 let blk = self.parse_block_tail(lo, blk_mode);
1987 return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk));
1990 // parse a.b or a(13) or a[4] or just a
1991 pub fn parse_dot_or_call_expr(&mut self) -> @Expr {
1992 let b = self.parse_bottom_expr();
1993 self.parse_dot_or_call_expr_with(b)
1996 pub fn parse_dot_or_call_expr_with(&mut self, e0: @Expr) -> @Expr {
2002 if self.eat(&token::DOT) {
2004 token::IDENT(i, _) => {
2007 let (_, tys) = if self.eat(&token::MOD_SEP) {
2008 self.expect(&token::LT);
2009 self.parse_generic_values_after_lt()
2011 (Vec::new(), Vec::new())
2014 // expr.f() method call
2017 let mut es = self.parse_unspanned_seq(
2020 seq_sep_trailing_disallowed(token::COMMA),
2023 hi = self.last_span.hi;
2026 let nd = self.mk_method_call(i, tys, es);
2027 e = self.mk_expr(lo, hi, nd);
2030 let field = self.mk_field(e, i, tys);
2031 e = self.mk_expr(lo, hi, field)
2035 _ => self.unexpected()
2039 if self.expr_is_complete(e) { break; }
2043 let es = self.parse_unspanned_seq(
2046 seq_sep_trailing_allowed(token::COMMA),
2049 hi = self.last_span.hi;
2051 let nd = self.mk_call(e, es);
2052 e = self.mk_expr(lo, hi, nd);
2056 token::LBRACKET => {
2058 let ix = self.parse_expr();
2060 self.commit_expr_expecting(ix, token::RBRACKET);
2061 let index = self.mk_index(e, ix);
2062 e = self.mk_expr(lo, hi, index)
2071 // parse an optional separator followed by a kleene-style
2072 // repetition token (+ or *).
2073 pub fn parse_sep_and_zerok(&mut self) -> (Option<token::Token>, bool) {
2074 fn parse_zerok(parser: &mut Parser) -> Option<bool> {
2075 match parser.token {
2076 token::BINOP(token::STAR) | token::BINOP(token::PLUS) => {
2077 let zerok = parser.token == token::BINOP(token::STAR);
2085 match parse_zerok(self) {
2086 Some(zerok) => return (None, zerok),
2090 let separator = self.bump_and_get();
2091 match parse_zerok(self) {
2092 Some(zerok) => (Some(separator), zerok),
2093 None => self.fatal("expected `*` or `+`")
2097 // parse a single token tree from the input.
2098 pub fn parse_token_tree(&mut self) -> TokenTree {
2099 // FIXME #6994: currently, this is too eager. It
2100 // parses token trees but also identifies TTSeq's
2101 // and TTNonterminal's; it's too early to know yet
2102 // whether something will be a nonterminal or a seq
2104 maybe_whole!(deref self, NtTT);
2106 // this is the fall-through for the 'match' below.
2107 // invariants: the current token is not a left-delimiter,
2108 // not an EOF, and not the desired right-delimiter (if
2109 // it were, parse_seq_to_before_end would have prevented
2110 // reaching this point.
2111 fn parse_non_delim_tt_tok(p: &mut Parser) -> TokenTree {
2112 maybe_whole!(deref p, NtTT);
2114 token::RPAREN | token::RBRACE | token::RBRACKET => {
2115 // This is a conservative error: only report the last unclosed delimiter. The
2116 // previous unclosed delimiters could actually be closed! The parser just hasn't
2117 // gotten to them yet.
2118 match p.open_braces.last() {
2120 Some(&sp) => p.span_note(sp, "unclosed delimiter"),
2122 let token_str = p.this_token_to_str();
2123 p.fatal(format!("incorrect close delimiter: `{}`",
2126 /* we ought to allow different depths of unquotation */
2127 token::DOLLAR if p.quote_depth > 0u => {
2131 if p.token == token::LPAREN {
2132 let seq = p.parse_seq(
2136 |p| p.parse_token_tree()
2138 let (s, z) = p.parse_sep_and_zerok();
2139 let seq = match seq {
2140 Spanned { node, .. } => node,
2142 TTSeq(mk_sp(sp.lo, p.span.hi), @seq, s, z)
2144 TTNonterminal(sp, p.parse_ident())
2153 // turn the next token into a TTTok:
2154 fn parse_any_tt_tok(p: &mut Parser) -> TokenTree {
2155 TTTok(p.span, p.bump_and_get())
2160 let open_braces = self.open_braces.clone();
2161 for sp in open_braces.iter() {
2162 self.span_note(*sp, "Did you mean to close this delimiter?");
2164 // There shouldn't really be a span, but it's easier for the test runner
2165 // if we give it one
2166 self.fatal("this file contains an un-closed delimiter ");
2168 token::LPAREN | token::LBRACE | token::LBRACKET => {
2169 let close_delim = token::flip_delimiter(&self.token);
2171 // Parse the open delimiter.
2172 self.open_braces.push(self.span);
2173 let mut result = vec!(parse_any_tt_tok(self));
2176 self.parse_seq_to_before_end(&close_delim,
2178 |p| p.parse_token_tree());
2179 result.push_all_move(trees);
2181 // Parse the close delimiter.
2182 result.push(parse_any_tt_tok(self));
2183 self.open_braces.pop().unwrap();
2187 _ => parse_non_delim_tt_tok(self)
2191 // parse a stream of tokens into a list of TokenTree's,
2193 pub fn parse_all_token_trees(&mut self) -> Vec<TokenTree> {
2194 let mut tts = Vec::new();
2195 while self.token != token::EOF {
2196 tts.push(self.parse_token_tree());
2201 pub fn parse_matchers(&mut self) -> Vec<Matcher> {
2202 // unification of Matcher's and TokenTree's would vastly improve
2203 // the interpolation of Matcher's
2204 maybe_whole!(self, NtMatchers);
2205 let name_idx = @Cell::new(0u);
2207 token::LBRACE | token::LPAREN | token::LBRACKET => {
2208 let other_delimiter = token::flip_delimiter(&self.token);
2210 self.parse_matcher_subseq_upto(name_idx, &other_delimiter)
2212 _ => self.fatal("expected open delimiter")
2216 // This goofy function is necessary to correctly match parens in Matcher's.
2217 // Otherwise, `$( ( )` would be a valid Matcher, and `$( () )` would be
2218 // invalid. It's similar to common::parse_seq.
2219 pub fn parse_matcher_subseq_upto(&mut self,
2220 name_idx: @Cell<uint>,
2223 let mut ret_val = Vec::new();
2224 let mut lparens = 0u;
2226 while self.token != *ket || lparens > 0u {
2227 if self.token == token::LPAREN { lparens += 1u; }
2228 if self.token == token::RPAREN { lparens -= 1u; }
2229 ret_val.push(self.parse_matcher(name_idx));
2237 pub fn parse_matcher(&mut self, name_idx: @Cell<uint>) -> Matcher {
2238 let lo = self.span.lo;
2240 let m = if self.token == token::DOLLAR {
2242 if self.token == token::LPAREN {
2243 let name_idx_lo = name_idx.get();
2245 let ms = self.parse_matcher_subseq_upto(name_idx,
2248 self.fatal("repetition body must be nonempty");
2250 let (sep, zerok) = self.parse_sep_and_zerok();
2251 MatchSeq(ms, sep, zerok, name_idx_lo, name_idx.get())
2253 let bound_to = self.parse_ident();
2254 self.expect(&token::COLON);
2255 let nt_name = self.parse_ident();
2256 let m = MatchNonterminal(bound_to, nt_name, name_idx.get());
2257 name_idx.set(name_idx.get() + 1u);
2261 MatchTok(self.bump_and_get())
2264 return spanned(lo, self.span.hi, m);
2267 // parse a prefix-operator expr
2268 pub fn parse_prefix_expr(&mut self) -> @Expr {
2269 let lo = self.span.lo;
2276 let e = self.parse_prefix_expr();
2278 ex = self.mk_unary(UnNot, e);
2280 token::BINOP(b) => {
2284 let e = self.parse_prefix_expr();
2286 ex = self.mk_unary(UnNeg, e);
2290 let e = self.parse_prefix_expr();
2292 ex = self.mk_unary(UnDeref, e);
2296 let _lt = self.parse_opt_lifetime();
2297 let m = self.parse_mutability();
2298 let e = self.parse_prefix_expr();
2300 // HACK: turn &[...] into a &-vec
2302 ExprVec(..) if m == MutImmutable => {
2303 ExprVstore(e, ExprVstoreSlice)
2305 ExprLit(lit) if lit_is_str(lit) && m == MutImmutable => {
2306 ExprVstore(e, ExprVstoreSlice)
2308 ExprVec(..) if m == MutMutable => {
2309 ExprVstore(e, ExprVstoreMutSlice)
2311 _ => ExprAddrOf(m, e)
2314 _ => return self.parse_dot_or_call_expr()
2319 let e = self.parse_prefix_expr();
2321 // HACK: pretending @[] is a (removed) @-vec
2325 self.obsolete(e.span, ObsoleteManagedVec);
2326 // the above error means that no-one will know we're
2327 // lying... hopefully.
2328 ExprVstore(e, ExprVstoreUniq)
2330 ExprLit(lit) if lit_is_str(lit) => {
2331 self.obsolete(self.last_span, ObsoleteManagedString);
2332 ExprVstore(e, ExprVstoreUniq)
2334 _ => self.mk_unary(UnBox, e)
2340 let e = self.parse_prefix_expr();
2342 // HACK: turn ~[...] into a ~-vec
2344 ExprVec(..) | ExprRepeat(..) => ExprVstore(e, ExprVstoreUniq),
2345 ExprLit(lit) if lit_is_str(lit) => {
2346 ExprVstore(e, ExprVstoreUniq)
2348 _ => self.mk_unary(UnUniq, e)
2351 token::IDENT(_, _) if self.is_keyword(keywords::Box) => {
2354 // Check for a place: `box(PLACE) EXPR`.
2355 if self.eat(&token::LPAREN) {
2356 // Support `box() EXPR` as the default.
2357 if !self.eat(&token::RPAREN) {
2358 let place = self.parse_expr();
2359 self.expect(&token::RPAREN);
2360 let subexpression = self.parse_prefix_expr();
2361 hi = subexpression.span.hi;
2362 ex = ExprBox(place, subexpression);
2363 return self.mk_expr(lo, hi, ex);
2367 // Otherwise, we use the unique pointer default.
2368 let subexpression = self.parse_prefix_expr();
2369 hi = subexpression.span.hi;
2370 // HACK: turn `box [...]` into a boxed-vec
2371 ex = match subexpression.node {
2372 ExprVec(..) | ExprRepeat(..) => {
2373 ExprVstore(subexpression, ExprVstoreUniq)
2375 ExprLit(lit) if lit_is_str(lit) => {
2376 ExprVstore(subexpression, ExprVstoreUniq)
2378 _ => self.mk_unary(UnUniq, subexpression)
2381 _ => return self.parse_dot_or_call_expr()
2383 return self.mk_expr(lo, hi, ex);
2386 // parse an expression of binops
2387 pub fn parse_binops(&mut self) -> @Expr {
2388 let prefix_expr = self.parse_prefix_expr();
2389 self.parse_more_binops(prefix_expr, 0)
2392 // parse an expression of binops of at least min_prec precedence
2393 pub fn parse_more_binops(&mut self, lhs: @Expr, min_prec: uint) -> @Expr {
2394 if self.expr_is_complete(lhs) { return lhs; }
2396 // Prevent dynamic borrow errors later on by limiting the
2397 // scope of the borrows.
2399 let token: &token::Token = &self.token;
2400 let restriction: &restriction = &self.restriction;
2401 match (token, restriction) {
2402 (&token::BINOP(token::OR), &RESTRICT_NO_BAR_OP) => return lhs,
2403 (&token::BINOP(token::OR),
2404 &RESTRICT_NO_BAR_OR_DOUBLEBAR_OP) => return lhs,
2405 (&token::OROR, &RESTRICT_NO_BAR_OR_DOUBLEBAR_OP) => return lhs,
2410 let cur_opt = token_to_binop(&self.token);
2413 let cur_prec = operator_prec(cur_op);
2414 if cur_prec > min_prec {
2416 let expr = self.parse_prefix_expr();
2417 let rhs = self.parse_more_binops(expr, cur_prec);
2418 let binary = self.mk_binary(cur_op, lhs, rhs);
2419 let bin = self.mk_expr(lhs.span.lo, rhs.span.hi, binary);
2420 self.parse_more_binops(bin, min_prec)
2426 if as_prec > min_prec && self.eat_keyword(keywords::As) {
2427 let rhs = self.parse_ty(true);
2428 let _as = self.mk_expr(lhs.span.lo,
2430 ExprCast(lhs, rhs));
2431 self.parse_more_binops(_as, min_prec)
2439 // parse an assignment expression....
2440 // actually, this seems to be the main entry point for
2441 // parsing an arbitrary expression.
2442 pub fn parse_assign_expr(&mut self) -> @Expr {
2443 let lo = self.span.lo;
2444 let lhs = self.parse_binops();
2448 let rhs = self.parse_expr();
2449 self.mk_expr(lo, rhs.span.hi, ExprAssign(lhs, rhs))
2451 token::BINOPEQ(op) => {
2453 let rhs = self.parse_expr();
2454 let aop = match op {
2455 token::PLUS => BiAdd,
2456 token::MINUS => BiSub,
2457 token::STAR => BiMul,
2458 token::SLASH => BiDiv,
2459 token::PERCENT => BiRem,
2460 token::CARET => BiBitXor,
2461 token::AND => BiBitAnd,
2462 token::OR => BiBitOr,
2463 token::SHL => BiShl,
2466 let assign_op = self.mk_assign_op(aop, lhs, rhs);
2467 self.mk_expr(lo, rhs.span.hi, assign_op)
2470 self.obsolete(self.span, ObsoleteSwap);
2472 // Ignore what we get, this is an error anyway
2474 self.mk_expr(lo, self.span.hi, ExprBreak(None))
2482 // parse an 'if' expression ('if' token already eaten)
2483 pub fn parse_if_expr(&mut self) -> @Expr {
2484 let lo = self.last_span.lo;
2485 let cond = self.parse_expr();
2486 let thn = self.parse_block();
2487 let mut els: Option<@Expr> = None;
2488 let mut hi = thn.span.hi;
2489 if self.eat_keyword(keywords::Else) {
2490 let elexpr = self.parse_else_expr();
2492 hi = elexpr.span.hi;
2494 self.mk_expr(lo, hi, ExprIf(cond, thn, els))
2497 // `|args| { ... }` or `{ ...}` like in `do` expressions
2498 pub fn parse_lambda_block_expr(&mut self) -> @Expr {
2499 self.parse_lambda_expr_(
2502 token::BINOP(token::OR) | token::OROR => {
2503 p.parse_fn_block_decl()
2506 // No argument list - `do foo {`
2510 id: ast::DUMMY_NODE_ID,
2521 let blk = p.parse_block();
2522 p.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk))
2527 pub fn parse_lambda_expr(&mut self) -> @Expr {
2528 self.parse_lambda_expr_(|p| p.parse_fn_block_decl(),
2532 // parse something of the form |args| expr
2533 // this is used both in parsing a lambda expr
2534 // and in parsing a block expr as e.g. in for...
2535 pub fn parse_lambda_expr_(&mut self,
2536 parse_decl: |&mut Parser| -> P<FnDecl>,
2537 parse_body: |&mut Parser| -> @Expr)
2539 let lo = self.span.lo;
2540 let decl = parse_decl(self);
2541 let body = parse_body(self);
2542 let fakeblock = P(ast::Block {
2543 view_items: Vec::new(),
2546 id: ast::DUMMY_NODE_ID,
2547 rules: DefaultBlock,
2551 return self.mk_expr(lo, body.span.hi, ExprFnBlock(decl, fakeblock));
2554 pub fn parse_else_expr(&mut self) -> @Expr {
2555 if self.eat_keyword(keywords::If) {
2556 return self.parse_if_expr();
2558 let blk = self.parse_block();
2559 return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk));
2563 // parse a 'for' .. 'in' expression ('for' token already eaten)
2564 pub fn parse_for_expr(&mut self, opt_ident: Option<ast::Ident>) -> @Expr {
2565 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
2567 let lo = self.last_span.lo;
2568 let pat = self.parse_pat();
2569 self.expect_keyword(keywords::In);
2570 let expr = self.parse_expr();
2571 let loop_block = self.parse_block();
2572 let hi = self.span.hi;
2574 self.mk_expr(lo, hi, ExprForLoop(pat, expr, loop_block, opt_ident))
2577 pub fn parse_while_expr(&mut self) -> @Expr {
2578 let lo = self.last_span.lo;
2579 let cond = self.parse_expr();
2580 let body = self.parse_block();
2581 let hi = body.span.hi;
2582 return self.mk_expr(lo, hi, ExprWhile(cond, body));
2585 pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::Ident>) -> @Expr {
2586 // loop headers look like 'loop {' or 'loop unsafe {'
2587 let is_loop_header =
2588 self.token == token::LBRACE
2589 || (is_ident(&self.token)
2590 && self.look_ahead(1, |t| *t == token::LBRACE));
2593 // This is a loop body
2594 let lo = self.last_span.lo;
2595 let body = self.parse_block();
2596 let hi = body.span.hi;
2597 return self.mk_expr(lo, hi, ExprLoop(body, opt_ident));
2599 // This is an obsolete 'continue' expression
2600 if opt_ident.is_some() {
2601 self.span_err(self.last_span,
2602 "a label may not be used with a `loop` expression");
2605 self.obsolete(self.last_span, ObsoleteLoopAsContinue);
2606 let lo = self.span.lo;
2607 let ex = if Parser::token_is_lifetime(&self.token) {
2608 let lifetime = self.get_lifetime();
2610 ExprAgain(Some(lifetime))
2614 let hi = self.span.hi;
2615 return self.mk_expr(lo, hi, ex);
2619 // For distingishing between struct literals and blocks
2620 fn looking_at_struct_literal(&mut self) -> bool {
2621 self.token == token::LBRACE &&
2622 ((self.look_ahead(1, |t| token::is_plain_ident(t)) &&
2623 self.look_ahead(2, |t| *t == token::COLON))
2624 || self.look_ahead(1, |t| *t == token::DOTDOT))
2627 fn parse_match_expr(&mut self) -> @Expr {
2628 let lo = self.last_span.lo;
2629 let discriminant = self.parse_expr();
2630 self.commit_expr_expecting(discriminant, token::LBRACE);
2631 let mut arms: Vec<Arm> = Vec::new();
2632 while self.token != token::RBRACE {
2633 let pats = self.parse_pats();
2634 let mut guard = None;
2635 if self.eat_keyword(keywords::If) {
2636 guard = Some(self.parse_expr());
2638 self.expect(&token::FAT_ARROW);
2639 let expr = self.parse_expr_res(RESTRICT_STMT_EXPR);
2642 !classify::expr_is_simple_block(expr)
2643 && self.token != token::RBRACE;
2646 self.commit_expr(expr, &[token::COMMA], &[token::RBRACE]);
2648 self.eat(&token::COMMA);
2651 arms.push(ast::Arm { pats: pats, guard: guard, body: expr });
2653 let hi = self.span.hi;
2655 return self.mk_expr(lo, hi, ExprMatch(discriminant, arms));
2658 // parse an expression
2659 pub fn parse_expr(&mut self) -> @Expr {
2660 return self.parse_expr_res(UNRESTRICTED);
2663 // parse an expression, subject to the given restriction
2664 fn parse_expr_res(&mut self, r: restriction) -> @Expr {
2665 let old = self.restriction;
2666 self.restriction = r;
2667 let e = self.parse_assign_expr();
2668 self.restriction = old;
2672 // parse the RHS of a local variable declaration (e.g. '= 14;')
2673 fn parse_initializer(&mut self) -> Option<@Expr> {
2674 if self.token == token::EQ {
2676 Some(self.parse_expr())
2682 // parse patterns, separated by '|' s
2683 fn parse_pats(&mut self) -> Vec<@Pat> {
2684 let mut pats = Vec::new();
2686 pats.push(self.parse_pat());
2687 if self.token == token::BINOP(token::OR) { self.bump(); }
2688 else { return pats; }
2692 fn parse_pat_vec_elements(
2694 ) -> (Vec<@Pat> , Option<@Pat>, Vec<@Pat> ) {
2695 let mut before = Vec::new();
2696 let mut slice = None;
2697 let mut after = Vec::new();
2698 let mut first = true;
2699 let mut before_slice = true;
2701 while self.token != token::RBRACKET {
2702 if first { first = false; }
2703 else { self.expect(&token::COMMA); }
2705 let mut is_slice = false;
2707 if self.token == token::DOTDOT {
2710 before_slice = false;
2715 if self.token == token::COMMA || self.token == token::RBRACKET {
2716 slice = Some(@ast::Pat {
2717 id: ast::DUMMY_NODE_ID,
2722 let subpat = self.parse_pat();
2724 ast::Pat { id, node: PatWild, span } => {
2725 self.obsolete(self.span, ObsoleteVecDotDotWildcard);
2726 slice = Some(@ast::Pat {
2732 ast::Pat { node: PatIdent(_, _, _), .. } => {
2733 slice = Some(subpat);
2735 ast::Pat { span, .. } => self.span_fatal(
2736 span, "expected an identifier or nothing"
2741 let subpat = self.parse_pat();
2743 before.push(subpat);
2750 (before, slice, after)
2753 // parse the fields of a struct-like pattern
2754 fn parse_pat_fields(&mut self) -> (Vec<ast::FieldPat> , bool) {
2755 let mut fields = Vec::new();
2756 let mut etc = false;
2757 let mut first = true;
2758 while self.token != token::RBRACE {
2762 self.expect(&token::COMMA);
2763 // accept trailing commas
2764 if self.token == token::RBRACE { break }
2767 etc = self.token == token::UNDERSCORE || self.token == token::DOTDOT;
2768 if self.token == token::UNDERSCORE {
2769 self.obsolete(self.span, ObsoleteStructWildcard);
2773 if self.token != token::RBRACE {
2774 let token_str = self.this_token_to_str();
2775 self.fatal(format!("expected `\\}`, found `{}`",
2782 let bind_type = if self.eat_keyword(keywords::Mut) {
2783 BindByValue(MutMutable)
2784 } else if self.eat_keyword(keywords::Ref) {
2785 BindByRef(self.parse_mutability())
2787 BindByValue(MutImmutable)
2790 let fieldname = self.parse_ident();
2792 let subpat = if self.token == token::COLON {
2794 BindByRef(..) | BindByValue(MutMutable) => {
2795 let token_str = self.this_token_to_str();
2796 self.fatal(format!("unexpected `{}`", token_str))
2804 let fieldpath = ast_util::ident_to_path(self.last_span,
2807 id: ast::DUMMY_NODE_ID,
2808 node: PatIdent(bind_type, fieldpath, None),
2809 span: self.last_span
2812 fields.push(ast::FieldPat { ident: fieldname, pat: subpat });
2814 return (fields, etc);
2818 pub fn parse_pat(&mut self) -> @Pat {
2819 maybe_whole!(self, NtPat);
2821 let lo = self.span.lo;
2826 token::UNDERSCORE => {
2829 hi = self.last_span.hi;
2831 id: ast::DUMMY_NODE_ID,
2839 let sub = self.parse_pat();
2840 self.obsolete(self.span, ObsoleteManagedPattern);
2841 let hi = self.last_span.hi;
2843 id: ast::DUMMY_NODE_ID,
2851 let sub = self.parse_pat();
2853 hi = self.last_span.hi;
2855 id: ast::DUMMY_NODE_ID,
2860 token::BINOP(token::AND) => {
2862 let lo = self.span.lo;
2864 let sub = self.parse_pat();
2866 // HACK: parse &"..." as a literal of a borrowed str
2867 pat = match sub.node {
2870 ExprLit(lit) if lit_is_str(lit) => {
2872 id: ast::DUMMY_NODE_ID,
2873 node: ExprVstore(e, ExprVstoreSlice),
2878 _ => PatRegion(sub),
2881 _ => PatRegion(sub),
2883 hi = self.last_span.hi;
2885 id: ast::DUMMY_NODE_ID,
2891 // parse (pat,pat,pat,...) as tuple
2893 if self.token == token::RPAREN {
2896 let lit = @codemap::Spanned {
2898 span: mk_sp(lo, hi)};
2899 let expr = self.mk_expr(lo, hi, ExprLit(lit));
2902 let mut fields = vec!(self.parse_pat());
2903 if self.look_ahead(1, |t| *t != token::RPAREN) {
2904 while self.token == token::COMMA {
2906 if self.token == token::RPAREN { break; }
2907 fields.push(self.parse_pat());
2910 if fields.len() == 1 { self.expect(&token::COMMA); }
2911 self.expect(&token::RPAREN);
2912 pat = PatTup(fields);
2914 hi = self.last_span.hi;
2916 id: ast::DUMMY_NODE_ID,
2921 token::LBRACKET => {
2922 // parse [pat,pat,...] as vector pattern
2924 let (before, slice, after) =
2925 self.parse_pat_vec_elements();
2927 self.expect(&token::RBRACKET);
2928 pat = ast::PatVec(before, slice, after);
2929 hi = self.last_span.hi;
2931 id: ast::DUMMY_NODE_ID,
2939 if !is_ident_or_path(&self.token)
2940 || self.is_keyword(keywords::True)
2941 || self.is_keyword(keywords::False) {
2942 // Parse an expression pattern or exp .. exp.
2944 // These expressions are limited to literals (possibly
2945 // preceded by unary-minus) or identifiers.
2946 let val = self.parse_literal_maybe_minus();
2947 if self.eat(&token::DOTDOT) {
2948 let end = if is_ident_or_path(&self.token) {
2949 let path = self.parse_path(LifetimeAndTypesWithColons)
2951 let hi = self.span.hi;
2952 self.mk_expr(lo, hi, ExprPath(path))
2954 self.parse_literal_maybe_minus()
2956 pat = PatRange(val, end);
2960 } else if self.eat_keyword(keywords::Mut) {
2961 pat = self.parse_pat_ident(BindByValue(MutMutable));
2962 } else if self.eat_keyword(keywords::Ref) {
2964 let mutbl = self.parse_mutability();
2965 pat = self.parse_pat_ident(BindByRef(mutbl));
2967 let can_be_enum_or_struct = self.look_ahead(1, |t| {
2969 token::LPAREN | token::LBRACKET | token::LT |
2970 token::LBRACE | token::MOD_SEP => true,
2975 if self.look_ahead(1, |t| *t == token::DOTDOT) {
2976 let start = self.parse_expr_res(RESTRICT_NO_BAR_OP);
2977 self.eat(&token::DOTDOT);
2978 let end = self.parse_expr_res(RESTRICT_NO_BAR_OP);
2979 pat = PatRange(start, end);
2980 } else if is_plain_ident(&self.token) && !can_be_enum_or_struct {
2981 let name = self.parse_path(NoTypesAllowed).path;
2983 if self.eat(&token::AT) {
2985 sub = Some(self.parse_pat());
2990 pat = PatIdent(BindByValue(MutImmutable), name, sub);
2992 // parse an enum pat
2993 let enum_path = self.parse_path(LifetimeAndTypesWithColons)
2999 self.parse_pat_fields();
3001 pat = PatStruct(enum_path, fields, etc);
3004 let mut args: Vec<@Pat> = Vec::new();
3007 let is_star = self.look_ahead(1, |t| {
3009 token::BINOP(token::STAR) => true,
3013 let is_dotdot = self.look_ahead(1, |t| {
3015 token::DOTDOT => true,
3019 if is_star | is_dotdot {
3020 // This is a "top constructor only" pat
3023 self.obsolete(self.span, ObsoleteEnumWildcard);
3026 self.expect(&token::RPAREN);
3027 pat = PatEnum(enum_path, None);
3029 args = self.parse_enum_variant_seq(
3032 seq_sep_trailing_disallowed(token::COMMA),
3035 pat = PatEnum(enum_path, Some(args));
3039 if enum_path.segments.len() == 1 {
3040 // it could still be either an enum
3041 // or an identifier pattern, resolve
3042 // will sort it out:
3043 pat = PatIdent(BindByValue(MutImmutable),
3047 pat = PatEnum(enum_path, Some(args));
3055 hi = self.last_span.hi;
3057 id: ast::DUMMY_NODE_ID,
3059 span: mk_sp(lo, hi),
3063 // parse ident or ident @ pat
3064 // used by the copy foo and ref foo patterns to give a good
3065 // error message when parsing mistakes like ref foo(a,b)
3066 fn parse_pat_ident(&mut self,
3067 binding_mode: ast::BindingMode)
3069 if !is_plain_ident(&self.token) {
3070 self.span_fatal(self.last_span,
3071 "expected identifier, found path");
3073 // why a path here, and not just an identifier?
3074 let name = self.parse_path(NoTypesAllowed).path;
3075 let sub = if self.eat(&token::AT) {
3076 Some(self.parse_pat())
3081 // just to be friendly, if they write something like
3083 // we end up here with ( as the current token. This shortly
3084 // leads to a parse error. Note that if there is no explicit
3085 // binding mode then we do not end up here, because the lookahead
3086 // will direct us over to parse_enum_variant()
3087 if self.token == token::LPAREN {
3090 "expected identifier, found enum pattern");
3093 PatIdent(binding_mode, name, sub)
3096 // parse a local variable declaration
3097 fn parse_local(&mut self) -> @Local {
3098 let lo = self.span.lo;
3099 let pat = self.parse_pat();
3102 id: ast::DUMMY_NODE_ID,
3104 span: mk_sp(lo, lo),
3106 if self.eat(&token::COLON) { ty = self.parse_ty(false); }
3107 let init = self.parse_initializer();
3112 id: ast::DUMMY_NODE_ID,
3113 span: mk_sp(lo, self.last_span.hi),
3117 // parse a "let" stmt
3118 fn parse_let(&mut self) -> @Decl {
3119 let lo = self.span.lo;
3120 let local = self.parse_local();
3121 while self.eat(&token::COMMA) {
3122 let _ = self.parse_local();
3123 self.obsolete(self.span, ObsoleteMultipleLocalDecl);
3125 return @spanned(lo, self.last_span.hi, DeclLocal(local));
3128 // parse a structure field
3129 fn parse_name_and_ty(&mut self, pr: Visibility,
3130 attrs: Vec<Attribute> ) -> StructField {
3131 let lo = self.span.lo;
3132 if !is_plain_ident(&self.token) {
3133 self.fatal("expected ident");
3135 let name = self.parse_ident();
3136 self.expect(&token::COLON);
3137 let ty = self.parse_ty(false);
3138 spanned(lo, self.last_span.hi, ast::StructField_ {
3139 kind: NamedField(name, pr),
3140 id: ast::DUMMY_NODE_ID,
3146 // parse a statement. may include decl.
3147 // precondition: any attributes are parsed already
3148 pub fn parse_stmt(&mut self, item_attrs: Vec<Attribute> ) -> @Stmt {
3149 maybe_whole!(self, NtStmt);
3151 fn check_expected_item(p: &mut Parser, found_attrs: bool) {
3152 // If we have attributes then we should have an item
3154 p.span_err(p.last_span, "expected item after attributes");
3158 let lo = self.span.lo;
3159 if self.is_keyword(keywords::Let) {
3160 check_expected_item(self, !item_attrs.is_empty());
3161 self.expect_keyword(keywords::Let);
3162 let decl = self.parse_let();
3163 return @spanned(lo, decl.span.hi, StmtDecl(decl, ast::DUMMY_NODE_ID));
3164 } else if is_ident(&self.token)
3165 && !token::is_any_keyword(&self.token)
3166 && self.look_ahead(1, |t| *t == token::NOT) {
3167 // parse a macro invocation. Looks like there's serious
3168 // overlap here; if this clause doesn't catch it (and it
3169 // won't, for brace-delimited macros) it will fall through
3170 // to the macro clause of parse_item_or_view_item. This
3171 // could use some cleanup, it appears to me.
3173 // whoops! I now have a guess: I'm guessing the "parens-only"
3174 // rule here is deliberate, to allow macro users to use parens
3175 // for things that should be parsed as stmt_mac, and braces
3176 // for things that should expand into items. Tricky, and
3177 // somewhat awkward... and probably undocumented. Of course,
3178 // I could just be wrong.
3180 check_expected_item(self, !item_attrs.is_empty());
3182 // Potential trouble: if we allow macros with paths instead of
3183 // idents, we'd need to look ahead past the whole path here...
3184 let pth = self.parse_path(NoTypesAllowed).path;
3187 let id = if self.token == token::LPAREN || self.token == token::LBRACE {
3188 token::special_idents::invalid // no special identifier
3193 // check that we're pointing at delimiters (need to check
3194 // again after the `if`, because of `parse_ident`
3195 // consuming more tokens).
3196 let (bra, ket) = match self.token {
3197 token::LPAREN => (token::LPAREN, token::RPAREN),
3198 token::LBRACE => (token::LBRACE, token::RBRACE),
3200 // we only expect an ident if we didn't parse one
3202 let ident_str = if id == token::special_idents::invalid {
3207 let tok_str = self.this_token_to_str();
3208 self.fatal(format!("expected {}`(` or `\\{`, but found `{}`",
3209 ident_str, tok_str))
3213 let tts = self.parse_unspanned_seq(
3217 |p| p.parse_token_tree()
3219 let hi = self.span.hi;
3221 if id == token::special_idents::invalid {
3222 return @spanned(lo, hi, StmtMac(
3223 spanned(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT)), false));
3225 // if it has a special ident, it's definitely an item
3226 return @spanned(lo, hi, StmtDecl(
3227 @spanned(lo, hi, DeclItem(
3229 lo, hi, id /*id is good here*/,
3230 ItemMac(spanned(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT))),
3231 Inherited, Vec::new(/*no attrs*/)))),
3232 ast::DUMMY_NODE_ID));
3236 let found_attrs = !item_attrs.is_empty();
3237 match self.parse_item_or_view_item(item_attrs, false) {
3240 let decl = @spanned(lo, hi, DeclItem(i));
3241 return @spanned(lo, hi, StmtDecl(decl, ast::DUMMY_NODE_ID));
3243 IoviViewItem(vi) => {
3244 self.span_fatal(vi.span,
3245 "view items must be declared at the top of the block");
3247 IoviForeignItem(_) => {
3248 self.fatal("foreign items are not allowed here");
3250 IoviNone(_) => { /* fallthrough */ }
3253 check_expected_item(self, found_attrs);
3255 // Remainder are line-expr stmts.
3256 let e = self.parse_expr_res(RESTRICT_STMT_EXPR);
3257 return @spanned(lo, e.span.hi, StmtExpr(e, ast::DUMMY_NODE_ID));
3261 // is this expression a successfully-parsed statement?
3262 fn expr_is_complete(&mut self, e: @Expr) -> bool {
3263 return self.restriction == RESTRICT_STMT_EXPR &&
3264 !classify::expr_requires_semi_to_be_stmt(e);
3267 // parse a block. No inner attrs are allowed.
3268 pub fn parse_block(&mut self) -> P<Block> {
3269 maybe_whole!(no_clone self, NtBlock);
3271 let lo = self.span.lo;
3272 if self.eat_keyword(keywords::Unsafe) {
3273 self.obsolete(self.span, ObsoleteUnsafeBlock);
3275 self.expect(&token::LBRACE);
3277 return self.parse_block_tail_(lo, DefaultBlock, Vec::new());
3280 // parse a block. Inner attrs are allowed.
3281 fn parse_inner_attrs_and_block(&mut self)
3282 -> (Vec<Attribute> , P<Block>) {
3284 maybe_whole!(pair_empty self, NtBlock);
3286 let lo = self.span.lo;
3287 if self.eat_keyword(keywords::Unsafe) {
3288 self.obsolete(self.span, ObsoleteUnsafeBlock);
3290 self.expect(&token::LBRACE);
3291 let (inner, next) = self.parse_inner_attrs_and_next();
3293 (inner, self.parse_block_tail_(lo, DefaultBlock, next))
3296 // Precondition: already parsed the '{' or '#{'
3297 // I guess that also means "already parsed the 'impure'" if
3298 // necessary, and this should take a qualifier.
3299 // some blocks start with "#{"...
3300 fn parse_block_tail(&mut self, lo: BytePos, s: BlockCheckMode) -> P<Block> {
3301 self.parse_block_tail_(lo, s, Vec::new())
3304 // parse the rest of a block expression or function body
3305 fn parse_block_tail_(&mut self, lo: BytePos, s: BlockCheckMode,
3306 first_item_attrs: Vec<Attribute> ) -> P<Block> {
3307 let mut stmts = Vec::new();
3308 let mut expr = None;
3310 // wouldn't it be more uniform to parse view items only, here?
3311 let ParsedItemsAndViewItems {
3312 attrs_remaining: attrs_remaining,
3313 view_items: view_items,
3316 } = self.parse_items_and_view_items(first_item_attrs,
3319 for item in items.iter() {
3320 let decl = @spanned(item.span.lo, item.span.hi, DeclItem(*item));
3321 stmts.push(@spanned(item.span.lo, item.span.hi,
3322 StmtDecl(decl, ast::DUMMY_NODE_ID)));
3325 let mut attributes_box = attrs_remaining;
3327 while self.token != token::RBRACE {
3328 // parsing items even when they're not allowed lets us give
3329 // better error messages and recover more gracefully.
3330 attributes_box.push_all(self.parse_outer_attributes().as_slice());
3333 if !attributes_box.is_empty() {
3334 self.span_err(self.last_span, "expected item after attributes");
3335 attributes_box = Vec::new();
3337 self.bump(); // empty
3340 // fall through and out.
3343 let stmt = self.parse_stmt(attributes_box);
3344 attributes_box = Vec::new();
3346 StmtExpr(e, stmt_id) => {
3347 // expression without semicolon
3348 if classify::stmt_ends_with_semi(stmt) {
3349 // Just check for errors and recover; do not eat semicolon yet.
3350 self.commit_stmt(stmt, &[], &[token::SEMI, token::RBRACE]);
3356 stmts.push(@codemap::Spanned {
3357 node: StmtSemi(e, stmt_id),
3369 StmtMac(ref m, _) => {
3370 // statement macro; might be an expr
3377 // if a block ends in `m!(arg)` without
3378 // a `;`, it must be an expr
3381 self.mk_mac_expr(stmt.span.lo,
3393 stmts.push(@codemap::Spanned {
3394 node: StmtMac((*m).clone(), true),
3399 _ => { // all other kinds of statements:
3402 if classify::stmt_ends_with_semi(stmt) {
3403 self.commit_stmt_expecting(stmt, token::SEMI);
3411 if !attributes_box.is_empty() {
3412 self.span_err(self.last_span, "expected item after attributes");
3415 let hi = self.span.hi;
3418 view_items: view_items,
3421 id: ast::DUMMY_NODE_ID,
3423 span: mk_sp(lo, hi),
3427 // matches optbounds = ( ( : ( boundseq )? )? )
3428 // where boundseq = ( bound + boundseq ) | bound
3429 // and bound = 'static | ty
3430 // Returns "None" if there's no colon (e.g. "T");
3431 // Returns "Some(Empty)" if there's a colon but nothing after (e.g. "T:")
3432 // Returns "Some(stuff)" otherwise (e.g. "T:stuff").
3433 // NB: The None/Some distinction is important for issue #7264.
3434 fn parse_optional_ty_param_bounds(&mut self) -> Option<OwnedSlice<TyParamBound>> {
3435 if !self.eat(&token::COLON) {
3439 let mut result = vec!();
3442 token::LIFETIME(lifetime) => {
3443 let lifetime_interned_string = token::get_ident(lifetime);
3444 if lifetime_interned_string.equiv(&("static")) {
3445 result.push(RegionTyParamBound);
3447 self.span_err(self.span,
3448 "`'static` is the only permissible region bound here");
3452 token::MOD_SEP | token::IDENT(..) => {
3453 let tref = self.parse_trait_ref();
3454 result.push(TraitTyParamBound(tref));
3459 if !self.eat(&token::BINOP(token::PLUS)) {
3464 return Some(OwnedSlice::from_vec(result));
3467 // matches typaram = IDENT optbounds ( EQ ty )?
3468 fn parse_ty_param(&mut self) -> TyParam {
3469 let ident = self.parse_ident();
3470 let opt_bounds = self.parse_optional_ty_param_bounds();
3471 // For typarams we don't care about the difference b/w "<T>" and "<T:>".
3472 let bounds = opt_bounds.unwrap_or_default();
3474 let default = if self.token == token::EQ {
3476 Some(self.parse_ty(false))
3482 id: ast::DUMMY_NODE_ID,
3488 // parse a set of optional generic type parameter declarations
3489 // matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
3490 // | ( < lifetimes , typaramseq ( , )? > )
3491 // where typaramseq = ( typaram ) | ( typaram , typaramseq )
3492 pub fn parse_generics(&mut self) -> ast::Generics {
3493 if self.eat(&token::LT) {
3494 let lifetimes = self.parse_lifetimes();
3495 let mut seen_default = false;
3496 let ty_params = self.parse_seq_to_gt(Some(token::COMMA), |p| {
3497 let ty_param = p.parse_ty_param();
3498 if ty_param.default.is_some() {
3499 seen_default = true;
3500 } else if seen_default {
3501 p.span_err(p.last_span,
3502 "type parameters with a default must be trailing");
3506 ast::Generics { lifetimes: lifetimes, ty_params: ty_params }
3508 ast_util::empty_generics()
3512 fn parse_generic_values_after_lt(&mut self) -> (Vec<ast::Lifetime>, Vec<P<Ty>> ) {
3513 let lifetimes = self.parse_lifetimes();
3514 let result = self.parse_seq_to_gt(
3516 |p| p.parse_ty(false));
3517 (lifetimes, result.into_vec())
3520 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
3521 -> (Vec<Arg> , bool) {
3523 let mut args: Vec<Option<Arg>> =
3524 self.parse_unspanned_seq(
3527 seq_sep_trailing_allowed(token::COMMA),
3529 if p.token == token::DOTDOTDOT {
3532 if p.token != token::RPAREN {
3533 p.span_fatal(p.span,
3534 "`...` must be last in argument list for variadic function");
3537 p.span_fatal(p.span,
3538 "only foreign functions are allowed to be variadic");
3542 Some(p.parse_arg_general(named_args))
3547 let variadic = match args.pop() {
3550 // Need to put back that last arg
3557 if variadic && args.is_empty() {
3559 "variadic function must be declared with at least one named argument");
3562 let args = args.move_iter().map(|x| x.unwrap()).collect();
3567 // parse the argument list and result type of a function declaration
3568 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> P<FnDecl> {
3570 let (args, variadic) = self.parse_fn_args(true, allow_variadic);
3571 let (ret_style, ret_ty) = self.parse_ret_ty();
3581 fn is_self_ident(&mut self) -> bool {
3583 token::IDENT(id, false) => id.name == special_idents::self_.name,
3588 fn expect_self_ident(&mut self) {
3589 if !self.is_self_ident() {
3590 let token_str = self.this_token_to_str();
3591 self.fatal(format!("expected `self` but found `{}`", token_str))
3596 // parse the argument list and result type of a function
3597 // that may have a self type.
3598 fn parse_fn_decl_with_self(&mut self, parse_arg_fn: |&mut Parser| -> Arg)
3599 -> (ExplicitSelf, P<FnDecl>) {
3600 fn maybe_parse_borrowed_explicit_self(this: &mut Parser)
3601 -> ast::ExplicitSelf_ {
3602 // The following things are possible to see here:
3607 // fn(&'lt mut self)
3609 // We already know that the current token is `&`.
3611 if this.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) {
3613 this.expect_self_ident();
3614 SelfRegion(None, MutImmutable)
3615 } else if this.look_ahead(1, |t| Parser::token_is_mutability(t)) &&
3617 |t| token::is_keyword(keywords::Self,
3620 let mutability = this.parse_mutability();
3621 this.expect_self_ident();
3622 SelfRegion(None, mutability)
3623 } else if this.look_ahead(1, |t| Parser::token_is_lifetime(t)) &&
3625 |t| token::is_keyword(keywords::Self,
3628 let lifetime = this.parse_lifetime();
3629 this.expect_self_ident();
3630 SelfRegion(Some(lifetime), MutImmutable)
3631 } else if this.look_ahead(1, |t| Parser::token_is_lifetime(t)) &&
3632 this.look_ahead(2, |t| {
3633 Parser::token_is_mutability(t)
3635 this.look_ahead(3, |t| token::is_keyword(keywords::Self,
3638 let lifetime = this.parse_lifetime();
3639 let mutability = this.parse_mutability();
3640 this.expect_self_ident();
3641 SelfRegion(Some(lifetime), mutability)
3647 self.expect(&token::LPAREN);
3649 // A bit of complexity and lookahead is needed here in order to be
3650 // backwards compatible.
3651 let lo = self.span.lo;
3652 let mut mutbl_self = MutImmutable;
3653 let explicit_self = match self.token {
3654 token::BINOP(token::AND) => {
3655 maybe_parse_borrowed_explicit_self(self)
3658 // We need to make sure it isn't a type
3659 if self.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) {
3661 self.expect_self_ident();
3667 token::IDENT(..) if self.is_self_ident() => {
3671 token::BINOP(token::STAR) => {
3672 // Possibly "*self" or "*mut self" -- not supported. Try to avoid
3673 // emitting cryptic "unexpected token" errors.
3675 let _mutability = if Parser::token_is_mutability(&self.token) {
3676 self.parse_mutability()
3677 } else { MutImmutable };
3678 if self.is_self_ident() {
3679 self.span_err(self.span, "cannot pass self by unsafe pointer");
3684 _ if Parser::token_is_mutability(&self.token) &&
3685 self.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) => {
3686 mutbl_self = self.parse_mutability();
3687 self.expect_self_ident();
3690 _ if Parser::token_is_mutability(&self.token) &&
3691 self.look_ahead(1, |t| *t == token::TILDE) &&
3692 self.look_ahead(2, |t| token::is_keyword(keywords::Self, t)) => {
3693 mutbl_self = self.parse_mutability();
3695 self.expect_self_ident();
3701 let explicit_self_sp = mk_sp(lo, self.span.hi);
3703 // If we parsed a self type, expect a comma before the argument list.
3704 let fn_inputs = if explicit_self != SelfStatic {
3708 let sep = seq_sep_trailing_disallowed(token::COMMA);
3709 let mut fn_inputs = self.parse_seq_to_before_end(
3714 fn_inputs.unshift(Arg::new_self(explicit_self_sp, mutbl_self));
3718 vec!(Arg::new_self(explicit_self_sp, mutbl_self))
3721 let token_str = self.this_token_to_str();
3722 self.fatal(format!("expected `,` or `)`, found `{}`",
3727 let sep = seq_sep_trailing_disallowed(token::COMMA);
3728 self.parse_seq_to_before_end(&token::RPAREN, sep, parse_arg_fn)
3731 self.expect(&token::RPAREN);
3733 let hi = self.span.hi;
3735 let (ret_style, ret_ty) = self.parse_ret_ty();
3737 let fn_decl = P(FnDecl {
3744 (spanned(lo, hi, explicit_self), fn_decl)
3747 // parse the |arg, arg| header on a lambda
3748 fn parse_fn_block_decl(&mut self) -> P<FnDecl> {
3749 let inputs_captures = {
3750 if self.eat(&token::OROR) {
3753 self.parse_unspanned_seq(
3754 &token::BINOP(token::OR),
3755 &token::BINOP(token::OR),
3756 seq_sep_trailing_disallowed(token::COMMA),
3757 |p| p.parse_fn_block_arg()
3761 let output = if self.eat(&token::RARROW) {
3762 self.parse_ty(false)
3765 id: ast::DUMMY_NODE_ID,
3772 inputs: inputs_captures,
3779 // Parses the `(arg, arg) -> return_type` header on a procedure.
3780 fn parse_proc_decl(&mut self) -> P<FnDecl> {
3782 self.parse_unspanned_seq(&token::LPAREN,
3784 seq_sep_trailing_allowed(token::COMMA),
3785 |p| p.parse_fn_block_arg());
3787 let output = if self.eat(&token::RARROW) {
3788 self.parse_ty(false)
3791 id: ast::DUMMY_NODE_ID,
3805 // parse the name and optional generic types of a function header.
3806 fn parse_fn_header(&mut self) -> (Ident, ast::Generics) {
3807 let id = self.parse_ident();
3808 let generics = self.parse_generics();
3812 fn mk_item(&mut self, lo: BytePos, hi: BytePos, ident: Ident,
3813 node: Item_, vis: Visibility,
3814 attrs: Vec<Attribute> ) -> @Item {
3818 id: ast::DUMMY_NODE_ID,
3825 // parse an item-position function declaration.
3826 fn parse_item_fn(&mut self, purity: Purity, abis: AbiSet) -> ItemInfo {
3827 let (ident, generics) = self.parse_fn_header();
3828 let decl = self.parse_fn_decl(false);
3829 let (inner_attrs, body) = self.parse_inner_attrs_and_block();
3830 (ident, ItemFn(decl, purity, abis, generics, body), Some(inner_attrs))
3833 // parse a method in a trait impl, starting with `attrs` attributes.
3834 fn parse_method(&mut self, already_parsed_attrs: Option<Vec<Attribute> >) -> @Method {
3835 let next_attrs = self.parse_outer_attributes();
3836 let attrs = match already_parsed_attrs {
3837 Some(mut a) => { a.push_all_move(next_attrs); a }
3841 let lo = self.span.lo;
3843 let visa = self.parse_visibility();
3844 let pur = self.parse_fn_purity();
3845 let ident = self.parse_ident();
3846 let generics = self.parse_generics();
3847 let (explicit_self, decl) = self.parse_fn_decl_with_self(|p| {
3851 let (inner_attrs, body) = self.parse_inner_attrs_and_block();
3852 let hi = body.span.hi;
3853 let attrs = vec::append(attrs, inner_attrs.as_slice());
3858 explicit_self: explicit_self,
3862 id: ast::DUMMY_NODE_ID,
3863 span: mk_sp(lo, hi),
3868 // parse trait Foo { ... }
3869 fn parse_item_trait(&mut self) -> ItemInfo {
3870 let ident = self.parse_ident();
3871 let tps = self.parse_generics();
3873 // Parse traits, if necessary.
3875 if self.token == token::COLON {
3877 traits = self.parse_trait_ref_list(&token::LBRACE);
3879 traits = Vec::new();
3882 let meths = self.parse_trait_methods();
3883 (ident, ItemTrait(tps, traits, meths), None)
3886 // Parses two variants (with the region/type params always optional):
3887 // impl<T> Foo { ... }
3888 // impl<T> ToStr for ~[T] { ... }
3889 fn parse_item_impl(&mut self) -> ItemInfo {
3890 // First, parse type parameters if necessary.
3891 let generics = self.parse_generics();
3893 // Special case: if the next identifier that follows is '(', don't
3894 // allow this to be parsed as a trait.
3895 let could_be_trait = self.token != token::LPAREN;
3898 let mut ty = self.parse_ty(false);
3900 // Parse traits, if necessary.
3901 let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) {
3902 // New-style trait. Reinterpret the type as a trait.
3903 let opt_trait_ref = match ty.node {
3904 TyPath(ref path, None, node_id) => {
3906 path: /* bad */ (*path).clone(),
3911 self.span_err(ty.span,
3912 "bounded traits are only valid in type position");
3916 self.span_err(ty.span, "not a trait");
3921 ty = self.parse_ty(false);
3927 let mut meths = Vec::new();
3928 self.expect(&token::LBRACE);
3929 let (inner_attrs, next) = self.parse_inner_attrs_and_next();
3930 let mut method_attrs = Some(next);
3931 while !self.eat(&token::RBRACE) {
3932 meths.push(self.parse_method(method_attrs));
3933 method_attrs = None;
3936 let ident = ast_util::impl_pretty_name(&opt_trait, ty);
3938 (ident, ItemImpl(generics, opt_trait, ty, meths), Some(inner_attrs))
3941 // parse a::B<~str,int>
3942 fn parse_trait_ref(&mut self) -> TraitRef {
3944 path: self.parse_path(LifetimeAndTypesWithoutColons).path,
3945 ref_id: ast::DUMMY_NODE_ID,
3949 // parse B + C<~str,int> + D
3950 fn parse_trait_ref_list(&mut self, ket: &token::Token) -> Vec<TraitRef> {
3951 self.parse_seq_to_before_end(
3953 seq_sep_trailing_disallowed(token::BINOP(token::PLUS)),
3954 |p| p.parse_trait_ref()
3958 // parse struct Foo { ... }
3959 fn parse_item_struct(&mut self) -> ItemInfo {
3960 let class_name = self.parse_ident();
3961 let generics = self.parse_generics();
3963 let mut fields: Vec<StructField> ;
3966 if self.eat(&token::LBRACE) {
3967 // It's a record-like struct.
3968 is_tuple_like = false;
3969 fields = Vec::new();
3970 while self.token != token::RBRACE {
3971 fields.push(self.parse_struct_decl_field());
3973 if fields.len() == 0 {
3974 self.fatal(format!("unit-like struct definition should be written as `struct {};`",
3975 token::get_ident(class_name)));
3978 } else if self.token == token::LPAREN {
3979 // It's a tuple-like struct.
3980 is_tuple_like = true;
3981 fields = self.parse_unspanned_seq(
3984 seq_sep_trailing_allowed(token::COMMA),
3986 let attrs = p.parse_outer_attributes();
3988 let struct_field_ = ast::StructField_ {
3990 id: ast::DUMMY_NODE_ID,
3991 ty: p.parse_ty(false),
3994 spanned(lo, p.span.hi, struct_field_)
3996 self.expect(&token::SEMI);
3997 } else if self.eat(&token::SEMI) {
3998 // It's a unit-like struct.
3999 is_tuple_like = true;
4000 fields = Vec::new();
4002 let token_str = self.this_token_to_str();
4003 self.fatal(format!("expected `\\{`, `(`, or `;` after struct \
4004 name but found `{}`",
4008 let _ = ast::DUMMY_NODE_ID; // FIXME: Workaround for crazy bug.
4009 let new_id = ast::DUMMY_NODE_ID;
4011 ItemStruct(@ast::StructDef {
4013 ctor_id: if is_tuple_like { Some(new_id) } else { None }
4018 // parse a structure field declaration
4019 pub fn parse_single_struct_field(&mut self,
4021 attrs: Vec<Attribute> )
4023 let a_var = self.parse_name_and_ty(vis, attrs);
4030 let token_str = self.this_token_to_str();
4031 self.span_fatal(self.span,
4032 format!("expected `,`, or `\\}` but found `{}`",
4039 // parse an element of a struct definition
4040 fn parse_struct_decl_field(&mut self) -> StructField {
4042 let attrs = self.parse_outer_attributes();
4044 if self.eat_keyword(keywords::Priv) {
4045 return self.parse_single_struct_field(Private, attrs);
4048 if self.eat_keyword(keywords::Pub) {
4049 return self.parse_single_struct_field(Public, attrs);
4052 return self.parse_single_struct_field(Inherited, attrs);
4055 // parse visiility: PUB, PRIV, or nothing
4056 fn parse_visibility(&mut self) -> Visibility {
4057 if self.eat_keyword(keywords::Pub) { Public }
4058 else if self.eat_keyword(keywords::Priv) { Private }
4062 // given a termination token and a vector of already-parsed
4063 // attributes (of length 0 or 1), parse all of the items in a module
4064 fn parse_mod_items(&mut self,
4066 first_item_attrs: Vec<Attribute> )
4068 // parse all of the items up to closing or an attribute.
4069 // view items are legal here.
4070 let ParsedItemsAndViewItems {
4071 attrs_remaining: attrs_remaining,
4072 view_items: view_items,
4073 items: starting_items,
4075 } = self.parse_items_and_view_items(first_item_attrs, true, true);
4076 let mut items: Vec<@Item> = starting_items;
4077 let attrs_remaining_len = attrs_remaining.len();
4079 // don't think this other loop is even necessary....
4081 let mut first = true;
4082 while self.token != term {
4083 let mut attrs = self.parse_outer_attributes();
4085 attrs = vec::append(attrs_remaining.clone(),
4089 debug!("parse_mod_items: parse_item_or_view_item(attrs={:?})",
4091 match self.parse_item_or_view_item(attrs,
4092 true /* macros allowed */) {
4093 IoviItem(item) => items.push(item),
4094 IoviViewItem(view_item) => {
4095 self.span_fatal(view_item.span,
4096 "view items must be declared at the top of \
4100 let token_str = self.this_token_to_str();
4101 self.fatal(format!("expected item but found `{}`",
4107 if first && attrs_remaining_len > 0u {
4108 // We parsed attributes for the first item but didn't find it
4109 self.span_err(self.last_span, "expected item after attributes");
4112 ast::Mod { view_items: view_items, items: items }
4115 fn parse_item_const(&mut self) -> ItemInfo {
4116 let m = if self.eat_keyword(keywords::Mut) {MutMutable} else {MutImmutable};
4117 let id = self.parse_ident();
4118 self.expect(&token::COLON);
4119 let ty = self.parse_ty(false);
4120 self.expect(&token::EQ);
4121 let e = self.parse_expr();
4122 self.commit_expr_expecting(e, token::SEMI);
4123 (id, ItemStatic(ty, m, e), None)
4126 // parse a `mod <foo> { ... }` or `mod <foo>;` item
4127 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> ItemInfo {
4128 let id_span = self.span;
4129 let id = self.parse_ident();
4130 if self.token == token::SEMI {
4132 // This mod is in an external file. Let's go get it!
4133 let (m, attrs) = self.eval_src_mod(id, outer_attrs, id_span);
4134 (id, m, Some(attrs))
4136 self.push_mod_path(id, outer_attrs);
4137 self.expect(&token::LBRACE);
4138 let (inner, next) = self.parse_inner_attrs_and_next();
4139 let m = self.parse_mod_items(token::RBRACE, next);
4140 self.expect(&token::RBRACE);
4141 self.pop_mod_path();
4142 (id, ItemMod(m), Some(inner))
4146 fn push_mod_path(&mut self, id: Ident, attrs: &[Attribute]) {
4147 let default_path = self.id_to_interned_str(id);
4148 let file_path = match ::attr::first_attr_value_str_by_name(attrs,
4151 None => default_path,
4153 self.mod_path_stack.push(file_path)
4156 fn pop_mod_path(&mut self) {
4157 self.mod_path_stack.pop().unwrap();
4160 // read a module from a source file.
4161 fn eval_src_mod(&mut self,
4163 outer_attrs: &[ast::Attribute],
4165 -> (ast::Item_, Vec<ast::Attribute> ) {
4166 let mut prefix = Path::new(self.sess.span_diagnostic.cm.span_to_filename(self.span));
4168 let mod_path = Path::new(".").join_many(self.mod_path_stack.as_slice());
4169 let dir_path = prefix.join(&mod_path);
4170 let file_path = match ::attr::first_attr_value_str_by_name(
4171 outer_attrs, "path") {
4172 Some(d) => dir_path.join(d),
4174 let mod_string = token::get_ident(id);
4175 let mod_name = mod_string.get().to_owned();
4176 let default_path_str = mod_name + ".rs";
4177 let secondary_path_str = mod_name + "/mod.rs";
4178 let default_path = dir_path.join(default_path_str.as_slice());
4179 let secondary_path = dir_path.join(secondary_path_str.as_slice());
4180 let default_exists = default_path.exists();
4181 let secondary_exists = secondary_path.exists();
4182 match (default_exists, secondary_exists) {
4183 (true, false) => default_path,
4184 (false, true) => secondary_path,
4186 self.span_fatal(id_sp, format!("file not found for module `{}`", mod_name));
4189 self.span_fatal(id_sp,
4190 format!("file for module `{}` found at both {} and {}",
4191 mod_name, default_path_str, secondary_path_str));
4197 self.eval_src_mod_from_path(file_path,
4198 outer_attrs.iter().map(|x| *x).collect(),
4202 fn eval_src_mod_from_path(&mut self,
4204 outer_attrs: Vec<ast::Attribute> ,
4205 id_sp: Span) -> (ast::Item_, Vec<ast::Attribute> ) {
4207 let mut included_mod_stack = self.sess
4210 let maybe_i = included_mod_stack.get()
4212 .position(|p| *p == path);
4215 let mut err = ~"circular modules: ";
4216 let len = included_mod_stack.get().len();
4217 for p in included_mod_stack.get().slice(i, len).iter() {
4218 err.push_str(p.display().as_maybe_owned().as_slice());
4219 err.push_str(" -> ");
4221 err.push_str(path.display().as_maybe_owned().as_slice());
4222 self.span_fatal(id_sp, err);
4226 included_mod_stack.get().push(path.clone());
4230 new_sub_parser_from_file(self.sess,
4234 let (inner, next) = p0.parse_inner_attrs_and_next();
4235 let mod_attrs = vec::append(outer_attrs, inner.as_slice());
4236 let first_item_outer_attrs = next;
4237 let m0 = p0.parse_mod_items(token::EOF, first_item_outer_attrs);
4239 let mut included_mod_stack = self.sess
4242 included_mod_stack.get().pop();
4244 return (ast::ItemMod(m0), mod_attrs);
4247 // parse a function declaration from a foreign module
4248 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility,
4249 attrs: Vec<Attribute> ) -> @ForeignItem {
4250 let lo = self.span.lo;
4252 // Parse obsolete purity.
4253 let purity = self.parse_fn_purity();
4254 if purity != ImpureFn {
4255 self.obsolete(self.last_span, ObsoleteUnsafeExternFn);
4258 let (ident, generics) = self.parse_fn_header();
4259 let decl = self.parse_fn_decl(true);
4260 let hi = self.span.hi;
4261 self.expect(&token::SEMI);
4262 @ast::ForeignItem { ident: ident,
4264 node: ForeignItemFn(decl, generics),
4265 id: ast::DUMMY_NODE_ID,
4266 span: mk_sp(lo, hi),
4270 // parse a static item from a foreign module
4271 fn parse_item_foreign_static(&mut self, vis: ast::Visibility,
4272 attrs: Vec<Attribute> ) -> @ForeignItem {
4273 let lo = self.span.lo;
4275 self.expect_keyword(keywords::Static);
4276 let mutbl = self.eat_keyword(keywords::Mut);
4278 let ident = self.parse_ident();
4279 self.expect(&token::COLON);
4280 let ty = self.parse_ty(false);
4281 let hi = self.span.hi;
4282 self.expect(&token::SEMI);
4283 @ast::ForeignItem { ident: ident,
4285 node: ForeignItemStatic(ty, mutbl),
4286 id: ast::DUMMY_NODE_ID,
4287 span: mk_sp(lo, hi),
4291 // parse safe/unsafe and fn
4292 fn parse_fn_purity(&mut self) -> Purity {
4293 if self.eat_keyword(keywords::Fn) { ImpureFn }
4294 else if self.eat_keyword(keywords::Unsafe) {
4295 self.expect_keyword(keywords::Fn);
4298 else { self.unexpected(); }
4302 // at this point, this is essentially a wrapper for
4303 // parse_foreign_items.
4304 fn parse_foreign_mod_items(&mut self,
4306 first_item_attrs: Vec<Attribute> )
4308 let ParsedItemsAndViewItems {
4309 attrs_remaining: attrs_remaining,
4310 view_items: view_items,
4312 foreign_items: foreign_items
4313 } = self.parse_foreign_items(first_item_attrs, true);
4314 if ! attrs_remaining.is_empty() {
4315 self.span_err(self.last_span,
4316 "expected item after attributes");
4318 assert!(self.token == token::RBRACE);
4321 view_items: view_items,
4322 items: foreign_items
4326 /// Parse extern crate links
4330 /// extern crate url;
4331 /// extern crate foo = "bar";
4332 fn parse_item_extern_crate(&mut self,
4334 visibility: Visibility,
4335 attrs: Vec<Attribute> )
4338 let (maybe_path, ident) = match self.token {
4339 token::IDENT(..) => {
4340 let the_ident = self.parse_ident();
4341 self.expect_one_of(&[], &[token::EQ, token::SEMI]);
4342 let path = if self.token == token::EQ {
4344 Some(self.parse_str())
4347 self.expect(&token::SEMI);
4351 let token_str = self.this_token_to_str();
4352 self.span_fatal(self.span,
4353 format!("expected extern crate name but found `{}`",
4358 IoviViewItem(ast::ViewItem {
4359 node: ViewItemExternCrate(ident, maybe_path, ast::DUMMY_NODE_ID),
4362 span: mk_sp(lo, self.last_span.hi)
4366 /// Parse `extern` for foreign ABIs
4369 /// `extern` is expected to have been
4370 /// consumed before calling this method
4376 fn parse_item_foreign_mod(&mut self,
4378 opt_abis: Option<AbiSet>,
4379 visibility: Visibility,
4380 attrs: Vec<Attribute> )
4383 self.expect(&token::LBRACE);
4385 let abis = opt_abis.unwrap_or(AbiSet::C());
4387 let (inner, next) = self.parse_inner_attrs_and_next();
4388 let m = self.parse_foreign_mod_items(abis, next);
4389 self.expect(&token::RBRACE);
4391 let item = self.mk_item(lo,
4393 special_idents::invalid,
4396 maybe_append(attrs, Some(inner)));
4397 return IoviItem(item);
4400 // parse type Foo = Bar;
4401 fn parse_item_type(&mut self) -> ItemInfo {
4402 let ident = self.parse_ident();
4403 let tps = self.parse_generics();
4404 self.expect(&token::EQ);
4405 let ty = self.parse_ty(false);
4406 self.expect(&token::SEMI);
4407 (ident, ItemTy(ty, tps), None)
4410 // parse a structure-like enum variant definition
4411 // this should probably be renamed or refactored...
4412 fn parse_struct_def(&mut self) -> @StructDef {
4413 let mut fields: Vec<StructField> = Vec::new();
4414 while self.token != token::RBRACE {
4415 fields.push(self.parse_struct_decl_field());
4419 return @ast::StructDef {
4425 // parse the part of an "enum" decl following the '{'
4426 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> EnumDef {
4427 let mut variants = Vec::new();
4428 let mut all_nullary = true;
4429 let mut have_disr = false;
4430 while self.token != token::RBRACE {
4431 let variant_attrs = self.parse_outer_attributes();
4432 let vlo = self.span.lo;
4434 let vis = self.parse_visibility();
4438 let mut args = Vec::new();
4439 let mut disr_expr = None;
4440 ident = self.parse_ident();
4441 if self.eat(&token::LBRACE) {
4442 // Parse a struct variant.
4443 all_nullary = false;
4444 kind = StructVariantKind(self.parse_struct_def());
4445 } else if self.token == token::LPAREN {
4446 all_nullary = false;
4447 let arg_tys = self.parse_enum_variant_seq(
4450 seq_sep_trailing_disallowed(token::COMMA),
4451 |p| p.parse_ty(false)
4453 for ty in arg_tys.move_iter() {
4454 args.push(ast::VariantArg {
4456 id: ast::DUMMY_NODE_ID,
4459 kind = TupleVariantKind(args);
4460 } else if self.eat(&token::EQ) {
4462 disr_expr = Some(self.parse_expr());
4463 kind = TupleVariantKind(args);
4465 kind = TupleVariantKind(Vec::new());
4468 let vr = ast::Variant_ {
4470 attrs: variant_attrs,
4472 id: ast::DUMMY_NODE_ID,
4473 disr_expr: disr_expr,
4476 variants.push(P(spanned(vlo, self.last_span.hi, vr)));
4478 if !self.eat(&token::COMMA) { break; }
4480 self.expect(&token::RBRACE);
4481 if have_disr && !all_nullary {
4482 self.fatal("discriminator values can only be used with a c-like \
4486 ast::EnumDef { variants: variants }
4489 // parse an "enum" declaration
4490 fn parse_item_enum(&mut self) -> ItemInfo {
4491 let id = self.parse_ident();
4492 let generics = self.parse_generics();
4493 self.expect(&token::LBRACE);
4495 let enum_definition = self.parse_enum_def(&generics);
4496 (id, ItemEnum(enum_definition, generics), None)
4499 fn fn_expr_lookahead(tok: &token::Token) -> bool {
4501 token::LPAREN | token::AT | token::TILDE | token::BINOP(_) => true,
4506 // Parses a string as an ABI spec on an extern type or module. Consumes
4507 // the `extern` keyword, if one is found.
4508 fn parse_opt_abis(&mut self) -> Option<AbiSet> {
4511 | token::LIT_STR_RAW(s, _) => {
4513 let identifier_string = token::get_ident(s);
4514 let the_string = identifier_string.get();
4515 let mut abis = AbiSet::empty();
4516 for word in the_string.words() {
4517 match abi::lookup(word) {
4519 if abis.contains(abi) {
4522 format!("ABI `{}` appears twice",
4532 format!("illegal ABI: \
4533 expected one of [{}], \
4535 abi::all_names().connect(", "),
4549 // parse one of the items or view items allowed by the
4550 // flags; on failure, return IoviNone.
4551 // NB: this function no longer parses the items inside an
4553 fn parse_item_or_view_item(&mut self,
4554 attrs: Vec<Attribute> ,
4555 macros_allowed: bool)
4558 INTERPOLATED(token::NtItem(item)) => {
4560 let new_attrs = vec::append(attrs, item.attrs.as_slice());
4561 return IoviItem(@Item {
4569 let lo = self.span.lo;
4571 let visibility = self.parse_visibility();
4573 // must be a view item:
4574 if self.eat_keyword(keywords::Use) {
4575 // USE ITEM (IoviViewItem)
4576 let view_item = self.parse_use();
4577 self.expect(&token::SEMI);
4578 return IoviViewItem(ast::ViewItem {
4582 span: mk_sp(lo, self.last_span.hi)
4585 // either a view item or an item:
4586 if self.eat_keyword(keywords::Extern) {
4587 let next_is_mod = self.eat_keyword(keywords::Mod);
4589 if next_is_mod || self.eat_keyword(keywords::Crate) {
4591 self.span_err(mk_sp(lo, self.last_span.hi),
4592 format!("`extern mod` is obsolete, use \
4593 `extern crate` instead \
4594 to refer to external crates."))
4596 return self.parse_item_extern_crate(lo, visibility, attrs);
4599 let opt_abis = self.parse_opt_abis();
4601 if self.eat_keyword(keywords::Fn) {
4602 // EXTERN FUNCTION ITEM
4603 let abis = opt_abis.unwrap_or(AbiSet::C());
4604 let (ident, item_, extra_attrs) =
4605 self.parse_item_fn(ExternFn, abis);
4606 let item = self.mk_item(lo,
4611 maybe_append(attrs, extra_attrs));
4612 return IoviItem(item);
4613 } else if self.token == token::LBRACE {
4614 return self.parse_item_foreign_mod(lo, opt_abis, visibility, attrs);
4617 let token_str = self.this_token_to_str();
4618 self.span_fatal(self.span,
4619 format!("expected `\\{` or `fn` but found `{}`", token_str));
4622 // the rest are all guaranteed to be items:
4623 if self.is_keyword(keywords::Static) {
4626 let (ident, item_, extra_attrs) = self.parse_item_const();
4627 let item = self.mk_item(lo,
4632 maybe_append(attrs, extra_attrs));
4633 return IoviItem(item);
4635 if self.is_keyword(keywords::Fn) &&
4636 self.look_ahead(1, |f| !Parser::fn_expr_lookahead(f)) {
4639 let (ident, item_, extra_attrs) =
4640 self.parse_item_fn(ImpureFn, AbiSet::Rust());
4641 let item = self.mk_item(lo,
4646 maybe_append(attrs, extra_attrs));
4647 return IoviItem(item);
4649 if self.is_keyword(keywords::Unsafe)
4650 && self.look_ahead(1u, |t| *t != token::LBRACE) {
4651 // UNSAFE FUNCTION ITEM
4653 self.expect_keyword(keywords::Fn);
4654 let (ident, item_, extra_attrs) =
4655 self.parse_item_fn(UnsafeFn, AbiSet::Rust());
4656 let item = self.mk_item(lo,
4661 maybe_append(attrs, extra_attrs));
4662 return IoviItem(item);
4664 if self.eat_keyword(keywords::Mod) {
4666 let (ident, item_, extra_attrs) =
4667 self.parse_item_mod(attrs.as_slice());
4668 let item = self.mk_item(lo,
4673 maybe_append(attrs, extra_attrs));
4674 return IoviItem(item);
4676 if self.eat_keyword(keywords::Type) {
4678 let (ident, item_, extra_attrs) = self.parse_item_type();
4679 let item = self.mk_item(lo,
4684 maybe_append(attrs, extra_attrs));
4685 return IoviItem(item);
4687 if self.eat_keyword(keywords::Enum) {
4689 let (ident, item_, extra_attrs) = self.parse_item_enum();
4690 let item = self.mk_item(lo,
4695 maybe_append(attrs, extra_attrs));
4696 return IoviItem(item);
4698 if self.eat_keyword(keywords::Trait) {
4700 let (ident, item_, extra_attrs) = self.parse_item_trait();
4701 let item = self.mk_item(lo,
4706 maybe_append(attrs, extra_attrs));
4707 return IoviItem(item);
4709 if self.eat_keyword(keywords::Impl) {
4711 let (ident, item_, extra_attrs) = self.parse_item_impl();
4712 let item = self.mk_item(lo,
4717 maybe_append(attrs, extra_attrs));
4718 return IoviItem(item);
4720 if self.eat_keyword(keywords::Struct) {
4722 let (ident, item_, extra_attrs) = self.parse_item_struct();
4723 let item = self.mk_item(lo,
4728 maybe_append(attrs, extra_attrs));
4729 return IoviItem(item);
4731 self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility)
4734 // parse a foreign item; on failure, return IoviNone.
4735 fn parse_foreign_item(&mut self,
4736 attrs: Vec<Attribute> ,
4737 macros_allowed: bool)
4739 maybe_whole!(iovi self, NtItem);
4740 let lo = self.span.lo;
4742 let visibility = self.parse_visibility();
4744 if self.is_keyword(keywords::Static) {
4745 // FOREIGN STATIC ITEM
4746 let item = self.parse_item_foreign_static(visibility, attrs);
4747 return IoviForeignItem(item);
4749 if self.is_keyword(keywords::Fn) || self.is_keyword(keywords::Unsafe) {
4750 // FOREIGN FUNCTION ITEM
4751 let item = self.parse_item_foreign_fn(visibility, attrs);
4752 return IoviForeignItem(item);
4754 self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility)
4757 // this is the fall-through for parsing items.
4758 fn parse_macro_use_or_failure(
4760 attrs: Vec<Attribute> ,
4761 macros_allowed: bool,
4763 visibility: Visibility
4764 ) -> ItemOrViewItem {
4765 if macros_allowed && !token::is_any_keyword(&self.token)
4766 && self.look_ahead(1, |t| *t == token::NOT)
4767 && (self.look_ahead(2, |t| is_plain_ident(t))
4768 || self.look_ahead(2, |t| *t == token::LPAREN)
4769 || self.look_ahead(2, |t| *t == token::LBRACE)) {
4770 // MACRO INVOCATION ITEM
4773 let pth = self.parse_path(NoTypesAllowed).path;
4774 self.expect(&token::NOT);
4776 // a 'special' identifier (like what `macro_rules!` uses)
4777 // is optional. We should eventually unify invoc syntax
4779 let id = if is_plain_ident(&self.token) {
4782 token::special_idents::invalid // no special identifier
4784 // eat a matched-delimiter token tree:
4785 let tts = match self.token {
4786 token::LPAREN | token::LBRACE => {
4787 let ket = token::flip_delimiter(&self.token);
4789 self.parse_seq_to_end(&ket,
4791 |p| p.parse_token_tree())
4793 _ => self.fatal("expected open delimiter")
4795 // single-variant-enum... :
4796 let m = ast::MacInvocTT(pth, tts, EMPTY_CTXT);
4797 let m: ast::Mac = codemap::Spanned { node: m,
4798 span: mk_sp(self.span.lo,
4800 let item_ = ItemMac(m);
4801 let item = self.mk_item(lo,
4807 return IoviItem(item);
4810 // FAILURE TO PARSE ITEM
4811 if visibility != Inherited {
4812 let mut s = ~"unmatched visibility `";
4813 if visibility == Public {
4819 self.span_fatal(self.last_span, s);
4821 return IoviNone(attrs);
4824 pub fn parse_item(&mut self, attrs: Vec<Attribute> ) -> Option<@Item> {
4825 match self.parse_item_or_view_item(attrs, true) {
4826 IoviNone(_) => None,
4828 self.fatal("view items are not allowed here"),
4829 IoviForeignItem(_) =>
4830 self.fatal("foreign items are not allowed here"),
4831 IoviItem(item) => Some(item)
4835 // parse, e.g., "use a::b::{z,y}"
4836 fn parse_use(&mut self) -> ViewItem_ {
4837 return ViewItemUse(self.parse_view_paths());
4841 // matches view_path : MOD? IDENT EQ non_global_path
4842 // | MOD? non_global_path MOD_SEP LBRACE RBRACE
4843 // | MOD? non_global_path MOD_SEP LBRACE ident_seq RBRACE
4844 // | MOD? non_global_path MOD_SEP STAR
4845 // | MOD? non_global_path
4846 fn parse_view_path(&mut self) -> @ViewPath {
4847 let lo = self.span.lo;
4849 if self.token == token::LBRACE {
4851 let idents = self.parse_unspanned_seq(
4852 &token::LBRACE, &token::RBRACE,
4853 seq_sep_trailing_allowed(token::COMMA),
4854 |p| p.parse_path_list_ident());
4855 let path = ast::Path {
4856 span: mk_sp(lo, self.span.hi),
4858 segments: Vec::new()
4860 return @spanned(lo, self.span.hi,
4861 ViewPathList(path, idents, ast::DUMMY_NODE_ID));
4864 let first_ident = self.parse_ident();
4865 let mut path = vec!(first_ident);
4870 let path_lo = self.span.lo;
4871 path = vec!(self.parse_ident());
4872 while self.token == token::MOD_SEP {
4874 let id = self.parse_ident();
4877 let path = ast::Path {
4878 span: mk_sp(path_lo, self.span.hi),
4880 segments: path.move_iter().map(|identifier| {
4882 identifier: identifier,
4883 lifetimes: Vec::new(),
4884 types: OwnedSlice::empty(),
4888 return @spanned(lo, self.span.hi,
4889 ViewPathSimple(first_ident, path,
4890 ast::DUMMY_NODE_ID));
4894 // foo::bar or foo::{a,b,c} or foo::*
4895 while self.token == token::MOD_SEP {
4899 token::IDENT(i, _) => {
4904 // foo::bar::{a,b,c}
4906 let idents = self.parse_unspanned_seq(
4909 seq_sep_trailing_allowed(token::COMMA),
4910 |p| p.parse_path_list_ident()
4912 let path = ast::Path {
4913 span: mk_sp(lo, self.span.hi),
4915 segments: path.move_iter().map(|identifier| {
4917 identifier: identifier,
4918 lifetimes: Vec::new(),
4919 types: OwnedSlice::empty(),
4923 return @spanned(lo, self.span.hi,
4924 ViewPathList(path, idents, ast::DUMMY_NODE_ID));
4928 token::BINOP(token::STAR) => {
4930 let path = ast::Path {
4931 span: mk_sp(lo, self.span.hi),
4933 segments: path.move_iter().map(|identifier| {
4935 identifier: identifier,
4936 lifetimes: Vec::new(),
4937 types: OwnedSlice::empty(),
4941 return @spanned(lo, self.span.hi,
4942 ViewPathGlob(path, ast::DUMMY_NODE_ID));
4951 let last = *path.get(path.len() - 1u);
4952 let path = ast::Path {
4953 span: mk_sp(lo, self.span.hi),
4955 segments: path.move_iter().map(|identifier| {
4957 identifier: identifier,
4958 lifetimes: Vec::new(),
4959 types: OwnedSlice::empty(),
4965 ViewPathSimple(last, path, ast::DUMMY_NODE_ID));
4968 // matches view_paths = view_path | view_path , view_paths
4969 fn parse_view_paths(&mut self) -> Vec<@ViewPath> {
4970 let mut vp = vec!(self.parse_view_path());
4971 while self.token == token::COMMA {
4973 self.obsolete(self.last_span, ObsoleteMultipleImport);
4974 vp.push(self.parse_view_path());
4979 // Parses a sequence of items. Stops when it finds program
4980 // text that can't be parsed as an item
4981 // - mod_items uses extern_mod_allowed = true
4982 // - block_tail_ uses extern_mod_allowed = false
4983 fn parse_items_and_view_items(&mut self,
4984 first_item_attrs: Vec<Attribute> ,
4985 mut extern_mod_allowed: bool,
4986 macros_allowed: bool)
4987 -> ParsedItemsAndViewItems {
4988 let mut attrs = vec::append(first_item_attrs,
4989 self.parse_outer_attributes()
4991 // First, parse view items.
4992 let mut view_items : Vec<ast::ViewItem> = Vec::new();
4993 let mut items = Vec::new();
4995 // I think this code would probably read better as a single
4996 // loop with a mutable three-state-variable (for extern crates,
4997 // view items, and regular items) ... except that because
4998 // of macros, I'd like to delay that entire check until later.
5000 match self.parse_item_or_view_item(attrs, macros_allowed) {
5001 IoviNone(attrs) => {
5002 return ParsedItemsAndViewItems {
5003 attrs_remaining: attrs,
5004 view_items: view_items,
5006 foreign_items: Vec::new()
5009 IoviViewItem(view_item) => {
5010 match view_item.node {
5011 ViewItemUse(..) => {
5012 // `extern crate` must precede `use`.
5013 extern_mod_allowed = false;
5015 ViewItemExternCrate(..) if !extern_mod_allowed => {
5016 self.span_err(view_item.span,
5017 "\"extern crate\" declarations are not allowed here");
5019 ViewItemExternCrate(..) => {}
5021 view_items.push(view_item);
5025 attrs = self.parse_outer_attributes();
5028 IoviForeignItem(_) => {
5032 attrs = self.parse_outer_attributes();
5035 // Next, parse items.
5037 match self.parse_item_or_view_item(attrs, macros_allowed) {
5038 IoviNone(returned_attrs) => {
5039 attrs = returned_attrs;
5042 IoviViewItem(view_item) => {
5043 attrs = self.parse_outer_attributes();
5044 self.span_err(view_item.span,
5045 "`use` and `extern crate` declarations must precede items");
5048 attrs = self.parse_outer_attributes();
5051 IoviForeignItem(_) => {
5057 ParsedItemsAndViewItems {
5058 attrs_remaining: attrs,
5059 view_items: view_items,
5061 foreign_items: Vec::new()
5065 // Parses a sequence of foreign items. Stops when it finds program
5066 // text that can't be parsed as an item
5067 fn parse_foreign_items(&mut self, first_item_attrs: Vec<Attribute> ,
5068 macros_allowed: bool)
5069 -> ParsedItemsAndViewItems {
5070 let mut attrs = vec::append(first_item_attrs,
5071 self.parse_outer_attributes()
5073 let mut foreign_items = Vec::new();
5075 match self.parse_foreign_item(attrs, macros_allowed) {
5076 IoviNone(returned_attrs) => {
5077 if self.token == token::RBRACE {
5078 attrs = returned_attrs;
5083 IoviViewItem(view_item) => {
5084 // I think this can't occur:
5085 self.span_err(view_item.span,
5086 "`use` and `extern crate` declarations must precede items");
5089 // FIXME #5668: this will occur for a macro invocation:
5090 self.span_fatal(item.span, "macros cannot expand to foreign items");
5092 IoviForeignItem(foreign_item) => {
5093 foreign_items.push(foreign_item);
5096 attrs = self.parse_outer_attributes();
5099 ParsedItemsAndViewItems {
5100 attrs_remaining: attrs,
5101 view_items: Vec::new(),
5103 foreign_items: foreign_items
5107 // Parses a source module as a crate. This is the main
5108 // entry point for the parser.
5109 pub fn parse_crate_mod(&mut self) -> Crate {
5110 let lo = self.span.lo;
5111 // parse the crate's inner attrs, maybe (oops) one
5112 // of the attrs of an item:
5113 let (inner, next) = self.parse_inner_attrs_and_next();
5114 let first_item_outer_attrs = next;
5115 // parse the items inside the crate:
5116 let m = self.parse_mod_items(token::EOF, first_item_outer_attrs);
5121 config: self.cfg.clone(),
5122 span: mk_sp(lo, self.span.lo)
5126 pub fn parse_optional_str(&mut self)
5127 -> Option<(InternedString, ast::StrStyle)> {
5128 let (s, style) = match self.token {
5129 token::LIT_STR(s) => (self.id_to_interned_str(s), ast::CookedStr),
5130 token::LIT_STR_RAW(s, n) => {
5131 (self.id_to_interned_str(s), ast::RawStr(n))
5139 pub fn parse_str(&mut self) -> (InternedString, StrStyle) {
5140 match self.parse_optional_str() {
5142 _ => self.fatal("expected string literal")