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::{StaticRegionTyParamBound, OtherRegionTyParamBound, 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, 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, LocalLet};
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, PatBox, 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, TyParen, TyPath, TyPtr, TyRptr};
55 use ast::{TyTup, TyU32, TyUnboxedFn, TyUniq, TyVec, UnUniq};
56 use ast::{UnboxedFnTy, UnboxedFnTyParamBound, UnnamedField, UnsafeBlock};
57 use ast::{UnsafeFn, ViewItem, 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 std::collections::HashSet;
80 use std::mem::replace;
82 use std::gc::{Gc, GC};
84 #[allow(non_camel_case_types)]
85 #[deriving(PartialEq)]
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.
97 #[deriving(PartialEq)]
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(Gc<ForeignItem>),
125 IoviViewItem(ViewItem)
129 // Possibly accept an `INTERPOLATED` expression (a pre-parsed expression
130 // dropped into the token stream, which happens while parsing the
131 // result of macro expansion)
132 /* Placement of these is not as complex as I feared it would be.
133 The important thing is to make sure that lookahead doesn't balk
134 at INTERPOLATED tokens */
135 macro_rules! maybe_whole_expr (
138 let found = match $p.token {
139 INTERPOLATED(token::NtExpr(e)) => {
142 INTERPOLATED(token::NtPath(_)) => {
143 // FIXME: The following avoids an issue with lexical borrowck scopes,
144 // but the clone is unfortunate.
145 let pt = match $p.token {
146 INTERPOLATED(token::NtPath(ref pt)) => (**pt).clone(),
150 Some($p.mk_expr(span.lo, span.hi, ExprPath(pt)))
152 INTERPOLATED(token::NtBlock(b)) => {
154 Some($p.mk_expr(span.lo, span.hi, ExprBlock(b)))
169 // As above, but for things other than expressions
170 macro_rules! maybe_whole (
171 ($p:expr, $constructor:ident) => (
173 let found = match ($p).token {
174 INTERPOLATED(token::$constructor(_)) => {
175 Some(($p).bump_and_get())
180 Some(INTERPOLATED(token::$constructor(x))) => {
187 (no_clone $p:expr, $constructor:ident) => (
189 let found = match ($p).token {
190 INTERPOLATED(token::$constructor(_)) => {
191 Some(($p).bump_and_get())
196 Some(INTERPOLATED(token::$constructor(x))) => {
203 (deref $p:expr, $constructor:ident) => (
205 let found = match ($p).token {
206 INTERPOLATED(token::$constructor(_)) => {
207 Some(($p).bump_and_get())
212 Some(INTERPOLATED(token::$constructor(x))) => {
219 (Some $p:expr, $constructor:ident) => (
221 let found = match ($p).token {
222 INTERPOLATED(token::$constructor(_)) => {
223 Some(($p).bump_and_get())
228 Some(INTERPOLATED(token::$constructor(x))) => {
229 return Some(x.clone()),
235 (iovi $p:expr, $constructor:ident) => (
237 let found = match ($p).token {
238 INTERPOLATED(token::$constructor(_)) => {
239 Some(($p).bump_and_get())
244 Some(INTERPOLATED(token::$constructor(x))) => {
245 return IoviItem(x.clone())
251 (pair_empty $p:expr, $constructor:ident) => (
253 let found = match ($p).token {
254 INTERPOLATED(token::$constructor(_)) => {
255 Some(($p).bump_and_get())
260 Some(INTERPOLATED(token::$constructor(x))) => {
261 return (Vec::new(), x)
270 fn maybe_append(lhs: Vec<Attribute> , rhs: Option<Vec<Attribute> >)
274 Some(ref attrs) => lhs.append(attrs.as_slice())
279 struct ParsedItemsAndViewItems {
280 attrs_remaining: Vec<Attribute>,
281 view_items: Vec<ViewItem>,
282 items: Vec<Gc<Item>>,
283 foreign_items: Vec<Gc<ForeignItem>>
286 /* ident is handled by common.rs */
288 pub struct Parser<'a> {
289 pub sess: &'a ParseSess,
290 // the current token:
291 pub token: token::Token,
292 // the span of the current token:
294 // the span of the prior token:
296 pub cfg: CrateConfig,
297 // the previous token or None (only stashed sometimes).
298 pub last_token: Option<Box<token::Token>>,
299 pub buffer: [TokenAndSpan, ..4],
300 pub buffer_start: int,
302 pub tokens_consumed: uint,
303 pub restriction: restriction,
304 pub quote_depth: uint, // not (yet) related to the quasiquoter
305 pub reader: Box<Reader>,
306 pub interner: Rc<token::IdentInterner>,
307 /// The set of seen errors about obsolete syntax. Used to suppress
308 /// extra detail when the same error is seen twice
309 pub obsolete_set: HashSet<ObsoleteSyntax>,
310 /// Used to determine the path to externally loaded source files
311 pub mod_path_stack: Vec<InternedString>,
312 /// Stack of spans of open delimiters. Used for error message.
313 pub open_braces: Vec<Span>,
314 /// Flag if this parser "owns" the directory that it is currently parsing
315 /// in. This will affect how nested files are looked up.
316 pub owns_directory: bool,
317 /// Name of the root module this parser originated from. If `None`, then the
318 /// name is not known. This does not change while the parser is descending
319 /// into modules, and sub-parsers have new values for this name.
320 pub root_module_name: Option<String>,
323 fn is_plain_ident_or_underscore(t: &token::Token) -> bool {
324 is_plain_ident(t) || *t == token::UNDERSCORE
327 impl<'a> Parser<'a> {
328 pub fn new(sess: &'a ParseSess, cfg: ast::CrateConfig,
329 mut rdr: Box<Reader>) -> Parser<'a> {
330 let tok0 = rdr.next_token();
332 let placeholder = TokenAndSpan {
333 tok: token::UNDERSCORE,
339 interner: token::get_ident_interner(),
355 restriction: UNRESTRICTED,
357 obsolete_set: HashSet::new(),
358 mod_path_stack: Vec::new(),
359 open_braces: Vec::new(),
360 owns_directory: true,
361 root_module_name: None,
364 // convert a token to a string using self's reader
365 pub fn token_to_str(token: &token::Token) -> String {
369 // convert the current token to a string using self's reader
370 pub fn this_token_to_str(&mut self) -> String {
371 Parser::token_to_str(&self.token)
374 pub fn unexpected_last(&mut self, t: &token::Token) -> ! {
375 let token_str = Parser::token_to_str(t);
376 let last_span = self.last_span;
377 self.span_fatal(last_span, format!("unexpected token: `{}`",
378 token_str).as_slice());
381 pub fn unexpected(&mut self) -> ! {
382 let this_token = self.this_token_to_str();
383 self.fatal(format!("unexpected token: `{}`", this_token).as_slice());
386 // expect and consume the token t. Signal an error if
387 // the next token is not t.
388 pub fn expect(&mut self, t: &token::Token) {
389 if self.token == *t {
392 let token_str = Parser::token_to_str(t);
393 let this_token_str = self.this_token_to_str();
394 self.fatal(format!("expected `{}` but found `{}`",
396 this_token_str).as_slice())
400 // Expect next token to be edible or inedible token. If edible,
401 // then consume it; if inedible, then return without consuming
402 // anything. Signal a fatal error if next token is unexpected.
403 pub fn expect_one_of(&mut self,
404 edible: &[token::Token],
405 inedible: &[token::Token]) {
406 fn tokens_to_str(tokens: &[token::Token]) -> String {
407 let mut i = tokens.iter();
408 // This might be a sign we need a connect method on Iterator.
410 .map_or("".to_string(), |t| Parser::token_to_str(t));
414 b.push_str(Parser::token_to_str(a).as_slice());
418 if edible.contains(&self.token) {
420 } else if inedible.contains(&self.token) {
421 // leave it in the input
423 let expected = edible.iter().map(|x| (*x).clone()).collect::<Vec<_>>().append(inedible);
424 let expect = tokens_to_str(expected.as_slice());
425 let actual = self.this_token_to_str();
427 (if expected.len() != 1 {
428 (format!("expected one of `{}` but found `{}`",
432 (format!("expected `{}` but found `{}`",
440 // Check for erroneous `ident { }`; if matches, signal error and
441 // recover (without consuming any expected input token). Returns
442 // true if and only if input was consumed for recovery.
443 pub fn check_for_erroneous_unit_struct_expecting(&mut self, expected: &[token::Token]) -> bool {
444 if self.token == token::LBRACE
445 && expected.iter().all(|t| *t != token::LBRACE)
446 && self.look_ahead(1, |t| *t == token::RBRACE) {
447 // matched; signal non-fatal error and recover.
448 let span = self.span;
450 "unit-like struct construction is written with no trailing `{ }`");
451 self.eat(&token::LBRACE);
452 self.eat(&token::RBRACE);
459 // Commit to parsing a complete expression `e` expected to be
460 // followed by some token from the set edible + inedible. Recover
461 // from anticipated input errors, discarding erroneous characters.
462 pub fn commit_expr(&mut self, e: Gc<Expr>, edible: &[token::Token],
463 inedible: &[token::Token]) {
464 debug!("commit_expr {:?}", e);
467 // might be unit-struct construction; check for recoverableinput error.
468 let expected = edible.iter().map(|x| (*x).clone()).collect::<Vec<_>>()
470 self.check_for_erroneous_unit_struct_expecting(
471 expected.as_slice());
475 self.expect_one_of(edible, inedible)
478 pub fn commit_expr_expecting(&mut self, e: Gc<Expr>, edible: token::Token) {
479 self.commit_expr(e, &[edible], &[])
482 // Commit to parsing a complete statement `s`, which expects to be
483 // followed by some token from the set edible + inedible. Check
484 // for recoverable input errors, discarding erroneous characters.
485 pub fn commit_stmt(&mut self, s: Gc<Stmt>, edible: &[token::Token],
486 inedible: &[token::Token]) {
487 debug!("commit_stmt {:?}", s);
488 let _s = s; // unused, but future checks might want to inspect `s`.
489 if self.last_token.as_ref().map_or(false, |t| is_ident_or_path(*t)) {
490 let expected = edible.iter().map(|x| (*x).clone()).collect::<Vec<_>>()
491 .append(inedible.as_slice());
492 self.check_for_erroneous_unit_struct_expecting(
493 expected.as_slice());
495 self.expect_one_of(edible, inedible)
498 pub fn commit_stmt_expecting(&mut self, s: Gc<Stmt>, edible: token::Token) {
499 self.commit_stmt(s, &[edible], &[])
502 pub fn parse_ident(&mut self) -> ast::Ident {
503 self.check_strict_keywords();
504 self.check_reserved_keywords();
506 token::IDENT(i, _) => {
510 token::INTERPOLATED(token::NtIdent(..)) => {
511 self.bug("ident interpolation not converted to real token");
514 let token_str = self.this_token_to_str();
515 self.fatal((format!("expected ident, found `{}`",
516 token_str)).as_slice())
521 pub fn parse_path_list_ident(&mut self) -> ast::PathListIdent {
522 let lo = self.span.lo;
523 let ident = self.parse_ident();
524 let hi = self.last_span.hi;
525 spanned(lo, hi, ast::PathListIdent_ { name: ident,
526 id: ast::DUMMY_NODE_ID })
529 // consume token 'tok' if it exists. Returns true if the given
530 // token was present, false otherwise.
531 pub fn eat(&mut self, tok: &token::Token) -> bool {
532 let is_present = self.token == *tok;
533 if is_present { self.bump() }
537 pub fn is_keyword(&mut self, kw: keywords::Keyword) -> bool {
538 token::is_keyword(kw, &self.token)
541 // if the next token is the given keyword, eat it and return
542 // true. Otherwise, return false.
543 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
544 let is_kw = match self.token {
545 token::IDENT(sid, false) => kw.to_ident().name == sid.name,
548 if is_kw { self.bump() }
552 // if the given word is not a keyword, signal an error.
553 // if the next token is not the given word, signal an error.
554 // otherwise, eat it.
555 pub fn expect_keyword(&mut self, kw: keywords::Keyword) {
556 if !self.eat_keyword(kw) {
557 let id_interned_str = token::get_ident(kw.to_ident());
558 let token_str = self.this_token_to_str();
559 self.fatal(format!("expected `{}`, found `{}`",
560 id_interned_str, token_str).as_slice())
564 // signal an error if the given string is a strict keyword
565 pub fn check_strict_keywords(&mut self) {
566 if token::is_strict_keyword(&self.token) {
567 let token_str = self.this_token_to_str();
568 let span = self.span;
570 format!("found `{}` in ident position",
571 token_str).as_slice());
575 // signal an error if the current token is a reserved keyword
576 pub fn check_reserved_keywords(&mut self) {
577 if token::is_reserved_keyword(&self.token) {
578 let token_str = self.this_token_to_str();
579 self.fatal(format!("`{}` is a reserved keyword",
580 token_str).as_slice())
584 // Expect and consume an `&`. If `&&` is seen, replace it with a single
585 // `&` and continue. If an `&` is not seen, signal an error.
586 fn expect_and(&mut self) {
588 token::BINOP(token::AND) => self.bump(),
590 let span = self.span;
591 let lo = span.lo + BytePos(1);
592 self.replace_token(token::BINOP(token::AND), lo, span.hi)
595 let token_str = self.this_token_to_str();
597 Parser::token_to_str(&token::BINOP(token::AND));
598 self.fatal(format!("expected `{}`, found `{}`",
600 token_str).as_slice())
605 // Expect and consume a `|`. If `||` is seen, replace it with a single
606 // `|` and continue. If a `|` is not seen, signal an error.
607 fn expect_or(&mut self) {
609 token::BINOP(token::OR) => self.bump(),
611 let span = self.span;
612 let lo = span.lo + BytePos(1);
613 self.replace_token(token::BINOP(token::OR), lo, span.hi)
616 let found_token = self.this_token_to_str();
618 Parser::token_to_str(&token::BINOP(token::OR));
619 self.fatal(format!("expected `{}`, found `{}`",
621 found_token).as_slice())
626 // Attempt to consume a `<`. If `<<` is seen, replace it with a single
627 // `<` and continue. If a `<` is not seen, return false.
629 // This is meant to be used when parsing generics on a path to get the
630 // starting token. The `force` parameter is used to forcefully break up a
631 // `<<` token. If `force` is false, then `<<` is only broken when a lifetime
632 // shows up next. For example, consider the expression:
634 // foo as bar << test
636 // The parser needs to know if `bar <<` is the start of a generic path or if
637 // it's a left-shift token. If `test` were a lifetime, then it's impossible
638 // for the token to be a left-shift, but if it's not a lifetime, then it's
639 // considered a left-shift.
641 // The reason for this is that the only current ambiguity with `<<` is when
642 // parsing closure types:
645 // impl Foo<<'a> ||>() { ... }
646 fn eat_lt(&mut self, force: bool) -> bool {
648 token::LT => { self.bump(); true }
649 token::BINOP(token::SHL) => {
650 let next_lifetime = self.look_ahead(1, |t| match *t {
651 token::LIFETIME(..) => true,
654 if force || next_lifetime {
655 let span = self.span;
656 let lo = span.lo + BytePos(1);
657 self.replace_token(token::LT, lo, span.hi);
667 fn expect_lt(&mut self) {
668 if !self.eat_lt(true) {
669 let found_token = self.this_token_to_str();
670 let token_str = Parser::token_to_str(&token::LT);
671 self.fatal(format!("expected `{}`, found `{}`",
673 found_token).as_slice())
677 // Parse a sequence bracketed by `|` and `|`, stopping before the `|`.
678 fn parse_seq_to_before_or<T>(
681 f: |&mut Parser| -> T)
683 let mut first = true;
684 let mut vector = Vec::new();
685 while self.token != token::BINOP(token::OR) &&
686 self.token != token::OROR {
698 // expect and consume a GT. if a >> is seen, replace it
699 // with a single > and continue. If a GT is not seen,
701 pub fn expect_gt(&mut self) {
703 token::GT => self.bump(),
704 token::BINOP(token::SHR) => {
705 let span = self.span;
706 let lo = span.lo + BytePos(1);
707 self.replace_token(token::GT, lo, span.hi)
710 let gt_str = Parser::token_to_str(&token::GT);
711 let this_token_str = self.this_token_to_str();
712 self.fatal(format!("expected `{}`, found `{}`",
714 this_token_str).as_slice())
719 // parse a sequence bracketed by '<' and '>', stopping
721 pub fn parse_seq_to_before_gt<T>(
723 sep: Option<token::Token>,
724 f: |&mut Parser| -> T)
726 let mut first = true;
727 let mut v = Vec::new();
728 while self.token != token::GT
729 && self.token != token::BINOP(token::SHR) {
732 if first { first = false; }
733 else { self.expect(t); }
739 return OwnedSlice::from_vec(v);
742 pub fn parse_seq_to_gt<T>(
744 sep: Option<token::Token>,
745 f: |&mut Parser| -> T)
747 let v = self.parse_seq_to_before_gt(sep, f);
752 // parse a sequence, including the closing delimiter. The function
753 // f must consume tokens until reaching the next separator or
755 pub fn parse_seq_to_end<T>(
759 f: |&mut Parser| -> T)
761 let val = self.parse_seq_to_before_end(ket, sep, f);
766 // parse a sequence, not including the closing delimiter. The function
767 // f must consume tokens until reaching the next separator or
769 pub fn parse_seq_to_before_end<T>(
773 f: |&mut Parser| -> T)
775 let mut first: bool = true;
777 while self.token != *ket {
780 if first { first = false; }
781 else { self.expect(t); }
785 if sep.trailing_sep_allowed && self.token == *ket { break; }
791 // parse a sequence, including the closing delimiter. The function
792 // f must consume tokens until reaching the next separator or
794 pub fn parse_unspanned_seq<T>(
799 f: |&mut Parser| -> T)
802 let result = self.parse_seq_to_before_end(ket, sep, f);
807 // parse a sequence parameter of enum variant. For consistency purposes,
808 // these should not be empty.
809 pub fn parse_enum_variant_seq<T>(
814 f: |&mut Parser| -> T)
816 let result = self.parse_unspanned_seq(bra, ket, sep, f);
817 if result.is_empty() {
818 let last_span = self.last_span;
819 self.span_err(last_span,
820 "nullary enum variants are written with no trailing `( )`");
825 // NB: Do not use this function unless you actually plan to place the
826 // spanned list in the AST.
832 f: |&mut Parser| -> T)
833 -> Spanned<Vec<T> > {
834 let lo = self.span.lo;
836 let result = self.parse_seq_to_before_end(ket, sep, f);
837 let hi = self.span.hi;
839 spanned(lo, hi, result)
842 // advance the parser by one token
843 pub fn bump(&mut self) {
844 self.last_span = self.span;
845 // Stash token for error recovery (sometimes; clone is not necessarily cheap).
846 self.last_token = if is_ident_or_path(&self.token) {
847 Some(box self.token.clone())
851 let next = if self.buffer_start == self.buffer_end {
852 self.reader.next_token()
854 // Avoid token copies with `replace`.
855 let buffer_start = self.buffer_start as uint;
856 let next_index = (buffer_start + 1) & 3 as uint;
857 self.buffer_start = next_index as int;
859 let placeholder = TokenAndSpan {
860 tok: token::UNDERSCORE,
863 replace(&mut self.buffer[buffer_start], placeholder)
866 self.token = next.tok;
867 self.tokens_consumed += 1u;
870 // Advance the parser by one token and return the bumped token.
871 pub fn bump_and_get(&mut self) -> token::Token {
872 let old_token = replace(&mut self.token, token::UNDERSCORE);
877 // EFFECT: replace the current token and span with the given one
878 pub fn replace_token(&mut self,
882 self.last_span = mk_sp(self.span.lo, lo);
884 self.span = mk_sp(lo, hi);
886 pub fn buffer_length(&mut self) -> int {
887 if self.buffer_start <= self.buffer_end {
888 return self.buffer_end - self.buffer_start;
890 return (4 - self.buffer_start) + self.buffer_end;
892 pub fn look_ahead<R>(&mut self, distance: uint, f: |&token::Token| -> R)
894 let dist = distance as int;
895 while self.buffer_length() < dist {
896 self.buffer[self.buffer_end as uint] = self.reader.next_token();
897 self.buffer_end = (self.buffer_end + 1) & 3;
899 f(&self.buffer[((self.buffer_start + dist - 1) & 3) as uint].tok)
901 pub fn fatal(&mut self, m: &str) -> ! {
902 self.sess.span_diagnostic.span_fatal(self.span, m)
904 pub fn span_fatal(&mut self, sp: Span, m: &str) -> ! {
905 self.sess.span_diagnostic.span_fatal(sp, m)
907 pub fn span_note(&mut self, sp: Span, m: &str) {
908 self.sess.span_diagnostic.span_note(sp, m)
910 pub fn bug(&mut self, m: &str) -> ! {
911 self.sess.span_diagnostic.span_bug(self.span, m)
913 pub fn warn(&mut self, m: &str) {
914 self.sess.span_diagnostic.span_warn(self.span, m)
916 pub fn span_warn(&mut self, sp: Span, m: &str) {
917 self.sess.span_diagnostic.span_warn(sp, m)
919 pub fn span_err(&mut self, sp: Span, m: &str) {
920 self.sess.span_diagnostic.span_err(sp, m)
922 pub fn abort_if_errors(&mut self) {
923 self.sess.span_diagnostic.handler().abort_if_errors();
926 pub fn id_to_interned_str(&mut self, id: Ident) -> InternedString {
930 // Is the current token one of the keywords that signals a bare function
932 pub fn token_is_bare_fn_keyword(&mut self) -> bool {
933 if token::is_keyword(keywords::Fn, &self.token) {
937 if token::is_keyword(keywords::Unsafe, &self.token) ||
938 token::is_keyword(keywords::Once, &self.token) {
939 return self.look_ahead(1, |t| token::is_keyword(keywords::Fn, t))
945 // Is the current token one of the keywords that signals a closure type?
946 pub fn token_is_closure_keyword(&mut self) -> bool {
947 token::is_keyword(keywords::Unsafe, &self.token) ||
948 token::is_keyword(keywords::Once, &self.token)
951 // Is the current token one of the keywords that signals an old-style
952 // closure type (with explicit sigil)?
953 pub fn token_is_old_style_closure_keyword(&mut self) -> bool {
954 token::is_keyword(keywords::Unsafe, &self.token) ||
955 token::is_keyword(keywords::Once, &self.token) ||
956 token::is_keyword(keywords::Fn, &self.token)
959 pub fn token_is_lifetime(tok: &token::Token) -> bool {
961 token::LIFETIME(..) => true,
966 pub fn get_lifetime(&mut self) -> ast::Ident {
968 token::LIFETIME(ref ident) => *ident,
969 _ => self.bug("not a lifetime"),
973 // parse a TyBareFn type:
974 pub fn parse_ty_bare_fn(&mut self) -> Ty_ {
977 [unsafe] [extern "ABI"] fn <'lt> (S) -> T
978 ^~~~^ ^~~~^ ^~~~^ ^~^ ^
987 let fn_style = self.parse_unsafety();
988 let abi = if self.eat_keyword(keywords::Extern) {
989 self.parse_opt_abi().unwrap_or(abi::C)
994 self.expect_keyword(keywords::Fn);
995 let (decl, lifetimes) = self.parse_ty_fn_decl(true);
996 return TyBareFn(box(GC) BareFnTy {
999 lifetimes: lifetimes,
1004 // Parses a procedure type (`proc`). The initial `proc` keyword must
1005 // already have been parsed.
1006 pub fn parse_proc_type(&mut self) -> Ty_ {
1009 proc <'lt> (S) [:Bounds] -> T
1010 ^~~^ ^~~~^ ^ ^~~~~~~~^ ^
1020 let lifetimes = if self.eat(&token::LT) {
1021 let lifetimes = self.parse_lifetimes();
1028 let (inputs, variadic) = self.parse_fn_args(false, false);
1030 if self.eat(&token::COLON) {
1031 let (_, bounds) = self.parse_ty_param_bounds(false);
1037 let (ret_style, ret_ty) = self.parse_ret_ty();
1038 let decl = P(FnDecl {
1044 TyProc(box(GC) ClosureTy {
1049 lifetimes: lifetimes,
1053 // parse a TyClosure type
1054 pub fn parse_ty_closure(&mut self) -> Ty_ {
1057 [unsafe] [once] <'lt> |S| [:Bounds] -> T
1058 ^~~~~~~^ ^~~~~^ ^~~~^ ^ ^~~~~~~~^ ^
1060 | | | | | Return type
1061 | | | | Closure bounds
1062 | | | Argument types
1064 | Once-ness (a.k.a., affine)
1069 let fn_style = self.parse_unsafety();
1070 let onceness = if self.eat_keyword(keywords::Once) {Once} else {Many};
1072 let lifetimes = if self.eat(&token::LT) {
1073 let lifetimes = self.parse_lifetimes();
1081 let (is_unboxed, inputs) = if self.eat(&token::OROR) {
1086 let is_unboxed = self.token == token::BINOP(token::AND) &&
1087 self.look_ahead(1, |t| {
1088 token::is_keyword(keywords::Mut, t)
1090 self.look_ahead(2, |t| *t == token::COLON);
1097 let inputs = self.parse_seq_to_before_or(
1099 |p| p.parse_arg_general(false));
1101 (is_unboxed, inputs)
1104 let (region, bounds) = {
1105 if self.eat(&token::COLON) {
1106 let (region, bounds) = self.parse_ty_param_bounds(true);
1107 (region, Some(bounds))
1113 let (return_style, output) = self.parse_ret_ty();
1114 let decl = P(FnDecl {
1122 TyUnboxedFn(box(GC) UnboxedFnTy {
1126 TyClosure(box(GC) ClosureTy {
1131 lifetimes: lifetimes,
1136 pub fn parse_unsafety(&mut self) -> FnStyle {
1137 if self.eat_keyword(keywords::Unsafe) {
1144 // parse a function type (following the 'fn')
1145 pub fn parse_ty_fn_decl(&mut self, allow_variadic: bool)
1146 -> (P<FnDecl>, Vec<ast::Lifetime>) {
1157 let lifetimes = if self.eat(&token::LT) {
1158 let lifetimes = self.parse_lifetimes();
1165 let (inputs, variadic) = self.parse_fn_args(false, allow_variadic);
1166 let (ret_style, ret_ty) = self.parse_ret_ty();
1167 let decl = P(FnDecl {
1176 // parse the methods in a trait declaration
1177 pub fn parse_trait_methods(&mut self) -> Vec<TraitMethod> {
1178 self.parse_unspanned_seq(
1183 let attrs = p.parse_outer_attributes();
1186 // NB: at the moment, trait methods are public by default; this
1188 let vis = p.parse_visibility();
1189 let style = p.parse_fn_style();
1190 let ident = p.parse_ident();
1192 let generics = p.parse_generics();
1194 let (explicit_self, d) = p.parse_fn_decl_with_self(|p| {
1195 // This is somewhat dubious; We don't want to allow argument
1196 // names to be left off if there is a definition...
1197 p.parse_arg_general(false)
1200 let hi = p.last_span.hi;
1204 debug!("parse_trait_methods(): parsing required method");
1205 Required(TypeMethod {
1211 explicit_self: explicit_self,
1212 id: ast::DUMMY_NODE_ID,
1213 span: mk_sp(lo, hi),
1218 debug!("parse_trait_methods(): parsing provided method");
1219 let (inner_attrs, body) =
1220 p.parse_inner_attrs_and_block();
1221 let attrs = attrs.append(inner_attrs.as_slice());
1222 Provided(box(GC) ast::Method {
1226 explicit_self: explicit_self,
1230 id: ast::DUMMY_NODE_ID,
1231 span: mk_sp(lo, hi),
1237 let token_str = p.this_token_to_str();
1238 p.fatal((format!("expected `;` or `{{` but found `{}`",
1239 token_str)).as_slice())
1245 // parse a possibly mutable type
1246 pub fn parse_mt(&mut self) -> MutTy {
1247 let mutbl = self.parse_mutability();
1248 let t = self.parse_ty(true);
1249 MutTy { ty: t, mutbl: mutbl }
1252 // parse [mut/const/imm] ID : TY
1253 // now used only by obsolete record syntax parser...
1254 pub fn parse_ty_field(&mut self) -> TypeField {
1255 let lo = self.span.lo;
1256 let mutbl = self.parse_mutability();
1257 let id = self.parse_ident();
1258 self.expect(&token::COLON);
1259 let ty = self.parse_ty(true);
1260 let hi = ty.span.hi;
1263 mt: MutTy { ty: ty, mutbl: mutbl },
1264 span: mk_sp(lo, hi),
1268 // parse optional return type [ -> TY ] in function decl
1269 pub fn parse_ret_ty(&mut self) -> (RetStyle, P<Ty>) {
1270 return if self.eat(&token::RARROW) {
1271 let lo = self.span.lo;
1272 if self.eat(&token::NOT) {
1276 id: ast::DUMMY_NODE_ID,
1278 span: mk_sp(lo, self.last_span.hi)
1282 (Return, self.parse_ty(true))
1285 let pos = self.span.lo;
1289 id: ast::DUMMY_NODE_ID,
1291 span: mk_sp(pos, pos),
1299 /// The second parameter specifies whether the `+` binary operator is
1300 /// allowed in the type grammar.
1301 pub fn parse_ty(&mut self, plus_allowed: bool) -> P<Ty> {
1302 maybe_whole!(no_clone self, NtTy);
1304 let lo = self.span.lo;
1306 let t = if self.token == token::LPAREN {
1308 if self.token == token::RPAREN {
1312 // (t) is a parenthesized ty
1313 // (t,) is the type of a tuple with only one field,
1315 let mut ts = vec!(self.parse_ty(true));
1316 let mut one_tuple = false;
1317 while self.token == token::COMMA {
1319 if self.token != token::RPAREN {
1320 ts.push(self.parse_ty(true));
1327 if ts.len() == 1 && !one_tuple {
1328 self.expect(&token::RPAREN);
1332 self.expect(&token::RPAREN);
1336 } else if self.token == token::AT {
1339 let span = self.last_span;
1340 self.obsolete(span, ObsoleteManagedType);
1341 TyBox(self.parse_ty(plus_allowed))
1342 } else if self.token == token::TILDE {
1345 let last_span = self.last_span;
1348 self.obsolete(last_span, ObsoleteOwnedVector),
1349 _ => self.obsolete(last_span, ObsoleteOwnedType),
1351 TyUniq(self.parse_ty(true))
1352 } else if self.token == token::BINOP(token::STAR) {
1353 // STAR POINTER (bare pointer?)
1355 TyPtr(self.parse_ptr())
1356 } else if self.token == token::LBRACKET {
1358 self.expect(&token::LBRACKET);
1359 let t = self.parse_ty(true);
1361 // Parse the `, ..e` in `[ int, ..e ]`
1362 // where `e` is a const expression
1363 let t = match self.maybe_parse_fixed_vstore() {
1365 Some(suffix) => TyFixedLengthVec(t, suffix)
1367 self.expect(&token::RBRACKET);
1369 } else if self.token == token::BINOP(token::AND) ||
1370 self.token == token::ANDAND {
1373 self.parse_borrowed_pointee()
1374 } else if self.is_keyword(keywords::Extern) ||
1375 self.is_keyword(keywords::Unsafe) ||
1376 self.token_is_bare_fn_keyword() {
1378 self.parse_ty_bare_fn()
1379 } else if self.token_is_closure_keyword() ||
1380 self.token == token::BINOP(token::OR) ||
1381 self.token == token::OROR ||
1382 self.token == token::LT {
1385 // FIXME(pcwalton): Eventually `token::LT` will not unambiguously
1386 // introduce a closure, once procs can have lifetime bounds. We
1387 // will need to refactor the grammar a little bit at that point.
1389 self.parse_ty_closure()
1390 } else if self.eat_keyword(keywords::Typeof) {
1392 // In order to not be ambiguous, the type must be surrounded by parens.
1393 self.expect(&token::LPAREN);
1394 let e = self.parse_expr();
1395 self.expect(&token::RPAREN);
1397 } else if self.eat_keyword(keywords::Proc) {
1398 self.parse_proc_type()
1399 } else if self.token == token::MOD_SEP
1400 || is_ident_or_path(&self.token) {
1402 let mode = if plus_allowed {
1403 LifetimeAndTypesAndBounds
1405 LifetimeAndTypesWithoutColons
1410 } = self.parse_path(mode);
1411 TyPath(path, bounds, ast::DUMMY_NODE_ID)
1412 } else if self.eat(&token::UNDERSCORE) {
1413 // TYPE TO BE INFERRED
1416 let msg = format!("expected type, found token {:?}", self.token);
1417 self.fatal(msg.as_slice());
1420 let sp = mk_sp(lo, self.last_span.hi);
1421 P(Ty {id: ast::DUMMY_NODE_ID, node: t, span: sp})
1424 pub fn parse_borrowed_pointee(&mut self) -> Ty_ {
1425 // look for `&'lt` or `&'foo ` and interpret `foo` as the region name:
1426 let opt_lifetime = self.parse_opt_lifetime();
1428 let mt = self.parse_mt();
1429 return TyRptr(opt_lifetime, mt);
1432 pub fn parse_ptr(&mut self) -> MutTy {
1433 let mutbl = if self.eat_keyword(keywords::Mut) {
1435 } else if self.eat_keyword(keywords::Const) {
1438 // NOTE: after a stage0 snap this should turn into a span_err.
1441 let t = self.parse_ty(true);
1442 MutTy { ty: t, mutbl: mutbl }
1445 pub fn is_named_argument(&mut self) -> bool {
1446 let offset = match self.token {
1447 token::BINOP(token::AND) => 1,
1449 _ if token::is_keyword(keywords::Mut, &self.token) => 1,
1453 debug!("parser is_named_argument offset:{}", offset);
1456 is_plain_ident_or_underscore(&self.token)
1457 && self.look_ahead(1, |t| *t == token::COLON)
1459 self.look_ahead(offset, |t| is_plain_ident_or_underscore(t))
1460 && self.look_ahead(offset + 1, |t| *t == token::COLON)
1464 // This version of parse arg doesn't necessarily require
1465 // identifier names.
1466 pub fn parse_arg_general(&mut self, require_name: bool) -> Arg {
1467 let pat = if require_name || self.is_named_argument() {
1468 debug!("parse_arg_general parse_pat (require_name:{:?})",
1470 let pat = self.parse_pat();
1472 self.expect(&token::COLON);
1475 debug!("parse_arg_general ident_to_pat");
1476 ast_util::ident_to_pat(ast::DUMMY_NODE_ID,
1478 special_idents::invalid)
1481 let t = self.parse_ty(true);
1486 id: ast::DUMMY_NODE_ID,
1490 // parse a single function argument
1491 pub fn parse_arg(&mut self) -> Arg {
1492 self.parse_arg_general(true)
1495 // parse an argument in a lambda header e.g. |arg, arg|
1496 pub fn parse_fn_block_arg(&mut self) -> Arg {
1497 let pat = self.parse_pat();
1498 let t = if self.eat(&token::COLON) {
1502 id: ast::DUMMY_NODE_ID,
1504 span: mk_sp(self.span.lo, self.span.hi),
1510 id: ast::DUMMY_NODE_ID
1514 pub fn maybe_parse_fixed_vstore(&mut self) -> Option<Gc<ast::Expr>> {
1515 if self.token == token::COMMA &&
1516 self.look_ahead(1, |t| *t == token::DOTDOT) {
1519 Some(self.parse_expr())
1525 // matches token_lit = LIT_INT | ...
1526 pub fn lit_from_token(&mut self, tok: &token::Token) -> Lit_ {
1528 token::LIT_CHAR(i) => LitChar(i),
1529 token::LIT_INT(i, it) => LitInt(i, it),
1530 token::LIT_UINT(u, ut) => LitUint(u, ut),
1531 token::LIT_INT_UNSUFFIXED(i) => LitIntUnsuffixed(i),
1532 token::LIT_FLOAT(s, ft) => {
1533 LitFloat(self.id_to_interned_str(s), ft)
1535 token::LIT_FLOAT_UNSUFFIXED(s) => {
1536 LitFloatUnsuffixed(self.id_to_interned_str(s))
1538 token::LIT_STR(s) => {
1539 LitStr(self.id_to_interned_str(s), ast::CookedStr)
1541 token::LIT_STR_RAW(s, n) => {
1542 LitStr(self.id_to_interned_str(s), ast::RawStr(n))
1544 token::LPAREN => { self.expect(&token::RPAREN); LitNil },
1545 _ => { self.unexpected_last(tok); }
1549 // matches lit = true | false | token_lit
1550 pub fn parse_lit(&mut self) -> Lit {
1551 let lo = self.span.lo;
1552 let lit = if self.eat_keyword(keywords::True) {
1554 } else if self.eat_keyword(keywords::False) {
1557 let token = self.bump_and_get();
1558 let lit = self.lit_from_token(&token);
1561 codemap::Spanned { node: lit, span: mk_sp(lo, self.last_span.hi) }
1564 // matches '-' lit | lit
1565 pub fn parse_literal_maybe_minus(&mut self) -> Gc<Expr> {
1566 let minus_lo = self.span.lo;
1567 let minus_present = self.eat(&token::BINOP(token::MINUS));
1569 let lo = self.span.lo;
1570 let literal = box(GC) self.parse_lit();
1571 let hi = self.span.hi;
1572 let expr = self.mk_expr(lo, hi, ExprLit(literal));
1575 let minus_hi = self.span.hi;
1576 let unary = self.mk_unary(UnNeg, expr);
1577 self.mk_expr(minus_lo, minus_hi, unary)
1583 /// Parses a path and optional type parameter bounds, depending on the
1584 /// mode. The `mode` parameter determines whether lifetimes, types, and/or
1585 /// bounds are permitted and whether `::` must precede type parameter
1587 pub fn parse_path(&mut self, mode: PathParsingMode) -> PathAndBounds {
1588 // Check for a whole path...
1589 let found = match self.token {
1590 INTERPOLATED(token::NtPath(_)) => Some(self.bump_and_get()),
1594 Some(INTERPOLATED(token::NtPath(box path))) => {
1595 return PathAndBounds {
1603 let lo = self.span.lo;
1604 let is_global = self.eat(&token::MOD_SEP);
1606 // Parse any number of segments and bound sets. A segment is an
1607 // identifier followed by an optional lifetime and a set of types.
1608 // A bound set is a set of type parameter bounds.
1609 let mut segments = Vec::new();
1611 // First, parse an identifier.
1612 let identifier = self.parse_ident();
1614 // Parse the '::' before type parameters if it's required. If
1615 // it is required and wasn't present, then we're done.
1616 if mode == LifetimeAndTypesWithColons &&
1617 !self.eat(&token::MOD_SEP) {
1618 segments.push(ast::PathSegment {
1619 identifier: identifier,
1620 lifetimes: Vec::new(),
1621 types: OwnedSlice::empty(),
1626 // Parse the `<` before the lifetime and types, if applicable.
1627 let (any_lifetime_or_types, lifetimes, types) = {
1628 if mode != NoTypesAllowed && self.eat_lt(false) {
1629 let (lifetimes, types) =
1630 self.parse_generic_values_after_lt();
1631 (true, lifetimes, OwnedSlice::from_vec(types))
1633 (false, Vec::new(), OwnedSlice::empty())
1637 // Assemble and push the result.
1638 segments.push(ast::PathSegment {
1639 identifier: identifier,
1640 lifetimes: lifetimes,
1644 // We're done if we don't see a '::', unless the mode required
1645 // a double colon to get here in the first place.
1646 if !(mode == LifetimeAndTypesWithColons &&
1647 !any_lifetime_or_types) {
1648 if !self.eat(&token::MOD_SEP) {
1654 // Next, parse a plus and bounded type parameters, if applicable.
1655 let bounds = if mode == LifetimeAndTypesAndBounds {
1657 if self.eat(&token::BINOP(token::PLUS)) {
1658 let (_, bounds) = self.parse_ty_param_bounds(false);
1669 // Assemble the span.
1670 let span = mk_sp(lo, self.last_span.hi);
1672 // Assemble the result.
1683 /// parses 0 or 1 lifetime
1684 pub fn parse_opt_lifetime(&mut self) -> Option<ast::Lifetime> {
1686 token::LIFETIME(..) => {
1687 Some(self.parse_lifetime())
1695 /// Parses a single lifetime
1696 // matches lifetime = LIFETIME
1697 pub fn parse_lifetime(&mut self) -> ast::Lifetime {
1699 token::LIFETIME(i) => {
1700 let span = self.span;
1702 return ast::Lifetime {
1703 id: ast::DUMMY_NODE_ID,
1709 self.fatal(format!("expected a lifetime name").as_slice());
1714 // matches lifetimes = ( lifetime ) | ( lifetime , lifetimes )
1715 // actually, it matches the empty one too, but putting that in there
1716 // messes up the grammar....
1717 pub fn parse_lifetimes(&mut self) -> Vec<ast::Lifetime> {
1720 * Parses zero or more comma separated lifetimes.
1721 * Expects each lifetime to be followed by either
1722 * a comma or `>`. Used when parsing type parameter
1723 * lists, where we expect something like `<'a, 'b, T>`.
1726 let mut res = Vec::new();
1729 token::LIFETIME(_) => {
1730 res.push(self.parse_lifetime());
1738 token::COMMA => { self.bump();}
1739 token::GT => { return res; }
1740 token::BINOP(token::SHR) => { return res; }
1742 let msg = format!("expected `,` or `>` after lifetime \
1745 self.fatal(msg.as_slice());
1751 pub fn token_is_mutability(tok: &token::Token) -> bool {
1752 token::is_keyword(keywords::Mut, tok) ||
1753 token::is_keyword(keywords::Const, tok)
1756 // parse mutability declaration (mut/const/imm)
1757 pub fn parse_mutability(&mut self) -> Mutability {
1758 if self.eat_keyword(keywords::Mut) {
1765 // parse ident COLON expr
1766 pub fn parse_field(&mut self) -> Field {
1767 let lo = self.span.lo;
1768 let i = self.parse_ident();
1769 let hi = self.last_span.hi;
1770 self.expect(&token::COLON);
1771 let e = self.parse_expr();
1773 ident: spanned(lo, hi, i),
1775 span: mk_sp(lo, e.span.hi),
1779 pub fn mk_expr(&mut self, lo: BytePos, hi: BytePos, node: Expr_) -> Gc<Expr> {
1781 id: ast::DUMMY_NODE_ID,
1783 span: mk_sp(lo, hi),
1787 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: Gc<Expr>) -> ast::Expr_ {
1788 ExprUnary(unop, expr)
1791 pub fn mk_binary(&mut self, binop: ast::BinOp,
1792 lhs: Gc<Expr>, rhs: Gc<Expr>) -> ast::Expr_ {
1793 ExprBinary(binop, lhs, rhs)
1796 pub fn mk_call(&mut self, f: Gc<Expr>, args: Vec<Gc<Expr>>) -> ast::Expr_ {
1800 fn mk_method_call(&mut self,
1801 ident: ast::SpannedIdent,
1803 args: Vec<Gc<Expr>>)
1805 ExprMethodCall(ident, tps, args)
1808 pub fn mk_index(&mut self, expr: Gc<Expr>, idx: Gc<Expr>) -> ast::Expr_ {
1809 ExprIndex(expr, idx)
1812 pub fn mk_field(&mut self, expr: Gc<Expr>, ident: Ident,
1813 tys: Vec<P<Ty>>) -> ast::Expr_ {
1814 ExprField(expr, ident, tys)
1817 pub fn mk_assign_op(&mut self, binop: ast::BinOp,
1818 lhs: Gc<Expr>, rhs: Gc<Expr>) -> ast::Expr_ {
1819 ExprAssignOp(binop, lhs, rhs)
1822 pub fn mk_mac_expr(&mut self, lo: BytePos, hi: BytePos, m: Mac_) -> Gc<Expr> {
1824 id: ast::DUMMY_NODE_ID,
1825 node: ExprMac(codemap::Spanned {node: m, span: mk_sp(lo, hi)}),
1826 span: mk_sp(lo, hi),
1830 pub fn mk_lit_u32(&mut self, i: u32) -> Gc<Expr> {
1831 let span = &self.span;
1832 let lv_lit = box(GC) codemap::Spanned {
1833 node: LitUint(i as u64, TyU32),
1838 id: ast::DUMMY_NODE_ID,
1839 node: ExprLit(lv_lit),
1844 // at the bottom (top?) of the precedence hierarchy,
1845 // parse things like parenthesized exprs,
1846 // macros, return, etc.
1847 pub fn parse_bottom_expr(&mut self) -> Gc<Expr> {
1848 maybe_whole_expr!(self);
1850 let lo = self.span.lo;
1851 let mut hi = self.span.hi;
1855 if self.token == token::LPAREN {
1857 // (e) is parenthesized e
1858 // (e,) is a tuple with only one field, e
1859 let mut trailing_comma = false;
1860 if self.token == token::RPAREN {
1863 let lit = box(GC) spanned(lo, hi, LitNil);
1864 return self.mk_expr(lo, hi, ExprLit(lit));
1866 let mut es = vec!(self.parse_expr());
1867 self.commit_expr(*es.last().unwrap(), &[], &[token::COMMA, token::RPAREN]);
1868 while self.token == token::COMMA {
1870 if self.token != token::RPAREN {
1871 es.push(self.parse_expr());
1872 self.commit_expr(*es.last().unwrap(), &[], &[token::COMMA, token::RPAREN]);
1875 trailing_comma = true;
1879 self.commit_expr_expecting(*es.last().unwrap(), token::RPAREN);
1881 return if es.len() == 1 && !trailing_comma {
1882 self.mk_expr(lo, hi, ExprParen(*es.get(0)))
1885 self.mk_expr(lo, hi, ExprTup(es))
1887 } else if self.token == token::LBRACE {
1889 let blk = self.parse_block_tail(lo, DefaultBlock);
1890 return self.mk_expr(blk.span.lo, blk.span.hi,
1892 } else if token::is_bar(&self.token) {
1893 return self.parse_lambda_expr();
1894 } else if self.eat_keyword(keywords::Proc) {
1895 let decl = self.parse_proc_decl();
1896 let body = self.parse_expr();
1897 let fakeblock = P(ast::Block {
1898 view_items: Vec::new(),
1901 id: ast::DUMMY_NODE_ID,
1902 rules: DefaultBlock,
1906 return self.mk_expr(lo, body.span.hi, ExprProc(decl, fakeblock));
1907 } else if self.eat_keyword(keywords::Self) {
1908 let path = ast_util::ident_to_path(mk_sp(lo, hi), special_idents::self_);
1909 ex = ExprPath(path);
1910 hi = self.last_span.hi;
1911 } else if self.eat_keyword(keywords::If) {
1912 return self.parse_if_expr();
1913 } else if self.eat_keyword(keywords::For) {
1914 return self.parse_for_expr(None);
1915 } else if self.eat_keyword(keywords::While) {
1916 return self.parse_while_expr();
1917 } else if Parser::token_is_lifetime(&self.token) {
1918 let lifetime = self.get_lifetime();
1920 self.expect(&token::COLON);
1921 if self.eat_keyword(keywords::For) {
1922 return self.parse_for_expr(Some(lifetime))
1923 } else if self.eat_keyword(keywords::Loop) {
1924 return self.parse_loop_expr(Some(lifetime))
1926 self.fatal("expected `for` or `loop` after a label")
1928 } else if self.eat_keyword(keywords::Loop) {
1929 return self.parse_loop_expr(None);
1930 } else if self.eat_keyword(keywords::Continue) {
1931 let lo = self.span.lo;
1932 let ex = if Parser::token_is_lifetime(&self.token) {
1933 let lifetime = self.get_lifetime();
1935 ExprAgain(Some(lifetime))
1939 let hi = self.span.hi;
1940 return self.mk_expr(lo, hi, ex);
1941 } else if self.eat_keyword(keywords::Match) {
1942 return self.parse_match_expr();
1943 } else if self.eat_keyword(keywords::Unsafe) {
1944 return self.parse_block_expr(lo, UnsafeBlock(ast::UserProvided));
1945 } else if self.token == token::LBRACKET {
1948 if self.token == token::RBRACKET {
1951 ex = ExprVec(Vec::new());
1954 let first_expr = self.parse_expr();
1955 if self.token == token::COMMA &&
1956 self.look_ahead(1, |t| *t == token::DOTDOT) {
1957 // Repeating vector syntax: [ 0, ..512 ]
1960 let count = self.parse_expr();
1961 self.expect(&token::RBRACKET);
1962 ex = ExprRepeat(first_expr, count);
1963 } else if self.token == token::COMMA {
1964 // Vector with two or more elements.
1966 let remaining_exprs = self.parse_seq_to_end(
1968 seq_sep_trailing_allowed(token::COMMA),
1971 let mut exprs = vec!(first_expr);
1972 exprs.push_all_move(remaining_exprs);
1973 ex = ExprVec(exprs);
1975 // Vector with one element.
1976 self.expect(&token::RBRACKET);
1977 ex = ExprVec(vec!(first_expr));
1980 hi = self.last_span.hi;
1981 } else if self.eat_keyword(keywords::Return) {
1982 // RETURN expression
1983 if can_begin_expr(&self.token) {
1984 let e = self.parse_expr();
1986 ex = ExprRet(Some(e));
1987 } else { ex = ExprRet(None); }
1988 } else if self.eat_keyword(keywords::Break) {
1990 if Parser::token_is_lifetime(&self.token) {
1991 let lifetime = self.get_lifetime();
1993 ex = ExprBreak(Some(lifetime));
1995 ex = ExprBreak(None);
1998 } else if self.token == token::MOD_SEP ||
1999 is_ident(&self.token) && !self.is_keyword(keywords::True) &&
2000 !self.is_keyword(keywords::False) {
2001 let pth = self.parse_path(LifetimeAndTypesWithColons).path;
2003 // `!`, as an operator, is prefix, so we know this isn't that
2004 if self.token == token::NOT {
2005 // MACRO INVOCATION expression
2008 let ket = token::close_delimiter_for(&self.token)
2009 .unwrap_or_else(|| self.fatal("expected open delimiter"));
2012 let tts = self.parse_seq_to_end(&ket,
2014 |p| p.parse_token_tree());
2015 let hi = self.span.hi;
2017 return self.mk_mac_expr(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT));
2018 } else if self.token == token::LBRACE {
2019 // This might be a struct literal.
2020 if self.looking_at_struct_literal() {
2021 // It's a struct literal.
2023 let mut fields = Vec::new();
2024 let mut base = None;
2026 while self.token != token::RBRACE {
2027 if self.eat(&token::DOTDOT) {
2028 base = Some(self.parse_expr());
2032 fields.push(self.parse_field());
2033 self.commit_expr(fields.last().unwrap().expr,
2034 &[token::COMMA], &[token::RBRACE]);
2038 self.expect(&token::RBRACE);
2039 ex = ExprStruct(pth, fields, base);
2040 return self.mk_expr(lo, hi, ex);
2047 // other literal expression
2048 let lit = self.parse_lit();
2050 ex = ExprLit(box(GC) lit);
2053 return self.mk_expr(lo, hi, ex);
2056 // parse a block or unsafe block
2057 pub fn parse_block_expr(&mut self, lo: BytePos, blk_mode: BlockCheckMode)
2059 self.expect(&token::LBRACE);
2060 let blk = self.parse_block_tail(lo, blk_mode);
2061 return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk));
2064 // parse a.b or a(13) or a[4] or just a
2065 pub fn parse_dot_or_call_expr(&mut self) -> Gc<Expr> {
2066 let b = self.parse_bottom_expr();
2067 self.parse_dot_or_call_expr_with(b)
2070 pub fn parse_dot_or_call_expr_with(&mut self, e0: Gc<Expr>) -> Gc<Expr> {
2076 if self.eat(&token::DOT) {
2078 token::IDENT(i, _) => {
2079 let dot = self.last_span.hi;
2082 let (_, tys) = if self.eat(&token::MOD_SEP) {
2084 self.parse_generic_values_after_lt()
2086 (Vec::new(), Vec::new())
2089 // expr.f() method call
2092 let mut es = self.parse_unspanned_seq(
2095 seq_sep_trailing_disallowed(token::COMMA),
2098 hi = self.last_span.hi;
2101 let id = spanned(dot, hi, i);
2102 let nd = self.mk_method_call(id, tys, es);
2103 e = self.mk_expr(lo, hi, nd);
2106 let field = self.mk_field(e, i, tys);
2107 e = self.mk_expr(lo, hi, field)
2111 _ => self.unexpected()
2115 if self.expr_is_complete(e) { break; }
2119 let es = self.parse_unspanned_seq(
2122 seq_sep_trailing_allowed(token::COMMA),
2125 hi = self.last_span.hi;
2127 let nd = self.mk_call(e, es);
2128 e = self.mk_expr(lo, hi, nd);
2132 token::LBRACKET => {
2134 let ix = self.parse_expr();
2136 self.commit_expr_expecting(ix, token::RBRACKET);
2137 let index = self.mk_index(e, ix);
2138 e = self.mk_expr(lo, hi, index)
2147 // parse an optional separator followed by a kleene-style
2148 // repetition token (+ or *).
2149 pub fn parse_sep_and_zerok(&mut self) -> (Option<token::Token>, bool) {
2150 fn parse_zerok(parser: &mut Parser) -> Option<bool> {
2151 match parser.token {
2152 token::BINOP(token::STAR) | token::BINOP(token::PLUS) => {
2153 let zerok = parser.token == token::BINOP(token::STAR);
2161 match parse_zerok(self) {
2162 Some(zerok) => return (None, zerok),
2166 let separator = self.bump_and_get();
2167 match parse_zerok(self) {
2168 Some(zerok) => (Some(separator), zerok),
2169 None => self.fatal("expected `*` or `+`")
2173 // parse a single token tree from the input.
2174 pub fn parse_token_tree(&mut self) -> TokenTree {
2175 // FIXME #6994: currently, this is too eager. It
2176 // parses token trees but also identifies TTSeq's
2177 // and TTNonterminal's; it's too early to know yet
2178 // whether something will be a nonterminal or a seq
2180 maybe_whole!(deref self, NtTT);
2182 // this is the fall-through for the 'match' below.
2183 // invariants: the current token is not a left-delimiter,
2184 // not an EOF, and not the desired right-delimiter (if
2185 // it were, parse_seq_to_before_end would have prevented
2186 // reaching this point.
2187 fn parse_non_delim_tt_tok(p: &mut Parser) -> TokenTree {
2188 maybe_whole!(deref p, NtTT);
2190 token::RPAREN | token::RBRACE | token::RBRACKET => {
2191 // This is a conservative error: only report the last unclosed delimiter. The
2192 // previous unclosed delimiters could actually be closed! The parser just hasn't
2193 // gotten to them yet.
2194 match p.open_braces.last() {
2196 Some(&sp) => p.span_note(sp, "unclosed delimiter"),
2198 let token_str = p.this_token_to_str();
2199 p.fatal(format!("incorrect close delimiter: `{}`",
2200 token_str).as_slice())
2202 /* we ought to allow different depths of unquotation */
2203 token::DOLLAR if p.quote_depth > 0u => {
2207 if p.token == token::LPAREN {
2208 let seq = p.parse_seq(
2212 |p| p.parse_token_tree()
2214 let (s, z) = p.parse_sep_and_zerok();
2215 let seq = match seq {
2216 Spanned { node, .. } => node,
2218 TTSeq(mk_sp(sp.lo, p.span.hi), Rc::new(seq), s, z)
2220 TTNonterminal(sp, p.parse_ident())
2229 // turn the next token into a TTTok:
2230 fn parse_any_tt_tok(p: &mut Parser) -> TokenTree {
2231 TTTok(p.span, p.bump_and_get())
2234 match (&self.token, token::close_delimiter_for(&self.token)) {
2235 (&token::EOF, _) => {
2236 let open_braces = self.open_braces.clone();
2237 for sp in open_braces.iter() {
2238 self.span_note(*sp, "Did you mean to close this delimiter?");
2240 // There shouldn't really be a span, but it's easier for the test runner
2241 // if we give it one
2242 self.fatal("this file contains an un-closed delimiter ");
2244 (_, Some(close_delim)) => {
2245 // Parse the open delimiter.
2246 self.open_braces.push(self.span);
2247 let mut result = vec!(parse_any_tt_tok(self));
2250 self.parse_seq_to_before_end(&close_delim,
2252 |p| p.parse_token_tree());
2253 result.push_all_move(trees);
2255 // Parse the close delimiter.
2256 result.push(parse_any_tt_tok(self));
2257 self.open_braces.pop().unwrap();
2259 TTDelim(Rc::new(result))
2261 _ => parse_non_delim_tt_tok(self)
2265 // parse a stream of tokens into a list of TokenTree's,
2267 pub fn parse_all_token_trees(&mut self) -> Vec<TokenTree> {
2268 let mut tts = Vec::new();
2269 while self.token != token::EOF {
2270 tts.push(self.parse_token_tree());
2275 pub fn parse_matchers(&mut self) -> Vec<Matcher> {
2276 // unification of Matcher's and TokenTree's would vastly improve
2277 // the interpolation of Matcher's
2278 maybe_whole!(self, NtMatchers);
2279 let mut name_idx = 0u;
2280 match token::close_delimiter_for(&self.token) {
2281 Some(other_delimiter) => {
2283 self.parse_matcher_subseq_upto(&mut name_idx, &other_delimiter)
2285 None => self.fatal("expected open delimiter")
2289 // This goofy function is necessary to correctly match parens in Matcher's.
2290 // Otherwise, `$( ( )` would be a valid Matcher, and `$( () )` would be
2291 // invalid. It's similar to common::parse_seq.
2292 pub fn parse_matcher_subseq_upto(&mut self,
2293 name_idx: &mut uint,
2296 let mut ret_val = Vec::new();
2297 let mut lparens = 0u;
2299 while self.token != *ket || lparens > 0u {
2300 if self.token == token::LPAREN { lparens += 1u; }
2301 if self.token == token::RPAREN { lparens -= 1u; }
2302 ret_val.push(self.parse_matcher(name_idx));
2310 pub fn parse_matcher(&mut self, name_idx: &mut uint) -> Matcher {
2311 let lo = self.span.lo;
2313 let m = if self.token == token::DOLLAR {
2315 if self.token == token::LPAREN {
2316 let name_idx_lo = *name_idx;
2318 let ms = self.parse_matcher_subseq_upto(name_idx,
2321 self.fatal("repetition body must be nonempty");
2323 let (sep, zerok) = self.parse_sep_and_zerok();
2324 MatchSeq(ms, sep, zerok, name_idx_lo, *name_idx)
2326 let bound_to = self.parse_ident();
2327 self.expect(&token::COLON);
2328 let nt_name = self.parse_ident();
2329 let m = MatchNonterminal(bound_to, nt_name, *name_idx);
2334 MatchTok(self.bump_and_get())
2337 return spanned(lo, self.span.hi, m);
2340 // parse a prefix-operator expr
2341 pub fn parse_prefix_expr(&mut self) -> Gc<Expr> {
2342 let lo = self.span.lo;
2349 let e = self.parse_prefix_expr();
2351 ex = self.mk_unary(UnNot, e);
2353 token::BINOP(token::MINUS) => {
2355 let e = self.parse_prefix_expr();
2357 ex = self.mk_unary(UnNeg, e);
2359 token::BINOP(token::STAR) => {
2361 let e = self.parse_prefix_expr();
2363 ex = self.mk_unary(UnDeref, e);
2365 token::BINOP(token::AND) | token::ANDAND => {
2367 let _lt = self.parse_opt_lifetime();
2368 let m = self.parse_mutability();
2369 let e = self.parse_prefix_expr();
2371 // HACK: turn &[...] into a &-vec
2373 ExprVec(..) if m == MutImmutable => {
2374 ExprVstore(e, ExprVstoreSlice)
2376 ExprVec(..) if m == MutMutable => {
2377 ExprVstore(e, ExprVstoreMutSlice)
2379 _ => ExprAddrOf(m, e)
2384 let span = self.last_span;
2385 self.obsolete(span, ObsoleteManagedExpr);
2386 let e = self.parse_prefix_expr();
2388 ex = self.mk_unary(UnBox, e);
2393 let e = self.parse_prefix_expr();
2395 // HACK: turn ~[...] into a ~-vec
2396 let last_span = self.last_span;
2398 ExprVec(..) | ExprRepeat(..) => {
2399 self.obsolete(last_span, ObsoleteOwnedVector);
2400 ExprVstore(e, ExprVstoreUniq)
2402 ExprLit(lit) if lit_is_str(lit) => {
2403 self.obsolete(last_span, ObsoleteOwnedExpr);
2404 ExprVstore(e, ExprVstoreUniq)
2407 self.obsolete(last_span, ObsoleteOwnedExpr);
2408 self.mk_unary(UnUniq, e)
2412 token::IDENT(_, _) if self.is_keyword(keywords::Box) => {
2415 // Check for a place: `box(PLACE) EXPR`.
2416 if self.eat(&token::LPAREN) {
2417 // Support `box() EXPR` as the default.
2418 if !self.eat(&token::RPAREN) {
2419 let place = self.parse_expr();
2420 self.expect(&token::RPAREN);
2421 let subexpression = self.parse_prefix_expr();
2422 hi = subexpression.span.hi;
2423 ex = ExprBox(place, subexpression);
2424 return self.mk_expr(lo, hi, ex);
2428 // Otherwise, we use the unique pointer default.
2429 let subexpression = self.parse_prefix_expr();
2430 hi = subexpression.span.hi;
2431 // HACK: turn `box [...]` into a boxed-vec
2432 ex = match subexpression.node {
2433 ExprVec(..) | ExprRepeat(..) => {
2434 let last_span = self.last_span;
2435 self.obsolete(last_span, ObsoleteOwnedVector);
2436 ExprVstore(subexpression, ExprVstoreUniq)
2438 ExprLit(lit) if lit_is_str(lit) => {
2439 ExprVstore(subexpression, ExprVstoreUniq)
2441 _ => self.mk_unary(UnUniq, subexpression)
2444 _ => return self.parse_dot_or_call_expr()
2446 return self.mk_expr(lo, hi, ex);
2449 // parse an expression of binops
2450 pub fn parse_binops(&mut self) -> Gc<Expr> {
2451 let prefix_expr = self.parse_prefix_expr();
2452 self.parse_more_binops(prefix_expr, 0)
2455 // parse an expression of binops of at least min_prec precedence
2456 pub fn parse_more_binops(&mut self, lhs: Gc<Expr>,
2457 min_prec: uint) -> Gc<Expr> {
2458 if self.expr_is_complete(lhs) { return lhs; }
2460 // Prevent dynamic borrow errors later on by limiting the
2461 // scope of the borrows.
2463 let token: &token::Token = &self.token;
2464 let restriction: &restriction = &self.restriction;
2465 match (token, restriction) {
2466 (&token::BINOP(token::OR), &RESTRICT_NO_BAR_OP) => return lhs,
2467 (&token::BINOP(token::OR),
2468 &RESTRICT_NO_BAR_OR_DOUBLEBAR_OP) => return lhs,
2469 (&token::OROR, &RESTRICT_NO_BAR_OR_DOUBLEBAR_OP) => return lhs,
2474 let cur_opt = token_to_binop(&self.token);
2477 let cur_prec = operator_prec(cur_op);
2478 if cur_prec > min_prec {
2480 let expr = self.parse_prefix_expr();
2481 let rhs = self.parse_more_binops(expr, cur_prec);
2482 let binary = self.mk_binary(cur_op, lhs, rhs);
2483 let bin = self.mk_expr(lhs.span.lo, rhs.span.hi, binary);
2484 self.parse_more_binops(bin, min_prec)
2490 if as_prec > min_prec && self.eat_keyword(keywords::As) {
2491 let rhs = self.parse_ty(false);
2492 let _as = self.mk_expr(lhs.span.lo,
2494 ExprCast(lhs, rhs));
2495 self.parse_more_binops(_as, min_prec)
2503 // parse an assignment expression....
2504 // actually, this seems to be the main entry point for
2505 // parsing an arbitrary expression.
2506 pub fn parse_assign_expr(&mut self) -> Gc<Expr> {
2507 let lo = self.span.lo;
2508 let lhs = self.parse_binops();
2512 let rhs = self.parse_expr();
2513 self.mk_expr(lo, rhs.span.hi, ExprAssign(lhs, rhs))
2515 token::BINOPEQ(op) => {
2517 let rhs = self.parse_expr();
2518 let aop = match op {
2519 token::PLUS => BiAdd,
2520 token::MINUS => BiSub,
2521 token::STAR => BiMul,
2522 token::SLASH => BiDiv,
2523 token::PERCENT => BiRem,
2524 token::CARET => BiBitXor,
2525 token::AND => BiBitAnd,
2526 token::OR => BiBitOr,
2527 token::SHL => BiShl,
2530 let assign_op = self.mk_assign_op(aop, lhs, rhs);
2531 self.mk_expr(lo, rhs.span.hi, assign_op)
2539 // parse an 'if' expression ('if' token already eaten)
2540 pub fn parse_if_expr(&mut self) -> Gc<Expr> {
2541 let lo = self.last_span.lo;
2542 let cond = self.parse_expr();
2543 let thn = self.parse_block();
2544 let mut els: Option<Gc<Expr>> = None;
2545 let mut hi = thn.span.hi;
2546 if self.eat_keyword(keywords::Else) {
2547 let elexpr = self.parse_else_expr();
2549 hi = elexpr.span.hi;
2551 self.mk_expr(lo, hi, ExprIf(cond, thn, els))
2554 // `|args| { ... }` or `{ ...}` like in `do` expressions
2555 pub fn parse_lambda_block_expr(&mut self) -> Gc<Expr> {
2556 self.parse_lambda_expr_(
2559 token::BINOP(token::OR) | token::OROR => {
2560 p.parse_fn_block_decl()
2563 // No argument list - `do foo {`
2567 id: ast::DUMMY_NODE_ID,
2578 let blk = p.parse_block();
2579 p.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk))
2584 pub fn parse_lambda_expr(&mut self) -> Gc<Expr> {
2585 self.parse_lambda_expr_(|p| p.parse_fn_block_decl(),
2589 // parse something of the form |args| expr
2590 // this is used both in parsing a lambda expr
2591 // and in parsing a block expr as e.g. in for...
2592 pub fn parse_lambda_expr_(&mut self,
2593 parse_decl: |&mut Parser| -> P<FnDecl>,
2594 parse_body: |&mut Parser| -> Gc<Expr>)
2596 let lo = self.span.lo;
2597 let decl = parse_decl(self);
2598 let body = parse_body(self);
2599 let fakeblock = P(ast::Block {
2600 view_items: Vec::new(),
2603 id: ast::DUMMY_NODE_ID,
2604 rules: DefaultBlock,
2608 return self.mk_expr(lo, body.span.hi, ExprFnBlock(decl, fakeblock));
2611 pub fn parse_else_expr(&mut self) -> Gc<Expr> {
2612 if self.eat_keyword(keywords::If) {
2613 return self.parse_if_expr();
2615 let blk = self.parse_block();
2616 return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk));
2620 // parse a 'for' .. 'in' expression ('for' token already eaten)
2621 pub fn parse_for_expr(&mut self, opt_ident: Option<ast::Ident>) -> Gc<Expr> {
2622 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
2624 let lo = self.last_span.lo;
2625 let pat = self.parse_pat();
2626 self.expect_keyword(keywords::In);
2627 let expr = self.parse_expr();
2628 let loop_block = self.parse_block();
2629 let hi = self.span.hi;
2631 self.mk_expr(lo, hi, ExprForLoop(pat, expr, loop_block, opt_ident))
2634 pub fn parse_while_expr(&mut self) -> Gc<Expr> {
2635 let lo = self.last_span.lo;
2636 let cond = self.parse_expr();
2637 let body = self.parse_block();
2638 let hi = body.span.hi;
2639 return self.mk_expr(lo, hi, ExprWhile(cond, body));
2642 pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::Ident>) -> Gc<Expr> {
2643 let lo = self.last_span.lo;
2644 let body = self.parse_block();
2645 let hi = body.span.hi;
2646 self.mk_expr(lo, hi, ExprLoop(body, opt_ident))
2649 // For distinguishing between struct literals and blocks
2650 fn looking_at_struct_literal(&mut self) -> bool {
2651 self.token == token::LBRACE &&
2652 ((self.look_ahead(1, |t| token::is_plain_ident(t)) &&
2653 self.look_ahead(2, |t| *t == token::COLON))
2654 || self.look_ahead(1, |t| *t == token::DOTDOT))
2657 fn parse_match_expr(&mut self) -> Gc<Expr> {
2658 let lo = self.last_span.lo;
2659 let discriminant = self.parse_expr();
2660 self.commit_expr_expecting(discriminant, token::LBRACE);
2661 let mut arms: Vec<Arm> = Vec::new();
2662 while self.token != token::RBRACE {
2663 let attrs = self.parse_outer_attributes();
2664 let pats = self.parse_pats();
2665 let mut guard = None;
2666 if self.eat_keyword(keywords::If) {
2667 guard = Some(self.parse_expr());
2669 self.expect(&token::FAT_ARROW);
2670 let expr = self.parse_expr_res(RESTRICT_STMT_EXPR);
2673 !classify::expr_is_simple_block(expr)
2674 && self.token != token::RBRACE;
2677 self.commit_expr(expr, &[token::COMMA], &[token::RBRACE]);
2679 self.eat(&token::COMMA);
2682 arms.push(ast::Arm {
2689 let hi = self.span.hi;
2691 return self.mk_expr(lo, hi, ExprMatch(discriminant, arms));
2694 // parse an expression
2695 pub fn parse_expr(&mut self) -> Gc<Expr> {
2696 return self.parse_expr_res(UNRESTRICTED);
2699 // parse an expression, subject to the given restriction
2700 fn parse_expr_res(&mut self, r: restriction) -> Gc<Expr> {
2701 let old = self.restriction;
2702 self.restriction = r;
2703 let e = self.parse_assign_expr();
2704 self.restriction = old;
2708 // parse the RHS of a local variable declaration (e.g. '= 14;')
2709 fn parse_initializer(&mut self) -> Option<Gc<Expr>> {
2710 if self.token == token::EQ {
2712 Some(self.parse_expr())
2718 // parse patterns, separated by '|' s
2719 fn parse_pats(&mut self) -> Vec<Gc<Pat>> {
2720 let mut pats = Vec::new();
2722 pats.push(self.parse_pat());
2723 if self.token == token::BINOP(token::OR) { self.bump(); }
2724 else { return pats; }
2728 fn parse_pat_vec_elements(
2730 ) -> (Vec<Gc<Pat>> , Option<Gc<Pat>>, Vec<Gc<Pat>> ) {
2731 let mut before = Vec::new();
2732 let mut slice = None;
2733 let mut after = Vec::new();
2734 let mut first = true;
2735 let mut before_slice = true;
2737 while self.token != token::RBRACKET {
2738 if first { first = false; }
2739 else { self.expect(&token::COMMA); }
2741 let mut is_slice = false;
2743 if self.token == token::DOTDOT {
2746 before_slice = false;
2751 if self.token == token::COMMA || self.token == token::RBRACKET {
2752 slice = Some(box(GC) ast::Pat {
2753 id: ast::DUMMY_NODE_ID,
2758 let subpat = self.parse_pat();
2760 ast::Pat { node: PatIdent(_, _, _), .. } => {
2761 slice = Some(subpat);
2763 ast::Pat { span, .. } => self.span_fatal(
2764 span, "expected an identifier or nothing"
2769 let subpat = self.parse_pat();
2771 before.push(subpat);
2778 (before, slice, after)
2781 // parse the fields of a struct-like pattern
2782 fn parse_pat_fields(&mut self) -> (Vec<ast::FieldPat> , bool) {
2783 let mut fields = Vec::new();
2784 let mut etc = false;
2785 let mut first = true;
2786 while self.token != token::RBRACE {
2790 self.expect(&token::COMMA);
2791 // accept trailing commas
2792 if self.token == token::RBRACE { break }
2795 if self.token == token::DOTDOT {
2797 if self.token != token::RBRACE {
2798 let token_str = self.this_token_to_str();
2799 self.fatal(format!("expected `{}`, found `{}`", "}",
2800 token_str).as_slice())
2806 let bind_type = if self.eat_keyword(keywords::Mut) {
2807 BindByValue(MutMutable)
2808 } else if self.eat_keyword(keywords::Ref) {
2809 BindByRef(self.parse_mutability())
2811 BindByValue(MutImmutable)
2814 let fieldname = self.parse_ident();
2816 let subpat = if self.token == token::COLON {
2818 BindByRef(..) | BindByValue(MutMutable) => {
2819 let token_str = self.this_token_to_str();
2820 self.fatal(format!("unexpected `{}`",
2821 token_str).as_slice())
2829 let fieldpath = ast_util::ident_to_path(self.last_span,
2832 id: ast::DUMMY_NODE_ID,
2833 node: PatIdent(bind_type, fieldpath, None),
2834 span: self.last_span
2837 fields.push(ast::FieldPat { ident: fieldname, pat: subpat });
2839 return (fields, etc);
2843 pub fn parse_pat(&mut self) -> Gc<Pat> {
2844 maybe_whole!(self, NtPat);
2846 let lo = self.span.lo;
2851 token::UNDERSCORE => {
2854 hi = self.last_span.hi;
2855 return box(GC) ast::Pat {
2856 id: ast::DUMMY_NODE_ID,
2864 let sub = self.parse_pat();
2866 let last_span = self.last_span;
2868 self.obsolete(last_span, ObsoleteOwnedPattern);
2869 return box(GC) ast::Pat {
2870 id: ast::DUMMY_NODE_ID,
2875 token::BINOP(token::AND) | token::ANDAND => {
2877 let lo = self.span.lo;
2879 let sub = self.parse_pat();
2880 pat = PatRegion(sub);
2881 hi = self.last_span.hi;
2882 return box(GC) ast::Pat {
2883 id: ast::DUMMY_NODE_ID,
2889 // parse (pat,pat,pat,...) as tuple
2891 if self.token == token::RPAREN {
2894 let lit = box(GC) codemap::Spanned {
2896 span: mk_sp(lo, hi)};
2897 let expr = self.mk_expr(lo, hi, ExprLit(lit));
2900 let mut fields = vec!(self.parse_pat());
2901 if self.look_ahead(1, |t| *t != token::RPAREN) {
2902 while self.token == token::COMMA {
2904 if self.token == token::RPAREN { break; }
2905 fields.push(self.parse_pat());
2908 if fields.len() == 1 { self.expect(&token::COMMA); }
2909 self.expect(&token::RPAREN);
2910 pat = PatTup(fields);
2912 hi = self.last_span.hi;
2913 return box(GC) ast::Pat {
2914 id: ast::DUMMY_NODE_ID,
2919 token::LBRACKET => {
2920 // parse [pat,pat,...] as vector pattern
2922 let (before, slice, after) =
2923 self.parse_pat_vec_elements();
2925 self.expect(&token::RBRACKET);
2926 pat = ast::PatVec(before, slice, after);
2927 hi = self.last_span.hi;
2928 return box(GC) ast::Pat {
2929 id: ast::DUMMY_NODE_ID,
2937 if (!is_ident_or_path(&self.token) && self.token != token::MOD_SEP)
2938 || self.is_keyword(keywords::True)
2939 || self.is_keyword(keywords::False) {
2940 // Parse an expression pattern or exp .. exp.
2942 // These expressions are limited to literals (possibly
2943 // preceded by unary-minus) or identifiers.
2944 let val = self.parse_literal_maybe_minus();
2945 if self.eat(&token::DOTDOT) {
2946 let end = if is_ident_or_path(&self.token) {
2947 let path = self.parse_path(LifetimeAndTypesWithColons)
2949 let hi = self.span.hi;
2950 self.mk_expr(lo, hi, ExprPath(path))
2952 self.parse_literal_maybe_minus()
2954 pat = PatRange(val, end);
2958 } else if self.eat_keyword(keywords::Mut) {
2959 pat = self.parse_pat_ident(BindByValue(MutMutable));
2960 } else if self.eat_keyword(keywords::Ref) {
2962 let mutbl = self.parse_mutability();
2963 pat = self.parse_pat_ident(BindByRef(mutbl));
2964 } else if self.eat_keyword(keywords::Box) {
2967 // FIXME(#13910): Rename to `PatBox` and extend to full DST
2969 let sub = self.parse_pat();
2971 hi = self.last_span.hi;
2972 return box(GC) ast::Pat {
2973 id: ast::DUMMY_NODE_ID,
2978 let can_be_enum_or_struct = self.look_ahead(1, |t| {
2980 token::LPAREN | token::LBRACKET | token::LT |
2981 token::LBRACE | token::MOD_SEP => true,
2986 if self.look_ahead(1, |t| *t == token::DOTDOT) {
2987 let start = self.parse_expr_res(RESTRICT_NO_BAR_OP);
2988 self.eat(&token::DOTDOT);
2989 let end = self.parse_expr_res(RESTRICT_NO_BAR_OP);
2990 pat = PatRange(start, end);
2991 } else if is_plain_ident(&self.token) && !can_be_enum_or_struct {
2992 let name = self.parse_path(NoTypesAllowed).path;
2993 if self.eat(&token::NOT) {
2995 let ket = token::close_delimiter_for(&self.token)
2996 .unwrap_or_else(|| self.fatal("expected open delimiter"));
2999 let tts = self.parse_seq_to_end(&ket,
3001 |p| p.parse_token_tree());
3003 let mac = MacInvocTT(name, tts, EMPTY_CTXT);
3004 pat = ast::PatMac(codemap::Spanned {node: mac, span: self.span});
3006 let sub = if self.eat(&token::AT) {
3008 Some(self.parse_pat())
3013 pat = PatIdent(BindByValue(MutImmutable), name, sub);
3016 // parse an enum pat
3017 let enum_path = self.parse_path(LifetimeAndTypesWithColons)
3023 self.parse_pat_fields();
3025 pat = PatStruct(enum_path, fields, etc);
3028 let mut args: Vec<Gc<Pat>> = Vec::new();
3031 let is_dotdot = self.look_ahead(1, |t| {
3033 token::DOTDOT => true,
3038 // This is a "top constructor only" pat
3041 self.expect(&token::RPAREN);
3042 pat = PatEnum(enum_path, None);
3044 args = self.parse_enum_variant_seq(
3047 seq_sep_trailing_disallowed(token::COMMA),
3050 pat = PatEnum(enum_path, Some(args));
3054 if enum_path.segments.len() == 1 {
3055 // it could still be either an enum
3056 // or an identifier pattern, resolve
3057 // will sort it out:
3058 pat = PatIdent(BindByValue(MutImmutable),
3062 pat = PatEnum(enum_path, Some(args));
3070 hi = self.last_span.hi;
3072 id: ast::DUMMY_NODE_ID,
3074 span: mk_sp(lo, hi),
3078 // parse ident or ident @ pat
3079 // used by the copy foo and ref foo patterns to give a good
3080 // error message when parsing mistakes like ref foo(a,b)
3081 fn parse_pat_ident(&mut self,
3082 binding_mode: ast::BindingMode)
3084 if !is_plain_ident(&self.token) {
3085 let last_span = self.last_span;
3086 self.span_fatal(last_span,
3087 "expected identifier, found path");
3089 // why a path here, and not just an identifier?
3090 let name = self.parse_path(NoTypesAllowed).path;
3091 let sub = if self.eat(&token::AT) {
3092 Some(self.parse_pat())
3097 // just to be friendly, if they write something like
3099 // we end up here with ( as the current token. This shortly
3100 // leads to a parse error. Note that if there is no explicit
3101 // binding mode then we do not end up here, because the lookahead
3102 // will direct us over to parse_enum_variant()
3103 if self.token == token::LPAREN {
3104 let last_span = self.last_span;
3107 "expected identifier, found enum pattern");
3110 PatIdent(binding_mode, name, sub)
3113 // parse a local variable declaration
3114 fn parse_local(&mut self) -> Gc<Local> {
3115 let lo = self.span.lo;
3116 let pat = self.parse_pat();
3119 id: ast::DUMMY_NODE_ID,
3121 span: mk_sp(lo, lo),
3123 if self.eat(&token::COLON) {
3124 ty = self.parse_ty(true);
3126 let init = self.parse_initializer();
3127 box(GC) ast::Local {
3131 id: ast::DUMMY_NODE_ID,
3132 span: mk_sp(lo, self.last_span.hi),
3137 // parse a "let" stmt
3138 fn parse_let(&mut self) -> Gc<Decl> {
3139 let lo = self.span.lo;
3140 let local = self.parse_local();
3141 box(GC) spanned(lo, self.last_span.hi, DeclLocal(local))
3144 // parse a structure field
3145 fn parse_name_and_ty(&mut self, pr: Visibility,
3146 attrs: Vec<Attribute> ) -> StructField {
3147 let lo = self.span.lo;
3148 if !is_plain_ident(&self.token) {
3149 self.fatal("expected ident");
3151 let name = self.parse_ident();
3152 self.expect(&token::COLON);
3153 let ty = self.parse_ty(true);
3154 spanned(lo, self.last_span.hi, ast::StructField_ {
3155 kind: NamedField(name, pr),
3156 id: ast::DUMMY_NODE_ID,
3162 // parse a statement. may include decl.
3163 // precondition: any attributes are parsed already
3164 pub fn parse_stmt(&mut self, item_attrs: Vec<Attribute>) -> Gc<Stmt> {
3165 maybe_whole!(self, NtStmt);
3167 fn check_expected_item(p: &mut Parser, found_attrs: bool) {
3168 // If we have attributes then we should have an item
3170 let last_span = p.last_span;
3171 p.span_err(last_span, "expected item after attributes");
3175 let lo = self.span.lo;
3176 if self.is_keyword(keywords::Let) {
3177 check_expected_item(self, !item_attrs.is_empty());
3178 self.expect_keyword(keywords::Let);
3179 let decl = self.parse_let();
3180 return box(GC) spanned(lo, decl.span.hi, StmtDecl(decl, ast::DUMMY_NODE_ID));
3181 } else if is_ident(&self.token)
3182 && !token::is_any_keyword(&self.token)
3183 && self.look_ahead(1, |t| *t == token::NOT) {
3184 // parse a macro invocation. Looks like there's serious
3185 // overlap here; if this clause doesn't catch it (and it
3186 // won't, for brace-delimited macros) it will fall through
3187 // to the macro clause of parse_item_or_view_item. This
3188 // could use some cleanup, it appears to me.
3190 // whoops! I now have a guess: I'm guessing the "parens-only"
3191 // rule here is deliberate, to allow macro users to use parens
3192 // for things that should be parsed as stmt_mac, and braces
3193 // for things that should expand into items. Tricky, and
3194 // somewhat awkward... and probably undocumented. Of course,
3195 // I could just be wrong.
3197 check_expected_item(self, !item_attrs.is_empty());
3199 // Potential trouble: if we allow macros with paths instead of
3200 // idents, we'd need to look ahead past the whole path here...
3201 let pth = self.parse_path(NoTypesAllowed).path;
3204 let id = if token::close_delimiter_for(&self.token).is_some() {
3205 token::special_idents::invalid // no special identifier
3210 // check that we're pointing at delimiters (need to check
3211 // again after the `if`, because of `parse_ident`
3212 // consuming more tokens).
3213 let (bra, ket) = match token::close_delimiter_for(&self.token) {
3214 Some(ket) => (self.token.clone(), ket),
3216 // we only expect an ident if we didn't parse one
3218 let ident_str = if id == token::special_idents::invalid {
3223 let tok_str = self.this_token_to_str();
3224 self.fatal(format!("expected {}`(` or `{{`, but found `{}`",
3226 tok_str).as_slice())
3230 let tts = self.parse_unspanned_seq(
3234 |p| p.parse_token_tree()
3236 let hi = self.span.hi;
3238 if id == token::special_idents::invalid {
3239 return box(GC) spanned(lo, hi, StmtMac(
3240 spanned(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT)), false));
3242 // if it has a special ident, it's definitely an item
3243 return box(GC) spanned(lo, hi, StmtDecl(
3244 box(GC) spanned(lo, hi, DeclItem(
3246 lo, hi, id /*id is good here*/,
3247 ItemMac(spanned(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT))),
3248 Inherited, Vec::new(/*no attrs*/)))),
3249 ast::DUMMY_NODE_ID));
3253 let found_attrs = !item_attrs.is_empty();
3254 match self.parse_item_or_view_item(item_attrs, false) {
3257 let decl = box(GC) spanned(lo, hi, DeclItem(i));
3258 return box(GC) spanned(lo, hi, StmtDecl(decl, ast::DUMMY_NODE_ID));
3260 IoviViewItem(vi) => {
3261 self.span_fatal(vi.span,
3262 "view items must be declared at the top of the block");
3264 IoviForeignItem(_) => {
3265 self.fatal("foreign items are not allowed here");
3267 IoviNone(_) => { /* fallthrough */ }
3270 check_expected_item(self, found_attrs);
3272 // Remainder are line-expr stmts.
3273 let e = self.parse_expr_res(RESTRICT_STMT_EXPR);
3274 return box(GC) spanned(lo, e.span.hi, StmtExpr(e, ast::DUMMY_NODE_ID));
3278 // is this expression a successfully-parsed statement?
3279 fn expr_is_complete(&mut self, e: Gc<Expr>) -> bool {
3280 return self.restriction == RESTRICT_STMT_EXPR &&
3281 !classify::expr_requires_semi_to_be_stmt(e);
3284 // parse a block. No inner attrs are allowed.
3285 pub fn parse_block(&mut self) -> P<Block> {
3286 maybe_whole!(no_clone self, NtBlock);
3288 let lo = self.span.lo;
3289 self.expect(&token::LBRACE);
3291 return self.parse_block_tail_(lo, DefaultBlock, Vec::new());
3294 // parse a block. Inner attrs are allowed.
3295 fn parse_inner_attrs_and_block(&mut self)
3296 -> (Vec<Attribute> , P<Block>) {
3298 maybe_whole!(pair_empty self, NtBlock);
3300 let lo = self.span.lo;
3301 self.expect(&token::LBRACE);
3302 let (inner, next) = self.parse_inner_attrs_and_next();
3304 (inner, self.parse_block_tail_(lo, DefaultBlock, next))
3307 // Precondition: already parsed the '{' or '#{'
3308 // I guess that also means "already parsed the 'impure'" if
3309 // necessary, and this should take a qualifier.
3310 // some blocks start with "#{"...
3311 fn parse_block_tail(&mut self, lo: BytePos, s: BlockCheckMode) -> P<Block> {
3312 self.parse_block_tail_(lo, s, Vec::new())
3315 // parse the rest of a block expression or function body
3316 fn parse_block_tail_(&mut self, lo: BytePos, s: BlockCheckMode,
3317 first_item_attrs: Vec<Attribute> ) -> P<Block> {
3318 let mut stmts = Vec::new();
3319 let mut expr = None;
3321 // wouldn't it be more uniform to parse view items only, here?
3322 let ParsedItemsAndViewItems {
3323 attrs_remaining: attrs_remaining,
3324 view_items: view_items,
3327 } = self.parse_items_and_view_items(first_item_attrs,
3330 for item in items.iter() {
3331 let decl = box(GC) spanned(item.span.lo, item.span.hi, DeclItem(*item));
3332 stmts.push(box(GC) spanned(item.span.lo, item.span.hi,
3333 StmtDecl(decl, ast::DUMMY_NODE_ID)));
3336 let mut attributes_box = attrs_remaining;
3338 while self.token != token::RBRACE {
3339 // parsing items even when they're not allowed lets us give
3340 // better error messages and recover more gracefully.
3341 attributes_box.push_all(self.parse_outer_attributes().as_slice());
3344 if !attributes_box.is_empty() {
3345 let last_span = self.last_span;
3346 self.span_err(last_span, "expected item after attributes");
3347 attributes_box = Vec::new();
3349 self.bump(); // empty
3352 // fall through and out.
3355 let stmt = self.parse_stmt(attributes_box);
3356 attributes_box = Vec::new();
3358 StmtExpr(e, stmt_id) => {
3359 // expression without semicolon
3360 if classify::stmt_ends_with_semi(&*stmt) {
3361 // Just check for errors and recover; do not eat semicolon yet.
3362 self.commit_stmt(stmt, &[], &[token::SEMI, token::RBRACE]);
3368 let span_with_semi = Span {
3370 hi: self.last_span.hi,
3371 expn_info: stmt.span.expn_info,
3373 stmts.push(box(GC) codemap::Spanned {
3374 node: StmtSemi(e, stmt_id),
3375 span: span_with_semi,
3386 StmtMac(ref m, _) => {
3387 // statement macro; might be an expr
3391 stmts.push(box(GC) codemap::Spanned {
3392 node: StmtMac((*m).clone(), true),
3397 // if a block ends in `m!(arg)` without
3398 // a `;`, it must be an expr
3400 self.mk_mac_expr(stmt.span.lo,
3409 _ => { // all other kinds of statements:
3410 stmts.push(stmt.clone());
3412 if classify::stmt_ends_with_semi(&*stmt) {
3413 self.commit_stmt_expecting(stmt, token::SEMI);
3421 if !attributes_box.is_empty() {
3422 let last_span = self.last_span;
3423 self.span_err(last_span, "expected item after attributes");
3426 let hi = self.span.hi;
3429 view_items: view_items,
3432 id: ast::DUMMY_NODE_ID,
3434 span: mk_sp(lo, hi),
3438 fn parse_unboxed_function_type(&mut self) -> UnboxedFnTy {
3439 let inputs = if self.eat(&token::OROR) {
3444 if self.token == token::BINOP(token::AND) &&
3445 self.look_ahead(1, |t| {
3446 token::is_keyword(keywords::Mut, t)
3448 self.look_ahead(2, |t| *t == token::COLON) {
3454 let inputs = self.parse_seq_to_before_or(&token::COMMA,
3456 p.parse_arg_general(false)
3462 let (return_style, output) = self.parse_ret_ty();
3473 // matches bounds = ( boundseq )?
3474 // where boundseq = ( bound + boundseq ) | bound
3475 // and bound = 'static | ty
3476 // Returns "None" if there's no colon (e.g. "T");
3477 // Returns "Some(Empty)" if there's a colon but nothing after (e.g. "T:")
3478 // Returns "Some(stuff)" otherwise (e.g. "T:stuff").
3479 // NB: The None/Some distinction is important for issue #7264.
3481 // Note that the `allow_any_lifetime` argument is a hack for now while the
3482 // AST doesn't support arbitrary lifetimes in bounds on type parameters. In
3483 // the future, this flag should be removed, and the return value of this
3484 // function should be Option<~[TyParamBound]>
3485 fn parse_ty_param_bounds(&mut self, allow_any_lifetime: bool)
3486 -> (Option<ast::Lifetime>,
3487 OwnedSlice<TyParamBound>) {
3488 let mut ret_lifetime = None;
3489 let mut result = vec!();
3492 token::LIFETIME(lifetime) => {
3493 let lifetime_interned_string = token::get_ident(lifetime);
3494 if lifetime_interned_string.equiv(&("'static")) {
3495 result.push(StaticRegionTyParamBound);
3496 if allow_any_lifetime && ret_lifetime.is_none() {
3497 ret_lifetime = Some(ast::Lifetime {
3498 id: ast::DUMMY_NODE_ID,
3503 } else if allow_any_lifetime && ret_lifetime.is_none() {
3504 ret_lifetime = Some(ast::Lifetime {
3505 id: ast::DUMMY_NODE_ID,
3510 result.push(OtherRegionTyParamBound(self.span));
3514 token::MOD_SEP | token::IDENT(..) => {
3515 let tref = self.parse_trait_ref();
3516 result.push(TraitTyParamBound(tref));
3518 token::BINOP(token::OR) | token::OROR => {
3519 let unboxed_function_type =
3520 self.parse_unboxed_function_type();
3521 result.push(UnboxedFnTyParamBound(unboxed_function_type));
3526 if !self.eat(&token::BINOP(token::PLUS)) {
3531 return (ret_lifetime, OwnedSlice::from_vec(result));
3534 // matches typaram = type? IDENT optbounds ( EQ ty )?
3535 fn parse_ty_param(&mut self) -> TyParam {
3536 let sized = self.parse_sized();
3537 let span = self.span;
3538 let ident = self.parse_ident();
3540 if self.eat(&token::COLON) {
3541 let (_, bounds) = self.parse_ty_param_bounds(false);
3547 // For typarams we don't care about the difference b/w "<T>" and "<T:>".
3548 let bounds = opt_bounds.unwrap_or_default();
3550 let default = if self.token == token::EQ {
3552 Some(self.parse_ty(true))
3558 id: ast::DUMMY_NODE_ID,
3566 // parse a set of optional generic type parameter declarations
3567 // matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
3568 // | ( < lifetimes , typaramseq ( , )? > )
3569 // where typaramseq = ( typaram ) | ( typaram , typaramseq )
3570 pub fn parse_generics(&mut self) -> ast::Generics {
3571 if self.eat(&token::LT) {
3572 let lifetimes = self.parse_lifetimes();
3573 let mut seen_default = false;
3574 let ty_params = self.parse_seq_to_gt(Some(token::COMMA), |p| {
3575 p.forbid_lifetime();
3576 let ty_param = p.parse_ty_param();
3577 if ty_param.default.is_some() {
3578 seen_default = true;
3579 } else if seen_default {
3580 let last_span = p.last_span;
3581 p.span_err(last_span,
3582 "type parameters with a default must be trailing");
3586 ast::Generics { lifetimes: lifetimes, ty_params: ty_params }
3588 ast_util::empty_generics()
3592 fn parse_generic_values_after_lt(&mut self) -> (Vec<ast::Lifetime>, Vec<P<Ty>> ) {
3593 let lifetimes = self.parse_lifetimes();
3594 let result = self.parse_seq_to_gt(
3597 p.forbid_lifetime();
3601 (lifetimes, result.into_vec())
3604 fn forbid_lifetime(&mut self) {
3605 if Parser::token_is_lifetime(&self.token) {
3606 let span = self.span;
3607 self.span_fatal(span, "lifetime parameters must be declared \
3608 prior to type parameters");
3612 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
3613 -> (Vec<Arg> , bool) {
3615 let mut args: Vec<Option<Arg>> =
3616 self.parse_unspanned_seq(
3619 seq_sep_trailing_allowed(token::COMMA),
3621 if p.token == token::DOTDOTDOT {
3624 if p.token != token::RPAREN {
3627 "`...` must be last in argument list for variadic function");
3632 "only foreign functions are allowed to be variadic");
3636 Some(p.parse_arg_general(named_args))
3641 let variadic = match args.pop() {
3644 // Need to put back that last arg
3651 if variadic && args.is_empty() {
3653 "variadic function must be declared with at least one named argument");
3656 let args = args.move_iter().map(|x| x.unwrap()).collect();
3661 // parse the argument list and result type of a function declaration
3662 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> P<FnDecl> {
3664 let (args, variadic) = self.parse_fn_args(true, allow_variadic);
3665 let (ret_style, ret_ty) = self.parse_ret_ty();
3675 fn is_self_ident(&mut self) -> bool {
3677 token::IDENT(id, false) => id.name == special_idents::self_.name,
3682 fn expect_self_ident(&mut self) {
3683 if !self.is_self_ident() {
3684 let token_str = self.this_token_to_str();
3685 self.fatal(format!("expected `self` but found `{}`",
3686 token_str).as_slice())
3691 // parse the argument list and result type of a function
3692 // that may have a self type.
3693 fn parse_fn_decl_with_self(&mut self, parse_arg_fn: |&mut Parser| -> Arg)
3694 -> (ExplicitSelf, P<FnDecl>) {
3695 fn maybe_parse_borrowed_explicit_self(this: &mut Parser)
3696 -> ast::ExplicitSelf_ {
3697 // The following things are possible to see here:
3702 // fn(&'lt mut self)
3704 // We already know that the current token is `&`.
3706 if this.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) {
3708 this.expect_self_ident();
3709 SelfRegion(None, MutImmutable)
3710 } else if this.look_ahead(1, |t| Parser::token_is_mutability(t)) &&
3712 |t| token::is_keyword(keywords::Self,
3715 let mutability = this.parse_mutability();
3716 this.expect_self_ident();
3717 SelfRegion(None, mutability)
3718 } else if this.look_ahead(1, |t| Parser::token_is_lifetime(t)) &&
3720 |t| token::is_keyword(keywords::Self,
3723 let lifetime = this.parse_lifetime();
3724 this.expect_self_ident();
3725 SelfRegion(Some(lifetime), MutImmutable)
3726 } else if this.look_ahead(1, |t| Parser::token_is_lifetime(t)) &&
3727 this.look_ahead(2, |t| {
3728 Parser::token_is_mutability(t)
3730 this.look_ahead(3, |t| token::is_keyword(keywords::Self,
3733 let lifetime = this.parse_lifetime();
3734 let mutability = this.parse_mutability();
3735 this.expect_self_ident();
3736 SelfRegion(Some(lifetime), mutability)
3742 self.expect(&token::LPAREN);
3744 // A bit of complexity and lookahead is needed here in order to be
3745 // backwards compatible.
3746 let lo = self.span.lo;
3747 let mut mutbl_self = MutImmutable;
3748 let explicit_self = match self.token {
3749 token::BINOP(token::AND) => {
3750 maybe_parse_borrowed_explicit_self(self)
3753 // We need to make sure it isn't a type
3754 if self.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) {
3756 self.expect_self_ident();
3762 token::IDENT(..) if self.is_self_ident() => {
3766 token::BINOP(token::STAR) => {
3767 // Possibly "*self" or "*mut self" -- not supported. Try to avoid
3768 // emitting cryptic "unexpected token" errors.
3770 let _mutability = if Parser::token_is_mutability(&self.token) {
3771 self.parse_mutability()
3772 } else { MutImmutable };
3773 if self.is_self_ident() {
3774 let span = self.span;
3775 self.span_err(span, "cannot pass self by unsafe pointer");
3780 _ if Parser::token_is_mutability(&self.token) &&
3781 self.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) => {
3782 mutbl_self = self.parse_mutability();
3783 self.expect_self_ident();
3786 _ if Parser::token_is_mutability(&self.token) &&
3787 self.look_ahead(1, |t| *t == token::TILDE) &&
3788 self.look_ahead(2, |t| token::is_keyword(keywords::Self, t)) => {
3789 mutbl_self = self.parse_mutability();
3791 self.expect_self_ident();
3797 let explicit_self_sp = mk_sp(lo, self.span.hi);
3799 // If we parsed a self type, expect a comma before the argument list.
3800 let fn_inputs = if explicit_self != SelfStatic {
3804 let sep = seq_sep_trailing_disallowed(token::COMMA);
3805 let mut fn_inputs = self.parse_seq_to_before_end(
3810 fn_inputs.unshift(Arg::new_self(explicit_self_sp, mutbl_self));
3814 vec!(Arg::new_self(explicit_self_sp, mutbl_self))
3817 let token_str = self.this_token_to_str();
3818 self.fatal(format!("expected `,` or `)`, found `{}`",
3819 token_str).as_slice())
3823 let sep = seq_sep_trailing_disallowed(token::COMMA);
3824 self.parse_seq_to_before_end(&token::RPAREN, sep, parse_arg_fn)
3827 self.expect(&token::RPAREN);
3829 let hi = self.span.hi;
3831 let (ret_style, ret_ty) = self.parse_ret_ty();
3833 let fn_decl = P(FnDecl {
3840 (spanned(lo, hi, explicit_self), fn_decl)
3843 // parse the |arg, arg| header on a lambda
3844 fn parse_fn_block_decl(&mut self) -> P<FnDecl> {
3845 let inputs_captures = {
3846 if self.eat(&token::OROR) {
3849 self.parse_unspanned_seq(
3850 &token::BINOP(token::OR),
3851 &token::BINOP(token::OR),
3852 seq_sep_trailing_disallowed(token::COMMA),
3853 |p| p.parse_fn_block_arg()
3857 let output = if self.eat(&token::RARROW) {
3861 id: ast::DUMMY_NODE_ID,
3868 inputs: inputs_captures,
3875 // Parses the `(arg, arg) -> return_type` header on a procedure.
3876 fn parse_proc_decl(&mut self) -> P<FnDecl> {
3878 self.parse_unspanned_seq(&token::LPAREN,
3880 seq_sep_trailing_allowed(token::COMMA),
3881 |p| p.parse_fn_block_arg());
3883 let output = if self.eat(&token::RARROW) {
3887 id: ast::DUMMY_NODE_ID,
3901 // parse the name and optional generic types of a function header.
3902 fn parse_fn_header(&mut self) -> (Ident, ast::Generics) {
3903 let id = self.parse_ident();
3904 let generics = self.parse_generics();
3908 fn mk_item(&mut self, lo: BytePos, hi: BytePos, ident: Ident,
3909 node: Item_, vis: Visibility,
3910 attrs: Vec<Attribute>) -> Gc<Item> {
3914 id: ast::DUMMY_NODE_ID,
3921 // parse an item-position function declaration.
3922 fn parse_item_fn(&mut self, fn_style: FnStyle, abi: abi::Abi) -> ItemInfo {
3923 let (ident, generics) = self.parse_fn_header();
3924 let decl = self.parse_fn_decl(false);
3925 let (inner_attrs, body) = self.parse_inner_attrs_and_block();
3926 (ident, ItemFn(decl, fn_style, abi, generics, body), Some(inner_attrs))
3929 // parse a method in a trait impl, starting with `attrs` attributes.
3930 fn parse_method(&mut self,
3931 already_parsed_attrs: Option<Vec<Attribute>>) -> Gc<Method> {
3932 let next_attrs = self.parse_outer_attributes();
3933 let attrs = match already_parsed_attrs {
3934 Some(mut a) => { a.push_all_move(next_attrs); a }
3938 let lo = self.span.lo;
3940 let visa = self.parse_visibility();
3941 let fn_style = self.parse_fn_style();
3942 let ident = self.parse_ident();
3943 let generics = self.parse_generics();
3944 let (explicit_self, decl) = self.parse_fn_decl_with_self(|p| {
3948 let (inner_attrs, body) = self.parse_inner_attrs_and_block();
3949 let hi = body.span.hi;
3950 let attrs = attrs.append(inner_attrs.as_slice());
3951 box(GC) ast::Method {
3955 explicit_self: explicit_self,
3959 id: ast::DUMMY_NODE_ID,
3960 span: mk_sp(lo, hi),
3965 // parse trait Foo { ... }
3966 fn parse_item_trait(&mut self) -> ItemInfo {
3967 let ident = self.parse_ident();
3968 let tps = self.parse_generics();
3969 let sized = self.parse_for_sized();
3971 // Parse traits, if necessary.
3973 if self.token == token::COLON {
3975 traits = self.parse_trait_ref_list(&token::LBRACE);
3977 traits = Vec::new();
3980 let meths = self.parse_trait_methods();
3981 (ident, ItemTrait(tps, sized, traits, meths), None)
3984 // Parses two variants (with the region/type params always optional):
3985 // impl<T> Foo { ... }
3986 // impl<T> ToStr for ~[T] { ... }
3987 fn parse_item_impl(&mut self) -> ItemInfo {
3988 // First, parse type parameters if necessary.
3989 let generics = self.parse_generics();
3991 // Special case: if the next identifier that follows is '(', don't
3992 // allow this to be parsed as a trait.
3993 let could_be_trait = self.token != token::LPAREN;
3996 let mut ty = self.parse_ty(true);
3998 // Parse traits, if necessary.
3999 let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) {
4000 // New-style trait. Reinterpret the type as a trait.
4001 let opt_trait_ref = match ty.node {
4002 TyPath(ref path, None, node_id) => {
4004 path: /* bad */ (*path).clone(),
4009 self.span_err(ty.span,
4010 "bounded traits are only valid in type position");
4014 self.span_err(ty.span, "not a trait");
4019 ty = self.parse_ty(true);
4025 let mut meths = Vec::new();
4026 self.expect(&token::LBRACE);
4027 let (inner_attrs, next) = self.parse_inner_attrs_and_next();
4028 let mut method_attrs = Some(next);
4029 while !self.eat(&token::RBRACE) {
4030 meths.push(self.parse_method(method_attrs));
4031 method_attrs = None;
4034 let ident = ast_util::impl_pretty_name(&opt_trait, &*ty);
4036 (ident, ItemImpl(generics, opt_trait, ty, meths), Some(inner_attrs))
4039 // parse a::B<String,int>
4040 fn parse_trait_ref(&mut self) -> TraitRef {
4042 path: self.parse_path(LifetimeAndTypesWithoutColons).path,
4043 ref_id: ast::DUMMY_NODE_ID,
4047 // parse B + C<String,int> + D
4048 fn parse_trait_ref_list(&mut self, ket: &token::Token) -> Vec<TraitRef> {
4049 self.parse_seq_to_before_end(
4051 seq_sep_trailing_disallowed(token::BINOP(token::PLUS)),
4052 |p| p.parse_trait_ref()
4056 // parse struct Foo { ... }
4057 fn parse_item_struct(&mut self, is_virtual: bool) -> ItemInfo {
4058 let class_name = self.parse_ident();
4059 let generics = self.parse_generics();
4061 let super_struct = if self.eat(&token::COLON) {
4062 let ty = self.parse_ty(true);
4064 TyPath(_, None, _) => {
4068 self.span_err(ty.span, "not a struct");
4076 let mut fields: Vec<StructField>;
4079 if self.eat(&token::LBRACE) {
4080 // It's a record-like struct.
4081 is_tuple_like = false;
4082 fields = Vec::new();
4083 while self.token != token::RBRACE {
4084 fields.push(self.parse_struct_decl_field());
4086 if fields.len() == 0 {
4087 self.fatal(format!("unit-like struct definition should be \
4088 written as `struct {};`",
4089 token::get_ident(class_name)).as_slice());
4092 } else if self.token == token::LPAREN {
4093 // It's a tuple-like struct.
4094 is_tuple_like = true;
4095 fields = self.parse_unspanned_seq(
4098 seq_sep_trailing_allowed(token::COMMA),
4100 let attrs = p.parse_outer_attributes();
4102 let struct_field_ = ast::StructField_ {
4103 kind: UnnamedField(p.parse_visibility()),
4104 id: ast::DUMMY_NODE_ID,
4105 ty: p.parse_ty(true),
4108 spanned(lo, p.span.hi, struct_field_)
4110 self.expect(&token::SEMI);
4111 } else if self.eat(&token::SEMI) {
4112 // It's a unit-like struct.
4113 is_tuple_like = true;
4114 fields = Vec::new();
4116 let token_str = self.this_token_to_str();
4117 self.fatal(format!("expected `{}`, `(`, or `;` after struct \
4118 name but found `{}`", "{",
4119 token_str).as_slice())
4122 let _ = ast::DUMMY_NODE_ID; // FIXME: Workaround for crazy bug.
4123 let new_id = ast::DUMMY_NODE_ID;
4125 ItemStruct(box(GC) ast::StructDef {
4127 ctor_id: if is_tuple_like { Some(new_id) } else { None },
4128 super_struct: super_struct,
4129 is_virtual: is_virtual,
4134 // parse a structure field declaration
4135 pub fn parse_single_struct_field(&mut self,
4137 attrs: Vec<Attribute> )
4139 let a_var = self.parse_name_and_ty(vis, attrs);
4146 let span = self.span;
4147 let token_str = self.this_token_to_str();
4148 self.span_fatal(span,
4149 format!("expected `,`, or `}}` but found `{}`",
4150 token_str).as_slice())
4156 // parse an element of a struct definition
4157 fn parse_struct_decl_field(&mut self) -> StructField {
4159 let attrs = self.parse_outer_attributes();
4161 if self.eat_keyword(keywords::Pub) {
4162 return self.parse_single_struct_field(Public, attrs);
4165 return self.parse_single_struct_field(Inherited, attrs);
4168 // parse visiility: PUB, PRIV, or nothing
4169 fn parse_visibility(&mut self) -> Visibility {
4170 if self.eat_keyword(keywords::Pub) { Public }
4174 fn parse_sized(&mut self) -> Sized {
4175 if self.eat_keyword(keywords::Type) { DynSize }
4179 fn parse_for_sized(&mut self) -> Sized {
4180 if self.eat_keyword(keywords::For) {
4181 if !self.eat_keyword(keywords::Type) {
4182 let last_span = self.last_span;
4183 self.span_err(last_span,
4184 "expected 'type' after for in trait item");
4192 // given a termination token and a vector of already-parsed
4193 // attributes (of length 0 or 1), parse all of the items in a module
4194 fn parse_mod_items(&mut self,
4196 first_item_attrs: Vec<Attribute>,
4199 // parse all of the items up to closing or an attribute.
4200 // view items are legal here.
4201 let ParsedItemsAndViewItems {
4202 attrs_remaining: attrs_remaining,
4203 view_items: view_items,
4204 items: starting_items,
4206 } = self.parse_items_and_view_items(first_item_attrs, true, true);
4207 let mut items: Vec<Gc<Item>> = starting_items;
4208 let attrs_remaining_len = attrs_remaining.len();
4210 // don't think this other loop is even necessary....
4212 let mut first = true;
4213 while self.token != term {
4214 let mut attrs = self.parse_outer_attributes();
4216 attrs = attrs_remaining.clone().append(attrs.as_slice());
4219 debug!("parse_mod_items: parse_item_or_view_item(attrs={:?})",
4221 match self.parse_item_or_view_item(attrs,
4222 true /* macros allowed */) {
4223 IoviItem(item) => items.push(item),
4224 IoviViewItem(view_item) => {
4225 self.span_fatal(view_item.span,
4226 "view items must be declared at the top of \
4230 let token_str = self.this_token_to_str();
4231 self.fatal(format!("expected item but found `{}`",
4232 token_str).as_slice())
4237 if first && attrs_remaining_len > 0u {
4238 // We parsed attributes for the first item but didn't find it
4239 let last_span = self.last_span;
4240 self.span_err(last_span, "expected item after attributes");
4244 inner: mk_sp(inner_lo, self.span.lo),
4245 view_items: view_items,
4250 fn parse_item_const(&mut self) -> ItemInfo {
4251 let m = if self.eat_keyword(keywords::Mut) {MutMutable} else {MutImmutable};
4252 let id = self.parse_ident();
4253 self.expect(&token::COLON);
4254 let ty = self.parse_ty(true);
4255 self.expect(&token::EQ);
4256 let e = self.parse_expr();
4257 self.commit_expr_expecting(e, token::SEMI);
4258 (id, ItemStatic(ty, m, e), None)
4261 // parse a `mod <foo> { ... }` or `mod <foo>;` item
4262 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> ItemInfo {
4263 let id_span = self.span;
4264 let id = self.parse_ident();
4265 if self.token == token::SEMI {
4267 // This mod is in an external file. Let's go get it!
4268 let (m, attrs) = self.eval_src_mod(id, outer_attrs, id_span);
4269 (id, m, Some(attrs))
4271 self.push_mod_path(id, outer_attrs);
4272 self.expect(&token::LBRACE);
4273 let mod_inner_lo = self.span.lo;
4274 let old_owns_directory = self.owns_directory;
4275 self.owns_directory = true;
4276 let (inner, next) = self.parse_inner_attrs_and_next();
4277 let m = self.parse_mod_items(token::RBRACE, next, mod_inner_lo);
4278 self.expect(&token::RBRACE);
4279 self.owns_directory = old_owns_directory;
4280 self.pop_mod_path();
4281 (id, ItemMod(m), Some(inner))
4285 fn push_mod_path(&mut self, id: Ident, attrs: &[Attribute]) {
4286 let default_path = self.id_to_interned_str(id);
4287 let file_path = match ::attr::first_attr_value_str_by_name(attrs,
4290 None => default_path,
4292 self.mod_path_stack.push(file_path)
4295 fn pop_mod_path(&mut self) {
4296 self.mod_path_stack.pop().unwrap();
4299 // read a module from a source file.
4300 fn eval_src_mod(&mut self,
4302 outer_attrs: &[ast::Attribute],
4304 -> (ast::Item_, Vec<ast::Attribute> ) {
4305 let mut prefix = Path::new(self.sess.span_diagnostic.cm.span_to_filename(self.span));
4307 let mod_path = Path::new(".").join_many(self.mod_path_stack.as_slice());
4308 let dir_path = prefix.join(&mod_path);
4309 let mod_string = token::get_ident(id);
4310 let (file_path, owns_directory) = match ::attr::first_attr_value_str_by_name(
4311 outer_attrs, "path") {
4312 Some(d) => (dir_path.join(d), true),
4314 let mod_name = mod_string.get().to_string();
4315 let default_path_str = format!("{}.rs", mod_name);
4316 let secondary_path_str = format!("{}/mod.rs", mod_name);
4317 let default_path = dir_path.join(default_path_str.as_slice());
4318 let secondary_path = dir_path.join(secondary_path_str.as_slice());
4319 let default_exists = default_path.exists();
4320 let secondary_exists = secondary_path.exists();
4322 if !self.owns_directory {
4323 self.span_err(id_sp,
4324 "cannot declare a new module at this location");
4325 let this_module = match self.mod_path_stack.last() {
4326 Some(name) => name.get().to_string(),
4327 None => self.root_module_name.get_ref().clone(),
4329 self.span_note(id_sp,
4330 format!("maybe move this module `{0}` \
4331 to its own directory via \
4333 this_module).as_slice());
4334 if default_exists || secondary_exists {
4335 self.span_note(id_sp,
4336 format!("... or maybe `use` the module \
4337 `{}` instead of possibly \
4339 mod_name).as_slice());
4341 self.abort_if_errors();
4344 match (default_exists, secondary_exists) {
4345 (true, false) => (default_path, false),
4346 (false, true) => (secondary_path, true),
4348 self.span_fatal(id_sp,
4349 format!("file not found for module \
4351 mod_name).as_slice());
4356 format!("file for module `{}` found at both {} \
4360 secondary_path_str).as_slice());
4366 self.eval_src_mod_from_path(file_path, owns_directory,
4367 mod_string.get().to_string(), id_sp)
4370 fn eval_src_mod_from_path(&mut self,
4372 owns_directory: bool,
4374 id_sp: Span) -> (ast::Item_, Vec<ast::Attribute> ) {
4375 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
4376 match included_mod_stack.iter().position(|p| *p == path) {
4378 let mut err = String::from_str("circular modules: ");
4379 let len = included_mod_stack.len();
4380 for p in included_mod_stack.slice(i, len).iter() {
4381 err.push_str(p.display().as_maybe_owned().as_slice());
4382 err.push_str(" -> ");
4384 err.push_str(path.display().as_maybe_owned().as_slice());
4385 self.span_fatal(id_sp, err.as_slice());
4389 included_mod_stack.push(path.clone());
4390 drop(included_mod_stack);
4393 new_sub_parser_from_file(self.sess,
4399 let mod_inner_lo = p0.span.lo;
4400 let (mod_attrs, next) = p0.parse_inner_attrs_and_next();
4401 let first_item_outer_attrs = next;
4402 let m0 = p0.parse_mod_items(token::EOF, first_item_outer_attrs, mod_inner_lo);
4403 self.sess.included_mod_stack.borrow_mut().pop();
4404 return (ast::ItemMod(m0), mod_attrs);
4407 // parse a function declaration from a foreign module
4408 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility,
4409 attrs: Vec<Attribute>) -> Gc<ForeignItem> {
4410 let lo = self.span.lo;
4411 self.expect_keyword(keywords::Fn);
4413 let (ident, generics) = self.parse_fn_header();
4414 let decl = self.parse_fn_decl(true);
4415 let hi = self.span.hi;
4416 self.expect(&token::SEMI);
4417 box(GC) ast::ForeignItem { ident: ident,
4419 node: ForeignItemFn(decl, generics),
4420 id: ast::DUMMY_NODE_ID,
4421 span: mk_sp(lo, hi),
4425 // parse a static item from a foreign module
4426 fn parse_item_foreign_static(&mut self, vis: ast::Visibility,
4427 attrs: Vec<Attribute> ) -> Gc<ForeignItem> {
4428 let lo = self.span.lo;
4430 self.expect_keyword(keywords::Static);
4431 let mutbl = self.eat_keyword(keywords::Mut);
4433 let ident = self.parse_ident();
4434 self.expect(&token::COLON);
4435 let ty = self.parse_ty(true);
4436 let hi = self.span.hi;
4437 self.expect(&token::SEMI);
4438 box(GC) ast::ForeignItem {
4441 node: ForeignItemStatic(ty, mutbl),
4442 id: ast::DUMMY_NODE_ID,
4443 span: mk_sp(lo, hi),
4448 // parse safe/unsafe and fn
4449 fn parse_fn_style(&mut self) -> FnStyle {
4450 if self.eat_keyword(keywords::Fn) { NormalFn }
4451 else if self.eat_keyword(keywords::Unsafe) {
4452 self.expect_keyword(keywords::Fn);
4455 else { self.unexpected(); }
4459 // at this point, this is essentially a wrapper for
4460 // parse_foreign_items.
4461 fn parse_foreign_mod_items(&mut self,
4463 first_item_attrs: Vec<Attribute> )
4465 let ParsedItemsAndViewItems {
4466 attrs_remaining: attrs_remaining,
4467 view_items: view_items,
4469 foreign_items: foreign_items
4470 } = self.parse_foreign_items(first_item_attrs, true);
4471 if ! attrs_remaining.is_empty() {
4472 let last_span = self.last_span;
4473 self.span_err(last_span,
4474 "expected item after attributes");
4476 assert!(self.token == token::RBRACE);
4479 view_items: view_items,
4480 items: foreign_items
4484 /// Parse extern crate links
4488 /// extern crate url;
4489 /// extern crate foo = "bar";
4490 fn parse_item_extern_crate(&mut self,
4492 visibility: Visibility,
4493 attrs: Vec<Attribute> )
4496 let (maybe_path, ident) = match self.token {
4497 token::IDENT(..) => {
4498 let the_ident = self.parse_ident();
4499 self.expect_one_of(&[], &[token::EQ, token::SEMI]);
4500 let path = if self.token == token::EQ {
4502 Some(self.parse_str())
4505 self.expect(&token::SEMI);
4509 let span = self.span;
4510 let token_str = self.this_token_to_str();
4511 self.span_fatal(span,
4512 format!("expected extern crate name but \
4514 token_str).as_slice());
4518 IoviViewItem(ast::ViewItem {
4519 node: ViewItemExternCrate(ident, maybe_path, ast::DUMMY_NODE_ID),
4522 span: mk_sp(lo, self.last_span.hi)
4526 /// Parse `extern` for foreign ABIs
4529 /// `extern` is expected to have been
4530 /// consumed before calling this method
4536 fn parse_item_foreign_mod(&mut self,
4538 opt_abi: Option<abi::Abi>,
4539 visibility: Visibility,
4540 attrs: Vec<Attribute> )
4543 self.expect(&token::LBRACE);
4545 let abi = opt_abi.unwrap_or(abi::C);
4547 let (inner, next) = self.parse_inner_attrs_and_next();
4548 let m = self.parse_foreign_mod_items(abi, next);
4549 self.expect(&token::RBRACE);
4551 let last_span = self.last_span;
4552 let item = self.mk_item(lo,
4554 special_idents::invalid,
4557 maybe_append(attrs, Some(inner)));
4558 return IoviItem(item);
4561 // parse type Foo = Bar;
4562 fn parse_item_type(&mut self) -> ItemInfo {
4563 let ident = self.parse_ident();
4564 let tps = self.parse_generics();
4565 self.expect(&token::EQ);
4566 let ty = self.parse_ty(true);
4567 self.expect(&token::SEMI);
4568 (ident, ItemTy(ty, tps), None)
4571 // parse a structure-like enum variant definition
4572 // this should probably be renamed or refactored...
4573 fn parse_struct_def(&mut self) -> Gc<StructDef> {
4574 let mut fields: Vec<StructField> = Vec::new();
4575 while self.token != token::RBRACE {
4576 fields.push(self.parse_struct_decl_field());
4580 return box(GC) ast::StructDef {
4588 // parse the part of an "enum" decl following the '{'
4589 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> EnumDef {
4590 let mut variants = Vec::new();
4591 let mut all_nullary = true;
4592 let mut have_disr = false;
4593 while self.token != token::RBRACE {
4594 let variant_attrs = self.parse_outer_attributes();
4595 let vlo = self.span.lo;
4597 let vis = self.parse_visibility();
4601 let mut args = Vec::new();
4602 let mut disr_expr = None;
4603 ident = self.parse_ident();
4604 if self.eat(&token::LBRACE) {
4605 // Parse a struct variant.
4606 all_nullary = false;
4607 kind = StructVariantKind(self.parse_struct_def());
4608 } else if self.token == token::LPAREN {
4609 all_nullary = false;
4610 let arg_tys = self.parse_enum_variant_seq(
4613 seq_sep_trailing_disallowed(token::COMMA),
4614 |p| p.parse_ty(true)
4616 for ty in arg_tys.move_iter() {
4617 args.push(ast::VariantArg {
4619 id: ast::DUMMY_NODE_ID,
4622 kind = TupleVariantKind(args);
4623 } else if self.eat(&token::EQ) {
4625 disr_expr = Some(self.parse_expr());
4626 kind = TupleVariantKind(args);
4628 kind = TupleVariantKind(Vec::new());
4631 let vr = ast::Variant_ {
4633 attrs: variant_attrs,
4635 id: ast::DUMMY_NODE_ID,
4636 disr_expr: disr_expr,
4639 variants.push(P(spanned(vlo, self.last_span.hi, vr)));
4641 if !self.eat(&token::COMMA) { break; }
4643 self.expect(&token::RBRACE);
4644 if have_disr && !all_nullary {
4645 self.fatal("discriminator values can only be used with a c-like \
4649 ast::EnumDef { variants: variants }
4652 // parse an "enum" declaration
4653 fn parse_item_enum(&mut self) -> ItemInfo {
4654 let id = self.parse_ident();
4655 let generics = self.parse_generics();
4656 self.expect(&token::LBRACE);
4658 let enum_definition = self.parse_enum_def(&generics);
4659 (id, ItemEnum(enum_definition, generics), None)
4662 fn fn_expr_lookahead(tok: &token::Token) -> bool {
4664 token::LPAREN | token::AT | token::TILDE | token::BINOP(_) => true,
4669 // Parses a string as an ABI spec on an extern type or module. Consumes
4670 // the `extern` keyword, if one is found.
4671 fn parse_opt_abi(&mut self) -> Option<abi::Abi> {
4673 token::LIT_STR(s) | token::LIT_STR_RAW(s, _) => {
4675 let identifier_string = token::get_ident(s);
4676 let the_string = identifier_string.get();
4677 match abi::lookup(the_string) {
4678 Some(abi) => Some(abi),
4680 let last_span = self.last_span;
4683 format!("illegal ABI: expected one of [{}], \
4685 abi::all_names().connect(", "),
4686 the_string).as_slice());
4696 // parse one of the items or view items allowed by the
4697 // flags; on failure, return IoviNone.
4698 // NB: this function no longer parses the items inside an
4700 fn parse_item_or_view_item(&mut self,
4701 attrs: Vec<Attribute> ,
4702 macros_allowed: bool)
4705 INTERPOLATED(token::NtItem(item)) => {
4707 let new_attrs = attrs.append(item.attrs.as_slice());
4708 return IoviItem(box(GC) Item {
4716 let lo = self.span.lo;
4718 let visibility = self.parse_visibility();
4720 // must be a view item:
4721 if self.eat_keyword(keywords::Use) {
4722 // USE ITEM (IoviViewItem)
4723 let view_item = self.parse_use();
4724 self.expect(&token::SEMI);
4725 return IoviViewItem(ast::ViewItem {
4729 span: mk_sp(lo, self.last_span.hi)
4732 // either a view item or an item:
4733 if self.eat_keyword(keywords::Extern) {
4734 let next_is_mod = self.eat_keyword(keywords::Mod);
4736 if next_is_mod || self.eat_keyword(keywords::Crate) {
4738 let last_span = self.last_span;
4739 self.span_err(mk_sp(lo, last_span.hi),
4740 format!("`extern mod` is obsolete, use \
4741 `extern crate` instead \
4742 to refer to external \
4743 crates.").as_slice())
4745 return self.parse_item_extern_crate(lo, visibility, attrs);
4748 let opt_abi = self.parse_opt_abi();
4750 if self.eat_keyword(keywords::Fn) {
4751 // EXTERN FUNCTION ITEM
4752 let abi = opt_abi.unwrap_or(abi::C);
4753 let (ident, item_, extra_attrs) =
4754 self.parse_item_fn(NormalFn, abi);
4755 let last_span = self.last_span;
4756 let item = self.mk_item(lo,
4761 maybe_append(attrs, extra_attrs));
4762 return IoviItem(item);
4763 } else if self.token == token::LBRACE {
4764 return self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs);
4767 let span = self.span;
4768 let token_str = self.this_token_to_str();
4769 self.span_fatal(span,
4770 format!("expected `{}` or `fn` but found `{}`", "{",
4771 token_str).as_slice());
4774 let is_virtual = self.eat_keyword(keywords::Virtual);
4775 if is_virtual && !self.is_keyword(keywords::Struct) {
4776 let span = self.span;
4778 "`virtual` keyword may only be used with `struct`");
4781 // the rest are all guaranteed to be items:
4782 if self.is_keyword(keywords::Static) {
4785 let (ident, item_, extra_attrs) = self.parse_item_const();
4786 let last_span = self.last_span;
4787 let item = self.mk_item(lo,
4792 maybe_append(attrs, extra_attrs));
4793 return IoviItem(item);
4795 if self.is_keyword(keywords::Fn) &&
4796 self.look_ahead(1, |f| !Parser::fn_expr_lookahead(f)) {
4799 let (ident, item_, extra_attrs) =
4800 self.parse_item_fn(NormalFn, abi::Rust);
4801 let last_span = self.last_span;
4802 let item = self.mk_item(lo,
4807 maybe_append(attrs, extra_attrs));
4808 return IoviItem(item);
4810 if self.is_keyword(keywords::Unsafe)
4811 && self.look_ahead(1u, |t| *t != token::LBRACE) {
4812 // UNSAFE FUNCTION ITEM
4814 let abi = if self.eat_keyword(keywords::Extern) {
4815 self.parse_opt_abi().unwrap_or(abi::C)
4819 self.expect_keyword(keywords::Fn);
4820 let (ident, item_, extra_attrs) =
4821 self.parse_item_fn(UnsafeFn, abi);
4822 let last_span = self.last_span;
4823 let item = self.mk_item(lo,
4828 maybe_append(attrs, extra_attrs));
4829 return IoviItem(item);
4831 if self.eat_keyword(keywords::Mod) {
4833 let (ident, item_, extra_attrs) =
4834 self.parse_item_mod(attrs.as_slice());
4835 let last_span = self.last_span;
4836 let item = self.mk_item(lo,
4841 maybe_append(attrs, extra_attrs));
4842 return IoviItem(item);
4844 if self.eat_keyword(keywords::Type) {
4846 let (ident, item_, extra_attrs) = self.parse_item_type();
4847 let last_span = self.last_span;
4848 let item = self.mk_item(lo,
4853 maybe_append(attrs, extra_attrs));
4854 return IoviItem(item);
4856 if self.eat_keyword(keywords::Enum) {
4858 let (ident, item_, extra_attrs) = self.parse_item_enum();
4859 let last_span = self.last_span;
4860 let item = self.mk_item(lo,
4865 maybe_append(attrs, extra_attrs));
4866 return IoviItem(item);
4868 if self.eat_keyword(keywords::Trait) {
4870 let (ident, item_, extra_attrs) = self.parse_item_trait();
4871 let last_span = self.last_span;
4872 let item = self.mk_item(lo,
4877 maybe_append(attrs, extra_attrs));
4878 return IoviItem(item);
4880 if self.eat_keyword(keywords::Impl) {
4882 let (ident, item_, extra_attrs) = self.parse_item_impl();
4883 let last_span = self.last_span;
4884 let item = self.mk_item(lo,
4889 maybe_append(attrs, extra_attrs));
4890 return IoviItem(item);
4892 if self.eat_keyword(keywords::Struct) {
4894 let (ident, item_, extra_attrs) = self.parse_item_struct(is_virtual);
4895 let last_span = self.last_span;
4896 let item = self.mk_item(lo,
4901 maybe_append(attrs, extra_attrs));
4902 return IoviItem(item);
4904 self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility)
4907 // parse a foreign item; on failure, return IoviNone.
4908 fn parse_foreign_item(&mut self,
4909 attrs: Vec<Attribute> ,
4910 macros_allowed: bool)
4912 maybe_whole!(iovi self, NtItem);
4913 let lo = self.span.lo;
4915 let visibility = self.parse_visibility();
4917 if self.is_keyword(keywords::Static) {
4918 // FOREIGN STATIC ITEM
4919 let item = self.parse_item_foreign_static(visibility, attrs);
4920 return IoviForeignItem(item);
4922 if self.is_keyword(keywords::Fn) || self.is_keyword(keywords::Unsafe) {
4923 // FOREIGN FUNCTION ITEM
4924 let item = self.parse_item_foreign_fn(visibility, attrs);
4925 return IoviForeignItem(item);
4927 self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility)
4930 // this is the fall-through for parsing items.
4931 fn parse_macro_use_or_failure(
4933 attrs: Vec<Attribute> ,
4934 macros_allowed: bool,
4936 visibility: Visibility
4937 ) -> ItemOrViewItem {
4938 if macros_allowed && !token::is_any_keyword(&self.token)
4939 && self.look_ahead(1, |t| *t == token::NOT)
4940 && (self.look_ahead(2, |t| is_plain_ident(t))
4941 || self.look_ahead(2, |t| *t == token::LPAREN)
4942 || self.look_ahead(2, |t| *t == token::LBRACE)) {
4943 // MACRO INVOCATION ITEM
4946 let pth = self.parse_path(NoTypesAllowed).path;
4947 self.expect(&token::NOT);
4949 // a 'special' identifier (like what `macro_rules!` uses)
4950 // is optional. We should eventually unify invoc syntax
4952 let id = if is_plain_ident(&self.token) {
4955 token::special_idents::invalid // no special identifier
4957 // eat a matched-delimiter token tree:
4958 let tts = match token::close_delimiter_for(&self.token) {
4961 self.parse_seq_to_end(&ket,
4963 |p| p.parse_token_tree())
4965 None => self.fatal("expected open delimiter")
4967 // single-variant-enum... :
4968 let m = ast::MacInvocTT(pth, tts, EMPTY_CTXT);
4969 let m: ast::Mac = codemap::Spanned { node: m,
4970 span: mk_sp(self.span.lo,
4972 let item_ = ItemMac(m);
4973 let last_span = self.last_span;
4974 let item = self.mk_item(lo,
4980 return IoviItem(item);
4983 // FAILURE TO PARSE ITEM
4984 if visibility != Inherited {
4985 let mut s = String::from_str("unmatched visibility `");
4986 if visibility == Public {
4992 let last_span = self.last_span;
4993 self.span_fatal(last_span, s.as_slice());
4995 return IoviNone(attrs);
4998 pub fn parse_item_with_outer_attributes(&mut self) -> Option<Gc<Item>> {
4999 let attrs = self.parse_outer_attributes();
5000 self.parse_item(attrs)
5003 pub fn parse_item(&mut self, attrs: Vec<Attribute> ) -> Option<Gc<Item>> {
5004 match self.parse_item_or_view_item(attrs, true) {
5005 IoviNone(_) => None,
5007 self.fatal("view items are not allowed here"),
5008 IoviForeignItem(_) =>
5009 self.fatal("foreign items are not allowed here"),
5010 IoviItem(item) => Some(item)
5014 // parse, e.g., "use a::b::{z,y}"
5015 fn parse_use(&mut self) -> ViewItem_ {
5016 return ViewItemUse(self.parse_view_path());
5020 // matches view_path : MOD? IDENT EQ non_global_path
5021 // | MOD? non_global_path MOD_SEP LBRACE RBRACE
5022 // | MOD? non_global_path MOD_SEP LBRACE ident_seq RBRACE
5023 // | MOD? non_global_path MOD_SEP STAR
5024 // | MOD? non_global_path
5025 fn parse_view_path(&mut self) -> Gc<ViewPath> {
5026 let lo = self.span.lo;
5028 if self.token == token::LBRACE {
5030 let idents = self.parse_unspanned_seq(
5031 &token::LBRACE, &token::RBRACE,
5032 seq_sep_trailing_allowed(token::COMMA),
5033 |p| p.parse_path_list_ident());
5034 let path = ast::Path {
5035 span: mk_sp(lo, self.span.hi),
5037 segments: Vec::new()
5039 return box(GC) spanned(lo, self.span.hi,
5040 ViewPathList(path, idents, ast::DUMMY_NODE_ID));
5043 let first_ident = self.parse_ident();
5044 let mut path = vec!(first_ident);
5049 let path_lo = self.span.lo;
5050 path = vec!(self.parse_ident());
5051 while self.token == token::MOD_SEP {
5053 let id = self.parse_ident();
5056 let path = ast::Path {
5057 span: mk_sp(path_lo, self.span.hi),
5059 segments: path.move_iter().map(|identifier| {
5061 identifier: identifier,
5062 lifetimes: Vec::new(),
5063 types: OwnedSlice::empty(),
5067 return box(GC) spanned(lo, self.span.hi,
5068 ViewPathSimple(first_ident, path,
5069 ast::DUMMY_NODE_ID));
5073 // foo::bar or foo::{a,b,c} or foo::*
5074 while self.token == token::MOD_SEP {
5078 token::IDENT(i, _) => {
5083 // foo::bar::{a,b,c}
5085 let idents = self.parse_unspanned_seq(
5088 seq_sep_trailing_allowed(token::COMMA),
5089 |p| p.parse_path_list_ident()
5091 let path = ast::Path {
5092 span: mk_sp(lo, self.span.hi),
5094 segments: path.move_iter().map(|identifier| {
5096 identifier: identifier,
5097 lifetimes: Vec::new(),
5098 types: OwnedSlice::empty(),
5102 return box(GC) spanned(lo, self.span.hi,
5103 ViewPathList(path, idents, ast::DUMMY_NODE_ID));
5107 token::BINOP(token::STAR) => {
5109 let path = ast::Path {
5110 span: mk_sp(lo, self.span.hi),
5112 segments: path.move_iter().map(|identifier| {
5114 identifier: identifier,
5115 lifetimes: Vec::new(),
5116 types: OwnedSlice::empty(),
5120 return box(GC) spanned(lo, self.span.hi,
5121 ViewPathGlob(path, ast::DUMMY_NODE_ID));
5130 let last = *path.get(path.len() - 1u);
5131 let path = ast::Path {
5132 span: mk_sp(lo, self.span.hi),
5134 segments: path.move_iter().map(|identifier| {
5136 identifier: identifier,
5137 lifetimes: Vec::new(),
5138 types: OwnedSlice::empty(),
5142 return box(GC) spanned(lo,
5144 ViewPathSimple(last, path, ast::DUMMY_NODE_ID));
5147 // Parses a sequence of items. Stops when it finds program
5148 // text that can't be parsed as an item
5149 // - mod_items uses extern_mod_allowed = true
5150 // - block_tail_ uses extern_mod_allowed = false
5151 fn parse_items_and_view_items(&mut self,
5152 first_item_attrs: Vec<Attribute> ,
5153 mut extern_mod_allowed: bool,
5154 macros_allowed: bool)
5155 -> ParsedItemsAndViewItems {
5156 let mut attrs = first_item_attrs.append(self.parse_outer_attributes().as_slice());
5157 // First, parse view items.
5158 let mut view_items : Vec<ast::ViewItem> = Vec::new();
5159 let mut items = Vec::new();
5161 // I think this code would probably read better as a single
5162 // loop with a mutable three-state-variable (for extern crates,
5163 // view items, and regular items) ... except that because
5164 // of macros, I'd like to delay that entire check until later.
5166 match self.parse_item_or_view_item(attrs, macros_allowed) {
5167 IoviNone(attrs) => {
5168 return ParsedItemsAndViewItems {
5169 attrs_remaining: attrs,
5170 view_items: view_items,
5172 foreign_items: Vec::new()
5175 IoviViewItem(view_item) => {
5176 match view_item.node {
5177 ViewItemUse(..) => {
5178 // `extern crate` must precede `use`.
5179 extern_mod_allowed = false;
5181 ViewItemExternCrate(..) if !extern_mod_allowed => {
5182 self.span_err(view_item.span,
5183 "\"extern crate\" declarations are \
5186 ViewItemExternCrate(..) => {}
5188 view_items.push(view_item);
5192 attrs = self.parse_outer_attributes();
5195 IoviForeignItem(_) => {
5199 attrs = self.parse_outer_attributes();
5202 // Next, parse items.
5204 match self.parse_item_or_view_item(attrs, macros_allowed) {
5205 IoviNone(returned_attrs) => {
5206 attrs = returned_attrs;
5209 IoviViewItem(view_item) => {
5210 attrs = self.parse_outer_attributes();
5211 self.span_err(view_item.span,
5212 "`use` and `extern crate` declarations must precede items");
5215 attrs = self.parse_outer_attributes();
5218 IoviForeignItem(_) => {
5224 ParsedItemsAndViewItems {
5225 attrs_remaining: attrs,
5226 view_items: view_items,
5228 foreign_items: Vec::new()
5232 // Parses a sequence of foreign items. Stops when it finds program
5233 // text that can't be parsed as an item
5234 fn parse_foreign_items(&mut self, first_item_attrs: Vec<Attribute> ,
5235 macros_allowed: bool)
5236 -> ParsedItemsAndViewItems {
5237 let mut attrs = first_item_attrs.append(self.parse_outer_attributes().as_slice());
5238 let mut foreign_items = Vec::new();
5240 match self.parse_foreign_item(attrs, macros_allowed) {
5241 IoviNone(returned_attrs) => {
5242 if self.token == token::RBRACE {
5243 attrs = returned_attrs;
5248 IoviViewItem(view_item) => {
5249 // I think this can't occur:
5250 self.span_err(view_item.span,
5251 "`use` and `extern crate` declarations must precede items");
5254 // FIXME #5668: this will occur for a macro invocation:
5255 self.span_fatal(item.span, "macros cannot expand to foreign items");
5257 IoviForeignItem(foreign_item) => {
5258 foreign_items.push(foreign_item);
5261 attrs = self.parse_outer_attributes();
5264 ParsedItemsAndViewItems {
5265 attrs_remaining: attrs,
5266 view_items: Vec::new(),
5268 foreign_items: foreign_items
5272 // Parses a source module as a crate. This is the main
5273 // entry point for the parser.
5274 pub fn parse_crate_mod(&mut self) -> Crate {
5275 let lo = self.span.lo;
5276 // parse the crate's inner attrs, maybe (oops) one
5277 // of the attrs of an item:
5278 let (inner, next) = self.parse_inner_attrs_and_next();
5279 let first_item_outer_attrs = next;
5280 // parse the items inside the crate:
5281 let m = self.parse_mod_items(token::EOF, first_item_outer_attrs, lo);
5286 config: self.cfg.clone(),
5287 span: mk_sp(lo, self.span.lo)
5291 pub fn parse_optional_str(&mut self)
5292 -> Option<(InternedString, ast::StrStyle)> {
5293 let (s, style) = match self.token {
5294 token::LIT_STR(s) => (self.id_to_interned_str(s), ast::CookedStr),
5295 token::LIT_STR_RAW(s, n) => {
5296 (self.id_to_interned_str(s), ast::RawStr(n))
5304 pub fn parse_str(&mut self) -> (InternedString, StrStyle) {
5305 match self.parse_optional_str() {
5307 _ => self.fatal("expected string literal")