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, mut rdr: Box<Reader:>) -> Parser<'a> {
329 let tok0 = rdr.next_token();
331 let placeholder = TokenAndSpan {
332 tok: token::UNDERSCORE,
338 interner: token::get_ident_interner(),
354 restriction: UNRESTRICTED,
356 obsolete_set: HashSet::new(),
357 mod_path_stack: Vec::new(),
358 open_braces: Vec::new(),
359 owns_directory: true,
360 root_module_name: None,
363 // convert a token to a string using self's reader
364 pub fn token_to_str(token: &token::Token) -> String {
368 // convert the current token to a string using self's reader
369 pub fn this_token_to_str(&mut self) -> String {
370 Parser::token_to_str(&self.token)
373 pub fn unexpected_last(&mut self, t: &token::Token) -> ! {
374 let token_str = Parser::token_to_str(t);
375 let last_span = self.last_span;
376 self.span_fatal(last_span, format!("unexpected token: `{}`",
377 token_str).as_slice());
380 pub fn unexpected(&mut self) -> ! {
381 let this_token = self.this_token_to_str();
382 self.fatal(format!("unexpected token: `{}`", this_token).as_slice());
385 // expect and consume the token t. Signal an error if
386 // the next token is not t.
387 pub fn expect(&mut self, t: &token::Token) {
388 if self.token == *t {
391 let token_str = Parser::token_to_str(t);
392 let this_token_str = self.this_token_to_str();
393 self.fatal(format!("expected `{}` but found `{}`",
395 this_token_str).as_slice())
399 // Expect next token to be edible or inedible token. If edible,
400 // then consume it; if inedible, then return without consuming
401 // anything. Signal a fatal error if next token is unexpected.
402 pub fn expect_one_of(&mut self,
403 edible: &[token::Token],
404 inedible: &[token::Token]) {
405 fn tokens_to_str(tokens: &[token::Token]) -> String {
406 let mut i = tokens.iter();
407 // This might be a sign we need a connect method on Iterator.
409 .map_or("".to_string(), |t| Parser::token_to_str(t));
413 b.push_str(Parser::token_to_str(a).as_slice());
417 if edible.contains(&self.token) {
419 } else if inedible.contains(&self.token) {
420 // leave it in the input
422 let expected = edible.iter().map(|x| (*x).clone()).collect::<Vec<_>>().append(inedible);
423 let expect = tokens_to_str(expected.as_slice());
424 let actual = self.this_token_to_str();
426 (if expected.len() != 1 {
427 (format!("expected one of `{}` but found `{}`",
431 (format!("expected `{}` but found `{}`",
439 // Check for erroneous `ident { }`; if matches, signal error and
440 // recover (without consuming any expected input token). Returns
441 // true if and only if input was consumed for recovery.
442 pub fn check_for_erroneous_unit_struct_expecting(&mut self, expected: &[token::Token]) -> bool {
443 if self.token == token::LBRACE
444 && expected.iter().all(|t| *t != token::LBRACE)
445 && self.look_ahead(1, |t| *t == token::RBRACE) {
446 // matched; signal non-fatal error and recover.
447 let span = self.span;
449 "unit-like struct construction is written with no trailing `{ }`");
450 self.eat(&token::LBRACE);
451 self.eat(&token::RBRACE);
458 // Commit to parsing a complete expression `e` expected to be
459 // followed by some token from the set edible + inedible. Recover
460 // from anticipated input errors, discarding erroneous characters.
461 pub fn commit_expr(&mut self, e: Gc<Expr>, edible: &[token::Token],
462 inedible: &[token::Token]) {
463 debug!("commit_expr {:?}", e);
466 // might be unit-struct construction; check for recoverableinput error.
467 let expected = edible.iter().map(|x| (*x).clone()).collect::<Vec<_>>()
469 self.check_for_erroneous_unit_struct_expecting(
470 expected.as_slice());
474 self.expect_one_of(edible, inedible)
477 pub fn commit_expr_expecting(&mut self, e: Gc<Expr>, edible: token::Token) {
478 self.commit_expr(e, &[edible], &[])
481 // Commit to parsing a complete statement `s`, which expects to be
482 // followed by some token from the set edible + inedible. Check
483 // for recoverable input errors, discarding erroneous characters.
484 pub fn commit_stmt(&mut self, s: Gc<Stmt>, edible: &[token::Token],
485 inedible: &[token::Token]) {
486 debug!("commit_stmt {:?}", s);
487 let _s = s; // unused, but future checks might want to inspect `s`.
488 if self.last_token.as_ref().map_or(false, |t| is_ident_or_path(*t)) {
489 let expected = edible.iter().map(|x| (*x).clone()).collect::<Vec<_>>()
490 .append(inedible.as_slice());
491 self.check_for_erroneous_unit_struct_expecting(
492 expected.as_slice());
494 self.expect_one_of(edible, inedible)
497 pub fn commit_stmt_expecting(&mut self, s: Gc<Stmt>, edible: token::Token) {
498 self.commit_stmt(s, &[edible], &[])
501 pub fn parse_ident(&mut self) -> ast::Ident {
502 self.check_strict_keywords();
503 self.check_reserved_keywords();
505 token::IDENT(i, _) => {
509 token::INTERPOLATED(token::NtIdent(..)) => {
510 self.bug("ident interpolation not converted to real token");
513 let token_str = self.this_token_to_str();
514 self.fatal((format!("expected ident, found `{}`",
515 token_str)).as_slice())
520 pub fn parse_path_list_ident(&mut self) -> ast::PathListIdent {
521 let lo = self.span.lo;
522 let ident = self.parse_ident();
523 let hi = self.last_span.hi;
524 spanned(lo, hi, ast::PathListIdent_ { name: ident,
525 id: ast::DUMMY_NODE_ID })
528 // consume token 'tok' if it exists. Returns true if the given
529 // token was present, false otherwise.
530 pub fn eat(&mut self, tok: &token::Token) -> bool {
531 let is_present = self.token == *tok;
532 if is_present { self.bump() }
536 pub fn is_keyword(&mut self, kw: keywords::Keyword) -> bool {
537 token::is_keyword(kw, &self.token)
540 // if the next token is the given keyword, eat it and return
541 // true. Otherwise, return false.
542 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
543 let is_kw = match self.token {
544 token::IDENT(sid, false) => kw.to_ident().name == sid.name,
547 if is_kw { self.bump() }
551 // if the given word is not a keyword, signal an error.
552 // if the next token is not the given word, signal an error.
553 // otherwise, eat it.
554 pub fn expect_keyword(&mut self, kw: keywords::Keyword) {
555 if !self.eat_keyword(kw) {
556 let id_interned_str = token::get_ident(kw.to_ident());
557 let token_str = self.this_token_to_str();
558 self.fatal(format!("expected `{}`, found `{}`",
559 id_interned_str, token_str).as_slice())
563 // signal an error if the given string is a strict keyword
564 pub fn check_strict_keywords(&mut self) {
565 if token::is_strict_keyword(&self.token) {
566 let token_str = self.this_token_to_str();
567 let span = self.span;
569 format!("found `{}` in ident position",
570 token_str).as_slice());
574 // signal an error if the current token is a reserved keyword
575 pub fn check_reserved_keywords(&mut self) {
576 if token::is_reserved_keyword(&self.token) {
577 let token_str = self.this_token_to_str();
578 self.fatal(format!("`{}` is a reserved keyword",
579 token_str).as_slice())
583 // Expect and consume an `&`. If `&&` is seen, replace it with a single
584 // `&` and continue. If an `&` is not seen, signal an error.
585 fn expect_and(&mut self) {
587 token::BINOP(token::AND) => self.bump(),
589 let span = self.span;
590 let lo = span.lo + BytePos(1);
591 self.replace_token(token::BINOP(token::AND), lo, span.hi)
594 let token_str = self.this_token_to_str();
596 Parser::token_to_str(&token::BINOP(token::AND));
597 self.fatal(format!("expected `{}`, found `{}`",
599 token_str).as_slice())
604 // Expect and consume a `|`. If `||` is seen, replace it with a single
605 // `|` and continue. If a `|` is not seen, signal an error.
606 fn expect_or(&mut self) {
608 token::BINOP(token::OR) => self.bump(),
610 let span = self.span;
611 let lo = span.lo + BytePos(1);
612 self.replace_token(token::BINOP(token::OR), lo, span.hi)
615 let found_token = self.this_token_to_str();
617 Parser::token_to_str(&token::BINOP(token::OR));
618 self.fatal(format!("expected `{}`, found `{}`",
620 found_token).as_slice())
625 // Attempt to consume a `<`. If `<<` is seen, replace it with a single
626 // `<` and continue. If a `<` is not seen, return false.
628 // This is meant to be used when parsing generics on a path to get the
629 // starting token. The `force` parameter is used to forcefully break up a
630 // `<<` token. If `force` is false, then `<<` is only broken when a lifetime
631 // shows up next. For example, consider the expression:
633 // foo as bar << test
635 // The parser needs to know if `bar <<` is the start of a generic path or if
636 // it's a left-shift token. If `test` were a lifetime, then it's impossible
637 // for the token to be a left-shift, but if it's not a lifetime, then it's
638 // considered a left-shift.
640 // The reason for this is that the only current ambiguity with `<<` is when
641 // parsing closure types:
644 // impl Foo<<'a> ||>() { ... }
645 fn eat_lt(&mut self, force: bool) -> bool {
647 token::LT => { self.bump(); true }
648 token::BINOP(token::SHL) => {
649 let next_lifetime = self.look_ahead(1, |t| match *t {
650 token::LIFETIME(..) => true,
653 if force || next_lifetime {
654 let span = self.span;
655 let lo = span.lo + BytePos(1);
656 self.replace_token(token::LT, lo, span.hi);
666 fn expect_lt(&mut self) {
667 if !self.eat_lt(true) {
668 let found_token = self.this_token_to_str();
669 let token_str = Parser::token_to_str(&token::LT);
670 self.fatal(format!("expected `{}`, found `{}`",
672 found_token).as_slice())
676 // Parse a sequence bracketed by `|` and `|`, stopping before the `|`.
677 fn parse_seq_to_before_or<T>(
680 f: |&mut Parser| -> T)
682 let mut first = true;
683 let mut vector = Vec::new();
684 while self.token != token::BINOP(token::OR) &&
685 self.token != token::OROR {
697 // expect and consume a GT. if a >> is seen, replace it
698 // with a single > and continue. If a GT is not seen,
700 pub fn expect_gt(&mut self) {
702 token::GT => self.bump(),
703 token::BINOP(token::SHR) => {
704 let span = self.span;
705 let lo = span.lo + BytePos(1);
706 self.replace_token(token::GT, lo, span.hi)
709 let gt_str = Parser::token_to_str(&token::GT);
710 let this_token_str = self.this_token_to_str();
711 self.fatal(format!("expected `{}`, found `{}`",
713 this_token_str).as_slice())
718 // parse a sequence bracketed by '<' and '>', stopping
720 pub fn parse_seq_to_before_gt<T>(
722 sep: Option<token::Token>,
723 f: |&mut Parser| -> T)
725 let mut first = true;
726 let mut v = Vec::new();
727 while self.token != token::GT
728 && self.token != token::BINOP(token::SHR) {
731 if first { first = false; }
732 else { self.expect(t); }
738 return OwnedSlice::from_vec(v);
741 pub fn parse_seq_to_gt<T>(
743 sep: Option<token::Token>,
744 f: |&mut Parser| -> T)
746 let v = self.parse_seq_to_before_gt(sep, f);
751 // parse a sequence, including the closing delimiter. The function
752 // f must consume tokens until reaching the next separator or
754 pub fn parse_seq_to_end<T>(
758 f: |&mut Parser| -> T)
760 let val = self.parse_seq_to_before_end(ket, sep, f);
765 // parse a sequence, not including the closing delimiter. The function
766 // f must consume tokens until reaching the next separator or
768 pub fn parse_seq_to_before_end<T>(
772 f: |&mut Parser| -> T)
774 let mut first: bool = true;
776 while self.token != *ket {
779 if first { first = false; }
780 else { self.expect(t); }
784 if sep.trailing_sep_allowed && self.token == *ket { break; }
790 // parse a sequence, including the closing delimiter. The function
791 // f must consume tokens until reaching the next separator or
793 pub fn parse_unspanned_seq<T>(
798 f: |&mut Parser| -> T)
801 let result = self.parse_seq_to_before_end(ket, sep, f);
806 // parse a sequence parameter of enum variant. For consistency purposes,
807 // these should not be empty.
808 pub fn parse_enum_variant_seq<T>(
813 f: |&mut Parser| -> T)
815 let result = self.parse_unspanned_seq(bra, ket, sep, f);
816 if result.is_empty() {
817 let last_span = self.last_span;
818 self.span_err(last_span,
819 "nullary enum variants are written with no trailing `( )`");
824 // NB: Do not use this function unless you actually plan to place the
825 // spanned list in the AST.
831 f: |&mut Parser| -> T)
832 -> Spanned<Vec<T> > {
833 let lo = self.span.lo;
835 let result = self.parse_seq_to_before_end(ket, sep, f);
836 let hi = self.span.hi;
838 spanned(lo, hi, result)
841 // advance the parser by one token
842 pub fn bump(&mut self) {
843 self.last_span = self.span;
844 // Stash token for error recovery (sometimes; clone is not necessarily cheap).
845 self.last_token = if is_ident_or_path(&self.token) {
846 Some(box self.token.clone())
850 let next = if self.buffer_start == self.buffer_end {
851 self.reader.next_token()
853 // Avoid token copies with `replace`.
854 let buffer_start = self.buffer_start as uint;
855 let next_index = (buffer_start + 1) & 3 as uint;
856 self.buffer_start = next_index as int;
858 let placeholder = TokenAndSpan {
859 tok: token::UNDERSCORE,
862 replace(&mut self.buffer[buffer_start], placeholder)
865 self.token = next.tok;
866 self.tokens_consumed += 1u;
869 // Advance the parser by one token and return the bumped token.
870 pub fn bump_and_get(&mut self) -> token::Token {
871 let old_token = replace(&mut self.token, token::UNDERSCORE);
876 // EFFECT: replace the current token and span with the given one
877 pub fn replace_token(&mut self,
881 self.last_span = mk_sp(self.span.lo, lo);
883 self.span = mk_sp(lo, hi);
885 pub fn buffer_length(&mut self) -> int {
886 if self.buffer_start <= self.buffer_end {
887 return self.buffer_end - self.buffer_start;
889 return (4 - self.buffer_start) + self.buffer_end;
891 pub fn look_ahead<R>(&mut self, distance: uint, f: |&token::Token| -> R)
893 let dist = distance as int;
894 while self.buffer_length() < dist {
895 self.buffer[self.buffer_end as uint] = self.reader.next_token();
896 self.buffer_end = (self.buffer_end + 1) & 3;
898 f(&self.buffer[((self.buffer_start + dist - 1) & 3) as uint].tok)
900 pub fn fatal(&mut self, m: &str) -> ! {
901 self.sess.span_diagnostic.span_fatal(self.span, m)
903 pub fn span_fatal(&mut self, sp: Span, m: &str) -> ! {
904 self.sess.span_diagnostic.span_fatal(sp, m)
906 pub fn span_note(&mut self, sp: Span, m: &str) {
907 self.sess.span_diagnostic.span_note(sp, m)
909 pub fn bug(&mut self, m: &str) -> ! {
910 self.sess.span_diagnostic.span_bug(self.span, m)
912 pub fn warn(&mut self, m: &str) {
913 self.sess.span_diagnostic.span_warn(self.span, m)
915 pub fn span_warn(&mut self, sp: Span, m: &str) {
916 self.sess.span_diagnostic.span_warn(sp, m)
918 pub fn span_err(&mut self, sp: Span, m: &str) {
919 self.sess.span_diagnostic.span_err(sp, m)
921 pub fn abort_if_errors(&mut self) {
922 self.sess.span_diagnostic.handler().abort_if_errors();
925 pub fn id_to_interned_str(&mut self, id: Ident) -> InternedString {
929 // Is the current token one of the keywords that signals a bare function
931 pub fn token_is_bare_fn_keyword(&mut self) -> bool {
932 if token::is_keyword(keywords::Fn, &self.token) {
936 if token::is_keyword(keywords::Unsafe, &self.token) ||
937 token::is_keyword(keywords::Once, &self.token) {
938 return self.look_ahead(1, |t| token::is_keyword(keywords::Fn, t))
944 // Is the current token one of the keywords that signals a closure type?
945 pub fn token_is_closure_keyword(&mut self) -> bool {
946 token::is_keyword(keywords::Unsafe, &self.token) ||
947 token::is_keyword(keywords::Once, &self.token)
950 // Is the current token one of the keywords that signals an old-style
951 // closure type (with explicit sigil)?
952 pub fn token_is_old_style_closure_keyword(&mut self) -> bool {
953 token::is_keyword(keywords::Unsafe, &self.token) ||
954 token::is_keyword(keywords::Once, &self.token) ||
955 token::is_keyword(keywords::Fn, &self.token)
958 pub fn token_is_lifetime(tok: &token::Token) -> bool {
960 token::LIFETIME(..) => true,
965 pub fn get_lifetime(&mut self) -> ast::Ident {
967 token::LIFETIME(ref ident) => *ident,
968 _ => self.bug("not a lifetime"),
972 // parse a TyBareFn type:
973 pub fn parse_ty_bare_fn(&mut self) -> Ty_ {
976 [unsafe] [extern "ABI"] fn <'lt> (S) -> T
977 ^~~~^ ^~~~^ ^~~~^ ^~^ ^
986 let fn_style = self.parse_unsafety();
987 let abi = if self.eat_keyword(keywords::Extern) {
988 self.parse_opt_abi().unwrap_or(abi::C)
993 self.expect_keyword(keywords::Fn);
994 let (decl, lifetimes) = self.parse_ty_fn_decl(true);
995 return TyBareFn(box(GC) BareFnTy {
998 lifetimes: lifetimes,
1003 // Parses a procedure type (`proc`). The initial `proc` keyword must
1004 // already have been parsed.
1005 pub fn parse_proc_type(&mut self) -> Ty_ {
1008 proc <'lt> (S) [:Bounds] -> T
1009 ^~~^ ^~~~^ ^ ^~~~~~~~^ ^
1019 let lifetimes = if self.eat(&token::LT) {
1020 let lifetimes = self.parse_lifetimes();
1027 let (inputs, variadic) = self.parse_fn_args(false, false);
1029 if self.eat(&token::COLON) {
1030 let (_, bounds) = self.parse_ty_param_bounds(false);
1036 let (ret_style, ret_ty) = self.parse_ret_ty();
1037 let decl = P(FnDecl {
1043 TyProc(box(GC) ClosureTy {
1048 lifetimes: lifetimes,
1052 // parse a TyClosure type
1053 pub fn parse_ty_closure(&mut self) -> Ty_ {
1056 [unsafe] [once] <'lt> |S| [:Bounds] -> T
1057 ^~~~~~~^ ^~~~~^ ^~~~^ ^ ^~~~~~~~^ ^
1059 | | | | | Return type
1060 | | | | Closure bounds
1061 | | | Argument types
1063 | Once-ness (a.k.a., affine)
1068 let fn_style = self.parse_unsafety();
1069 let onceness = if self.eat_keyword(keywords::Once) {Once} else {Many};
1071 let lifetimes = if self.eat(&token::LT) {
1072 let lifetimes = self.parse_lifetimes();
1080 let (is_unboxed, inputs) = if self.eat(&token::OROR) {
1085 let is_unboxed = self.token == token::BINOP(token::AND) &&
1086 self.look_ahead(1, |t| {
1087 token::is_keyword(keywords::Mut, t)
1089 self.look_ahead(2, |t| *t == token::COLON);
1096 let inputs = self.parse_seq_to_before_or(
1098 |p| p.parse_arg_general(false));
1100 (is_unboxed, inputs)
1103 let (region, bounds) = {
1104 if self.eat(&token::COLON) {
1105 let (region, bounds) = self.parse_ty_param_bounds(true);
1106 (region, Some(bounds))
1112 let (return_style, output) = self.parse_ret_ty();
1113 let decl = P(FnDecl {
1121 TyUnboxedFn(box(GC) UnboxedFnTy {
1125 TyClosure(box(GC) ClosureTy {
1130 lifetimes: lifetimes,
1135 pub fn parse_unsafety(&mut self) -> FnStyle {
1136 if self.eat_keyword(keywords::Unsafe) {
1143 // parse a function type (following the 'fn')
1144 pub fn parse_ty_fn_decl(&mut self, allow_variadic: bool)
1145 -> (P<FnDecl>, Vec<ast::Lifetime>) {
1156 let lifetimes = if self.eat(&token::LT) {
1157 let lifetimes = self.parse_lifetimes();
1164 let (inputs, variadic) = self.parse_fn_args(false, allow_variadic);
1165 let (ret_style, ret_ty) = self.parse_ret_ty();
1166 let decl = P(FnDecl {
1175 // parse the methods in a trait declaration
1176 pub fn parse_trait_methods(&mut self) -> Vec<TraitMethod> {
1177 self.parse_unspanned_seq(
1182 let attrs = p.parse_outer_attributes();
1185 // NB: at the moment, trait methods are public by default; this
1187 let vis = p.parse_visibility();
1188 let style = p.parse_fn_style();
1189 let ident = p.parse_ident();
1191 let generics = p.parse_generics();
1193 let (explicit_self, d) = p.parse_fn_decl_with_self(|p| {
1194 // This is somewhat dubious; We don't want to allow argument
1195 // names to be left off if there is a definition...
1196 p.parse_arg_general(false)
1199 let hi = p.last_span.hi;
1203 debug!("parse_trait_methods(): parsing required method");
1204 Required(TypeMethod {
1210 explicit_self: explicit_self,
1211 id: ast::DUMMY_NODE_ID,
1212 span: mk_sp(lo, hi),
1217 debug!("parse_trait_methods(): parsing provided method");
1218 let (inner_attrs, body) =
1219 p.parse_inner_attrs_and_block();
1220 let attrs = attrs.append(inner_attrs.as_slice());
1221 Provided(box(GC) ast::Method {
1225 explicit_self: explicit_self,
1229 id: ast::DUMMY_NODE_ID,
1230 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())
1243 let token_str = p.this_token_to_str();
1244 p.fatal((format!("expected `;` or `{{` but found `{}`",
1245 token_str)).as_slice())
1251 // parse a possibly mutable type
1252 pub fn parse_mt(&mut self) -> MutTy {
1253 let mutbl = self.parse_mutability();
1254 let t = self.parse_ty(true);
1255 MutTy { ty: t, mutbl: mutbl }
1258 // parse [mut/const/imm] ID : TY
1259 // now used only by obsolete record syntax parser...
1260 pub fn parse_ty_field(&mut self) -> TypeField {
1261 let lo = self.span.lo;
1262 let mutbl = self.parse_mutability();
1263 let id = self.parse_ident();
1264 self.expect(&token::COLON);
1265 let ty = self.parse_ty(true);
1266 let hi = ty.span.hi;
1269 mt: MutTy { ty: ty, mutbl: mutbl },
1270 span: mk_sp(lo, hi),
1274 // parse optional return type [ -> TY ] in function decl
1275 pub fn parse_ret_ty(&mut self) -> (RetStyle, P<Ty>) {
1276 return if self.eat(&token::RARROW) {
1277 let lo = self.span.lo;
1278 if self.eat(&token::NOT) {
1282 id: ast::DUMMY_NODE_ID,
1284 span: mk_sp(lo, self.last_span.hi)
1288 (Return, self.parse_ty(true))
1291 let pos = self.span.lo;
1295 id: ast::DUMMY_NODE_ID,
1297 span: mk_sp(pos, pos),
1305 /// The second parameter specifies whether the `+` binary operator is
1306 /// allowed in the type grammar.
1307 pub fn parse_ty(&mut self, plus_allowed: bool) -> P<Ty> {
1308 maybe_whole!(no_clone self, NtTy);
1310 let lo = self.span.lo;
1312 let t = if self.token == token::LPAREN {
1314 if self.token == token::RPAREN {
1318 // (t) is a parenthesized ty
1319 // (t,) is the type of a tuple with only one field,
1321 let mut ts = vec!(self.parse_ty(true));
1322 let mut one_tuple = false;
1323 while self.token == token::COMMA {
1325 if self.token != token::RPAREN {
1326 ts.push(self.parse_ty(true));
1333 if ts.len() == 1 && !one_tuple {
1334 self.expect(&token::RPAREN);
1338 self.expect(&token::RPAREN);
1342 } else if self.token == token::AT {
1345 let span = self.last_span;
1346 self.obsolete(span, ObsoleteManagedType);
1347 TyBox(self.parse_ty(plus_allowed))
1348 } else if self.token == token::TILDE {
1351 let last_span = self.last_span;
1354 self.obsolete(last_span, ObsoleteOwnedVector),
1355 _ => self.obsolete(last_span, ObsoleteOwnedType),
1357 TyUniq(self.parse_ty(true))
1358 } else if self.token == token::BINOP(token::STAR) {
1359 // STAR POINTER (bare pointer?)
1361 TyPtr(self.parse_mt())
1362 } else if self.token == token::LBRACKET {
1364 self.expect(&token::LBRACKET);
1365 let t = self.parse_ty(true);
1367 // Parse the `, ..e` in `[ int, ..e ]`
1368 // where `e` is a const expression
1369 let t = match self.maybe_parse_fixed_vstore() {
1371 Some(suffix) => TyFixedLengthVec(t, suffix)
1373 self.expect(&token::RBRACKET);
1375 } else if self.token == token::BINOP(token::AND) ||
1376 self.token == token::ANDAND {
1379 self.parse_borrowed_pointee()
1380 } else if self.is_keyword(keywords::Extern) ||
1381 self.is_keyword(keywords::Unsafe) ||
1382 self.token_is_bare_fn_keyword() {
1384 self.parse_ty_bare_fn()
1385 } else if self.token_is_closure_keyword() ||
1386 self.token == token::BINOP(token::OR) ||
1387 self.token == token::OROR ||
1388 self.token == token::LT {
1391 // FIXME(pcwalton): Eventually `token::LT` will not unambiguously
1392 // introduce a closure, once procs can have lifetime bounds. We
1393 // will need to refactor the grammar a little bit at that point.
1395 self.parse_ty_closure()
1396 } else if self.eat_keyword(keywords::Typeof) {
1398 // In order to not be ambiguous, the type must be surrounded by parens.
1399 self.expect(&token::LPAREN);
1400 let e = self.parse_expr();
1401 self.expect(&token::RPAREN);
1403 } else if self.eat_keyword(keywords::Proc) {
1404 self.parse_proc_type()
1405 } else if self.token == token::MOD_SEP
1406 || is_ident_or_path(&self.token) {
1408 let mode = if plus_allowed {
1409 LifetimeAndTypesAndBounds
1411 LifetimeAndTypesWithoutColons
1416 } = self.parse_path(mode);
1417 TyPath(path, bounds, ast::DUMMY_NODE_ID)
1418 } else if self.eat(&token::UNDERSCORE) {
1419 // TYPE TO BE INFERRED
1422 let msg = format!("expected type, found token {:?}", self.token);
1423 self.fatal(msg.as_slice());
1426 let sp = mk_sp(lo, self.last_span.hi);
1427 P(Ty {id: ast::DUMMY_NODE_ID, node: t, span: sp})
1430 pub fn parse_borrowed_pointee(&mut self) -> Ty_ {
1431 // look for `&'lt` or `&'foo ` and interpret `foo` as the region name:
1432 let opt_lifetime = self.parse_opt_lifetime();
1434 let mt = self.parse_mt();
1435 return TyRptr(opt_lifetime, mt);
1438 pub fn is_named_argument(&mut self) -> bool {
1439 let offset = match self.token {
1440 token::BINOP(token::AND) => 1,
1442 _ if token::is_keyword(keywords::Mut, &self.token) => 1,
1446 debug!("parser is_named_argument offset:{}", offset);
1449 is_plain_ident_or_underscore(&self.token)
1450 && self.look_ahead(1, |t| *t == token::COLON)
1452 self.look_ahead(offset, |t| is_plain_ident_or_underscore(t))
1453 && self.look_ahead(offset + 1, |t| *t == token::COLON)
1457 // This version of parse arg doesn't necessarily require
1458 // identifier names.
1459 pub fn parse_arg_general(&mut self, require_name: bool) -> Arg {
1460 let pat = if require_name || self.is_named_argument() {
1461 debug!("parse_arg_general parse_pat (require_name:{:?})",
1463 let pat = self.parse_pat();
1465 self.expect(&token::COLON);
1468 debug!("parse_arg_general ident_to_pat");
1469 ast_util::ident_to_pat(ast::DUMMY_NODE_ID,
1471 special_idents::invalid)
1474 let t = self.parse_ty(true);
1479 id: ast::DUMMY_NODE_ID,
1483 // parse a single function argument
1484 pub fn parse_arg(&mut self) -> Arg {
1485 self.parse_arg_general(true)
1488 // parse an argument in a lambda header e.g. |arg, arg|
1489 pub fn parse_fn_block_arg(&mut self) -> Arg {
1490 let pat = self.parse_pat();
1491 let t = if self.eat(&token::COLON) {
1495 id: ast::DUMMY_NODE_ID,
1497 span: mk_sp(self.span.lo, self.span.hi),
1503 id: ast::DUMMY_NODE_ID
1507 pub fn maybe_parse_fixed_vstore(&mut self) -> Option<Gc<ast::Expr>> {
1508 if self.token == token::COMMA &&
1509 self.look_ahead(1, |t| *t == token::DOTDOT) {
1512 Some(self.parse_expr())
1518 // matches token_lit = LIT_INT | ...
1519 pub fn lit_from_token(&mut self, tok: &token::Token) -> Lit_ {
1521 token::LIT_CHAR(i) => LitChar(i),
1522 token::LIT_INT(i, it) => LitInt(i, it),
1523 token::LIT_UINT(u, ut) => LitUint(u, ut),
1524 token::LIT_INT_UNSUFFIXED(i) => LitIntUnsuffixed(i),
1525 token::LIT_FLOAT(s, ft) => {
1526 LitFloat(self.id_to_interned_str(s), ft)
1528 token::LIT_FLOAT_UNSUFFIXED(s) => {
1529 LitFloatUnsuffixed(self.id_to_interned_str(s))
1531 token::LIT_STR(s) => {
1532 LitStr(self.id_to_interned_str(s), ast::CookedStr)
1534 token::LIT_STR_RAW(s, n) => {
1535 LitStr(self.id_to_interned_str(s), ast::RawStr(n))
1537 token::LPAREN => { self.expect(&token::RPAREN); LitNil },
1538 _ => { self.unexpected_last(tok); }
1542 // matches lit = true | false | token_lit
1543 pub fn parse_lit(&mut self) -> Lit {
1544 let lo = self.span.lo;
1545 let lit = if self.eat_keyword(keywords::True) {
1547 } else if self.eat_keyword(keywords::False) {
1550 let token = self.bump_and_get();
1551 let lit = self.lit_from_token(&token);
1554 codemap::Spanned { node: lit, span: mk_sp(lo, self.last_span.hi) }
1557 // matches '-' lit | lit
1558 pub fn parse_literal_maybe_minus(&mut self) -> Gc<Expr> {
1559 let minus_lo = self.span.lo;
1560 let minus_present = self.eat(&token::BINOP(token::MINUS));
1562 let lo = self.span.lo;
1563 let literal = box(GC) self.parse_lit();
1564 let hi = self.span.hi;
1565 let expr = self.mk_expr(lo, hi, ExprLit(literal));
1568 let minus_hi = self.span.hi;
1569 let unary = self.mk_unary(UnNeg, expr);
1570 self.mk_expr(minus_lo, minus_hi, unary)
1576 /// Parses a path and optional type parameter bounds, depending on the
1577 /// mode. The `mode` parameter determines whether lifetimes, types, and/or
1578 /// bounds are permitted and whether `::` must precede type parameter
1580 pub fn parse_path(&mut self, mode: PathParsingMode) -> PathAndBounds {
1581 // Check for a whole path...
1582 let found = match self.token {
1583 INTERPOLATED(token::NtPath(_)) => Some(self.bump_and_get()),
1587 Some(INTERPOLATED(token::NtPath(box path))) => {
1588 return PathAndBounds {
1596 let lo = self.span.lo;
1597 let is_global = self.eat(&token::MOD_SEP);
1599 // Parse any number of segments and bound sets. A segment is an
1600 // identifier followed by an optional lifetime and a set of types.
1601 // A bound set is a set of type parameter bounds.
1602 let mut segments = Vec::new();
1604 // First, parse an identifier.
1605 let identifier = self.parse_ident();
1607 // Parse the '::' before type parameters if it's required. If
1608 // it is required and wasn't present, then we're done.
1609 if mode == LifetimeAndTypesWithColons &&
1610 !self.eat(&token::MOD_SEP) {
1611 segments.push(ast::PathSegment {
1612 identifier: identifier,
1613 lifetimes: Vec::new(),
1614 types: OwnedSlice::empty(),
1619 // Parse the `<` before the lifetime and types, if applicable.
1620 let (any_lifetime_or_types, lifetimes, types) = {
1621 if mode != NoTypesAllowed && self.eat_lt(false) {
1622 let (lifetimes, types) =
1623 self.parse_generic_values_after_lt();
1624 (true, lifetimes, OwnedSlice::from_vec(types))
1626 (false, Vec::new(), OwnedSlice::empty())
1630 // Assemble and push the result.
1631 segments.push(ast::PathSegment {
1632 identifier: identifier,
1633 lifetimes: lifetimes,
1637 // We're done if we don't see a '::', unless the mode required
1638 // a double colon to get here in the first place.
1639 if !(mode == LifetimeAndTypesWithColons &&
1640 !any_lifetime_or_types) {
1641 if !self.eat(&token::MOD_SEP) {
1647 // Next, parse a plus and bounded type parameters, if applicable.
1649 // NOTE(stage0, pcwalton): Remove `token::COLON` after a snapshot.
1650 let bounds = if mode == LifetimeAndTypesAndBounds {
1652 if self.eat(&token::BINOP(token::PLUS)) ||
1653 self.eat(&token::COLON) {
1654 let (_, bounds) = self.parse_ty_param_bounds(false);
1665 // Assemble the span.
1666 let span = mk_sp(lo, self.last_span.hi);
1668 // Assemble the result.
1679 /// parses 0 or 1 lifetime
1680 pub fn parse_opt_lifetime(&mut self) -> Option<ast::Lifetime> {
1682 token::LIFETIME(..) => {
1683 Some(self.parse_lifetime())
1691 /// Parses a single lifetime
1692 // matches lifetime = LIFETIME
1693 pub fn parse_lifetime(&mut self) -> ast::Lifetime {
1695 token::LIFETIME(i) => {
1696 let span = self.span;
1698 return ast::Lifetime {
1699 id: ast::DUMMY_NODE_ID,
1705 self.fatal(format!("expected a lifetime name").as_slice());
1710 // matches lifetimes = ( lifetime ) | ( lifetime , lifetimes )
1711 // actually, it matches the empty one too, but putting that in there
1712 // messes up the grammar....
1713 pub fn parse_lifetimes(&mut self) -> Vec<ast::Lifetime> {
1716 * Parses zero or more comma separated lifetimes.
1717 * Expects each lifetime to be followed by either
1718 * a comma or `>`. Used when parsing type parameter
1719 * lists, where we expect something like `<'a, 'b, T>`.
1722 let mut res = Vec::new();
1725 token::LIFETIME(_) => {
1726 res.push(self.parse_lifetime());
1734 token::COMMA => { self.bump();}
1735 token::GT => { return res; }
1736 token::BINOP(token::SHR) => { return res; }
1738 let msg = format!("expected `,` or `>` after lifetime \
1741 self.fatal(msg.as_slice());
1747 pub fn token_is_mutability(tok: &token::Token) -> bool {
1748 token::is_keyword(keywords::Mut, tok) ||
1749 token::is_keyword(keywords::Const, tok)
1752 // parse mutability declaration (mut/const/imm)
1753 pub fn parse_mutability(&mut self) -> Mutability {
1754 if self.eat_keyword(keywords::Mut) {
1761 // parse ident COLON expr
1762 pub fn parse_field(&mut self) -> Field {
1763 let lo = self.span.lo;
1764 let i = self.parse_ident();
1765 let hi = self.last_span.hi;
1766 self.expect(&token::COLON);
1767 let e = self.parse_expr();
1769 ident: spanned(lo, hi, i),
1771 span: mk_sp(lo, e.span.hi),
1775 pub fn mk_expr(&mut self, lo: BytePos, hi: BytePos, node: Expr_) -> Gc<Expr> {
1777 id: ast::DUMMY_NODE_ID,
1779 span: mk_sp(lo, hi),
1783 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: Gc<Expr>) -> ast::Expr_ {
1784 ExprUnary(unop, expr)
1787 pub fn mk_binary(&mut self, binop: ast::BinOp,
1788 lhs: Gc<Expr>, rhs: Gc<Expr>) -> ast::Expr_ {
1789 ExprBinary(binop, lhs, rhs)
1792 pub fn mk_call(&mut self, f: Gc<Expr>, args: Vec<Gc<Expr>>) -> ast::Expr_ {
1796 fn mk_method_call(&mut self,
1797 ident: ast::SpannedIdent,
1799 args: Vec<Gc<Expr>>)
1801 ExprMethodCall(ident, tps, args)
1804 pub fn mk_index(&mut self, expr: Gc<Expr>, idx: Gc<Expr>) -> ast::Expr_ {
1805 ExprIndex(expr, idx)
1808 pub fn mk_field(&mut self, expr: Gc<Expr>, ident: Ident,
1809 tys: Vec<P<Ty>>) -> ast::Expr_ {
1810 ExprField(expr, ident, tys)
1813 pub fn mk_assign_op(&mut self, binop: ast::BinOp,
1814 lhs: Gc<Expr>, rhs: Gc<Expr>) -> ast::Expr_ {
1815 ExprAssignOp(binop, lhs, rhs)
1818 pub fn mk_mac_expr(&mut self, lo: BytePos, hi: BytePos, m: Mac_) -> Gc<Expr> {
1820 id: ast::DUMMY_NODE_ID,
1821 node: ExprMac(codemap::Spanned {node: m, span: mk_sp(lo, hi)}),
1822 span: mk_sp(lo, hi),
1826 pub fn mk_lit_u32(&mut self, i: u32) -> Gc<Expr> {
1827 let span = &self.span;
1828 let lv_lit = box(GC) codemap::Spanned {
1829 node: LitUint(i as u64, TyU32),
1834 id: ast::DUMMY_NODE_ID,
1835 node: ExprLit(lv_lit),
1840 // at the bottom (top?) of the precedence hierarchy,
1841 // parse things like parenthesized exprs,
1842 // macros, return, etc.
1843 pub fn parse_bottom_expr(&mut self) -> Gc<Expr> {
1844 maybe_whole_expr!(self);
1846 let lo = self.span.lo;
1847 let mut hi = self.span.hi;
1851 if self.token == token::LPAREN {
1853 // (e) is parenthesized e
1854 // (e,) is a tuple with only one field, e
1855 let mut trailing_comma = false;
1856 if self.token == token::RPAREN {
1859 let lit = box(GC) spanned(lo, hi, LitNil);
1860 return self.mk_expr(lo, hi, ExprLit(lit));
1862 let mut es = vec!(self.parse_expr());
1863 self.commit_expr(*es.last().unwrap(), &[], &[token::COMMA, token::RPAREN]);
1864 while self.token == token::COMMA {
1866 if self.token != token::RPAREN {
1867 es.push(self.parse_expr());
1868 self.commit_expr(*es.last().unwrap(), &[], &[token::COMMA, token::RPAREN]);
1871 trailing_comma = true;
1875 self.commit_expr_expecting(*es.last().unwrap(), token::RPAREN);
1877 return if es.len() == 1 && !trailing_comma {
1878 self.mk_expr(lo, hi, ExprParen(*es.get(0)))
1881 self.mk_expr(lo, hi, ExprTup(es))
1883 } else if self.token == token::LBRACE {
1885 let blk = self.parse_block_tail(lo, DefaultBlock);
1886 return self.mk_expr(blk.span.lo, blk.span.hi,
1888 } else if token::is_bar(&self.token) {
1889 return self.parse_lambda_expr();
1890 } else if self.eat_keyword(keywords::Proc) {
1891 let decl = self.parse_proc_decl();
1892 let body = self.parse_expr();
1893 let fakeblock = P(ast::Block {
1894 view_items: Vec::new(),
1897 id: ast::DUMMY_NODE_ID,
1898 rules: DefaultBlock,
1902 return self.mk_expr(lo, body.span.hi, ExprProc(decl, fakeblock));
1903 } else if self.eat_keyword(keywords::Self) {
1904 let path = ast_util::ident_to_path(mk_sp(lo, hi), special_idents::self_);
1905 ex = ExprPath(path);
1906 hi = self.last_span.hi;
1907 } else if self.eat_keyword(keywords::If) {
1908 return self.parse_if_expr();
1909 } else if self.eat_keyword(keywords::For) {
1910 return self.parse_for_expr(None);
1911 } else if self.eat_keyword(keywords::While) {
1912 return self.parse_while_expr();
1913 } else if Parser::token_is_lifetime(&self.token) {
1914 let lifetime = self.get_lifetime();
1916 self.expect(&token::COLON);
1917 if self.eat_keyword(keywords::For) {
1918 return self.parse_for_expr(Some(lifetime))
1919 } else if self.eat_keyword(keywords::Loop) {
1920 return self.parse_loop_expr(Some(lifetime))
1922 self.fatal("expected `for` or `loop` after a label")
1924 } else if self.eat_keyword(keywords::Loop) {
1925 return self.parse_loop_expr(None);
1926 } else if self.eat_keyword(keywords::Continue) {
1927 let lo = self.span.lo;
1928 let ex = if Parser::token_is_lifetime(&self.token) {
1929 let lifetime = self.get_lifetime();
1931 ExprAgain(Some(lifetime))
1935 let hi = self.span.hi;
1936 return self.mk_expr(lo, hi, ex);
1937 } else if self.eat_keyword(keywords::Match) {
1938 return self.parse_match_expr();
1939 } else if self.eat_keyword(keywords::Unsafe) {
1940 return self.parse_block_expr(lo, UnsafeBlock(ast::UserProvided));
1941 } else if self.token == token::LBRACKET {
1944 if self.token == token::RBRACKET {
1947 ex = ExprVec(Vec::new());
1950 let first_expr = self.parse_expr();
1951 if self.token == token::COMMA &&
1952 self.look_ahead(1, |t| *t == token::DOTDOT) {
1953 // Repeating vector syntax: [ 0, ..512 ]
1956 let count = self.parse_expr();
1957 self.expect(&token::RBRACKET);
1958 ex = ExprRepeat(first_expr, count);
1959 } else if self.token == token::COMMA {
1960 // Vector with two or more elements.
1962 let remaining_exprs = self.parse_seq_to_end(
1964 seq_sep_trailing_allowed(token::COMMA),
1967 let mut exprs = vec!(first_expr);
1968 exprs.push_all_move(remaining_exprs);
1969 ex = ExprVec(exprs);
1971 // Vector with one element.
1972 self.expect(&token::RBRACKET);
1973 ex = ExprVec(vec!(first_expr));
1976 hi = self.last_span.hi;
1977 } else if self.eat_keyword(keywords::Return) {
1978 // RETURN expression
1979 if can_begin_expr(&self.token) {
1980 let e = self.parse_expr();
1982 ex = ExprRet(Some(e));
1983 } else { ex = ExprRet(None); }
1984 } else if self.eat_keyword(keywords::Break) {
1986 if Parser::token_is_lifetime(&self.token) {
1987 let lifetime = self.get_lifetime();
1989 ex = ExprBreak(Some(lifetime));
1991 ex = ExprBreak(None);
1994 } else if self.token == token::MOD_SEP ||
1995 is_ident(&self.token) && !self.is_keyword(keywords::True) &&
1996 !self.is_keyword(keywords::False) {
1997 let pth = self.parse_path(LifetimeAndTypesWithColons).path;
1999 // `!`, as an operator, is prefix, so we know this isn't that
2000 if self.token == token::NOT {
2001 // MACRO INVOCATION expression
2004 let ket = token::close_delimiter_for(&self.token)
2005 .unwrap_or_else(|| self.fatal("expected open delimiter"));
2008 let tts = self.parse_seq_to_end(&ket,
2010 |p| p.parse_token_tree());
2011 let hi = self.span.hi;
2013 return self.mk_mac_expr(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT));
2014 } else if self.token == token::LBRACE {
2015 // This might be a struct literal.
2016 if self.looking_at_struct_literal() {
2017 // It's a struct literal.
2019 let mut fields = Vec::new();
2020 let mut base = None;
2022 while self.token != token::RBRACE {
2023 if self.eat(&token::DOTDOT) {
2024 base = Some(self.parse_expr());
2028 fields.push(self.parse_field());
2029 self.commit_expr(fields.last().unwrap().expr,
2030 &[token::COMMA], &[token::RBRACE]);
2034 self.expect(&token::RBRACE);
2035 ex = ExprStruct(pth, fields, base);
2036 return self.mk_expr(lo, hi, ex);
2043 // other literal expression
2044 let lit = self.parse_lit();
2046 ex = ExprLit(box(GC) lit);
2049 return self.mk_expr(lo, hi, ex);
2052 // parse a block or unsafe block
2053 pub fn parse_block_expr(&mut self, lo: BytePos, blk_mode: BlockCheckMode)
2055 self.expect(&token::LBRACE);
2056 let blk = self.parse_block_tail(lo, blk_mode);
2057 return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk));
2060 // parse a.b or a(13) or a[4] or just a
2061 pub fn parse_dot_or_call_expr(&mut self) -> Gc<Expr> {
2062 let b = self.parse_bottom_expr();
2063 self.parse_dot_or_call_expr_with(b)
2066 pub fn parse_dot_or_call_expr_with(&mut self, e0: Gc<Expr>) -> Gc<Expr> {
2072 if self.eat(&token::DOT) {
2074 token::IDENT(i, _) => {
2075 let dot = self.last_span.hi;
2078 let (_, tys) = if self.eat(&token::MOD_SEP) {
2080 self.parse_generic_values_after_lt()
2082 (Vec::new(), Vec::new())
2085 // expr.f() method call
2088 let mut es = self.parse_unspanned_seq(
2091 seq_sep_trailing_disallowed(token::COMMA),
2094 hi = self.last_span.hi;
2097 let id = spanned(dot, hi, i);
2098 let nd = self.mk_method_call(id, tys, es);
2099 e = self.mk_expr(lo, hi, nd);
2102 let field = self.mk_field(e, i, tys);
2103 e = self.mk_expr(lo, hi, field)
2107 _ => self.unexpected()
2111 if self.expr_is_complete(e) { break; }
2115 let es = self.parse_unspanned_seq(
2118 seq_sep_trailing_allowed(token::COMMA),
2121 hi = self.last_span.hi;
2123 let nd = self.mk_call(e, es);
2124 e = self.mk_expr(lo, hi, nd);
2128 token::LBRACKET => {
2130 let ix = self.parse_expr();
2132 self.commit_expr_expecting(ix, token::RBRACKET);
2133 let index = self.mk_index(e, ix);
2134 e = self.mk_expr(lo, hi, index)
2143 // parse an optional separator followed by a kleene-style
2144 // repetition token (+ or *).
2145 pub fn parse_sep_and_zerok(&mut self) -> (Option<token::Token>, bool) {
2146 fn parse_zerok(parser: &mut Parser) -> Option<bool> {
2147 match parser.token {
2148 token::BINOP(token::STAR) | token::BINOP(token::PLUS) => {
2149 let zerok = parser.token == token::BINOP(token::STAR);
2157 match parse_zerok(self) {
2158 Some(zerok) => return (None, zerok),
2162 let separator = self.bump_and_get();
2163 match parse_zerok(self) {
2164 Some(zerok) => (Some(separator), zerok),
2165 None => self.fatal("expected `*` or `+`")
2169 // parse a single token tree from the input.
2170 pub fn parse_token_tree(&mut self) -> TokenTree {
2171 // FIXME #6994: currently, this is too eager. It
2172 // parses token trees but also identifies TTSeq's
2173 // and TTNonterminal's; it's too early to know yet
2174 // whether something will be a nonterminal or a seq
2176 maybe_whole!(deref self, NtTT);
2178 // this is the fall-through for the 'match' below.
2179 // invariants: the current token is not a left-delimiter,
2180 // not an EOF, and not the desired right-delimiter (if
2181 // it were, parse_seq_to_before_end would have prevented
2182 // reaching this point.
2183 fn parse_non_delim_tt_tok(p: &mut Parser) -> TokenTree {
2184 maybe_whole!(deref p, NtTT);
2186 token::RPAREN | token::RBRACE | token::RBRACKET => {
2187 // This is a conservative error: only report the last unclosed delimiter. The
2188 // previous unclosed delimiters could actually be closed! The parser just hasn't
2189 // gotten to them yet.
2190 match p.open_braces.last() {
2192 Some(&sp) => p.span_note(sp, "unclosed delimiter"),
2194 let token_str = p.this_token_to_str();
2195 p.fatal(format!("incorrect close delimiter: `{}`",
2196 token_str).as_slice())
2198 /* we ought to allow different depths of unquotation */
2199 token::DOLLAR if p.quote_depth > 0u => {
2203 if p.token == token::LPAREN {
2204 let seq = p.parse_seq(
2208 |p| p.parse_token_tree()
2210 let (s, z) = p.parse_sep_and_zerok();
2211 let seq = match seq {
2212 Spanned { node, .. } => node,
2214 TTSeq(mk_sp(sp.lo, p.span.hi), Rc::new(seq), s, z)
2216 TTNonterminal(sp, p.parse_ident())
2225 // turn the next token into a TTTok:
2226 fn parse_any_tt_tok(p: &mut Parser) -> TokenTree {
2227 TTTok(p.span, p.bump_and_get())
2230 match (&self.token, token::close_delimiter_for(&self.token)) {
2231 (&token::EOF, _) => {
2232 let open_braces = self.open_braces.clone();
2233 for sp in open_braces.iter() {
2234 self.span_note(*sp, "Did you mean to close this delimiter?");
2236 // There shouldn't really be a span, but it's easier for the test runner
2237 // if we give it one
2238 self.fatal("this file contains an un-closed delimiter ");
2240 (_, Some(close_delim)) => {
2241 // Parse the open delimiter.
2242 self.open_braces.push(self.span);
2243 let mut result = vec!(parse_any_tt_tok(self));
2246 self.parse_seq_to_before_end(&close_delim,
2248 |p| p.parse_token_tree());
2249 result.push_all_move(trees);
2251 // Parse the close delimiter.
2252 result.push(parse_any_tt_tok(self));
2253 self.open_braces.pop().unwrap();
2255 TTDelim(Rc::new(result))
2257 _ => parse_non_delim_tt_tok(self)
2261 // parse a stream of tokens into a list of TokenTree's,
2263 pub fn parse_all_token_trees(&mut self) -> Vec<TokenTree> {
2264 let mut tts = Vec::new();
2265 while self.token != token::EOF {
2266 tts.push(self.parse_token_tree());
2271 pub fn parse_matchers(&mut self) -> Vec<Matcher> {
2272 // unification of Matcher's and TokenTree's would vastly improve
2273 // the interpolation of Matcher's
2274 maybe_whole!(self, NtMatchers);
2275 let mut name_idx = 0u;
2276 match token::close_delimiter_for(&self.token) {
2277 Some(other_delimiter) => {
2279 self.parse_matcher_subseq_upto(&mut name_idx, &other_delimiter)
2281 None => self.fatal("expected open delimiter")
2285 // This goofy function is necessary to correctly match parens in Matcher's.
2286 // Otherwise, `$( ( )` would be a valid Matcher, and `$( () )` would be
2287 // invalid. It's similar to common::parse_seq.
2288 pub fn parse_matcher_subseq_upto(&mut self,
2289 name_idx: &mut uint,
2292 let mut ret_val = Vec::new();
2293 let mut lparens = 0u;
2295 while self.token != *ket || lparens > 0u {
2296 if self.token == token::LPAREN { lparens += 1u; }
2297 if self.token == token::RPAREN { lparens -= 1u; }
2298 ret_val.push(self.parse_matcher(name_idx));
2306 pub fn parse_matcher(&mut self, name_idx: &mut uint) -> Matcher {
2307 let lo = self.span.lo;
2309 let m = if self.token == token::DOLLAR {
2311 if self.token == token::LPAREN {
2312 let name_idx_lo = *name_idx;
2314 let ms = self.parse_matcher_subseq_upto(name_idx,
2317 self.fatal("repetition body must be nonempty");
2319 let (sep, zerok) = self.parse_sep_and_zerok();
2320 MatchSeq(ms, sep, zerok, name_idx_lo, *name_idx)
2322 let bound_to = self.parse_ident();
2323 self.expect(&token::COLON);
2324 let nt_name = self.parse_ident();
2325 let m = MatchNonterminal(bound_to, nt_name, *name_idx);
2330 MatchTok(self.bump_and_get())
2333 return spanned(lo, self.span.hi, m);
2336 // parse a prefix-operator expr
2337 pub fn parse_prefix_expr(&mut self) -> Gc<Expr> {
2338 let lo = self.span.lo;
2345 let e = self.parse_prefix_expr();
2347 ex = self.mk_unary(UnNot, e);
2349 token::BINOP(token::MINUS) => {
2351 let e = self.parse_prefix_expr();
2353 ex = self.mk_unary(UnNeg, e);
2355 token::BINOP(token::STAR) => {
2357 let e = self.parse_prefix_expr();
2359 ex = self.mk_unary(UnDeref, e);
2361 token::BINOP(token::AND) | token::ANDAND => {
2363 let _lt = self.parse_opt_lifetime();
2364 let m = self.parse_mutability();
2365 let e = self.parse_prefix_expr();
2367 // HACK: turn &[...] into a &-vec
2369 ExprVec(..) if m == MutImmutable => {
2370 ExprVstore(e, ExprVstoreSlice)
2372 ExprVec(..) if m == MutMutable => {
2373 ExprVstore(e, ExprVstoreMutSlice)
2375 _ => ExprAddrOf(m, e)
2380 let span = self.last_span;
2381 self.obsolete(span, ObsoleteManagedExpr);
2382 let e = self.parse_prefix_expr();
2384 ex = self.mk_unary(UnBox, e);
2389 let e = self.parse_prefix_expr();
2391 // HACK: turn ~[...] into a ~-vec
2392 let last_span = self.last_span;
2394 ExprVec(..) | ExprRepeat(..) => {
2395 self.obsolete(last_span, ObsoleteOwnedVector);
2396 ExprVstore(e, ExprVstoreUniq)
2398 ExprLit(lit) if lit_is_str(lit) => {
2399 self.obsolete(last_span, ObsoleteOwnedExpr);
2400 ExprVstore(e, ExprVstoreUniq)
2403 self.obsolete(last_span, ObsoleteOwnedExpr);
2404 self.mk_unary(UnUniq, e)
2408 token::IDENT(_, _) if self.is_keyword(keywords::Box) => {
2411 // Check for a place: `box(PLACE) EXPR`.
2412 if self.eat(&token::LPAREN) {
2413 // Support `box() EXPR` as the default.
2414 if !self.eat(&token::RPAREN) {
2415 let place = self.parse_expr();
2416 self.expect(&token::RPAREN);
2417 let subexpression = self.parse_prefix_expr();
2418 hi = subexpression.span.hi;
2419 ex = ExprBox(place, subexpression);
2420 return self.mk_expr(lo, hi, ex);
2424 // Otherwise, we use the unique pointer default.
2425 let subexpression = self.parse_prefix_expr();
2426 hi = subexpression.span.hi;
2427 // HACK: turn `box [...]` into a boxed-vec
2428 ex = match subexpression.node {
2429 ExprVec(..) | ExprRepeat(..) => {
2430 let last_span = self.last_span;
2431 self.obsolete(last_span, ObsoleteOwnedVector);
2432 ExprVstore(subexpression, ExprVstoreUniq)
2434 ExprLit(lit) if lit_is_str(lit) => {
2435 ExprVstore(subexpression, ExprVstoreUniq)
2437 _ => self.mk_unary(UnUniq, subexpression)
2440 _ => return self.parse_dot_or_call_expr()
2442 return self.mk_expr(lo, hi, ex);
2445 // parse an expression of binops
2446 pub fn parse_binops(&mut self) -> Gc<Expr> {
2447 let prefix_expr = self.parse_prefix_expr();
2448 self.parse_more_binops(prefix_expr, 0)
2451 // parse an expression of binops of at least min_prec precedence
2452 pub fn parse_more_binops(&mut self, lhs: Gc<Expr>,
2453 min_prec: uint) -> Gc<Expr> {
2454 if self.expr_is_complete(lhs) { return lhs; }
2456 // Prevent dynamic borrow errors later on by limiting the
2457 // scope of the borrows.
2459 let token: &token::Token = &self.token;
2460 let restriction: &restriction = &self.restriction;
2461 match (token, restriction) {
2462 (&token::BINOP(token::OR), &RESTRICT_NO_BAR_OP) => return lhs,
2463 (&token::BINOP(token::OR),
2464 &RESTRICT_NO_BAR_OR_DOUBLEBAR_OP) => return lhs,
2465 (&token::OROR, &RESTRICT_NO_BAR_OR_DOUBLEBAR_OP) => return lhs,
2470 let cur_opt = token_to_binop(&self.token);
2473 let cur_prec = operator_prec(cur_op);
2474 if cur_prec > min_prec {
2476 let expr = self.parse_prefix_expr();
2477 let rhs = self.parse_more_binops(expr, cur_prec);
2478 let binary = self.mk_binary(cur_op, lhs, rhs);
2479 let bin = self.mk_expr(lhs.span.lo, rhs.span.hi, binary);
2480 self.parse_more_binops(bin, min_prec)
2486 if as_prec > min_prec && self.eat_keyword(keywords::As) {
2487 let rhs = self.parse_ty(false);
2488 let _as = self.mk_expr(lhs.span.lo,
2490 ExprCast(lhs, rhs));
2491 self.parse_more_binops(_as, min_prec)
2499 // parse an assignment expression....
2500 // actually, this seems to be the main entry point for
2501 // parsing an arbitrary expression.
2502 pub fn parse_assign_expr(&mut self) -> Gc<Expr> {
2503 let lo = self.span.lo;
2504 let lhs = self.parse_binops();
2508 let rhs = self.parse_expr();
2509 self.mk_expr(lo, rhs.span.hi, ExprAssign(lhs, rhs))
2511 token::BINOPEQ(op) => {
2513 let rhs = self.parse_expr();
2514 let aop = match op {
2515 token::PLUS => BiAdd,
2516 token::MINUS => BiSub,
2517 token::STAR => BiMul,
2518 token::SLASH => BiDiv,
2519 token::PERCENT => BiRem,
2520 token::CARET => BiBitXor,
2521 token::AND => BiBitAnd,
2522 token::OR => BiBitOr,
2523 token::SHL => BiShl,
2526 let assign_op = self.mk_assign_op(aop, lhs, rhs);
2527 self.mk_expr(lo, rhs.span.hi, assign_op)
2535 // parse an 'if' expression ('if' token already eaten)
2536 pub fn parse_if_expr(&mut self) -> Gc<Expr> {
2537 let lo = self.last_span.lo;
2538 let cond = self.parse_expr();
2539 let thn = self.parse_block();
2540 let mut els: Option<Gc<Expr>> = None;
2541 let mut hi = thn.span.hi;
2542 if self.eat_keyword(keywords::Else) {
2543 let elexpr = self.parse_else_expr();
2545 hi = elexpr.span.hi;
2547 self.mk_expr(lo, hi, ExprIf(cond, thn, els))
2550 // `|args| { ... }` or `{ ...}` like in `do` expressions
2551 pub fn parse_lambda_block_expr(&mut self) -> Gc<Expr> {
2552 self.parse_lambda_expr_(
2555 token::BINOP(token::OR) | token::OROR => {
2556 p.parse_fn_block_decl()
2559 // No argument list - `do foo {`
2563 id: ast::DUMMY_NODE_ID,
2574 let blk = p.parse_block();
2575 p.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk))
2580 pub fn parse_lambda_expr(&mut self) -> Gc<Expr> {
2581 self.parse_lambda_expr_(|p| p.parse_fn_block_decl(),
2585 // parse something of the form |args| expr
2586 // this is used both in parsing a lambda expr
2587 // and in parsing a block expr as e.g. in for...
2588 pub fn parse_lambda_expr_(&mut self,
2589 parse_decl: |&mut Parser| -> P<FnDecl>,
2590 parse_body: |&mut Parser| -> Gc<Expr>)
2592 let lo = self.span.lo;
2593 let decl = parse_decl(self);
2594 let body = parse_body(self);
2595 let fakeblock = P(ast::Block {
2596 view_items: Vec::new(),
2599 id: ast::DUMMY_NODE_ID,
2600 rules: DefaultBlock,
2604 return self.mk_expr(lo, body.span.hi, ExprFnBlock(decl, fakeblock));
2607 pub fn parse_else_expr(&mut self) -> Gc<Expr> {
2608 if self.eat_keyword(keywords::If) {
2609 return self.parse_if_expr();
2611 let blk = self.parse_block();
2612 return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk));
2616 // parse a 'for' .. 'in' expression ('for' token already eaten)
2617 pub fn parse_for_expr(&mut self, opt_ident: Option<ast::Ident>) -> Gc<Expr> {
2618 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
2620 let lo = self.last_span.lo;
2621 let pat = self.parse_pat();
2622 self.expect_keyword(keywords::In);
2623 let expr = self.parse_expr();
2624 let loop_block = self.parse_block();
2625 let hi = self.span.hi;
2627 self.mk_expr(lo, hi, ExprForLoop(pat, expr, loop_block, opt_ident))
2630 pub fn parse_while_expr(&mut self) -> Gc<Expr> {
2631 let lo = self.last_span.lo;
2632 let cond = self.parse_expr();
2633 let body = self.parse_block();
2634 let hi = body.span.hi;
2635 return self.mk_expr(lo, hi, ExprWhile(cond, body));
2638 pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::Ident>) -> Gc<Expr> {
2639 let lo = self.last_span.lo;
2640 let body = self.parse_block();
2641 let hi = body.span.hi;
2642 self.mk_expr(lo, hi, ExprLoop(body, opt_ident))
2645 // For distinguishing between struct literals and blocks
2646 fn looking_at_struct_literal(&mut self) -> bool {
2647 self.token == token::LBRACE &&
2648 ((self.look_ahead(1, |t| token::is_plain_ident(t)) &&
2649 self.look_ahead(2, |t| *t == token::COLON))
2650 || self.look_ahead(1, |t| *t == token::DOTDOT))
2653 fn parse_match_expr(&mut self) -> Gc<Expr> {
2654 let lo = self.last_span.lo;
2655 let discriminant = self.parse_expr();
2656 self.commit_expr_expecting(discriminant, token::LBRACE);
2657 let mut arms: Vec<Arm> = Vec::new();
2658 while self.token != token::RBRACE {
2659 let attrs = self.parse_outer_attributes();
2660 let pats = self.parse_pats();
2661 let mut guard = None;
2662 if self.eat_keyword(keywords::If) {
2663 guard = Some(self.parse_expr());
2665 self.expect(&token::FAT_ARROW);
2666 let expr = self.parse_expr_res(RESTRICT_STMT_EXPR);
2669 !classify::expr_is_simple_block(expr)
2670 && self.token != token::RBRACE;
2673 self.commit_expr(expr, &[token::COMMA], &[token::RBRACE]);
2675 self.eat(&token::COMMA);
2678 arms.push(ast::Arm {
2685 let hi = self.span.hi;
2687 return self.mk_expr(lo, hi, ExprMatch(discriminant, arms));
2690 // parse an expression
2691 pub fn parse_expr(&mut self) -> Gc<Expr> {
2692 return self.parse_expr_res(UNRESTRICTED);
2695 // parse an expression, subject to the given restriction
2696 fn parse_expr_res(&mut self, r: restriction) -> Gc<Expr> {
2697 let old = self.restriction;
2698 self.restriction = r;
2699 let e = self.parse_assign_expr();
2700 self.restriction = old;
2704 // parse the RHS of a local variable declaration (e.g. '= 14;')
2705 fn parse_initializer(&mut self) -> Option<Gc<Expr>> {
2706 if self.token == token::EQ {
2708 Some(self.parse_expr())
2714 // parse patterns, separated by '|' s
2715 fn parse_pats(&mut self) -> Vec<Gc<Pat>> {
2716 let mut pats = Vec::new();
2718 pats.push(self.parse_pat());
2719 if self.token == token::BINOP(token::OR) { self.bump(); }
2720 else { return pats; }
2724 fn parse_pat_vec_elements(
2726 ) -> (Vec<Gc<Pat>> , Option<Gc<Pat>>, Vec<Gc<Pat>> ) {
2727 let mut before = Vec::new();
2728 let mut slice = None;
2729 let mut after = Vec::new();
2730 let mut first = true;
2731 let mut before_slice = true;
2733 while self.token != token::RBRACKET {
2734 if first { first = false; }
2735 else { self.expect(&token::COMMA); }
2737 let mut is_slice = false;
2739 if self.token == token::DOTDOT {
2742 before_slice = false;
2747 if self.token == token::COMMA || self.token == token::RBRACKET {
2748 slice = Some(box(GC) ast::Pat {
2749 id: ast::DUMMY_NODE_ID,
2754 let subpat = self.parse_pat();
2756 ast::Pat { node: PatIdent(_, _, _), .. } => {
2757 slice = Some(subpat);
2759 ast::Pat { span, .. } => self.span_fatal(
2760 span, "expected an identifier or nothing"
2765 let subpat = self.parse_pat();
2767 before.push(subpat);
2774 (before, slice, after)
2777 // parse the fields of a struct-like pattern
2778 fn parse_pat_fields(&mut self) -> (Vec<ast::FieldPat> , bool) {
2779 let mut fields = Vec::new();
2780 let mut etc = false;
2781 let mut first = true;
2782 while self.token != token::RBRACE {
2786 self.expect(&token::COMMA);
2787 // accept trailing commas
2788 if self.token == token::RBRACE { break }
2791 if self.token == token::DOTDOT {
2793 if self.token != token::RBRACE {
2794 let token_str = self.this_token_to_str();
2795 self.fatal(format!("expected `{}`, found `{}`", "}",
2796 token_str).as_slice())
2802 let bind_type = if self.eat_keyword(keywords::Mut) {
2803 BindByValue(MutMutable)
2804 } else if self.eat_keyword(keywords::Ref) {
2805 BindByRef(self.parse_mutability())
2807 BindByValue(MutImmutable)
2810 let fieldname = self.parse_ident();
2812 let subpat = if self.token == token::COLON {
2814 BindByRef(..) | BindByValue(MutMutable) => {
2815 let token_str = self.this_token_to_str();
2816 self.fatal(format!("unexpected `{}`",
2817 token_str).as_slice())
2825 let fieldpath = ast_util::ident_to_path(self.last_span,
2828 id: ast::DUMMY_NODE_ID,
2829 node: PatIdent(bind_type, fieldpath, None),
2830 span: self.last_span
2833 fields.push(ast::FieldPat { ident: fieldname, pat: subpat });
2835 return (fields, etc);
2839 pub fn parse_pat(&mut self) -> Gc<Pat> {
2840 maybe_whole!(self, NtPat);
2842 let lo = self.span.lo;
2847 token::UNDERSCORE => {
2850 hi = self.last_span.hi;
2851 return box(GC) ast::Pat {
2852 id: ast::DUMMY_NODE_ID,
2860 let sub = self.parse_pat();
2862 let last_span = self.last_span;
2864 self.obsolete(last_span, ObsoleteOwnedPattern);
2865 return box(GC) ast::Pat {
2866 id: ast::DUMMY_NODE_ID,
2871 token::BINOP(token::AND) | token::ANDAND => {
2873 let lo = self.span.lo;
2875 let sub = self.parse_pat();
2876 pat = PatRegion(sub);
2877 hi = self.last_span.hi;
2878 return box(GC) ast::Pat {
2879 id: ast::DUMMY_NODE_ID,
2885 // parse (pat,pat,pat,...) as tuple
2887 if self.token == token::RPAREN {
2890 let lit = box(GC) codemap::Spanned {
2892 span: mk_sp(lo, hi)};
2893 let expr = self.mk_expr(lo, hi, ExprLit(lit));
2896 let mut fields = vec!(self.parse_pat());
2897 if self.look_ahead(1, |t| *t != token::RPAREN) {
2898 while self.token == token::COMMA {
2900 if self.token == token::RPAREN { break; }
2901 fields.push(self.parse_pat());
2904 if fields.len() == 1 { self.expect(&token::COMMA); }
2905 self.expect(&token::RPAREN);
2906 pat = PatTup(fields);
2908 hi = self.last_span.hi;
2909 return box(GC) ast::Pat {
2910 id: ast::DUMMY_NODE_ID,
2915 token::LBRACKET => {
2916 // parse [pat,pat,...] as vector pattern
2918 let (before, slice, after) =
2919 self.parse_pat_vec_elements();
2921 self.expect(&token::RBRACKET);
2922 pat = ast::PatVec(before, slice, after);
2923 hi = self.last_span.hi;
2924 return box(GC) ast::Pat {
2925 id: ast::DUMMY_NODE_ID,
2933 if (!is_ident_or_path(&self.token) && self.token != token::MOD_SEP)
2934 || self.is_keyword(keywords::True)
2935 || self.is_keyword(keywords::False) {
2936 // Parse an expression pattern or exp .. exp.
2938 // These expressions are limited to literals (possibly
2939 // preceded by unary-minus) or identifiers.
2940 let val = self.parse_literal_maybe_minus();
2941 if self.eat(&token::DOTDOT) {
2942 let end = if is_ident_or_path(&self.token) {
2943 let path = self.parse_path(LifetimeAndTypesWithColons)
2945 let hi = self.span.hi;
2946 self.mk_expr(lo, hi, ExprPath(path))
2948 self.parse_literal_maybe_minus()
2950 pat = PatRange(val, end);
2954 } else if self.eat_keyword(keywords::Mut) {
2955 pat = self.parse_pat_ident(BindByValue(MutMutable));
2956 } else if self.eat_keyword(keywords::Ref) {
2958 let mutbl = self.parse_mutability();
2959 pat = self.parse_pat_ident(BindByRef(mutbl));
2960 } else if self.eat_keyword(keywords::Box) {
2963 // FIXME(#13910): Rename to `PatBox` and extend to full DST
2965 let sub = self.parse_pat();
2967 hi = self.last_span.hi;
2968 return box(GC) ast::Pat {
2969 id: ast::DUMMY_NODE_ID,
2974 let can_be_enum_or_struct = self.look_ahead(1, |t| {
2976 token::LPAREN | token::LBRACKET | token::LT |
2977 token::LBRACE | token::MOD_SEP => true,
2982 if self.look_ahead(1, |t| *t == token::DOTDOT) {
2983 let start = self.parse_expr_res(RESTRICT_NO_BAR_OP);
2984 self.eat(&token::DOTDOT);
2985 let end = self.parse_expr_res(RESTRICT_NO_BAR_OP);
2986 pat = PatRange(start, end);
2987 } else if is_plain_ident(&self.token) && !can_be_enum_or_struct {
2988 let name = self.parse_path(NoTypesAllowed).path;
2989 if self.eat(&token::NOT) {
2991 let ket = token::close_delimiter_for(&self.token)
2992 .unwrap_or_else(|| self.fatal("expected open delimiter"));
2995 let tts = self.parse_seq_to_end(&ket,
2997 |p| p.parse_token_tree());
2999 let mac = MacInvocTT(name, tts, EMPTY_CTXT);
3000 pat = ast::PatMac(codemap::Spanned {node: mac, span: self.span});
3002 let sub = if self.eat(&token::AT) {
3004 Some(self.parse_pat())
3009 pat = PatIdent(BindByValue(MutImmutable), name, sub);
3012 // parse an enum pat
3013 let enum_path = self.parse_path(LifetimeAndTypesWithColons)
3019 self.parse_pat_fields();
3021 pat = PatStruct(enum_path, fields, etc);
3024 let mut args: Vec<Gc<Pat>> = Vec::new();
3027 let is_dotdot = self.look_ahead(1, |t| {
3029 token::DOTDOT => true,
3034 // This is a "top constructor only" pat
3037 self.expect(&token::RPAREN);
3038 pat = PatEnum(enum_path, None);
3040 args = self.parse_enum_variant_seq(
3043 seq_sep_trailing_disallowed(token::COMMA),
3046 pat = PatEnum(enum_path, Some(args));
3050 if enum_path.segments.len() == 1 {
3051 // it could still be either an enum
3052 // or an identifier pattern, resolve
3053 // will sort it out:
3054 pat = PatIdent(BindByValue(MutImmutable),
3058 pat = PatEnum(enum_path, Some(args));
3066 hi = self.last_span.hi;
3068 id: ast::DUMMY_NODE_ID,
3070 span: mk_sp(lo, hi),
3074 // parse ident or ident @ pat
3075 // used by the copy foo and ref foo patterns to give a good
3076 // error message when parsing mistakes like ref foo(a,b)
3077 fn parse_pat_ident(&mut self,
3078 binding_mode: ast::BindingMode)
3080 if !is_plain_ident(&self.token) {
3081 let last_span = self.last_span;
3082 self.span_fatal(last_span,
3083 "expected identifier, found path");
3085 // why a path here, and not just an identifier?
3086 let name = self.parse_path(NoTypesAllowed).path;
3087 let sub = if self.eat(&token::AT) {
3088 Some(self.parse_pat())
3093 // just to be friendly, if they write something like
3095 // we end up here with ( as the current token. This shortly
3096 // leads to a parse error. Note that if there is no explicit
3097 // binding mode then we do not end up here, because the lookahead
3098 // will direct us over to parse_enum_variant()
3099 if self.token == token::LPAREN {
3100 let last_span = self.last_span;
3103 "expected identifier, found enum pattern");
3106 PatIdent(binding_mode, name, sub)
3109 // parse a local variable declaration
3110 fn parse_local(&mut self) -> Gc<Local> {
3111 let lo = self.span.lo;
3112 let pat = self.parse_pat();
3115 id: ast::DUMMY_NODE_ID,
3117 span: mk_sp(lo, lo),
3119 if self.eat(&token::COLON) {
3120 ty = self.parse_ty(true);
3122 let init = self.parse_initializer();
3123 box(GC) ast::Local {
3127 id: ast::DUMMY_NODE_ID,
3128 span: mk_sp(lo, self.last_span.hi),
3133 // parse a "let" stmt
3134 fn parse_let(&mut self) -> Gc<Decl> {
3135 let lo = self.span.lo;
3136 let local = self.parse_local();
3137 box(GC) spanned(lo, self.last_span.hi, DeclLocal(local))
3140 // parse a structure field
3141 fn parse_name_and_ty(&mut self, pr: Visibility,
3142 attrs: Vec<Attribute> ) -> StructField {
3143 let lo = self.span.lo;
3144 if !is_plain_ident(&self.token) {
3145 self.fatal("expected ident");
3147 let name = self.parse_ident();
3148 self.expect(&token::COLON);
3149 let ty = self.parse_ty(true);
3150 spanned(lo, self.last_span.hi, ast::StructField_ {
3151 kind: NamedField(name, pr),
3152 id: ast::DUMMY_NODE_ID,
3158 // parse a statement. may include decl.
3159 // precondition: any attributes are parsed already
3160 pub fn parse_stmt(&mut self, item_attrs: Vec<Attribute>) -> Gc<Stmt> {
3161 maybe_whole!(self, NtStmt);
3163 fn check_expected_item(p: &mut Parser, found_attrs: bool) {
3164 // If we have attributes then we should have an item
3166 let last_span = p.last_span;
3167 p.span_err(last_span, "expected item after attributes");
3171 let lo = self.span.lo;
3172 if self.is_keyword(keywords::Let) {
3173 check_expected_item(self, !item_attrs.is_empty());
3174 self.expect_keyword(keywords::Let);
3175 let decl = self.parse_let();
3176 return box(GC) spanned(lo, decl.span.hi, StmtDecl(decl, ast::DUMMY_NODE_ID));
3177 } else if is_ident(&self.token)
3178 && !token::is_any_keyword(&self.token)
3179 && self.look_ahead(1, |t| *t == token::NOT) {
3180 // parse a macro invocation. Looks like there's serious
3181 // overlap here; if this clause doesn't catch it (and it
3182 // won't, for brace-delimited macros) it will fall through
3183 // to the macro clause of parse_item_or_view_item. This
3184 // could use some cleanup, it appears to me.
3186 // whoops! I now have a guess: I'm guessing the "parens-only"
3187 // rule here is deliberate, to allow macro users to use parens
3188 // for things that should be parsed as stmt_mac, and braces
3189 // for things that should expand into items. Tricky, and
3190 // somewhat awkward... and probably undocumented. Of course,
3191 // I could just be wrong.
3193 check_expected_item(self, !item_attrs.is_empty());
3195 // Potential trouble: if we allow macros with paths instead of
3196 // idents, we'd need to look ahead past the whole path here...
3197 let pth = self.parse_path(NoTypesAllowed).path;
3200 let id = if token::close_delimiter_for(&self.token).is_some() {
3201 token::special_idents::invalid // no special identifier
3206 // check that we're pointing at delimiters (need to check
3207 // again after the `if`, because of `parse_ident`
3208 // consuming more tokens).
3209 let (bra, ket) = match token::close_delimiter_for(&self.token) {
3210 Some(ket) => (self.token.clone(), ket),
3213 // we only expect an ident if we didn't parse one
3215 let ident_str = if id == token::special_idents::invalid {
3220 let tok_str = self.this_token_to_str();
3221 self.fatal(format!("expected {}`(` or `\\{`, but found `{}`",
3223 tok_str).as_slice())
3227 // we only expect an ident if we didn't parse one
3229 let ident_str = if id == token::special_idents::invalid {
3234 let tok_str = self.this_token_to_str();
3235 self.fatal(format!("expected {}`(` or `{{`, but found `{}`",
3237 tok_str).as_slice())
3241 let tts = self.parse_unspanned_seq(
3245 |p| p.parse_token_tree()
3247 let hi = self.span.hi;
3249 if id == token::special_idents::invalid {
3250 return box(GC) spanned(lo, hi, StmtMac(
3251 spanned(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT)), false));
3253 // if it has a special ident, it's definitely an item
3254 return box(GC) spanned(lo, hi, StmtDecl(
3255 box(GC) spanned(lo, hi, DeclItem(
3257 lo, hi, id /*id is good here*/,
3258 ItemMac(spanned(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT))),
3259 Inherited, Vec::new(/*no attrs*/)))),
3260 ast::DUMMY_NODE_ID));
3264 let found_attrs = !item_attrs.is_empty();
3265 match self.parse_item_or_view_item(item_attrs, false) {
3268 let decl = box(GC) spanned(lo, hi, DeclItem(i));
3269 return box(GC) spanned(lo, hi, StmtDecl(decl, ast::DUMMY_NODE_ID));
3271 IoviViewItem(vi) => {
3272 self.span_fatal(vi.span,
3273 "view items must be declared at the top of the block");
3275 IoviForeignItem(_) => {
3276 self.fatal("foreign items are not allowed here");
3278 IoviNone(_) => { /* fallthrough */ }
3281 check_expected_item(self, found_attrs);
3283 // Remainder are line-expr stmts.
3284 let e = self.parse_expr_res(RESTRICT_STMT_EXPR);
3285 return box(GC) spanned(lo, e.span.hi, StmtExpr(e, ast::DUMMY_NODE_ID));
3289 // is this expression a successfully-parsed statement?
3290 fn expr_is_complete(&mut self, e: Gc<Expr>) -> bool {
3291 return self.restriction == RESTRICT_STMT_EXPR &&
3292 !classify::expr_requires_semi_to_be_stmt(e);
3295 // parse a block. No inner attrs are allowed.
3296 pub fn parse_block(&mut self) -> P<Block> {
3297 maybe_whole!(no_clone self, NtBlock);
3299 let lo = self.span.lo;
3300 self.expect(&token::LBRACE);
3302 return self.parse_block_tail_(lo, DefaultBlock, Vec::new());
3305 // parse a block. Inner attrs are allowed.
3306 fn parse_inner_attrs_and_block(&mut self)
3307 -> (Vec<Attribute> , P<Block>) {
3309 maybe_whole!(pair_empty self, NtBlock);
3311 let lo = self.span.lo;
3312 self.expect(&token::LBRACE);
3313 let (inner, next) = self.parse_inner_attrs_and_next();
3315 (inner, self.parse_block_tail_(lo, DefaultBlock, next))
3318 // Precondition: already parsed the '{' or '#{'
3319 // I guess that also means "already parsed the 'impure'" if
3320 // necessary, and this should take a qualifier.
3321 // some blocks start with "#{"...
3322 fn parse_block_tail(&mut self, lo: BytePos, s: BlockCheckMode) -> P<Block> {
3323 self.parse_block_tail_(lo, s, Vec::new())
3326 // parse the rest of a block expression or function body
3327 fn parse_block_tail_(&mut self, lo: BytePos, s: BlockCheckMode,
3328 first_item_attrs: Vec<Attribute> ) -> P<Block> {
3329 let mut stmts = Vec::new();
3330 let mut expr = None;
3332 // wouldn't it be more uniform to parse view items only, here?
3333 let ParsedItemsAndViewItems {
3334 attrs_remaining: attrs_remaining,
3335 view_items: view_items,
3338 } = self.parse_items_and_view_items(first_item_attrs,
3341 for item in items.iter() {
3342 let decl = box(GC) spanned(item.span.lo, item.span.hi, DeclItem(*item));
3343 stmts.push(box(GC) spanned(item.span.lo, item.span.hi,
3344 StmtDecl(decl, ast::DUMMY_NODE_ID)));
3347 let mut attributes_box = attrs_remaining;
3349 while self.token != token::RBRACE {
3350 // parsing items even when they're not allowed lets us give
3351 // better error messages and recover more gracefully.
3352 attributes_box.push_all(self.parse_outer_attributes().as_slice());
3355 if !attributes_box.is_empty() {
3356 let last_span = self.last_span;
3357 self.span_err(last_span, "expected item after attributes");
3358 attributes_box = Vec::new();
3360 self.bump(); // empty
3363 // fall through and out.
3366 let stmt = self.parse_stmt(attributes_box);
3367 attributes_box = Vec::new();
3369 StmtExpr(e, stmt_id) => {
3370 // expression without semicolon
3371 if classify::stmt_ends_with_semi(&*stmt) {
3372 // Just check for errors and recover; do not eat semicolon yet.
3373 self.commit_stmt(stmt, &[], &[token::SEMI, token::RBRACE]);
3379 let span_with_semi = Span {
3381 hi: self.last_span.hi,
3382 expn_info: stmt.span.expn_info,
3384 stmts.push(box(GC) codemap::Spanned {
3385 node: StmtSemi(e, stmt_id),
3386 span: span_with_semi,
3397 StmtMac(ref m, _) => {
3398 // statement macro; might be an expr
3402 stmts.push(box(GC) codemap::Spanned {
3403 node: StmtMac((*m).clone(), true),
3408 // if a block ends in `m!(arg)` without
3409 // a `;`, it must be an expr
3411 self.mk_mac_expr(stmt.span.lo,
3420 _ => { // all other kinds of statements:
3421 stmts.push(stmt.clone());
3423 if classify::stmt_ends_with_semi(&*stmt) {
3424 self.commit_stmt_expecting(stmt, token::SEMI);
3432 if !attributes_box.is_empty() {
3433 let last_span = self.last_span;
3434 self.span_err(last_span, "expected item after attributes");
3437 let hi = self.span.hi;
3440 view_items: view_items,
3443 id: ast::DUMMY_NODE_ID,
3445 span: mk_sp(lo, hi),
3449 fn parse_unboxed_function_type(&mut self) -> UnboxedFnTy {
3450 let inputs = if self.eat(&token::OROR) {
3455 if self.token == token::BINOP(token::AND) &&
3456 self.look_ahead(1, |t| {
3457 token::is_keyword(keywords::Mut, t)
3459 self.look_ahead(2, |t| *t == token::COLON) {
3465 let inputs = self.parse_seq_to_before_or(&token::COMMA,
3467 p.parse_arg_general(false)
3473 let (return_style, output) = self.parse_ret_ty();
3484 // matches bounds = ( boundseq )?
3485 // where boundseq = ( bound + boundseq ) | bound
3486 // and bound = 'static | ty
3487 // Returns "None" if there's no colon (e.g. "T");
3488 // Returns "Some(Empty)" if there's a colon but nothing after (e.g. "T:")
3489 // Returns "Some(stuff)" otherwise (e.g. "T:stuff").
3490 // NB: The None/Some distinction is important for issue #7264.
3492 // Note that the `allow_any_lifetime` argument is a hack for now while the
3493 // AST doesn't support arbitrary lifetimes in bounds on type parameters. In
3494 // the future, this flag should be removed, and the return value of this
3495 // function should be Option<~[TyParamBound]>
3496 fn parse_ty_param_bounds(&mut self, allow_any_lifetime: bool)
3497 -> (Option<ast::Lifetime>,
3498 OwnedSlice<TyParamBound>) {
3499 let mut ret_lifetime = None;
3500 let mut result = vec!();
3503 token::LIFETIME(lifetime) => {
3504 let lifetime_interned_string = token::get_ident(lifetime);
3505 if lifetime_interned_string.equiv(&("'static")) {
3506 result.push(StaticRegionTyParamBound);
3507 if allow_any_lifetime && ret_lifetime.is_none() {
3508 ret_lifetime = Some(ast::Lifetime {
3509 id: ast::DUMMY_NODE_ID,
3514 } else if allow_any_lifetime && ret_lifetime.is_none() {
3515 ret_lifetime = Some(ast::Lifetime {
3516 id: ast::DUMMY_NODE_ID,
3521 result.push(OtherRegionTyParamBound(self.span));
3525 token::MOD_SEP | token::IDENT(..) => {
3526 let tref = self.parse_trait_ref();
3527 result.push(TraitTyParamBound(tref));
3529 token::BINOP(token::OR) | token::OROR => {
3530 let unboxed_function_type =
3531 self.parse_unboxed_function_type();
3532 result.push(UnboxedFnTyParamBound(unboxed_function_type));
3537 if !self.eat(&token::BINOP(token::PLUS)) {
3542 return (ret_lifetime, OwnedSlice::from_vec(result));
3545 // matches typaram = type? IDENT optbounds ( EQ ty )?
3546 fn parse_ty_param(&mut self) -> TyParam {
3547 let sized = self.parse_sized();
3548 let span = self.span;
3549 let ident = self.parse_ident();
3551 if self.eat(&token::COLON) {
3552 let (_, bounds) = self.parse_ty_param_bounds(false);
3558 // For typarams we don't care about the difference b/w "<T>" and "<T:>".
3559 let bounds = opt_bounds.unwrap_or_default();
3561 let default = if self.token == token::EQ {
3563 Some(self.parse_ty(true))
3569 id: ast::DUMMY_NODE_ID,
3577 // parse a set of optional generic type parameter declarations
3578 // matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
3579 // | ( < lifetimes , typaramseq ( , )? > )
3580 // where typaramseq = ( typaram ) | ( typaram , typaramseq )
3581 pub fn parse_generics(&mut self) -> ast::Generics {
3582 if self.eat(&token::LT) {
3583 let lifetimes = self.parse_lifetimes();
3584 let mut seen_default = false;
3585 let ty_params = self.parse_seq_to_gt(Some(token::COMMA), |p| {
3586 p.forbid_lifetime();
3587 let ty_param = p.parse_ty_param();
3588 if ty_param.default.is_some() {
3589 seen_default = true;
3590 } else if seen_default {
3591 let last_span = p.last_span;
3592 p.span_err(last_span,
3593 "type parameters with a default must be trailing");
3597 ast::Generics { lifetimes: lifetimes, ty_params: ty_params }
3599 ast_util::empty_generics()
3603 fn parse_generic_values_after_lt(&mut self) -> (Vec<ast::Lifetime>, Vec<P<Ty>> ) {
3604 let lifetimes = self.parse_lifetimes();
3605 let result = self.parse_seq_to_gt(
3608 p.forbid_lifetime();
3612 (lifetimes, result.into_vec())
3615 fn forbid_lifetime(&mut self) {
3616 if Parser::token_is_lifetime(&self.token) {
3617 let span = self.span;
3618 self.span_fatal(span, "lifetime parameters must be declared \
3619 prior to type parameters");
3623 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
3624 -> (Vec<Arg> , bool) {
3626 let mut args: Vec<Option<Arg>> =
3627 self.parse_unspanned_seq(
3630 seq_sep_trailing_allowed(token::COMMA),
3632 if p.token == token::DOTDOTDOT {
3635 if p.token != token::RPAREN {
3638 "`...` must be last in argument list for variadic function");
3643 "only foreign functions are allowed to be variadic");
3647 Some(p.parse_arg_general(named_args))
3652 let variadic = match args.pop() {
3655 // Need to put back that last arg
3662 if variadic && args.is_empty() {
3664 "variadic function must be declared with at least one named argument");
3667 let args = args.move_iter().map(|x| x.unwrap()).collect();
3672 // parse the argument list and result type of a function declaration
3673 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> P<FnDecl> {
3675 let (args, variadic) = self.parse_fn_args(true, allow_variadic);
3676 let (ret_style, ret_ty) = self.parse_ret_ty();
3686 fn is_self_ident(&mut self) -> bool {
3688 token::IDENT(id, false) => id.name == special_idents::self_.name,
3693 fn expect_self_ident(&mut self) {
3694 if !self.is_self_ident() {
3695 let token_str = self.this_token_to_str();
3696 self.fatal(format!("expected `self` but found `{}`",
3697 token_str).as_slice())
3702 // parse the argument list and result type of a function
3703 // that may have a self type.
3704 fn parse_fn_decl_with_self(&mut self, parse_arg_fn: |&mut Parser| -> Arg)
3705 -> (ExplicitSelf, P<FnDecl>) {
3706 fn maybe_parse_borrowed_explicit_self(this: &mut Parser)
3707 -> ast::ExplicitSelf_ {
3708 // The following things are possible to see here:
3713 // fn(&'lt mut self)
3715 // We already know that the current token is `&`.
3717 if this.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) {
3719 this.expect_self_ident();
3720 SelfRegion(None, MutImmutable)
3721 } else if this.look_ahead(1, |t| Parser::token_is_mutability(t)) &&
3723 |t| token::is_keyword(keywords::Self,
3726 let mutability = this.parse_mutability();
3727 this.expect_self_ident();
3728 SelfRegion(None, mutability)
3729 } else if this.look_ahead(1, |t| Parser::token_is_lifetime(t)) &&
3731 |t| token::is_keyword(keywords::Self,
3734 let lifetime = this.parse_lifetime();
3735 this.expect_self_ident();
3736 SelfRegion(Some(lifetime), MutImmutable)
3737 } else if this.look_ahead(1, |t| Parser::token_is_lifetime(t)) &&
3738 this.look_ahead(2, |t| {
3739 Parser::token_is_mutability(t)
3741 this.look_ahead(3, |t| token::is_keyword(keywords::Self,
3744 let lifetime = this.parse_lifetime();
3745 let mutability = this.parse_mutability();
3746 this.expect_self_ident();
3747 SelfRegion(Some(lifetime), mutability)
3753 self.expect(&token::LPAREN);
3755 // A bit of complexity and lookahead is needed here in order to be
3756 // backwards compatible.
3757 let lo = self.span.lo;
3758 let mut mutbl_self = MutImmutable;
3759 let explicit_self = match self.token {
3760 token::BINOP(token::AND) => {
3761 maybe_parse_borrowed_explicit_self(self)
3764 // We need to make sure it isn't a type
3765 if self.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) {
3767 self.expect_self_ident();
3773 token::IDENT(..) if self.is_self_ident() => {
3777 token::BINOP(token::STAR) => {
3778 // Possibly "*self" or "*mut self" -- not supported. Try to avoid
3779 // emitting cryptic "unexpected token" errors.
3781 let _mutability = if Parser::token_is_mutability(&self.token) {
3782 self.parse_mutability()
3783 } else { MutImmutable };
3784 if self.is_self_ident() {
3785 let span = self.span;
3786 self.span_err(span, "cannot pass self by unsafe pointer");
3791 _ if Parser::token_is_mutability(&self.token) &&
3792 self.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) => {
3793 mutbl_self = self.parse_mutability();
3794 self.expect_self_ident();
3797 _ if Parser::token_is_mutability(&self.token) &&
3798 self.look_ahead(1, |t| *t == token::TILDE) &&
3799 self.look_ahead(2, |t| token::is_keyword(keywords::Self, t)) => {
3800 mutbl_self = self.parse_mutability();
3802 self.expect_self_ident();
3808 let explicit_self_sp = mk_sp(lo, self.span.hi);
3810 // If we parsed a self type, expect a comma before the argument list.
3811 let fn_inputs = if explicit_self != SelfStatic {
3815 let sep = seq_sep_trailing_disallowed(token::COMMA);
3816 let mut fn_inputs = self.parse_seq_to_before_end(
3821 fn_inputs.unshift(Arg::new_self(explicit_self_sp, mutbl_self));
3825 vec!(Arg::new_self(explicit_self_sp, mutbl_self))
3828 let token_str = self.this_token_to_str();
3829 self.fatal(format!("expected `,` or `)`, found `{}`",
3830 token_str).as_slice())
3834 let sep = seq_sep_trailing_disallowed(token::COMMA);
3835 self.parse_seq_to_before_end(&token::RPAREN, sep, parse_arg_fn)
3838 self.expect(&token::RPAREN);
3840 let hi = self.span.hi;
3842 let (ret_style, ret_ty) = self.parse_ret_ty();
3844 let fn_decl = P(FnDecl {
3851 (spanned(lo, hi, explicit_self), fn_decl)
3854 // parse the |arg, arg| header on a lambda
3855 fn parse_fn_block_decl(&mut self) -> P<FnDecl> {
3856 let inputs_captures = {
3857 if self.eat(&token::OROR) {
3860 self.parse_unspanned_seq(
3861 &token::BINOP(token::OR),
3862 &token::BINOP(token::OR),
3863 seq_sep_trailing_disallowed(token::COMMA),
3864 |p| p.parse_fn_block_arg()
3868 let output = if self.eat(&token::RARROW) {
3872 id: ast::DUMMY_NODE_ID,
3879 inputs: inputs_captures,
3886 // Parses the `(arg, arg) -> return_type` header on a procedure.
3887 fn parse_proc_decl(&mut self) -> P<FnDecl> {
3889 self.parse_unspanned_seq(&token::LPAREN,
3891 seq_sep_trailing_allowed(token::COMMA),
3892 |p| p.parse_fn_block_arg());
3894 let output = if self.eat(&token::RARROW) {
3898 id: ast::DUMMY_NODE_ID,
3912 // parse the name and optional generic types of a function header.
3913 fn parse_fn_header(&mut self) -> (Ident, ast::Generics) {
3914 let id = self.parse_ident();
3915 let generics = self.parse_generics();
3919 fn mk_item(&mut self, lo: BytePos, hi: BytePos, ident: Ident,
3920 node: Item_, vis: Visibility,
3921 attrs: Vec<Attribute>) -> Gc<Item> {
3925 id: ast::DUMMY_NODE_ID,
3932 // parse an item-position function declaration.
3933 fn parse_item_fn(&mut self, fn_style: FnStyle, abi: abi::Abi) -> ItemInfo {
3934 let (ident, generics) = self.parse_fn_header();
3935 let decl = self.parse_fn_decl(false);
3936 let (inner_attrs, body) = self.parse_inner_attrs_and_block();
3937 (ident, ItemFn(decl, fn_style, abi, generics, body), Some(inner_attrs))
3940 // parse a method in a trait impl, starting with `attrs` attributes.
3941 fn parse_method(&mut self,
3942 already_parsed_attrs: Option<Vec<Attribute>>) -> Gc<Method> {
3943 let next_attrs = self.parse_outer_attributes();
3944 let attrs = match already_parsed_attrs {
3945 Some(mut a) => { a.push_all_move(next_attrs); a }
3949 let lo = self.span.lo;
3951 let visa = self.parse_visibility();
3952 let fn_style = self.parse_fn_style();
3953 let ident = self.parse_ident();
3954 let generics = self.parse_generics();
3955 let (explicit_self, decl) = self.parse_fn_decl_with_self(|p| {
3959 let (inner_attrs, body) = self.parse_inner_attrs_and_block();
3960 let hi = body.span.hi;
3961 let attrs = attrs.append(inner_attrs.as_slice());
3962 box(GC) ast::Method {
3966 explicit_self: explicit_self,
3970 id: ast::DUMMY_NODE_ID,
3971 span: mk_sp(lo, hi),
3976 // parse trait Foo { ... }
3977 fn parse_item_trait(&mut self) -> ItemInfo {
3978 let ident = self.parse_ident();
3979 let tps = self.parse_generics();
3980 let sized = self.parse_for_sized();
3982 // Parse traits, if necessary.
3984 if self.token == token::COLON {
3986 traits = self.parse_trait_ref_list(&token::LBRACE);
3988 traits = Vec::new();
3991 let meths = self.parse_trait_methods();
3992 (ident, ItemTrait(tps, sized, traits, meths), None)
3995 // Parses two variants (with the region/type params always optional):
3996 // impl<T> Foo { ... }
3997 // impl<T> ToStr for ~[T] { ... }
3998 fn parse_item_impl(&mut self) -> ItemInfo {
3999 // First, parse type parameters if necessary.
4000 let generics = self.parse_generics();
4002 // Special case: if the next identifier that follows is '(', don't
4003 // allow this to be parsed as a trait.
4004 let could_be_trait = self.token != token::LPAREN;
4007 let mut ty = self.parse_ty(true);
4009 // Parse traits, if necessary.
4010 let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) {
4011 // New-style trait. Reinterpret the type as a trait.
4012 let opt_trait_ref = match ty.node {
4013 TyPath(ref path, None, node_id) => {
4015 path: /* bad */ (*path).clone(),
4020 self.span_err(ty.span,
4021 "bounded traits are only valid in type position");
4025 self.span_err(ty.span, "not a trait");
4030 ty = self.parse_ty(true);
4036 let mut meths = Vec::new();
4037 self.expect(&token::LBRACE);
4038 let (inner_attrs, next) = self.parse_inner_attrs_and_next();
4039 let mut method_attrs = Some(next);
4040 while !self.eat(&token::RBRACE) {
4041 meths.push(self.parse_method(method_attrs));
4042 method_attrs = None;
4045 let ident = ast_util::impl_pretty_name(&opt_trait, &*ty);
4047 (ident, ItemImpl(generics, opt_trait, ty, meths), Some(inner_attrs))
4050 // parse a::B<String,int>
4051 fn parse_trait_ref(&mut self) -> TraitRef {
4053 path: self.parse_path(LifetimeAndTypesWithoutColons).path,
4054 ref_id: ast::DUMMY_NODE_ID,
4058 // parse B + C<String,int> + D
4059 fn parse_trait_ref_list(&mut self, ket: &token::Token) -> Vec<TraitRef> {
4060 self.parse_seq_to_before_end(
4062 seq_sep_trailing_disallowed(token::BINOP(token::PLUS)),
4063 |p| p.parse_trait_ref()
4067 // parse struct Foo { ... }
4068 fn parse_item_struct(&mut self, is_virtual: bool) -> ItemInfo {
4069 let class_name = self.parse_ident();
4070 let generics = self.parse_generics();
4072 let super_struct = if self.eat(&token::COLON) {
4073 let ty = self.parse_ty(true);
4075 TyPath(_, None, _) => {
4079 self.span_err(ty.span, "not a struct");
4087 let mut fields: Vec<StructField>;
4090 if self.eat(&token::LBRACE) {
4091 // It's a record-like struct.
4092 is_tuple_like = false;
4093 fields = Vec::new();
4094 while self.token != token::RBRACE {
4095 fields.push(self.parse_struct_decl_field());
4097 if fields.len() == 0 {
4098 self.fatal(format!("unit-like struct definition should be \
4099 written as `struct {};`",
4100 token::get_ident(class_name)).as_slice());
4103 } else if self.token == token::LPAREN {
4104 // It's a tuple-like struct.
4105 is_tuple_like = true;
4106 fields = self.parse_unspanned_seq(
4109 seq_sep_trailing_allowed(token::COMMA),
4111 let attrs = p.parse_outer_attributes();
4113 let struct_field_ = ast::StructField_ {
4114 kind: UnnamedField(p.parse_visibility()),
4115 id: ast::DUMMY_NODE_ID,
4116 ty: p.parse_ty(true),
4119 spanned(lo, p.span.hi, struct_field_)
4121 self.expect(&token::SEMI);
4122 } else if self.eat(&token::SEMI) {
4123 // It's a unit-like struct.
4124 is_tuple_like = true;
4125 fields = Vec::new();
4127 let token_str = self.this_token_to_str();
4128 self.fatal(format!("expected `{}`, `(`, or `;` after struct \
4129 name but found `{}`", "{",
4130 token_str).as_slice())
4133 let _ = ast::DUMMY_NODE_ID; // FIXME: Workaround for crazy bug.
4134 let new_id = ast::DUMMY_NODE_ID;
4136 ItemStruct(box(GC) ast::StructDef {
4138 ctor_id: if is_tuple_like { Some(new_id) } else { None },
4139 super_struct: super_struct,
4140 is_virtual: is_virtual,
4145 // parse a structure field declaration
4146 pub fn parse_single_struct_field(&mut self,
4148 attrs: Vec<Attribute> )
4150 let a_var = self.parse_name_and_ty(vis, attrs);
4158 let span = self.span;
4159 let token_str = self.this_token_to_str();
4160 self.span_fatal(span,
4161 format!("expected `,`, or `\\}` but found `{}`",
4162 token_str).as_slice())
4166 let span = self.span;
4167 let token_str = self.this_token_to_str();
4168 self.span_fatal(span,
4169 format!("expected `,`, or `}}` but found `{}`",
4170 token_str).as_slice())
4176 // parse an element of a struct definition
4177 fn parse_struct_decl_field(&mut self) -> StructField {
4179 let attrs = self.parse_outer_attributes();
4181 if self.eat_keyword(keywords::Pub) {
4182 return self.parse_single_struct_field(Public, attrs);
4185 return self.parse_single_struct_field(Inherited, attrs);
4188 // parse visiility: PUB, PRIV, or nothing
4189 fn parse_visibility(&mut self) -> Visibility {
4190 if self.eat_keyword(keywords::Pub) { Public }
4194 fn parse_sized(&mut self) -> Sized {
4195 if self.eat_keyword(keywords::Type) { DynSize }
4199 fn parse_for_sized(&mut self) -> Sized {
4200 if self.eat_keyword(keywords::For) {
4201 if !self.eat_keyword(keywords::Type) {
4202 let last_span = self.last_span;
4203 self.span_err(last_span,
4204 "expected 'type' after for in trait item");
4212 // given a termination token and a vector of already-parsed
4213 // attributes (of length 0 or 1), parse all of the items in a module
4214 fn parse_mod_items(&mut self,
4216 first_item_attrs: Vec<Attribute>,
4219 // parse all of the items up to closing or an attribute.
4220 // view items are legal here.
4221 let ParsedItemsAndViewItems {
4222 attrs_remaining: attrs_remaining,
4223 view_items: view_items,
4224 items: starting_items,
4226 } = self.parse_items_and_view_items(first_item_attrs, true, true);
4227 let mut items: Vec<Gc<Item>> = starting_items;
4228 let attrs_remaining_len = attrs_remaining.len();
4230 // don't think this other loop is even necessary....
4232 let mut first = true;
4233 while self.token != term {
4234 let mut attrs = self.parse_outer_attributes();
4236 attrs = attrs_remaining.clone().append(attrs.as_slice());
4239 debug!("parse_mod_items: parse_item_or_view_item(attrs={:?})",
4241 match self.parse_item_or_view_item(attrs,
4242 true /* macros allowed */) {
4243 IoviItem(item) => items.push(item),
4244 IoviViewItem(view_item) => {
4245 self.span_fatal(view_item.span,
4246 "view items must be declared at the top of \
4250 let token_str = self.this_token_to_str();
4251 self.fatal(format!("expected item but found `{}`",
4252 token_str).as_slice())
4257 if first && attrs_remaining_len > 0u {
4258 // We parsed attributes for the first item but didn't find it
4259 let last_span = self.last_span;
4260 self.span_err(last_span, "expected item after attributes");
4264 inner: mk_sp(inner_lo, self.span.lo),
4265 view_items: view_items,
4270 fn parse_item_const(&mut self) -> ItemInfo {
4271 let m = if self.eat_keyword(keywords::Mut) {MutMutable} else {MutImmutable};
4272 let id = self.parse_ident();
4273 self.expect(&token::COLON);
4274 let ty = self.parse_ty(true);
4275 self.expect(&token::EQ);
4276 let e = self.parse_expr();
4277 self.commit_expr_expecting(e, token::SEMI);
4278 (id, ItemStatic(ty, m, e), None)
4281 // parse a `mod <foo> { ... }` or `mod <foo>;` item
4282 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> ItemInfo {
4283 let id_span = self.span;
4284 let id = self.parse_ident();
4285 if self.token == token::SEMI {
4287 // This mod is in an external file. Let's go get it!
4288 let (m, attrs) = self.eval_src_mod(id, outer_attrs, id_span);
4289 (id, m, Some(attrs))
4291 self.push_mod_path(id, outer_attrs);
4292 self.expect(&token::LBRACE);
4293 let mod_inner_lo = self.span.lo;
4294 let old_owns_directory = self.owns_directory;
4295 self.owns_directory = true;
4296 let (inner, next) = self.parse_inner_attrs_and_next();
4297 let m = self.parse_mod_items(token::RBRACE, next, mod_inner_lo);
4298 self.expect(&token::RBRACE);
4299 self.owns_directory = old_owns_directory;
4300 self.pop_mod_path();
4301 (id, ItemMod(m), Some(inner))
4305 fn push_mod_path(&mut self, id: Ident, attrs: &[Attribute]) {
4306 let default_path = self.id_to_interned_str(id);
4307 let file_path = match ::attr::first_attr_value_str_by_name(attrs,
4310 None => default_path,
4312 self.mod_path_stack.push(file_path)
4315 fn pop_mod_path(&mut self) {
4316 self.mod_path_stack.pop().unwrap();
4319 // read a module from a source file.
4320 fn eval_src_mod(&mut self,
4322 outer_attrs: &[ast::Attribute],
4324 -> (ast::Item_, Vec<ast::Attribute> ) {
4325 let mut prefix = Path::new(self.sess.span_diagnostic.cm.span_to_filename(self.span));
4327 let mod_path = Path::new(".").join_many(self.mod_path_stack.as_slice());
4328 let dir_path = prefix.join(&mod_path);
4329 let mod_string = token::get_ident(id);
4330 let (file_path, owns_directory) = match ::attr::first_attr_value_str_by_name(
4331 outer_attrs, "path") {
4332 Some(d) => (dir_path.join(d), true),
4334 let mod_name = mod_string.get().to_string();
4335 let default_path_str = format!("{}.rs", mod_name);
4336 let secondary_path_str = format!("{}/mod.rs", mod_name);
4337 let default_path = dir_path.join(default_path_str.as_slice());
4338 let secondary_path = dir_path.join(secondary_path_str.as_slice());
4339 let default_exists = default_path.exists();
4340 let secondary_exists = secondary_path.exists();
4342 if !self.owns_directory {
4343 self.span_err(id_sp,
4344 "cannot declare a new module at this location");
4345 let this_module = match self.mod_path_stack.last() {
4346 Some(name) => name.get().to_string(),
4347 None => self.root_module_name.get_ref().clone(),
4349 self.span_note(id_sp,
4350 format!("maybe move this module `{0}` \
4351 to its own directory via \
4353 this_module).as_slice());
4354 if default_exists || secondary_exists {
4355 self.span_note(id_sp,
4356 format!("... or maybe `use` the module \
4357 `{}` instead of possibly \
4359 mod_name).as_slice());
4361 self.abort_if_errors();
4364 match (default_exists, secondary_exists) {
4365 (true, false) => (default_path, false),
4366 (false, true) => (secondary_path, true),
4368 self.span_fatal(id_sp,
4369 format!("file not found for module \
4371 mod_name).as_slice());
4376 format!("file for module `{}` found at both {} \
4380 secondary_path_str).as_slice());
4386 self.eval_src_mod_from_path(file_path, owns_directory,
4387 mod_string.get().to_string(), id_sp)
4390 fn eval_src_mod_from_path(&mut self,
4392 owns_directory: bool,
4394 id_sp: Span) -> (ast::Item_, Vec<ast::Attribute> ) {
4395 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
4396 match included_mod_stack.iter().position(|p| *p == path) {
4398 let mut err = String::from_str("circular modules: ");
4399 let len = included_mod_stack.len();
4400 for p in included_mod_stack.slice(i, len).iter() {
4401 err.push_str(p.display().as_maybe_owned().as_slice());
4402 err.push_str(" -> ");
4404 err.push_str(path.display().as_maybe_owned().as_slice());
4405 self.span_fatal(id_sp, err.as_slice());
4409 included_mod_stack.push(path.clone());
4410 drop(included_mod_stack);
4413 new_sub_parser_from_file(self.sess,
4419 let mod_inner_lo = p0.span.lo;
4420 let (mod_attrs, next) = p0.parse_inner_attrs_and_next();
4421 let first_item_outer_attrs = next;
4422 let m0 = p0.parse_mod_items(token::EOF, first_item_outer_attrs, mod_inner_lo);
4423 self.sess.included_mod_stack.borrow_mut().pop();
4424 return (ast::ItemMod(m0), mod_attrs);
4427 // parse a function declaration from a foreign module
4428 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility,
4429 attrs: Vec<Attribute>) -> Gc<ForeignItem> {
4430 let lo = self.span.lo;
4431 self.expect_keyword(keywords::Fn);
4433 let (ident, generics) = self.parse_fn_header();
4434 let decl = self.parse_fn_decl(true);
4435 let hi = self.span.hi;
4436 self.expect(&token::SEMI);
4437 box(GC) ast::ForeignItem { ident: ident,
4439 node: ForeignItemFn(decl, generics),
4440 id: ast::DUMMY_NODE_ID,
4441 span: mk_sp(lo, hi),
4445 // parse a static item from a foreign module
4446 fn parse_item_foreign_static(&mut self, vis: ast::Visibility,
4447 attrs: Vec<Attribute> ) -> Gc<ForeignItem> {
4448 let lo = self.span.lo;
4450 self.expect_keyword(keywords::Static);
4451 let mutbl = self.eat_keyword(keywords::Mut);
4453 let ident = self.parse_ident();
4454 self.expect(&token::COLON);
4455 let ty = self.parse_ty(true);
4456 let hi = self.span.hi;
4457 self.expect(&token::SEMI);
4458 box(GC) ast::ForeignItem {
4461 node: ForeignItemStatic(ty, mutbl),
4462 id: ast::DUMMY_NODE_ID,
4463 span: mk_sp(lo, hi),
4468 // parse safe/unsafe and fn
4469 fn parse_fn_style(&mut self) -> FnStyle {
4470 if self.eat_keyword(keywords::Fn) { NormalFn }
4471 else if self.eat_keyword(keywords::Unsafe) {
4472 self.expect_keyword(keywords::Fn);
4475 else { self.unexpected(); }
4479 // at this point, this is essentially a wrapper for
4480 // parse_foreign_items.
4481 fn parse_foreign_mod_items(&mut self,
4483 first_item_attrs: Vec<Attribute> )
4485 let ParsedItemsAndViewItems {
4486 attrs_remaining: attrs_remaining,
4487 view_items: view_items,
4489 foreign_items: foreign_items
4490 } = self.parse_foreign_items(first_item_attrs, true);
4491 if ! attrs_remaining.is_empty() {
4492 let last_span = self.last_span;
4493 self.span_err(last_span,
4494 "expected item after attributes");
4496 assert!(self.token == token::RBRACE);
4499 view_items: view_items,
4500 items: foreign_items
4504 /// Parse extern crate links
4508 /// extern crate url;
4509 /// extern crate foo = "bar";
4510 fn parse_item_extern_crate(&mut self,
4512 visibility: Visibility,
4513 attrs: Vec<Attribute> )
4516 let (maybe_path, ident) = match self.token {
4517 token::IDENT(..) => {
4518 let the_ident = self.parse_ident();
4519 self.expect_one_of(&[], &[token::EQ, token::SEMI]);
4520 let path = if self.token == token::EQ {
4522 Some(self.parse_str())
4525 self.expect(&token::SEMI);
4529 let span = self.span;
4530 let token_str = self.this_token_to_str();
4531 self.span_fatal(span,
4532 format!("expected extern crate name but \
4534 token_str).as_slice());
4538 IoviViewItem(ast::ViewItem {
4539 node: ViewItemExternCrate(ident, maybe_path, ast::DUMMY_NODE_ID),
4542 span: mk_sp(lo, self.last_span.hi)
4546 /// Parse `extern` for foreign ABIs
4549 /// `extern` is expected to have been
4550 /// consumed before calling this method
4556 fn parse_item_foreign_mod(&mut self,
4558 opt_abi: Option<abi::Abi>,
4559 visibility: Visibility,
4560 attrs: Vec<Attribute> )
4563 self.expect(&token::LBRACE);
4565 let abi = opt_abi.unwrap_or(abi::C);
4567 let (inner, next) = self.parse_inner_attrs_and_next();
4568 let m = self.parse_foreign_mod_items(abi, next);
4569 self.expect(&token::RBRACE);
4571 let last_span = self.last_span;
4572 let item = self.mk_item(lo,
4574 special_idents::invalid,
4577 maybe_append(attrs, Some(inner)));
4578 return IoviItem(item);
4581 // parse type Foo = Bar;
4582 fn parse_item_type(&mut self) -> ItemInfo {
4583 let ident = self.parse_ident();
4584 let tps = self.parse_generics();
4585 self.expect(&token::EQ);
4586 let ty = self.parse_ty(true);
4587 self.expect(&token::SEMI);
4588 (ident, ItemTy(ty, tps), None)
4591 // parse a structure-like enum variant definition
4592 // this should probably be renamed or refactored...
4593 fn parse_struct_def(&mut self) -> Gc<StructDef> {
4594 let mut fields: Vec<StructField> = Vec::new();
4595 while self.token != token::RBRACE {
4596 fields.push(self.parse_struct_decl_field());
4600 return box(GC) ast::StructDef {
4608 // parse the part of an "enum" decl following the '{'
4609 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> EnumDef {
4610 let mut variants = Vec::new();
4611 let mut all_nullary = true;
4612 let mut have_disr = false;
4613 while self.token != token::RBRACE {
4614 let variant_attrs = self.parse_outer_attributes();
4615 let vlo = self.span.lo;
4617 let vis = self.parse_visibility();
4621 let mut args = Vec::new();
4622 let mut disr_expr = None;
4623 ident = self.parse_ident();
4624 if self.eat(&token::LBRACE) {
4625 // Parse a struct variant.
4626 all_nullary = false;
4627 kind = StructVariantKind(self.parse_struct_def());
4628 } else if self.token == token::LPAREN {
4629 all_nullary = false;
4630 let arg_tys = self.parse_enum_variant_seq(
4633 seq_sep_trailing_disallowed(token::COMMA),
4634 |p| p.parse_ty(true)
4636 for ty in arg_tys.move_iter() {
4637 args.push(ast::VariantArg {
4639 id: ast::DUMMY_NODE_ID,
4642 kind = TupleVariantKind(args);
4643 } else if self.eat(&token::EQ) {
4645 disr_expr = Some(self.parse_expr());
4646 kind = TupleVariantKind(args);
4648 kind = TupleVariantKind(Vec::new());
4651 let vr = ast::Variant_ {
4653 attrs: variant_attrs,
4655 id: ast::DUMMY_NODE_ID,
4656 disr_expr: disr_expr,
4659 variants.push(P(spanned(vlo, self.last_span.hi, vr)));
4661 if !self.eat(&token::COMMA) { break; }
4663 self.expect(&token::RBRACE);
4664 if have_disr && !all_nullary {
4665 self.fatal("discriminator values can only be used with a c-like \
4669 ast::EnumDef { variants: variants }
4672 // parse an "enum" declaration
4673 fn parse_item_enum(&mut self) -> ItemInfo {
4674 let id = self.parse_ident();
4675 let generics = self.parse_generics();
4676 self.expect(&token::LBRACE);
4678 let enum_definition = self.parse_enum_def(&generics);
4679 (id, ItemEnum(enum_definition, generics), None)
4682 fn fn_expr_lookahead(tok: &token::Token) -> bool {
4684 token::LPAREN | token::AT | token::TILDE | token::BINOP(_) => true,
4689 // Parses a string as an ABI spec on an extern type or module. Consumes
4690 // the `extern` keyword, if one is found.
4691 fn parse_opt_abi(&mut self) -> Option<abi::Abi> {
4693 token::LIT_STR(s) | token::LIT_STR_RAW(s, _) => {
4695 let identifier_string = token::get_ident(s);
4696 let the_string = identifier_string.get();
4697 match abi::lookup(the_string) {
4698 Some(abi) => Some(abi),
4700 let last_span = self.last_span;
4703 format!("illegal ABI: expected one of [{}], \
4705 abi::all_names().connect(", "),
4706 the_string).as_slice());
4716 // parse one of the items or view items allowed by the
4717 // flags; on failure, return IoviNone.
4718 // NB: this function no longer parses the items inside an
4720 fn parse_item_or_view_item(&mut self,
4721 attrs: Vec<Attribute> ,
4722 macros_allowed: bool)
4725 INTERPOLATED(token::NtItem(item)) => {
4727 let new_attrs = attrs.append(item.attrs.as_slice());
4728 return IoviItem(box(GC) Item {
4736 let lo = self.span.lo;
4738 let visibility = self.parse_visibility();
4740 // must be a view item:
4741 if self.eat_keyword(keywords::Use) {
4742 // USE ITEM (IoviViewItem)
4743 let view_item = self.parse_use();
4744 self.expect(&token::SEMI);
4745 return IoviViewItem(ast::ViewItem {
4749 span: mk_sp(lo, self.last_span.hi)
4752 // either a view item or an item:
4753 if self.eat_keyword(keywords::Extern) {
4754 let next_is_mod = self.eat_keyword(keywords::Mod);
4756 if next_is_mod || self.eat_keyword(keywords::Crate) {
4758 let last_span = self.last_span;
4759 self.span_err(mk_sp(lo, last_span.hi),
4760 format!("`extern mod` is obsolete, use \
4761 `extern crate` instead \
4762 to refer to external \
4763 crates.").as_slice())
4765 return self.parse_item_extern_crate(lo, visibility, attrs);
4768 let opt_abi = self.parse_opt_abi();
4770 if self.eat_keyword(keywords::Fn) {
4771 // EXTERN FUNCTION ITEM
4772 let abi = opt_abi.unwrap_or(abi::C);
4773 let (ident, item_, extra_attrs) =
4774 self.parse_item_fn(NormalFn, abi);
4775 let last_span = self.last_span;
4776 let item = self.mk_item(lo,
4781 maybe_append(attrs, extra_attrs));
4782 return IoviItem(item);
4783 } else if self.token == token::LBRACE {
4784 return self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs);
4787 let span = self.span;
4788 let token_str = self.this_token_to_str();
4789 self.span_fatal(span,
4790 format!("expected `{}` or `fn` but found `{}`", "{",
4791 token_str).as_slice());
4794 let is_virtual = self.eat_keyword(keywords::Virtual);
4795 if is_virtual && !self.is_keyword(keywords::Struct) {
4796 let span = self.span;
4798 "`virtual` keyword may only be used with `struct`");
4801 // the rest are all guaranteed to be items:
4802 if self.is_keyword(keywords::Static) {
4805 let (ident, item_, extra_attrs) = self.parse_item_const();
4806 let last_span = self.last_span;
4807 let item = self.mk_item(lo,
4812 maybe_append(attrs, extra_attrs));
4813 return IoviItem(item);
4815 if self.is_keyword(keywords::Fn) &&
4816 self.look_ahead(1, |f| !Parser::fn_expr_lookahead(f)) {
4819 let (ident, item_, extra_attrs) =
4820 self.parse_item_fn(NormalFn, abi::Rust);
4821 let last_span = self.last_span;
4822 let item = self.mk_item(lo,
4827 maybe_append(attrs, extra_attrs));
4828 return IoviItem(item);
4830 if self.is_keyword(keywords::Unsafe)
4831 && self.look_ahead(1u, |t| *t != token::LBRACE) {
4832 // UNSAFE FUNCTION ITEM
4834 let abi = if self.eat_keyword(keywords::Extern) {
4835 self.parse_opt_abi().unwrap_or(abi::C)
4839 self.expect_keyword(keywords::Fn);
4840 let (ident, item_, extra_attrs) =
4841 self.parse_item_fn(UnsafeFn, abi);
4842 let last_span = self.last_span;
4843 let item = self.mk_item(lo,
4848 maybe_append(attrs, extra_attrs));
4849 return IoviItem(item);
4851 if self.eat_keyword(keywords::Mod) {
4853 let (ident, item_, extra_attrs) =
4854 self.parse_item_mod(attrs.as_slice());
4855 let last_span = self.last_span;
4856 let item = self.mk_item(lo,
4861 maybe_append(attrs, extra_attrs));
4862 return IoviItem(item);
4864 if self.eat_keyword(keywords::Type) {
4866 let (ident, item_, extra_attrs) = self.parse_item_type();
4867 let last_span = self.last_span;
4868 let item = self.mk_item(lo,
4873 maybe_append(attrs, extra_attrs));
4874 return IoviItem(item);
4876 if self.eat_keyword(keywords::Enum) {
4878 let (ident, item_, extra_attrs) = self.parse_item_enum();
4879 let last_span = self.last_span;
4880 let item = self.mk_item(lo,
4885 maybe_append(attrs, extra_attrs));
4886 return IoviItem(item);
4888 if self.eat_keyword(keywords::Trait) {
4890 let (ident, item_, extra_attrs) = self.parse_item_trait();
4891 let last_span = self.last_span;
4892 let item = self.mk_item(lo,
4897 maybe_append(attrs, extra_attrs));
4898 return IoviItem(item);
4900 if self.eat_keyword(keywords::Impl) {
4902 let (ident, item_, extra_attrs) = self.parse_item_impl();
4903 let last_span = self.last_span;
4904 let item = self.mk_item(lo,
4909 maybe_append(attrs, extra_attrs));
4910 return IoviItem(item);
4912 if self.eat_keyword(keywords::Struct) {
4914 let (ident, item_, extra_attrs) = self.parse_item_struct(is_virtual);
4915 let last_span = self.last_span;
4916 let item = self.mk_item(lo,
4921 maybe_append(attrs, extra_attrs));
4922 return IoviItem(item);
4924 self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility)
4927 // parse a foreign item; on failure, return IoviNone.
4928 fn parse_foreign_item(&mut self,
4929 attrs: Vec<Attribute> ,
4930 macros_allowed: bool)
4932 maybe_whole!(iovi self, NtItem);
4933 let lo = self.span.lo;
4935 let visibility = self.parse_visibility();
4937 if self.is_keyword(keywords::Static) {
4938 // FOREIGN STATIC ITEM
4939 let item = self.parse_item_foreign_static(visibility, attrs);
4940 return IoviForeignItem(item);
4942 if self.is_keyword(keywords::Fn) || self.is_keyword(keywords::Unsafe) {
4943 // FOREIGN FUNCTION ITEM
4944 let item = self.parse_item_foreign_fn(visibility, attrs);
4945 return IoviForeignItem(item);
4947 self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility)
4950 // this is the fall-through for parsing items.
4951 fn parse_macro_use_or_failure(
4953 attrs: Vec<Attribute> ,
4954 macros_allowed: bool,
4956 visibility: Visibility
4957 ) -> ItemOrViewItem {
4958 if macros_allowed && !token::is_any_keyword(&self.token)
4959 && self.look_ahead(1, |t| *t == token::NOT)
4960 && (self.look_ahead(2, |t| is_plain_ident(t))
4961 || self.look_ahead(2, |t| *t == token::LPAREN)
4962 || self.look_ahead(2, |t| *t == token::LBRACE)) {
4963 // MACRO INVOCATION ITEM
4966 let pth = self.parse_path(NoTypesAllowed).path;
4967 self.expect(&token::NOT);
4969 // a 'special' identifier (like what `macro_rules!` uses)
4970 // is optional. We should eventually unify invoc syntax
4972 let id = if is_plain_ident(&self.token) {
4975 token::special_idents::invalid // no special identifier
4977 // eat a matched-delimiter token tree:
4978 let tts = match token::close_delimiter_for(&self.token) {
4981 self.parse_seq_to_end(&ket,
4983 |p| p.parse_token_tree())
4985 None => self.fatal("expected open delimiter")
4987 // single-variant-enum... :
4988 let m = ast::MacInvocTT(pth, tts, EMPTY_CTXT);
4989 let m: ast::Mac = codemap::Spanned { node: m,
4990 span: mk_sp(self.span.lo,
4992 let item_ = ItemMac(m);
4993 let last_span = self.last_span;
4994 let item = self.mk_item(lo,
5000 return IoviItem(item);
5003 // FAILURE TO PARSE ITEM
5004 if visibility != Inherited {
5005 let mut s = String::from_str("unmatched visibility `");
5006 if visibility == Public {
5012 let last_span = self.last_span;
5013 self.span_fatal(last_span, s.as_slice());
5015 return IoviNone(attrs);
5018 pub fn parse_item_with_outer_attributes(&mut self) -> Option<Gc<Item>> {
5019 let attrs = self.parse_outer_attributes();
5020 self.parse_item(attrs)
5023 pub fn parse_item(&mut self, attrs: Vec<Attribute> ) -> Option<Gc<Item>> {
5024 match self.parse_item_or_view_item(attrs, true) {
5025 IoviNone(_) => None,
5027 self.fatal("view items are not allowed here"),
5028 IoviForeignItem(_) =>
5029 self.fatal("foreign items are not allowed here"),
5030 IoviItem(item) => Some(item)
5034 // parse, e.g., "use a::b::{z,y}"
5035 fn parse_use(&mut self) -> ViewItem_ {
5036 return ViewItemUse(self.parse_view_path());
5040 // matches view_path : MOD? IDENT EQ non_global_path
5041 // | MOD? non_global_path MOD_SEP LBRACE RBRACE
5042 // | MOD? non_global_path MOD_SEP LBRACE ident_seq RBRACE
5043 // | MOD? non_global_path MOD_SEP STAR
5044 // | MOD? non_global_path
5045 fn parse_view_path(&mut self) -> Gc<ViewPath> {
5046 let lo = self.span.lo;
5048 if self.token == token::LBRACE {
5050 let idents = self.parse_unspanned_seq(
5051 &token::LBRACE, &token::RBRACE,
5052 seq_sep_trailing_allowed(token::COMMA),
5053 |p| p.parse_path_list_ident());
5054 let path = ast::Path {
5055 span: mk_sp(lo, self.span.hi),
5057 segments: Vec::new()
5059 return box(GC) spanned(lo, self.span.hi,
5060 ViewPathList(path, idents, ast::DUMMY_NODE_ID));
5063 let first_ident = self.parse_ident();
5064 let mut path = vec!(first_ident);
5069 let path_lo = self.span.lo;
5070 path = vec!(self.parse_ident());
5071 while self.token == token::MOD_SEP {
5073 let id = self.parse_ident();
5076 let path = ast::Path {
5077 span: mk_sp(path_lo, self.span.hi),
5079 segments: path.move_iter().map(|identifier| {
5081 identifier: identifier,
5082 lifetimes: Vec::new(),
5083 types: OwnedSlice::empty(),
5087 return box(GC) spanned(lo, self.span.hi,
5088 ViewPathSimple(first_ident, path,
5089 ast::DUMMY_NODE_ID));
5093 // foo::bar or foo::{a,b,c} or foo::*
5094 while self.token == token::MOD_SEP {
5098 token::IDENT(i, _) => {
5103 // foo::bar::{a,b,c}
5105 let idents = self.parse_unspanned_seq(
5108 seq_sep_trailing_allowed(token::COMMA),
5109 |p| p.parse_path_list_ident()
5111 let path = ast::Path {
5112 span: mk_sp(lo, self.span.hi),
5114 segments: path.move_iter().map(|identifier| {
5116 identifier: identifier,
5117 lifetimes: Vec::new(),
5118 types: OwnedSlice::empty(),
5122 return box(GC) spanned(lo, self.span.hi,
5123 ViewPathList(path, idents, ast::DUMMY_NODE_ID));
5127 token::BINOP(token::STAR) => {
5129 let path = ast::Path {
5130 span: mk_sp(lo, self.span.hi),
5132 segments: path.move_iter().map(|identifier| {
5134 identifier: identifier,
5135 lifetimes: Vec::new(),
5136 types: OwnedSlice::empty(),
5140 return box(GC) spanned(lo, self.span.hi,
5141 ViewPathGlob(path, ast::DUMMY_NODE_ID));
5150 let last = *path.get(path.len() - 1u);
5151 let path = ast::Path {
5152 span: mk_sp(lo, self.span.hi),
5154 segments: path.move_iter().map(|identifier| {
5156 identifier: identifier,
5157 lifetimes: Vec::new(),
5158 types: OwnedSlice::empty(),
5162 return box(GC) spanned(lo,
5164 ViewPathSimple(last, path, ast::DUMMY_NODE_ID));
5167 // Parses a sequence of items. Stops when it finds program
5168 // text that can't be parsed as an item
5169 // - mod_items uses extern_mod_allowed = true
5170 // - block_tail_ uses extern_mod_allowed = false
5171 fn parse_items_and_view_items(&mut self,
5172 first_item_attrs: Vec<Attribute> ,
5173 mut extern_mod_allowed: bool,
5174 macros_allowed: bool)
5175 -> ParsedItemsAndViewItems {
5176 let mut attrs = first_item_attrs.append(self.parse_outer_attributes().as_slice());
5177 // First, parse view items.
5178 let mut view_items : Vec<ast::ViewItem> = Vec::new();
5179 let mut items = Vec::new();
5181 // I think this code would probably read better as a single
5182 // loop with a mutable three-state-variable (for extern crates,
5183 // view items, and regular items) ... except that because
5184 // of macros, I'd like to delay that entire check until later.
5186 match self.parse_item_or_view_item(attrs, macros_allowed) {
5187 IoviNone(attrs) => {
5188 return ParsedItemsAndViewItems {
5189 attrs_remaining: attrs,
5190 view_items: view_items,
5192 foreign_items: Vec::new()
5195 IoviViewItem(view_item) => {
5196 match view_item.node {
5197 ViewItemUse(..) => {
5198 // `extern crate` must precede `use`.
5199 extern_mod_allowed = false;
5201 ViewItemExternCrate(..) if !extern_mod_allowed => {
5202 self.span_err(view_item.span,
5203 "\"extern crate\" declarations are \
5206 ViewItemExternCrate(..) => {}
5208 view_items.push(view_item);
5212 attrs = self.parse_outer_attributes();
5215 IoviForeignItem(_) => {
5219 attrs = self.parse_outer_attributes();
5222 // Next, parse items.
5224 match self.parse_item_or_view_item(attrs, macros_allowed) {
5225 IoviNone(returned_attrs) => {
5226 attrs = returned_attrs;
5229 IoviViewItem(view_item) => {
5230 attrs = self.parse_outer_attributes();
5231 self.span_err(view_item.span,
5232 "`use` and `extern crate` declarations must precede items");
5235 attrs = self.parse_outer_attributes();
5238 IoviForeignItem(_) => {
5244 ParsedItemsAndViewItems {
5245 attrs_remaining: attrs,
5246 view_items: view_items,
5248 foreign_items: Vec::new()
5252 // Parses a sequence of foreign items. Stops when it finds program
5253 // text that can't be parsed as an item
5254 fn parse_foreign_items(&mut self, first_item_attrs: Vec<Attribute> ,
5255 macros_allowed: bool)
5256 -> ParsedItemsAndViewItems {
5257 let mut attrs = first_item_attrs.append(self.parse_outer_attributes().as_slice());
5258 let mut foreign_items = Vec::new();
5260 match self.parse_foreign_item(attrs, macros_allowed) {
5261 IoviNone(returned_attrs) => {
5262 if self.token == token::RBRACE {
5263 attrs = returned_attrs;
5268 IoviViewItem(view_item) => {
5269 // I think this can't occur:
5270 self.span_err(view_item.span,
5271 "`use` and `extern crate` declarations must precede items");
5274 // FIXME #5668: this will occur for a macro invocation:
5275 self.span_fatal(item.span, "macros cannot expand to foreign items");
5277 IoviForeignItem(foreign_item) => {
5278 foreign_items.push(foreign_item);
5281 attrs = self.parse_outer_attributes();
5284 ParsedItemsAndViewItems {
5285 attrs_remaining: attrs,
5286 view_items: Vec::new(),
5288 foreign_items: foreign_items
5292 // Parses a source module as a crate. This is the main
5293 // entry point for the parser.
5294 pub fn parse_crate_mod(&mut self) -> Crate {
5295 let lo = self.span.lo;
5296 // parse the crate's inner attrs, maybe (oops) one
5297 // of the attrs of an item:
5298 let (inner, next) = self.parse_inner_attrs_and_next();
5299 let first_item_outer_attrs = next;
5300 // parse the items inside the crate:
5301 let m = self.parse_mod_items(token::EOF, first_item_outer_attrs, lo);
5306 config: self.cfg.clone(),
5307 span: mk_sp(lo, self.span.lo)
5311 pub fn parse_optional_str(&mut self)
5312 -> Option<(InternedString, ast::StrStyle)> {
5313 let (s, style) = match self.token {
5314 token::LIT_STR(s) => (self.id_to_interned_str(s), ast::CookedStr),
5315 token::LIT_STR_RAW(s, n) => {
5316 (self.id_to_interned_str(s), ast::RawStr(n))
5324 pub fn parse_str(&mut self) -> (InternedString, StrStyle) {
5325 match self.parse_optional_str() {
5327 _ => self.fatal("expected string literal")