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_mt())
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 is_named_argument(&mut self) -> bool {
1433 let offset = match self.token {
1434 token::BINOP(token::AND) => 1,
1436 _ if token::is_keyword(keywords::Mut, &self.token) => 1,
1440 debug!("parser is_named_argument offset:{}", offset);
1443 is_plain_ident_or_underscore(&self.token)
1444 && self.look_ahead(1, |t| *t == token::COLON)
1446 self.look_ahead(offset, |t| is_plain_ident_or_underscore(t))
1447 && self.look_ahead(offset + 1, |t| *t == token::COLON)
1451 // This version of parse arg doesn't necessarily require
1452 // identifier names.
1453 pub fn parse_arg_general(&mut self, require_name: bool) -> Arg {
1454 let pat = if require_name || self.is_named_argument() {
1455 debug!("parse_arg_general parse_pat (require_name:{:?})",
1457 let pat = self.parse_pat();
1459 self.expect(&token::COLON);
1462 debug!("parse_arg_general ident_to_pat");
1463 ast_util::ident_to_pat(ast::DUMMY_NODE_ID,
1465 special_idents::invalid)
1468 let t = self.parse_ty(true);
1473 id: ast::DUMMY_NODE_ID,
1477 // parse a single function argument
1478 pub fn parse_arg(&mut self) -> Arg {
1479 self.parse_arg_general(true)
1482 // parse an argument in a lambda header e.g. |arg, arg|
1483 pub fn parse_fn_block_arg(&mut self) -> Arg {
1484 let pat = self.parse_pat();
1485 let t = if self.eat(&token::COLON) {
1489 id: ast::DUMMY_NODE_ID,
1491 span: mk_sp(self.span.lo, self.span.hi),
1497 id: ast::DUMMY_NODE_ID
1501 pub fn maybe_parse_fixed_vstore(&mut self) -> Option<Gc<ast::Expr>> {
1502 if self.token == token::COMMA &&
1503 self.look_ahead(1, |t| *t == token::DOTDOT) {
1506 Some(self.parse_expr())
1512 // matches token_lit = LIT_INT | ...
1513 pub fn lit_from_token(&mut self, tok: &token::Token) -> Lit_ {
1515 token::LIT_CHAR(i) => LitChar(i),
1516 token::LIT_INT(i, it) => LitInt(i, it),
1517 token::LIT_UINT(u, ut) => LitUint(u, ut),
1518 token::LIT_INT_UNSUFFIXED(i) => LitIntUnsuffixed(i),
1519 token::LIT_FLOAT(s, ft) => {
1520 LitFloat(self.id_to_interned_str(s), ft)
1522 token::LIT_FLOAT_UNSUFFIXED(s) => {
1523 LitFloatUnsuffixed(self.id_to_interned_str(s))
1525 token::LIT_STR(s) => {
1526 LitStr(self.id_to_interned_str(s), ast::CookedStr)
1528 token::LIT_STR_RAW(s, n) => {
1529 LitStr(self.id_to_interned_str(s), ast::RawStr(n))
1531 token::LPAREN => { self.expect(&token::RPAREN); LitNil },
1532 _ => { self.unexpected_last(tok); }
1536 // matches lit = true | false | token_lit
1537 pub fn parse_lit(&mut self) -> Lit {
1538 let lo = self.span.lo;
1539 let lit = if self.eat_keyword(keywords::True) {
1541 } else if self.eat_keyword(keywords::False) {
1544 let token = self.bump_and_get();
1545 let lit = self.lit_from_token(&token);
1548 codemap::Spanned { node: lit, span: mk_sp(lo, self.last_span.hi) }
1551 // matches '-' lit | lit
1552 pub fn parse_literal_maybe_minus(&mut self) -> Gc<Expr> {
1553 let minus_lo = self.span.lo;
1554 let minus_present = self.eat(&token::BINOP(token::MINUS));
1556 let lo = self.span.lo;
1557 let literal = box(GC) self.parse_lit();
1558 let hi = self.span.hi;
1559 let expr = self.mk_expr(lo, hi, ExprLit(literal));
1562 let minus_hi = self.span.hi;
1563 let unary = self.mk_unary(UnNeg, expr);
1564 self.mk_expr(minus_lo, minus_hi, unary)
1570 /// Parses a path and optional type parameter bounds, depending on the
1571 /// mode. The `mode` parameter determines whether lifetimes, types, and/or
1572 /// bounds are permitted and whether `::` must precede type parameter
1574 pub fn parse_path(&mut self, mode: PathParsingMode) -> PathAndBounds {
1575 // Check for a whole path...
1576 let found = match self.token {
1577 INTERPOLATED(token::NtPath(_)) => Some(self.bump_and_get()),
1581 Some(INTERPOLATED(token::NtPath(box path))) => {
1582 return PathAndBounds {
1590 let lo = self.span.lo;
1591 let is_global = self.eat(&token::MOD_SEP);
1593 // Parse any number of segments and bound sets. A segment is an
1594 // identifier followed by an optional lifetime and a set of types.
1595 // A bound set is a set of type parameter bounds.
1596 let mut segments = Vec::new();
1598 // First, parse an identifier.
1599 let identifier = self.parse_ident();
1601 // Parse the '::' before type parameters if it's required. If
1602 // it is required and wasn't present, then we're done.
1603 if mode == LifetimeAndTypesWithColons &&
1604 !self.eat(&token::MOD_SEP) {
1605 segments.push(ast::PathSegment {
1606 identifier: identifier,
1607 lifetimes: Vec::new(),
1608 types: OwnedSlice::empty(),
1613 // Parse the `<` before the lifetime and types, if applicable.
1614 let (any_lifetime_or_types, lifetimes, types) = {
1615 if mode != NoTypesAllowed && self.eat_lt(false) {
1616 let (lifetimes, types) =
1617 self.parse_generic_values_after_lt();
1618 (true, lifetimes, OwnedSlice::from_vec(types))
1620 (false, Vec::new(), OwnedSlice::empty())
1624 // Assemble and push the result.
1625 segments.push(ast::PathSegment {
1626 identifier: identifier,
1627 lifetimes: lifetimes,
1631 // We're done if we don't see a '::', unless the mode required
1632 // a double colon to get here in the first place.
1633 if !(mode == LifetimeAndTypesWithColons &&
1634 !any_lifetime_or_types) {
1635 if !self.eat(&token::MOD_SEP) {
1641 // Next, parse a plus and bounded type parameters, if applicable.
1642 let bounds = if mode == LifetimeAndTypesAndBounds {
1644 if self.eat(&token::BINOP(token::PLUS)) {
1645 let (_, bounds) = self.parse_ty_param_bounds(false);
1656 // Assemble the span.
1657 let span = mk_sp(lo, self.last_span.hi);
1659 // Assemble the result.
1670 /// parses 0 or 1 lifetime
1671 pub fn parse_opt_lifetime(&mut self) -> Option<ast::Lifetime> {
1673 token::LIFETIME(..) => {
1674 Some(self.parse_lifetime())
1682 /// Parses a single lifetime
1683 // matches lifetime = LIFETIME
1684 pub fn parse_lifetime(&mut self) -> ast::Lifetime {
1686 token::LIFETIME(i) => {
1687 let span = self.span;
1689 return ast::Lifetime {
1690 id: ast::DUMMY_NODE_ID,
1696 self.fatal(format!("expected a lifetime name").as_slice());
1701 // matches lifetimes = ( lifetime ) | ( lifetime , lifetimes )
1702 // actually, it matches the empty one too, but putting that in there
1703 // messes up the grammar....
1704 pub fn parse_lifetimes(&mut self) -> Vec<ast::Lifetime> {
1707 * Parses zero or more comma separated lifetimes.
1708 * Expects each lifetime to be followed by either
1709 * a comma or `>`. Used when parsing type parameter
1710 * lists, where we expect something like `<'a, 'b, T>`.
1713 let mut res = Vec::new();
1716 token::LIFETIME(_) => {
1717 res.push(self.parse_lifetime());
1725 token::COMMA => { self.bump();}
1726 token::GT => { return res; }
1727 token::BINOP(token::SHR) => { return res; }
1729 let msg = format!("expected `,` or `>` after lifetime \
1732 self.fatal(msg.as_slice());
1738 pub fn token_is_mutability(tok: &token::Token) -> bool {
1739 token::is_keyword(keywords::Mut, tok) ||
1740 token::is_keyword(keywords::Const, tok)
1743 // parse mutability declaration (mut/const/imm)
1744 pub fn parse_mutability(&mut self) -> Mutability {
1745 if self.eat_keyword(keywords::Mut) {
1752 // parse ident COLON expr
1753 pub fn parse_field(&mut self) -> Field {
1754 let lo = self.span.lo;
1755 let i = self.parse_ident();
1756 let hi = self.last_span.hi;
1757 self.expect(&token::COLON);
1758 let e = self.parse_expr();
1760 ident: spanned(lo, hi, i),
1762 span: mk_sp(lo, e.span.hi),
1766 pub fn mk_expr(&mut self, lo: BytePos, hi: BytePos, node: Expr_) -> Gc<Expr> {
1768 id: ast::DUMMY_NODE_ID,
1770 span: mk_sp(lo, hi),
1774 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: Gc<Expr>) -> ast::Expr_ {
1775 ExprUnary(unop, expr)
1778 pub fn mk_binary(&mut self, binop: ast::BinOp,
1779 lhs: Gc<Expr>, rhs: Gc<Expr>) -> ast::Expr_ {
1780 ExprBinary(binop, lhs, rhs)
1783 pub fn mk_call(&mut self, f: Gc<Expr>, args: Vec<Gc<Expr>>) -> ast::Expr_ {
1787 fn mk_method_call(&mut self,
1788 ident: ast::SpannedIdent,
1790 args: Vec<Gc<Expr>>)
1792 ExprMethodCall(ident, tps, args)
1795 pub fn mk_index(&mut self, expr: Gc<Expr>, idx: Gc<Expr>) -> ast::Expr_ {
1796 ExprIndex(expr, idx)
1799 pub fn mk_field(&mut self, expr: Gc<Expr>, ident: Ident,
1800 tys: Vec<P<Ty>>) -> ast::Expr_ {
1801 ExprField(expr, ident, tys)
1804 pub fn mk_assign_op(&mut self, binop: ast::BinOp,
1805 lhs: Gc<Expr>, rhs: Gc<Expr>) -> ast::Expr_ {
1806 ExprAssignOp(binop, lhs, rhs)
1809 pub fn mk_mac_expr(&mut self, lo: BytePos, hi: BytePos, m: Mac_) -> Gc<Expr> {
1811 id: ast::DUMMY_NODE_ID,
1812 node: ExprMac(codemap::Spanned {node: m, span: mk_sp(lo, hi)}),
1813 span: mk_sp(lo, hi),
1817 pub fn mk_lit_u32(&mut self, i: u32) -> Gc<Expr> {
1818 let span = &self.span;
1819 let lv_lit = box(GC) codemap::Spanned {
1820 node: LitUint(i as u64, TyU32),
1825 id: ast::DUMMY_NODE_ID,
1826 node: ExprLit(lv_lit),
1831 // at the bottom (top?) of the precedence hierarchy,
1832 // parse things like parenthesized exprs,
1833 // macros, return, etc.
1834 pub fn parse_bottom_expr(&mut self) -> Gc<Expr> {
1835 maybe_whole_expr!(self);
1837 let lo = self.span.lo;
1838 let mut hi = self.span.hi;
1842 if self.token == token::LPAREN {
1844 // (e) is parenthesized e
1845 // (e,) is a tuple with only one field, e
1846 let mut trailing_comma = false;
1847 if self.token == token::RPAREN {
1850 let lit = box(GC) spanned(lo, hi, LitNil);
1851 return self.mk_expr(lo, hi, ExprLit(lit));
1853 let mut es = vec!(self.parse_expr());
1854 self.commit_expr(*es.last().unwrap(), &[], &[token::COMMA, token::RPAREN]);
1855 while self.token == token::COMMA {
1857 if self.token != token::RPAREN {
1858 es.push(self.parse_expr());
1859 self.commit_expr(*es.last().unwrap(), &[], &[token::COMMA, token::RPAREN]);
1862 trailing_comma = true;
1866 self.commit_expr_expecting(*es.last().unwrap(), token::RPAREN);
1868 return if es.len() == 1 && !trailing_comma {
1869 self.mk_expr(lo, hi, ExprParen(*es.get(0)))
1872 self.mk_expr(lo, hi, ExprTup(es))
1874 } else if self.token == token::LBRACE {
1876 let blk = self.parse_block_tail(lo, DefaultBlock);
1877 return self.mk_expr(blk.span.lo, blk.span.hi,
1879 } else if token::is_bar(&self.token) {
1880 return self.parse_lambda_expr();
1881 } else if self.eat_keyword(keywords::Proc) {
1882 let decl = self.parse_proc_decl();
1883 let body = self.parse_expr();
1884 let fakeblock = P(ast::Block {
1885 view_items: Vec::new(),
1888 id: ast::DUMMY_NODE_ID,
1889 rules: DefaultBlock,
1893 return self.mk_expr(lo, body.span.hi, ExprProc(decl, fakeblock));
1894 } else if self.eat_keyword(keywords::Self) {
1895 let path = ast_util::ident_to_path(mk_sp(lo, hi), special_idents::self_);
1896 ex = ExprPath(path);
1897 hi = self.last_span.hi;
1898 } else if self.eat_keyword(keywords::If) {
1899 return self.parse_if_expr();
1900 } else if self.eat_keyword(keywords::For) {
1901 return self.parse_for_expr(None);
1902 } else if self.eat_keyword(keywords::While) {
1903 return self.parse_while_expr();
1904 } else if Parser::token_is_lifetime(&self.token) {
1905 let lifetime = self.get_lifetime();
1907 self.expect(&token::COLON);
1908 if self.eat_keyword(keywords::For) {
1909 return self.parse_for_expr(Some(lifetime))
1910 } else if self.eat_keyword(keywords::Loop) {
1911 return self.parse_loop_expr(Some(lifetime))
1913 self.fatal("expected `for` or `loop` after a label")
1915 } else if self.eat_keyword(keywords::Loop) {
1916 return self.parse_loop_expr(None);
1917 } else if self.eat_keyword(keywords::Continue) {
1918 let lo = self.span.lo;
1919 let ex = if Parser::token_is_lifetime(&self.token) {
1920 let lifetime = self.get_lifetime();
1922 ExprAgain(Some(lifetime))
1926 let hi = self.span.hi;
1927 return self.mk_expr(lo, hi, ex);
1928 } else if self.eat_keyword(keywords::Match) {
1929 return self.parse_match_expr();
1930 } else if self.eat_keyword(keywords::Unsafe) {
1931 return self.parse_block_expr(lo, UnsafeBlock(ast::UserProvided));
1932 } else if self.token == token::LBRACKET {
1935 if self.token == token::RBRACKET {
1938 ex = ExprVec(Vec::new());
1941 let first_expr = self.parse_expr();
1942 if self.token == token::COMMA &&
1943 self.look_ahead(1, |t| *t == token::DOTDOT) {
1944 // Repeating vector syntax: [ 0, ..512 ]
1947 let count = self.parse_expr();
1948 self.expect(&token::RBRACKET);
1949 ex = ExprRepeat(first_expr, count);
1950 } else if self.token == token::COMMA {
1951 // Vector with two or more elements.
1953 let remaining_exprs = self.parse_seq_to_end(
1955 seq_sep_trailing_allowed(token::COMMA),
1958 let mut exprs = vec!(first_expr);
1959 exprs.push_all_move(remaining_exprs);
1960 ex = ExprVec(exprs);
1962 // Vector with one element.
1963 self.expect(&token::RBRACKET);
1964 ex = ExprVec(vec!(first_expr));
1967 hi = self.last_span.hi;
1968 } else if self.eat_keyword(keywords::Return) {
1969 // RETURN expression
1970 if can_begin_expr(&self.token) {
1971 let e = self.parse_expr();
1973 ex = ExprRet(Some(e));
1974 } else { ex = ExprRet(None); }
1975 } else if self.eat_keyword(keywords::Break) {
1977 if Parser::token_is_lifetime(&self.token) {
1978 let lifetime = self.get_lifetime();
1980 ex = ExprBreak(Some(lifetime));
1982 ex = ExprBreak(None);
1985 } else if self.token == token::MOD_SEP ||
1986 is_ident(&self.token) && !self.is_keyword(keywords::True) &&
1987 !self.is_keyword(keywords::False) {
1988 let pth = self.parse_path(LifetimeAndTypesWithColons).path;
1990 // `!`, as an operator, is prefix, so we know this isn't that
1991 if self.token == token::NOT {
1992 // MACRO INVOCATION expression
1995 let ket = token::close_delimiter_for(&self.token)
1996 .unwrap_or_else(|| self.fatal("expected open delimiter"));
1999 let tts = self.parse_seq_to_end(&ket,
2001 |p| p.parse_token_tree());
2002 let hi = self.span.hi;
2004 return self.mk_mac_expr(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT));
2005 } else if self.token == token::LBRACE {
2006 // This might be a struct literal.
2007 if self.looking_at_struct_literal() {
2008 // It's a struct literal.
2010 let mut fields = Vec::new();
2011 let mut base = None;
2013 while self.token != token::RBRACE {
2014 if self.eat(&token::DOTDOT) {
2015 base = Some(self.parse_expr());
2019 fields.push(self.parse_field());
2020 self.commit_expr(fields.last().unwrap().expr,
2021 &[token::COMMA], &[token::RBRACE]);
2025 self.expect(&token::RBRACE);
2026 ex = ExprStruct(pth, fields, base);
2027 return self.mk_expr(lo, hi, ex);
2034 // other literal expression
2035 let lit = self.parse_lit();
2037 ex = ExprLit(box(GC) lit);
2040 return self.mk_expr(lo, hi, ex);
2043 // parse a block or unsafe block
2044 pub fn parse_block_expr(&mut self, lo: BytePos, blk_mode: BlockCheckMode)
2046 self.expect(&token::LBRACE);
2047 let blk = self.parse_block_tail(lo, blk_mode);
2048 return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk));
2051 // parse a.b or a(13) or a[4] or just a
2052 pub fn parse_dot_or_call_expr(&mut self) -> Gc<Expr> {
2053 let b = self.parse_bottom_expr();
2054 self.parse_dot_or_call_expr_with(b)
2057 pub fn parse_dot_or_call_expr_with(&mut self, e0: Gc<Expr>) -> Gc<Expr> {
2063 if self.eat(&token::DOT) {
2065 token::IDENT(i, _) => {
2066 let dot = self.last_span.hi;
2069 let (_, tys) = if self.eat(&token::MOD_SEP) {
2071 self.parse_generic_values_after_lt()
2073 (Vec::new(), Vec::new())
2076 // expr.f() method call
2079 let mut es = self.parse_unspanned_seq(
2082 seq_sep_trailing_disallowed(token::COMMA),
2085 hi = self.last_span.hi;
2088 let id = spanned(dot, hi, i);
2089 let nd = self.mk_method_call(id, tys, es);
2090 e = self.mk_expr(lo, hi, nd);
2093 let field = self.mk_field(e, i, tys);
2094 e = self.mk_expr(lo, hi, field)
2098 _ => self.unexpected()
2102 if self.expr_is_complete(e) { break; }
2106 let es = self.parse_unspanned_seq(
2109 seq_sep_trailing_allowed(token::COMMA),
2112 hi = self.last_span.hi;
2114 let nd = self.mk_call(e, es);
2115 e = self.mk_expr(lo, hi, nd);
2119 token::LBRACKET => {
2121 let ix = self.parse_expr();
2123 self.commit_expr_expecting(ix, token::RBRACKET);
2124 let index = self.mk_index(e, ix);
2125 e = self.mk_expr(lo, hi, index)
2134 // parse an optional separator followed by a kleene-style
2135 // repetition token (+ or *).
2136 pub fn parse_sep_and_zerok(&mut self) -> (Option<token::Token>, bool) {
2137 fn parse_zerok(parser: &mut Parser) -> Option<bool> {
2138 match parser.token {
2139 token::BINOP(token::STAR) | token::BINOP(token::PLUS) => {
2140 let zerok = parser.token == token::BINOP(token::STAR);
2148 match parse_zerok(self) {
2149 Some(zerok) => return (None, zerok),
2153 let separator = self.bump_and_get();
2154 match parse_zerok(self) {
2155 Some(zerok) => (Some(separator), zerok),
2156 None => self.fatal("expected `*` or `+`")
2160 // parse a single token tree from the input.
2161 pub fn parse_token_tree(&mut self) -> TokenTree {
2162 // FIXME #6994: currently, this is too eager. It
2163 // parses token trees but also identifies TTSeq's
2164 // and TTNonterminal's; it's too early to know yet
2165 // whether something will be a nonterminal or a seq
2167 maybe_whole!(deref self, NtTT);
2169 // this is the fall-through for the 'match' below.
2170 // invariants: the current token is not a left-delimiter,
2171 // not an EOF, and not the desired right-delimiter (if
2172 // it were, parse_seq_to_before_end would have prevented
2173 // reaching this point.
2174 fn parse_non_delim_tt_tok(p: &mut Parser) -> TokenTree {
2175 maybe_whole!(deref p, NtTT);
2177 token::RPAREN | token::RBRACE | token::RBRACKET => {
2178 // This is a conservative error: only report the last unclosed delimiter. The
2179 // previous unclosed delimiters could actually be closed! The parser just hasn't
2180 // gotten to them yet.
2181 match p.open_braces.last() {
2183 Some(&sp) => p.span_note(sp, "unclosed delimiter"),
2185 let token_str = p.this_token_to_str();
2186 p.fatal(format!("incorrect close delimiter: `{}`",
2187 token_str).as_slice())
2189 /* we ought to allow different depths of unquotation */
2190 token::DOLLAR if p.quote_depth > 0u => {
2194 if p.token == token::LPAREN {
2195 let seq = p.parse_seq(
2199 |p| p.parse_token_tree()
2201 let (s, z) = p.parse_sep_and_zerok();
2202 let seq = match seq {
2203 Spanned { node, .. } => node,
2205 TTSeq(mk_sp(sp.lo, p.span.hi), Rc::new(seq), s, z)
2207 TTNonterminal(sp, p.parse_ident())
2216 // turn the next token into a TTTok:
2217 fn parse_any_tt_tok(p: &mut Parser) -> TokenTree {
2218 TTTok(p.span, p.bump_and_get())
2221 match (&self.token, token::close_delimiter_for(&self.token)) {
2222 (&token::EOF, _) => {
2223 let open_braces = self.open_braces.clone();
2224 for sp in open_braces.iter() {
2225 self.span_note(*sp, "Did you mean to close this delimiter?");
2227 // There shouldn't really be a span, but it's easier for the test runner
2228 // if we give it one
2229 self.fatal("this file contains an un-closed delimiter ");
2231 (_, Some(close_delim)) => {
2232 // Parse the open delimiter.
2233 self.open_braces.push(self.span);
2234 let mut result = vec!(parse_any_tt_tok(self));
2237 self.parse_seq_to_before_end(&close_delim,
2239 |p| p.parse_token_tree());
2240 result.push_all_move(trees);
2242 // Parse the close delimiter.
2243 result.push(parse_any_tt_tok(self));
2244 self.open_braces.pop().unwrap();
2246 TTDelim(Rc::new(result))
2248 _ => parse_non_delim_tt_tok(self)
2252 // parse a stream of tokens into a list of TokenTree's,
2254 pub fn parse_all_token_trees(&mut self) -> Vec<TokenTree> {
2255 let mut tts = Vec::new();
2256 while self.token != token::EOF {
2257 tts.push(self.parse_token_tree());
2262 pub fn parse_matchers(&mut self) -> Vec<Matcher> {
2263 // unification of Matcher's and TokenTree's would vastly improve
2264 // the interpolation of Matcher's
2265 maybe_whole!(self, NtMatchers);
2266 let mut name_idx = 0u;
2267 match token::close_delimiter_for(&self.token) {
2268 Some(other_delimiter) => {
2270 self.parse_matcher_subseq_upto(&mut name_idx, &other_delimiter)
2272 None => self.fatal("expected open delimiter")
2276 // This goofy function is necessary to correctly match parens in Matcher's.
2277 // Otherwise, `$( ( )` would be a valid Matcher, and `$( () )` would be
2278 // invalid. It's similar to common::parse_seq.
2279 pub fn parse_matcher_subseq_upto(&mut self,
2280 name_idx: &mut uint,
2283 let mut ret_val = Vec::new();
2284 let mut lparens = 0u;
2286 while self.token != *ket || lparens > 0u {
2287 if self.token == token::LPAREN { lparens += 1u; }
2288 if self.token == token::RPAREN { lparens -= 1u; }
2289 ret_val.push(self.parse_matcher(name_idx));
2297 pub fn parse_matcher(&mut self, name_idx: &mut uint) -> Matcher {
2298 let lo = self.span.lo;
2300 let m = if self.token == token::DOLLAR {
2302 if self.token == token::LPAREN {
2303 let name_idx_lo = *name_idx;
2305 let ms = self.parse_matcher_subseq_upto(name_idx,
2308 self.fatal("repetition body must be nonempty");
2310 let (sep, zerok) = self.parse_sep_and_zerok();
2311 MatchSeq(ms, sep, zerok, name_idx_lo, *name_idx)
2313 let bound_to = self.parse_ident();
2314 self.expect(&token::COLON);
2315 let nt_name = self.parse_ident();
2316 let m = MatchNonterminal(bound_to, nt_name, *name_idx);
2321 MatchTok(self.bump_and_get())
2324 return spanned(lo, self.span.hi, m);
2327 // parse a prefix-operator expr
2328 pub fn parse_prefix_expr(&mut self) -> Gc<Expr> {
2329 let lo = self.span.lo;
2336 let e = self.parse_prefix_expr();
2338 ex = self.mk_unary(UnNot, e);
2340 token::BINOP(token::MINUS) => {
2342 let e = self.parse_prefix_expr();
2344 ex = self.mk_unary(UnNeg, e);
2346 token::BINOP(token::STAR) => {
2348 let e = self.parse_prefix_expr();
2350 ex = self.mk_unary(UnDeref, e);
2352 token::BINOP(token::AND) | token::ANDAND => {
2354 let _lt = self.parse_opt_lifetime();
2355 let m = self.parse_mutability();
2356 let e = self.parse_prefix_expr();
2358 // HACK: turn &[...] into a &-vec
2360 ExprVec(..) if m == MutImmutable => {
2361 ExprVstore(e, ExprVstoreSlice)
2363 ExprVec(..) if m == MutMutable => {
2364 ExprVstore(e, ExprVstoreMutSlice)
2366 _ => ExprAddrOf(m, e)
2371 let span = self.last_span;
2372 self.obsolete(span, ObsoleteManagedExpr);
2373 let e = self.parse_prefix_expr();
2375 ex = self.mk_unary(UnBox, e);
2380 let e = self.parse_prefix_expr();
2382 // HACK: turn ~[...] into a ~-vec
2383 let last_span = self.last_span;
2385 ExprVec(..) | ExprRepeat(..) => {
2386 self.obsolete(last_span, ObsoleteOwnedVector);
2387 ExprVstore(e, ExprVstoreUniq)
2389 ExprLit(lit) if lit_is_str(lit) => {
2390 self.obsolete(last_span, ObsoleteOwnedExpr);
2391 ExprVstore(e, ExprVstoreUniq)
2394 self.obsolete(last_span, ObsoleteOwnedExpr);
2395 self.mk_unary(UnUniq, e)
2399 token::IDENT(_, _) if self.is_keyword(keywords::Box) => {
2402 // Check for a place: `box(PLACE) EXPR`.
2403 if self.eat(&token::LPAREN) {
2404 // Support `box() EXPR` as the default.
2405 if !self.eat(&token::RPAREN) {
2406 let place = self.parse_expr();
2407 self.expect(&token::RPAREN);
2408 let subexpression = self.parse_prefix_expr();
2409 hi = subexpression.span.hi;
2410 ex = ExprBox(place, subexpression);
2411 return self.mk_expr(lo, hi, ex);
2415 // Otherwise, we use the unique pointer default.
2416 let subexpression = self.parse_prefix_expr();
2417 hi = subexpression.span.hi;
2418 // HACK: turn `box [...]` into a boxed-vec
2419 ex = match subexpression.node {
2420 ExprVec(..) | ExprRepeat(..) => {
2421 let last_span = self.last_span;
2422 self.obsolete(last_span, ObsoleteOwnedVector);
2423 ExprVstore(subexpression, ExprVstoreUniq)
2425 ExprLit(lit) if lit_is_str(lit) => {
2426 ExprVstore(subexpression, ExprVstoreUniq)
2428 _ => self.mk_unary(UnUniq, subexpression)
2431 _ => return self.parse_dot_or_call_expr()
2433 return self.mk_expr(lo, hi, ex);
2436 // parse an expression of binops
2437 pub fn parse_binops(&mut self) -> Gc<Expr> {
2438 let prefix_expr = self.parse_prefix_expr();
2439 self.parse_more_binops(prefix_expr, 0)
2442 // parse an expression of binops of at least min_prec precedence
2443 pub fn parse_more_binops(&mut self, lhs: Gc<Expr>,
2444 min_prec: uint) -> Gc<Expr> {
2445 if self.expr_is_complete(lhs) { return lhs; }
2447 // Prevent dynamic borrow errors later on by limiting the
2448 // scope of the borrows.
2450 let token: &token::Token = &self.token;
2451 let restriction: &restriction = &self.restriction;
2452 match (token, restriction) {
2453 (&token::BINOP(token::OR), &RESTRICT_NO_BAR_OP) => return lhs,
2454 (&token::BINOP(token::OR),
2455 &RESTRICT_NO_BAR_OR_DOUBLEBAR_OP) => return lhs,
2456 (&token::OROR, &RESTRICT_NO_BAR_OR_DOUBLEBAR_OP) => return lhs,
2461 let cur_opt = token_to_binop(&self.token);
2464 let cur_prec = operator_prec(cur_op);
2465 if cur_prec > min_prec {
2467 let expr = self.parse_prefix_expr();
2468 let rhs = self.parse_more_binops(expr, cur_prec);
2469 let binary = self.mk_binary(cur_op, lhs, rhs);
2470 let bin = self.mk_expr(lhs.span.lo, rhs.span.hi, binary);
2471 self.parse_more_binops(bin, min_prec)
2477 if as_prec > min_prec && self.eat_keyword(keywords::As) {
2478 let rhs = self.parse_ty(false);
2479 let _as = self.mk_expr(lhs.span.lo,
2481 ExprCast(lhs, rhs));
2482 self.parse_more_binops(_as, min_prec)
2490 // parse an assignment expression....
2491 // actually, this seems to be the main entry point for
2492 // parsing an arbitrary expression.
2493 pub fn parse_assign_expr(&mut self) -> Gc<Expr> {
2494 let lo = self.span.lo;
2495 let lhs = self.parse_binops();
2499 let rhs = self.parse_expr();
2500 self.mk_expr(lo, rhs.span.hi, ExprAssign(lhs, rhs))
2502 token::BINOPEQ(op) => {
2504 let rhs = self.parse_expr();
2505 let aop = match op {
2506 token::PLUS => BiAdd,
2507 token::MINUS => BiSub,
2508 token::STAR => BiMul,
2509 token::SLASH => BiDiv,
2510 token::PERCENT => BiRem,
2511 token::CARET => BiBitXor,
2512 token::AND => BiBitAnd,
2513 token::OR => BiBitOr,
2514 token::SHL => BiShl,
2517 let assign_op = self.mk_assign_op(aop, lhs, rhs);
2518 self.mk_expr(lo, rhs.span.hi, assign_op)
2526 // parse an 'if' expression ('if' token already eaten)
2527 pub fn parse_if_expr(&mut self) -> Gc<Expr> {
2528 let lo = self.last_span.lo;
2529 let cond = self.parse_expr();
2530 let thn = self.parse_block();
2531 let mut els: Option<Gc<Expr>> = None;
2532 let mut hi = thn.span.hi;
2533 if self.eat_keyword(keywords::Else) {
2534 let elexpr = self.parse_else_expr();
2536 hi = elexpr.span.hi;
2538 self.mk_expr(lo, hi, ExprIf(cond, thn, els))
2541 // `|args| { ... }` or `{ ...}` like in `do` expressions
2542 pub fn parse_lambda_block_expr(&mut self) -> Gc<Expr> {
2543 self.parse_lambda_expr_(
2546 token::BINOP(token::OR) | token::OROR => {
2547 p.parse_fn_block_decl()
2550 // No argument list - `do foo {`
2554 id: ast::DUMMY_NODE_ID,
2565 let blk = p.parse_block();
2566 p.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk))
2571 pub fn parse_lambda_expr(&mut self) -> Gc<Expr> {
2572 self.parse_lambda_expr_(|p| p.parse_fn_block_decl(),
2576 // parse something of the form |args| expr
2577 // this is used both in parsing a lambda expr
2578 // and in parsing a block expr as e.g. in for...
2579 pub fn parse_lambda_expr_(&mut self,
2580 parse_decl: |&mut Parser| -> P<FnDecl>,
2581 parse_body: |&mut Parser| -> Gc<Expr>)
2583 let lo = self.span.lo;
2584 let decl = parse_decl(self);
2585 let body = parse_body(self);
2586 let fakeblock = P(ast::Block {
2587 view_items: Vec::new(),
2590 id: ast::DUMMY_NODE_ID,
2591 rules: DefaultBlock,
2595 return self.mk_expr(lo, body.span.hi, ExprFnBlock(decl, fakeblock));
2598 pub fn parse_else_expr(&mut self) -> Gc<Expr> {
2599 if self.eat_keyword(keywords::If) {
2600 return self.parse_if_expr();
2602 let blk = self.parse_block();
2603 return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk));
2607 // parse a 'for' .. 'in' expression ('for' token already eaten)
2608 pub fn parse_for_expr(&mut self, opt_ident: Option<ast::Ident>) -> Gc<Expr> {
2609 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
2611 let lo = self.last_span.lo;
2612 let pat = self.parse_pat();
2613 self.expect_keyword(keywords::In);
2614 let expr = self.parse_expr();
2615 let loop_block = self.parse_block();
2616 let hi = self.span.hi;
2618 self.mk_expr(lo, hi, ExprForLoop(pat, expr, loop_block, opt_ident))
2621 pub fn parse_while_expr(&mut self) -> Gc<Expr> {
2622 let lo = self.last_span.lo;
2623 let cond = self.parse_expr();
2624 let body = self.parse_block();
2625 let hi = body.span.hi;
2626 return self.mk_expr(lo, hi, ExprWhile(cond, body));
2629 pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::Ident>) -> Gc<Expr> {
2630 let lo = self.last_span.lo;
2631 let body = self.parse_block();
2632 let hi = body.span.hi;
2633 self.mk_expr(lo, hi, ExprLoop(body, opt_ident))
2636 // For distinguishing between struct literals and blocks
2637 fn looking_at_struct_literal(&mut self) -> bool {
2638 self.token == token::LBRACE &&
2639 ((self.look_ahead(1, |t| token::is_plain_ident(t)) &&
2640 self.look_ahead(2, |t| *t == token::COLON))
2641 || self.look_ahead(1, |t| *t == token::DOTDOT))
2644 fn parse_match_expr(&mut self) -> Gc<Expr> {
2645 let lo = self.last_span.lo;
2646 let discriminant = self.parse_expr();
2647 self.commit_expr_expecting(discriminant, token::LBRACE);
2648 let mut arms: Vec<Arm> = Vec::new();
2649 while self.token != token::RBRACE {
2650 let attrs = self.parse_outer_attributes();
2651 let pats = self.parse_pats();
2652 let mut guard = None;
2653 if self.eat_keyword(keywords::If) {
2654 guard = Some(self.parse_expr());
2656 self.expect(&token::FAT_ARROW);
2657 let expr = self.parse_expr_res(RESTRICT_STMT_EXPR);
2660 !classify::expr_is_simple_block(expr)
2661 && self.token != token::RBRACE;
2664 self.commit_expr(expr, &[token::COMMA], &[token::RBRACE]);
2666 self.eat(&token::COMMA);
2669 arms.push(ast::Arm {
2676 let hi = self.span.hi;
2678 return self.mk_expr(lo, hi, ExprMatch(discriminant, arms));
2681 // parse an expression
2682 pub fn parse_expr(&mut self) -> Gc<Expr> {
2683 return self.parse_expr_res(UNRESTRICTED);
2686 // parse an expression, subject to the given restriction
2687 fn parse_expr_res(&mut self, r: restriction) -> Gc<Expr> {
2688 let old = self.restriction;
2689 self.restriction = r;
2690 let e = self.parse_assign_expr();
2691 self.restriction = old;
2695 // parse the RHS of a local variable declaration (e.g. '= 14;')
2696 fn parse_initializer(&mut self) -> Option<Gc<Expr>> {
2697 if self.token == token::EQ {
2699 Some(self.parse_expr())
2705 // parse patterns, separated by '|' s
2706 fn parse_pats(&mut self) -> Vec<Gc<Pat>> {
2707 let mut pats = Vec::new();
2709 pats.push(self.parse_pat());
2710 if self.token == token::BINOP(token::OR) { self.bump(); }
2711 else { return pats; }
2715 fn parse_pat_vec_elements(
2717 ) -> (Vec<Gc<Pat>> , Option<Gc<Pat>>, Vec<Gc<Pat>> ) {
2718 let mut before = Vec::new();
2719 let mut slice = None;
2720 let mut after = Vec::new();
2721 let mut first = true;
2722 let mut before_slice = true;
2724 while self.token != token::RBRACKET {
2725 if first { first = false; }
2726 else { self.expect(&token::COMMA); }
2728 let mut is_slice = false;
2730 if self.token == token::DOTDOT {
2733 before_slice = false;
2738 if self.token == token::COMMA || self.token == token::RBRACKET {
2739 slice = Some(box(GC) ast::Pat {
2740 id: ast::DUMMY_NODE_ID,
2745 let subpat = self.parse_pat();
2747 ast::Pat { node: PatIdent(_, _, _), .. } => {
2748 slice = Some(subpat);
2750 ast::Pat { span, .. } => self.span_fatal(
2751 span, "expected an identifier or nothing"
2756 let subpat = self.parse_pat();
2758 before.push(subpat);
2765 (before, slice, after)
2768 // parse the fields of a struct-like pattern
2769 fn parse_pat_fields(&mut self) -> (Vec<ast::FieldPat> , bool) {
2770 let mut fields = Vec::new();
2771 let mut etc = false;
2772 let mut first = true;
2773 while self.token != token::RBRACE {
2777 self.expect(&token::COMMA);
2778 // accept trailing commas
2779 if self.token == token::RBRACE { break }
2782 if self.token == token::DOTDOT {
2784 if self.token != token::RBRACE {
2785 let token_str = self.this_token_to_str();
2786 self.fatal(format!("expected `{}`, found `{}`", "}",
2787 token_str).as_slice())
2793 let bind_type = if self.eat_keyword(keywords::Mut) {
2794 BindByValue(MutMutable)
2795 } else if self.eat_keyword(keywords::Ref) {
2796 BindByRef(self.parse_mutability())
2798 BindByValue(MutImmutable)
2801 let fieldname = self.parse_ident();
2803 let subpat = if self.token == token::COLON {
2805 BindByRef(..) | BindByValue(MutMutable) => {
2806 let token_str = self.this_token_to_str();
2807 self.fatal(format!("unexpected `{}`",
2808 token_str).as_slice())
2816 let fieldpath = ast_util::ident_to_path(self.last_span,
2819 id: ast::DUMMY_NODE_ID,
2820 node: PatIdent(bind_type, fieldpath, None),
2821 span: self.last_span
2824 fields.push(ast::FieldPat { ident: fieldname, pat: subpat });
2826 return (fields, etc);
2830 pub fn parse_pat(&mut self) -> Gc<Pat> {
2831 maybe_whole!(self, NtPat);
2833 let lo = self.span.lo;
2838 token::UNDERSCORE => {
2841 hi = self.last_span.hi;
2842 return box(GC) ast::Pat {
2843 id: ast::DUMMY_NODE_ID,
2851 let sub = self.parse_pat();
2853 let last_span = self.last_span;
2855 self.obsolete(last_span, ObsoleteOwnedPattern);
2856 return box(GC) ast::Pat {
2857 id: ast::DUMMY_NODE_ID,
2862 token::BINOP(token::AND) | token::ANDAND => {
2864 let lo = self.span.lo;
2866 let sub = self.parse_pat();
2867 pat = PatRegion(sub);
2868 hi = self.last_span.hi;
2869 return box(GC) ast::Pat {
2870 id: ast::DUMMY_NODE_ID,
2876 // parse (pat,pat,pat,...) as tuple
2878 if self.token == token::RPAREN {
2881 let lit = box(GC) codemap::Spanned {
2883 span: mk_sp(lo, hi)};
2884 let expr = self.mk_expr(lo, hi, ExprLit(lit));
2887 let mut fields = vec!(self.parse_pat());
2888 if self.look_ahead(1, |t| *t != token::RPAREN) {
2889 while self.token == token::COMMA {
2891 if self.token == token::RPAREN { break; }
2892 fields.push(self.parse_pat());
2895 if fields.len() == 1 { self.expect(&token::COMMA); }
2896 self.expect(&token::RPAREN);
2897 pat = PatTup(fields);
2899 hi = self.last_span.hi;
2900 return box(GC) ast::Pat {
2901 id: ast::DUMMY_NODE_ID,
2906 token::LBRACKET => {
2907 // parse [pat,pat,...] as vector pattern
2909 let (before, slice, after) =
2910 self.parse_pat_vec_elements();
2912 self.expect(&token::RBRACKET);
2913 pat = ast::PatVec(before, slice, after);
2914 hi = self.last_span.hi;
2915 return box(GC) ast::Pat {
2916 id: ast::DUMMY_NODE_ID,
2924 if (!is_ident_or_path(&self.token) && self.token != token::MOD_SEP)
2925 || self.is_keyword(keywords::True)
2926 || self.is_keyword(keywords::False) {
2927 // Parse an expression pattern or exp .. exp.
2929 // These expressions are limited to literals (possibly
2930 // preceded by unary-minus) or identifiers.
2931 let val = self.parse_literal_maybe_minus();
2932 if self.eat(&token::DOTDOT) {
2933 let end = if is_ident_or_path(&self.token) {
2934 let path = self.parse_path(LifetimeAndTypesWithColons)
2936 let hi = self.span.hi;
2937 self.mk_expr(lo, hi, ExprPath(path))
2939 self.parse_literal_maybe_minus()
2941 pat = PatRange(val, end);
2945 } else if self.eat_keyword(keywords::Mut) {
2946 pat = self.parse_pat_ident(BindByValue(MutMutable));
2947 } else if self.eat_keyword(keywords::Ref) {
2949 let mutbl = self.parse_mutability();
2950 pat = self.parse_pat_ident(BindByRef(mutbl));
2951 } else if self.eat_keyword(keywords::Box) {
2954 // FIXME(#13910): Rename to `PatBox` and extend to full DST
2956 let sub = self.parse_pat();
2958 hi = self.last_span.hi;
2959 return box(GC) ast::Pat {
2960 id: ast::DUMMY_NODE_ID,
2965 let can_be_enum_or_struct = self.look_ahead(1, |t| {
2967 token::LPAREN | token::LBRACKET | token::LT |
2968 token::LBRACE | token::MOD_SEP => true,
2973 if self.look_ahead(1, |t| *t == token::DOTDOT) {
2974 let start = self.parse_expr_res(RESTRICT_NO_BAR_OP);
2975 self.eat(&token::DOTDOT);
2976 let end = self.parse_expr_res(RESTRICT_NO_BAR_OP);
2977 pat = PatRange(start, end);
2978 } else if is_plain_ident(&self.token) && !can_be_enum_or_struct {
2979 let name = self.parse_path(NoTypesAllowed).path;
2980 if self.eat(&token::NOT) {
2982 let ket = token::close_delimiter_for(&self.token)
2983 .unwrap_or_else(|| self.fatal("expected open delimiter"));
2986 let tts = self.parse_seq_to_end(&ket,
2988 |p| p.parse_token_tree());
2990 let mac = MacInvocTT(name, tts, EMPTY_CTXT);
2991 pat = ast::PatMac(codemap::Spanned {node: mac, span: self.span});
2993 let sub = if self.eat(&token::AT) {
2995 Some(self.parse_pat())
3000 pat = PatIdent(BindByValue(MutImmutable), name, sub);
3003 // parse an enum pat
3004 let enum_path = self.parse_path(LifetimeAndTypesWithColons)
3010 self.parse_pat_fields();
3012 pat = PatStruct(enum_path, fields, etc);
3015 let mut args: Vec<Gc<Pat>> = Vec::new();
3018 let is_dotdot = self.look_ahead(1, |t| {
3020 token::DOTDOT => true,
3025 // This is a "top constructor only" pat
3028 self.expect(&token::RPAREN);
3029 pat = PatEnum(enum_path, None);
3031 args = self.parse_enum_variant_seq(
3034 seq_sep_trailing_disallowed(token::COMMA),
3037 pat = PatEnum(enum_path, Some(args));
3041 if enum_path.segments.len() == 1 {
3042 // it could still be either an enum
3043 // or an identifier pattern, resolve
3044 // will sort it out:
3045 pat = PatIdent(BindByValue(MutImmutable),
3049 pat = PatEnum(enum_path, Some(args));
3057 hi = self.last_span.hi;
3059 id: ast::DUMMY_NODE_ID,
3061 span: mk_sp(lo, hi),
3065 // parse ident or ident @ pat
3066 // used by the copy foo and ref foo patterns to give a good
3067 // error message when parsing mistakes like ref foo(a,b)
3068 fn parse_pat_ident(&mut self,
3069 binding_mode: ast::BindingMode)
3071 if !is_plain_ident(&self.token) {
3072 let last_span = self.last_span;
3073 self.span_fatal(last_span,
3074 "expected identifier, found path");
3076 // why a path here, and not just an identifier?
3077 let name = self.parse_path(NoTypesAllowed).path;
3078 let sub = if self.eat(&token::AT) {
3079 Some(self.parse_pat())
3084 // just to be friendly, if they write something like
3086 // we end up here with ( as the current token. This shortly
3087 // leads to a parse error. Note that if there is no explicit
3088 // binding mode then we do not end up here, because the lookahead
3089 // will direct us over to parse_enum_variant()
3090 if self.token == token::LPAREN {
3091 let last_span = self.last_span;
3094 "expected identifier, found enum pattern");
3097 PatIdent(binding_mode, name, sub)
3100 // parse a local variable declaration
3101 fn parse_local(&mut self) -> Gc<Local> {
3102 let lo = self.span.lo;
3103 let pat = self.parse_pat();
3106 id: ast::DUMMY_NODE_ID,
3108 span: mk_sp(lo, lo),
3110 if self.eat(&token::COLON) {
3111 ty = self.parse_ty(true);
3113 let init = self.parse_initializer();
3114 box(GC) ast::Local {
3118 id: ast::DUMMY_NODE_ID,
3119 span: mk_sp(lo, self.last_span.hi),
3124 // parse a "let" stmt
3125 fn parse_let(&mut self) -> Gc<Decl> {
3126 let lo = self.span.lo;
3127 let local = self.parse_local();
3128 box(GC) spanned(lo, self.last_span.hi, DeclLocal(local))
3131 // parse a structure field
3132 fn parse_name_and_ty(&mut self, pr: Visibility,
3133 attrs: Vec<Attribute> ) -> StructField {
3134 let lo = self.span.lo;
3135 if !is_plain_ident(&self.token) {
3136 self.fatal("expected ident");
3138 let name = self.parse_ident();
3139 self.expect(&token::COLON);
3140 let ty = self.parse_ty(true);
3141 spanned(lo, self.last_span.hi, ast::StructField_ {
3142 kind: NamedField(name, pr),
3143 id: ast::DUMMY_NODE_ID,
3149 // parse a statement. may include decl.
3150 // precondition: any attributes are parsed already
3151 pub fn parse_stmt(&mut self, item_attrs: Vec<Attribute>) -> Gc<Stmt> {
3152 maybe_whole!(self, NtStmt);
3154 fn check_expected_item(p: &mut Parser, found_attrs: bool) {
3155 // If we have attributes then we should have an item
3157 let last_span = p.last_span;
3158 p.span_err(last_span, "expected item after attributes");
3162 let lo = self.span.lo;
3163 if self.is_keyword(keywords::Let) {
3164 check_expected_item(self, !item_attrs.is_empty());
3165 self.expect_keyword(keywords::Let);
3166 let decl = self.parse_let();
3167 return box(GC) spanned(lo, decl.span.hi, StmtDecl(decl, ast::DUMMY_NODE_ID));
3168 } else if is_ident(&self.token)
3169 && !token::is_any_keyword(&self.token)
3170 && self.look_ahead(1, |t| *t == token::NOT) {
3171 // parse a macro invocation. Looks like there's serious
3172 // overlap here; if this clause doesn't catch it (and it
3173 // won't, for brace-delimited macros) it will fall through
3174 // to the macro clause of parse_item_or_view_item. This
3175 // could use some cleanup, it appears to me.
3177 // whoops! I now have a guess: I'm guessing the "parens-only"
3178 // rule here is deliberate, to allow macro users to use parens
3179 // for things that should be parsed as stmt_mac, and braces
3180 // for things that should expand into items. Tricky, and
3181 // somewhat awkward... and probably undocumented. Of course,
3182 // I could just be wrong.
3184 check_expected_item(self, !item_attrs.is_empty());
3186 // Potential trouble: if we allow macros with paths instead of
3187 // idents, we'd need to look ahead past the whole path here...
3188 let pth = self.parse_path(NoTypesAllowed).path;
3191 let id = if token::close_delimiter_for(&self.token).is_some() {
3192 token::special_idents::invalid // no special identifier
3197 // check that we're pointing at delimiters (need to check
3198 // again after the `if`, because of `parse_ident`
3199 // consuming more tokens).
3200 let (bra, ket) = match token::close_delimiter_for(&self.token) {
3201 Some(ket) => (self.token.clone(), ket),
3203 // we only expect an ident if we didn't parse one
3205 let ident_str = if id == token::special_idents::invalid {
3210 let tok_str = self.this_token_to_str();
3211 self.fatal(format!("expected {}`(` or `{{`, but found `{}`",
3213 tok_str).as_slice())
3217 let tts = self.parse_unspanned_seq(
3221 |p| p.parse_token_tree()
3223 let hi = self.span.hi;
3225 if id == token::special_idents::invalid {
3226 return box(GC) spanned(lo, hi, StmtMac(
3227 spanned(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT)), false));
3229 // if it has a special ident, it's definitely an item
3230 return box(GC) spanned(lo, hi, StmtDecl(
3231 box(GC) spanned(lo, hi, DeclItem(
3233 lo, hi, id /*id is good here*/,
3234 ItemMac(spanned(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT))),
3235 Inherited, Vec::new(/*no attrs*/)))),
3236 ast::DUMMY_NODE_ID));
3240 let found_attrs = !item_attrs.is_empty();
3241 match self.parse_item_or_view_item(item_attrs, false) {
3244 let decl = box(GC) spanned(lo, hi, DeclItem(i));
3245 return box(GC) spanned(lo, hi, StmtDecl(decl, ast::DUMMY_NODE_ID));
3247 IoviViewItem(vi) => {
3248 self.span_fatal(vi.span,
3249 "view items must be declared at the top of the block");
3251 IoviForeignItem(_) => {
3252 self.fatal("foreign items are not allowed here");
3254 IoviNone(_) => { /* fallthrough */ }
3257 check_expected_item(self, found_attrs);
3259 // Remainder are line-expr stmts.
3260 let e = self.parse_expr_res(RESTRICT_STMT_EXPR);
3261 return box(GC) spanned(lo, e.span.hi, StmtExpr(e, ast::DUMMY_NODE_ID));
3265 // is this expression a successfully-parsed statement?
3266 fn expr_is_complete(&mut self, e: Gc<Expr>) -> bool {
3267 return self.restriction == RESTRICT_STMT_EXPR &&
3268 !classify::expr_requires_semi_to_be_stmt(e);
3271 // parse a block. No inner attrs are allowed.
3272 pub fn parse_block(&mut self) -> P<Block> {
3273 maybe_whole!(no_clone self, NtBlock);
3275 let lo = self.span.lo;
3276 self.expect(&token::LBRACE);
3278 return self.parse_block_tail_(lo, DefaultBlock, Vec::new());
3281 // parse a block. Inner attrs are allowed.
3282 fn parse_inner_attrs_and_block(&mut self)
3283 -> (Vec<Attribute> , P<Block>) {
3285 maybe_whole!(pair_empty self, NtBlock);
3287 let lo = self.span.lo;
3288 self.expect(&token::LBRACE);
3289 let (inner, next) = self.parse_inner_attrs_and_next();
3291 (inner, self.parse_block_tail_(lo, DefaultBlock, next))
3294 // Precondition: already parsed the '{' or '#{'
3295 // I guess that also means "already parsed the 'impure'" if
3296 // necessary, and this should take a qualifier.
3297 // some blocks start with "#{"...
3298 fn parse_block_tail(&mut self, lo: BytePos, s: BlockCheckMode) -> P<Block> {
3299 self.parse_block_tail_(lo, s, Vec::new())
3302 // parse the rest of a block expression or function body
3303 fn parse_block_tail_(&mut self, lo: BytePos, s: BlockCheckMode,
3304 first_item_attrs: Vec<Attribute> ) -> P<Block> {
3305 let mut stmts = Vec::new();
3306 let mut expr = None;
3308 // wouldn't it be more uniform to parse view items only, here?
3309 let ParsedItemsAndViewItems {
3310 attrs_remaining: attrs_remaining,
3311 view_items: view_items,
3314 } = self.parse_items_and_view_items(first_item_attrs,
3317 for item in items.iter() {
3318 let decl = box(GC) spanned(item.span.lo, item.span.hi, DeclItem(*item));
3319 stmts.push(box(GC) spanned(item.span.lo, item.span.hi,
3320 StmtDecl(decl, ast::DUMMY_NODE_ID)));
3323 let mut attributes_box = attrs_remaining;
3325 while self.token != token::RBRACE {
3326 // parsing items even when they're not allowed lets us give
3327 // better error messages and recover more gracefully.
3328 attributes_box.push_all(self.parse_outer_attributes().as_slice());
3331 if !attributes_box.is_empty() {
3332 let last_span = self.last_span;
3333 self.span_err(last_span, "expected item after attributes");
3334 attributes_box = Vec::new();
3336 self.bump(); // empty
3339 // fall through and out.
3342 let stmt = self.parse_stmt(attributes_box);
3343 attributes_box = Vec::new();
3345 StmtExpr(e, stmt_id) => {
3346 // expression without semicolon
3347 if classify::stmt_ends_with_semi(&*stmt) {
3348 // Just check for errors and recover; do not eat semicolon yet.
3349 self.commit_stmt(stmt, &[], &[token::SEMI, token::RBRACE]);
3355 let span_with_semi = Span {
3357 hi: self.last_span.hi,
3358 expn_info: stmt.span.expn_info,
3360 stmts.push(box(GC) codemap::Spanned {
3361 node: StmtSemi(e, stmt_id),
3362 span: span_with_semi,
3373 StmtMac(ref m, _) => {
3374 // statement macro; might be an expr
3378 stmts.push(box(GC) codemap::Spanned {
3379 node: StmtMac((*m).clone(), true),
3384 // if a block ends in `m!(arg)` without
3385 // a `;`, it must be an expr
3387 self.mk_mac_expr(stmt.span.lo,
3396 _ => { // all other kinds of statements:
3397 stmts.push(stmt.clone());
3399 if classify::stmt_ends_with_semi(&*stmt) {
3400 self.commit_stmt_expecting(stmt, token::SEMI);
3408 if !attributes_box.is_empty() {
3409 let last_span = self.last_span;
3410 self.span_err(last_span, "expected item after attributes");
3413 let hi = self.span.hi;
3416 view_items: view_items,
3419 id: ast::DUMMY_NODE_ID,
3421 span: mk_sp(lo, hi),
3425 fn parse_unboxed_function_type(&mut self) -> UnboxedFnTy {
3426 let inputs = if self.eat(&token::OROR) {
3431 if self.token == token::BINOP(token::AND) &&
3432 self.look_ahead(1, |t| {
3433 token::is_keyword(keywords::Mut, t)
3435 self.look_ahead(2, |t| *t == token::COLON) {
3441 let inputs = self.parse_seq_to_before_or(&token::COMMA,
3443 p.parse_arg_general(false)
3449 let (return_style, output) = self.parse_ret_ty();
3460 // matches bounds = ( boundseq )?
3461 // where boundseq = ( bound + boundseq ) | bound
3462 // and bound = 'static | ty
3463 // Returns "None" if there's no colon (e.g. "T");
3464 // Returns "Some(Empty)" if there's a colon but nothing after (e.g. "T:")
3465 // Returns "Some(stuff)" otherwise (e.g. "T:stuff").
3466 // NB: The None/Some distinction is important for issue #7264.
3468 // Note that the `allow_any_lifetime` argument is a hack for now while the
3469 // AST doesn't support arbitrary lifetimes in bounds on type parameters. In
3470 // the future, this flag should be removed, and the return value of this
3471 // function should be Option<~[TyParamBound]>
3472 fn parse_ty_param_bounds(&mut self, allow_any_lifetime: bool)
3473 -> (Option<ast::Lifetime>,
3474 OwnedSlice<TyParamBound>) {
3475 let mut ret_lifetime = None;
3476 let mut result = vec!();
3479 token::LIFETIME(lifetime) => {
3480 let lifetime_interned_string = token::get_ident(lifetime);
3481 if lifetime_interned_string.equiv(&("'static")) {
3482 result.push(StaticRegionTyParamBound);
3483 if allow_any_lifetime && ret_lifetime.is_none() {
3484 ret_lifetime = Some(ast::Lifetime {
3485 id: ast::DUMMY_NODE_ID,
3490 } else if allow_any_lifetime && ret_lifetime.is_none() {
3491 ret_lifetime = Some(ast::Lifetime {
3492 id: ast::DUMMY_NODE_ID,
3497 result.push(OtherRegionTyParamBound(self.span));
3501 token::MOD_SEP | token::IDENT(..) => {
3502 let tref = self.parse_trait_ref();
3503 result.push(TraitTyParamBound(tref));
3505 token::BINOP(token::OR) | token::OROR => {
3506 let unboxed_function_type =
3507 self.parse_unboxed_function_type();
3508 result.push(UnboxedFnTyParamBound(unboxed_function_type));
3513 if !self.eat(&token::BINOP(token::PLUS)) {
3518 return (ret_lifetime, OwnedSlice::from_vec(result));
3521 // matches typaram = type? IDENT optbounds ( EQ ty )?
3522 fn parse_ty_param(&mut self) -> TyParam {
3523 let sized = self.parse_sized();
3524 let span = self.span;
3525 let ident = self.parse_ident();
3527 if self.eat(&token::COLON) {
3528 let (_, bounds) = self.parse_ty_param_bounds(false);
3534 // For typarams we don't care about the difference b/w "<T>" and "<T:>".
3535 let bounds = opt_bounds.unwrap_or_default();
3537 let default = if self.token == token::EQ {
3539 Some(self.parse_ty(true))
3545 id: ast::DUMMY_NODE_ID,
3553 // parse a set of optional generic type parameter declarations
3554 // matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
3555 // | ( < lifetimes , typaramseq ( , )? > )
3556 // where typaramseq = ( typaram ) | ( typaram , typaramseq )
3557 pub fn parse_generics(&mut self) -> ast::Generics {
3558 if self.eat(&token::LT) {
3559 let lifetimes = self.parse_lifetimes();
3560 let mut seen_default = false;
3561 let ty_params = self.parse_seq_to_gt(Some(token::COMMA), |p| {
3562 p.forbid_lifetime();
3563 let ty_param = p.parse_ty_param();
3564 if ty_param.default.is_some() {
3565 seen_default = true;
3566 } else if seen_default {
3567 let last_span = p.last_span;
3568 p.span_err(last_span,
3569 "type parameters with a default must be trailing");
3573 ast::Generics { lifetimes: lifetimes, ty_params: ty_params }
3575 ast_util::empty_generics()
3579 fn parse_generic_values_after_lt(&mut self) -> (Vec<ast::Lifetime>, Vec<P<Ty>> ) {
3580 let lifetimes = self.parse_lifetimes();
3581 let result = self.parse_seq_to_gt(
3584 p.forbid_lifetime();
3588 (lifetimes, result.into_vec())
3591 fn forbid_lifetime(&mut self) {
3592 if Parser::token_is_lifetime(&self.token) {
3593 let span = self.span;
3594 self.span_fatal(span, "lifetime parameters must be declared \
3595 prior to type parameters");
3599 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
3600 -> (Vec<Arg> , bool) {
3602 let mut args: Vec<Option<Arg>> =
3603 self.parse_unspanned_seq(
3606 seq_sep_trailing_allowed(token::COMMA),
3608 if p.token == token::DOTDOTDOT {
3611 if p.token != token::RPAREN {
3614 "`...` must be last in argument list for variadic function");
3619 "only foreign functions are allowed to be variadic");
3623 Some(p.parse_arg_general(named_args))
3628 let variadic = match args.pop() {
3631 // Need to put back that last arg
3638 if variadic && args.is_empty() {
3640 "variadic function must be declared with at least one named argument");
3643 let args = args.move_iter().map(|x| x.unwrap()).collect();
3648 // parse the argument list and result type of a function declaration
3649 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> P<FnDecl> {
3651 let (args, variadic) = self.parse_fn_args(true, allow_variadic);
3652 let (ret_style, ret_ty) = self.parse_ret_ty();
3662 fn is_self_ident(&mut self) -> bool {
3664 token::IDENT(id, false) => id.name == special_idents::self_.name,
3669 fn expect_self_ident(&mut self) {
3670 if !self.is_self_ident() {
3671 let token_str = self.this_token_to_str();
3672 self.fatal(format!("expected `self` but found `{}`",
3673 token_str).as_slice())
3678 // parse the argument list and result type of a function
3679 // that may have a self type.
3680 fn parse_fn_decl_with_self(&mut self, parse_arg_fn: |&mut Parser| -> Arg)
3681 -> (ExplicitSelf, P<FnDecl>) {
3682 fn maybe_parse_borrowed_explicit_self(this: &mut Parser)
3683 -> ast::ExplicitSelf_ {
3684 // The following things are possible to see here:
3689 // fn(&'lt mut self)
3691 // We already know that the current token is `&`.
3693 if this.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) {
3695 this.expect_self_ident();
3696 SelfRegion(None, MutImmutable)
3697 } else if this.look_ahead(1, |t| Parser::token_is_mutability(t)) &&
3699 |t| token::is_keyword(keywords::Self,
3702 let mutability = this.parse_mutability();
3703 this.expect_self_ident();
3704 SelfRegion(None, mutability)
3705 } else if this.look_ahead(1, |t| Parser::token_is_lifetime(t)) &&
3707 |t| token::is_keyword(keywords::Self,
3710 let lifetime = this.parse_lifetime();
3711 this.expect_self_ident();
3712 SelfRegion(Some(lifetime), MutImmutable)
3713 } else if this.look_ahead(1, |t| Parser::token_is_lifetime(t)) &&
3714 this.look_ahead(2, |t| {
3715 Parser::token_is_mutability(t)
3717 this.look_ahead(3, |t| token::is_keyword(keywords::Self,
3720 let lifetime = this.parse_lifetime();
3721 let mutability = this.parse_mutability();
3722 this.expect_self_ident();
3723 SelfRegion(Some(lifetime), mutability)
3729 self.expect(&token::LPAREN);
3731 // A bit of complexity and lookahead is needed here in order to be
3732 // backwards compatible.
3733 let lo = self.span.lo;
3734 let mut mutbl_self = MutImmutable;
3735 let explicit_self = match self.token {
3736 token::BINOP(token::AND) => {
3737 maybe_parse_borrowed_explicit_self(self)
3740 // We need to make sure it isn't a type
3741 if self.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) {
3743 self.expect_self_ident();
3749 token::IDENT(..) if self.is_self_ident() => {
3753 token::BINOP(token::STAR) => {
3754 // Possibly "*self" or "*mut self" -- not supported. Try to avoid
3755 // emitting cryptic "unexpected token" errors.
3757 let _mutability = if Parser::token_is_mutability(&self.token) {
3758 self.parse_mutability()
3759 } else { MutImmutable };
3760 if self.is_self_ident() {
3761 let span = self.span;
3762 self.span_err(span, "cannot pass self by unsafe pointer");
3767 _ if Parser::token_is_mutability(&self.token) &&
3768 self.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) => {
3769 mutbl_self = self.parse_mutability();
3770 self.expect_self_ident();
3773 _ if Parser::token_is_mutability(&self.token) &&
3774 self.look_ahead(1, |t| *t == token::TILDE) &&
3775 self.look_ahead(2, |t| token::is_keyword(keywords::Self, t)) => {
3776 mutbl_self = self.parse_mutability();
3778 self.expect_self_ident();
3784 let explicit_self_sp = mk_sp(lo, self.span.hi);
3786 // If we parsed a self type, expect a comma before the argument list.
3787 let fn_inputs = if explicit_self != SelfStatic {
3791 let sep = seq_sep_trailing_disallowed(token::COMMA);
3792 let mut fn_inputs = self.parse_seq_to_before_end(
3797 fn_inputs.unshift(Arg::new_self(explicit_self_sp, mutbl_self));
3801 vec!(Arg::new_self(explicit_self_sp, mutbl_self))
3804 let token_str = self.this_token_to_str();
3805 self.fatal(format!("expected `,` or `)`, found `{}`",
3806 token_str).as_slice())
3810 let sep = seq_sep_trailing_disallowed(token::COMMA);
3811 self.parse_seq_to_before_end(&token::RPAREN, sep, parse_arg_fn)
3814 self.expect(&token::RPAREN);
3816 let hi = self.span.hi;
3818 let (ret_style, ret_ty) = self.parse_ret_ty();
3820 let fn_decl = P(FnDecl {
3827 (spanned(lo, hi, explicit_self), fn_decl)
3830 // parse the |arg, arg| header on a lambda
3831 fn parse_fn_block_decl(&mut self) -> P<FnDecl> {
3832 let inputs_captures = {
3833 if self.eat(&token::OROR) {
3836 self.parse_unspanned_seq(
3837 &token::BINOP(token::OR),
3838 &token::BINOP(token::OR),
3839 seq_sep_trailing_disallowed(token::COMMA),
3840 |p| p.parse_fn_block_arg()
3844 let output = if self.eat(&token::RARROW) {
3848 id: ast::DUMMY_NODE_ID,
3855 inputs: inputs_captures,
3862 // Parses the `(arg, arg) -> return_type` header on a procedure.
3863 fn parse_proc_decl(&mut self) -> P<FnDecl> {
3865 self.parse_unspanned_seq(&token::LPAREN,
3867 seq_sep_trailing_allowed(token::COMMA),
3868 |p| p.parse_fn_block_arg());
3870 let output = if self.eat(&token::RARROW) {
3874 id: ast::DUMMY_NODE_ID,
3888 // parse the name and optional generic types of a function header.
3889 fn parse_fn_header(&mut self) -> (Ident, ast::Generics) {
3890 let id = self.parse_ident();
3891 let generics = self.parse_generics();
3895 fn mk_item(&mut self, lo: BytePos, hi: BytePos, ident: Ident,
3896 node: Item_, vis: Visibility,
3897 attrs: Vec<Attribute>) -> Gc<Item> {
3901 id: ast::DUMMY_NODE_ID,
3908 // parse an item-position function declaration.
3909 fn parse_item_fn(&mut self, fn_style: FnStyle, abi: abi::Abi) -> ItemInfo {
3910 let (ident, generics) = self.parse_fn_header();
3911 let decl = self.parse_fn_decl(false);
3912 let (inner_attrs, body) = self.parse_inner_attrs_and_block();
3913 (ident, ItemFn(decl, fn_style, abi, generics, body), Some(inner_attrs))
3916 // parse a method in a trait impl, starting with `attrs` attributes.
3917 fn parse_method(&mut self,
3918 already_parsed_attrs: Option<Vec<Attribute>>) -> Gc<Method> {
3919 let next_attrs = self.parse_outer_attributes();
3920 let attrs = match already_parsed_attrs {
3921 Some(mut a) => { a.push_all_move(next_attrs); a }
3925 let lo = self.span.lo;
3927 let visa = self.parse_visibility();
3928 let fn_style = self.parse_fn_style();
3929 let ident = self.parse_ident();
3930 let generics = self.parse_generics();
3931 let (explicit_self, decl) = self.parse_fn_decl_with_self(|p| {
3935 let (inner_attrs, body) = self.parse_inner_attrs_and_block();
3936 let hi = body.span.hi;
3937 let attrs = attrs.append(inner_attrs.as_slice());
3938 box(GC) ast::Method {
3942 explicit_self: explicit_self,
3946 id: ast::DUMMY_NODE_ID,
3947 span: mk_sp(lo, hi),
3952 // parse trait Foo { ... }
3953 fn parse_item_trait(&mut self) -> ItemInfo {
3954 let ident = self.parse_ident();
3955 let tps = self.parse_generics();
3956 let sized = self.parse_for_sized();
3958 // Parse traits, if necessary.
3960 if self.token == token::COLON {
3962 traits = self.parse_trait_ref_list(&token::LBRACE);
3964 traits = Vec::new();
3967 let meths = self.parse_trait_methods();
3968 (ident, ItemTrait(tps, sized, traits, meths), None)
3971 // Parses two variants (with the region/type params always optional):
3972 // impl<T> Foo { ... }
3973 // impl<T> ToStr for ~[T] { ... }
3974 fn parse_item_impl(&mut self) -> ItemInfo {
3975 // First, parse type parameters if necessary.
3976 let generics = self.parse_generics();
3978 // Special case: if the next identifier that follows is '(', don't
3979 // allow this to be parsed as a trait.
3980 let could_be_trait = self.token != token::LPAREN;
3983 let mut ty = self.parse_ty(true);
3985 // Parse traits, if necessary.
3986 let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) {
3987 // New-style trait. Reinterpret the type as a trait.
3988 let opt_trait_ref = match ty.node {
3989 TyPath(ref path, None, node_id) => {
3991 path: /* bad */ (*path).clone(),
3996 self.span_err(ty.span,
3997 "bounded traits are only valid in type position");
4001 self.span_err(ty.span, "not a trait");
4006 ty = self.parse_ty(true);
4012 let mut meths = Vec::new();
4013 self.expect(&token::LBRACE);
4014 let (inner_attrs, next) = self.parse_inner_attrs_and_next();
4015 let mut method_attrs = Some(next);
4016 while !self.eat(&token::RBRACE) {
4017 meths.push(self.parse_method(method_attrs));
4018 method_attrs = None;
4021 let ident = ast_util::impl_pretty_name(&opt_trait, &*ty);
4023 (ident, ItemImpl(generics, opt_trait, ty, meths), Some(inner_attrs))
4026 // parse a::B<String,int>
4027 fn parse_trait_ref(&mut self) -> TraitRef {
4029 path: self.parse_path(LifetimeAndTypesWithoutColons).path,
4030 ref_id: ast::DUMMY_NODE_ID,
4034 // parse B + C<String,int> + D
4035 fn parse_trait_ref_list(&mut self, ket: &token::Token) -> Vec<TraitRef> {
4036 self.parse_seq_to_before_end(
4038 seq_sep_trailing_disallowed(token::BINOP(token::PLUS)),
4039 |p| p.parse_trait_ref()
4043 // parse struct Foo { ... }
4044 fn parse_item_struct(&mut self, is_virtual: bool) -> ItemInfo {
4045 let class_name = self.parse_ident();
4046 let generics = self.parse_generics();
4048 let super_struct = if self.eat(&token::COLON) {
4049 let ty = self.parse_ty(true);
4051 TyPath(_, None, _) => {
4055 self.span_err(ty.span, "not a struct");
4063 let mut fields: Vec<StructField>;
4066 if self.eat(&token::LBRACE) {
4067 // It's a record-like struct.
4068 is_tuple_like = false;
4069 fields = Vec::new();
4070 while self.token != token::RBRACE {
4071 fields.push(self.parse_struct_decl_field());
4073 if fields.len() == 0 {
4074 self.fatal(format!("unit-like struct definition should be \
4075 written as `struct {};`",
4076 token::get_ident(class_name)).as_slice());
4079 } else if self.token == token::LPAREN {
4080 // It's a tuple-like struct.
4081 is_tuple_like = true;
4082 fields = self.parse_unspanned_seq(
4085 seq_sep_trailing_allowed(token::COMMA),
4087 let attrs = p.parse_outer_attributes();
4089 let struct_field_ = ast::StructField_ {
4090 kind: UnnamedField(p.parse_visibility()),
4091 id: ast::DUMMY_NODE_ID,
4092 ty: p.parse_ty(true),
4095 spanned(lo, p.span.hi, struct_field_)
4097 self.expect(&token::SEMI);
4098 } else if self.eat(&token::SEMI) {
4099 // It's a unit-like struct.
4100 is_tuple_like = true;
4101 fields = Vec::new();
4103 let token_str = self.this_token_to_str();
4104 self.fatal(format!("expected `{}`, `(`, or `;` after struct \
4105 name but found `{}`", "{",
4106 token_str).as_slice())
4109 let _ = ast::DUMMY_NODE_ID; // FIXME: Workaround for crazy bug.
4110 let new_id = ast::DUMMY_NODE_ID;
4112 ItemStruct(box(GC) ast::StructDef {
4114 ctor_id: if is_tuple_like { Some(new_id) } else { None },
4115 super_struct: super_struct,
4116 is_virtual: is_virtual,
4121 // parse a structure field declaration
4122 pub fn parse_single_struct_field(&mut self,
4124 attrs: Vec<Attribute> )
4126 let a_var = self.parse_name_and_ty(vis, attrs);
4133 let span = self.span;
4134 let token_str = self.this_token_to_str();
4135 self.span_fatal(span,
4136 format!("expected `,`, or `}}` but found `{}`",
4137 token_str).as_slice())
4143 // parse an element of a struct definition
4144 fn parse_struct_decl_field(&mut self) -> StructField {
4146 let attrs = self.parse_outer_attributes();
4148 if self.eat_keyword(keywords::Pub) {
4149 return self.parse_single_struct_field(Public, attrs);
4152 return self.parse_single_struct_field(Inherited, attrs);
4155 // parse visiility: PUB, PRIV, or nothing
4156 fn parse_visibility(&mut self) -> Visibility {
4157 if self.eat_keyword(keywords::Pub) { Public }
4161 fn parse_sized(&mut self) -> Sized {
4162 if self.eat_keyword(keywords::Type) { DynSize }
4166 fn parse_for_sized(&mut self) -> Sized {
4167 if self.eat_keyword(keywords::For) {
4168 if !self.eat_keyword(keywords::Type) {
4169 let last_span = self.last_span;
4170 self.span_err(last_span,
4171 "expected 'type' after for in trait item");
4179 // given a termination token and a vector of already-parsed
4180 // attributes (of length 0 or 1), parse all of the items in a module
4181 fn parse_mod_items(&mut self,
4183 first_item_attrs: Vec<Attribute>,
4186 // parse all of the items up to closing or an attribute.
4187 // view items are legal here.
4188 let ParsedItemsAndViewItems {
4189 attrs_remaining: attrs_remaining,
4190 view_items: view_items,
4191 items: starting_items,
4193 } = self.parse_items_and_view_items(first_item_attrs, true, true);
4194 let mut items: Vec<Gc<Item>> = starting_items;
4195 let attrs_remaining_len = attrs_remaining.len();
4197 // don't think this other loop is even necessary....
4199 let mut first = true;
4200 while self.token != term {
4201 let mut attrs = self.parse_outer_attributes();
4203 attrs = attrs_remaining.clone().append(attrs.as_slice());
4206 debug!("parse_mod_items: parse_item_or_view_item(attrs={:?})",
4208 match self.parse_item_or_view_item(attrs,
4209 true /* macros allowed */) {
4210 IoviItem(item) => items.push(item),
4211 IoviViewItem(view_item) => {
4212 self.span_fatal(view_item.span,
4213 "view items must be declared at the top of \
4217 let token_str = self.this_token_to_str();
4218 self.fatal(format!("expected item but found `{}`",
4219 token_str).as_slice())
4224 if first && attrs_remaining_len > 0u {
4225 // We parsed attributes for the first item but didn't find it
4226 let last_span = self.last_span;
4227 self.span_err(last_span, "expected item after attributes");
4231 inner: mk_sp(inner_lo, self.span.lo),
4232 view_items: view_items,
4237 fn parse_item_const(&mut self) -> ItemInfo {
4238 let m = if self.eat_keyword(keywords::Mut) {MutMutable} else {MutImmutable};
4239 let id = self.parse_ident();
4240 self.expect(&token::COLON);
4241 let ty = self.parse_ty(true);
4242 self.expect(&token::EQ);
4243 let e = self.parse_expr();
4244 self.commit_expr_expecting(e, token::SEMI);
4245 (id, ItemStatic(ty, m, e), None)
4248 // parse a `mod <foo> { ... }` or `mod <foo>;` item
4249 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> ItemInfo {
4250 let id_span = self.span;
4251 let id = self.parse_ident();
4252 if self.token == token::SEMI {
4254 // This mod is in an external file. Let's go get it!
4255 let (m, attrs) = self.eval_src_mod(id, outer_attrs, id_span);
4256 (id, m, Some(attrs))
4258 self.push_mod_path(id, outer_attrs);
4259 self.expect(&token::LBRACE);
4260 let mod_inner_lo = self.span.lo;
4261 let old_owns_directory = self.owns_directory;
4262 self.owns_directory = true;
4263 let (inner, next) = self.parse_inner_attrs_and_next();
4264 let m = self.parse_mod_items(token::RBRACE, next, mod_inner_lo);
4265 self.expect(&token::RBRACE);
4266 self.owns_directory = old_owns_directory;
4267 self.pop_mod_path();
4268 (id, ItemMod(m), Some(inner))
4272 fn push_mod_path(&mut self, id: Ident, attrs: &[Attribute]) {
4273 let default_path = self.id_to_interned_str(id);
4274 let file_path = match ::attr::first_attr_value_str_by_name(attrs,
4277 None => default_path,
4279 self.mod_path_stack.push(file_path)
4282 fn pop_mod_path(&mut self) {
4283 self.mod_path_stack.pop().unwrap();
4286 // read a module from a source file.
4287 fn eval_src_mod(&mut self,
4289 outer_attrs: &[ast::Attribute],
4291 -> (ast::Item_, Vec<ast::Attribute> ) {
4292 let mut prefix = Path::new(self.sess.span_diagnostic.cm.span_to_filename(self.span));
4294 let mod_path = Path::new(".").join_many(self.mod_path_stack.as_slice());
4295 let dir_path = prefix.join(&mod_path);
4296 let mod_string = token::get_ident(id);
4297 let (file_path, owns_directory) = match ::attr::first_attr_value_str_by_name(
4298 outer_attrs, "path") {
4299 Some(d) => (dir_path.join(d), true),
4301 let mod_name = mod_string.get().to_string();
4302 let default_path_str = format!("{}.rs", mod_name);
4303 let secondary_path_str = format!("{}/mod.rs", mod_name);
4304 let default_path = dir_path.join(default_path_str.as_slice());
4305 let secondary_path = dir_path.join(secondary_path_str.as_slice());
4306 let default_exists = default_path.exists();
4307 let secondary_exists = secondary_path.exists();
4309 if !self.owns_directory {
4310 self.span_err(id_sp,
4311 "cannot declare a new module at this location");
4312 let this_module = match self.mod_path_stack.last() {
4313 Some(name) => name.get().to_string(),
4314 None => self.root_module_name.get_ref().clone(),
4316 self.span_note(id_sp,
4317 format!("maybe move this module `{0}` \
4318 to its own directory via \
4320 this_module).as_slice());
4321 if default_exists || secondary_exists {
4322 self.span_note(id_sp,
4323 format!("... or maybe `use` the module \
4324 `{}` instead of possibly \
4326 mod_name).as_slice());
4328 self.abort_if_errors();
4331 match (default_exists, secondary_exists) {
4332 (true, false) => (default_path, false),
4333 (false, true) => (secondary_path, true),
4335 self.span_fatal(id_sp,
4336 format!("file not found for module \
4338 mod_name).as_slice());
4343 format!("file for module `{}` found at both {} \
4347 secondary_path_str).as_slice());
4353 self.eval_src_mod_from_path(file_path, owns_directory,
4354 mod_string.get().to_string(), id_sp)
4357 fn eval_src_mod_from_path(&mut self,
4359 owns_directory: bool,
4361 id_sp: Span) -> (ast::Item_, Vec<ast::Attribute> ) {
4362 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
4363 match included_mod_stack.iter().position(|p| *p == path) {
4365 let mut err = String::from_str("circular modules: ");
4366 let len = included_mod_stack.len();
4367 for p in included_mod_stack.slice(i, len).iter() {
4368 err.push_str(p.display().as_maybe_owned().as_slice());
4369 err.push_str(" -> ");
4371 err.push_str(path.display().as_maybe_owned().as_slice());
4372 self.span_fatal(id_sp, err.as_slice());
4376 included_mod_stack.push(path.clone());
4377 drop(included_mod_stack);
4380 new_sub_parser_from_file(self.sess,
4386 let mod_inner_lo = p0.span.lo;
4387 let (mod_attrs, next) = p0.parse_inner_attrs_and_next();
4388 let first_item_outer_attrs = next;
4389 let m0 = p0.parse_mod_items(token::EOF, first_item_outer_attrs, mod_inner_lo);
4390 self.sess.included_mod_stack.borrow_mut().pop();
4391 return (ast::ItemMod(m0), mod_attrs);
4394 // parse a function declaration from a foreign module
4395 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility,
4396 attrs: Vec<Attribute>) -> Gc<ForeignItem> {
4397 let lo = self.span.lo;
4398 self.expect_keyword(keywords::Fn);
4400 let (ident, generics) = self.parse_fn_header();
4401 let decl = self.parse_fn_decl(true);
4402 let hi = self.span.hi;
4403 self.expect(&token::SEMI);
4404 box(GC) ast::ForeignItem { ident: ident,
4406 node: ForeignItemFn(decl, generics),
4407 id: ast::DUMMY_NODE_ID,
4408 span: mk_sp(lo, hi),
4412 // parse a static item from a foreign module
4413 fn parse_item_foreign_static(&mut self, vis: ast::Visibility,
4414 attrs: Vec<Attribute> ) -> Gc<ForeignItem> {
4415 let lo = self.span.lo;
4417 self.expect_keyword(keywords::Static);
4418 let mutbl = self.eat_keyword(keywords::Mut);
4420 let ident = self.parse_ident();
4421 self.expect(&token::COLON);
4422 let ty = self.parse_ty(true);
4423 let hi = self.span.hi;
4424 self.expect(&token::SEMI);
4425 box(GC) ast::ForeignItem {
4428 node: ForeignItemStatic(ty, mutbl),
4429 id: ast::DUMMY_NODE_ID,
4430 span: mk_sp(lo, hi),
4435 // parse safe/unsafe and fn
4436 fn parse_fn_style(&mut self) -> FnStyle {
4437 if self.eat_keyword(keywords::Fn) { NormalFn }
4438 else if self.eat_keyword(keywords::Unsafe) {
4439 self.expect_keyword(keywords::Fn);
4442 else { self.unexpected(); }
4446 // at this point, this is essentially a wrapper for
4447 // parse_foreign_items.
4448 fn parse_foreign_mod_items(&mut self,
4450 first_item_attrs: Vec<Attribute> )
4452 let ParsedItemsAndViewItems {
4453 attrs_remaining: attrs_remaining,
4454 view_items: view_items,
4456 foreign_items: foreign_items
4457 } = self.parse_foreign_items(first_item_attrs, true);
4458 if ! attrs_remaining.is_empty() {
4459 let last_span = self.last_span;
4460 self.span_err(last_span,
4461 "expected item after attributes");
4463 assert!(self.token == token::RBRACE);
4466 view_items: view_items,
4467 items: foreign_items
4471 /// Parse extern crate links
4475 /// extern crate url;
4476 /// extern crate foo = "bar";
4477 fn parse_item_extern_crate(&mut self,
4479 visibility: Visibility,
4480 attrs: Vec<Attribute> )
4483 let (maybe_path, ident) = match self.token {
4484 token::IDENT(..) => {
4485 let the_ident = self.parse_ident();
4486 self.expect_one_of(&[], &[token::EQ, token::SEMI]);
4487 let path = if self.token == token::EQ {
4489 Some(self.parse_str())
4492 self.expect(&token::SEMI);
4496 let span = self.span;
4497 let token_str = self.this_token_to_str();
4498 self.span_fatal(span,
4499 format!("expected extern crate name but \
4501 token_str).as_slice());
4505 IoviViewItem(ast::ViewItem {
4506 node: ViewItemExternCrate(ident, maybe_path, ast::DUMMY_NODE_ID),
4509 span: mk_sp(lo, self.last_span.hi)
4513 /// Parse `extern` for foreign ABIs
4516 /// `extern` is expected to have been
4517 /// consumed before calling this method
4523 fn parse_item_foreign_mod(&mut self,
4525 opt_abi: Option<abi::Abi>,
4526 visibility: Visibility,
4527 attrs: Vec<Attribute> )
4530 self.expect(&token::LBRACE);
4532 let abi = opt_abi.unwrap_or(abi::C);
4534 let (inner, next) = self.parse_inner_attrs_and_next();
4535 let m = self.parse_foreign_mod_items(abi, next);
4536 self.expect(&token::RBRACE);
4538 let last_span = self.last_span;
4539 let item = self.mk_item(lo,
4541 special_idents::invalid,
4544 maybe_append(attrs, Some(inner)));
4545 return IoviItem(item);
4548 // parse type Foo = Bar;
4549 fn parse_item_type(&mut self) -> ItemInfo {
4550 let ident = self.parse_ident();
4551 let tps = self.parse_generics();
4552 self.expect(&token::EQ);
4553 let ty = self.parse_ty(true);
4554 self.expect(&token::SEMI);
4555 (ident, ItemTy(ty, tps), None)
4558 // parse a structure-like enum variant definition
4559 // this should probably be renamed or refactored...
4560 fn parse_struct_def(&mut self) -> Gc<StructDef> {
4561 let mut fields: Vec<StructField> = Vec::new();
4562 while self.token != token::RBRACE {
4563 fields.push(self.parse_struct_decl_field());
4567 return box(GC) ast::StructDef {
4575 // parse the part of an "enum" decl following the '{'
4576 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> EnumDef {
4577 let mut variants = Vec::new();
4578 let mut all_nullary = true;
4579 let mut have_disr = false;
4580 while self.token != token::RBRACE {
4581 let variant_attrs = self.parse_outer_attributes();
4582 let vlo = self.span.lo;
4584 let vis = self.parse_visibility();
4588 let mut args = Vec::new();
4589 let mut disr_expr = None;
4590 ident = self.parse_ident();
4591 if self.eat(&token::LBRACE) {
4592 // Parse a struct variant.
4593 all_nullary = false;
4594 kind = StructVariantKind(self.parse_struct_def());
4595 } else if self.token == token::LPAREN {
4596 all_nullary = false;
4597 let arg_tys = self.parse_enum_variant_seq(
4600 seq_sep_trailing_disallowed(token::COMMA),
4601 |p| p.parse_ty(true)
4603 for ty in arg_tys.move_iter() {
4604 args.push(ast::VariantArg {
4606 id: ast::DUMMY_NODE_ID,
4609 kind = TupleVariantKind(args);
4610 } else if self.eat(&token::EQ) {
4612 disr_expr = Some(self.parse_expr());
4613 kind = TupleVariantKind(args);
4615 kind = TupleVariantKind(Vec::new());
4618 let vr = ast::Variant_ {
4620 attrs: variant_attrs,
4622 id: ast::DUMMY_NODE_ID,
4623 disr_expr: disr_expr,
4626 variants.push(P(spanned(vlo, self.last_span.hi, vr)));
4628 if !self.eat(&token::COMMA) { break; }
4630 self.expect(&token::RBRACE);
4631 if have_disr && !all_nullary {
4632 self.fatal("discriminator values can only be used with a c-like \
4636 ast::EnumDef { variants: variants }
4639 // parse an "enum" declaration
4640 fn parse_item_enum(&mut self) -> ItemInfo {
4641 let id = self.parse_ident();
4642 let generics = self.parse_generics();
4643 self.expect(&token::LBRACE);
4645 let enum_definition = self.parse_enum_def(&generics);
4646 (id, ItemEnum(enum_definition, generics), None)
4649 fn fn_expr_lookahead(tok: &token::Token) -> bool {
4651 token::LPAREN | token::AT | token::TILDE | token::BINOP(_) => true,
4656 // Parses a string as an ABI spec on an extern type or module. Consumes
4657 // the `extern` keyword, if one is found.
4658 fn parse_opt_abi(&mut self) -> Option<abi::Abi> {
4660 token::LIT_STR(s) | token::LIT_STR_RAW(s, _) => {
4662 let identifier_string = token::get_ident(s);
4663 let the_string = identifier_string.get();
4664 match abi::lookup(the_string) {
4665 Some(abi) => Some(abi),
4667 let last_span = self.last_span;
4670 format!("illegal ABI: expected one of [{}], \
4672 abi::all_names().connect(", "),
4673 the_string).as_slice());
4683 // parse one of the items or view items allowed by the
4684 // flags; on failure, return IoviNone.
4685 // NB: this function no longer parses the items inside an
4687 fn parse_item_or_view_item(&mut self,
4688 attrs: Vec<Attribute> ,
4689 macros_allowed: bool)
4692 INTERPOLATED(token::NtItem(item)) => {
4694 let new_attrs = attrs.append(item.attrs.as_slice());
4695 return IoviItem(box(GC) Item {
4703 let lo = self.span.lo;
4705 let visibility = self.parse_visibility();
4707 // must be a view item:
4708 if self.eat_keyword(keywords::Use) {
4709 // USE ITEM (IoviViewItem)
4710 let view_item = self.parse_use();
4711 self.expect(&token::SEMI);
4712 return IoviViewItem(ast::ViewItem {
4716 span: mk_sp(lo, self.last_span.hi)
4719 // either a view item or an item:
4720 if self.eat_keyword(keywords::Extern) {
4721 let next_is_mod = self.eat_keyword(keywords::Mod);
4723 if next_is_mod || self.eat_keyword(keywords::Crate) {
4725 let last_span = self.last_span;
4726 self.span_err(mk_sp(lo, last_span.hi),
4727 format!("`extern mod` is obsolete, use \
4728 `extern crate` instead \
4729 to refer to external \
4730 crates.").as_slice())
4732 return self.parse_item_extern_crate(lo, visibility, attrs);
4735 let opt_abi = self.parse_opt_abi();
4737 if self.eat_keyword(keywords::Fn) {
4738 // EXTERN FUNCTION ITEM
4739 let abi = opt_abi.unwrap_or(abi::C);
4740 let (ident, item_, extra_attrs) =
4741 self.parse_item_fn(NormalFn, abi);
4742 let last_span = self.last_span;
4743 let item = self.mk_item(lo,
4748 maybe_append(attrs, extra_attrs));
4749 return IoviItem(item);
4750 } else if self.token == token::LBRACE {
4751 return self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs);
4754 let span = self.span;
4755 let token_str = self.this_token_to_str();
4756 self.span_fatal(span,
4757 format!("expected `{}` or `fn` but found `{}`", "{",
4758 token_str).as_slice());
4761 let is_virtual = self.eat_keyword(keywords::Virtual);
4762 if is_virtual && !self.is_keyword(keywords::Struct) {
4763 let span = self.span;
4765 "`virtual` keyword may only be used with `struct`");
4768 // the rest are all guaranteed to be items:
4769 if self.is_keyword(keywords::Static) {
4772 let (ident, item_, extra_attrs) = self.parse_item_const();
4773 let last_span = self.last_span;
4774 let item = self.mk_item(lo,
4779 maybe_append(attrs, extra_attrs));
4780 return IoviItem(item);
4782 if self.is_keyword(keywords::Fn) &&
4783 self.look_ahead(1, |f| !Parser::fn_expr_lookahead(f)) {
4786 let (ident, item_, extra_attrs) =
4787 self.parse_item_fn(NormalFn, abi::Rust);
4788 let last_span = self.last_span;
4789 let item = self.mk_item(lo,
4794 maybe_append(attrs, extra_attrs));
4795 return IoviItem(item);
4797 if self.is_keyword(keywords::Unsafe)
4798 && self.look_ahead(1u, |t| *t != token::LBRACE) {
4799 // UNSAFE FUNCTION ITEM
4801 let abi = if self.eat_keyword(keywords::Extern) {
4802 self.parse_opt_abi().unwrap_or(abi::C)
4806 self.expect_keyword(keywords::Fn);
4807 let (ident, item_, extra_attrs) =
4808 self.parse_item_fn(UnsafeFn, abi);
4809 let last_span = self.last_span;
4810 let item = self.mk_item(lo,
4815 maybe_append(attrs, extra_attrs));
4816 return IoviItem(item);
4818 if self.eat_keyword(keywords::Mod) {
4820 let (ident, item_, extra_attrs) =
4821 self.parse_item_mod(attrs.as_slice());
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::Type) {
4833 let (ident, item_, extra_attrs) = self.parse_item_type();
4834 let last_span = self.last_span;
4835 let item = self.mk_item(lo,
4840 maybe_append(attrs, extra_attrs));
4841 return IoviItem(item);
4843 if self.eat_keyword(keywords::Enum) {
4845 let (ident, item_, extra_attrs) = self.parse_item_enum();
4846 let last_span = self.last_span;
4847 let item = self.mk_item(lo,
4852 maybe_append(attrs, extra_attrs));
4853 return IoviItem(item);
4855 if self.eat_keyword(keywords::Trait) {
4857 let (ident, item_, extra_attrs) = self.parse_item_trait();
4858 let last_span = self.last_span;
4859 let item = self.mk_item(lo,
4864 maybe_append(attrs, extra_attrs));
4865 return IoviItem(item);
4867 if self.eat_keyword(keywords::Impl) {
4869 let (ident, item_, extra_attrs) = self.parse_item_impl();
4870 let last_span = self.last_span;
4871 let item = self.mk_item(lo,
4876 maybe_append(attrs, extra_attrs));
4877 return IoviItem(item);
4879 if self.eat_keyword(keywords::Struct) {
4881 let (ident, item_, extra_attrs) = self.parse_item_struct(is_virtual);
4882 let last_span = self.last_span;
4883 let item = self.mk_item(lo,
4888 maybe_append(attrs, extra_attrs));
4889 return IoviItem(item);
4891 self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility)
4894 // parse a foreign item; on failure, return IoviNone.
4895 fn parse_foreign_item(&mut self,
4896 attrs: Vec<Attribute> ,
4897 macros_allowed: bool)
4899 maybe_whole!(iovi self, NtItem);
4900 let lo = self.span.lo;
4902 let visibility = self.parse_visibility();
4904 if self.is_keyword(keywords::Static) {
4905 // FOREIGN STATIC ITEM
4906 let item = self.parse_item_foreign_static(visibility, attrs);
4907 return IoviForeignItem(item);
4909 if self.is_keyword(keywords::Fn) || self.is_keyword(keywords::Unsafe) {
4910 // FOREIGN FUNCTION ITEM
4911 let item = self.parse_item_foreign_fn(visibility, attrs);
4912 return IoviForeignItem(item);
4914 self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility)
4917 // this is the fall-through for parsing items.
4918 fn parse_macro_use_or_failure(
4920 attrs: Vec<Attribute> ,
4921 macros_allowed: bool,
4923 visibility: Visibility
4924 ) -> ItemOrViewItem {
4925 if macros_allowed && !token::is_any_keyword(&self.token)
4926 && self.look_ahead(1, |t| *t == token::NOT)
4927 && (self.look_ahead(2, |t| is_plain_ident(t))
4928 || self.look_ahead(2, |t| *t == token::LPAREN)
4929 || self.look_ahead(2, |t| *t == token::LBRACE)) {
4930 // MACRO INVOCATION ITEM
4933 let pth = self.parse_path(NoTypesAllowed).path;
4934 self.expect(&token::NOT);
4936 // a 'special' identifier (like what `macro_rules!` uses)
4937 // is optional. We should eventually unify invoc syntax
4939 let id = if is_plain_ident(&self.token) {
4942 token::special_idents::invalid // no special identifier
4944 // eat a matched-delimiter token tree:
4945 let tts = match token::close_delimiter_for(&self.token) {
4948 self.parse_seq_to_end(&ket,
4950 |p| p.parse_token_tree())
4952 None => self.fatal("expected open delimiter")
4954 // single-variant-enum... :
4955 let m = ast::MacInvocTT(pth, tts, EMPTY_CTXT);
4956 let m: ast::Mac = codemap::Spanned { node: m,
4957 span: mk_sp(self.span.lo,
4959 let item_ = ItemMac(m);
4960 let last_span = self.last_span;
4961 let item = self.mk_item(lo,
4967 return IoviItem(item);
4970 // FAILURE TO PARSE ITEM
4971 if visibility != Inherited {
4972 let mut s = String::from_str("unmatched visibility `");
4973 if visibility == Public {
4979 let last_span = self.last_span;
4980 self.span_fatal(last_span, s.as_slice());
4982 return IoviNone(attrs);
4985 pub fn parse_item_with_outer_attributes(&mut self) -> Option<Gc<Item>> {
4986 let attrs = self.parse_outer_attributes();
4987 self.parse_item(attrs)
4990 pub fn parse_item(&mut self, attrs: Vec<Attribute> ) -> Option<Gc<Item>> {
4991 match self.parse_item_or_view_item(attrs, true) {
4992 IoviNone(_) => None,
4994 self.fatal("view items are not allowed here"),
4995 IoviForeignItem(_) =>
4996 self.fatal("foreign items are not allowed here"),
4997 IoviItem(item) => Some(item)
5001 // parse, e.g., "use a::b::{z,y}"
5002 fn parse_use(&mut self) -> ViewItem_ {
5003 return ViewItemUse(self.parse_view_path());
5007 // matches view_path : MOD? IDENT EQ non_global_path
5008 // | MOD? non_global_path MOD_SEP LBRACE RBRACE
5009 // | MOD? non_global_path MOD_SEP LBRACE ident_seq RBRACE
5010 // | MOD? non_global_path MOD_SEP STAR
5011 // | MOD? non_global_path
5012 fn parse_view_path(&mut self) -> Gc<ViewPath> {
5013 let lo = self.span.lo;
5015 if self.token == token::LBRACE {
5017 let idents = self.parse_unspanned_seq(
5018 &token::LBRACE, &token::RBRACE,
5019 seq_sep_trailing_allowed(token::COMMA),
5020 |p| p.parse_path_list_ident());
5021 let path = ast::Path {
5022 span: mk_sp(lo, self.span.hi),
5024 segments: Vec::new()
5026 return box(GC) spanned(lo, self.span.hi,
5027 ViewPathList(path, idents, ast::DUMMY_NODE_ID));
5030 let first_ident = self.parse_ident();
5031 let mut path = vec!(first_ident);
5036 let path_lo = self.span.lo;
5037 path = vec!(self.parse_ident());
5038 while self.token == token::MOD_SEP {
5040 let id = self.parse_ident();
5043 let path = ast::Path {
5044 span: mk_sp(path_lo, self.span.hi),
5046 segments: path.move_iter().map(|identifier| {
5048 identifier: identifier,
5049 lifetimes: Vec::new(),
5050 types: OwnedSlice::empty(),
5054 return box(GC) spanned(lo, self.span.hi,
5055 ViewPathSimple(first_ident, path,
5056 ast::DUMMY_NODE_ID));
5060 // foo::bar or foo::{a,b,c} or foo::*
5061 while self.token == token::MOD_SEP {
5065 token::IDENT(i, _) => {
5070 // foo::bar::{a,b,c}
5072 let idents = self.parse_unspanned_seq(
5075 seq_sep_trailing_allowed(token::COMMA),
5076 |p| p.parse_path_list_ident()
5078 let path = ast::Path {
5079 span: mk_sp(lo, self.span.hi),
5081 segments: path.move_iter().map(|identifier| {
5083 identifier: identifier,
5084 lifetimes: Vec::new(),
5085 types: OwnedSlice::empty(),
5089 return box(GC) spanned(lo, self.span.hi,
5090 ViewPathList(path, idents, ast::DUMMY_NODE_ID));
5094 token::BINOP(token::STAR) => {
5096 let path = ast::Path {
5097 span: mk_sp(lo, self.span.hi),
5099 segments: path.move_iter().map(|identifier| {
5101 identifier: identifier,
5102 lifetimes: Vec::new(),
5103 types: OwnedSlice::empty(),
5107 return box(GC) spanned(lo, self.span.hi,
5108 ViewPathGlob(path, ast::DUMMY_NODE_ID));
5117 let last = *path.get(path.len() - 1u);
5118 let path = ast::Path {
5119 span: mk_sp(lo, self.span.hi),
5121 segments: path.move_iter().map(|identifier| {
5123 identifier: identifier,
5124 lifetimes: Vec::new(),
5125 types: OwnedSlice::empty(),
5129 return box(GC) spanned(lo,
5131 ViewPathSimple(last, path, ast::DUMMY_NODE_ID));
5134 // Parses a sequence of items. Stops when it finds program
5135 // text that can't be parsed as an item
5136 // - mod_items uses extern_mod_allowed = true
5137 // - block_tail_ uses extern_mod_allowed = false
5138 fn parse_items_and_view_items(&mut self,
5139 first_item_attrs: Vec<Attribute> ,
5140 mut extern_mod_allowed: bool,
5141 macros_allowed: bool)
5142 -> ParsedItemsAndViewItems {
5143 let mut attrs = first_item_attrs.append(self.parse_outer_attributes().as_slice());
5144 // First, parse view items.
5145 let mut view_items : Vec<ast::ViewItem> = Vec::new();
5146 let mut items = Vec::new();
5148 // I think this code would probably read better as a single
5149 // loop with a mutable three-state-variable (for extern crates,
5150 // view items, and regular items) ... except that because
5151 // of macros, I'd like to delay that entire check until later.
5153 match self.parse_item_or_view_item(attrs, macros_allowed) {
5154 IoviNone(attrs) => {
5155 return ParsedItemsAndViewItems {
5156 attrs_remaining: attrs,
5157 view_items: view_items,
5159 foreign_items: Vec::new()
5162 IoviViewItem(view_item) => {
5163 match view_item.node {
5164 ViewItemUse(..) => {
5165 // `extern crate` must precede `use`.
5166 extern_mod_allowed = false;
5168 ViewItemExternCrate(..) if !extern_mod_allowed => {
5169 self.span_err(view_item.span,
5170 "\"extern crate\" declarations are \
5173 ViewItemExternCrate(..) => {}
5175 view_items.push(view_item);
5179 attrs = self.parse_outer_attributes();
5182 IoviForeignItem(_) => {
5186 attrs = self.parse_outer_attributes();
5189 // Next, parse items.
5191 match self.parse_item_or_view_item(attrs, macros_allowed) {
5192 IoviNone(returned_attrs) => {
5193 attrs = returned_attrs;
5196 IoviViewItem(view_item) => {
5197 attrs = self.parse_outer_attributes();
5198 self.span_err(view_item.span,
5199 "`use` and `extern crate` declarations must precede items");
5202 attrs = self.parse_outer_attributes();
5205 IoviForeignItem(_) => {
5211 ParsedItemsAndViewItems {
5212 attrs_remaining: attrs,
5213 view_items: view_items,
5215 foreign_items: Vec::new()
5219 // Parses a sequence of foreign items. Stops when it finds program
5220 // text that can't be parsed as an item
5221 fn parse_foreign_items(&mut self, first_item_attrs: Vec<Attribute> ,
5222 macros_allowed: bool)
5223 -> ParsedItemsAndViewItems {
5224 let mut attrs = first_item_attrs.append(self.parse_outer_attributes().as_slice());
5225 let mut foreign_items = Vec::new();
5227 match self.parse_foreign_item(attrs, macros_allowed) {
5228 IoviNone(returned_attrs) => {
5229 if self.token == token::RBRACE {
5230 attrs = returned_attrs;
5235 IoviViewItem(view_item) => {
5236 // I think this can't occur:
5237 self.span_err(view_item.span,
5238 "`use` and `extern crate` declarations must precede items");
5241 // FIXME #5668: this will occur for a macro invocation:
5242 self.span_fatal(item.span, "macros cannot expand to foreign items");
5244 IoviForeignItem(foreign_item) => {
5245 foreign_items.push(foreign_item);
5248 attrs = self.parse_outer_attributes();
5251 ParsedItemsAndViewItems {
5252 attrs_remaining: attrs,
5253 view_items: Vec::new(),
5255 foreign_items: foreign_items
5259 // Parses a source module as a crate. This is the main
5260 // entry point for the parser.
5261 pub fn parse_crate_mod(&mut self) -> Crate {
5262 let lo = self.span.lo;
5263 // parse the crate's inner attrs, maybe (oops) one
5264 // of the attrs of an item:
5265 let (inner, next) = self.parse_inner_attrs_and_next();
5266 let first_item_outer_attrs = next;
5267 // parse the items inside the crate:
5268 let m = self.parse_mod_items(token::EOF, first_item_outer_attrs, lo);
5273 config: self.cfg.clone(),
5274 span: mk_sp(lo, self.span.lo)
5278 pub fn parse_optional_str(&mut self)
5279 -> Option<(InternedString, ast::StrStyle)> {
5280 let (s, style) = match self.token {
5281 token::LIT_STR(s) => (self.id_to_interned_str(s), ast::CookedStr),
5282 token::LIT_STR_RAW(s, n) => {
5283 (self.id_to_interned_str(s), ast::RawStr(n))
5291 pub fn parse_str(&mut self) -> (InternedString, StrStyle) {
5292 match self.parse_optional_str() {
5294 _ => self.fatal("expected string literal")