1 // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
15 use ast::{Sigil, BorrowedSigil, ManagedSigil, OwnedSigil};
16 use ast::{CallSugar, NoSugar, DoSugar};
17 use ast::{TyBareFn, TyClosure};
18 use ast::{RegionTyParamBound, TraitTyParamBound};
19 use ast::{provided, public, purity};
20 use ast::{_mod, BiAdd, arg, Arm, Attribute, BindByRef, BindInfer};
21 use ast::{BiBitAnd, BiBitOr, BiBitXor, Block};
22 use ast::{BlockCheckMode, UnBox};
23 use ast::{Crate, CrateConfig, Decl, DeclItem};
24 use ast::{DeclLocal, DefaultBlock, UnDeref, BiDiv, EMPTY_CTXT, enum_def, explicit_self};
25 use ast::{Expr, Expr_, ExprAddrOf, ExprMatch, ExprAgain};
26 use ast::{ExprAssign, ExprAssignOp, ExprBinary, ExprBlock};
27 use ast::{ExprBreak, ExprCall, ExprCast, ExprDoBody};
28 use ast::{ExprField, ExprFnBlock, ExprIf, ExprIndex};
29 use ast::{ExprLit, ExprLogLevel, ExprLoop, ExprMac};
30 use ast::{ExprMethodCall, ExprParen, ExprPath, ExprRepeat};
31 use ast::{ExprRet, ExprSelf, ExprStruct, ExprTup, ExprUnary};
32 use ast::{ExprVec, ExprVstore, ExprVstoreMutBox};
33 use ast::{ExprVstoreSlice, ExprVstoreBox};
34 use ast::{ExprVstoreMutSlice, ExprWhile, ExprForLoop, extern_fn, Field, fn_decl};
35 use ast::{ExprVstoreUniq, Onceness, Once, Many};
36 use ast::{foreign_item, foreign_item_static, foreign_item_fn, foreign_mod};
37 use ast::{Ident, impure_fn, inherited, item, item_, item_static};
38 use ast::{item_enum, item_fn, item_foreign_mod, item_impl};
39 use ast::{item_mac, item_mod, item_struct, item_trait, item_ty, lit, lit_};
40 use ast::{lit_bool, lit_float, lit_float_unsuffixed, lit_int, lit_char};
41 use ast::{lit_int_unsuffixed, lit_nil, lit_str, lit_uint, Local};
42 use ast::{MutImmutable, MutMutable, mac_, mac_invoc_tt, matcher, match_nonterminal};
43 use ast::{match_seq, match_tok, method, mt, BiMul, Mutability};
44 use ast::{named_field, UnNeg, noreturn, UnNot, Pat, PatBox, PatEnum};
45 use ast::{PatIdent, PatLit, PatRange, PatRegion, PatStruct};
46 use ast::{PatTup, PatUniq, PatWild, private};
47 use ast::{BiRem, required};
48 use ast::{ret_style, return_val, BiShl, BiShr, Stmt, StmtDecl};
49 use ast::{StmtExpr, StmtSemi, StmtMac, struct_def, struct_field};
50 use ast::{struct_variant_kind, BiSub};
52 use ast::{sty_box, sty_region, sty_static, sty_uniq, sty_value};
53 use ast::{token_tree, trait_method, trait_ref, tt_delim, tt_seq, tt_tok};
54 use ast::{tt_nonterminal, tuple_variant_kind, Ty, ty_, ty_bot, ty_box};
55 use ast::{TypeField, ty_fixed_length_vec, ty_closure, ty_bare_fn, ty_typeof};
56 use ast::{ty_infer, TypeMethod};
57 use ast::{ty_nil, TyParam, TyParamBound, ty_path, ty_ptr, ty_rptr};
58 use ast::{ty_tup, ty_u32, ty_uniq, ty_vec, UnUniq};
59 use ast::{unnamed_field, UnsafeBlock, unsafe_fn, view_item};
60 use ast::{view_item_, view_item_extern_mod, view_item_use};
61 use ast::{view_path, view_path_glob, view_path_list, view_path_simple};
64 use ast_util::{as_prec, operator_prec};
66 use codemap::{Span, BytePos, Spanned, spanned, mk_sp};
68 use parse::attr::parser_attr;
70 use parse::common::{SeqSep, seq_sep_none};
71 use parse::common::{seq_sep_trailing_disallowed, seq_sep_trailing_allowed};
72 use parse::lexer::reader;
73 use parse::lexer::TokenAndSpan;
74 use parse::obsolete::*;
75 use parse::token::{can_begin_expr, get_ident_interner, ident_to_str, is_ident};
76 use parse::token::{is_ident_or_path};
77 use parse::token::{is_plain_ident, INTERPOLATED, keywords, special_idents};
78 use parse::token::{token_to_binop};
80 use parse::{new_sub_parser_from_file, ParseSess};
84 use std::hashmap::HashSet;
93 RESTRICT_NO_BAR_OR_DOUBLEBAR_OP,
96 type item_info = (Ident, item_, Option<~[Attribute]>);
98 /// How to parse a path. There are four different kinds of paths, all of which
99 /// are parsed somewhat differently.
101 pub enum PathParsingMode {
102 /// A path with no type parameters; e.g. `foo::bar::Baz`
104 /// A path with a lifetime and type parameters, with no double colons
105 /// before the type parameters; e.g. `foo::bar<'self>::Baz<T>`
106 LifetimeAndTypesWithoutColons,
107 /// A path with a lifetime and type parameters with double colons before
108 /// the type parameters; e.g. `foo::bar::<'self>::Baz::<T>`
109 LifetimeAndTypesWithColons,
110 /// A path with a lifetime and type parameters with bounds before the last
111 /// set of type parameters only; e.g. `foo::bar<'self>::Baz:X+Y<T>` This
112 /// form does not use extra double colons.
113 LifetimeAndTypesAndBounds,
116 /// A pair of a path segment and group of type parameter bounds. (See `ast.rs`
117 /// for the definition of a path segment.)
118 struct PathSegmentAndBoundSet {
119 segment: ast::PathSegment,
120 bound_set: Option<OptVec<TyParamBound>>,
123 /// A path paired with optional type bounds.
124 struct PathAndBounds {
126 bounds: Option<OptVec<TyParamBound>>,
129 pub enum item_or_view_item {
130 // Indicates a failure to parse any kind of item. The attributes are
132 iovi_none(~[Attribute]),
134 iovi_foreign_item(@foreign_item),
135 iovi_view_item(view_item)
139 enum view_item_parse_mode {
140 VIEW_ITEMS_AND_ITEMS_ALLOWED,
141 FOREIGN_ITEMS_ALLOWED,
142 IMPORTS_AND_ITEMS_ALLOWED
145 /* The expr situation is not as complex as I thought it would be.
146 The important thing is to make sure that lookahead doesn't balk
147 at INTERPOLATED tokens */
148 macro_rules! maybe_whole_expr (
151 // This horrible convolution is brought to you by
152 // @mut, have a terrible day
153 let ret = match *($p).token {
154 INTERPOLATED(token::nt_expr(e)) => {
157 INTERPOLATED(token::nt_path(ref pt)) => {
161 ExprPath(/* bad */ (**pt).clone())))
176 macro_rules! maybe_whole (
177 ($p:expr, $constructor:ident) => (
179 let __found__ = match *($p).token {
180 INTERPOLATED(token::$constructor(_)) => {
181 Some(($p).bump_and_get())
186 Some(INTERPOLATED(token::$constructor(x))) => {
193 (deref $p:expr, $constructor:ident) => (
195 let __found__ = match *($p).token {
196 INTERPOLATED(token::$constructor(_)) => {
197 Some(($p).bump_and_get())
202 Some(INTERPOLATED(token::$constructor(x))) => {
209 (Some $p:expr, $constructor:ident) => (
211 let __found__ = match *($p).token {
212 INTERPOLATED(token::$constructor(_)) => {
213 Some(($p).bump_and_get())
218 Some(INTERPOLATED(token::$constructor(x))) => {
219 return Some(x.clone()),
225 (iovi $p:expr, $constructor:ident) => (
227 let __found__ = match *($p).token {
228 INTERPOLATED(token::$constructor(_)) => {
229 Some(($p).bump_and_get())
234 Some(INTERPOLATED(token::$constructor(x))) => {
235 return iovi_item(x.clone())
241 (pair_empty $p:expr, $constructor:ident) => (
243 let __found__ = match *($p).token {
244 INTERPOLATED(token::$constructor(_)) => {
245 Some(($p).bump_and_get())
250 Some(INTERPOLATED(token::$constructor(ref x))) => {
251 return (~[], (**x).clone())
260 fn maybe_append(lhs: ~[Attribute], rhs: Option<~[Attribute]>)
264 Some(ref attrs) => vec::append(lhs, (*attrs))
269 struct ParsedItemsAndViewItems {
270 attrs_remaining: ~[Attribute],
271 view_items: ~[view_item],
273 foreign_items: ~[@foreign_item]
276 /* ident is handled by common.rs */
278 pub fn Parser(sess: @mut ParseSess,
279 cfg: ast::CrateConfig,
282 let tok0 = rdr.next_token();
283 let interner = get_ident_interner();
285 let placeholder = TokenAndSpan {
286 tok: token::UNDERSCORE,
295 token: @mut tok0.tok,
297 last_span: @mut span,
298 last_token: @mut None,
305 buffer_start: @mut 0,
307 tokens_consumed: @mut 0,
308 restriction: @mut UNRESTRICTED,
310 obsolete_set: @mut HashSet::new(),
311 mod_path_stack: @mut ~[],
312 open_braces: @mut ~[]
316 // ooh, nasty mutable fields everywhere....
318 sess: @mut ParseSess,
320 // the current token:
321 token: @mut token::Token,
322 // the span of the current token:
324 // the span of the prior token:
325 last_span: @mut Span,
326 // the previous token or None (only stashed sometimes).
327 last_token: @mut Option<~token::Token>,
328 buffer: @mut [TokenAndSpan, ..4],
329 buffer_start: @mut int,
330 buffer_end: @mut int,
331 tokens_consumed: @mut uint,
332 restriction: @mut restriction,
333 quote_depth: @mut uint, // not (yet) related to the quasiquoter
335 interner: @token::ident_interner,
336 /// The set of seen errors about obsolete syntax. Used to suppress
337 /// extra detail when the same error is seen twice
338 obsolete_set: @mut HashSet<ObsoleteSyntax>,
339 /// Used to determine the path to externally loaded source files
340 mod_path_stack: @mut ~[@str],
341 /// Stack of spans of open delimiters. Used for error message.
342 open_braces: @mut ~[Span]
346 impl Drop for Parser {
347 /* do not copy the parser; its state is tied to outside state */
348 fn drop(&mut self) {}
351 fn is_plain_ident_or_underscore(t: &token::Token) -> bool {
352 is_plain_ident(t) || *t == token::UNDERSCORE
356 // convert a token to a string using self's reader
357 pub fn token_to_str(&self, token: &token::Token) -> ~str {
358 token::to_str(get_ident_interner(), token)
361 // convert the current token to a string using self's reader
362 pub fn this_token_to_str(&self) -> ~str {
363 self.token_to_str(self.token)
366 pub fn unexpected_last(&self, t: &token::Token) -> ! {
370 "unexpected token: `{}`",
376 pub fn unexpected(&self) -> ! {
379 "unexpected token: `{}`",
380 self.this_token_to_str()
385 // expect and consume the token t. Signal an error if
386 // the next token is not t.
387 pub fn expect(&self, t: &token::Token) {
388 if *self.token == *t {
393 "expected `{}` but found `{}`",
394 self.token_to_str(t),
395 self.this_token_to_str()
401 // Expect next token to be edible or inedible token. If edible,
402 // then consume it; if inedible, then return without consuming
403 // anything. Signal a fatal error if next token is unexpected.
404 pub fn expect_one_of(&self, edible: &[token::Token], inedible: &[token::Token]) {
405 fn tokens_to_str(p:&Parser, tokens: &[token::Token]) -> ~str {
406 let mut i = tokens.iter();
407 // This might be a sign we need a connect method on Iterator.
408 let b = i.next().map_default(~"", |t| p.token_to_str(t));
409 i.fold(b, |b,a| b + "`, `" + p.token_to_str(a))
411 if edible.contains(self.token) {
413 } else if inedible.contains(self.token) {
414 // leave it in the input
416 let expected = vec::append(edible.to_owned(), inedible);
417 let expect = tokens_to_str(self, expected);
418 let actual = self.this_token_to_str();
420 if expected.len() != 1 {
421 format!("expected one of `{}` but found `{}`", expect, actual)
423 format!("expected `{}` but found `{}`", expect, actual)
429 // Check for erroneous `ident { }`; if matches, signal error and
430 // recover (without consuming any expected input token). Returns
431 // true if and only if input was consumed for recovery.
432 pub fn check_for_erroneous_unit_struct_expecting(&self, expected: &[token::Token]) -> bool {
433 if *self.token == token::LBRACE
434 && expected.iter().all(|t| *t != token::LBRACE)
435 && self.look_ahead(1, |t| *t == token::RBRACE) {
436 // matched; signal non-fatal error and recover.
437 self.span_err(*self.span,
438 "Unit-like struct construction is written with no trailing `{ }`");
439 self.eat(&token::LBRACE);
440 self.eat(&token::RBRACE);
447 // Commit to parsing a complete expression `e` expected to be
448 // followed by some token from the set edible + inedible. Recover
449 // from anticipated input errors, discarding erroneous characters.
450 pub fn commit_expr(&self, e: @Expr, edible: &[token::Token], inedible: &[token::Token]) {
451 debug!("commit_expr {:?}", e);
454 // might be unit-struct construction; check for recoverableinput error.
455 let expected = vec::append(edible.to_owned(), inedible);
456 self.check_for_erroneous_unit_struct_expecting(expected);
460 self.expect_one_of(edible, inedible)
463 pub fn commit_expr_expecting(&self, e: @Expr, edible: token::Token) {
464 self.commit_expr(e, &[edible], &[])
467 // Commit to parsing a complete statement `s`, which expects to be
468 // followed by some token from the set edible + inedible. Check
469 // for recoverable input errors, discarding erroneous characters.
470 pub fn commit_stmt(&self, s: @Stmt, edible: &[token::Token], inedible: &[token::Token]) {
471 debug!("commit_stmt {:?}", s);
472 let _s = s; // unused, but future checks might want to inspect `s`.
473 if self.last_token.as_ref().map_default(false, |t| is_ident_or_path(*t)) {
474 let expected = vec::append(edible.to_owned(), inedible);
475 self.check_for_erroneous_unit_struct_expecting(expected);
477 self.expect_one_of(edible, inedible)
480 pub fn commit_stmt_expecting(&self, s: @Stmt, edible: token::Token) {
481 self.commit_stmt(s, &[edible], &[])
484 pub fn parse_ident(&self) -> ast::Ident {
485 self.check_strict_keywords();
486 self.check_reserved_keywords();
488 token::IDENT(i, _) => {
492 token::INTERPOLATED(token::nt_ident(*)) => {
493 self.bug("ident interpolation not converted to real token");
498 "expected ident, found `{}`",
499 self.this_token_to_str()
506 pub fn parse_path_list_ident(&self) -> ast::path_list_ident {
507 let lo = self.span.lo;
508 let ident = self.parse_ident();
509 let hi = self.last_span.hi;
510 spanned(lo, hi, ast::path_list_ident_ { name: ident,
511 id: ast::DUMMY_NODE_ID })
514 // consume token 'tok' if it exists. Returns true if the given
515 // token was present, false otherwise.
516 pub fn eat(&self, tok: &token::Token) -> bool {
517 let is_present = *self.token == *tok;
518 if is_present { self.bump() }
522 pub fn is_keyword(&self, kw: keywords::Keyword) -> bool {
523 token::is_keyword(kw, self.token)
526 // if the next token is the given keyword, eat it and return
527 // true. Otherwise, return false.
528 pub fn eat_keyword(&self, kw: keywords::Keyword) -> bool {
529 let is_kw = match *self.token {
530 token::IDENT(sid, false) => kw.to_ident().name == sid.name,
533 if is_kw { self.bump() }
537 // if the given word is not a keyword, signal an error.
538 // if the next token is not the given word, signal an error.
539 // otherwise, eat it.
540 pub fn expect_keyword(&self, kw: keywords::Keyword) {
541 if !self.eat_keyword(kw) {
544 "expected `{}`, found `{}`",
545 self.id_to_str(kw.to_ident()).to_str(),
546 self.this_token_to_str()
552 // signal an error if the given string is a strict keyword
553 pub fn check_strict_keywords(&self) {
554 if token::is_strict_keyword(self.token) {
555 self.span_err(*self.span,
556 format!("found `{}` in ident position", self.this_token_to_str()));
560 // signal an error if the current token is a reserved keyword
561 pub fn check_reserved_keywords(&self) {
562 if token::is_reserved_keyword(self.token) {
563 self.fatal(format!("`{}` is a reserved keyword", self.this_token_to_str()));
567 // expect and consume a GT. if a >> is seen, replace it
568 // with a single > and continue. If a GT is not seen,
570 pub fn expect_gt(&self) {
572 token::GT => self.bump(),
573 token::BINOP(token::SHR) => self.replace_token(
575 self.span.lo + BytePos(1u),
578 _ => self.fatal(format!("expected `{}`, found `{}`",
579 self.token_to_str(&token::GT),
580 self.this_token_to_str()))
584 // parse a sequence bracketed by '<' and '>', stopping
586 pub fn parse_seq_to_before_gt<T>(&self,
587 sep: Option<token::Token>,
588 f: &fn(&Parser) -> T)
590 let mut first = true;
591 let mut v = opt_vec::Empty;
592 while *self.token != token::GT
593 && *self.token != token::BINOP(token::SHR) {
596 if first { first = false; }
597 else { self.expect(t); }
606 pub fn parse_seq_to_gt<T>(&self,
607 sep: Option<token::Token>,
608 f: &fn(&Parser) -> T)
610 let v = self.parse_seq_to_before_gt(sep, f);
615 // parse a sequence, including the closing delimiter. The function
616 // f must consume tokens until reaching the next separator or
618 pub fn parse_seq_to_end<T>(&self,
621 f: &fn(&Parser) -> T)
623 let val = self.parse_seq_to_before_end(ket, sep, f);
628 // parse a sequence, not including the closing delimiter. The function
629 // f must consume tokens until reaching the next separator or
631 pub fn parse_seq_to_before_end<T>(&self,
634 f: &fn(&Parser) -> T)
636 let mut first: bool = true;
637 let mut v: ~[T] = ~[];
638 while *self.token != *ket {
641 if first { first = false; }
642 else { self.expect(t); }
646 if sep.trailing_sep_allowed && *self.token == *ket { break; }
652 // parse a sequence, including the closing delimiter. The function
653 // f must consume tokens until reaching the next separator or
655 pub fn parse_unspanned_seq<T>(&self,
659 f: &fn(&Parser) -> T)
662 let result = self.parse_seq_to_before_end(ket, sep, f);
667 // NB: Do not use this function unless you actually plan to place the
668 // spanned list in the AST.
669 pub fn parse_seq<T>(&self,
673 f: &fn(&Parser) -> T)
675 let lo = self.span.lo;
677 let result = self.parse_seq_to_before_end(ket, sep, f);
678 let hi = self.span.hi;
680 spanned(lo, hi, result)
683 // advance the parser by one token
685 *self.last_span = *self.span;
686 // Stash token for error recovery (sometimes; clone is not necessarily cheap).
687 *self.last_token = if is_ident_or_path(self.token) {
688 Some(~(*self.token).clone())
692 let next = if *self.buffer_start == *self.buffer_end {
693 self.reader.next_token()
695 // Avoid token copies with `util::replace`.
696 let buffer_start = *self.buffer_start as uint;
697 let next_index = (buffer_start + 1) & 3 as uint;
698 *self.buffer_start = next_index as int;
700 let placeholder = TokenAndSpan {
701 tok: token::UNDERSCORE,
704 util::replace(&mut self.buffer[buffer_start], placeholder)
706 *self.span = next.sp;
707 *self.token = next.tok;
708 *self.tokens_consumed += 1u;
711 // Advance the parser by one token and return the bumped token.
712 pub fn bump_and_get(&self) -> token::Token {
713 let old_token = util::replace(self.token, token::UNDERSCORE);
718 // EFFECT: replace the current token and span with the given one
719 pub fn replace_token(&self,
724 *self.span = mk_sp(lo, hi);
726 pub fn buffer_length(&self) -> int {
727 if *self.buffer_start <= *self.buffer_end {
728 return *self.buffer_end - *self.buffer_start;
730 return (4 - *self.buffer_start) + *self.buffer_end;
732 pub fn look_ahead<R>(&self, distance: uint, f: &fn(&token::Token) -> R)
734 let dist = distance as int;
735 while self.buffer_length() < dist {
736 self.buffer[*self.buffer_end] = self.reader.next_token();
737 *self.buffer_end = (*self.buffer_end + 1) & 3;
739 f(&self.buffer[(*self.buffer_start + dist - 1) & 3].tok)
741 pub fn fatal(&self, m: &str) -> ! {
742 self.sess.span_diagnostic.span_fatal(*self.span, m)
744 pub fn span_fatal(&self, sp: Span, m: &str) -> ! {
745 self.sess.span_diagnostic.span_fatal(sp, m)
747 pub fn span_note(&self, sp: Span, m: &str) {
748 self.sess.span_diagnostic.span_note(sp, m)
750 pub fn bug(&self, m: &str) -> ! {
751 self.sess.span_diagnostic.span_bug(*self.span, m)
753 pub fn warn(&self, m: &str) {
754 self.sess.span_diagnostic.span_warn(*self.span, m)
756 pub fn span_err(&self, sp: Span, m: &str) {
757 self.sess.span_diagnostic.span_err(sp, m)
759 pub fn abort_if_errors(&self) {
760 self.sess.span_diagnostic.handler().abort_if_errors();
763 pub fn id_to_str(&self, id: Ident) -> @str {
764 get_ident_interner().get(id.name)
767 // is this one of the keywords that signals a closure type?
768 pub fn token_is_closure_keyword(&self, tok: &token::Token) -> bool {
769 token::is_keyword(keywords::Unsafe, tok) ||
770 token::is_keyword(keywords::Once, tok) ||
771 token::is_keyword(keywords::Fn, tok)
774 pub fn token_is_lifetime(&self, tok: &token::Token) -> bool {
776 token::LIFETIME(*) => true,
781 pub fn get_lifetime(&self, tok: &token::Token) -> ast::Ident {
783 token::LIFETIME(ref ident) => *ident,
784 _ => self.bug("not a lifetime"),
788 // parse a ty_bare_fun type:
789 pub fn parse_ty_bare_fn(&self) -> ty_ {
792 extern "ABI" [unsafe] fn <'lt> (S) -> T
793 ^~~~^ ^~~~~~~^ ^~~~^ ^~^ ^
804 let opt_abis = self.parse_opt_abis();
805 let abis = opt_abis.unwrap_or(AbiSet::Rust());
806 let purity = self.parse_unsafety();
807 self.expect_keyword(keywords::Fn);
808 let (decl, lifetimes) = self.parse_ty_fn_decl();
809 return ty_bare_fn(@TyBareFn {
812 lifetimes: lifetimes,
817 // parse a ty_closure type
818 pub fn parse_ty_closure(&self,
820 region: Option<ast::Lifetime>)
824 (&|~|@) ['r] [unsafe] [once] fn [:Bounds] <'lt> (S) -> T
825 ^~~~~~^ ^~~^ ^~~~~~~^ ^~~~~^ ^~~~~~~~^ ^~~~^ ^~^ ^
827 | | | | | | | Return type
828 | | | | | | Argument types
830 | | | | Closure bounds
831 | | | Once-ness (a.k.a., affine)
838 // At this point, the allocation type and lifetime bound have been
841 let purity = self.parse_unsafety();
842 let onceness = parse_onceness(self);
843 self.expect_keyword(keywords::Fn);
844 let bounds = self.parse_optional_ty_param_bounds();
846 let (decl, lifetimes) = self.parse_ty_fn_decl();
848 return ty_closure(@TyClosure {
855 lifetimes: lifetimes,
858 fn parse_onceness(this: &Parser) -> Onceness {
859 if this.eat_keyword(keywords::Once) {
867 pub fn parse_unsafety(&self) -> purity {
868 if self.eat_keyword(keywords::Unsafe) {
875 // parse a function type (following the 'fn')
876 pub fn parse_ty_fn_decl(&self) -> (fn_decl, OptVec<ast::Lifetime>) {
887 let lifetimes = if self.eat(&token::LT) {
888 let lifetimes = self.parse_lifetimes();
895 let inputs = self.parse_unspanned_seq(
898 seq_sep_trailing_disallowed(token::COMMA),
899 |p| p.parse_arg_general(false)
901 let (ret_style, ret_ty) = self.parse_ret_ty();
902 let decl = ast::fn_decl {
910 // parse the methods in a trait declaration
911 pub fn parse_trait_methods(&self) -> ~[trait_method] {
912 do self.parse_unspanned_seq(
917 let attrs = p.parse_outer_attributes();
920 let vis_span = *self.span;
921 let vis = p.parse_visibility();
922 let pur = p.parse_fn_purity();
923 // NB: at the moment, trait methods are public by default; this
925 let ident = p.parse_ident();
927 let generics = p.parse_generics();
929 let (explicit_self, d) = do self.parse_fn_decl_with_self() |p| {
930 // This is somewhat dubious; We don't want to allow argument
931 // names to be left off if there is a definition...
932 p.parse_arg_general(false)
935 let hi = p.last_span.hi;
936 debug!("parse_trait_methods(): trait method signature ends in \
938 self.this_token_to_str());
942 debug!("parse_trait_methods(): parsing required method");
943 // NB: at the moment, visibility annotations on required
944 // methods are ignored; this could change.
945 if vis != ast::inherited {
946 self.obsolete(vis_span,
947 ObsoleteTraitFuncVisibility);
949 required(TypeMethod {
955 explicit_self: explicit_self,
956 id: ast::DUMMY_NODE_ID,
961 debug!("parse_trait_methods(): parsing provided method");
962 let (inner_attrs, body) =
963 p.parse_inner_attrs_and_block();
964 let attrs = vec::append(attrs, inner_attrs);
965 provided(@ast::method {
969 explicit_self: explicit_self,
973 id: ast::DUMMY_NODE_ID,
975 self_id: ast::DUMMY_NODE_ID,
983 "expected `;` or `\\{` but found `{}`",
984 self.this_token_to_str()
992 // parse a possibly mutable type
993 pub fn parse_mt(&self) -> mt {
994 let mutbl = self.parse_mutability();
995 let t = ~self.parse_ty(false);
996 mt { ty: t, mutbl: mutbl }
999 // parse [mut/const/imm] ID : TY
1000 // now used only by obsolete record syntax parser...
1001 pub fn parse_ty_field(&self) -> TypeField {
1002 let lo = self.span.lo;
1003 let mutbl = self.parse_mutability();
1004 let id = self.parse_ident();
1005 self.expect(&token::COLON);
1006 let ty = ~self.parse_ty(false);
1007 let hi = ty.span.hi;
1010 mt: ast::mt { ty: ty, mutbl: mutbl },
1011 span: mk_sp(lo, hi),
1015 // parse optional return type [ -> TY ] in function decl
1016 pub fn parse_ret_ty(&self) -> (ret_style, Ty) {
1017 return if self.eat(&token::RARROW) {
1018 let lo = self.span.lo;
1019 if self.eat(&token::NOT) {
1023 id: ast::DUMMY_NODE_ID,
1025 span: mk_sp(lo, self.last_span.hi)
1029 (return_val, self.parse_ty(false))
1032 let pos = self.span.lo;
1036 id: ast::DUMMY_NODE_ID,
1038 span: mk_sp(pos, pos),
1045 // Useless second parameter for compatibility with quasiquote macros.
1047 pub fn parse_ty(&self, _: bool) -> Ty {
1048 maybe_whole!(deref self, nt_ty);
1050 let lo = self.span.lo;
1052 let t = if *self.token == token::LPAREN {
1054 if *self.token == token::RPAREN {
1058 // (t) is a parenthesized ty
1059 // (t,) is the type of a tuple with only one field,
1061 let mut ts = ~[self.parse_ty(false)];
1062 let mut one_tuple = false;
1063 while *self.token == token::COMMA {
1065 if *self.token != token::RPAREN {
1066 ts.push(self.parse_ty(false));
1073 if ts.len() == 1 && !one_tuple {
1074 self.expect(&token::RPAREN);
1079 self.expect(&token::RPAREN);
1082 } else if *self.token == token::AT {
1085 self.parse_box_or_uniq_pointee(ManagedSigil, ty_box)
1086 } else if *self.token == token::TILDE {
1089 self.parse_box_or_uniq_pointee(OwnedSigil, ty_uniq)
1090 } else if *self.token == token::BINOP(token::STAR) {
1091 // STAR POINTER (bare pointer?)
1093 ty_ptr(self.parse_mt())
1094 } else if *self.token == token::LBRACKET {
1096 self.expect(&token::LBRACKET);
1097 let mt = mt { ty: ~self.parse_ty(false), mutbl: MutImmutable };
1099 // Parse the `, ..e` in `[ int, ..e ]`
1100 // where `e` is a const expression
1101 let t = match self.maybe_parse_fixed_vstore() {
1103 Some(suffix) => ty_fixed_length_vec(mt, suffix)
1105 self.expect(&token::RBRACKET);
1107 } else if *self.token == token::BINOP(token::AND) {
1110 self.parse_borrowed_pointee()
1111 } else if self.eat_keyword(keywords::Extern) {
1113 self.parse_ty_bare_fn()
1114 } else if self.token_is_closure_keyword(self.token) {
1116 let result = self.parse_ty_closure(ast::BorrowedSigil, None);
1117 self.obsolete(*self.last_span, ObsoleteBareFnType);
1119 } else if self.eat_keyword(keywords::Typeof) {
1121 // In order to not be ambiguous, the type must be surrounded by parens.
1122 self.expect(&token::LPAREN);
1123 let e = self.parse_expr();
1124 self.expect(&token::RPAREN);
1126 } else if *self.token == token::MOD_SEP
1127 || is_ident_or_path(self.token) {
1132 } = self.parse_path(LifetimeAndTypesAndBounds);
1133 ty_path(path, bounds, ast::DUMMY_NODE_ID)
1135 self.fatal(format!("expected type, found token {:?}", *self.token));
1138 let sp = mk_sp(lo, self.last_span.hi);
1139 Ty {id: ast::DUMMY_NODE_ID, node: t, span: sp}
1142 // parse the type following a @ or a ~
1143 pub fn parse_box_or_uniq_pointee(&self,
1145 ctor: &fn(v: mt) -> ty_) -> ty_ {
1146 // ~'foo fn() or ~fn() are parsed directly as fn types:
1148 token::LIFETIME(*) => {
1149 let lifetime = self.parse_lifetime();
1150 return self.parse_ty_closure(sigil, Some(lifetime));
1153 token::IDENT(*) => {
1154 if self.token_is_closure_keyword(self.token) {
1155 return self.parse_ty_closure(sigil, None);
1161 // other things are parsed as @/~ + a type. Note that constructs like
1162 // @[] and @str will be resolved during typeck to slices and so forth,
1163 // rather than boxed ptrs. But the special casing of str/vec is not
1164 // reflected in the AST type.
1165 if sigil == OwnedSigil {
1166 ctor(mt { ty: ~self.parse_ty(false), mutbl: MutImmutable })
1168 ctor(self.parse_mt())
1172 pub fn parse_borrowed_pointee(&self) -> ty_ {
1173 // look for `&'lt` or `&'foo ` and interpret `foo` as the region name:
1174 let opt_lifetime = self.parse_opt_lifetime();
1176 if self.token_is_closure_keyword(self.token) {
1177 return self.parse_ty_closure(BorrowedSigil, opt_lifetime);
1180 let mt = self.parse_mt();
1181 return ty_rptr(opt_lifetime, mt);
1184 pub fn is_named_argument(&self) -> bool {
1185 let offset = match *self.token {
1186 token::BINOP(token::AND) => 1,
1187 token::BINOP(token::MINUS) => 1,
1189 token::BINOP(token::PLUS) => {
1190 if self.look_ahead(1, |t| *t == token::BINOP(token::PLUS)) {
1199 debug!("parser is_named_argument offset:{}", offset);
1202 is_plain_ident_or_underscore(&*self.token)
1203 && self.look_ahead(1, |t| *t == token::COLON)
1205 self.look_ahead(offset, |t| is_plain_ident_or_underscore(t))
1206 && self.look_ahead(offset + 1, |t| *t == token::COLON)
1210 // This version of parse arg doesn't necessarily require
1211 // identifier names.
1212 pub fn parse_arg_general(&self, require_name: bool) -> arg {
1213 let is_mutbl = self.eat_keyword(keywords::Mut);
1214 let pat = if require_name || self.is_named_argument() {
1215 debug!("parse_arg_general parse_pat (require_name:{:?})",
1217 let pat = self.parse_pat();
1219 if is_mutbl && !ast_util::pat_is_ident(pat) {
1220 self.obsolete(*self.span, ObsoleteMutWithMultipleBindings)
1223 self.expect(&token::COLON);
1226 debug!("parse_arg_general ident_to_pat");
1227 ast_util::ident_to_pat(ast::DUMMY_NODE_ID,
1229 special_idents::invalid)
1232 let t = self.parse_ty(false);
1238 id: ast::DUMMY_NODE_ID,
1242 // parse a single function argument
1243 pub fn parse_arg(&self) -> arg {
1244 self.parse_arg_general(true)
1247 // parse an argument in a lambda header e.g. |arg, arg|
1248 pub fn parse_fn_block_arg(&self) -> arg {
1249 let is_mutbl = self.eat_keyword(keywords::Mut);
1250 let pat = self.parse_pat();
1251 let t = if self.eat(&token::COLON) {
1252 self.parse_ty(false)
1255 id: ast::DUMMY_NODE_ID,
1257 span: mk_sp(self.span.lo, self.span.hi),
1264 id: ast::DUMMY_NODE_ID
1268 pub fn maybe_parse_fixed_vstore(&self) -> Option<@ast::Expr> {
1269 if *self.token == token::COMMA &&
1270 self.look_ahead(1, |t| *t == token::DOTDOT) {
1273 Some(self.parse_expr())
1279 // matches token_lit = LIT_INT | ...
1280 pub fn lit_from_token(&self, tok: &token::Token) -> lit_ {
1282 token::LIT_CHAR(i) => lit_char(i),
1283 token::LIT_INT(i, it) => lit_int(i, it),
1284 token::LIT_UINT(u, ut) => lit_uint(u, ut),
1285 token::LIT_INT_UNSUFFIXED(i) => lit_int_unsuffixed(i),
1286 token::LIT_FLOAT(s, ft) => lit_float(self.id_to_str(s), ft),
1287 token::LIT_FLOAT_UNSUFFIXED(s) =>
1288 lit_float_unsuffixed(self.id_to_str(s)),
1289 token::LIT_STR(s) => lit_str(self.id_to_str(s), ast::CookedStr),
1290 token::LIT_STR_RAW(s, n) => lit_str(self.id_to_str(s), ast::RawStr(n)),
1291 token::LPAREN => { self.expect(&token::RPAREN); lit_nil },
1292 _ => { self.unexpected_last(tok); }
1296 // matches lit = true | false | token_lit
1297 pub fn parse_lit(&self) -> lit {
1298 let lo = self.span.lo;
1299 let lit = if self.eat_keyword(keywords::True) {
1301 } else if self.eat_keyword(keywords::False) {
1304 let token = self.bump_and_get();
1305 let lit = self.lit_from_token(&token);
1308 codemap::Spanned { node: lit, span: mk_sp(lo, self.last_span.hi) }
1311 // matches '-' lit | lit
1312 pub fn parse_literal_maybe_minus(&self) -> @Expr {
1313 let minus_lo = self.span.lo;
1314 let minus_present = self.eat(&token::BINOP(token::MINUS));
1316 let lo = self.span.lo;
1317 let literal = @self.parse_lit();
1318 let hi = self.span.hi;
1319 let expr = self.mk_expr(lo, hi, ExprLit(literal));
1322 let minus_hi = self.span.hi;
1323 self.mk_expr(minus_lo, minus_hi, self.mk_unary(UnNeg, expr))
1329 /// Parses a path and optional type parameter bounds, depending on the
1330 /// mode. The `mode` parameter determines whether lifetimes, types, and/or
1331 /// bounds are permitted and whether `::` must precede type parameter
1333 pub fn parse_path(&self, mode: PathParsingMode) -> PathAndBounds {
1334 // Check for a whole path...
1335 let found = match *self.token {
1336 INTERPOLATED(token::nt_path(_)) => Some(self.bump_and_get()),
1340 Some(INTERPOLATED(token::nt_path(~path))) => {
1341 return PathAndBounds {
1349 let lo = self.span.lo;
1350 let is_global = self.eat(&token::MOD_SEP);
1352 // Parse any number of segments and bound sets. A segment is an
1353 // identifier followed by an optional lifetime and a set of types.
1354 // A bound set is a set of type parameter bounds.
1355 let mut segments = ~[];
1357 // First, parse an identifier.
1359 token::IDENT(*) => {}
1362 let identifier = self.parse_ident();
1364 // Next, parse a colon and bounded type parameters, if applicable.
1365 let bound_set = if mode == LifetimeAndTypesAndBounds {
1366 self.parse_optional_ty_param_bounds()
1371 // Parse the '::' before type parameters if it's required. If
1372 // it is required and wasn't present, then we're done.
1373 if mode == LifetimeAndTypesWithColons &&
1374 !self.eat(&token::MOD_SEP) {
1375 segments.push(PathSegmentAndBoundSet {
1376 segment: ast::PathSegment {
1377 identifier: identifier,
1379 types: opt_vec::Empty,
1381 bound_set: bound_set
1386 // Parse the `<` before the lifetime and types, if applicable.
1387 let (any_lifetime_or_types, optional_lifetime, types) =
1388 if mode != NoTypesAllowed && self.eat(&token::LT) {
1389 // Parse an optional lifetime.
1390 let optional_lifetime = match *self.token {
1391 token::LIFETIME(*) => Some(self.parse_lifetime()),
1395 // Parse type parameters.
1396 let mut types = opt_vec::Empty;
1397 let mut need_comma = optional_lifetime.is_some();
1399 // We're done if we see a `>`.
1401 token::GT | token::BINOP(token::SHR) => {
1409 self.expect(&token::COMMA)
1414 types.push(self.parse_ty(false))
1417 (true, optional_lifetime, types)
1419 (false, None, opt_vec::Empty)
1422 // Assemble and push the result.
1423 segments.push(PathSegmentAndBoundSet {
1424 segment: ast::PathSegment {
1425 identifier: identifier,
1426 lifetime: optional_lifetime,
1429 bound_set: bound_set
1432 // We're done if we don't see a '::', unless the mode required
1433 // a double colon to get here in the first place.
1434 if !(mode == LifetimeAndTypesWithColons &&
1435 !any_lifetime_or_types) {
1436 if !self.eat(&token::MOD_SEP) {
1442 // Assemble the span.
1443 let span = mk_sp(lo, self.last_span.hi);
1445 // Assemble the path segments.
1446 let mut path_segments = ~[];
1447 let mut bounds = None;
1448 let last_segment_index = segments.len() - 1;
1449 for (i, segment_and_bounds) in segments.move_iter().enumerate() {
1450 let PathSegmentAndBoundSet {
1452 bound_set: bound_set
1453 } = segment_and_bounds;
1454 path_segments.push(segment);
1456 if bound_set.is_some() {
1457 if i != last_segment_index {
1459 "type parameter bounds are allowed only \
1460 before the last segment in a path")
1467 // Assemble the result.
1468 let path_and_bounds = PathAndBounds {
1472 segments: path_segments,
1480 /// parses 0 or 1 lifetime
1481 pub fn parse_opt_lifetime(&self) -> Option<ast::Lifetime> {
1483 token::LIFETIME(*) => {
1484 Some(self.parse_lifetime())
1492 /// Parses a single lifetime
1493 // matches lifetime = LIFETIME
1494 pub fn parse_lifetime(&self) -> ast::Lifetime {
1496 token::LIFETIME(i) => {
1497 let span = self.span;
1499 return ast::Lifetime {
1500 id: ast::DUMMY_NODE_ID,
1506 self.fatal(format!("Expected a lifetime name"));
1511 // matches lifetimes = ( lifetime ) | ( lifetime , lifetimes )
1512 // actually, it matches the empty one too, but putting that in there
1513 // messes up the grammar....
1514 pub fn parse_lifetimes(&self) -> OptVec<ast::Lifetime> {
1517 * Parses zero or more comma separated lifetimes.
1518 * Expects each lifetime to be followed by either
1519 * a comma or `>`. Used when parsing type parameter
1520 * lists, where we expect something like `<'a, 'b, T>`.
1523 let mut res = opt_vec::Empty;
1526 token::LIFETIME(_) => {
1527 res.push(self.parse_lifetime());
1535 token::COMMA => { self.bump();}
1536 token::GT => { return res; }
1537 token::BINOP(token::SHR) => { return res; }
1539 self.fatal(format!("expected `,` or `>` after lifetime name, got: {:?}",
1546 pub fn token_is_mutability(&self, tok: &token::Token) -> bool {
1547 token::is_keyword(keywords::Mut, tok) ||
1548 token::is_keyword(keywords::Const, tok)
1551 // parse mutability declaration (mut/const/imm)
1552 pub fn parse_mutability(&self) -> Mutability {
1553 if self.eat_keyword(keywords::Mut) {
1555 } else if self.eat_keyword(keywords::Const) {
1556 self.obsolete(*self.last_span, ObsoleteConstPointer);
1563 // parse ident COLON expr
1564 pub fn parse_field(&self) -> Field {
1565 let lo = self.span.lo;
1566 let i = self.parse_ident();
1567 self.expect(&token::COLON);
1568 let e = self.parse_expr();
1572 span: mk_sp(lo, e.span.hi),
1576 pub fn mk_expr(&self, lo: BytePos, hi: BytePos, node: Expr_) -> @Expr {
1578 id: ast::DUMMY_NODE_ID,
1580 span: mk_sp(lo, hi),
1584 pub fn mk_unary(&self, unop: ast::UnOp, expr: @Expr) -> ast::Expr_ {
1585 ExprUnary(ast::DUMMY_NODE_ID, unop, expr)
1588 pub fn mk_binary(&self, binop: ast::BinOp, lhs: @Expr, rhs: @Expr) -> ast::Expr_ {
1589 ExprBinary(ast::DUMMY_NODE_ID, binop, lhs, rhs)
1592 pub fn mk_call(&self, f: @Expr, args: ~[@Expr], sugar: CallSugar) -> ast::Expr_ {
1593 ExprCall(f, args, sugar)
1596 pub fn mk_method_call(&self,
1601 sugar: CallSugar) -> ast::Expr_ {
1602 ExprMethodCall(ast::DUMMY_NODE_ID, rcvr, ident, tps, args, sugar)
1605 pub fn mk_index(&self, expr: @Expr, idx: @Expr) -> ast::Expr_ {
1606 ExprIndex(ast::DUMMY_NODE_ID, expr, idx)
1609 pub fn mk_field(&self, expr: @Expr, ident: Ident, tys: ~[Ty]) -> ast::Expr_ {
1610 ExprField(expr, ident, tys)
1613 pub fn mk_assign_op(&self, binop: ast::BinOp, lhs: @Expr, rhs: @Expr) -> ast::Expr_ {
1614 ExprAssignOp(ast::DUMMY_NODE_ID, binop, lhs, rhs)
1617 pub fn mk_mac_expr(&self, lo: BytePos, hi: BytePos, m: mac_) -> @Expr {
1619 id: ast::DUMMY_NODE_ID,
1620 node: ExprMac(codemap::Spanned {node: m, span: mk_sp(lo, hi)}),
1621 span: mk_sp(lo, hi),
1625 pub fn mk_lit_u32(&self, i: u32) -> @Expr {
1626 let span = self.span;
1627 let lv_lit = @codemap::Spanned {
1628 node: lit_uint(i as u64, ty_u32),
1633 id: ast::DUMMY_NODE_ID,
1634 node: ExprLit(lv_lit),
1639 // at the bottom (top?) of the precedence hierarchy,
1640 // parse things like parenthesized exprs,
1641 // macros, return, etc.
1642 pub fn parse_bottom_expr(&self) -> @Expr {
1643 maybe_whole_expr!(self);
1645 let lo = self.span.lo;
1646 let mut hi = self.span.hi;
1650 if *self.token == token::LPAREN {
1652 // (e) is parenthesized e
1653 // (e,) is a tuple with only one field, e
1654 let mut trailing_comma = false;
1655 if *self.token == token::RPAREN {
1658 let lit = @spanned(lo, hi, lit_nil);
1659 return self.mk_expr(lo, hi, ExprLit(lit));
1661 let mut es = ~[self.parse_expr()];
1662 self.commit_expr(*es.last(), &[], &[token::COMMA, token::RPAREN]);
1663 while *self.token == token::COMMA {
1665 if *self.token != token::RPAREN {
1666 es.push(self.parse_expr());
1667 self.commit_expr(*es.last(), &[], &[token::COMMA, token::RPAREN]);
1670 trailing_comma = true;
1674 self.commit_expr_expecting(*es.last(), token::RPAREN);
1676 return if es.len() == 1 && !trailing_comma {
1677 self.mk_expr(lo, self.span.hi, ExprParen(es[0]))
1680 self.mk_expr(lo, hi, ExprTup(es))
1682 } else if *self.token == token::LBRACE {
1684 let blk = self.parse_block_tail(lo, DefaultBlock);
1685 return self.mk_expr(blk.span.lo, blk.span.hi,
1687 } else if token::is_bar(&*self.token) {
1688 return self.parse_lambda_expr();
1689 } else if self.eat_keyword(keywords::Self) {
1692 } else if self.eat_keyword(keywords::If) {
1693 return self.parse_if_expr();
1694 } else if self.eat_keyword(keywords::For) {
1695 return self.parse_for_expr(None);
1696 } else if self.eat_keyword(keywords::Do) {
1697 return self.parse_sugary_call_expr(lo, ~"do", DoSugar,
1699 } else if self.eat_keyword(keywords::While) {
1700 return self.parse_while_expr();
1701 } else if self.token_is_lifetime(&*self.token) {
1702 let lifetime = self.get_lifetime(&*self.token);
1704 self.expect(&token::COLON);
1705 if self.eat_keyword(keywords::For) {
1706 return self.parse_for_expr(Some(lifetime))
1707 } else if self.eat_keyword(keywords::Loop) {
1708 return self.parse_loop_expr(Some(lifetime))
1710 self.fatal("expected `for` or `loop` after a label")
1712 } else if self.eat_keyword(keywords::Loop) {
1713 return self.parse_loop_expr(None);
1714 } else if self.eat_keyword(keywords::Continue) {
1715 let lo = self.span.lo;
1716 let ex = if self.token_is_lifetime(&*self.token) {
1717 let lifetime = self.get_lifetime(&*self.token);
1719 ExprAgain(Some(lifetime.name))
1723 let hi = self.span.hi;
1724 return self.mk_expr(lo, hi, ex);
1725 } else if self.eat_keyword(keywords::Match) {
1726 return self.parse_match_expr();
1727 } else if self.eat_keyword(keywords::Unsafe) {
1728 return self.parse_block_expr(lo, UnsafeBlock(ast::UserProvided));
1729 } else if *self.token == token::LBRACKET {
1731 let mutbl = MutImmutable;
1733 if *self.token == token::RBRACKET {
1736 ex = ExprVec(~[], mutbl);
1739 let first_expr = self.parse_expr();
1740 if *self.token == token::COMMA &&
1741 self.look_ahead(1, |t| *t == token::DOTDOT) {
1742 // Repeating vector syntax: [ 0, ..512 ]
1745 let count = self.parse_expr();
1746 self.expect(&token::RBRACKET);
1747 ex = ExprRepeat(first_expr, count, mutbl);
1748 } else if *self.token == token::COMMA {
1749 // Vector with two or more elements.
1751 let remaining_exprs = self.parse_seq_to_end(
1753 seq_sep_trailing_allowed(token::COMMA),
1756 ex = ExprVec(~[first_expr] + remaining_exprs, mutbl);
1758 // Vector with one element.
1759 self.expect(&token::RBRACKET);
1760 ex = ExprVec(~[first_expr], mutbl);
1763 hi = self.last_span.hi;
1764 } else if self.eat_keyword(keywords::__LogLevel) {
1765 // LOG LEVEL expression
1766 self.expect(&token::LPAREN);
1769 self.expect(&token::RPAREN);
1770 } else if self.eat_keyword(keywords::Return) {
1771 // RETURN expression
1772 if can_begin_expr(&*self.token) {
1773 let e = self.parse_expr();
1775 ex = ExprRet(Some(e));
1776 } else { ex = ExprRet(None); }
1777 } else if self.eat_keyword(keywords::Break) {
1779 if self.token_is_lifetime(&*self.token) {
1780 let lifetime = self.get_lifetime(&*self.token);
1782 ex = ExprBreak(Some(lifetime.name));
1784 ex = ExprBreak(None);
1787 } else if *self.token == token::MOD_SEP ||
1788 is_ident(&*self.token) && !self.is_keyword(keywords::True) &&
1789 !self.is_keyword(keywords::False) {
1790 let pth = self.parse_path(LifetimeAndTypesWithColons).path;
1792 // `!`, as an operator, is prefix, so we know this isn't that
1793 if *self.token == token::NOT {
1794 // MACRO INVOCATION expression
1797 token::LPAREN | token::LBRACE => {}
1798 _ => self.fatal("expected open delimiter")
1801 let ket = token::flip_delimiter(&*self.token);
1804 let tts = self.parse_seq_to_end(&ket,
1806 |p| p.parse_token_tree());
1807 let hi = self.span.hi;
1809 return self.mk_mac_expr(lo, hi, mac_invoc_tt(pth, tts, EMPTY_CTXT));
1810 } else if *self.token == token::LBRACE {
1811 // This might be a struct literal.
1812 if self.looking_at_record_literal() {
1813 // It's a struct literal.
1815 let mut fields = ~[];
1816 let mut base = None;
1818 fields.push(self.parse_field());
1819 while *self.token != token::RBRACE {
1820 self.commit_expr(fields.last().expr, &[token::COMMA], &[token::RBRACE]);
1822 if self.eat(&token::DOTDOT) {
1823 base = Some(self.parse_expr());
1827 if *self.token == token::RBRACE {
1828 // Accept an optional trailing comma.
1831 fields.push(self.parse_field());
1835 self.commit_expr_expecting(fields.last().expr, token::RBRACE);
1836 ex = ExprStruct(pth, fields, base);
1837 return self.mk_expr(lo, hi, ex);
1844 // other literal expression
1845 let lit = self.parse_lit();
1850 return self.mk_expr(lo, hi, ex);
1853 // parse a block or unsafe block
1854 pub fn parse_block_expr(&self, lo: BytePos, blk_mode: BlockCheckMode)
1856 self.expect(&token::LBRACE);
1857 let blk = self.parse_block_tail(lo, blk_mode);
1858 return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk));
1861 // parse a.b or a(13) or a[4] or just a
1862 pub fn parse_dot_or_call_expr(&self) -> @Expr {
1863 let b = self.parse_bottom_expr();
1864 self.parse_dot_or_call_expr_with(b)
1867 pub fn parse_dot_or_call_expr_with(&self, e0: @Expr) -> @Expr {
1873 if self.eat(&token::DOT) {
1875 token::IDENT(i, _) => {
1878 let (_, tys) = if self.eat(&token::MOD_SEP) {
1879 self.expect(&token::LT);
1880 self.parse_generic_values_after_lt()
1882 (opt_vec::Empty, ~[])
1885 // expr.f() method call
1888 let es = self.parse_unspanned_seq(
1891 seq_sep_trailing_disallowed(token::COMMA),
1896 let nd = self.mk_method_call(e, i, tys, es, NoSugar);
1897 e = self.mk_expr(lo, hi, nd);
1900 e = self.mk_expr(lo, hi, self.mk_field(e, i, tys));
1904 _ => self.unexpected()
1908 if self.expr_is_complete(e) { break; }
1912 let es = self.parse_unspanned_seq(
1915 seq_sep_trailing_disallowed(token::COMMA),
1920 let nd = self.mk_call(e, es, NoSugar);
1921 e = self.mk_expr(lo, hi, nd);
1925 token::LBRACKET => {
1927 let ix = self.parse_expr();
1929 self.commit_expr_expecting(ix, token::RBRACKET);
1930 e = self.mk_expr(lo, hi, self.mk_index(e, ix));
1939 // parse an optional separator followed by a kleene-style
1940 // repetition token (+ or *).
1941 pub fn parse_sep_and_zerok(&self) -> (Option<token::Token>, bool) {
1942 fn parse_zerok(parser: &Parser) -> Option<bool> {
1943 match *parser.token {
1944 token::BINOP(token::STAR) | token::BINOP(token::PLUS) => {
1945 let zerok = *parser.token == token::BINOP(token::STAR);
1953 match parse_zerok(self) {
1954 Some(zerok) => return (None, zerok),
1958 let separator = self.bump_and_get();
1959 match parse_zerok(self) {
1960 Some(zerok) => (Some(separator), zerok),
1961 None => self.fatal("expected `*` or `+`")
1965 // parse a single token tree from the input.
1966 pub fn parse_token_tree(&self) -> token_tree {
1967 // FIXME #6994: currently, this is too eager. It
1968 // parses token trees but also identifies tt_seq's
1969 // and tt_nonterminals; it's too early to know yet
1970 // whether something will be a nonterminal or a seq
1972 maybe_whole!(deref self, nt_tt);
1974 // this is the fall-through for the 'match' below.
1975 // invariants: the current token is not a left-delimiter,
1976 // not an EOF, and not the desired right-delimiter (if
1977 // it were, parse_seq_to_before_end would have prevented
1978 // reaching this point.
1979 fn parse_non_delim_tt_tok(p: &Parser) -> token_tree {
1980 maybe_whole!(deref p, nt_tt);
1982 token::RPAREN | token::RBRACE | token::RBRACKET
1986 "incorrect close delimiter: `{}`",
1987 p.this_token_to_str()
1991 /* we ought to allow different depths of unquotation */
1992 token::DOLLAR if *p.quote_depth > 0u => {
1996 if *p.token == token::LPAREN {
1997 let seq = p.parse_seq(
2001 |p| p.parse_token_tree()
2003 let (s, z) = p.parse_sep_and_zerok();
2004 let seq = match seq {
2005 Spanned { node, _ } => node,
2008 mk_sp(sp.lo, p.span.hi),
2014 tt_nonterminal(sp, p.parse_ident())
2023 // turn the next token into a tt_tok:
2024 fn parse_any_tt_tok(p: &Parser) -> token_tree{
2025 tt_tok(*p.span, p.bump_and_get())
2030 for sp in self.open_braces.iter() {
2031 self.span_note(*sp, "Did you mean to close this delimiter?");
2033 // There shouldn't really be a span, but it's easier for the test runner
2034 // if we give it one
2035 self.fatal("This file contains an un-closed delimiter ");
2037 token::LPAREN | token::LBRACE | token::LBRACKET => {
2038 let close_delim = token::flip_delimiter(&*self.token);
2040 // Parse the open delimiter.
2041 (*self.open_braces).push(*self.span);
2042 let mut result = ~[parse_any_tt_tok(self)];
2045 self.parse_seq_to_before_end(&close_delim,
2047 |p| p.parse_token_tree());
2048 result.push_all_move(trees);
2050 // Parse the close delimiter.
2051 result.push(parse_any_tt_tok(self));
2052 self.open_braces.pop();
2054 tt_delim(@mut result)
2056 _ => parse_non_delim_tt_tok(self)
2060 // parse a stream of tokens into a list of token_trees,
2062 pub fn parse_all_token_trees(&self) -> ~[token_tree] {
2064 while *self.token != token::EOF {
2065 tts.push(self.parse_token_tree());
2070 pub fn parse_matchers(&self) -> ~[matcher] {
2071 // unification of matchers and token_trees would vastly improve
2072 // the interpolation of matchers
2073 maybe_whole!(self, nt_matchers);
2074 let name_idx = @mut 0u;
2076 token::LBRACE | token::LPAREN | token::LBRACKET => {
2077 let other_delimiter = token::flip_delimiter(self.token);
2079 self.parse_matcher_subseq_upto(name_idx, &other_delimiter)
2081 _ => self.fatal("expected open delimiter")
2085 // This goofy function is necessary to correctly match parens in matchers.
2086 // Otherwise, `$( ( )` would be a valid matcher, and `$( () )` would be
2087 // invalid. It's similar to common::parse_seq.
2088 pub fn parse_matcher_subseq_upto(&self,
2089 name_idx: @mut uint,
2092 let mut ret_val = ~[];
2093 let mut lparens = 0u;
2095 while *self.token != *ket || lparens > 0u {
2096 if *self.token == token::LPAREN { lparens += 1u; }
2097 if *self.token == token::RPAREN { lparens -= 1u; }
2098 ret_val.push(self.parse_matcher(name_idx));
2106 pub fn parse_matcher(&self, name_idx: @mut uint) -> matcher {
2107 let lo = self.span.lo;
2109 let m = if *self.token == token::DOLLAR {
2111 if *self.token == token::LPAREN {
2112 let name_idx_lo = *name_idx;
2114 let ms = self.parse_matcher_subseq_upto(name_idx,
2117 self.fatal("repetition body must be nonempty");
2119 let (sep, zerok) = self.parse_sep_and_zerok();
2120 match_seq(ms, sep, zerok, name_idx_lo, *name_idx)
2122 let bound_to = self.parse_ident();
2123 self.expect(&token::COLON);
2124 let nt_name = self.parse_ident();
2125 let m = match_nonterminal(bound_to, nt_name, *name_idx);
2130 match_tok(self.bump_and_get())
2133 return spanned(lo, self.span.hi, m);
2136 // parse a prefix-operator expr
2137 pub fn parse_prefix_expr(&self) -> @Expr {
2138 let lo = self.span.lo;
2145 let e = self.parse_prefix_expr();
2147 ex = self.mk_unary(UnNot, e);
2149 token::BINOP(b) => {
2153 let e = self.parse_prefix_expr();
2155 ex = self.mk_unary(UnNeg, e);
2159 let e = self.parse_prefix_expr();
2161 ex = self.mk_unary(UnDeref, e);
2165 let _lt = self.parse_opt_lifetime();
2166 let m = self.parse_mutability();
2167 let e = self.parse_prefix_expr();
2169 // HACK: turn &[...] into a &-evec
2171 ExprVec(*) | ExprLit(@codemap::Spanned {
2172 node: lit_str(*), span: _
2174 if m == MutImmutable => {
2175 ExprVstore(e, ExprVstoreSlice)
2177 ExprVec(*) if m == MutMutable => {
2178 ExprVstore(e, ExprVstoreMutSlice)
2180 _ => ExprAddrOf(m, e)
2183 _ => return self.parse_dot_or_call_expr()
2188 let m = self.parse_mutability();
2189 let e = self.parse_prefix_expr();
2191 // HACK: turn @[...] into a @-evec
2193 ExprVec(*) | ExprRepeat(*) if m == MutMutable =>
2194 ExprVstore(e, ExprVstoreMutBox),
2196 ExprLit(@codemap::Spanned { node: lit_str(*), span: _}) |
2197 ExprRepeat(*) if m == MutImmutable => ExprVstore(e, ExprVstoreBox),
2198 _ => self.mk_unary(UnBox(m), e)
2204 let e = self.parse_prefix_expr();
2206 // HACK: turn ~[...] into a ~-evec
2209 ExprLit(@codemap::Spanned { node: lit_str(*), span: _}) |
2210 ExprRepeat(*) => ExprVstore(e, ExprVstoreUniq),
2211 _ => self.mk_unary(UnUniq, e)
2214 _ => return self.parse_dot_or_call_expr()
2216 return self.mk_expr(lo, hi, ex);
2219 // parse an expression of binops
2220 pub fn parse_binops(&self) -> @Expr {
2221 self.parse_more_binops(self.parse_prefix_expr(), 0)
2224 // parse an expression of binops of at least min_prec precedence
2225 pub fn parse_more_binops(&self, lhs: @Expr, min_prec: uint) -> @Expr {
2226 if self.expr_is_complete(lhs) { return lhs; }
2228 // Prevent dynamic borrow errors later on by limiting the
2229 // scope of the borrows.
2231 let token: &token::Token = self.token;
2232 let restriction: &restriction = self.restriction;
2233 match (token, restriction) {
2234 (&token::BINOP(token::OR), &RESTRICT_NO_BAR_OP) => return lhs,
2235 (&token::BINOP(token::OR),
2236 &RESTRICT_NO_BAR_OR_DOUBLEBAR_OP) => return lhs,
2237 (&token::OROR, &RESTRICT_NO_BAR_OR_DOUBLEBAR_OP) => return lhs,
2242 let cur_opt = token_to_binop(self.token);
2245 let cur_prec = operator_prec(cur_op);
2246 if cur_prec > min_prec {
2248 let expr = self.parse_prefix_expr();
2249 let rhs = self.parse_more_binops(expr, cur_prec);
2250 let bin = self.mk_expr(lhs.span.lo, rhs.span.hi,
2251 self.mk_binary(cur_op, lhs, rhs));
2252 self.parse_more_binops(bin, min_prec)
2258 if as_prec > min_prec && self.eat_keyword(keywords::As) {
2259 let rhs = self.parse_ty(true);
2260 let _as = self.mk_expr(lhs.span.lo,
2262 ExprCast(lhs, rhs));
2263 self.parse_more_binops(_as, min_prec)
2271 // parse an assignment expression....
2272 // actually, this seems to be the main entry point for
2273 // parsing an arbitrary expression.
2274 pub fn parse_assign_expr(&self) -> @Expr {
2275 let lo = self.span.lo;
2276 let lhs = self.parse_binops();
2280 let rhs = self.parse_expr();
2281 self.mk_expr(lo, rhs.span.hi, ExprAssign(lhs, rhs))
2283 token::BINOPEQ(op) => {
2285 let rhs = self.parse_expr();
2286 let aop = match op {
2287 token::PLUS => BiAdd,
2288 token::MINUS => BiSub,
2289 token::STAR => BiMul,
2290 token::SLASH => BiDiv,
2291 token::PERCENT => BiRem,
2292 token::CARET => BiBitXor,
2293 token::AND => BiBitAnd,
2294 token::OR => BiBitOr,
2295 token::SHL => BiShl,
2298 self.mk_expr(lo, rhs.span.hi,
2299 self.mk_assign_op(aop, lhs, rhs))
2302 self.obsolete(*self.span, ObsoleteSwap);
2304 // Ignore what we get, this is an error anyway
2306 self.mk_expr(lo, self.span.hi, ExprBreak(None))
2314 // parse an 'if' expression ('if' token already eaten)
2315 pub fn parse_if_expr(&self) -> @Expr {
2316 let lo = self.last_span.lo;
2317 let cond = self.parse_expr();
2318 let thn = self.parse_block();
2319 let mut els: Option<@Expr> = None;
2320 let mut hi = thn.span.hi;
2321 if self.eat_keyword(keywords::Else) {
2322 let elexpr = self.parse_else_expr();
2324 hi = elexpr.span.hi;
2326 self.mk_expr(lo, hi, ExprIf(cond, thn, els))
2329 // `|args| { ... }` or `{ ...}` like in `do` expressions
2330 pub fn parse_lambda_block_expr(&self) -> @Expr {
2331 self.parse_lambda_expr_(
2334 token::BINOP(token::OR) | token::OROR => {
2335 self.parse_fn_block_decl()
2338 // No argument list - `do foo {`
2342 id: ast::DUMMY_NODE_ID,
2352 let blk = self.parse_block();
2353 self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk))
2358 pub fn parse_lambda_expr(&self) -> @Expr {
2359 self.parse_lambda_expr_(|| self.parse_fn_block_decl(),
2360 || self.parse_expr())
2363 // parse something of the form |args| expr
2364 // this is used both in parsing a lambda expr
2365 // and in parsing a block expr as e.g. in for...
2366 pub fn parse_lambda_expr_(&self,
2367 parse_decl: &fn() -> fn_decl,
2368 parse_body: &fn() -> @Expr)
2370 let lo = self.last_span.lo;
2371 let decl = parse_decl();
2372 let body = parse_body();
2373 let fakeblock = ast::Block {
2377 id: ast::DUMMY_NODE_ID,
2378 rules: DefaultBlock,
2382 return self.mk_expr(lo, body.span.hi,
2383 ExprFnBlock(decl, fakeblock));
2386 pub fn parse_else_expr(&self) -> @Expr {
2387 if self.eat_keyword(keywords::If) {
2388 return self.parse_if_expr();
2390 let blk = self.parse_block();
2391 return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk));
2395 // parse a 'for' .. 'in' expression ('for' token already eaten)
2396 pub fn parse_for_expr(&self, opt_ident: Option<ast::Ident>) -> @Expr {
2397 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
2399 let lo = self.last_span.lo;
2400 let pat = self.parse_pat();
2401 self.expect_keyword(keywords::In);
2402 let expr = self.parse_expr();
2403 let loop_block = self.parse_block();
2404 let hi = self.span.hi;
2406 self.mk_expr(lo, hi, ExprForLoop(pat, expr, loop_block, opt_ident))
2410 // parse a 'for' or 'do'.
2411 // the 'for' and 'do' expressions parse as calls, but look like
2412 // function calls followed by a closure expression.
2413 pub fn parse_sugary_call_expr(&self, lo: BytePos,
2416 ctor: &fn(v: @Expr) -> Expr_)
2418 // Parse the callee `foo` in
2421 // etc, or the portion of the call expression before the lambda in
2424 // for foo.bar(a) || {
2425 // Turn on the restriction to stop at | or || so we can parse
2426 // them as the lambda arguments
2427 let e = self.parse_expr_res(RESTRICT_NO_BAR_OR_DOUBLEBAR_OP);
2429 ExprCall(f, ref args, NoSugar) => {
2430 let block = self.parse_lambda_block_expr();
2431 let last_arg = self.mk_expr(block.span.lo, block.span.hi,
2433 let args = vec::append((*args).clone(), [last_arg]);
2434 self.mk_expr(lo, block.span.hi, ExprCall(f, args, sugar))
2436 ExprMethodCall(_, f, i, ref tps, ref args, NoSugar) => {
2437 let block = self.parse_lambda_block_expr();
2438 let last_arg = self.mk_expr(block.span.lo, block.span.hi,
2440 let args = vec::append((*args).clone(), [last_arg]);
2441 self.mk_expr(lo, block.span.hi,
2442 self.mk_method_call(f,
2448 ExprField(f, i, ref tps) => {
2449 let block = self.parse_lambda_block_expr();
2450 let last_arg = self.mk_expr(block.span.lo, block.span.hi,
2452 self.mk_expr(lo, block.span.hi,
2453 self.mk_method_call(f,
2459 ExprPath(*) | ExprCall(*) | ExprMethodCall(*) |
2461 let block = self.parse_lambda_block_expr();
2462 let last_arg = self.mk_expr(block.span.lo, block.span.hi,
2467 self.mk_call(e, ~[last_arg], sugar))
2470 // There may be other types of expressions that can
2471 // represent the callee in `for` and `do` expressions
2472 // but they aren't represented by tests
2473 debug!("sugary call on {:?}", e.node);
2476 format!("`{}` must be followed by a block call", keyword));
2481 pub fn parse_while_expr(&self) -> @Expr {
2482 let lo = self.last_span.lo;
2483 let cond = self.parse_expr();
2484 let body = self.parse_block();
2485 let hi = body.span.hi;
2486 return self.mk_expr(lo, hi, ExprWhile(cond, body));
2489 pub fn parse_loop_expr(&self, opt_ident: Option<ast::Ident>) -> @Expr {
2490 // loop headers look like 'loop {' or 'loop unsafe {'
2491 let is_loop_header =
2492 *self.token == token::LBRACE
2493 || (is_ident(&*self.token)
2494 && self.look_ahead(1, |t| *t == token::LBRACE));
2497 // This is a loop body
2498 let lo = self.last_span.lo;
2499 let body = self.parse_block();
2500 let hi = body.span.hi;
2501 return self.mk_expr(lo, hi, ExprLoop(body, opt_ident));
2503 // This is an obsolete 'continue' expression
2504 if opt_ident.is_some() {
2505 self.span_err(*self.last_span,
2506 "a label may not be used with a `loop` expression");
2509 self.obsolete(*self.last_span, ObsoleteLoopAsContinue);
2510 let lo = self.span.lo;
2511 let ex = if self.token_is_lifetime(&*self.token) {
2512 let lifetime = self.get_lifetime(&*self.token);
2514 ExprAgain(Some(lifetime.name))
2518 let hi = self.span.hi;
2519 return self.mk_expr(lo, hi, ex);
2523 // For distingishing between record literals and blocks
2524 fn looking_at_record_literal(&self) -> bool {
2525 *self.token == token::LBRACE &&
2526 (self.look_ahead(1, |t| token::is_keyword(keywords::Mut, t)) ||
2527 (self.look_ahead(1, |t| token::is_plain_ident(t)) &&
2528 self.look_ahead(2, |t| *t == token::COLON)))
2531 fn parse_match_expr(&self) -> @Expr {
2532 let lo = self.last_span.lo;
2533 let discriminant = self.parse_expr();
2534 self.commit_expr_expecting(discriminant, token::LBRACE);
2535 let mut arms: ~[Arm] = ~[];
2536 while *self.token != token::RBRACE {
2537 let pats = self.parse_pats();
2538 let mut guard = None;
2539 if self.eat_keyword(keywords::If) {
2540 guard = Some(self.parse_expr());
2542 self.expect(&token::FAT_ARROW);
2543 let expr = self.parse_expr_res(RESTRICT_STMT_EXPR);
2546 !classify::expr_is_simple_block(expr)
2547 && *self.token != token::RBRACE;
2550 self.commit_expr(expr, &[token::COMMA], &[token::RBRACE]);
2552 self.eat(&token::COMMA);
2555 let blk = ast::Block {
2559 id: ast::DUMMY_NODE_ID,
2560 rules: DefaultBlock,
2564 arms.push(ast::Arm { pats: pats, guard: guard, body: blk });
2566 let hi = self.span.hi;
2568 return self.mk_expr(lo, hi, ExprMatch(discriminant, arms));
2571 // parse an expression
2572 pub fn parse_expr(&self) -> @Expr {
2573 return self.parse_expr_res(UNRESTRICTED);
2576 // parse an expression, subject to the given restriction
2577 fn parse_expr_res(&self, r: restriction) -> @Expr {
2578 let old = *self.restriction;
2579 *self.restriction = r;
2580 let e = self.parse_assign_expr();
2581 *self.restriction = old;
2585 // parse the RHS of a local variable declaration (e.g. '= 14;')
2586 fn parse_initializer(&self) -> Option<@Expr> {
2587 if *self.token == token::EQ {
2589 Some(self.parse_expr())
2595 // parse patterns, separated by '|' s
2596 fn parse_pats(&self) -> ~[@Pat] {
2599 pats.push(self.parse_pat());
2600 if *self.token == token::BINOP(token::OR) { self.bump(); }
2601 else { return pats; }
2605 fn parse_pat_vec_elements(
2607 ) -> (~[@Pat], Option<@Pat>, ~[@Pat]) {
2608 let mut before = ~[];
2609 let mut slice = None;
2610 let mut after = ~[];
2611 let mut first = true;
2612 let mut before_slice = true;
2614 while *self.token != token::RBRACKET {
2615 if first { first = false; }
2616 else { self.expect(&token::COMMA); }
2618 let mut is_slice = false;
2620 if *self.token == token::DOTDOT {
2623 before_slice = false;
2627 let subpat = self.parse_pat();
2630 @ast::Pat { node: PatWild, _ } => (),
2631 @ast::Pat { node: PatIdent(_, _, _), _ } => (),
2632 @ast::Pat { span, _ } => self.span_fatal(
2633 span, "expected an identifier or `_`"
2636 slice = Some(subpat);
2639 before.push(subpat);
2646 (before, slice, after)
2649 // parse the fields of a struct-like pattern
2650 fn parse_pat_fields(&self) -> (~[ast::FieldPat], bool) {
2651 let mut fields = ~[];
2652 let mut etc = false;
2653 let mut first = true;
2654 while *self.token != token::RBRACE {
2655 if first { first = false; }
2656 else { self.expect(&token::COMMA); }
2658 if *self.token == token::UNDERSCORE {
2660 if *self.token != token::RBRACE {
2663 "expected `\\}`, found `{}`",
2664 self.this_token_to_str()
2672 let lo1 = self.last_span.lo;
2673 let fieldname = self.parse_ident();
2674 let hi1 = self.last_span.lo;
2675 let fieldpath = ast_util::ident_to_path(mk_sp(lo1, hi1),
2678 if *self.token == token::COLON {
2680 subpat = self.parse_pat();
2682 subpat = @ast::Pat {
2683 id: ast::DUMMY_NODE_ID,
2684 node: PatIdent(BindInfer, fieldpath, None),
2685 span: *self.last_span
2688 fields.push(ast::FieldPat { ident: fieldname, pat: subpat });
2690 return (fields, etc);
2694 pub fn parse_pat(&self) -> @Pat {
2695 maybe_whole!(self, nt_pat);
2697 let lo = self.span.lo;
2702 token::UNDERSCORE => {
2705 hi = self.last_span.hi;
2707 id: ast::DUMMY_NODE_ID,
2715 let sub = self.parse_pat();
2717 // HACK: parse @"..." as a literal of a vstore @str
2718 pat = match sub.node {
2720 node: ExprLit(@codemap::Spanned {
2725 id: ast::DUMMY_NODE_ID,
2726 node: ExprVstore(e, ExprVstoreBox),
2727 span: mk_sp(lo, hi),
2733 hi = self.last_span.hi;
2735 id: ast::DUMMY_NODE_ID,
2743 let sub = self.parse_pat();
2745 // HACK: parse ~"..." as a literal of a vstore ~str
2746 pat = match sub.node {
2748 node: ExprLit(@codemap::Spanned {
2753 id: ast::DUMMY_NODE_ID,
2754 node: ExprVstore(e, ExprVstoreUniq),
2755 span: mk_sp(lo, hi),
2761 hi = self.last_span.hi;
2763 id: ast::DUMMY_NODE_ID,
2768 token::BINOP(token::AND) => {
2770 let lo = self.span.lo;
2772 let sub = self.parse_pat();
2774 // HACK: parse &"..." as a literal of a borrowed str
2775 pat = match sub.node {
2777 node: ExprLit(@codemap::Spanned {
2778 node: lit_str(*), span: _}), _
2781 id: ast::DUMMY_NODE_ID,
2782 node: ExprVstore(e, ExprVstoreSlice),
2789 hi = self.last_span.hi;
2791 id: ast::DUMMY_NODE_ID,
2797 // parse (pat,pat,pat,...) as tuple
2799 if *self.token == token::RPAREN {
2802 let lit = @codemap::Spanned {
2804 span: mk_sp(lo, hi)};
2805 let expr = self.mk_expr(lo, hi, ExprLit(lit));
2808 let mut fields = ~[self.parse_pat()];
2809 if self.look_ahead(1, |t| *t != token::RPAREN) {
2810 while *self.token == token::COMMA {
2812 fields.push(self.parse_pat());
2815 if fields.len() == 1 { self.expect(&token::COMMA); }
2816 self.expect(&token::RPAREN);
2817 pat = PatTup(fields);
2819 hi = self.last_span.hi;
2821 id: ast::DUMMY_NODE_ID,
2826 token::LBRACKET => {
2827 // parse [pat,pat,...] as vector pattern
2829 let (before, slice, after) =
2830 self.parse_pat_vec_elements();
2832 self.expect(&token::RBRACKET);
2833 pat = ast::PatVec(before, slice, after);
2834 hi = self.last_span.hi;
2836 id: ast::DUMMY_NODE_ID,
2844 let tok = self.token;
2845 if !is_ident_or_path(tok)
2846 || self.is_keyword(keywords::True)
2847 || self.is_keyword(keywords::False) {
2848 // Parse an expression pattern or exp .. exp.
2850 // These expressions are limited to literals (possibly
2851 // preceded by unary-minus) or identifiers.
2852 let val = self.parse_literal_maybe_minus();
2853 if self.eat(&token::DOTDOT) {
2854 let end = if is_ident_or_path(tok) {
2855 let path = self.parse_path(LifetimeAndTypesWithColons)
2857 let hi = self.span.hi;
2858 self.mk_expr(lo, hi, ExprPath(path))
2860 self.parse_literal_maybe_minus()
2862 pat = PatRange(val, end);
2866 } else if self.eat_keyword(keywords::Ref) {
2868 let mutbl = self.parse_mutability();
2869 pat = self.parse_pat_ident(BindByRef(mutbl));
2871 let can_be_enum_or_struct = do self.look_ahead(1) |t| {
2873 token::LPAREN | token::LBRACKET | token::LT |
2874 token::LBRACE | token::MOD_SEP => true,
2879 if self.look_ahead(1, |t| *t == token::DOTDOT) {
2880 let start = self.parse_expr_res(RESTRICT_NO_BAR_OP);
2881 self.eat(&token::DOTDOT);
2882 let end = self.parse_expr_res(RESTRICT_NO_BAR_OP);
2883 pat = PatRange(start, end);
2884 } else if is_plain_ident(&*self.token) && !can_be_enum_or_struct {
2885 let name = self.parse_path(NoTypesAllowed).path;
2887 if self.eat(&token::AT) {
2889 sub = Some(self.parse_pat());
2894 pat = PatIdent(BindInfer, name, sub);
2896 // parse an enum pat
2897 let enum_path = self.parse_path(LifetimeAndTypesWithColons)
2903 self.parse_pat_fields();
2905 pat = PatStruct(enum_path, fields, etc);
2908 let mut args: ~[@Pat] = ~[];
2911 let is_star = do self.look_ahead(1) |t| {
2913 token::BINOP(token::STAR) => true,
2918 // This is a "top constructor only" pat
2921 self.expect(&token::RPAREN);
2922 pat = PatEnum(enum_path, None);
2924 args = self.parse_unspanned_seq(
2927 seq_sep_trailing_disallowed(token::COMMA),
2930 pat = PatEnum(enum_path, Some(args));
2934 if enum_path.segments.len() == 1 {
2935 // it could still be either an enum
2936 // or an identifier pattern, resolve
2937 // will sort it out:
2938 pat = PatIdent(BindInfer,
2942 pat = PatEnum(enum_path, Some(args));
2950 hi = self.last_span.hi;
2952 id: ast::DUMMY_NODE_ID,
2954 span: mk_sp(lo, hi),
2958 // parse ident or ident @ pat
2959 // used by the copy foo and ref foo patterns to give a good
2960 // error message when parsing mistakes like ref foo(a,b)
2961 fn parse_pat_ident(&self,
2962 binding_mode: ast::BindingMode)
2964 if !is_plain_ident(&*self.token) {
2965 self.span_fatal(*self.last_span,
2966 "expected identifier, found path");
2968 // why a path here, and not just an identifier?
2969 let name = self.parse_path(NoTypesAllowed).path;
2970 let sub = if self.eat(&token::AT) {
2971 Some(self.parse_pat())
2976 // just to be friendly, if they write something like
2978 // we end up here with ( as the current token. This shortly
2979 // leads to a parse error. Note that if there is no explicit
2980 // binding mode then we do not end up here, because the lookahead
2981 // will direct us over to parse_enum_variant()
2982 if *self.token == token::LPAREN {
2985 "expected identifier, found enum pattern");
2988 PatIdent(binding_mode, name, sub)
2991 // parse a local variable declaration
2992 fn parse_local(&self, is_mutbl: bool) -> @Local {
2993 let lo = self.span.lo;
2994 let pat = self.parse_pat();
2996 if is_mutbl && !ast_util::pat_is_ident(pat) {
2997 self.obsolete(*self.span, ObsoleteMutWithMultipleBindings)
3001 id: ast::DUMMY_NODE_ID,
3003 span: mk_sp(lo, lo),
3005 if self.eat(&token::COLON) { ty = self.parse_ty(false); }
3006 let init = self.parse_initializer();
3012 id: ast::DUMMY_NODE_ID,
3013 span: mk_sp(lo, self.last_span.hi),
3017 // parse a "let" stmt
3018 fn parse_let(&self) -> @Decl {
3019 let is_mutbl = self.eat_keyword(keywords::Mut);
3020 let lo = self.span.lo;
3021 let local = self.parse_local(is_mutbl);
3022 while self.eat(&token::COMMA) {
3023 let _ = self.parse_local(is_mutbl);
3024 self.obsolete(*self.span, ObsoleteMultipleLocalDecl);
3026 return @spanned(lo, self.last_span.hi, DeclLocal(local));
3029 // parse a structure field
3030 fn parse_name_and_ty(&self,
3032 attrs: ~[Attribute]) -> @struct_field {
3033 let lo = self.span.lo;
3034 if !is_plain_ident(&*self.token) {
3035 self.fatal("expected ident");
3037 let name = self.parse_ident();
3038 self.expect(&token::COLON);
3039 let ty = self.parse_ty(false);
3040 @spanned(lo, self.last_span.hi, ast::struct_field_ {
3041 kind: named_field(name, pr),
3042 id: ast::DUMMY_NODE_ID,
3048 // parse a statement. may include decl.
3049 // precondition: any attributes are parsed already
3050 pub fn parse_stmt(&self, item_attrs: ~[Attribute]) -> @Stmt {
3051 maybe_whole!(self, nt_stmt);
3053 fn check_expected_item(p: &Parser, found_attrs: bool) {
3054 // If we have attributes then we should have an item
3056 p.span_err(*p.last_span, "expected item after attributes");
3060 let lo = self.span.lo;
3061 if self.is_keyword(keywords::Let) {
3062 check_expected_item(self, !item_attrs.is_empty());
3063 self.expect_keyword(keywords::Let);
3064 let decl = self.parse_let();
3065 return @spanned(lo, decl.span.hi, StmtDecl(decl, ast::DUMMY_NODE_ID));
3066 } else if is_ident(&*self.token)
3067 && !token::is_any_keyword(self.token)
3068 && self.look_ahead(1, |t| *t == token::NOT) {
3069 // parse a macro invocation. Looks like there's serious
3070 // overlap here; if this clause doesn't catch it (and it
3071 // won't, for brace-delimited macros) it will fall through
3072 // to the macro clause of parse_item_or_view_item. This
3073 // could use some cleanup, it appears to me.
3075 // whoops! I now have a guess: I'm guessing the "parens-only"
3076 // rule here is deliberate, to allow macro users to use parens
3077 // for things that should be parsed as stmt_mac, and braces
3078 // for things that should expand into items. Tricky, and
3079 // somewhat awkward... and probably undocumented. Of course,
3080 // I could just be wrong.
3082 check_expected_item(self, !item_attrs.is_empty());
3084 // Potential trouble: if we allow macros with paths instead of
3085 // idents, we'd need to look ahead past the whole path here...
3086 let pth = self.parse_path(NoTypesAllowed).path;
3089 let id = if *self.token == token::LPAREN {
3090 token::special_idents::invalid // no special identifier
3095 let tts = self.parse_unspanned_seq(
3099 |p| p.parse_token_tree()
3101 let hi = self.span.hi;
3103 if id == token::special_idents::invalid {
3104 return @spanned(lo, hi, StmtMac(
3105 spanned(lo, hi, mac_invoc_tt(pth, tts, EMPTY_CTXT)), false));
3107 // if it has a special ident, it's definitely an item
3108 return @spanned(lo, hi, StmtDecl(
3109 @spanned(lo, hi, DeclItem(
3111 lo, hi, id /*id is good here*/,
3112 item_mac(spanned(lo, hi, mac_invoc_tt(pth, tts, EMPTY_CTXT))),
3113 inherited, ~[/*no attrs*/]))),
3114 ast::DUMMY_NODE_ID));
3118 let found_attrs = !item_attrs.is_empty();
3119 match self.parse_item_or_view_item(item_attrs, false) {
3122 let decl = @spanned(lo, hi, DeclItem(i));
3123 return @spanned(lo, hi, StmtDecl(decl, ast::DUMMY_NODE_ID));
3125 iovi_view_item(vi) => {
3126 self.span_fatal(vi.span,
3127 "view items must be declared at the top of the block");
3129 iovi_foreign_item(_) => {
3130 self.fatal("foreign items are not allowed here");
3132 iovi_none(_) => { /* fallthrough */ }
3135 check_expected_item(self, found_attrs);
3137 // Remainder are line-expr stmts.
3138 let e = self.parse_expr_res(RESTRICT_STMT_EXPR);
3139 return @spanned(lo, e.span.hi, StmtExpr(e, ast::DUMMY_NODE_ID));
3143 // is this expression a successfully-parsed statement?
3144 fn expr_is_complete(&self, e: @Expr) -> bool {
3145 return *self.restriction == RESTRICT_STMT_EXPR &&
3146 !classify::expr_requires_semi_to_be_stmt(e);
3149 // parse a block. No inner attrs are allowed.
3150 pub fn parse_block(&self) -> Block {
3151 maybe_whole!(deref self, nt_block);
3153 let lo = self.span.lo;
3154 if self.eat_keyword(keywords::Unsafe) {
3155 self.obsolete(*self.span, ObsoleteUnsafeBlock);
3157 self.expect(&token::LBRACE);
3159 return self.parse_block_tail_(lo, DefaultBlock, ~[]);
3162 // parse a block. Inner attrs are allowed.
3163 fn parse_inner_attrs_and_block(&self)
3164 -> (~[Attribute], Block) {
3166 maybe_whole!(pair_empty self, nt_block);
3168 let lo = self.span.lo;
3169 if self.eat_keyword(keywords::Unsafe) {
3170 self.obsolete(*self.span, ObsoleteUnsafeBlock);
3172 self.expect(&token::LBRACE);
3173 let (inner, next) = self.parse_inner_attrs_and_next();
3175 (inner, self.parse_block_tail_(lo, DefaultBlock, next))
3178 // Precondition: already parsed the '{' or '#{'
3179 // I guess that also means "already parsed the 'impure'" if
3180 // necessary, and this should take a qualifier.
3181 // some blocks start with "#{"...
3182 fn parse_block_tail(&self, lo: BytePos, s: BlockCheckMode) -> Block {
3183 self.parse_block_tail_(lo, s, ~[])
3186 // parse the rest of a block expression or function body
3187 fn parse_block_tail_(&self, lo: BytePos, s: BlockCheckMode,
3188 first_item_attrs: ~[Attribute]) -> Block {
3189 let mut stmts = ~[];
3190 let mut expr = None;
3192 // wouldn't it be more uniform to parse view items only, here?
3193 let ParsedItemsAndViewItems {
3194 attrs_remaining: attrs_remaining,
3195 view_items: view_items,
3198 } = self.parse_items_and_view_items(first_item_attrs,
3201 for item in items.iter() {
3202 let decl = @spanned(item.span.lo, item.span.hi, DeclItem(*item));
3203 stmts.push(@spanned(item.span.lo, item.span.hi,
3204 StmtDecl(decl, ast::DUMMY_NODE_ID)));
3207 let mut attributes_box = attrs_remaining;
3209 while (*self.token != token::RBRACE) {
3210 // parsing items even when they're not allowed lets us give
3211 // better error messages and recover more gracefully.
3212 attributes_box.push_all(self.parse_outer_attributes());
3215 if !attributes_box.is_empty() {
3216 self.span_err(*self.last_span, "expected item after attributes");
3217 attributes_box = ~[];
3219 self.bump(); // empty
3222 // fall through and out.
3225 let stmt = self.parse_stmt(attributes_box);
3226 attributes_box = ~[];
3228 StmtExpr(e, stmt_id) => {
3229 // expression without semicolon
3230 if classify::stmt_ends_with_semi(stmt) {
3231 // Just check for errors and recover; do not eat semicolon yet.
3232 self.commit_stmt(stmt, &[], &[token::SEMI, token::RBRACE]);
3238 stmts.push(@codemap::Spanned {
3239 node: StmtSemi(e, stmt_id),
3251 StmtMac(ref m, _) => {
3252 // statement macro; might be an expr
3259 // if a block ends in `m!(arg)` without
3260 // a `;`, it must be an expr
3263 self.mk_mac_expr(stmt.span.lo,
3275 stmts.push(@codemap::Spanned {
3276 node: StmtMac((*m).clone(), true),
3281 _ => { // all other kinds of statements:
3284 if classify::stmt_ends_with_semi(stmt) {
3285 self.commit_stmt_expecting(stmt, token::SEMI);
3293 if !attributes_box.is_empty() {
3294 self.span_err(*self.last_span, "expected item after attributes");
3297 let hi = self.span.hi;
3300 view_items: view_items,
3303 id: ast::DUMMY_NODE_ID,
3305 span: mk_sp(lo, hi),
3309 fn parse_optional_purity(&self) -> ast::purity {
3310 if self.eat_keyword(keywords::Unsafe) {
3317 fn parse_optional_onceness(&self) -> ast::Onceness {
3318 if self.eat_keyword(keywords::Once) { ast::Once } else { ast::Many }
3321 // matches optbounds = ( ( : ( boundseq )? )? )
3322 // where boundseq = ( bound + boundseq ) | bound
3323 // and bound = 'static | ty
3324 // Returns "None" if there's no colon (e.g. "T");
3325 // Returns "Some(Empty)" if there's a colon but nothing after (e.g. "T:")
3326 // Returns "Some(stuff)" otherwise (e.g. "T:stuff").
3327 // NB: The None/Some distinction is important for issue #7264.
3328 fn parse_optional_ty_param_bounds(&self) -> Option<OptVec<TyParamBound>> {
3329 if !self.eat(&token::COLON) {
3333 let mut result = opt_vec::Empty;
3336 token::LIFETIME(lifetime) => {
3337 if "static" == self.id_to_str(lifetime) {
3338 result.push(RegionTyParamBound);
3340 self.span_err(*self.span,
3341 "`'static` is the only permissible region bound here");
3345 token::MOD_SEP | token::IDENT(*) => {
3346 let tref = self.parse_trait_ref();
3347 result.push(TraitTyParamBound(tref));
3352 if !self.eat(&token::BINOP(token::PLUS)) {
3357 return Some(result);
3360 // matches typaram = IDENT optbounds
3361 fn parse_ty_param(&self) -> TyParam {
3362 let ident = self.parse_ident();
3363 let opt_bounds = self.parse_optional_ty_param_bounds();
3364 // For typarams we don't care about the difference b/w "<T>" and "<T:>".
3365 let bounds = opt_bounds.unwrap_or_default();
3366 ast::TyParam { ident: ident, id: ast::DUMMY_NODE_ID, bounds: bounds }
3369 // parse a set of optional generic type parameter declarations
3370 // matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
3371 // | ( < lifetimes , typaramseq ( , )? > )
3372 // where typaramseq = ( typaram ) | ( typaram , typaramseq )
3373 pub fn parse_generics(&self) -> ast::Generics {
3374 if self.eat(&token::LT) {
3375 let lifetimes = self.parse_lifetimes();
3376 let ty_params = self.parse_seq_to_gt(
3378 |p| p.parse_ty_param());
3379 ast::Generics { lifetimes: lifetimes, ty_params: ty_params }
3381 ast_util::empty_generics()
3385 // parse a generic use site
3386 fn parse_generic_values(&self) -> (OptVec<ast::Lifetime>, ~[Ty]) {
3387 if !self.eat(&token::LT) {
3388 (opt_vec::Empty, ~[])
3390 self.parse_generic_values_after_lt()
3394 fn parse_generic_values_after_lt(&self) -> (OptVec<ast::Lifetime>, ~[Ty]) {
3395 let lifetimes = self.parse_lifetimes();
3396 let result = self.parse_seq_to_gt(
3398 |p| p.parse_ty(false));
3399 (lifetimes, opt_vec::take_vec(result))
3402 // parse the argument list and result type of a function declaration
3403 pub fn parse_fn_decl(&self) -> fn_decl {
3405 self.parse_unspanned_seq(
3408 seq_sep_trailing_disallowed(token::COMMA),
3412 let (ret_style, ret_ty) = self.parse_ret_ty();
3420 fn is_self_ident(&self) -> bool {
3422 token::IDENT(id, false) => id.name == special_idents::self_.name,
3427 fn expect_self_ident(&self) {
3428 if !self.is_self_ident() {
3431 "expected `self` but found `{}`",
3432 self.this_token_to_str()
3439 // parse the argument list and result type of a function
3440 // that may have a self type.
3441 fn parse_fn_decl_with_self(&self, parse_arg_fn: &fn(&Parser) -> arg)
3442 -> (explicit_self, fn_decl) {
3444 fn maybe_parse_explicit_self(cnstr: &fn(v: Mutability) -> ast::explicit_self_,
3445 p: &Parser) -> ast::explicit_self_ {
3446 // We need to make sure it isn't a type
3447 if p.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) ||
3448 ((p.look_ahead(1, |t| token::is_keyword(keywords::Const, t)) ||
3449 p.look_ahead(1, |t| token::is_keyword(keywords::Mut, t))) &&
3450 p.look_ahead(2, |t| token::is_keyword(keywords::Self, t))) {
3453 let mutability = p.parse_mutability();
3454 p.expect_self_ident();
3461 fn maybe_parse_borrowed_explicit_self(this: &Parser) -> ast::explicit_self_ {
3462 // The following things are possible to see here:
3467 // fn(&'lt mut self)
3469 // We already know that the current token is `&`.
3471 if this.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) {
3473 this.expect_self_ident();
3474 sty_region(None, MutImmutable)
3475 } else if this.look_ahead(1, |t| this.token_is_mutability(t)) &&
3477 |t| token::is_keyword(keywords::Self,
3480 let mutability = this.parse_mutability();
3481 this.expect_self_ident();
3482 sty_region(None, mutability)
3483 } else if this.look_ahead(1, |t| this.token_is_lifetime(t)) &&
3485 |t| token::is_keyword(keywords::Self,
3488 let lifetime = this.parse_lifetime();
3489 this.expect_self_ident();
3490 sty_region(Some(lifetime), MutImmutable)
3491 } else if this.look_ahead(1, |t| this.token_is_lifetime(t)) &&
3492 this.look_ahead(2, |t| this.token_is_mutability(t)) &&
3493 this.look_ahead(3, |t| token::is_keyword(keywords::Self,
3496 let lifetime = this.parse_lifetime();
3497 let mutability = this.parse_mutability();
3498 this.expect_self_ident();
3499 sty_region(Some(lifetime), mutability)
3505 self.expect(&token::LPAREN);
3507 // A bit of complexity and lookahead is needed here in order to be
3508 // backwards compatible.
3509 let lo = self.span.lo;
3510 let explicit_self = match *self.token {
3511 token::BINOP(token::AND) => {
3512 maybe_parse_borrowed_explicit_self(self)
3515 maybe_parse_explicit_self(sty_box, self)
3518 maybe_parse_explicit_self(|mutability| {
3519 if mutability != MutImmutable {
3520 self.span_err(*self.last_span,
3521 "mutability declaration not allowed here");
3523 sty_uniq(MutImmutable)
3526 token::IDENT(*) if self.is_self_ident() => {
3528 sty_value(MutImmutable)
3530 token::BINOP(token::STAR) => {
3531 // Possibly "*self" or "*mut self" -- not supported. Try to avoid
3532 // emitting cryptic "unexpected token" errors.
3534 let mutability = if self.token_is_mutability(self.token) {
3535 self.parse_mutability()
3536 } else { MutImmutable };
3537 if self.is_self_ident() {
3538 self.span_err(*self.span, "cannot pass self by unsafe pointer");
3541 sty_value(mutability)
3543 _ if self.token_is_mutability(self.token) &&
3544 self.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) => {
3545 let mutability = self.parse_mutability();
3546 self.expect_self_ident();
3547 sty_value(mutability)
3549 _ if self.token_is_mutability(self.token) &&
3550 self.look_ahead(1, |t| *t == token::TILDE) &&
3551 self.look_ahead(2, |t| token::is_keyword(keywords::Self, t)) => {
3552 let mutability = self.parse_mutability();
3554 self.expect_self_ident();
3555 sty_uniq(mutability)
3562 // If we parsed a self type, expect a comma before the argument list.
3564 if explicit_self != sty_static {
3568 let sep = seq_sep_trailing_disallowed(token::COMMA);
3569 fn_inputs = self.parse_seq_to_before_end(
3581 "expected `,` or `)`, found `{}`",
3582 self.this_token_to_str()
3588 let sep = seq_sep_trailing_disallowed(token::COMMA);
3589 fn_inputs = self.parse_seq_to_before_end(
3596 self.expect(&token::RPAREN);
3598 let hi = self.span.hi;
3600 let (ret_style, ret_ty) = self.parse_ret_ty();
3602 let fn_decl = ast::fn_decl {
3608 (spanned(lo, hi, explicit_self), fn_decl)
3611 // parse the |arg, arg| header on a lambda
3612 fn parse_fn_block_decl(&self) -> fn_decl {
3613 let inputs_captures = {
3614 if self.eat(&token::OROR) {
3617 self.parse_unspanned_seq(
3618 &token::BINOP(token::OR),
3619 &token::BINOP(token::OR),
3620 seq_sep_trailing_disallowed(token::COMMA),
3621 |p| p.parse_fn_block_arg()
3625 let output = if self.eat(&token::RARROW) {
3626 self.parse_ty(false)
3628 Ty { id: ast::DUMMY_NODE_ID, node: ty_infer, span: *self.span }
3632 inputs: inputs_captures,
3638 // parse the name and optional generic types of a function header.
3639 fn parse_fn_header(&self) -> (Ident, ast::Generics) {
3640 let id = self.parse_ident();
3641 let generics = self.parse_generics();
3645 fn mk_item(&self, lo: BytePos, hi: BytePos, ident: Ident,
3646 node: item_, vis: visibility,
3647 attrs: ~[Attribute]) -> @item {
3648 @ast::item { ident: ident,
3650 id: ast::DUMMY_NODE_ID,
3653 span: mk_sp(lo, hi) }
3656 // parse an item-position function declaration.
3657 fn parse_item_fn(&self, purity: purity, abis: AbiSet) -> item_info {
3658 let (ident, generics) = self.parse_fn_header();
3659 let decl = self.parse_fn_decl();
3660 let (inner_attrs, body) = self.parse_inner_attrs_and_block();
3662 item_fn(decl, purity, abis, generics, body),
3666 // parse a method in a trait impl
3667 fn parse_method(&self) -> @method {
3668 let attrs = self.parse_outer_attributes();
3669 let lo = self.span.lo;
3671 let visa = self.parse_visibility();
3672 let pur = self.parse_fn_purity();
3673 let ident = self.parse_ident();
3674 let generics = self.parse_generics();
3675 let (explicit_self, decl) = do self.parse_fn_decl_with_self() |p| {
3679 let (inner_attrs, body) = self.parse_inner_attrs_and_block();
3680 let hi = body.span.hi;
3681 let attrs = vec::append(attrs, inner_attrs);
3686 explicit_self: explicit_self,
3690 id: ast::DUMMY_NODE_ID,
3691 span: mk_sp(lo, hi),
3692 self_id: ast::DUMMY_NODE_ID,
3697 // parse trait Foo { ... }
3698 fn parse_item_trait(&self) -> item_info {
3699 let ident = self.parse_ident();
3700 let tps = self.parse_generics();
3702 // Parse traits, if necessary.
3704 if *self.token == token::COLON {
3706 traits = self.parse_trait_ref_list(&token::LBRACE);
3711 let meths = self.parse_trait_methods();
3712 (ident, item_trait(tps, traits, meths), None)
3715 // Parses two variants (with the region/type params always optional):
3716 // impl<T> Foo { ... }
3717 // impl<T> ToStr for ~[T] { ... }
3718 fn parse_item_impl(&self) -> item_info {
3719 // First, parse type parameters if necessary.
3720 let generics = self.parse_generics();
3722 // This is a new-style impl declaration.
3724 let ident = special_idents::clownshoes_extensions;
3726 // Special case: if the next identifier that follows is '(', don't
3727 // allow this to be parsed as a trait.
3728 let could_be_trait = *self.token != token::LPAREN;
3731 let mut ty = self.parse_ty(false);
3733 // Parse traits, if necessary.
3734 let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) {
3735 // New-style trait. Reinterpret the type as a trait.
3736 let opt_trait_ref = match ty.node {
3737 ty_path(ref path, None, node_id) => {
3739 path: /* bad */ (*path).clone(),
3744 self.span_err(ty.span,
3745 "bounded traits are only valid in type position");
3749 self.span_err(ty.span, "not a trait");
3754 ty = self.parse_ty(false);
3760 let mut meths = ~[];
3761 if self.eat(&token::SEMI) {
3762 self.obsolete(*self.last_span, ObsoleteEmptyImpl);
3764 self.expect(&token::LBRACE);
3765 while !self.eat(&token::RBRACE) {
3766 meths.push(self.parse_method());
3770 (ident, item_impl(generics, opt_trait, ty, meths), None)
3773 // parse a::B<~str,int>
3774 fn parse_trait_ref(&self) -> trait_ref {
3776 path: self.parse_path(LifetimeAndTypesWithoutColons).path,
3777 ref_id: ast::DUMMY_NODE_ID,
3781 // parse B + C<~str,int> + D
3782 fn parse_trait_ref_list(&self, ket: &token::Token) -> ~[trait_ref] {
3783 self.parse_seq_to_before_end(
3785 seq_sep_trailing_disallowed(token::BINOP(token::PLUS)),
3786 |p| p.parse_trait_ref()
3790 // parse struct Foo { ... }
3791 fn parse_item_struct(&self) -> item_info {
3792 let class_name = self.parse_ident();
3793 let generics = self.parse_generics();
3795 let mut fields: ~[@struct_field];
3798 if self.eat(&token::LBRACE) {
3799 // It's a record-like struct.
3800 is_tuple_like = false;
3802 while *self.token != token::RBRACE {
3803 fields.push(self.parse_struct_decl_field());
3805 if fields.len() == 0 {
3806 self.fatal(format!("Unit-like struct definition should be written as `struct {};`",
3807 get_ident_interner().get(class_name.name)));
3810 } else if *self.token == token::LPAREN {
3811 // It's a tuple-like struct.
3812 is_tuple_like = true;
3813 fields = do self.parse_unspanned_seq(
3816 seq_sep_trailing_allowed(token::COMMA)
3818 let attrs = self.parse_outer_attributes();
3820 let struct_field_ = ast::struct_field_ {
3821 kind: unnamed_field,
3822 id: ast::DUMMY_NODE_ID,
3823 ty: p.parse_ty(false),
3826 @spanned(lo, p.span.hi, struct_field_)
3828 self.expect(&token::SEMI);
3829 } else if self.eat(&token::SEMI) {
3830 // It's a unit-like struct.
3831 is_tuple_like = true;
3836 "expected `\\{`, `(`, or `;` after struct name \
3838 self.this_token_to_str()
3843 let _ = ast::DUMMY_NODE_ID; // XXX: Workaround for crazy bug.
3844 let new_id = ast::DUMMY_NODE_ID;
3846 item_struct(@ast::struct_def {
3848 ctor_id: if is_tuple_like { Some(new_id) } else { None }
3853 fn token_is_pound_or_doc_comment(&self, tok: token::Token) -> bool {
3855 token::POUND | token::DOC_COMMENT(_) => true,
3860 // parse a structure field declaration
3861 pub fn parse_single_struct_field(&self,
3863 attrs: ~[Attribute])
3865 let a_var = self.parse_name_and_ty(vis, attrs);
3872 self.span_fatal(*self.span,
3873 format!("expected `,`, or `\\}` but found `{}`",
3874 self.this_token_to_str()));
3880 // parse an element of a struct definition
3881 fn parse_struct_decl_field(&self) -> @struct_field {
3883 let attrs = self.parse_outer_attributes();
3885 if self.eat_keyword(keywords::Priv) {
3886 return self.parse_single_struct_field(private, attrs);
3889 if self.eat_keyword(keywords::Pub) {
3890 return self.parse_single_struct_field(public, attrs);
3893 return self.parse_single_struct_field(inherited, attrs);
3896 // parse visiility: PUB, PRIV, or nothing
3897 fn parse_visibility(&self) -> visibility {
3898 if self.eat_keyword(keywords::Pub) { public }
3899 else if self.eat_keyword(keywords::Priv) { private }
3903 // given a termination token and a vector of already-parsed
3904 // attributes (of length 0 or 1), parse all of the items in a module
3905 fn parse_mod_items(&self,
3907 first_item_attrs: ~[Attribute])
3909 // parse all of the items up to closing or an attribute.
3910 // view items are legal here.
3911 let ParsedItemsAndViewItems {
3912 attrs_remaining: attrs_remaining,
3913 view_items: view_items,
3914 items: starting_items,
3916 } = self.parse_items_and_view_items(first_item_attrs, true, true);
3917 let mut items: ~[@item] = starting_items;
3918 let attrs_remaining_len = attrs_remaining.len();
3920 // don't think this other loop is even necessary....
3922 let mut first = true;
3923 while *self.token != term {
3924 let mut attrs = self.parse_outer_attributes();
3926 attrs = attrs_remaining + attrs;
3929 debug!("parse_mod_items: parse_item_or_view_item(attrs={:?})",
3931 match self.parse_item_or_view_item(attrs,
3932 true /* macros allowed */) {
3933 iovi_item(item) => items.push(item),
3934 iovi_view_item(view_item) => {
3935 self.span_fatal(view_item.span,
3936 "view items must be declared at the top of \
3940 self.fatal(format!("expected item but found `{}`",
3941 self.this_token_to_str()));
3946 if first && attrs_remaining_len > 0u {
3947 // We parsed attributes for the first item but didn't find it
3948 self.span_err(*self.last_span, "expected item after attributes");
3951 ast::_mod { view_items: view_items, items: items }
3954 fn parse_item_const(&self) -> item_info {
3955 let m = if self.eat_keyword(keywords::Mut) {MutMutable} else {MutImmutable};
3956 let id = self.parse_ident();
3957 self.expect(&token::COLON);
3958 let ty = self.parse_ty(false);
3959 self.expect(&token::EQ);
3960 let e = self.parse_expr();
3961 self.commit_expr_expecting(e, token::SEMI);
3962 (id, item_static(ty, m, e), None)
3965 // parse a `mod <foo> { ... }` or `mod <foo>;` item
3966 fn parse_item_mod(&self, outer_attrs: &[Attribute]) -> item_info {
3967 let id_span = *self.span;
3968 let id = self.parse_ident();
3969 if *self.token == token::SEMI {
3971 // This mod is in an external file. Let's go get it!
3972 let (m, attrs) = self.eval_src_mod(id, outer_attrs, id_span);
3973 (id, m, Some(attrs))
3975 self.push_mod_path(id, outer_attrs);
3976 self.expect(&token::LBRACE);
3977 let (inner, next) = self.parse_inner_attrs_and_next();
3978 let m = self.parse_mod_items(token::RBRACE, next);
3979 self.expect(&token::RBRACE);
3980 self.pop_mod_path();
3981 (id, item_mod(m), Some(inner))
3985 fn push_mod_path(&self, id: Ident, attrs: &[Attribute]) {
3986 let default_path = token::interner_get(id.name);
3987 let file_path = match ::attr::first_attr_value_str_by_name(attrs,
3990 None => default_path
3992 self.mod_path_stack.push(file_path)
3995 fn pop_mod_path(&self) {
3996 self.mod_path_stack.pop();
3999 // read a module from a source file.
4000 fn eval_src_mod(&self,
4002 outer_attrs: &[ast::Attribute],
4004 -> (ast::item_, ~[ast::Attribute]) {
4005 let mut prefix = Path::new(self.sess.cm.span_to_filename(*self.span));
4007 let mod_path_stack = &*self.mod_path_stack;
4008 let mod_path = Path::new(".").join_many(*mod_path_stack);
4009 let dir_path = prefix.join(&mod_path);
4010 let file_path = match ::attr::first_attr_value_str_by_name(
4011 outer_attrs, "path") {
4012 Some(d) => dir_path.join(d),
4014 let mod_name = token::interner_get(id.name).to_owned();
4015 let default_path_str = mod_name + ".rs";
4016 let secondary_path_str = mod_name + "/mod.rs";
4017 let default_path = dir_path.join(default_path_str.as_slice());
4018 let secondary_path = dir_path.join(secondary_path_str.as_slice());
4019 let default_exists = default_path.exists();
4020 let secondary_exists = secondary_path.exists();
4021 match (default_exists, secondary_exists) {
4022 (true, false) => default_path,
4023 (false, true) => secondary_path,
4025 self.span_fatal(id_sp, format!("file not found for module `{}`", mod_name));
4028 self.span_fatal(id_sp,
4029 format!("file for module `{}` found at both {} and {}",
4030 mod_name, default_path_str, secondary_path_str));
4036 self.eval_src_mod_from_path(file_path,
4037 outer_attrs.to_owned(),
4041 fn eval_src_mod_from_path(&self,
4043 outer_attrs: ~[ast::Attribute],
4044 id_sp: Span) -> (ast::item_, ~[ast::Attribute]) {
4045 let maybe_i = do self.sess.included_mod_stack.iter().position |p| { *p == path };
4048 let stack = &self.sess.included_mod_stack;
4049 let mut err = ~"circular modules: ";
4050 for p in stack.slice(i, stack.len()).iter() {
4051 do p.display().with_str |s| {
4054 err.push_str(" -> ");
4056 do path.display().with_str |s| {
4059 self.span_fatal(id_sp, err);
4063 self.sess.included_mod_stack.push(path.clone());
4066 new_sub_parser_from_file(self.sess,
4070 let (inner, next) = p0.parse_inner_attrs_and_next();
4071 let mod_attrs = vec::append(outer_attrs, inner);
4072 let first_item_outer_attrs = next;
4073 let m0 = p0.parse_mod_items(token::EOF, first_item_outer_attrs);
4074 self.sess.included_mod_stack.pop();
4075 return (ast::item_mod(m0), mod_attrs);
4078 // parse a function declaration from a foreign module
4079 fn parse_item_foreign_fn(&self, vis: ast::visibility,
4080 attrs: ~[Attribute]) -> @foreign_item {
4081 let lo = self.span.lo;
4083 // Parse obsolete purity.
4084 let purity = self.parse_fn_purity();
4085 if purity != impure_fn {
4086 self.obsolete(*self.last_span, ObsoleteUnsafeExternFn);
4089 let (ident, generics) = self.parse_fn_header();
4090 let decl = self.parse_fn_decl();
4091 let hi = self.span.hi;
4092 self.expect(&token::SEMI);
4093 @ast::foreign_item { ident: ident,
4095 node: foreign_item_fn(decl, generics),
4096 id: ast::DUMMY_NODE_ID,
4097 span: mk_sp(lo, hi),
4101 // parse a static item from a foreign module
4102 fn parse_item_foreign_static(&self, vis: ast::visibility,
4103 attrs: ~[Attribute]) -> @foreign_item {
4104 let lo = self.span.lo;
4106 self.expect_keyword(keywords::Static);
4107 let mutbl = self.eat_keyword(keywords::Mut);
4109 let ident = self.parse_ident();
4110 self.expect(&token::COLON);
4111 let ty = self.parse_ty(false);
4112 let hi = self.span.hi;
4113 self.expect(&token::SEMI);
4114 @ast::foreign_item { ident: ident,
4116 node: foreign_item_static(ty, mutbl),
4117 id: ast::DUMMY_NODE_ID,
4118 span: mk_sp(lo, hi),
4122 // parse safe/unsafe and fn
4123 fn parse_fn_purity(&self) -> purity {
4124 if self.eat_keyword(keywords::Fn) { impure_fn }
4125 else if self.eat_keyword(keywords::Unsafe) {
4126 self.expect_keyword(keywords::Fn);
4129 else { self.unexpected(); }
4133 // at this point, this is essentially a wrapper for
4134 // parse_foreign_items.
4135 fn parse_foreign_mod_items(&self,
4137 first_item_attrs: ~[Attribute])
4139 let ParsedItemsAndViewItems {
4140 attrs_remaining: attrs_remaining,
4141 view_items: view_items,
4143 foreign_items: foreign_items
4144 } = self.parse_foreign_items(first_item_attrs, true);
4145 if (! attrs_remaining.is_empty()) {
4146 self.span_err(*self.last_span,
4147 "expected item after attributes");
4149 assert!(*self.token == token::RBRACE);
4152 view_items: view_items,
4153 items: foreign_items
4157 // parse extern foo; or extern mod foo { ... } or extern { ... }
4158 fn parse_item_foreign_mod(&self,
4160 opt_abis: Option<AbiSet>,
4161 visibility: visibility,
4162 attrs: ~[Attribute],
4163 items_allowed: bool)
4164 -> item_or_view_item {
4165 let mut must_be_named_mod = false;
4166 if self.is_keyword(keywords::Mod) {
4167 must_be_named_mod = true;
4168 self.expect_keyword(keywords::Mod);
4169 } else if *self.token != token::LBRACE {
4170 self.span_fatal(*self.span,
4171 format!("expected `\\{` or `mod` but found `{}`",
4172 self.this_token_to_str()));
4175 let (named, maybe_path, ident) = match *self.token {
4176 token::IDENT(*) => {
4177 let the_ident = self.parse_ident();
4178 let path = if *self.token == token::EQ {
4180 Some(self.parse_str())
4183 (true, path, the_ident)
4186 if must_be_named_mod {
4187 self.span_fatal(*self.span,
4188 format!("expected foreign module name but \
4190 self.this_token_to_str()));
4194 special_idents::clownshoes_foreign_mod)
4198 // extern mod foo { ... } or extern { ... }
4199 if items_allowed && self.eat(&token::LBRACE) {
4200 // `extern mod foo { ... }` is obsolete.
4202 self.obsolete(*self.last_span, ObsoleteNamedExternModule);
4205 let abis = opt_abis.unwrap_or(AbiSet::C());
4207 let (inner, next) = self.parse_inner_attrs_and_next();
4208 let m = self.parse_foreign_mod_items(abis, next);
4209 self.expect(&token::RBRACE);
4211 return iovi_item(self.mk_item(lo,
4214 item_foreign_mod(m),
4216 maybe_append(attrs, Some(inner))));
4219 if opt_abis.is_some() {
4220 self.span_err(*self.span, "an ABI may not be specified here");
4224 let metadata = self.parse_optional_meta();
4225 self.expect(&token::SEMI);
4226 iovi_view_item(ast::view_item {
4227 node: view_item_extern_mod(ident, maybe_path, metadata, ast::DUMMY_NODE_ID),
4230 span: mk_sp(lo, self.last_span.hi)
4234 // parse type Foo = Bar;
4235 fn parse_item_type(&self) -> item_info {
4236 let ident = self.parse_ident();
4237 let tps = self.parse_generics();
4238 self.expect(&token::EQ);
4239 let ty = self.parse_ty(false);
4240 self.expect(&token::SEMI);
4241 (ident, item_ty(ty, tps), None)
4244 // parse a structure-like enum variant definition
4245 // this should probably be renamed or refactored...
4246 fn parse_struct_def(&self) -> @struct_def {
4247 let mut fields: ~[@struct_field] = ~[];
4248 while *self.token != token::RBRACE {
4249 fields.push(self.parse_struct_decl_field());
4253 return @ast::struct_def {
4259 // parse the part of an "enum" decl following the '{'
4260 fn parse_enum_def(&self, _generics: &ast::Generics) -> enum_def {
4261 let mut variants = ~[];
4262 let mut all_nullary = true;
4263 let mut have_disr = false;
4264 while *self.token != token::RBRACE {
4265 let variant_attrs = self.parse_outer_attributes();
4266 let vlo = self.span.lo;
4268 let vis = self.parse_visibility();
4273 let mut disr_expr = None;
4274 ident = self.parse_ident();
4275 if self.eat(&token::LBRACE) {
4276 // Parse a struct variant.
4277 all_nullary = false;
4278 kind = struct_variant_kind(self.parse_struct_def());
4279 } else if *self.token == token::LPAREN {
4280 all_nullary = false;
4281 let arg_tys = self.parse_unspanned_seq(
4284 seq_sep_trailing_disallowed(token::COMMA),
4285 |p| p.parse_ty(false)
4287 for ty in arg_tys.move_iter() {
4288 args.push(ast::variant_arg {
4290 id: ast::DUMMY_NODE_ID,
4293 kind = tuple_variant_kind(args);
4294 } else if self.eat(&token::EQ) {
4296 disr_expr = Some(self.parse_expr());
4297 kind = tuple_variant_kind(args);
4299 kind = tuple_variant_kind(~[]);
4302 let vr = ast::variant_ {
4304 attrs: variant_attrs,
4306 id: ast::DUMMY_NODE_ID,
4307 disr_expr: disr_expr,
4310 variants.push(spanned(vlo, self.last_span.hi, vr));
4312 if !self.eat(&token::COMMA) { break; }
4314 self.expect(&token::RBRACE);
4315 if (have_disr && !all_nullary) {
4316 self.fatal("discriminator values can only be used with a c-like \
4320 ast::enum_def { variants: variants }
4323 // parse an "enum" declaration
4324 fn parse_item_enum(&self) -> item_info {
4325 let id = self.parse_ident();
4326 let generics = self.parse_generics();
4327 self.expect(&token::LBRACE);
4329 let enum_definition = self.parse_enum_def(&generics);
4330 (id, item_enum(enum_definition, generics), None)
4333 fn parse_fn_ty_sigil(&self) -> Option<Sigil> {
4343 token::BINOP(token::AND) => {
4353 fn fn_expr_lookahead(&self, tok: &token::Token) -> bool {
4355 token::LPAREN | token::AT | token::TILDE | token::BINOP(_) => true,
4360 // parse a string as an ABI spec on an extern type or module
4361 fn parse_opt_abis(&self) -> Option<AbiSet> {
4364 | token::LIT_STR_RAW(s, _) => {
4366 let the_string = ident_to_str(&s);
4367 let mut abis = AbiSet::empty();
4368 for word in the_string.word_iter() {
4369 match abi::lookup(word) {
4371 if abis.contains(abi) {
4374 format!("ABI `{}` appears twice",
4384 format!("illegal ABI: \
4385 expected one of [{}], \
4387 abi::all_names().connect(", "),
4401 // parse one of the items or view items allowed by the
4402 // flags; on failure, return iovi_none.
4403 // NB: this function no longer parses the items inside an
4405 fn parse_item_or_view_item(&self,
4406 attrs: ~[Attribute],
4407 macros_allowed: bool)
4408 -> item_or_view_item {
4410 INTERPOLATED(token::nt_item(item)) => {
4412 let new_attrs = vec::append(attrs, item.attrs);
4413 return iovi_item(@ast::item {
4415 ..(*item).clone()});
4420 let lo = self.span.lo;
4422 let visibility = self.parse_visibility();
4424 // must be a view item:
4425 if self.eat_keyword(keywords::Use) {
4426 // USE ITEM (iovi_view_item)
4427 let view_item = self.parse_use();
4428 self.expect(&token::SEMI);
4429 return iovi_view_item(ast::view_item {
4433 span: mk_sp(lo, self.last_span.hi)
4436 // either a view item or an item:
4437 if self.eat_keyword(keywords::Extern) {
4438 let opt_abis = self.parse_opt_abis();
4440 if self.eat_keyword(keywords::Fn) {
4441 // EXTERN FUNCTION ITEM
4442 let abis = opt_abis.unwrap_or(AbiSet::C());
4443 let (ident, item_, extra_attrs) =
4444 self.parse_item_fn(extern_fn, abis);
4445 return iovi_item(self.mk_item(lo, self.last_span.hi, ident,
4450 // EXTERN MODULE ITEM (iovi_view_item)
4451 return self.parse_item_foreign_mod(lo, opt_abis, visibility, attrs,
4455 // the rest are all guaranteed to be items:
4456 if self.is_keyword(keywords::Static) {
4459 let (ident, item_, extra_attrs) = self.parse_item_const();
4460 return iovi_item(self.mk_item(lo, self.last_span.hi, ident, item_,
4462 maybe_append(attrs, extra_attrs)));
4464 if self.is_keyword(keywords::Fn) &&
4465 self.look_ahead(1, |f| !self.fn_expr_lookahead(f)) {
4468 let (ident, item_, extra_attrs) =
4469 self.parse_item_fn(impure_fn, AbiSet::Rust());
4470 return iovi_item(self.mk_item(lo, self.last_span.hi, ident, item_,
4472 maybe_append(attrs, extra_attrs)));
4474 if self.is_keyword(keywords::Unsafe)
4475 && self.look_ahead(1u, |t| *t != token::LBRACE) {
4476 // UNSAFE FUNCTION ITEM
4478 self.expect_keyword(keywords::Fn);
4479 let (ident, item_, extra_attrs) =
4480 self.parse_item_fn(unsafe_fn, AbiSet::Rust());
4481 return iovi_item(self.mk_item(lo, self.last_span.hi, ident, item_,
4483 maybe_append(attrs, extra_attrs)));
4485 if self.eat_keyword(keywords::Mod) {
4487 let (ident, item_, extra_attrs) = self.parse_item_mod(attrs);
4488 return iovi_item(self.mk_item(lo, self.last_span.hi, ident, item_,
4490 maybe_append(attrs, extra_attrs)));
4492 if self.eat_keyword(keywords::Type) {
4494 let (ident, item_, extra_attrs) = self.parse_item_type();
4495 return iovi_item(self.mk_item(lo, self.last_span.hi, ident, item_,
4497 maybe_append(attrs, extra_attrs)));
4499 if self.eat_keyword(keywords::Enum) {
4501 let (ident, item_, extra_attrs) = self.parse_item_enum();
4502 return iovi_item(self.mk_item(lo, self.last_span.hi, ident, item_,
4504 maybe_append(attrs, extra_attrs)));
4506 if self.eat_keyword(keywords::Trait) {
4508 let (ident, item_, extra_attrs) = self.parse_item_trait();
4509 return iovi_item(self.mk_item(lo, self.last_span.hi, ident, item_,
4511 maybe_append(attrs, extra_attrs)));
4513 if self.eat_keyword(keywords::Impl) {
4515 let (ident, item_, extra_attrs) = self.parse_item_impl();
4516 return iovi_item(self.mk_item(lo, self.last_span.hi, ident, item_,
4518 maybe_append(attrs, extra_attrs)));
4520 if self.eat_keyword(keywords::Struct) {
4522 let (ident, item_, extra_attrs) = self.parse_item_struct();
4523 return iovi_item(self.mk_item(lo, self.last_span.hi, ident, item_,
4525 maybe_append(attrs, extra_attrs)));
4527 self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility)
4530 // parse a foreign item; on failure, return iovi_none.
4531 fn parse_foreign_item(&self,
4532 attrs: ~[Attribute],
4533 macros_allowed: bool)
4534 -> item_or_view_item {
4535 maybe_whole!(iovi self, nt_item);
4536 let lo = self.span.lo;
4538 let visibility = self.parse_visibility();
4540 if self.is_keyword(keywords::Static) {
4541 // FOREIGN STATIC ITEM
4542 let item = self.parse_item_foreign_static(visibility, attrs);
4543 return iovi_foreign_item(item);
4545 if self.is_keyword(keywords::Fn) || self.is_keyword(keywords::Unsafe) {
4546 // FOREIGN FUNCTION ITEM
4547 let item = self.parse_item_foreign_fn(visibility, attrs);
4548 return iovi_foreign_item(item);
4550 self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility)
4553 // this is the fall-through for parsing items.
4554 fn parse_macro_use_or_failure(
4556 attrs: ~[Attribute],
4557 macros_allowed: bool,
4559 visibility : visibility
4560 ) -> item_or_view_item {
4561 if macros_allowed && !token::is_any_keyword(self.token)
4562 && self.look_ahead(1, |t| *t == token::NOT)
4563 && (self.look_ahead(2, |t| is_plain_ident(t))
4564 || self.look_ahead(2, |t| *t == token::LPAREN)
4565 || self.look_ahead(2, |t| *t == token::LBRACE)) {
4566 // MACRO INVOCATION ITEM
4569 let pth = self.parse_path(NoTypesAllowed).path;
4570 self.expect(&token::NOT);
4572 // a 'special' identifier (like what `macro_rules!` uses)
4573 // is optional. We should eventually unify invoc syntax
4575 let id = if is_plain_ident(&*self.token) {
4578 token::special_idents::invalid // no special identifier
4580 // eat a matched-delimiter token tree:
4581 let tts = match *self.token {
4582 token::LPAREN | token::LBRACE => {
4583 let ket = token::flip_delimiter(&*self.token);
4585 self.parse_seq_to_end(&ket,
4587 |p| p.parse_token_tree())
4589 _ => self.fatal("expected open delimiter")
4591 // single-variant-enum... :
4592 let m = ast::mac_invoc_tt(pth, tts, EMPTY_CTXT);
4593 let m: ast::mac = codemap::Spanned { node: m,
4594 span: mk_sp(self.span.lo,
4596 let item_ = item_mac(m);
4597 return iovi_item(self.mk_item(lo, self.last_span.hi, id, item_,
4598 visibility, attrs));
4601 // FAILURE TO PARSE ITEM
4602 if visibility != inherited {
4603 let mut s = ~"unmatched visibility `";
4604 if visibility == public {
4610 self.span_fatal(*self.last_span, s);
4612 return iovi_none(attrs);
4615 pub fn parse_item(&self, attrs: ~[Attribute]) -> Option<@ast::item> {
4616 match self.parse_item_or_view_item(attrs, true) {
4617 iovi_none(_) => None,
4618 iovi_view_item(_) =>
4619 self.fatal("view items are not allowed here"),
4620 iovi_foreign_item(_) =>
4621 self.fatal("foreign items are not allowed here"),
4622 iovi_item(item) => Some(item)
4626 // parse, e.g., "use a::b::{z,y}"
4627 fn parse_use(&self) -> view_item_ {
4628 return view_item_use(self.parse_view_paths());
4632 // matches view_path : MOD? IDENT EQ non_global_path
4633 // | MOD? non_global_path MOD_SEP LBRACE RBRACE
4634 // | MOD? non_global_path MOD_SEP LBRACE ident_seq RBRACE
4635 // | MOD? non_global_path MOD_SEP STAR
4636 // | MOD? non_global_path
4637 fn parse_view_path(&self) -> @view_path {
4638 let lo = self.span.lo;
4640 let first_ident = self.parse_ident();
4641 let mut path = ~[first_ident];
4642 debug!("parsed view_path: {}", self.id_to_str(first_ident));
4647 path = ~[self.parse_ident()];
4648 while *self.token == token::MOD_SEP {
4650 let id = self.parse_ident();
4653 let path = ast::Path {
4654 span: mk_sp(lo, self.span.hi),
4656 segments: path.move_iter().map(|identifier| {
4658 identifier: identifier,
4660 types: opt_vec::Empty,
4664 return @spanned(lo, self.span.hi,
4665 view_path_simple(first_ident,
4667 ast::DUMMY_NODE_ID));
4671 // foo::bar or foo::{a,b,c} or foo::*
4672 while *self.token == token::MOD_SEP {
4676 token::IDENT(i, _) => {
4681 // foo::bar::{a,b,c}
4683 let idents = self.parse_unspanned_seq(
4686 seq_sep_trailing_allowed(token::COMMA),
4687 |p| p.parse_path_list_ident()
4689 let path = ast::Path {
4690 span: mk_sp(lo, self.span.hi),
4692 segments: path.move_iter().map(|identifier| {
4694 identifier: identifier,
4696 types: opt_vec::Empty,
4700 return @spanned(lo, self.span.hi,
4701 view_path_list(path, idents, ast::DUMMY_NODE_ID));
4705 token::BINOP(token::STAR) => {
4707 let path = ast::Path {
4708 span: mk_sp(lo, self.span.hi),
4710 segments: path.move_iter().map(|identifier| {
4712 identifier: identifier,
4714 types: opt_vec::Empty,
4718 return @spanned(lo, self.span.hi,
4719 view_path_glob(path, ast::DUMMY_NODE_ID));
4728 let last = path[path.len() - 1u];
4729 let path = ast::Path {
4730 span: mk_sp(lo, self.span.hi),
4732 segments: path.move_iter().map(|identifier| {
4734 identifier: identifier,
4736 types: opt_vec::Empty,
4742 view_path_simple(last, path, ast::DUMMY_NODE_ID));
4745 // matches view_paths = view_path | view_path , view_paths
4746 fn parse_view_paths(&self) -> ~[@view_path] {
4747 let mut vp = ~[self.parse_view_path()];
4748 while *self.token == token::COMMA {
4750 vp.push(self.parse_view_path());
4755 fn is_view_item(&self) -> bool {
4756 if !self.is_keyword(keywords::Pub) && !self.is_keyword(keywords::Priv) {
4757 token::is_keyword(keywords::Use, self.token)
4758 || (token::is_keyword(keywords::Extern, self.token) &&
4760 |t| token::is_keyword(keywords::Mod, t)))
4762 self.look_ahead(1, |t| token::is_keyword(keywords::Use, t))
4763 || (self.look_ahead(1,
4764 |t| token::is_keyword(keywords::Extern,
4767 |t| token::is_keyword(keywords::Mod, t)))
4771 // parse a view item.
4774 attrs: ~[Attribute],
4777 let lo = self.span.lo;
4778 let node = if self.eat_keyword(keywords::Use) {
4780 } else if self.eat_keyword(keywords::Extern) {
4781 self.expect_keyword(keywords::Mod);
4782 let ident = self.parse_ident();
4783 let path = if *self.token == token::EQ {
4785 Some(self.parse_str())
4788 let metadata = self.parse_optional_meta();
4789 view_item_extern_mod(ident, path, metadata, ast::DUMMY_NODE_ID)
4791 self.bug("expected view item");
4793 self.expect(&token::SEMI);
4794 ast::view_item { node: node,
4797 span: mk_sp(lo, self.last_span.hi) }
4800 // Parses a sequence of items. Stops when it finds program
4801 // text that can't be parsed as an item
4802 // - mod_items uses extern_mod_allowed = true
4803 // - block_tail_ uses extern_mod_allowed = false
4804 fn parse_items_and_view_items(&self,
4805 first_item_attrs: ~[Attribute],
4806 mut extern_mod_allowed: bool,
4807 macros_allowed: bool)
4808 -> ParsedItemsAndViewItems {
4809 let mut attrs = vec::append(first_item_attrs,
4810 self.parse_outer_attributes());
4811 // First, parse view items.
4812 let mut view_items : ~[ast::view_item] = ~[];
4813 let mut items = ~[];
4815 // I think this code would probably read better as a single
4816 // loop with a mutable three-state-variable (for extern mods,
4817 // view items, and regular items) ... except that because
4818 // of macros, I'd like to delay that entire check until later.
4820 match self.parse_item_or_view_item(attrs, macros_allowed) {
4821 iovi_none(attrs) => {
4822 return ParsedItemsAndViewItems {
4823 attrs_remaining: attrs,
4824 view_items: view_items,
4829 iovi_view_item(view_item) => {
4830 match view_item.node {
4831 view_item_use(*) => {
4832 // `extern mod` must precede `use`.
4833 extern_mod_allowed = false;
4835 view_item_extern_mod(*)
4836 if !extern_mod_allowed => {
4837 self.span_err(view_item.span,
4838 "\"extern mod\" declarations are not allowed here");
4840 view_item_extern_mod(*) => {}
4842 view_items.push(view_item);
4844 iovi_item(item) => {
4846 attrs = self.parse_outer_attributes();
4849 iovi_foreign_item(_) => {
4853 attrs = self.parse_outer_attributes();
4856 // Next, parse items.
4858 match self.parse_item_or_view_item(attrs, macros_allowed) {
4859 iovi_none(returned_attrs) => {
4860 attrs = returned_attrs;
4863 iovi_view_item(view_item) => {
4864 attrs = self.parse_outer_attributes();
4865 self.span_err(view_item.span,
4866 "`use` and `extern mod` declarations must precede items");
4868 iovi_item(item) => {
4869 attrs = self.parse_outer_attributes();
4872 iovi_foreign_item(_) => {
4878 ParsedItemsAndViewItems {
4879 attrs_remaining: attrs,
4880 view_items: view_items,
4886 // Parses a sequence of foreign items. Stops when it finds program
4887 // text that can't be parsed as an item
4888 fn parse_foreign_items(&self, first_item_attrs: ~[Attribute],
4889 macros_allowed: bool)
4890 -> ParsedItemsAndViewItems {
4891 let mut attrs = vec::append(first_item_attrs,
4892 self.parse_outer_attributes());
4893 let mut foreign_items = ~[];
4895 match self.parse_foreign_item(attrs, macros_allowed) {
4896 iovi_none(returned_attrs) => {
4897 if *self.token == token::RBRACE {
4898 attrs = returned_attrs;
4903 iovi_view_item(view_item) => {
4904 // I think this can't occur:
4905 self.span_err(view_item.span,
4906 "`use` and `extern mod` declarations must precede items");
4908 iovi_item(item) => {
4909 // FIXME #5668: this will occur for a macro invocation:
4910 self.span_fatal(item.span, "macros cannot expand to foreign items");
4912 iovi_foreign_item(foreign_item) => {
4913 foreign_items.push(foreign_item);
4916 attrs = self.parse_outer_attributes();
4919 ParsedItemsAndViewItems {
4920 attrs_remaining: attrs,
4923 foreign_items: foreign_items
4927 // Parses a source module as a crate. This is the main
4928 // entry point for the parser.
4929 pub fn parse_crate_mod(&self) -> Crate {
4930 let lo = self.span.lo;
4931 // parse the crate's inner attrs, maybe (oops) one
4932 // of the attrs of an item:
4933 let (inner, next) = self.parse_inner_attrs_and_next();
4934 let first_item_outer_attrs = next;
4935 // parse the items inside the crate:
4936 let m = self.parse_mod_items(token::EOF, first_item_outer_attrs);
4941 config: self.cfg.clone(),
4942 span: mk_sp(lo, self.span.lo)
4946 pub fn parse_optional_str(&self) -> Option<(@str, ast::StrStyle)> {
4947 let (s, style) = match *self.token {
4948 token::LIT_STR(s) => (s, ast::CookedStr),
4949 token::LIT_STR_RAW(s, n) => (s, ast::RawStr(n)),
4953 Some((ident_to_str(&s), style))
4956 pub fn parse_str(&self) -> (@str, StrStyle) {
4957 match self.parse_optional_str() {
4959 _ => self.fatal("expected string literal")