1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
14 use ast::{BareFnTy, ClosureTy};
15 use ast::{RegionTyParamBound, TraitTyParamBound};
16 use ast::{Provided, Public, FnStyle};
17 use ast::{Mod, BiAdd, Arg, Arm, Attribute, BindByRef, BindByValue};
18 use ast::{BiBitAnd, BiBitOr, BiBitXor, Block};
19 use ast::{BlockCheckMode, UnBox};
20 use ast::{Crate, CrateConfig, Decl, DeclItem};
21 use ast::{DeclLocal, DefaultBlock, UnDeref, BiDiv, EMPTY_CTXT, EnumDef, ExplicitSelf};
22 use ast::{Expr, Expr_, ExprAddrOf, ExprMatch, ExprAgain};
23 use ast::{ExprAssign, ExprAssignOp, ExprBinary, ExprBlock, ExprBox};
24 use ast::{ExprBreak, ExprCall, ExprCast};
25 use ast::{ExprField, ExprFnBlock, ExprIf, ExprIndex};
26 use ast::{ExprLit, ExprLoop, ExprMac};
27 use ast::{ExprMethodCall, ExprParen, ExprPath, ExprProc};
28 use ast::{ExprRepeat, ExprRet, ExprStruct, ExprTup, ExprUnary};
29 use ast::{ExprVec, ExprVstore, ExprVstoreSlice};
30 use ast::{ExprVstoreMutSlice, ExprWhile, ExprForLoop, ExternFn, Field, FnDecl};
31 use ast::{ExprVstoreUniq, Once, Many};
32 use ast::{ForeignItem, ForeignItemStatic, ForeignItemFn, ForeignMod};
33 use ast::{Ident, NormalFn, Inherited, Item, Item_, ItemStatic};
34 use ast::{ItemEnum, ItemFn, ItemForeignMod, ItemImpl};
35 use ast::{ItemMac, ItemMod, ItemStruct, ItemTrait, ItemTy, Lit, Lit_};
36 use ast::{LitBool, LitFloat, LitFloatUnsuffixed, LitInt, LitChar};
37 use ast::{LitIntUnsuffixed, LitNil, LitStr, LitUint, Local};
38 use ast::{MutImmutable, MutMutable, Mac_, MacInvocTT, Matcher, MatchNonterminal};
39 use ast::{MatchSeq, MatchTok, Method, MutTy, BiMul, Mutability};
40 use ast::{NamedField, UnNeg, NoReturn, UnNot, P, Pat, PatEnum};
41 use ast::{PatIdent, PatLit, PatRange, PatRegion, PatStruct};
42 use ast::{PatTup, PatUniq, PatWild, PatWildMulti};
43 use ast::{BiRem, Required};
44 use ast::{RetStyle, Return, BiShl, BiShr, Stmt, StmtDecl};
45 use ast::{Sized, DynSize, StaticSize};
46 use ast::{StmtExpr, StmtSemi, StmtMac, StructDef, StructField};
47 use ast::{StructVariantKind, BiSub};
49 use ast::{SelfRegion, SelfStatic, SelfUniq, SelfValue};
50 use ast::{TokenTree, TraitMethod, TraitRef, TTDelim, TTSeq, TTTok};
51 use ast::{TTNonterminal, TupleVariantKind, Ty, Ty_, TyBot, TyBox};
52 use ast::{TypeField, TyFixedLengthVec, TyClosure, TyProc, TyBareFn};
53 use ast::{TyTypeof, TyInfer, TypeMethod};
54 use ast::{TyNil, TyParam, TyParamBound, TyPath, TyPtr, TyRptr};
55 use ast::{TyTup, TyU32, TyUniq, TyVec, UnUniq};
56 use ast::{UnnamedField, UnsafeBlock, UnsafeFn, ViewItem};
57 use ast::{ViewItem_, ViewItemExternCrate, ViewItemUse};
58 use ast::{ViewPath, ViewPathGlob, ViewPathList, ViewPathSimple};
61 use ast_util::{as_prec, lit_is_str, operator_prec};
63 use codemap::{Span, BytePos, Spanned, spanned, mk_sp};
65 use parse::attr::ParserAttr;
67 use parse::common::{SeqSep, seq_sep_none};
68 use parse::common::{seq_sep_trailing_disallowed, seq_sep_trailing_allowed};
69 use parse::lexer::Reader;
70 use parse::lexer::TokenAndSpan;
71 use parse::obsolete::*;
72 use parse::token::{INTERPOLATED, InternedString, can_begin_expr};
73 use parse::token::{is_ident, is_ident_or_path, is_plain_ident};
74 use parse::token::{keywords, special_idents, token_to_binop};
76 use parse::{new_sub_parser_from_file, ParseSess};
77 use owned_slice::OwnedSlice;
79 use collections::HashSet;
80 use std::mem::replace;
82 use std::strbuf::StrBuf;
84 #[allow(non_camel_case_types)]
86 pub enum restriction {
90 RESTRICT_NO_BAR_OR_DOUBLEBAR_OP,
93 type ItemInfo = (Ident, Item_, Option<Vec<Attribute> >);
95 /// How to parse a path. There are four different kinds of paths, all of which
96 /// are parsed somewhat differently.
98 pub enum PathParsingMode {
99 /// A path with no type parameters; e.g. `foo::bar::Baz`
101 /// A path with a lifetime and type parameters, with no double colons
102 /// before the type parameters; e.g. `foo::bar<'a>::Baz<T>`
103 LifetimeAndTypesWithoutColons,
104 /// A path with a lifetime and type parameters with double colons before
105 /// the type parameters; e.g. `foo::bar::<'a>::Baz::<T>`
106 LifetimeAndTypesWithColons,
107 /// A path with a lifetime and type parameters with bounds before the last
108 /// set of type parameters only; e.g. `foo::bar<'a>::Baz:X+Y<T>` This
109 /// form does not use extra double colons.
110 LifetimeAndTypesAndBounds,
113 /// A path paired with optional type bounds.
114 pub struct PathAndBounds {
116 pub bounds: Option<OwnedSlice<TyParamBound>>,
119 enum ItemOrViewItem {
120 // Indicates a failure to parse any kind of item. The attributes are
122 IoviNone(Vec<Attribute> ),
124 IoviForeignItem(@ForeignItem),
125 IoviViewItem(ViewItem)
128 /* The expr situation is not as complex as I thought it would be.
129 The important thing is to make sure that lookahead doesn't balk
130 at INTERPOLATED tokens */
131 macro_rules! maybe_whole_expr (
134 let mut maybe_path = match ($p).token {
135 INTERPOLATED(token::NtPath(ref pt)) => Some((**pt).clone()),
138 let ret = match ($p).token {
139 INTERPOLATED(token::NtExpr(e)) => {
142 INTERPOLATED(token::NtPath(_)) => {
143 let pt = maybe_path.take_unwrap();
144 Some($p.mk_expr(($p).span.lo, ($p).span.hi, ExprPath(pt)))
159 macro_rules! maybe_whole (
160 ($p:expr, $constructor:ident) => (
162 let __found__ = match ($p).token {
163 INTERPOLATED(token::$constructor(_)) => {
164 Some(($p).bump_and_get())
169 Some(INTERPOLATED(token::$constructor(x))) => {
176 (no_clone $p:expr, $constructor:ident) => (
178 let __found__ = match ($p).token {
179 INTERPOLATED(token::$constructor(_)) => {
180 Some(($p).bump_and_get())
185 Some(INTERPOLATED(token::$constructor(x))) => {
192 (deref $p:expr, $constructor:ident) => (
194 let __found__ = match ($p).token {
195 INTERPOLATED(token::$constructor(_)) => {
196 Some(($p).bump_and_get())
201 Some(INTERPOLATED(token::$constructor(x))) => {
208 (Some $p:expr, $constructor:ident) => (
210 let __found__ = match ($p).token {
211 INTERPOLATED(token::$constructor(_)) => {
212 Some(($p).bump_and_get())
217 Some(INTERPOLATED(token::$constructor(x))) => {
218 return Some(x.clone()),
224 (iovi $p:expr, $constructor:ident) => (
226 let __found__ = match ($p).token {
227 INTERPOLATED(token::$constructor(_)) => {
228 Some(($p).bump_and_get())
233 Some(INTERPOLATED(token::$constructor(x))) => {
234 return IoviItem(x.clone())
240 (pair_empty $p:expr, $constructor:ident) => (
242 let __found__ = match ($p).token {
243 INTERPOLATED(token::$constructor(_)) => {
244 Some(($p).bump_and_get())
249 Some(INTERPOLATED(token::$constructor(x))) => {
250 return (Vec::new(), x)
259 fn maybe_append(lhs: Vec<Attribute> , rhs: Option<Vec<Attribute> >)
263 Some(ref attrs) => lhs.append(attrs.as_slice())
268 struct ParsedItemsAndViewItems {
269 attrs_remaining: Vec<Attribute> ,
270 view_items: Vec<ViewItem> ,
272 foreign_items: Vec<@ForeignItem> }
274 /* ident is handled by common.rs */
276 pub fn Parser<'a>(sess: &'a ParseSess, cfg: ast::CrateConfig, mut rdr: ~Reader:)
278 let tok0 = rdr.next_token();
280 let placeholder = TokenAndSpan {
281 tok: token::UNDERSCORE,
287 interner: token::get_ident_interner(),
303 restriction: UNRESTRICTED,
305 obsolete_set: HashSet::new(),
306 mod_path_stack: Vec::new(),
307 open_braces: Vec::new(),
311 pub struct Parser<'a> {
312 pub sess: &'a ParseSess,
313 // the current token:
314 pub token: token::Token,
315 // the span of the current token:
317 // the span of the prior token:
319 pub cfg: CrateConfig,
320 // the previous token or None (only stashed sometimes).
321 pub last_token: Option<~token::Token>,
322 pub buffer: [TokenAndSpan, ..4],
323 pub buffer_start: int,
325 pub tokens_consumed: uint,
326 pub restriction: restriction,
327 pub quote_depth: uint, // not (yet) related to the quasiquoter
328 pub reader: ~Reader:,
329 pub interner: Rc<token::IdentInterner>,
330 /// The set of seen errors about obsolete syntax. Used to suppress
331 /// extra detail when the same error is seen twice
332 pub obsolete_set: HashSet<ObsoleteSyntax>,
333 /// Used to determine the path to externally loaded source files
334 pub mod_path_stack: Vec<InternedString>,
335 /// Stack of spans of open delimiters. Used for error message.
336 pub open_braces: Vec<Span>,
339 fn is_plain_ident_or_underscore(t: &token::Token) -> bool {
340 is_plain_ident(t) || *t == token::UNDERSCORE
343 impl<'a> Parser<'a> {
344 // convert a token to a string using self's reader
345 pub fn token_to_str(token: &token::Token) -> ~str {
349 // convert the current token to a string using self's reader
350 pub fn this_token_to_str(&mut self) -> ~str {
351 Parser::token_to_str(&self.token)
354 pub fn unexpected_last(&mut self, t: &token::Token) -> ! {
355 let token_str = Parser::token_to_str(t);
356 self.span_fatal(self.last_span, format!("unexpected token: `{}`",
360 pub fn unexpected(&mut self) -> ! {
361 let this_token = self.this_token_to_str();
362 self.fatal(format!("unexpected token: `{}`", this_token));
365 // expect and consume the token t. Signal an error if
366 // the next token is not t.
367 pub fn expect(&mut self, t: &token::Token) {
368 if self.token == *t {
371 let token_str = Parser::token_to_str(t);
372 let this_token_str = self.this_token_to_str();
373 self.fatal(format!("expected `{}` but found `{}`",
379 // Expect next token to be edible or inedible token. If edible,
380 // then consume it; if inedible, then return without consuming
381 // anything. Signal a fatal error if next token is unexpected.
382 pub fn expect_one_of(&mut self,
383 edible: &[token::Token],
384 inedible: &[token::Token]) {
385 fn tokens_to_str(tokens: &[token::Token]) -> ~str {
386 let mut i = tokens.iter();
387 // This might be a sign we need a connect method on Iterator.
388 let b = i.next().map_or("".to_owned(), |t| Parser::token_to_str(t));
389 i.fold(b, |b,a| b + "`, `" + Parser::token_to_str(a))
391 if edible.contains(&self.token) {
393 } else if inedible.contains(&self.token) {
394 // leave it in the input
396 let expected = edible.iter().map(|x| (*x).clone()).collect::<Vec<_>>().append(inedible);
397 let expect = tokens_to_str(expected.as_slice());
398 let actual = self.this_token_to_str();
400 if expected.len() != 1 {
401 format!("expected one of `{}` but found `{}`", expect, actual)
403 format!("expected `{}` but found `{}`", expect, actual)
409 // Check for erroneous `ident { }`; if matches, signal error and
410 // recover (without consuming any expected input token). Returns
411 // true if and only if input was consumed for recovery.
412 pub fn check_for_erroneous_unit_struct_expecting(&mut self, expected: &[token::Token]) -> bool {
413 if self.token == token::LBRACE
414 && expected.iter().all(|t| *t != token::LBRACE)
415 && self.look_ahead(1, |t| *t == token::RBRACE) {
416 // matched; signal non-fatal error and recover.
417 self.span_err(self.span,
418 "unit-like struct construction is written with no trailing `{ }`");
419 self.eat(&token::LBRACE);
420 self.eat(&token::RBRACE);
427 // Commit to parsing a complete expression `e` expected to be
428 // followed by some token from the set edible + inedible. Recover
429 // from anticipated input errors, discarding erroneous characters.
430 pub fn commit_expr(&mut self, e: @Expr, edible: &[token::Token], inedible: &[token::Token]) {
431 debug!("commit_expr {:?}", e);
434 // might be unit-struct construction; check for recoverableinput error.
435 let expected = edible.iter().map(|x| (*x).clone()).collect::<Vec<_>>()
437 self.check_for_erroneous_unit_struct_expecting(
438 expected.as_slice());
442 self.expect_one_of(edible, inedible)
445 pub fn commit_expr_expecting(&mut self, e: @Expr, edible: token::Token) {
446 self.commit_expr(e, &[edible], &[])
449 // Commit to parsing a complete statement `s`, which expects to be
450 // followed by some token from the set edible + inedible. Check
451 // for recoverable input errors, discarding erroneous characters.
452 pub fn commit_stmt(&mut self, s: @Stmt, edible: &[token::Token], inedible: &[token::Token]) {
453 debug!("commit_stmt {:?}", s);
454 let _s = s; // unused, but future checks might want to inspect `s`.
455 if self.last_token.as_ref().map_or(false, |t| is_ident_or_path(*t)) {
456 let expected = edible.iter().map(|x| (*x).clone()).collect::<Vec<_>>()
457 .append(inedible.as_slice());
458 self.check_for_erroneous_unit_struct_expecting(
459 expected.as_slice());
461 self.expect_one_of(edible, inedible)
464 pub fn commit_stmt_expecting(&mut self, s: @Stmt, edible: token::Token) {
465 self.commit_stmt(s, &[edible], &[])
468 pub fn parse_ident(&mut self) -> ast::Ident {
469 self.check_strict_keywords();
470 self.check_reserved_keywords();
472 token::IDENT(i, _) => {
476 token::INTERPOLATED(token::NtIdent(..)) => {
477 self.bug("ident interpolation not converted to real token");
480 let token_str = self.this_token_to_str();
481 self.fatal(format!( "expected ident, found `{}`", token_str))
486 pub fn parse_path_list_ident(&mut self) -> ast::PathListIdent {
487 let lo = self.span.lo;
488 let ident = self.parse_ident();
489 let hi = self.last_span.hi;
490 spanned(lo, hi, ast::PathListIdent_ { name: ident,
491 id: ast::DUMMY_NODE_ID })
494 // consume token 'tok' if it exists. Returns true if the given
495 // token was present, false otherwise.
496 pub fn eat(&mut self, tok: &token::Token) -> bool {
497 let is_present = self.token == *tok;
498 if is_present { self.bump() }
502 pub fn is_keyword(&mut self, kw: keywords::Keyword) -> bool {
503 token::is_keyword(kw, &self.token)
506 // if the next token is the given keyword, eat it and return
507 // true. Otherwise, return false.
508 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
509 let is_kw = match self.token {
510 token::IDENT(sid, false) => kw.to_ident().name == sid.name,
513 if is_kw { self.bump() }
517 // if the given word is not a keyword, signal an error.
518 // if the next token is not the given word, signal an error.
519 // otherwise, eat it.
520 pub fn expect_keyword(&mut self, kw: keywords::Keyword) {
521 if !self.eat_keyword(kw) {
522 let id_interned_str = token::get_ident(kw.to_ident());
523 let token_str = self.this_token_to_str();
524 self.fatal(format!("expected `{}`, found `{}`",
525 id_interned_str, token_str))
529 // signal an error if the given string is a strict keyword
530 pub fn check_strict_keywords(&mut self) {
531 if token::is_strict_keyword(&self.token) {
532 let token_str = self.this_token_to_str();
533 self.span_err(self.span,
534 format!("found `{}` in ident position", token_str));
538 // signal an error if the current token is a reserved keyword
539 pub fn check_reserved_keywords(&mut self) {
540 if token::is_reserved_keyword(&self.token) {
541 let token_str = self.this_token_to_str();
542 self.fatal(format!("`{}` is a reserved keyword", token_str))
546 // Expect and consume an `&`. If `&&` is seen, replace it with a single
547 // `&` and continue. If an `&` is not seen, signal an error.
548 fn expect_and(&mut self) {
550 token::BINOP(token::AND) => self.bump(),
552 let lo = self.span.lo + BytePos(1);
553 self.replace_token(token::BINOP(token::AND), lo, self.span.hi)
556 let token_str = self.this_token_to_str();
558 Parser::token_to_str(&token::BINOP(token::AND));
559 self.fatal(format!("expected `{}`, found `{}`",
566 // Expect and consume a `|`. If `||` is seen, replace it with a single
567 // `|` and continue. If a `|` is not seen, signal an error.
568 fn expect_or(&mut self) {
570 token::BINOP(token::OR) => self.bump(),
572 let lo = self.span.lo + BytePos(1);
573 self.replace_token(token::BINOP(token::OR), lo, self.span.hi)
576 let token_str = self.this_token_to_str();
578 Parser::token_to_str(&token::BINOP(token::OR));
579 self.fatal(format!("expected `{}`, found `{}`",
586 // Parse a sequence bracketed by `|` and `|`, stopping before the `|`.
587 fn parse_seq_to_before_or<T>(
590 f: |&mut Parser| -> T)
592 let mut first = true;
593 let mut vector = Vec::new();
594 while self.token != token::BINOP(token::OR) &&
595 self.token != token::OROR {
607 // expect and consume a GT. if a >> is seen, replace it
608 // with a single > and continue. If a GT is not seen,
610 pub fn expect_gt(&mut self) {
612 token::GT => self.bump(),
613 token::BINOP(token::SHR) => {
614 let lo = self.span.lo + BytePos(1);
615 self.replace_token(token::GT, lo, self.span.hi)
618 let gt_str = Parser::token_to_str(&token::GT);
619 let this_token_str = self.this_token_to_str();
620 self.fatal(format!("expected `{}`, found `{}`",
627 // parse a sequence bracketed by '<' and '>', stopping
629 pub fn parse_seq_to_before_gt<T>(
631 sep: Option<token::Token>,
632 f: |&mut Parser| -> T)
634 let mut first = true;
635 let mut v = Vec::new();
636 while self.token != token::GT
637 && self.token != token::BINOP(token::SHR) {
640 if first { first = false; }
641 else { self.expect(t); }
647 return OwnedSlice::from_vec(v);
650 pub fn parse_seq_to_gt<T>(
652 sep: Option<token::Token>,
653 f: |&mut Parser| -> T)
655 let v = self.parse_seq_to_before_gt(sep, f);
660 // parse a sequence, including the closing delimiter. The function
661 // f must consume tokens until reaching the next separator or
663 pub fn parse_seq_to_end<T>(
667 f: |&mut Parser| -> T)
669 let val = self.parse_seq_to_before_end(ket, sep, f);
674 // parse a sequence, not including the closing delimiter. The function
675 // f must consume tokens until reaching the next separator or
677 pub fn parse_seq_to_before_end<T>(
681 f: |&mut Parser| -> T)
683 let mut first: bool = true;
685 while self.token != *ket {
688 if first { first = false; }
689 else { self.expect(t); }
693 if sep.trailing_sep_allowed && self.token == *ket { break; }
699 // parse a sequence, including the closing delimiter. The function
700 // f must consume tokens until reaching the next separator or
702 pub fn parse_unspanned_seq<T>(
707 f: |&mut Parser| -> T)
710 let result = self.parse_seq_to_before_end(ket, sep, f);
715 // parse a sequence parameter of enum variant. For consistency purposes,
716 // these should not be empty.
717 pub fn parse_enum_variant_seq<T>(
722 f: |&mut Parser| -> T)
724 let result = self.parse_unspanned_seq(bra, ket, sep, f);
725 if result.is_empty() {
726 self.span_err(self.last_span,
727 "nullary enum variants are written with no trailing `( )`");
732 // NB: Do not use this function unless you actually plan to place the
733 // spanned list in the AST.
739 f: |&mut Parser| -> T)
740 -> Spanned<Vec<T> > {
741 let lo = self.span.lo;
743 let result = self.parse_seq_to_before_end(ket, sep, f);
744 let hi = self.span.hi;
746 spanned(lo, hi, result)
749 // advance the parser by one token
750 pub fn bump(&mut self) {
751 self.last_span = self.span;
752 // Stash token for error recovery (sometimes; clone is not necessarily cheap).
753 self.last_token = if is_ident_or_path(&self.token) {
754 Some(~self.token.clone())
758 let next = if self.buffer_start == self.buffer_end {
759 self.reader.next_token()
761 // Avoid token copies with `replace`.
762 let buffer_start = self.buffer_start as uint;
763 let next_index = (buffer_start + 1) & 3 as uint;
764 self.buffer_start = next_index as int;
766 let placeholder = TokenAndSpan {
767 tok: token::UNDERSCORE,
770 replace(&mut self.buffer[buffer_start], placeholder)
773 self.token = next.tok;
774 self.tokens_consumed += 1u;
777 // Advance the parser by one token and return the bumped token.
778 pub fn bump_and_get(&mut self) -> token::Token {
779 let old_token = replace(&mut self.token, token::UNDERSCORE);
784 // EFFECT: replace the current token and span with the given one
785 pub fn replace_token(&mut self,
789 self.last_span = mk_sp(self.span.lo, lo);
791 self.span = mk_sp(lo, hi);
793 pub fn buffer_length(&mut self) -> int {
794 if self.buffer_start <= self.buffer_end {
795 return self.buffer_end - self.buffer_start;
797 return (4 - self.buffer_start) + self.buffer_end;
799 pub fn look_ahead<R>(&mut self, distance: uint, f: |&token::Token| -> R)
801 let dist = distance as int;
802 while self.buffer_length() < dist {
803 self.buffer[self.buffer_end as uint] = self.reader.next_token();
804 self.buffer_end = (self.buffer_end + 1) & 3;
806 f(&self.buffer[((self.buffer_start + dist - 1) & 3) as uint].tok)
808 pub fn fatal(&mut self, m: &str) -> ! {
809 self.sess.span_diagnostic.span_fatal(self.span, m)
811 pub fn span_fatal(&mut self, sp: Span, m: &str) -> ! {
812 self.sess.span_diagnostic.span_fatal(sp, m)
814 pub fn span_note(&mut self, sp: Span, m: &str) {
815 self.sess.span_diagnostic.span_note(sp, m)
817 pub fn bug(&mut self, m: &str) -> ! {
818 self.sess.span_diagnostic.span_bug(self.span, m)
820 pub fn warn(&mut self, m: &str) {
821 self.sess.span_diagnostic.span_warn(self.span, m)
823 pub fn span_warn(&mut self, sp: Span, m: &str) {
824 self.sess.span_diagnostic.span_warn(sp, m)
826 pub fn span_err(&mut self, sp: Span, m: &str) {
827 self.sess.span_diagnostic.span_err(sp, m)
829 pub fn abort_if_errors(&mut self) {
830 self.sess.span_diagnostic.handler().abort_if_errors();
833 pub fn id_to_interned_str(&mut self, id: Ident) -> InternedString {
837 // Is the current token one of the keywords that signals a bare function
839 pub fn token_is_bare_fn_keyword(&mut self) -> bool {
840 if token::is_keyword(keywords::Fn, &self.token) {
844 if token::is_keyword(keywords::Unsafe, &self.token) ||
845 token::is_keyword(keywords::Once, &self.token) {
846 return self.look_ahead(1, |t| token::is_keyword(keywords::Fn, t))
852 // Is the current token one of the keywords that signals a closure type?
853 pub fn token_is_closure_keyword(&mut self) -> bool {
854 token::is_keyword(keywords::Unsafe, &self.token) ||
855 token::is_keyword(keywords::Once, &self.token)
858 // Is the current token one of the keywords that signals an old-style
859 // closure type (with explicit sigil)?
860 pub fn token_is_old_style_closure_keyword(&mut self) -> bool {
861 token::is_keyword(keywords::Unsafe, &self.token) ||
862 token::is_keyword(keywords::Once, &self.token) ||
863 token::is_keyword(keywords::Fn, &self.token)
866 pub fn token_is_lifetime(tok: &token::Token) -> bool {
868 token::LIFETIME(..) => true,
873 pub fn get_lifetime(&mut self) -> ast::Ident {
875 token::LIFETIME(ref ident) => *ident,
876 _ => self.bug("not a lifetime"),
880 // parse a TyBareFn type:
881 pub fn parse_ty_bare_fn(&mut self) -> Ty_ {
884 [extern "ABI"] [unsafe] fn <'lt> (S) -> T
885 ^~~~^ ^~~~~~~^ ^~~~^ ^~^ ^
896 let abi = if self.eat_keyword(keywords::Extern) {
897 self.parse_opt_abi().unwrap_or(abi::C)
902 let fn_style = self.parse_unsafety();
903 self.expect_keyword(keywords::Fn);
904 let (decl, lifetimes) = self.parse_ty_fn_decl(true);
905 return TyBareFn(@BareFnTy {
908 lifetimes: lifetimes,
913 // Parses a procedure type (`proc`). The initial `proc` keyword must
914 // already have been parsed.
915 pub fn parse_proc_type(&mut self) -> Ty_ {
918 proc <'lt> (S) [:Bounds] -> T
919 ^~~^ ^~~~^ ^ ^~~~~~~~^ ^
929 let lifetimes = if self.eat(&token::LT) {
930 let lifetimes = self.parse_lifetimes();
937 let (inputs, variadic) = self.parse_fn_args(false, false);
938 let (_, bounds) = self.parse_optional_ty_param_bounds(false);
939 let (ret_style, ret_ty) = self.parse_ret_ty();
940 let decl = P(FnDecl {
951 lifetimes: lifetimes,
955 // parse a TyClosure type
956 pub fn parse_ty_closure(&mut self) -> Ty_ {
959 [unsafe] [once] <'lt> |S| [:Bounds] -> T
960 ^~~~~~~^ ^~~~~^ ^~~~^ ^ ^~~~~~~~^ ^
962 | | | | | Return type
963 | | | | Closure bounds
966 | Once-ness (a.k.a., affine)
971 let fn_style = self.parse_unsafety();
972 let onceness = if self.eat_keyword(keywords::Once) {Once} else {Many};
974 let lifetimes = if self.eat(&token::LT) {
975 let lifetimes = self.parse_lifetimes();
983 let inputs = if self.eat(&token::OROR) {
987 let inputs = self.parse_seq_to_before_or(
989 |p| p.parse_arg_general(false));
994 let (region, bounds) = self.parse_optional_ty_param_bounds(true);
996 let (return_style, output) = self.parse_ret_ty();
997 let decl = P(FnDecl {
1004 TyClosure(@ClosureTy {
1009 lifetimes: lifetimes,
1013 pub fn parse_unsafety(&mut self) -> FnStyle {
1014 if self.eat_keyword(keywords::Unsafe) {
1021 // parse a function type (following the 'fn')
1022 pub fn parse_ty_fn_decl(&mut self, allow_variadic: bool)
1023 -> (P<FnDecl>, Vec<ast::Lifetime>) {
1034 let lifetimes = if self.eat(&token::LT) {
1035 let lifetimes = self.parse_lifetimes();
1042 let (inputs, variadic) = self.parse_fn_args(false, allow_variadic);
1043 let (ret_style, ret_ty) = self.parse_ret_ty();
1044 let decl = P(FnDecl {
1053 // parse the methods in a trait declaration
1054 pub fn parse_trait_methods(&mut self) -> Vec<TraitMethod> {
1055 self.parse_unspanned_seq(
1060 let attrs = p.parse_outer_attributes();
1063 let vis_span = p.span;
1064 let vis = p.parse_visibility();
1065 let style = p.parse_fn_style();
1066 // NB: at the moment, trait methods are public by default; this
1068 let ident = p.parse_ident();
1070 let generics = p.parse_generics();
1072 let (explicit_self, d) = p.parse_fn_decl_with_self(|p| {
1073 // This is somewhat dubious; We don't want to allow argument
1074 // names to be left off if there is a definition...
1075 p.parse_arg_general(false)
1078 let hi = p.last_span.hi;
1082 debug!("parse_trait_methods(): parsing required method");
1083 // NB: at the moment, visibility annotations on required
1084 // methods are ignored; this could change.
1085 if vis != ast::Inherited {
1086 p.obsolete(vis_span, ObsoleteTraitFuncVisibility);
1088 Required(TypeMethod {
1094 explicit_self: explicit_self,
1095 id: ast::DUMMY_NODE_ID,
1100 debug!("parse_trait_methods(): parsing provided method");
1101 let (inner_attrs, body) =
1102 p.parse_inner_attrs_and_block();
1103 let attrs = attrs.append(inner_attrs.as_slice());
1104 Provided(@ast::Method {
1108 explicit_self: explicit_self,
1112 id: ast::DUMMY_NODE_ID,
1113 span: mk_sp(lo, hi),
1119 let token_str = p.this_token_to_str();
1120 p.fatal(format!("expected `;` or `\\{` but found `{}`",
1127 // parse a possibly mutable type
1128 pub fn parse_mt(&mut self) -> MutTy {
1129 let mutbl = self.parse_mutability();
1130 let t = self.parse_ty(false);
1131 MutTy { ty: t, mutbl: mutbl }
1134 // parse [mut/const/imm] ID : TY
1135 // now used only by obsolete record syntax parser...
1136 pub fn parse_ty_field(&mut self) -> TypeField {
1137 let lo = self.span.lo;
1138 let mutbl = self.parse_mutability();
1139 let id = self.parse_ident();
1140 self.expect(&token::COLON);
1141 let ty = self.parse_ty(false);
1142 let hi = ty.span.hi;
1145 mt: MutTy { ty: ty, mutbl: mutbl },
1146 span: mk_sp(lo, hi),
1150 // parse optional return type [ -> TY ] in function decl
1151 pub fn parse_ret_ty(&mut self) -> (RetStyle, P<Ty>) {
1152 return if self.eat(&token::RARROW) {
1153 let lo = self.span.lo;
1154 if self.eat(&token::NOT) {
1158 id: ast::DUMMY_NODE_ID,
1160 span: mk_sp(lo, self.last_span.hi)
1164 (Return, self.parse_ty(false))
1167 let pos = self.span.lo;
1171 id: ast::DUMMY_NODE_ID,
1173 span: mk_sp(pos, pos),
1180 // Useless second parameter for compatibility with quasiquote macros.
1182 pub fn parse_ty(&mut self, _: bool) -> P<Ty> {
1183 maybe_whole!(no_clone self, NtTy);
1185 let lo = self.span.lo;
1187 let t = if self.token == token::LPAREN {
1189 if self.token == token::RPAREN {
1193 // (t) is a parenthesized ty
1194 // (t,) is the type of a tuple with only one field,
1196 let mut ts = vec!(self.parse_ty(false));
1197 let mut one_tuple = false;
1198 while self.token == token::COMMA {
1200 if self.token != token::RPAREN {
1201 ts.push(self.parse_ty(false));
1208 if ts.len() == 1 && !one_tuple {
1209 self.expect(&token::RPAREN);
1214 self.expect(&token::RPAREN);
1217 } else if self.token == token::AT {
1220 TyBox(self.parse_ty(false))
1221 } else if self.token == token::TILDE {
1224 TyUniq(self.parse_ty(false))
1225 } else if self.token == token::BINOP(token::STAR) {
1226 // STAR POINTER (bare pointer?)
1228 TyPtr(self.parse_mt())
1229 } else if self.token == token::LBRACKET {
1231 self.expect(&token::LBRACKET);
1232 let t = self.parse_ty(false);
1234 // Parse the `, ..e` in `[ int, ..e ]`
1235 // where `e` is a const expression
1236 let t = match self.maybe_parse_fixed_vstore() {
1238 Some(suffix) => TyFixedLengthVec(t, suffix)
1240 self.expect(&token::RBRACKET);
1242 } else if self.token == token::BINOP(token::AND) ||
1243 self.token == token::ANDAND {
1246 self.parse_borrowed_pointee()
1247 } else if self.is_keyword(keywords::Extern) ||
1248 self.token_is_bare_fn_keyword() {
1250 self.parse_ty_bare_fn()
1251 } else if self.token_is_closure_keyword() ||
1252 self.token == token::BINOP(token::OR) ||
1253 self.token == token::OROR ||
1254 self.token == token::LT {
1257 // FIXME(pcwalton): Eventually `token::LT` will not unambiguously
1258 // introduce a closure, once procs can have lifetime bounds. We
1259 // will need to refactor the grammar a little bit at that point.
1261 self.parse_ty_closure()
1262 } else if self.eat_keyword(keywords::Typeof) {
1264 // In order to not be ambiguous, the type must be surrounded by parens.
1265 self.expect(&token::LPAREN);
1266 let e = self.parse_expr();
1267 self.expect(&token::RPAREN);
1269 } else if self.eat_keyword(keywords::Proc) {
1270 self.parse_proc_type()
1271 } else if self.token == token::MOD_SEP
1272 || is_ident_or_path(&self.token) {
1277 } = self.parse_path(LifetimeAndTypesAndBounds);
1278 TyPath(path, bounds, ast::DUMMY_NODE_ID)
1279 } else if self.eat(&token::UNDERSCORE) {
1280 // TYPE TO BE INFERRED
1283 let msg = format!("expected type, found token {:?}", self.token);
1287 let sp = mk_sp(lo, self.last_span.hi);
1288 P(Ty {id: ast::DUMMY_NODE_ID, node: t, span: sp})
1291 pub fn parse_borrowed_pointee(&mut self) -> Ty_ {
1292 // look for `&'lt` or `&'foo ` and interpret `foo` as the region name:
1293 let opt_lifetime = self.parse_opt_lifetime();
1295 let mt = self.parse_mt();
1296 return TyRptr(opt_lifetime, mt);
1299 pub fn is_named_argument(&mut self) -> bool {
1300 let offset = match self.token {
1301 token::BINOP(token::AND) => 1,
1303 _ if token::is_keyword(keywords::Mut, &self.token) => 1,
1307 debug!("parser is_named_argument offset:{}", offset);
1310 is_plain_ident_or_underscore(&self.token)
1311 && self.look_ahead(1, |t| *t == token::COLON)
1313 self.look_ahead(offset, |t| is_plain_ident_or_underscore(t))
1314 && self.look_ahead(offset + 1, |t| *t == token::COLON)
1318 // This version of parse arg doesn't necessarily require
1319 // identifier names.
1320 pub fn parse_arg_general(&mut self, require_name: bool) -> Arg {
1321 let pat = if require_name || self.is_named_argument() {
1322 debug!("parse_arg_general parse_pat (require_name:{:?})",
1324 let pat = self.parse_pat();
1326 self.expect(&token::COLON);
1329 debug!("parse_arg_general ident_to_pat");
1330 ast_util::ident_to_pat(ast::DUMMY_NODE_ID,
1332 special_idents::invalid)
1335 let t = self.parse_ty(false);
1340 id: ast::DUMMY_NODE_ID,
1344 // parse a single function argument
1345 pub fn parse_arg(&mut self) -> Arg {
1346 self.parse_arg_general(true)
1349 // parse an argument in a lambda header e.g. |arg, arg|
1350 pub fn parse_fn_block_arg(&mut self) -> Arg {
1351 let pat = self.parse_pat();
1352 let t = if self.eat(&token::COLON) {
1353 self.parse_ty(false)
1356 id: ast::DUMMY_NODE_ID,
1358 span: mk_sp(self.span.lo, self.span.hi),
1364 id: ast::DUMMY_NODE_ID
1368 pub fn maybe_parse_fixed_vstore(&mut self) -> Option<@ast::Expr> {
1369 if self.token == token::COMMA &&
1370 self.look_ahead(1, |t| *t == token::DOTDOT) {
1373 Some(self.parse_expr())
1379 // matches token_lit = LIT_INT | ...
1380 pub fn lit_from_token(&mut self, tok: &token::Token) -> Lit_ {
1382 token::LIT_CHAR(i) => LitChar(i),
1383 token::LIT_INT(i, it) => LitInt(i, it),
1384 token::LIT_UINT(u, ut) => LitUint(u, ut),
1385 token::LIT_INT_UNSUFFIXED(i) => LitIntUnsuffixed(i),
1386 token::LIT_FLOAT(s, ft) => {
1387 LitFloat(self.id_to_interned_str(s), ft)
1389 token::LIT_FLOAT_UNSUFFIXED(s) => {
1390 LitFloatUnsuffixed(self.id_to_interned_str(s))
1392 token::LIT_STR(s) => {
1393 LitStr(self.id_to_interned_str(s), ast::CookedStr)
1395 token::LIT_STR_RAW(s, n) => {
1396 LitStr(self.id_to_interned_str(s), ast::RawStr(n))
1398 token::LPAREN => { self.expect(&token::RPAREN); LitNil },
1399 _ => { self.unexpected_last(tok); }
1403 // matches lit = true | false | token_lit
1404 pub fn parse_lit(&mut self) -> Lit {
1405 let lo = self.span.lo;
1406 let lit = if self.eat_keyword(keywords::True) {
1408 } else if self.eat_keyword(keywords::False) {
1411 let token = self.bump_and_get();
1412 let lit = self.lit_from_token(&token);
1415 codemap::Spanned { node: lit, span: mk_sp(lo, self.last_span.hi) }
1418 // matches '-' lit | lit
1419 pub fn parse_literal_maybe_minus(&mut self) -> @Expr {
1420 let minus_lo = self.span.lo;
1421 let minus_present = self.eat(&token::BINOP(token::MINUS));
1423 let lo = self.span.lo;
1424 let literal = @self.parse_lit();
1425 let hi = self.span.hi;
1426 let expr = self.mk_expr(lo, hi, ExprLit(literal));
1429 let minus_hi = self.span.hi;
1430 let unary = self.mk_unary(UnNeg, expr);
1431 self.mk_expr(minus_lo, minus_hi, unary)
1437 /// Parses a path and optional type parameter bounds, depending on the
1438 /// mode. The `mode` parameter determines whether lifetimes, types, and/or
1439 /// bounds are permitted and whether `::` must precede type parameter
1441 pub fn parse_path(&mut self, mode: PathParsingMode) -> PathAndBounds {
1442 // Check for a whole path...
1443 let found = match self.token {
1444 INTERPOLATED(token::NtPath(_)) => Some(self.bump_and_get()),
1448 Some(INTERPOLATED(token::NtPath(~path))) => {
1449 return PathAndBounds {
1457 let lo = self.span.lo;
1458 let is_global = self.eat(&token::MOD_SEP);
1460 // Parse any number of segments and bound sets. A segment is an
1461 // identifier followed by an optional lifetime and a set of types.
1462 // A bound set is a set of type parameter bounds.
1463 let mut segments = Vec::new();
1465 // First, parse an identifier.
1466 let identifier = self.parse_ident();
1468 // Parse the '::' before type parameters if it's required. If
1469 // it is required and wasn't present, then we're done.
1470 if mode == LifetimeAndTypesWithColons &&
1471 !self.eat(&token::MOD_SEP) {
1472 segments.push(ast::PathSegment {
1473 identifier: identifier,
1474 lifetimes: Vec::new(),
1475 types: OwnedSlice::empty(),
1480 // Parse the `<` before the lifetime and types, if applicable.
1481 let (any_lifetime_or_types, lifetimes, types) = {
1482 if mode != NoTypesAllowed && self.eat(&token::LT) {
1483 let (lifetimes, types) =
1484 self.parse_generic_values_after_lt();
1485 (true, lifetimes, OwnedSlice::from_vec(types))
1487 (false, Vec::new(), OwnedSlice::empty())
1491 // Assemble and push the result.
1492 segments.push(ast::PathSegment {
1493 identifier: identifier,
1494 lifetimes: lifetimes,
1498 // We're done if we don't see a '::', unless the mode required
1499 // a double colon to get here in the first place.
1500 if !(mode == LifetimeAndTypesWithColons &&
1501 !any_lifetime_or_types) {
1502 if !self.eat(&token::MOD_SEP) {
1508 // Next, parse a colon and bounded type parameters, if applicable.
1509 let bounds = if mode == LifetimeAndTypesAndBounds {
1510 let (_, bounds) = self.parse_optional_ty_param_bounds(false);
1516 // Assemble the span.
1517 let span = mk_sp(lo, self.last_span.hi);
1519 // Assemble the result.
1530 /// parses 0 or 1 lifetime
1531 pub fn parse_opt_lifetime(&mut self) -> Option<ast::Lifetime> {
1533 token::LIFETIME(..) => {
1534 Some(self.parse_lifetime())
1542 /// Parses a single lifetime
1543 // matches lifetime = LIFETIME
1544 pub fn parse_lifetime(&mut self) -> ast::Lifetime {
1546 token::LIFETIME(i) => {
1547 let span = self.span;
1549 return ast::Lifetime {
1550 id: ast::DUMMY_NODE_ID,
1556 self.fatal(format!("expected a lifetime name"));
1561 // matches lifetimes = ( lifetime ) | ( lifetime , lifetimes )
1562 // actually, it matches the empty one too, but putting that in there
1563 // messes up the grammar....
1564 pub fn parse_lifetimes(&mut self) -> Vec<ast::Lifetime> {
1567 * Parses zero or more comma separated lifetimes.
1568 * Expects each lifetime to be followed by either
1569 * a comma or `>`. Used when parsing type parameter
1570 * lists, where we expect something like `<'a, 'b, T>`.
1573 let mut res = Vec::new();
1576 token::LIFETIME(_) => {
1577 res.push(self.parse_lifetime());
1585 token::COMMA => { self.bump();}
1586 token::GT => { return res; }
1587 token::BINOP(token::SHR) => { return res; }
1589 let msg = format!("expected `,` or `>` after lifetime \
1598 pub fn token_is_mutability(tok: &token::Token) -> bool {
1599 token::is_keyword(keywords::Mut, tok) ||
1600 token::is_keyword(keywords::Const, tok)
1603 // parse mutability declaration (mut/const/imm)
1604 pub fn parse_mutability(&mut self) -> Mutability {
1605 if self.eat_keyword(keywords::Mut) {
1607 } else if self.eat_keyword(keywords::Const) {
1608 self.obsolete(self.last_span, ObsoleteConstPointer);
1615 // parse ident COLON expr
1616 pub fn parse_field(&mut self) -> Field {
1617 let lo = self.span.lo;
1618 let i = self.parse_ident();
1619 let hi = self.last_span.hi;
1620 self.expect(&token::COLON);
1621 let e = self.parse_expr();
1623 ident: spanned(lo, hi, i),
1625 span: mk_sp(lo, e.span.hi),
1629 pub fn mk_expr(&mut self, lo: BytePos, hi: BytePos, node: Expr_) -> @Expr {
1631 id: ast::DUMMY_NODE_ID,
1633 span: mk_sp(lo, hi),
1637 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: @Expr) -> ast::Expr_ {
1638 ExprUnary(unop, expr)
1641 pub fn mk_binary(&mut self, binop: ast::BinOp, lhs: @Expr, rhs: @Expr) -> ast::Expr_ {
1642 ExprBinary(binop, lhs, rhs)
1645 pub fn mk_call(&mut self, f: @Expr, args: Vec<@Expr> ) -> ast::Expr_ {
1649 fn mk_method_call(&mut self,
1650 ident: ast::SpannedIdent,
1654 ExprMethodCall(ident, tps, args)
1657 pub fn mk_index(&mut self, expr: @Expr, idx: @Expr) -> ast::Expr_ {
1658 ExprIndex(expr, idx)
1661 pub fn mk_field(&mut self, expr: @Expr, ident: Ident, tys: Vec<P<Ty>> ) -> ast::Expr_ {
1662 ExprField(expr, ident, tys)
1665 pub fn mk_assign_op(&mut self, binop: ast::BinOp, lhs: @Expr, rhs: @Expr) -> ast::Expr_ {
1666 ExprAssignOp(binop, lhs, rhs)
1669 pub fn mk_mac_expr(&mut self, lo: BytePos, hi: BytePos, m: Mac_) -> @Expr {
1671 id: ast::DUMMY_NODE_ID,
1672 node: ExprMac(codemap::Spanned {node: m, span: mk_sp(lo, hi)}),
1673 span: mk_sp(lo, hi),
1677 pub fn mk_lit_u32(&mut self, i: u32) -> @Expr {
1678 let span = &self.span;
1679 let lv_lit = @codemap::Spanned {
1680 node: LitUint(i as u64, TyU32),
1685 id: ast::DUMMY_NODE_ID,
1686 node: ExprLit(lv_lit),
1691 // at the bottom (top?) of the precedence hierarchy,
1692 // parse things like parenthesized exprs,
1693 // macros, return, etc.
1694 pub fn parse_bottom_expr(&mut self) -> @Expr {
1695 maybe_whole_expr!(self);
1697 let lo = self.span.lo;
1698 let mut hi = self.span.hi;
1702 if self.token == token::LPAREN {
1704 // (e) is parenthesized e
1705 // (e,) is a tuple with only one field, e
1706 let mut trailing_comma = false;
1707 if self.token == token::RPAREN {
1710 let lit = @spanned(lo, hi, LitNil);
1711 return self.mk_expr(lo, hi, ExprLit(lit));
1713 let mut es = vec!(self.parse_expr());
1714 self.commit_expr(*es.last().unwrap(), &[], &[token::COMMA, token::RPAREN]);
1715 while self.token == token::COMMA {
1717 if self.token != token::RPAREN {
1718 es.push(self.parse_expr());
1719 self.commit_expr(*es.last().unwrap(), &[], &[token::COMMA, token::RPAREN]);
1722 trailing_comma = true;
1726 self.commit_expr_expecting(*es.last().unwrap(), token::RPAREN);
1728 return if es.len() == 1 && !trailing_comma {
1729 self.mk_expr(lo, hi, ExprParen(*es.get(0)))
1732 self.mk_expr(lo, hi, ExprTup(es))
1734 } else if self.token == token::LBRACE {
1736 let blk = self.parse_block_tail(lo, DefaultBlock);
1737 return self.mk_expr(blk.span.lo, blk.span.hi,
1739 } else if token::is_bar(&self.token) {
1740 return self.parse_lambda_expr();
1741 } else if self.eat_keyword(keywords::Proc) {
1742 let decl = self.parse_proc_decl();
1743 let body = self.parse_expr();
1744 let fakeblock = P(ast::Block {
1745 view_items: Vec::new(),
1748 id: ast::DUMMY_NODE_ID,
1749 rules: DefaultBlock,
1753 return self.mk_expr(lo, body.span.hi, ExprProc(decl, fakeblock));
1754 } else if self.eat_keyword(keywords::Self) {
1755 let path = ast_util::ident_to_path(mk_sp(lo, hi), special_idents::self_);
1756 ex = ExprPath(path);
1757 hi = self.last_span.hi;
1758 } else if self.eat_keyword(keywords::If) {
1759 return self.parse_if_expr();
1760 } else if self.eat_keyword(keywords::For) {
1761 return self.parse_for_expr(None);
1762 } else if self.eat_keyword(keywords::While) {
1763 return self.parse_while_expr();
1764 } else if Parser::token_is_lifetime(&self.token) {
1765 let lifetime = self.get_lifetime();
1767 self.expect(&token::COLON);
1768 if self.eat_keyword(keywords::For) {
1769 return self.parse_for_expr(Some(lifetime))
1770 } else if self.eat_keyword(keywords::Loop) {
1771 return self.parse_loop_expr(Some(lifetime))
1773 self.fatal("expected `for` or `loop` after a label")
1775 } else if self.eat_keyword(keywords::Loop) {
1776 return self.parse_loop_expr(None);
1777 } else if self.eat_keyword(keywords::Continue) {
1778 let lo = self.span.lo;
1779 let ex = if Parser::token_is_lifetime(&self.token) {
1780 let lifetime = self.get_lifetime();
1782 ExprAgain(Some(lifetime))
1786 let hi = self.span.hi;
1787 return self.mk_expr(lo, hi, ex);
1788 } else if self.eat_keyword(keywords::Match) {
1789 return self.parse_match_expr();
1790 } else if self.eat_keyword(keywords::Unsafe) {
1791 return self.parse_block_expr(lo, UnsafeBlock(ast::UserProvided));
1792 } else if self.token == token::LBRACKET {
1795 if self.token == token::RBRACKET {
1798 ex = ExprVec(Vec::new());
1801 let first_expr = self.parse_expr();
1802 if self.token == token::COMMA &&
1803 self.look_ahead(1, |t| *t == token::DOTDOT) {
1804 // Repeating vector syntax: [ 0, ..512 ]
1807 let count = self.parse_expr();
1808 self.expect(&token::RBRACKET);
1809 ex = ExprRepeat(first_expr, count);
1810 } else if self.token == token::COMMA {
1811 // Vector with two or more elements.
1813 let remaining_exprs = self.parse_seq_to_end(
1815 seq_sep_trailing_allowed(token::COMMA),
1818 let mut exprs = vec!(first_expr);
1819 exprs.push_all_move(remaining_exprs);
1820 ex = ExprVec(exprs);
1822 // Vector with one element.
1823 self.expect(&token::RBRACKET);
1824 ex = ExprVec(vec!(first_expr));
1827 hi = self.last_span.hi;
1828 } else if self.eat_keyword(keywords::Return) {
1829 // RETURN expression
1830 if can_begin_expr(&self.token) {
1831 let e = self.parse_expr();
1833 ex = ExprRet(Some(e));
1834 } else { ex = ExprRet(None); }
1835 } else if self.eat_keyword(keywords::Break) {
1837 if Parser::token_is_lifetime(&self.token) {
1838 let lifetime = self.get_lifetime();
1840 ex = ExprBreak(Some(lifetime));
1842 ex = ExprBreak(None);
1845 } else if self.token == token::MOD_SEP ||
1846 is_ident(&self.token) && !self.is_keyword(keywords::True) &&
1847 !self.is_keyword(keywords::False) {
1848 let pth = self.parse_path(LifetimeAndTypesWithColons).path;
1850 // `!`, as an operator, is prefix, so we know this isn't that
1851 if self.token == token::NOT {
1852 // MACRO INVOCATION expression
1855 let ket = token::close_delimiter_for(&self.token)
1856 .unwrap_or_else(|| self.fatal("expected open delimiter"));
1859 let tts = self.parse_seq_to_end(&ket,
1861 |p| p.parse_token_tree());
1862 let hi = self.span.hi;
1864 return self.mk_mac_expr(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT));
1865 } else if self.token == token::LBRACE {
1866 // This might be a struct literal.
1867 if self.looking_at_struct_literal() {
1868 // It's a struct literal.
1870 let mut fields = Vec::new();
1871 let mut base = None;
1873 while self.token != token::RBRACE {
1874 if self.eat(&token::DOTDOT) {
1875 base = Some(self.parse_expr());
1879 fields.push(self.parse_field());
1880 self.commit_expr(fields.last().unwrap().expr,
1881 &[token::COMMA], &[token::RBRACE]);
1885 self.expect(&token::RBRACE);
1886 ex = ExprStruct(pth, fields, base);
1887 return self.mk_expr(lo, hi, ex);
1894 // other literal expression
1895 let lit = self.parse_lit();
1900 return self.mk_expr(lo, hi, ex);
1903 // parse a block or unsafe block
1904 pub fn parse_block_expr(&mut self, lo: BytePos, blk_mode: BlockCheckMode)
1906 self.expect(&token::LBRACE);
1907 let blk = self.parse_block_tail(lo, blk_mode);
1908 return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk));
1911 // parse a.b or a(13) or a[4] or just a
1912 pub fn parse_dot_or_call_expr(&mut self) -> @Expr {
1913 let b = self.parse_bottom_expr();
1914 self.parse_dot_or_call_expr_with(b)
1917 pub fn parse_dot_or_call_expr_with(&mut self, e0: @Expr) -> @Expr {
1923 if self.eat(&token::DOT) {
1925 token::IDENT(i, _) => {
1926 let dot = self.last_span.hi;
1929 let (_, tys) = if self.eat(&token::MOD_SEP) {
1930 self.expect(&token::LT);
1931 self.parse_generic_values_after_lt()
1933 (Vec::new(), Vec::new())
1936 // expr.f() method call
1939 let mut es = self.parse_unspanned_seq(
1942 seq_sep_trailing_disallowed(token::COMMA),
1945 hi = self.last_span.hi;
1948 let id = spanned(dot, hi, i);
1949 let nd = self.mk_method_call(id, tys, es);
1950 e = self.mk_expr(lo, hi, nd);
1953 let field = self.mk_field(e, i, tys);
1954 e = self.mk_expr(lo, hi, field)
1958 _ => self.unexpected()
1962 if self.expr_is_complete(e) { break; }
1966 let es = self.parse_unspanned_seq(
1969 seq_sep_trailing_allowed(token::COMMA),
1972 hi = self.last_span.hi;
1974 let nd = self.mk_call(e, es);
1975 e = self.mk_expr(lo, hi, nd);
1979 token::LBRACKET => {
1981 let ix = self.parse_expr();
1983 self.commit_expr_expecting(ix, token::RBRACKET);
1984 let index = self.mk_index(e, ix);
1985 e = self.mk_expr(lo, hi, index)
1994 // parse an optional separator followed by a kleene-style
1995 // repetition token (+ or *).
1996 pub fn parse_sep_and_zerok(&mut self) -> (Option<token::Token>, bool) {
1997 fn parse_zerok(parser: &mut Parser) -> Option<bool> {
1998 match parser.token {
1999 token::BINOP(token::STAR) | token::BINOP(token::PLUS) => {
2000 let zerok = parser.token == token::BINOP(token::STAR);
2008 match parse_zerok(self) {
2009 Some(zerok) => return (None, zerok),
2013 let separator = self.bump_and_get();
2014 match parse_zerok(self) {
2015 Some(zerok) => (Some(separator), zerok),
2016 None => self.fatal("expected `*` or `+`")
2020 // parse a single token tree from the input.
2021 pub fn parse_token_tree(&mut self) -> TokenTree {
2022 // FIXME #6994: currently, this is too eager. It
2023 // parses token trees but also identifies TTSeq's
2024 // and TTNonterminal's; it's too early to know yet
2025 // whether something will be a nonterminal or a seq
2027 maybe_whole!(deref self, NtTT);
2029 // this is the fall-through for the 'match' below.
2030 // invariants: the current token is not a left-delimiter,
2031 // not an EOF, and not the desired right-delimiter (if
2032 // it were, parse_seq_to_before_end would have prevented
2033 // reaching this point.
2034 fn parse_non_delim_tt_tok(p: &mut Parser) -> TokenTree {
2035 maybe_whole!(deref p, NtTT);
2037 token::RPAREN | token::RBRACE | token::RBRACKET => {
2038 // This is a conservative error: only report the last unclosed delimiter. The
2039 // previous unclosed delimiters could actually be closed! The parser just hasn't
2040 // gotten to them yet.
2041 match p.open_braces.last() {
2043 Some(&sp) => p.span_note(sp, "unclosed delimiter"),
2045 let token_str = p.this_token_to_str();
2046 p.fatal(format!("incorrect close delimiter: `{}`",
2049 /* we ought to allow different depths of unquotation */
2050 token::DOLLAR if p.quote_depth > 0u => {
2054 if p.token == token::LPAREN {
2055 let seq = p.parse_seq(
2059 |p| p.parse_token_tree()
2061 let (s, z) = p.parse_sep_and_zerok();
2062 let seq = match seq {
2063 Spanned { node, .. } => node,
2065 TTSeq(mk_sp(sp.lo, p.span.hi), Rc::new(seq), s, z)
2067 TTNonterminal(sp, p.parse_ident())
2076 // turn the next token into a TTTok:
2077 fn parse_any_tt_tok(p: &mut Parser) -> TokenTree {
2078 TTTok(p.span, p.bump_and_get())
2081 match (&self.token, token::close_delimiter_for(&self.token)) {
2082 (&token::EOF, _) => {
2083 let open_braces = self.open_braces.clone();
2084 for sp in open_braces.iter() {
2085 self.span_note(*sp, "Did you mean to close this delimiter?");
2087 // There shouldn't really be a span, but it's easier for the test runner
2088 // if we give it one
2089 self.fatal("this file contains an un-closed delimiter ");
2091 (_, Some(close_delim)) => {
2092 // Parse the open delimiter.
2093 self.open_braces.push(self.span);
2094 let mut result = vec!(parse_any_tt_tok(self));
2097 self.parse_seq_to_before_end(&close_delim,
2099 |p| p.parse_token_tree());
2100 result.push_all_move(trees);
2102 // Parse the close delimiter.
2103 result.push(parse_any_tt_tok(self));
2104 self.open_braces.pop().unwrap();
2106 TTDelim(Rc::new(result))
2108 _ => parse_non_delim_tt_tok(self)
2112 // parse a stream of tokens into a list of TokenTree's,
2114 pub fn parse_all_token_trees(&mut self) -> Vec<TokenTree> {
2115 let mut tts = Vec::new();
2116 while self.token != token::EOF {
2117 tts.push(self.parse_token_tree());
2122 pub fn parse_matchers(&mut self) -> Vec<Matcher> {
2123 // unification of Matcher's and TokenTree's would vastly improve
2124 // the interpolation of Matcher's
2125 maybe_whole!(self, NtMatchers);
2126 let mut name_idx = 0u;
2127 match token::close_delimiter_for(&self.token) {
2128 Some(other_delimiter) => {
2130 self.parse_matcher_subseq_upto(&mut name_idx, &other_delimiter)
2132 None => self.fatal("expected open delimiter")
2136 // This goofy function is necessary to correctly match parens in Matcher's.
2137 // Otherwise, `$( ( )` would be a valid Matcher, and `$( () )` would be
2138 // invalid. It's similar to common::parse_seq.
2139 pub fn parse_matcher_subseq_upto(&mut self,
2140 name_idx: &mut uint,
2143 let mut ret_val = Vec::new();
2144 let mut lparens = 0u;
2146 while self.token != *ket || lparens > 0u {
2147 if self.token == token::LPAREN { lparens += 1u; }
2148 if self.token == token::RPAREN { lparens -= 1u; }
2149 ret_val.push(self.parse_matcher(name_idx));
2157 pub fn parse_matcher(&mut self, name_idx: &mut uint) -> Matcher {
2158 let lo = self.span.lo;
2160 let m = if self.token == token::DOLLAR {
2162 if self.token == token::LPAREN {
2163 let name_idx_lo = *name_idx;
2165 let ms = self.parse_matcher_subseq_upto(name_idx,
2168 self.fatal("repetition body must be nonempty");
2170 let (sep, zerok) = self.parse_sep_and_zerok();
2171 MatchSeq(ms, sep, zerok, name_idx_lo, *name_idx)
2173 let bound_to = self.parse_ident();
2174 self.expect(&token::COLON);
2175 let nt_name = self.parse_ident();
2176 let m = MatchNonterminal(bound_to, nt_name, *name_idx);
2181 MatchTok(self.bump_and_get())
2184 return spanned(lo, self.span.hi, m);
2187 // parse a prefix-operator expr
2188 pub fn parse_prefix_expr(&mut self) -> @Expr {
2189 let lo = self.span.lo;
2196 let e = self.parse_prefix_expr();
2198 ex = self.mk_unary(UnNot, e);
2200 token::BINOP(token::MINUS) => {
2202 let e = self.parse_prefix_expr();
2204 ex = self.mk_unary(UnNeg, e);
2206 token::BINOP(token::STAR) => {
2208 let e = self.parse_prefix_expr();
2210 ex = self.mk_unary(UnDeref, e);
2212 token::BINOP(token::AND) | token::ANDAND => {
2214 let _lt = self.parse_opt_lifetime();
2215 let m = self.parse_mutability();
2216 let e = self.parse_prefix_expr();
2218 // HACK: turn &[...] into a &-vec
2220 ExprVec(..) if m == MutImmutable => {
2221 ExprVstore(e, ExprVstoreSlice)
2223 ExprLit(lit) if lit_is_str(lit) && m == MutImmutable => {
2224 ExprVstore(e, ExprVstoreSlice)
2226 ExprVec(..) if m == MutMutable => {
2227 ExprVstore(e, ExprVstoreMutSlice)
2229 _ => ExprAddrOf(m, e)
2234 let e = self.parse_prefix_expr();
2236 // HACK: pretending @[] is a (removed) @-vec
2240 self.obsolete(e.span, ObsoleteManagedVec);
2241 // the above error means that no-one will know we're
2242 // lying... hopefully.
2243 ExprVstore(e, ExprVstoreUniq)
2245 ExprLit(lit) if lit_is_str(lit) => {
2246 self.obsolete(self.last_span, ObsoleteManagedString);
2247 ExprVstore(e, ExprVstoreUniq)
2249 _ => self.mk_unary(UnBox, e)
2255 let e = self.parse_prefix_expr();
2257 // HACK: turn ~[...] into a ~-vec
2259 ExprVec(..) | ExprRepeat(..) => ExprVstore(e, ExprVstoreUniq),
2260 ExprLit(lit) if lit_is_str(lit) => {
2261 ExprVstore(e, ExprVstoreUniq)
2263 _ => self.mk_unary(UnUniq, e)
2266 token::IDENT(_, _) if self.is_keyword(keywords::Box) => {
2269 // Check for a place: `box(PLACE) EXPR`.
2270 if self.eat(&token::LPAREN) {
2271 // Support `box() EXPR` as the default.
2272 if !self.eat(&token::RPAREN) {
2273 let place = self.parse_expr();
2274 self.expect(&token::RPAREN);
2275 let subexpression = self.parse_prefix_expr();
2276 hi = subexpression.span.hi;
2277 ex = ExprBox(place, subexpression);
2278 return self.mk_expr(lo, hi, ex);
2282 // Otherwise, we use the unique pointer default.
2283 let subexpression = self.parse_prefix_expr();
2284 hi = subexpression.span.hi;
2285 // HACK: turn `box [...]` into a boxed-vec
2286 ex = match subexpression.node {
2287 ExprVec(..) | ExprRepeat(..) => {
2288 ExprVstore(subexpression, ExprVstoreUniq)
2290 ExprLit(lit) if lit_is_str(lit) => {
2291 ExprVstore(subexpression, ExprVstoreUniq)
2293 _ => self.mk_unary(UnUniq, subexpression)
2296 _ => return self.parse_dot_or_call_expr()
2298 return self.mk_expr(lo, hi, ex);
2301 // parse an expression of binops
2302 pub fn parse_binops(&mut self) -> @Expr {
2303 let prefix_expr = self.parse_prefix_expr();
2304 self.parse_more_binops(prefix_expr, 0)
2307 // parse an expression of binops of at least min_prec precedence
2308 pub fn parse_more_binops(&mut self, lhs: @Expr, min_prec: uint) -> @Expr {
2309 if self.expr_is_complete(lhs) { return lhs; }
2311 // Prevent dynamic borrow errors later on by limiting the
2312 // scope of the borrows.
2314 let token: &token::Token = &self.token;
2315 let restriction: &restriction = &self.restriction;
2316 match (token, restriction) {
2317 (&token::BINOP(token::OR), &RESTRICT_NO_BAR_OP) => return lhs,
2318 (&token::BINOP(token::OR),
2319 &RESTRICT_NO_BAR_OR_DOUBLEBAR_OP) => return lhs,
2320 (&token::OROR, &RESTRICT_NO_BAR_OR_DOUBLEBAR_OP) => return lhs,
2325 let cur_opt = token_to_binop(&self.token);
2328 let cur_prec = operator_prec(cur_op);
2329 if cur_prec > min_prec {
2331 let expr = self.parse_prefix_expr();
2332 let rhs = self.parse_more_binops(expr, cur_prec);
2333 let binary = self.mk_binary(cur_op, lhs, rhs);
2334 let bin = self.mk_expr(lhs.span.lo, rhs.span.hi, binary);
2335 self.parse_more_binops(bin, min_prec)
2341 if as_prec > min_prec && self.eat_keyword(keywords::As) {
2342 let rhs = self.parse_ty(true);
2343 let _as = self.mk_expr(lhs.span.lo,
2345 ExprCast(lhs, rhs));
2346 self.parse_more_binops(_as, min_prec)
2354 // parse an assignment expression....
2355 // actually, this seems to be the main entry point for
2356 // parsing an arbitrary expression.
2357 pub fn parse_assign_expr(&mut self) -> @Expr {
2358 let lo = self.span.lo;
2359 let lhs = self.parse_binops();
2363 let rhs = self.parse_expr();
2364 self.mk_expr(lo, rhs.span.hi, ExprAssign(lhs, rhs))
2366 token::BINOPEQ(op) => {
2368 let rhs = self.parse_expr();
2369 let aop = match op {
2370 token::PLUS => BiAdd,
2371 token::MINUS => BiSub,
2372 token::STAR => BiMul,
2373 token::SLASH => BiDiv,
2374 token::PERCENT => BiRem,
2375 token::CARET => BiBitXor,
2376 token::AND => BiBitAnd,
2377 token::OR => BiBitOr,
2378 token::SHL => BiShl,
2381 let assign_op = self.mk_assign_op(aop, lhs, rhs);
2382 self.mk_expr(lo, rhs.span.hi, assign_op)
2385 self.obsolete(self.span, ObsoleteSwap);
2387 // Ignore what we get, this is an error anyway
2389 self.mk_expr(lo, self.span.hi, ExprBreak(None))
2397 // parse an 'if' expression ('if' token already eaten)
2398 pub fn parse_if_expr(&mut self) -> @Expr {
2399 let lo = self.last_span.lo;
2400 let cond = self.parse_expr();
2401 let thn = self.parse_block();
2402 let mut els: Option<@Expr> = None;
2403 let mut hi = thn.span.hi;
2404 if self.eat_keyword(keywords::Else) {
2405 let elexpr = self.parse_else_expr();
2407 hi = elexpr.span.hi;
2409 self.mk_expr(lo, hi, ExprIf(cond, thn, els))
2412 // `|args| { ... }` or `{ ...}` like in `do` expressions
2413 pub fn parse_lambda_block_expr(&mut self) -> @Expr {
2414 self.parse_lambda_expr_(
2417 token::BINOP(token::OR) | token::OROR => {
2418 p.parse_fn_block_decl()
2421 // No argument list - `do foo {`
2425 id: ast::DUMMY_NODE_ID,
2436 let blk = p.parse_block();
2437 p.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk))
2442 pub fn parse_lambda_expr(&mut self) -> @Expr {
2443 self.parse_lambda_expr_(|p| p.parse_fn_block_decl(),
2447 // parse something of the form |args| expr
2448 // this is used both in parsing a lambda expr
2449 // and in parsing a block expr as e.g. in for...
2450 pub fn parse_lambda_expr_(&mut self,
2451 parse_decl: |&mut Parser| -> P<FnDecl>,
2452 parse_body: |&mut Parser| -> @Expr)
2454 let lo = self.span.lo;
2455 let decl = parse_decl(self);
2456 let body = parse_body(self);
2457 let fakeblock = P(ast::Block {
2458 view_items: Vec::new(),
2461 id: ast::DUMMY_NODE_ID,
2462 rules: DefaultBlock,
2466 return self.mk_expr(lo, body.span.hi, ExprFnBlock(decl, fakeblock));
2469 pub fn parse_else_expr(&mut self) -> @Expr {
2470 if self.eat_keyword(keywords::If) {
2471 return self.parse_if_expr();
2473 let blk = self.parse_block();
2474 return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk));
2478 // parse a 'for' .. 'in' expression ('for' token already eaten)
2479 pub fn parse_for_expr(&mut self, opt_ident: Option<ast::Ident>) -> @Expr {
2480 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
2482 let lo = self.last_span.lo;
2483 let pat = self.parse_pat();
2484 self.expect_keyword(keywords::In);
2485 let expr = self.parse_expr();
2486 let loop_block = self.parse_block();
2487 let hi = self.span.hi;
2489 self.mk_expr(lo, hi, ExprForLoop(pat, expr, loop_block, opt_ident))
2492 pub fn parse_while_expr(&mut self) -> @Expr {
2493 let lo = self.last_span.lo;
2494 let cond = self.parse_expr();
2495 let body = self.parse_block();
2496 let hi = body.span.hi;
2497 return self.mk_expr(lo, hi, ExprWhile(cond, body));
2500 pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::Ident>) -> @Expr {
2501 // loop headers look like 'loop {' or 'loop unsafe {'
2502 let is_loop_header =
2503 self.token == token::LBRACE
2504 || (is_ident(&self.token)
2505 && self.look_ahead(1, |t| *t == token::LBRACE));
2508 // This is a loop body
2509 let lo = self.last_span.lo;
2510 let body = self.parse_block();
2511 let hi = body.span.hi;
2512 return self.mk_expr(lo, hi, ExprLoop(body, opt_ident));
2514 // This is an obsolete 'continue' expression
2515 if opt_ident.is_some() {
2516 self.span_err(self.last_span,
2517 "a label may not be used with a `loop` expression");
2520 self.obsolete(self.last_span, ObsoleteLoopAsContinue);
2521 let lo = self.span.lo;
2522 let ex = if Parser::token_is_lifetime(&self.token) {
2523 let lifetime = self.get_lifetime();
2525 ExprAgain(Some(lifetime))
2529 let hi = self.span.hi;
2530 return self.mk_expr(lo, hi, ex);
2534 // For distingishing between struct literals and blocks
2535 fn looking_at_struct_literal(&mut self) -> bool {
2536 self.token == token::LBRACE &&
2537 ((self.look_ahead(1, |t| token::is_plain_ident(t)) &&
2538 self.look_ahead(2, |t| *t == token::COLON))
2539 || self.look_ahead(1, |t| *t == token::DOTDOT))
2542 fn parse_match_expr(&mut self) -> @Expr {
2543 let lo = self.last_span.lo;
2544 let discriminant = self.parse_expr();
2545 self.commit_expr_expecting(discriminant, token::LBRACE);
2546 let mut arms: Vec<Arm> = Vec::new();
2547 while self.token != token::RBRACE {
2548 let attrs = self.parse_outer_attributes();
2549 let pats = self.parse_pats();
2550 let mut guard = None;
2551 if self.eat_keyword(keywords::If) {
2552 guard = Some(self.parse_expr());
2554 self.expect(&token::FAT_ARROW);
2555 let expr = self.parse_expr_res(RESTRICT_STMT_EXPR);
2558 !classify::expr_is_simple_block(expr)
2559 && self.token != token::RBRACE;
2562 self.commit_expr(expr, &[token::COMMA], &[token::RBRACE]);
2564 self.eat(&token::COMMA);
2567 arms.push(ast::Arm {
2574 let hi = self.span.hi;
2576 return self.mk_expr(lo, hi, ExprMatch(discriminant, arms));
2579 // parse an expression
2580 pub fn parse_expr(&mut self) -> @Expr {
2581 return self.parse_expr_res(UNRESTRICTED);
2584 // parse an expression, subject to the given restriction
2585 fn parse_expr_res(&mut self, r: restriction) -> @Expr {
2586 let old = self.restriction;
2587 self.restriction = r;
2588 let e = self.parse_assign_expr();
2589 self.restriction = old;
2593 // parse the RHS of a local variable declaration (e.g. '= 14;')
2594 fn parse_initializer(&mut self) -> Option<@Expr> {
2595 if self.token == token::EQ {
2597 Some(self.parse_expr())
2603 // parse patterns, separated by '|' s
2604 fn parse_pats(&mut self) -> Vec<@Pat> {
2605 let mut pats = Vec::new();
2607 pats.push(self.parse_pat());
2608 if self.token == token::BINOP(token::OR) { self.bump(); }
2609 else { return pats; }
2613 fn parse_pat_vec_elements(
2615 ) -> (Vec<@Pat> , Option<@Pat>, Vec<@Pat> ) {
2616 let mut before = Vec::new();
2617 let mut slice = None;
2618 let mut after = Vec::new();
2619 let mut first = true;
2620 let mut before_slice = true;
2622 while self.token != token::RBRACKET {
2623 if first { first = false; }
2624 else { self.expect(&token::COMMA); }
2626 let mut is_slice = false;
2628 if self.token == token::DOTDOT {
2631 before_slice = false;
2636 if self.token == token::COMMA || self.token == token::RBRACKET {
2637 slice = Some(@ast::Pat {
2638 id: ast::DUMMY_NODE_ID,
2643 let subpat = self.parse_pat();
2645 ast::Pat { id, node: PatWild, span } => {
2646 self.obsolete(self.span, ObsoleteVecDotDotWildcard);
2647 slice = Some(@ast::Pat {
2653 ast::Pat { node: PatIdent(_, _, _), .. } => {
2654 slice = Some(subpat);
2656 ast::Pat { span, .. } => self.span_fatal(
2657 span, "expected an identifier or nothing"
2662 let subpat = self.parse_pat();
2664 before.push(subpat);
2671 (before, slice, after)
2674 // parse the fields of a struct-like pattern
2675 fn parse_pat_fields(&mut self) -> (Vec<ast::FieldPat> , bool) {
2676 let mut fields = Vec::new();
2677 let mut etc = false;
2678 let mut first = true;
2679 while self.token != token::RBRACE {
2683 self.expect(&token::COMMA);
2684 // accept trailing commas
2685 if self.token == token::RBRACE { break }
2688 etc = self.token == token::UNDERSCORE || self.token == token::DOTDOT;
2689 if self.token == token::UNDERSCORE {
2690 self.obsolete(self.span, ObsoleteStructWildcard);
2694 if self.token != token::RBRACE {
2695 let token_str = self.this_token_to_str();
2696 self.fatal(format!("expected `\\}`, found `{}`",
2703 let bind_type = if self.eat_keyword(keywords::Mut) {
2704 BindByValue(MutMutable)
2705 } else if self.eat_keyword(keywords::Ref) {
2706 BindByRef(self.parse_mutability())
2708 BindByValue(MutImmutable)
2711 let fieldname = self.parse_ident();
2713 let subpat = if self.token == token::COLON {
2715 BindByRef(..) | BindByValue(MutMutable) => {
2716 let token_str = self.this_token_to_str();
2717 self.fatal(format!("unexpected `{}`", token_str))
2725 let fieldpath = ast_util::ident_to_path(self.last_span,
2728 id: ast::DUMMY_NODE_ID,
2729 node: PatIdent(bind_type, fieldpath, None),
2730 span: self.last_span
2733 fields.push(ast::FieldPat { ident: fieldname, pat: subpat });
2735 return (fields, etc);
2739 pub fn parse_pat(&mut self) -> @Pat {
2740 maybe_whole!(self, NtPat);
2742 let lo = self.span.lo;
2747 token::UNDERSCORE => {
2750 hi = self.last_span.hi;
2752 id: ast::DUMMY_NODE_ID,
2760 let sub = self.parse_pat();
2761 self.obsolete(self.span, ObsoleteManagedPattern);
2762 let hi = self.last_span.hi;
2764 id: ast::DUMMY_NODE_ID,
2772 let sub = self.parse_pat();
2774 hi = self.last_span.hi;
2776 id: ast::DUMMY_NODE_ID,
2781 token::BINOP(token::AND) | token::ANDAND => {
2783 let lo = self.span.lo;
2785 let sub = self.parse_pat();
2787 // HACK: parse &"..." as a literal of a borrowed str
2788 pat = match sub.node {
2791 ExprLit(lit) if lit_is_str(lit) => {
2793 id: ast::DUMMY_NODE_ID,
2794 node: ExprVstore(e, ExprVstoreSlice),
2799 _ => PatRegion(sub),
2802 _ => PatRegion(sub),
2804 hi = self.last_span.hi;
2806 id: ast::DUMMY_NODE_ID,
2812 // parse (pat,pat,pat,...) as tuple
2814 if self.token == token::RPAREN {
2817 let lit = @codemap::Spanned {
2819 span: mk_sp(lo, hi)};
2820 let expr = self.mk_expr(lo, hi, ExprLit(lit));
2823 let mut fields = vec!(self.parse_pat());
2824 if self.look_ahead(1, |t| *t != token::RPAREN) {
2825 while self.token == token::COMMA {
2827 if self.token == token::RPAREN { break; }
2828 fields.push(self.parse_pat());
2831 if fields.len() == 1 { self.expect(&token::COMMA); }
2832 self.expect(&token::RPAREN);
2833 pat = PatTup(fields);
2835 hi = self.last_span.hi;
2837 id: ast::DUMMY_NODE_ID,
2842 token::LBRACKET => {
2843 // parse [pat,pat,...] as vector pattern
2845 let (before, slice, after) =
2846 self.parse_pat_vec_elements();
2848 self.expect(&token::RBRACKET);
2849 pat = ast::PatVec(before, slice, after);
2850 hi = self.last_span.hi;
2852 id: ast::DUMMY_NODE_ID,
2860 if !is_ident_or_path(&self.token)
2861 || self.is_keyword(keywords::True)
2862 || self.is_keyword(keywords::False) {
2863 // Parse an expression pattern or exp .. exp.
2865 // These expressions are limited to literals (possibly
2866 // preceded by unary-minus) or identifiers.
2867 let val = self.parse_literal_maybe_minus();
2868 if self.eat(&token::DOTDOT) {
2869 let end = if is_ident_or_path(&self.token) {
2870 let path = self.parse_path(LifetimeAndTypesWithColons)
2872 let hi = self.span.hi;
2873 self.mk_expr(lo, hi, ExprPath(path))
2875 self.parse_literal_maybe_minus()
2877 pat = PatRange(val, end);
2881 } else if self.eat_keyword(keywords::Mut) {
2882 pat = self.parse_pat_ident(BindByValue(MutMutable));
2883 } else if self.eat_keyword(keywords::Ref) {
2885 let mutbl = self.parse_mutability();
2886 pat = self.parse_pat_ident(BindByRef(mutbl));
2888 let can_be_enum_or_struct = self.look_ahead(1, |t| {
2890 token::LPAREN | token::LBRACKET | token::LT |
2891 token::LBRACE | token::MOD_SEP => true,
2896 if self.look_ahead(1, |t| *t == token::DOTDOT) {
2897 let start = self.parse_expr_res(RESTRICT_NO_BAR_OP);
2898 self.eat(&token::DOTDOT);
2899 let end = self.parse_expr_res(RESTRICT_NO_BAR_OP);
2900 pat = PatRange(start, end);
2901 } else if is_plain_ident(&self.token) && !can_be_enum_or_struct {
2902 let name = self.parse_path(NoTypesAllowed).path;
2904 if self.eat(&token::AT) {
2906 sub = Some(self.parse_pat());
2911 pat = PatIdent(BindByValue(MutImmutable), name, sub);
2913 // parse an enum pat
2914 let enum_path = self.parse_path(LifetimeAndTypesWithColons)
2920 self.parse_pat_fields();
2922 pat = PatStruct(enum_path, fields, etc);
2925 let mut args: Vec<@Pat> = Vec::new();
2928 let is_star = self.look_ahead(1, |t| {
2930 token::BINOP(token::STAR) => true,
2934 let is_dotdot = self.look_ahead(1, |t| {
2936 token::DOTDOT => true,
2940 if is_star | is_dotdot {
2941 // This is a "top constructor only" pat
2944 self.obsolete(self.span, ObsoleteEnumWildcard);
2947 self.expect(&token::RPAREN);
2948 pat = PatEnum(enum_path, None);
2950 args = self.parse_enum_variant_seq(
2953 seq_sep_trailing_disallowed(token::COMMA),
2956 pat = PatEnum(enum_path, Some(args));
2960 if enum_path.segments.len() == 1 {
2961 // it could still be either an enum
2962 // or an identifier pattern, resolve
2963 // will sort it out:
2964 pat = PatIdent(BindByValue(MutImmutable),
2968 pat = PatEnum(enum_path, Some(args));
2976 hi = self.last_span.hi;
2978 id: ast::DUMMY_NODE_ID,
2980 span: mk_sp(lo, hi),
2984 // parse ident or ident @ pat
2985 // used by the copy foo and ref foo patterns to give a good
2986 // error message when parsing mistakes like ref foo(a,b)
2987 fn parse_pat_ident(&mut self,
2988 binding_mode: ast::BindingMode)
2990 if !is_plain_ident(&self.token) {
2991 self.span_fatal(self.last_span,
2992 "expected identifier, found path");
2994 // why a path here, and not just an identifier?
2995 let name = self.parse_path(NoTypesAllowed).path;
2996 let sub = if self.eat(&token::AT) {
2997 Some(self.parse_pat())
3002 // just to be friendly, if they write something like
3004 // we end up here with ( as the current token. This shortly
3005 // leads to a parse error. Note that if there is no explicit
3006 // binding mode then we do not end up here, because the lookahead
3007 // will direct us over to parse_enum_variant()
3008 if self.token == token::LPAREN {
3011 "expected identifier, found enum pattern");
3014 PatIdent(binding_mode, name, sub)
3017 // parse a local variable declaration
3018 fn parse_local(&mut self) -> @Local {
3019 let lo = self.span.lo;
3020 let pat = self.parse_pat();
3023 id: ast::DUMMY_NODE_ID,
3025 span: mk_sp(lo, lo),
3027 if self.eat(&token::COLON) { ty = self.parse_ty(false); }
3028 let init = self.parse_initializer();
3033 id: ast::DUMMY_NODE_ID,
3034 span: mk_sp(lo, self.last_span.hi),
3038 // parse a "let" stmt
3039 fn parse_let(&mut self) -> @Decl {
3040 let lo = self.span.lo;
3041 let local = self.parse_local();
3042 while self.eat(&token::COMMA) {
3043 let _ = self.parse_local();
3044 self.obsolete(self.span, ObsoleteMultipleLocalDecl);
3046 return @spanned(lo, self.last_span.hi, DeclLocal(local));
3049 // parse a structure field
3050 fn parse_name_and_ty(&mut self, pr: Visibility,
3051 attrs: Vec<Attribute> ) -> StructField {
3052 let lo = self.span.lo;
3053 if !is_plain_ident(&self.token) {
3054 self.fatal("expected ident");
3056 let name = self.parse_ident();
3057 self.expect(&token::COLON);
3058 let ty = self.parse_ty(false);
3059 spanned(lo, self.last_span.hi, ast::StructField_ {
3060 kind: NamedField(name, pr),
3061 id: ast::DUMMY_NODE_ID,
3067 // parse a statement. may include decl.
3068 // precondition: any attributes are parsed already
3069 pub fn parse_stmt(&mut self, item_attrs: Vec<Attribute> ) -> @Stmt {
3070 maybe_whole!(self, NtStmt);
3072 fn check_expected_item(p: &mut Parser, found_attrs: bool) {
3073 // If we have attributes then we should have an item
3075 p.span_err(p.last_span, "expected item after attributes");
3079 let lo = self.span.lo;
3080 if self.is_keyword(keywords::Let) {
3081 check_expected_item(self, !item_attrs.is_empty());
3082 self.expect_keyword(keywords::Let);
3083 let decl = self.parse_let();
3084 return @spanned(lo, decl.span.hi, StmtDecl(decl, ast::DUMMY_NODE_ID));
3085 } else if is_ident(&self.token)
3086 && !token::is_any_keyword(&self.token)
3087 && self.look_ahead(1, |t| *t == token::NOT) {
3088 // parse a macro invocation. Looks like there's serious
3089 // overlap here; if this clause doesn't catch it (and it
3090 // won't, for brace-delimited macros) it will fall through
3091 // to the macro clause of parse_item_or_view_item. This
3092 // could use some cleanup, it appears to me.
3094 // whoops! I now have a guess: I'm guessing the "parens-only"
3095 // rule here is deliberate, to allow macro users to use parens
3096 // for things that should be parsed as stmt_mac, and braces
3097 // for things that should expand into items. Tricky, and
3098 // somewhat awkward... and probably undocumented. Of course,
3099 // I could just be wrong.
3101 check_expected_item(self, !item_attrs.is_empty());
3103 // Potential trouble: if we allow macros with paths instead of
3104 // idents, we'd need to look ahead past the whole path here...
3105 let pth = self.parse_path(NoTypesAllowed).path;
3108 let id = if token::close_delimiter_for(&self.token).is_some() {
3109 token::special_idents::invalid // no special identifier
3114 // check that we're pointing at delimiters (need to check
3115 // again after the `if`, because of `parse_ident`
3116 // consuming more tokens).
3117 let (bra, ket) = match token::close_delimiter_for(&self.token) {
3118 Some(ket) => (self.token.clone(), ket),
3120 // we only expect an ident if we didn't parse one
3122 let ident_str = if id == token::special_idents::invalid {
3127 let tok_str = self.this_token_to_str();
3128 self.fatal(format!("expected {}`(` or `\\{`, but found `{}`",
3129 ident_str, tok_str))
3133 let tts = self.parse_unspanned_seq(
3137 |p| p.parse_token_tree()
3139 let hi = self.span.hi;
3141 if id == token::special_idents::invalid {
3142 return @spanned(lo, hi, StmtMac(
3143 spanned(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT)), false));
3145 // if it has a special ident, it's definitely an item
3146 return @spanned(lo, hi, StmtDecl(
3147 @spanned(lo, hi, DeclItem(
3149 lo, hi, id /*id is good here*/,
3150 ItemMac(spanned(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT))),
3151 Inherited, Vec::new(/*no attrs*/)))),
3152 ast::DUMMY_NODE_ID));
3156 let found_attrs = !item_attrs.is_empty();
3157 match self.parse_item_or_view_item(item_attrs, false) {
3160 let decl = @spanned(lo, hi, DeclItem(i));
3161 return @spanned(lo, hi, StmtDecl(decl, ast::DUMMY_NODE_ID));
3163 IoviViewItem(vi) => {
3164 self.span_fatal(vi.span,
3165 "view items must be declared at the top of the block");
3167 IoviForeignItem(_) => {
3168 self.fatal("foreign items are not allowed here");
3170 IoviNone(_) => { /* fallthrough */ }
3173 check_expected_item(self, found_attrs);
3175 // Remainder are line-expr stmts.
3176 let e = self.parse_expr_res(RESTRICT_STMT_EXPR);
3177 return @spanned(lo, e.span.hi, StmtExpr(e, ast::DUMMY_NODE_ID));
3181 // is this expression a successfully-parsed statement?
3182 fn expr_is_complete(&mut self, e: @Expr) -> bool {
3183 return self.restriction == RESTRICT_STMT_EXPR &&
3184 !classify::expr_requires_semi_to_be_stmt(e);
3187 // parse a block. No inner attrs are allowed.
3188 pub fn parse_block(&mut self) -> P<Block> {
3189 maybe_whole!(no_clone self, NtBlock);
3191 let lo = self.span.lo;
3192 if self.eat_keyword(keywords::Unsafe) {
3193 self.obsolete(self.span, ObsoleteUnsafeBlock);
3195 self.expect(&token::LBRACE);
3197 return self.parse_block_tail_(lo, DefaultBlock, Vec::new());
3200 // parse a block. Inner attrs are allowed.
3201 fn parse_inner_attrs_and_block(&mut self)
3202 -> (Vec<Attribute> , P<Block>) {
3204 maybe_whole!(pair_empty self, NtBlock);
3206 let lo = self.span.lo;
3207 if self.eat_keyword(keywords::Unsafe) {
3208 self.obsolete(self.span, ObsoleteUnsafeBlock);
3210 self.expect(&token::LBRACE);
3211 let (inner, next) = self.parse_inner_attrs_and_next();
3213 (inner, self.parse_block_tail_(lo, DefaultBlock, next))
3216 // Precondition: already parsed the '{' or '#{'
3217 // I guess that also means "already parsed the 'impure'" if
3218 // necessary, and this should take a qualifier.
3219 // some blocks start with "#{"...
3220 fn parse_block_tail(&mut self, lo: BytePos, s: BlockCheckMode) -> P<Block> {
3221 self.parse_block_tail_(lo, s, Vec::new())
3224 // parse the rest of a block expression or function body
3225 fn parse_block_tail_(&mut self, lo: BytePos, s: BlockCheckMode,
3226 first_item_attrs: Vec<Attribute> ) -> P<Block> {
3227 let mut stmts = Vec::new();
3228 let mut expr = None;
3230 // wouldn't it be more uniform to parse view items only, here?
3231 let ParsedItemsAndViewItems {
3232 attrs_remaining: attrs_remaining,
3233 view_items: view_items,
3236 } = self.parse_items_and_view_items(first_item_attrs,
3239 for item in items.iter() {
3240 let decl = @spanned(item.span.lo, item.span.hi, DeclItem(*item));
3241 stmts.push(@spanned(item.span.lo, item.span.hi,
3242 StmtDecl(decl, ast::DUMMY_NODE_ID)));
3245 let mut attributes_box = attrs_remaining;
3247 while self.token != token::RBRACE {
3248 // parsing items even when they're not allowed lets us give
3249 // better error messages and recover more gracefully.
3250 attributes_box.push_all(self.parse_outer_attributes().as_slice());
3253 if !attributes_box.is_empty() {
3254 self.span_err(self.last_span, "expected item after attributes");
3255 attributes_box = Vec::new();
3257 self.bump(); // empty
3260 // fall through and out.
3263 let stmt = self.parse_stmt(attributes_box);
3264 attributes_box = Vec::new();
3266 StmtExpr(e, stmt_id) => {
3267 // expression without semicolon
3268 if classify::stmt_ends_with_semi(stmt) {
3269 // Just check for errors and recover; do not eat semicolon yet.
3270 self.commit_stmt(stmt, &[], &[token::SEMI, token::RBRACE]);
3276 let span_with_semi = Span {
3278 hi: self.last_span.hi,
3279 expn_info: stmt.span.expn_info,
3281 stmts.push(@codemap::Spanned {
3282 node: StmtSemi(e, stmt_id),
3283 span: span_with_semi,
3294 StmtMac(ref m, _) => {
3295 // statement macro; might be an expr
3299 stmts.push(@codemap::Spanned {
3300 node: StmtMac((*m).clone(), true),
3305 // if a block ends in `m!(arg)` without
3306 // a `;`, it must be an expr
3308 self.mk_mac_expr(stmt.span.lo,
3317 _ => { // all other kinds of statements:
3320 if classify::stmt_ends_with_semi(stmt) {
3321 self.commit_stmt_expecting(stmt, token::SEMI);
3329 if !attributes_box.is_empty() {
3330 self.span_err(self.last_span, "expected item after attributes");
3333 let hi = self.span.hi;
3336 view_items: view_items,
3339 id: ast::DUMMY_NODE_ID,
3341 span: mk_sp(lo, hi),
3345 // matches optbounds = ( ( : ( boundseq )? )? )
3346 // where boundseq = ( bound + boundseq ) | bound
3347 // and bound = 'static | ty
3348 // Returns "None" if there's no colon (e.g. "T");
3349 // Returns "Some(Empty)" if there's a colon but nothing after (e.g. "T:")
3350 // Returns "Some(stuff)" otherwise (e.g. "T:stuff").
3351 // NB: The None/Some distinction is important for issue #7264.
3353 // Note that the `allow_any_lifetime` argument is a hack for now while the
3354 // AST doesn't support arbitrary lifetimes in bounds on type parameters. In
3355 // the future, this flag should be removed, and the return value of this
3356 // function should be Option<~[TyParamBound]>
3357 fn parse_optional_ty_param_bounds(&mut self, allow_any_lifetime: bool)
3358 -> (Option<ast::Lifetime>, Option<OwnedSlice<TyParamBound>>)
3360 if !self.eat(&token::COLON) {
3361 return (None, None);
3364 let mut ret_lifetime = None;
3365 let mut result = vec!();
3368 token::LIFETIME(lifetime) => {
3369 let lifetime_interned_string = token::get_ident(lifetime);
3370 if lifetime_interned_string.equiv(&("static")) {
3371 result.push(RegionTyParamBound);
3372 if allow_any_lifetime && ret_lifetime.is_none() {
3373 ret_lifetime = Some(ast::Lifetime {
3374 id: ast::DUMMY_NODE_ID,
3379 } else if allow_any_lifetime && ret_lifetime.is_none() {
3380 ret_lifetime = Some(ast::Lifetime {
3381 id: ast::DUMMY_NODE_ID,
3386 self.span_err(self.span,
3387 "`'static` is the only permissible region bound here");
3391 token::MOD_SEP | token::IDENT(..) => {
3392 let tref = self.parse_trait_ref();
3393 result.push(TraitTyParamBound(tref));
3398 if !self.eat(&token::BINOP(token::PLUS)) {
3403 return (ret_lifetime, Some(OwnedSlice::from_vec(result)));
3406 // matches typaram = type? IDENT optbounds ( EQ ty )?
3407 fn parse_ty_param(&mut self) -> TyParam {
3408 let sized = self.parse_sized();
3409 let span = self.span;
3410 let ident = self.parse_ident();
3411 let (_, opt_bounds) = self.parse_optional_ty_param_bounds(false);
3412 // For typarams we don't care about the difference b/w "<T>" and "<T:>".
3413 let bounds = opt_bounds.unwrap_or_default();
3415 let default = if self.token == token::EQ {
3417 Some(self.parse_ty(false))
3423 id: ast::DUMMY_NODE_ID,
3431 // parse a set of optional generic type parameter declarations
3432 // matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
3433 // | ( < lifetimes , typaramseq ( , )? > )
3434 // where typaramseq = ( typaram ) | ( typaram , typaramseq )
3435 pub fn parse_generics(&mut self) -> ast::Generics {
3436 if self.eat(&token::LT) {
3437 let lifetimes = self.parse_lifetimes();
3438 let mut seen_default = false;
3439 let ty_params = self.parse_seq_to_gt(Some(token::COMMA), |p| {
3440 let ty_param = p.parse_ty_param();
3441 if ty_param.default.is_some() {
3442 seen_default = true;
3443 } else if seen_default {
3444 p.span_err(p.last_span,
3445 "type parameters with a default must be trailing");
3449 ast::Generics { lifetimes: lifetimes, ty_params: ty_params }
3451 ast_util::empty_generics()
3455 fn parse_generic_values_after_lt(&mut self) -> (Vec<ast::Lifetime>, Vec<P<Ty>> ) {
3456 let lifetimes = self.parse_lifetimes();
3457 let result = self.parse_seq_to_gt(
3459 |p| p.parse_ty(false));
3460 (lifetimes, result.into_vec())
3463 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
3464 -> (Vec<Arg> , bool) {
3466 let mut args: Vec<Option<Arg>> =
3467 self.parse_unspanned_seq(
3470 seq_sep_trailing_allowed(token::COMMA),
3472 if p.token == token::DOTDOTDOT {
3475 if p.token != token::RPAREN {
3476 p.span_fatal(p.span,
3477 "`...` must be last in argument list for variadic function");
3480 p.span_fatal(p.span,
3481 "only foreign functions are allowed to be variadic");
3485 Some(p.parse_arg_general(named_args))
3490 let variadic = match args.pop() {
3493 // Need to put back that last arg
3500 if variadic && args.is_empty() {
3502 "variadic function must be declared with at least one named argument");
3505 let args = args.move_iter().map(|x| x.unwrap()).collect();
3510 // parse the argument list and result type of a function declaration
3511 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> P<FnDecl> {
3513 let (args, variadic) = self.parse_fn_args(true, allow_variadic);
3514 let (ret_style, ret_ty) = self.parse_ret_ty();
3524 fn is_self_ident(&mut self) -> bool {
3526 token::IDENT(id, false) => id.name == special_idents::self_.name,
3531 fn expect_self_ident(&mut self) {
3532 if !self.is_self_ident() {
3533 let token_str = self.this_token_to_str();
3534 self.fatal(format!("expected `self` but found `{}`", token_str))
3539 // parse the argument list and result type of a function
3540 // that may have a self type.
3541 fn parse_fn_decl_with_self(&mut self, parse_arg_fn: |&mut Parser| -> Arg)
3542 -> (ExplicitSelf, P<FnDecl>) {
3543 fn maybe_parse_borrowed_explicit_self(this: &mut Parser)
3544 -> ast::ExplicitSelf_ {
3545 // The following things are possible to see here:
3550 // fn(&'lt mut self)
3552 // We already know that the current token is `&`.
3554 if this.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) {
3556 this.expect_self_ident();
3557 SelfRegion(None, MutImmutable)
3558 } else if this.look_ahead(1, |t| Parser::token_is_mutability(t)) &&
3560 |t| token::is_keyword(keywords::Self,
3563 let mutability = this.parse_mutability();
3564 this.expect_self_ident();
3565 SelfRegion(None, mutability)
3566 } else if this.look_ahead(1, |t| Parser::token_is_lifetime(t)) &&
3568 |t| token::is_keyword(keywords::Self,
3571 let lifetime = this.parse_lifetime();
3572 this.expect_self_ident();
3573 SelfRegion(Some(lifetime), MutImmutable)
3574 } else if this.look_ahead(1, |t| Parser::token_is_lifetime(t)) &&
3575 this.look_ahead(2, |t| {
3576 Parser::token_is_mutability(t)
3578 this.look_ahead(3, |t| token::is_keyword(keywords::Self,
3581 let lifetime = this.parse_lifetime();
3582 let mutability = this.parse_mutability();
3583 this.expect_self_ident();
3584 SelfRegion(Some(lifetime), mutability)
3590 self.expect(&token::LPAREN);
3592 // A bit of complexity and lookahead is needed here in order to be
3593 // backwards compatible.
3594 let lo = self.span.lo;
3595 let mut mutbl_self = MutImmutable;
3596 let explicit_self = match self.token {
3597 token::BINOP(token::AND) => {
3598 maybe_parse_borrowed_explicit_self(self)
3601 // We need to make sure it isn't a type
3602 if self.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) {
3604 self.expect_self_ident();
3610 token::IDENT(..) if self.is_self_ident() => {
3614 token::BINOP(token::STAR) => {
3615 // Possibly "*self" or "*mut self" -- not supported. Try to avoid
3616 // emitting cryptic "unexpected token" errors.
3618 let _mutability = if Parser::token_is_mutability(&self.token) {
3619 self.parse_mutability()
3620 } else { MutImmutable };
3621 if self.is_self_ident() {
3622 self.span_err(self.span, "cannot pass self by unsafe pointer");
3627 _ if Parser::token_is_mutability(&self.token) &&
3628 self.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) => {
3629 mutbl_self = self.parse_mutability();
3630 self.expect_self_ident();
3633 _ if Parser::token_is_mutability(&self.token) &&
3634 self.look_ahead(1, |t| *t == token::TILDE) &&
3635 self.look_ahead(2, |t| token::is_keyword(keywords::Self, t)) => {
3636 mutbl_self = self.parse_mutability();
3638 self.expect_self_ident();
3644 let explicit_self_sp = mk_sp(lo, self.span.hi);
3646 // If we parsed a self type, expect a comma before the argument list.
3647 let fn_inputs = if explicit_self != SelfStatic {
3651 let sep = seq_sep_trailing_disallowed(token::COMMA);
3652 let mut fn_inputs = self.parse_seq_to_before_end(
3657 fn_inputs.unshift(Arg::new_self(explicit_self_sp, mutbl_self));
3661 vec!(Arg::new_self(explicit_self_sp, mutbl_self))
3664 let token_str = self.this_token_to_str();
3665 self.fatal(format!("expected `,` or `)`, found `{}`",
3670 let sep = seq_sep_trailing_disallowed(token::COMMA);
3671 self.parse_seq_to_before_end(&token::RPAREN, sep, parse_arg_fn)
3674 self.expect(&token::RPAREN);
3676 let hi = self.span.hi;
3678 let (ret_style, ret_ty) = self.parse_ret_ty();
3680 let fn_decl = P(FnDecl {
3687 (spanned(lo, hi, explicit_self), fn_decl)
3690 // parse the |arg, arg| header on a lambda
3691 fn parse_fn_block_decl(&mut self) -> P<FnDecl> {
3692 let inputs_captures = {
3693 if self.eat(&token::OROR) {
3696 self.parse_unspanned_seq(
3697 &token::BINOP(token::OR),
3698 &token::BINOP(token::OR),
3699 seq_sep_trailing_disallowed(token::COMMA),
3700 |p| p.parse_fn_block_arg()
3704 let output = if self.eat(&token::RARROW) {
3705 self.parse_ty(false)
3708 id: ast::DUMMY_NODE_ID,
3715 inputs: inputs_captures,
3722 // Parses the `(arg, arg) -> return_type` header on a procedure.
3723 fn parse_proc_decl(&mut self) -> P<FnDecl> {
3725 self.parse_unspanned_seq(&token::LPAREN,
3727 seq_sep_trailing_allowed(token::COMMA),
3728 |p| p.parse_fn_block_arg());
3730 let output = if self.eat(&token::RARROW) {
3731 self.parse_ty(false)
3734 id: ast::DUMMY_NODE_ID,
3748 // parse the name and optional generic types of a function header.
3749 fn parse_fn_header(&mut self) -> (Ident, ast::Generics) {
3750 let id = self.parse_ident();
3751 let generics = self.parse_generics();
3755 fn mk_item(&mut self, lo: BytePos, hi: BytePos, ident: Ident,
3756 node: Item_, vis: Visibility,
3757 attrs: Vec<Attribute> ) -> @Item {
3761 id: ast::DUMMY_NODE_ID,
3768 // parse an item-position function declaration.
3769 fn parse_item_fn(&mut self, fn_style: FnStyle, abi: abi::Abi) -> ItemInfo {
3770 let (ident, generics) = self.parse_fn_header();
3771 let decl = self.parse_fn_decl(false);
3772 let (inner_attrs, body) = self.parse_inner_attrs_and_block();
3773 (ident, ItemFn(decl, fn_style, abi, generics, body), Some(inner_attrs))
3776 // parse a method in a trait impl, starting with `attrs` attributes.
3777 fn parse_method(&mut self, already_parsed_attrs: Option<Vec<Attribute> >) -> @Method {
3778 let next_attrs = self.parse_outer_attributes();
3779 let attrs = match already_parsed_attrs {
3780 Some(mut a) => { a.push_all_move(next_attrs); a }
3784 let lo = self.span.lo;
3786 let visa = self.parse_visibility();
3787 let fn_style = self.parse_fn_style();
3788 let ident = self.parse_ident();
3789 let generics = self.parse_generics();
3790 let (explicit_self, decl) = self.parse_fn_decl_with_self(|p| {
3794 let (inner_attrs, body) = self.parse_inner_attrs_and_block();
3795 let hi = body.span.hi;
3796 let attrs = attrs.append(inner_attrs.as_slice());
3801 explicit_self: explicit_self,
3805 id: ast::DUMMY_NODE_ID,
3806 span: mk_sp(lo, hi),
3811 // parse trait Foo { ... }
3812 fn parse_item_trait(&mut self) -> ItemInfo {
3813 let ident = self.parse_ident();
3814 let tps = self.parse_generics();
3815 let sized = self.parse_for_sized();
3817 // Parse traits, if necessary.
3819 if self.token == token::COLON {
3821 traits = self.parse_trait_ref_list(&token::LBRACE);
3823 traits = Vec::new();
3826 let meths = self.parse_trait_methods();
3827 (ident, ItemTrait(tps, sized, traits, meths), None)
3830 // Parses two variants (with the region/type params always optional):
3831 // impl<T> Foo { ... }
3832 // impl<T> ToStr for ~[T] { ... }
3833 fn parse_item_impl(&mut self) -> ItemInfo {
3834 // First, parse type parameters if necessary.
3835 let generics = self.parse_generics();
3837 // Special case: if the next identifier that follows is '(', don't
3838 // allow this to be parsed as a trait.
3839 let could_be_trait = self.token != token::LPAREN;
3842 let mut ty = self.parse_ty(false);
3844 // Parse traits, if necessary.
3845 let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) {
3846 // New-style trait. Reinterpret the type as a trait.
3847 let opt_trait_ref = match ty.node {
3848 TyPath(ref path, None, node_id) => {
3850 path: /* bad */ (*path).clone(),
3855 self.span_err(ty.span,
3856 "bounded traits are only valid in type position");
3860 self.span_err(ty.span, "not a trait");
3865 ty = self.parse_ty(false);
3871 let mut meths = Vec::new();
3872 self.expect(&token::LBRACE);
3873 let (inner_attrs, next) = self.parse_inner_attrs_and_next();
3874 let mut method_attrs = Some(next);
3875 while !self.eat(&token::RBRACE) {
3876 meths.push(self.parse_method(method_attrs));
3877 method_attrs = None;
3880 let ident = ast_util::impl_pretty_name(&opt_trait, ty);
3882 (ident, ItemImpl(generics, opt_trait, ty, meths), Some(inner_attrs))
3885 // parse a::B<~str,int>
3886 fn parse_trait_ref(&mut self) -> TraitRef {
3888 path: self.parse_path(LifetimeAndTypesWithoutColons).path,
3889 ref_id: ast::DUMMY_NODE_ID,
3893 // parse B + C<~str,int> + D
3894 fn parse_trait_ref_list(&mut self, ket: &token::Token) -> Vec<TraitRef> {
3895 self.parse_seq_to_before_end(
3897 seq_sep_trailing_disallowed(token::BINOP(token::PLUS)),
3898 |p| p.parse_trait_ref()
3902 // parse struct Foo { ... }
3903 fn parse_item_struct(&mut self, is_virtual: bool) -> ItemInfo {
3904 let class_name = self.parse_ident();
3905 let generics = self.parse_generics();
3907 let super_struct = if self.eat(&token::COLON) {
3908 let ty = self.parse_ty(false);
3910 TyPath(_, None, _) => {
3914 self.span_err(ty.span, "not a struct");
3922 let mut fields: Vec<StructField>;
3925 if self.eat(&token::LBRACE) {
3926 // It's a record-like struct.
3927 is_tuple_like = false;
3928 fields = Vec::new();
3929 while self.token != token::RBRACE {
3930 fields.push(self.parse_struct_decl_field());
3932 if fields.len() == 0 {
3933 self.fatal(format!("unit-like struct definition should be written as `struct {};`",
3934 token::get_ident(class_name)));
3937 } else if self.token == token::LPAREN {
3938 // It's a tuple-like struct.
3939 is_tuple_like = true;
3940 fields = self.parse_unspanned_seq(
3943 seq_sep_trailing_allowed(token::COMMA),
3945 let attrs = p.parse_outer_attributes();
3947 let struct_field_ = ast::StructField_ {
3948 kind: UnnamedField(p.parse_visibility()),
3949 id: ast::DUMMY_NODE_ID,
3950 ty: p.parse_ty(false),
3953 spanned(lo, p.span.hi, struct_field_)
3955 self.expect(&token::SEMI);
3956 } else if self.eat(&token::SEMI) {
3957 // It's a unit-like struct.
3958 is_tuple_like = true;
3959 fields = Vec::new();
3961 let token_str = self.this_token_to_str();
3962 self.fatal(format!("expected `\\{`, `(`, or `;` after struct \
3963 name but found `{}`",
3967 let _ = ast::DUMMY_NODE_ID; // FIXME: Workaround for crazy bug.
3968 let new_id = ast::DUMMY_NODE_ID;
3970 ItemStruct(@ast::StructDef {
3972 ctor_id: if is_tuple_like { Some(new_id) } else { None },
3973 super_struct: super_struct,
3974 is_virtual: is_virtual,
3979 // parse a structure field declaration
3980 pub fn parse_single_struct_field(&mut self,
3982 attrs: Vec<Attribute> )
3984 let a_var = self.parse_name_and_ty(vis, attrs);
3991 let token_str = self.this_token_to_str();
3992 self.span_fatal(self.span,
3993 format!("expected `,`, or `\\}` but found `{}`",
4000 // parse an element of a struct definition
4001 fn parse_struct_decl_field(&mut self) -> StructField {
4003 let attrs = self.parse_outer_attributes();
4005 if self.eat_keyword(keywords::Pub) {
4006 return self.parse_single_struct_field(Public, attrs);
4009 return self.parse_single_struct_field(Inherited, attrs);
4012 // parse visiility: PUB, PRIV, or nothing
4013 fn parse_visibility(&mut self) -> Visibility {
4014 if self.eat_keyword(keywords::Pub) { Public }
4018 fn parse_sized(&mut self) -> Sized {
4019 if self.eat_keyword(keywords::Type) { DynSize }
4023 fn parse_for_sized(&mut self) -> Sized {
4024 if self.eat_keyword(keywords::For) {
4025 if !self.eat_keyword(keywords::Type) {
4026 self.span_err(self.last_span,
4027 "expected 'type' after for in trait item");
4035 // given a termination token and a vector of already-parsed
4036 // attributes (of length 0 or 1), parse all of the items in a module
4037 fn parse_mod_items(&mut self,
4039 first_item_attrs: Vec<Attribute> )
4041 // parse all of the items up to closing or an attribute.
4042 // view items are legal here.
4043 let ParsedItemsAndViewItems {
4044 attrs_remaining: attrs_remaining,
4045 view_items: view_items,
4046 items: starting_items,
4048 } = self.parse_items_and_view_items(first_item_attrs, true, true);
4049 let mut items: Vec<@Item> = starting_items;
4050 let attrs_remaining_len = attrs_remaining.len();
4052 // don't think this other loop is even necessary....
4054 let mut first = true;
4055 while self.token != term {
4056 let mut attrs = self.parse_outer_attributes();
4058 attrs = attrs_remaining.clone().append(attrs.as_slice());
4061 debug!("parse_mod_items: parse_item_or_view_item(attrs={:?})",
4063 match self.parse_item_or_view_item(attrs,
4064 true /* macros allowed */) {
4065 IoviItem(item) => items.push(item),
4066 IoviViewItem(view_item) => {
4067 self.span_fatal(view_item.span,
4068 "view items must be declared at the top of \
4072 let token_str = self.this_token_to_str();
4073 self.fatal(format!("expected item but found `{}`",
4079 if first && attrs_remaining_len > 0u {
4080 // We parsed attributes for the first item but didn't find it
4081 self.span_err(self.last_span, "expected item after attributes");
4084 ast::Mod { view_items: view_items, items: items }
4087 fn parse_item_const(&mut self) -> ItemInfo {
4088 let m = if self.eat_keyword(keywords::Mut) {MutMutable} else {MutImmutable};
4089 let id = self.parse_ident();
4090 self.expect(&token::COLON);
4091 let ty = self.parse_ty(false);
4092 self.expect(&token::EQ);
4093 let e = self.parse_expr();
4094 self.commit_expr_expecting(e, token::SEMI);
4095 (id, ItemStatic(ty, m, e), None)
4098 // parse a `mod <foo> { ... }` or `mod <foo>;` item
4099 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> ItemInfo {
4100 let id_span = self.span;
4101 let id = self.parse_ident();
4102 if self.token == token::SEMI {
4104 // This mod is in an external file. Let's go get it!
4105 let (m, attrs) = self.eval_src_mod(id, outer_attrs, id_span);
4106 (id, m, Some(attrs))
4108 self.push_mod_path(id, outer_attrs);
4109 self.expect(&token::LBRACE);
4110 let (inner, next) = self.parse_inner_attrs_and_next();
4111 let m = self.parse_mod_items(token::RBRACE, next);
4112 self.expect(&token::RBRACE);
4113 self.pop_mod_path();
4114 (id, ItemMod(m), Some(inner))
4118 fn push_mod_path(&mut self, id: Ident, attrs: &[Attribute]) {
4119 let default_path = self.id_to_interned_str(id);
4120 let file_path = match ::attr::first_attr_value_str_by_name(attrs,
4123 None => default_path,
4125 self.mod_path_stack.push(file_path)
4128 fn pop_mod_path(&mut self) {
4129 self.mod_path_stack.pop().unwrap();
4132 // read a module from a source file.
4133 fn eval_src_mod(&mut self,
4135 outer_attrs: &[ast::Attribute],
4137 -> (ast::Item_, Vec<ast::Attribute> ) {
4138 let mut prefix = Path::new(self.sess.span_diagnostic.cm.span_to_filename(self.span));
4140 let mod_path = Path::new(".").join_many(self.mod_path_stack.as_slice());
4141 let dir_path = prefix.join(&mod_path);
4142 let file_path = match ::attr::first_attr_value_str_by_name(
4143 outer_attrs, "path") {
4144 Some(d) => dir_path.join(d),
4146 let mod_string = token::get_ident(id);
4147 let mod_name = mod_string.get().to_owned();
4148 let default_path_str = mod_name + ".rs";
4149 let secondary_path_str = mod_name + "/mod.rs";
4150 let default_path = dir_path.join(default_path_str.as_slice());
4151 let secondary_path = dir_path.join(secondary_path_str.as_slice());
4152 let default_exists = default_path.exists();
4153 let secondary_exists = secondary_path.exists();
4154 match (default_exists, secondary_exists) {
4155 (true, false) => default_path,
4156 (false, true) => secondary_path,
4158 self.span_fatal(id_sp, format!("file not found for module `{}`", mod_name));
4161 self.span_fatal(id_sp,
4162 format!("file for module `{}` found at both {} and {}",
4163 mod_name, default_path_str, secondary_path_str));
4169 self.eval_src_mod_from_path(file_path,
4170 outer_attrs.iter().map(|x| *x).collect(),
4174 fn eval_src_mod_from_path(&mut self,
4176 outer_attrs: Vec<ast::Attribute> ,
4177 id_sp: Span) -> (ast::Item_, Vec<ast::Attribute> ) {
4178 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
4179 match included_mod_stack.iter().position(|p| *p == path) {
4181 let mut err = StrBuf::from_str("circular modules: ");
4182 let len = included_mod_stack.len();
4183 for p in included_mod_stack.slice(i, len).iter() {
4184 err.push_str(p.display().as_maybe_owned().as_slice());
4185 err.push_str(" -> ");
4187 err.push_str(path.display().as_maybe_owned().as_slice());
4188 self.span_fatal(id_sp, err.into_owned());
4192 included_mod_stack.push(path.clone());
4193 drop(included_mod_stack);
4196 new_sub_parser_from_file(self.sess,
4200 let (inner, next) = p0.parse_inner_attrs_and_next();
4201 let mod_attrs = outer_attrs.append(inner.as_slice());
4202 let first_item_outer_attrs = next;
4203 let m0 = p0.parse_mod_items(token::EOF, first_item_outer_attrs);
4204 self.sess.included_mod_stack.borrow_mut().pop();
4205 return (ast::ItemMod(m0), mod_attrs);
4208 // parse a function declaration from a foreign module
4209 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility,
4210 attrs: Vec<Attribute> ) -> @ForeignItem {
4211 let lo = self.span.lo;
4213 // Parse obsolete purity.
4214 let fn_style = self.parse_fn_style();
4215 if fn_style != NormalFn {
4216 self.obsolete(self.last_span, ObsoleteUnsafeExternFn);
4219 let (ident, generics) = self.parse_fn_header();
4220 let decl = self.parse_fn_decl(true);
4221 let hi = self.span.hi;
4222 self.expect(&token::SEMI);
4223 @ast::ForeignItem { ident: ident,
4225 node: ForeignItemFn(decl, generics),
4226 id: ast::DUMMY_NODE_ID,
4227 span: mk_sp(lo, hi),
4231 // parse a static item from a foreign module
4232 fn parse_item_foreign_static(&mut self, vis: ast::Visibility,
4233 attrs: Vec<Attribute> ) -> @ForeignItem {
4234 let lo = self.span.lo;
4236 self.expect_keyword(keywords::Static);
4237 let mutbl = self.eat_keyword(keywords::Mut);
4239 let ident = self.parse_ident();
4240 self.expect(&token::COLON);
4241 let ty = self.parse_ty(false);
4242 let hi = self.span.hi;
4243 self.expect(&token::SEMI);
4244 @ast::ForeignItem { ident: ident,
4246 node: ForeignItemStatic(ty, mutbl),
4247 id: ast::DUMMY_NODE_ID,
4248 span: mk_sp(lo, hi),
4252 // parse safe/unsafe and fn
4253 fn parse_fn_style(&mut self) -> FnStyle {
4254 if self.eat_keyword(keywords::Fn) { NormalFn }
4255 else if self.eat_keyword(keywords::Unsafe) {
4256 self.expect_keyword(keywords::Fn);
4259 else { self.unexpected(); }
4263 // at this point, this is essentially a wrapper for
4264 // parse_foreign_items.
4265 fn parse_foreign_mod_items(&mut self,
4267 first_item_attrs: Vec<Attribute> )
4269 let ParsedItemsAndViewItems {
4270 attrs_remaining: attrs_remaining,
4271 view_items: view_items,
4273 foreign_items: foreign_items
4274 } = self.parse_foreign_items(first_item_attrs, true);
4275 if ! attrs_remaining.is_empty() {
4276 self.span_err(self.last_span,
4277 "expected item after attributes");
4279 assert!(self.token == token::RBRACE);
4282 view_items: view_items,
4283 items: foreign_items
4287 /// Parse extern crate links
4291 /// extern crate url;
4292 /// extern crate foo = "bar";
4293 fn parse_item_extern_crate(&mut self,
4295 visibility: Visibility,
4296 attrs: Vec<Attribute> )
4299 let (maybe_path, ident) = match self.token {
4300 token::IDENT(..) => {
4301 let the_ident = self.parse_ident();
4302 self.expect_one_of(&[], &[token::EQ, token::SEMI]);
4303 let path = if self.token == token::EQ {
4305 Some(self.parse_str())
4308 self.expect(&token::SEMI);
4312 let token_str = self.this_token_to_str();
4313 self.span_fatal(self.span,
4314 format!("expected extern crate name but found `{}`",
4319 IoviViewItem(ast::ViewItem {
4320 node: ViewItemExternCrate(ident, maybe_path, ast::DUMMY_NODE_ID),
4323 span: mk_sp(lo, self.last_span.hi)
4327 /// Parse `extern` for foreign ABIs
4330 /// `extern` is expected to have been
4331 /// consumed before calling this method
4337 fn parse_item_foreign_mod(&mut self,
4339 opt_abi: Option<abi::Abi>,
4340 visibility: Visibility,
4341 attrs: Vec<Attribute> )
4344 self.expect(&token::LBRACE);
4346 let abi = opt_abi.unwrap_or(abi::C);
4348 let (inner, next) = self.parse_inner_attrs_and_next();
4349 let m = self.parse_foreign_mod_items(abi, next);
4350 self.expect(&token::RBRACE);
4352 let item = self.mk_item(lo,
4354 special_idents::invalid,
4357 maybe_append(attrs, Some(inner)));
4358 return IoviItem(item);
4361 // parse type Foo = Bar;
4362 fn parse_item_type(&mut self) -> ItemInfo {
4363 let ident = self.parse_ident();
4364 let tps = self.parse_generics();
4365 self.expect(&token::EQ);
4366 let ty = self.parse_ty(false);
4367 self.expect(&token::SEMI);
4368 (ident, ItemTy(ty, tps), None)
4371 // parse a structure-like enum variant definition
4372 // this should probably be renamed or refactored...
4373 fn parse_struct_def(&mut self) -> @StructDef {
4374 let mut fields: Vec<StructField> = Vec::new();
4375 while self.token != token::RBRACE {
4376 fields.push(self.parse_struct_decl_field());
4380 return @ast::StructDef {
4388 // parse the part of an "enum" decl following the '{'
4389 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> EnumDef {
4390 let mut variants = Vec::new();
4391 let mut all_nullary = true;
4392 let mut have_disr = false;
4393 while self.token != token::RBRACE {
4394 let variant_attrs = self.parse_outer_attributes();
4395 let vlo = self.span.lo;
4397 let vis = self.parse_visibility();
4401 let mut args = Vec::new();
4402 let mut disr_expr = None;
4403 ident = self.parse_ident();
4404 if self.eat(&token::LBRACE) {
4405 // Parse a struct variant.
4406 all_nullary = false;
4407 kind = StructVariantKind(self.parse_struct_def());
4408 } else if self.token == token::LPAREN {
4409 all_nullary = false;
4410 let arg_tys = self.parse_enum_variant_seq(
4413 seq_sep_trailing_disallowed(token::COMMA),
4414 |p| p.parse_ty(false)
4416 for ty in arg_tys.move_iter() {
4417 args.push(ast::VariantArg {
4419 id: ast::DUMMY_NODE_ID,
4422 kind = TupleVariantKind(args);
4423 } else if self.eat(&token::EQ) {
4425 disr_expr = Some(self.parse_expr());
4426 kind = TupleVariantKind(args);
4428 kind = TupleVariantKind(Vec::new());
4431 let vr = ast::Variant_ {
4433 attrs: variant_attrs,
4435 id: ast::DUMMY_NODE_ID,
4436 disr_expr: disr_expr,
4439 variants.push(P(spanned(vlo, self.last_span.hi, vr)));
4441 if !self.eat(&token::COMMA) { break; }
4443 self.expect(&token::RBRACE);
4444 if have_disr && !all_nullary {
4445 self.fatal("discriminator values can only be used with a c-like \
4449 ast::EnumDef { variants: variants }
4452 // parse an "enum" declaration
4453 fn parse_item_enum(&mut self) -> ItemInfo {
4454 let id = self.parse_ident();
4455 let generics = self.parse_generics();
4456 self.expect(&token::LBRACE);
4458 let enum_definition = self.parse_enum_def(&generics);
4459 (id, ItemEnum(enum_definition, generics), None)
4462 fn fn_expr_lookahead(tok: &token::Token) -> bool {
4464 token::LPAREN | token::AT | token::TILDE | token::BINOP(_) => true,
4469 // Parses a string as an ABI spec on an extern type or module. Consumes
4470 // the `extern` keyword, if one is found.
4471 fn parse_opt_abi(&mut self) -> Option<abi::Abi> {
4473 token::LIT_STR(s) | token::LIT_STR_RAW(s, _) => {
4475 let identifier_string = token::get_ident(s);
4476 let the_string = identifier_string.get();
4477 match abi::lookup(the_string) {
4478 Some(abi) => Some(abi),
4482 format!("illegal ABI: \
4483 expected one of [{}], \
4485 abi::all_names().connect(", "),
4496 // parse one of the items or view items allowed by the
4497 // flags; on failure, return IoviNone.
4498 // NB: this function no longer parses the items inside an
4500 fn parse_item_or_view_item(&mut self,
4501 attrs: Vec<Attribute> ,
4502 macros_allowed: bool)
4505 INTERPOLATED(token::NtItem(item)) => {
4507 let new_attrs = attrs.append(item.attrs.as_slice());
4508 return IoviItem(@Item {
4516 let lo = self.span.lo;
4518 let visibility = self.parse_visibility();
4520 // must be a view item:
4521 if self.eat_keyword(keywords::Use) {
4522 // USE ITEM (IoviViewItem)
4523 let view_item = self.parse_use();
4524 self.expect(&token::SEMI);
4525 return IoviViewItem(ast::ViewItem {
4529 span: mk_sp(lo, self.last_span.hi)
4532 // either a view item or an item:
4533 if self.eat_keyword(keywords::Extern) {
4534 let next_is_mod = self.eat_keyword(keywords::Mod);
4536 if next_is_mod || self.eat_keyword(keywords::Crate) {
4538 self.span_err(mk_sp(lo, self.last_span.hi),
4539 format!("`extern mod` is obsolete, use \
4540 `extern crate` instead \
4541 to refer to external crates."))
4543 return self.parse_item_extern_crate(lo, visibility, attrs);
4546 let opt_abi = self.parse_opt_abi();
4548 if self.eat_keyword(keywords::Fn) {
4549 // EXTERN FUNCTION ITEM
4550 let abi = opt_abi.unwrap_or(abi::C);
4551 let (ident, item_, extra_attrs) =
4552 self.parse_item_fn(ExternFn, abi);
4553 let item = self.mk_item(lo,
4558 maybe_append(attrs, extra_attrs));
4559 return IoviItem(item);
4560 } else if self.token == token::LBRACE {
4561 return self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs);
4564 let token_str = self.this_token_to_str();
4565 self.span_fatal(self.span,
4566 format!("expected `\\{` or `fn` but found `{}`", token_str));
4569 let is_virtual = self.eat_keyword(keywords::Virtual);
4570 if is_virtual && !self.is_keyword(keywords::Struct) {
4571 self.span_err(self.span,
4572 "`virtual` keyword may only be used with `struct`");
4575 // the rest are all guaranteed to be items:
4576 if self.is_keyword(keywords::Static) {
4579 let (ident, item_, extra_attrs) = self.parse_item_const();
4580 let item = self.mk_item(lo,
4585 maybe_append(attrs, extra_attrs));
4586 return IoviItem(item);
4588 if self.is_keyword(keywords::Fn) &&
4589 self.look_ahead(1, |f| !Parser::fn_expr_lookahead(f)) {
4592 let (ident, item_, extra_attrs) =
4593 self.parse_item_fn(NormalFn, abi::Rust);
4594 let item = self.mk_item(lo,
4599 maybe_append(attrs, extra_attrs));
4600 return IoviItem(item);
4602 if self.is_keyword(keywords::Unsafe)
4603 && self.look_ahead(1u, |t| *t != token::LBRACE) {
4604 // UNSAFE FUNCTION ITEM
4606 self.expect_keyword(keywords::Fn);
4607 let (ident, item_, extra_attrs) =
4608 self.parse_item_fn(UnsafeFn, abi::Rust);
4609 let item = self.mk_item(lo,
4614 maybe_append(attrs, extra_attrs));
4615 return IoviItem(item);
4617 if self.eat_keyword(keywords::Mod) {
4619 let (ident, item_, extra_attrs) =
4620 self.parse_item_mod(attrs.as_slice());
4621 let item = self.mk_item(lo,
4626 maybe_append(attrs, extra_attrs));
4627 return IoviItem(item);
4629 if self.eat_keyword(keywords::Type) {
4631 let (ident, item_, extra_attrs) = self.parse_item_type();
4632 let item = self.mk_item(lo,
4637 maybe_append(attrs, extra_attrs));
4638 return IoviItem(item);
4640 if self.eat_keyword(keywords::Enum) {
4642 let (ident, item_, extra_attrs) = self.parse_item_enum();
4643 let item = self.mk_item(lo,
4648 maybe_append(attrs, extra_attrs));
4649 return IoviItem(item);
4651 if self.eat_keyword(keywords::Trait) {
4653 let (ident, item_, extra_attrs) = self.parse_item_trait();
4654 let item = self.mk_item(lo,
4659 maybe_append(attrs, extra_attrs));
4660 return IoviItem(item);
4662 if self.eat_keyword(keywords::Impl) {
4664 let (ident, item_, extra_attrs) = self.parse_item_impl();
4665 let item = self.mk_item(lo,
4670 maybe_append(attrs, extra_attrs));
4671 return IoviItem(item);
4673 if self.eat_keyword(keywords::Struct) {
4675 let (ident, item_, extra_attrs) = self.parse_item_struct(is_virtual);
4676 let item = self.mk_item(lo,
4681 maybe_append(attrs, extra_attrs));
4682 return IoviItem(item);
4684 self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility)
4687 // parse a foreign item; on failure, return IoviNone.
4688 fn parse_foreign_item(&mut self,
4689 attrs: Vec<Attribute> ,
4690 macros_allowed: bool)
4692 maybe_whole!(iovi self, NtItem);
4693 let lo = self.span.lo;
4695 let visibility = self.parse_visibility();
4697 if self.is_keyword(keywords::Static) {
4698 // FOREIGN STATIC ITEM
4699 let item = self.parse_item_foreign_static(visibility, attrs);
4700 return IoviForeignItem(item);
4702 if self.is_keyword(keywords::Fn) || self.is_keyword(keywords::Unsafe) {
4703 // FOREIGN FUNCTION ITEM
4704 let item = self.parse_item_foreign_fn(visibility, attrs);
4705 return IoviForeignItem(item);
4707 self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility)
4710 // this is the fall-through for parsing items.
4711 fn parse_macro_use_or_failure(
4713 attrs: Vec<Attribute> ,
4714 macros_allowed: bool,
4716 visibility: Visibility
4717 ) -> ItemOrViewItem {
4718 if macros_allowed && !token::is_any_keyword(&self.token)
4719 && self.look_ahead(1, |t| *t == token::NOT)
4720 && (self.look_ahead(2, |t| is_plain_ident(t))
4721 || self.look_ahead(2, |t| *t == token::LPAREN)
4722 || self.look_ahead(2, |t| *t == token::LBRACE)) {
4723 // MACRO INVOCATION ITEM
4726 let pth = self.parse_path(NoTypesAllowed).path;
4727 self.expect(&token::NOT);
4729 // a 'special' identifier (like what `macro_rules!` uses)
4730 // is optional. We should eventually unify invoc syntax
4732 let id = if is_plain_ident(&self.token) {
4735 token::special_idents::invalid // no special identifier
4737 // eat a matched-delimiter token tree:
4738 let tts = match token::close_delimiter_for(&self.token) {
4741 self.parse_seq_to_end(&ket,
4743 |p| p.parse_token_tree())
4745 None => self.fatal("expected open delimiter")
4747 // single-variant-enum... :
4748 let m = ast::MacInvocTT(pth, tts, EMPTY_CTXT);
4749 let m: ast::Mac = codemap::Spanned { node: m,
4750 span: mk_sp(self.span.lo,
4752 let item_ = ItemMac(m);
4753 let item = self.mk_item(lo,
4759 return IoviItem(item);
4762 // FAILURE TO PARSE ITEM
4763 if visibility != Inherited {
4764 let mut s = StrBuf::from_str("unmatched visibility `");
4765 if visibility == Public {
4771 self.span_fatal(self.last_span, s.as_slice());
4773 return IoviNone(attrs);
4776 pub fn parse_item(&mut self, attrs: Vec<Attribute> ) -> Option<@Item> {
4777 match self.parse_item_or_view_item(attrs, true) {
4778 IoviNone(_) => None,
4780 self.fatal("view items are not allowed here"),
4781 IoviForeignItem(_) =>
4782 self.fatal("foreign items are not allowed here"),
4783 IoviItem(item) => Some(item)
4787 // parse, e.g., "use a::b::{z,y}"
4788 fn parse_use(&mut self) -> ViewItem_ {
4789 return ViewItemUse(self.parse_view_paths());
4793 // matches view_path : MOD? IDENT EQ non_global_path
4794 // | MOD? non_global_path MOD_SEP LBRACE RBRACE
4795 // | MOD? non_global_path MOD_SEP LBRACE ident_seq RBRACE
4796 // | MOD? non_global_path MOD_SEP STAR
4797 // | MOD? non_global_path
4798 fn parse_view_path(&mut self) -> @ViewPath {
4799 let lo = self.span.lo;
4801 if self.token == token::LBRACE {
4803 let idents = self.parse_unspanned_seq(
4804 &token::LBRACE, &token::RBRACE,
4805 seq_sep_trailing_allowed(token::COMMA),
4806 |p| p.parse_path_list_ident());
4807 let path = ast::Path {
4808 span: mk_sp(lo, self.span.hi),
4810 segments: Vec::new()
4812 return @spanned(lo, self.span.hi,
4813 ViewPathList(path, idents, ast::DUMMY_NODE_ID));
4816 let first_ident = self.parse_ident();
4817 let mut path = vec!(first_ident);
4822 let path_lo = self.span.lo;
4823 path = vec!(self.parse_ident());
4824 while self.token == token::MOD_SEP {
4826 let id = self.parse_ident();
4829 let path = ast::Path {
4830 span: mk_sp(path_lo, self.span.hi),
4832 segments: path.move_iter().map(|identifier| {
4834 identifier: identifier,
4835 lifetimes: Vec::new(),
4836 types: OwnedSlice::empty(),
4840 return @spanned(lo, self.span.hi,
4841 ViewPathSimple(first_ident, path,
4842 ast::DUMMY_NODE_ID));
4846 // foo::bar or foo::{a,b,c} or foo::*
4847 while self.token == token::MOD_SEP {
4851 token::IDENT(i, _) => {
4856 // foo::bar::{a,b,c}
4858 let idents = self.parse_unspanned_seq(
4861 seq_sep_trailing_allowed(token::COMMA),
4862 |p| p.parse_path_list_ident()
4864 let path = ast::Path {
4865 span: mk_sp(lo, self.span.hi),
4867 segments: path.move_iter().map(|identifier| {
4869 identifier: identifier,
4870 lifetimes: Vec::new(),
4871 types: OwnedSlice::empty(),
4875 return @spanned(lo, self.span.hi,
4876 ViewPathList(path, idents, ast::DUMMY_NODE_ID));
4880 token::BINOP(token::STAR) => {
4882 let path = ast::Path {
4883 span: mk_sp(lo, self.span.hi),
4885 segments: path.move_iter().map(|identifier| {
4887 identifier: identifier,
4888 lifetimes: Vec::new(),
4889 types: OwnedSlice::empty(),
4893 return @spanned(lo, self.span.hi,
4894 ViewPathGlob(path, ast::DUMMY_NODE_ID));
4903 let last = *path.get(path.len() - 1u);
4904 let path = ast::Path {
4905 span: mk_sp(lo, self.span.hi),
4907 segments: path.move_iter().map(|identifier| {
4909 identifier: identifier,
4910 lifetimes: Vec::new(),
4911 types: OwnedSlice::empty(),
4917 ViewPathSimple(last, path, ast::DUMMY_NODE_ID));
4920 // matches view_paths = view_path | view_path , view_paths
4921 fn parse_view_paths(&mut self) -> Vec<@ViewPath> {
4922 let mut vp = vec!(self.parse_view_path());
4923 while self.token == token::COMMA {
4925 self.obsolete(self.last_span, ObsoleteMultipleImport);
4926 vp.push(self.parse_view_path());
4931 // Parses a sequence of items. Stops when it finds program
4932 // text that can't be parsed as an item
4933 // - mod_items uses extern_mod_allowed = true
4934 // - block_tail_ uses extern_mod_allowed = false
4935 fn parse_items_and_view_items(&mut self,
4936 first_item_attrs: Vec<Attribute> ,
4937 mut extern_mod_allowed: bool,
4938 macros_allowed: bool)
4939 -> ParsedItemsAndViewItems {
4940 let mut attrs = first_item_attrs.append(self.parse_outer_attributes().as_slice());
4941 // First, parse view items.
4942 let mut view_items : Vec<ast::ViewItem> = Vec::new();
4943 let mut items = Vec::new();
4945 // I think this code would probably read better as a single
4946 // loop with a mutable three-state-variable (for extern crates,
4947 // view items, and regular items) ... except that because
4948 // of macros, I'd like to delay that entire check until later.
4950 match self.parse_item_or_view_item(attrs, macros_allowed) {
4951 IoviNone(attrs) => {
4952 return ParsedItemsAndViewItems {
4953 attrs_remaining: attrs,
4954 view_items: view_items,
4956 foreign_items: Vec::new()
4959 IoviViewItem(view_item) => {
4960 match view_item.node {
4961 ViewItemUse(..) => {
4962 // `extern crate` must precede `use`.
4963 extern_mod_allowed = false;
4965 ViewItemExternCrate(..) if !extern_mod_allowed => {
4966 self.span_err(view_item.span,
4967 "\"extern crate\" declarations are not allowed here");
4969 ViewItemExternCrate(..) => {}
4971 view_items.push(view_item);
4975 attrs = self.parse_outer_attributes();
4978 IoviForeignItem(_) => {
4982 attrs = self.parse_outer_attributes();
4985 // Next, parse items.
4987 match self.parse_item_or_view_item(attrs, macros_allowed) {
4988 IoviNone(returned_attrs) => {
4989 attrs = returned_attrs;
4992 IoviViewItem(view_item) => {
4993 attrs = self.parse_outer_attributes();
4994 self.span_err(view_item.span,
4995 "`use` and `extern crate` declarations must precede items");
4998 attrs = self.parse_outer_attributes();
5001 IoviForeignItem(_) => {
5007 ParsedItemsAndViewItems {
5008 attrs_remaining: attrs,
5009 view_items: view_items,
5011 foreign_items: Vec::new()
5015 // Parses a sequence of foreign items. Stops when it finds program
5016 // text that can't be parsed as an item
5017 fn parse_foreign_items(&mut self, first_item_attrs: Vec<Attribute> ,
5018 macros_allowed: bool)
5019 -> ParsedItemsAndViewItems {
5020 let mut attrs = first_item_attrs.append(self.parse_outer_attributes().as_slice());
5021 let mut foreign_items = Vec::new();
5023 match self.parse_foreign_item(attrs, macros_allowed) {
5024 IoviNone(returned_attrs) => {
5025 if self.token == token::RBRACE {
5026 attrs = returned_attrs;
5031 IoviViewItem(view_item) => {
5032 // I think this can't occur:
5033 self.span_err(view_item.span,
5034 "`use` and `extern crate` declarations must precede items");
5037 // FIXME #5668: this will occur for a macro invocation:
5038 self.span_fatal(item.span, "macros cannot expand to foreign items");
5040 IoviForeignItem(foreign_item) => {
5041 foreign_items.push(foreign_item);
5044 attrs = self.parse_outer_attributes();
5047 ParsedItemsAndViewItems {
5048 attrs_remaining: attrs,
5049 view_items: Vec::new(),
5051 foreign_items: foreign_items
5055 // Parses a source module as a crate. This is the main
5056 // entry point for the parser.
5057 pub fn parse_crate_mod(&mut self) -> Crate {
5058 let lo = self.span.lo;
5059 // parse the crate's inner attrs, maybe (oops) one
5060 // of the attrs of an item:
5061 let (inner, next) = self.parse_inner_attrs_and_next();
5062 let first_item_outer_attrs = next;
5063 // parse the items inside the crate:
5064 let m = self.parse_mod_items(token::EOF, first_item_outer_attrs);
5069 config: self.cfg.clone(),
5070 span: mk_sp(lo, self.span.lo)
5074 pub fn parse_optional_str(&mut self)
5075 -> Option<(InternedString, ast::StrStyle)> {
5076 let (s, style) = match self.token {
5077 token::LIT_STR(s) => (self.id_to_interned_str(s), ast::CookedStr),
5078 token::LIT_STR_RAW(s, n) => {
5079 (self.id_to_interned_str(s), ast::RawStr(n))
5087 pub fn parse_str(&mut self) -> (InternedString, StrStyle) {
5088 match self.parse_optional_str() {
5090 _ => self.fatal("expected string literal")