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, LitChar, LitByte, LitBinary};
37 use ast::{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::{StmtExpr, StmtSemi, StmtMac, StructDef, StructField};
46 use ast::{StructVariantKind, BiSub};
48 use ast::{SelfRegion, SelfStatic, SelfUniq, SelfValue};
49 use ast::{TokenTree, TraitMethod, TraitRef, TTDelim, TTSeq, TTTok};
50 use ast::{TTNonterminal, TupleVariantKind, Ty, Ty_, TyBot, TyBox};
51 use ast::{TypeField, TyFixedLengthVec, TyClosure, TyProc, TyBareFn};
52 use ast::{TyTypeof, TyInfer, TypeMethod};
53 use ast::{TyNil, TyParam, TyParamBound, TyParen, TyPath, TyPtr, TyRptr};
54 use ast::{TyTup, TyU32, TyUnboxedFn, TyUniq, TyVec, UnUniq};
55 use ast::{UnboxedFnTy, UnboxedFnTyParamBound, UnnamedField, UnsafeBlock};
56 use ast::{UnsafeFn, ViewItem, ViewItem_, ViewItemExternCrate, ViewItemUse};
57 use ast::{ViewPath, ViewPathGlob, ViewPathList, ViewPathSimple};
60 use ast_util::{as_prec, ident_to_path, lit_is_str, operator_prec};
62 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,
91 RESTRICT_NO_STRUCT_LITERAL,
94 type ItemInfo = (Ident, Item_, Option<Vec<Attribute> >);
96 /// How to parse a path. There are four different kinds of paths, all of which
97 /// are parsed somewhat differently.
98 #[deriving(PartialEq)]
99 pub enum PathParsingMode {
100 /// A path with no type parameters; e.g. `foo::bar::Baz`
102 /// A path with a lifetime and type parameters, with no double colons
103 /// before the type parameters; e.g. `foo::bar<'a>::Baz<T>`
104 LifetimeAndTypesWithoutColons,
105 /// A path with a lifetime and type parameters with double colons before
106 /// the type parameters; e.g. `foo::bar::<'a>::Baz::<T>`
107 LifetimeAndTypesWithColons,
108 /// A path with a lifetime and type parameters with bounds before the last
109 /// set of type parameters only; e.g. `foo::bar<'a>::Baz+X+Y<T>` This
110 /// form does not use extra double colons.
111 LifetimeAndTypesAndBounds,
114 /// A path paired with optional type bounds.
115 pub struct PathAndBounds {
117 pub bounds: Option<OwnedSlice<TyParamBound>>,
120 enum ItemOrViewItem {
121 /// Indicates a failure to parse any kind of item. The attributes are
123 IoviNone(Vec<Attribute>),
125 IoviForeignItem(Gc<ForeignItem>),
126 IoviViewItem(ViewItem)
130 /// Possibly accept an `INTERPOLATED` expression (a pre-parsed expression
131 /// dropped into the token stream, which happens while parsing the
132 /// result of macro expansion)
133 /// Placement of these is not as complex as I feared it would be.
134 /// The important thing is to make sure that lookahead doesn't balk
135 /// at INTERPOLATED tokens
136 macro_rules! maybe_whole_expr (
139 let found = match $p.token {
140 INTERPOLATED(token::NtExpr(e)) => {
143 INTERPOLATED(token::NtPath(_)) => {
144 // FIXME: The following avoids an issue with lexical borrowck scopes,
145 // but the clone is unfortunate.
146 let pt = match $p.token {
147 INTERPOLATED(token::NtPath(ref pt)) => (**pt).clone(),
151 Some($p.mk_expr(span.lo, span.hi, ExprPath(pt)))
153 INTERPOLATED(token::NtBlock(b)) => {
155 Some($p.mk_expr(span.lo, span.hi, ExprBlock(b)))
170 /// As maybe_whole_expr, but for things other than expressions
171 macro_rules! maybe_whole (
172 ($p:expr, $constructor:ident) => (
174 let found = match ($p).token {
175 INTERPOLATED(token::$constructor(_)) => {
176 Some(($p).bump_and_get())
181 Some(INTERPOLATED(token::$constructor(x))) => {
188 (no_clone $p:expr, $constructor:ident) => (
190 let found = match ($p).token {
191 INTERPOLATED(token::$constructor(_)) => {
192 Some(($p).bump_and_get())
197 Some(INTERPOLATED(token::$constructor(x))) => {
204 (deref $p:expr, $constructor:ident) => (
206 let found = match ($p).token {
207 INTERPOLATED(token::$constructor(_)) => {
208 Some(($p).bump_and_get())
213 Some(INTERPOLATED(token::$constructor(x))) => {
220 (Some $p:expr, $constructor:ident) => (
222 let found = match ($p).token {
223 INTERPOLATED(token::$constructor(_)) => {
224 Some(($p).bump_and_get())
229 Some(INTERPOLATED(token::$constructor(x))) => {
230 return Some(x.clone()),
236 (iovi $p:expr, $constructor:ident) => (
238 let found = match ($p).token {
239 INTERPOLATED(token::$constructor(_)) => {
240 Some(($p).bump_and_get())
245 Some(INTERPOLATED(token::$constructor(x))) => {
246 return IoviItem(x.clone())
252 (pair_empty $p:expr, $constructor:ident) => (
254 let found = match ($p).token {
255 INTERPOLATED(token::$constructor(_)) => {
256 Some(($p).bump_and_get())
261 Some(INTERPOLATED(token::$constructor(x))) => {
262 return (Vec::new(), x)
271 fn maybe_append(lhs: Vec<Attribute> , rhs: Option<Vec<Attribute> >)
275 Some(ref attrs) => lhs.append(attrs.as_slice())
280 struct ParsedItemsAndViewItems {
281 attrs_remaining: Vec<Attribute>,
282 view_items: Vec<ViewItem>,
283 items: Vec<Gc<Item>>,
284 foreign_items: Vec<Gc<ForeignItem>>
287 /* ident is handled by common.rs */
289 pub struct Parser<'a> {
290 pub sess: &'a ParseSess,
291 /// the current token:
292 pub token: token::Token,
293 /// the span of the current token:
295 /// the span of the prior token:
297 pub cfg: CrateConfig,
298 /// the previous token or None (only stashed sometimes).
299 pub last_token: Option<Box<token::Token>>,
300 pub buffer: [TokenAndSpan, ..4],
301 pub buffer_start: int,
303 pub tokens_consumed: uint,
304 pub restriction: restriction,
305 pub quote_depth: uint, // not (yet) related to the quasiquoter
306 pub reader: Box<Reader>,
307 pub interner: Rc<token::IdentInterner>,
308 /// The set of seen errors about obsolete syntax. Used to suppress
309 /// extra detail when the same error is seen twice
310 pub obsolete_set: HashSet<ObsoleteSyntax>,
311 /// Used to determine the path to externally loaded source files
312 pub mod_path_stack: Vec<InternedString>,
313 /// Stack of spans of open delimiters. Used for error message.
314 pub open_braces: Vec<Span>,
315 /// Flag if this parser "owns" the directory that it is currently parsing
316 /// in. This will affect how nested files are looked up.
317 pub owns_directory: bool,
318 /// Name of the root module this parser originated from. If `None`, then the
319 /// name is not known. This does not change while the parser is descending
320 /// into modules, and sub-parsers have new values for this name.
321 pub root_module_name: Option<String>,
324 fn is_plain_ident_or_underscore(t: &token::Token) -> bool {
325 is_plain_ident(t) || *t == token::UNDERSCORE
328 /// Get a token the parser cares about
329 fn real_token(rdr: &mut Reader) -> TokenAndSpan {
330 let mut t = rdr.next_token();
333 token::WS | token::COMMENT | token::SHEBANG(_) => {
334 t = rdr.next_token();
342 impl<'a> Parser<'a> {
343 pub fn new(sess: &'a ParseSess, cfg: ast::CrateConfig,
344 mut rdr: Box<Reader>) -> Parser<'a> {
345 let tok0 = real_token(rdr);
347 let placeholder = TokenAndSpan {
348 tok: token::UNDERSCORE,
354 interner: token::get_ident_interner(),
370 restriction: UNRESTRICTED,
372 obsolete_set: HashSet::new(),
373 mod_path_stack: Vec::new(),
374 open_braces: Vec::new(),
375 owns_directory: true,
376 root_module_name: None,
380 /// Convert a token to a string using self's reader
381 pub fn token_to_string(token: &token::Token) -> String {
382 token::to_string(token)
385 /// Convert the current token to a string using self's reader
386 pub fn this_token_to_string(&mut self) -> String {
387 Parser::token_to_string(&self.token)
390 pub fn unexpected_last(&mut self, t: &token::Token) -> ! {
391 let token_str = Parser::token_to_string(t);
392 let last_span = self.last_span;
393 self.span_fatal(last_span, format!("unexpected token: `{}`",
394 token_str).as_slice());
397 pub fn unexpected(&mut self) -> ! {
398 let this_token = self.this_token_to_string();
399 self.fatal(format!("unexpected token: `{}`", this_token).as_slice());
402 /// Expect and consume the token t. Signal an error if
403 /// the next token is not t.
404 pub fn expect(&mut self, t: &token::Token) {
405 if self.token == *t {
408 let token_str = Parser::token_to_string(t);
409 let this_token_str = self.this_token_to_string();
410 self.fatal(format!("expected `{}` but found `{}`",
412 this_token_str).as_slice())
416 /// Expect next token to be edible or inedible token. If edible,
417 /// then consume it; if inedible, then return without consuming
418 /// anything. Signal a fatal error if next token is unexpected.
419 pub fn expect_one_of(&mut self,
420 edible: &[token::Token],
421 inedible: &[token::Token]) {
422 fn tokens_to_string(tokens: &[token::Token]) -> String {
423 let mut i = tokens.iter();
424 // This might be a sign we need a connect method on Iterator.
426 .map_or("".to_string(), |t| Parser::token_to_string(t));
430 b.push_str(Parser::token_to_string(a).as_slice());
434 if edible.contains(&self.token) {
436 } else if inedible.contains(&self.token) {
437 // leave it in the input
439 let expected = edible.iter().map(|x| (*x).clone()).collect::<Vec<_>>().append(inedible);
440 let expect = tokens_to_string(expected.as_slice());
441 let actual = self.this_token_to_string();
443 (if expected.len() != 1 {
444 (format!("expected one of `{}` but found `{}`",
448 (format!("expected `{}` but found `{}`",
456 /// Check for erroneous `ident { }`; if matches, signal error and
457 /// recover (without consuming any expected input token). Returns
458 /// true if and only if input was consumed for recovery.
459 pub fn check_for_erroneous_unit_struct_expecting(&mut self, expected: &[token::Token]) -> bool {
460 if self.token == token::LBRACE
461 && expected.iter().all(|t| *t != token::LBRACE)
462 && self.look_ahead(1, |t| *t == token::RBRACE) {
463 // matched; signal non-fatal error and recover.
464 let span = self.span;
466 "unit-like struct construction is written with no trailing `{ }`");
467 self.eat(&token::LBRACE);
468 self.eat(&token::RBRACE);
475 /// Commit to parsing a complete expression `e` expected to be
476 /// followed by some token from the set edible + inedible. Recover
477 /// from anticipated input errors, discarding erroneous characters.
478 pub fn commit_expr(&mut self, e: Gc<Expr>, edible: &[token::Token],
479 inedible: &[token::Token]) {
480 debug!("commit_expr {:?}", e);
483 // might be unit-struct construction; check for recoverableinput error.
484 let expected = edible.iter().map(|x| (*x).clone()).collect::<Vec<_>>()
486 self.check_for_erroneous_unit_struct_expecting(
487 expected.as_slice());
491 self.expect_one_of(edible, inedible)
494 pub fn commit_expr_expecting(&mut self, e: Gc<Expr>, edible: token::Token) {
495 self.commit_expr(e, &[edible], &[])
498 /// Commit to parsing a complete statement `s`, which expects to be
499 /// followed by some token from the set edible + inedible. Check
500 /// for recoverable input errors, discarding erroneous characters.
501 pub fn commit_stmt(&mut self, s: Gc<Stmt>, edible: &[token::Token],
502 inedible: &[token::Token]) {
503 debug!("commit_stmt {:?}", s);
504 let _s = s; // unused, but future checks might want to inspect `s`.
505 if self.last_token.as_ref().map_or(false, |t| is_ident_or_path(*t)) {
506 let expected = edible.iter().map(|x| (*x).clone()).collect::<Vec<_>>()
507 .append(inedible.as_slice());
508 self.check_for_erroneous_unit_struct_expecting(
509 expected.as_slice());
511 self.expect_one_of(edible, inedible)
514 pub fn commit_stmt_expecting(&mut self, s: Gc<Stmt>, edible: token::Token) {
515 self.commit_stmt(s, &[edible], &[])
518 pub fn parse_ident(&mut self) -> ast::Ident {
519 self.check_strict_keywords();
520 self.check_reserved_keywords();
522 token::IDENT(i, _) => {
526 token::INTERPOLATED(token::NtIdent(..)) => {
527 self.bug("ident interpolation not converted to real token");
530 let token_str = self.this_token_to_string();
531 self.fatal((format!("expected ident, found `{}`",
532 token_str)).as_slice())
537 pub fn parse_path_list_ident(&mut self) -> ast::PathListIdent {
538 let lo = self.span.lo;
539 let ident = self.parse_ident();
540 let hi = self.last_span.hi;
541 spanned(lo, hi, ast::PathListIdent_ { name: ident,
542 id: ast::DUMMY_NODE_ID })
545 /// Consume token 'tok' if it exists. Returns true if the given
546 /// token was present, false otherwise.
547 pub fn eat(&mut self, tok: &token::Token) -> bool {
548 let is_present = self.token == *tok;
549 if is_present { self.bump() }
553 pub fn is_keyword(&mut self, kw: keywords::Keyword) -> bool {
554 token::is_keyword(kw, &self.token)
557 /// If the next token is the given keyword, eat it and return
558 /// true. Otherwise, return false.
559 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
561 token::IDENT(sid, false) if kw.to_name() == sid.name => {
569 /// If the given word is not a keyword, signal an error.
570 /// If the next token is not the given word, signal an error.
571 /// Otherwise, eat it.
572 pub fn expect_keyword(&mut self, kw: keywords::Keyword) {
573 if !self.eat_keyword(kw) {
574 let id_interned_str = token::get_name(kw.to_name());
575 let token_str = self.this_token_to_string();
576 self.fatal(format!("expected `{}`, found `{}`",
577 id_interned_str, token_str).as_slice())
581 /// Signal an error if the given string is a strict keyword
582 pub fn check_strict_keywords(&mut self) {
583 if token::is_strict_keyword(&self.token) {
584 let token_str = self.this_token_to_string();
585 let span = self.span;
587 format!("found `{}` in ident position",
588 token_str).as_slice());
592 /// Signal an error if the current token is a reserved keyword
593 pub fn check_reserved_keywords(&mut self) {
594 if token::is_reserved_keyword(&self.token) {
595 let token_str = self.this_token_to_string();
596 self.fatal(format!("`{}` is a reserved keyword",
597 token_str).as_slice())
601 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
602 /// `&` and continue. If an `&` is not seen, signal an error.
603 fn expect_and(&mut self) {
605 token::BINOP(token::AND) => self.bump(),
607 let span = self.span;
608 let lo = span.lo + BytePos(1);
609 self.replace_token(token::BINOP(token::AND), lo, span.hi)
612 let token_str = self.this_token_to_string();
614 Parser::token_to_string(&token::BINOP(token::AND));
615 self.fatal(format!("expected `{}`, found `{}`",
617 token_str).as_slice())
622 /// Expect and consume a `|`. If `||` is seen, replace it with a single
623 /// `|` and continue. If a `|` is not seen, signal an error.
624 fn expect_or(&mut self) {
626 token::BINOP(token::OR) => self.bump(),
628 let span = self.span;
629 let lo = span.lo + BytePos(1);
630 self.replace_token(token::BINOP(token::OR), lo, span.hi)
633 let found_token = self.this_token_to_string();
635 Parser::token_to_string(&token::BINOP(token::OR));
636 self.fatal(format!("expected `{}`, found `{}`",
638 found_token).as_slice())
643 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
644 /// `<` and continue. If a `<` is not seen, return false.
646 /// This is meant to be used when parsing generics on a path to get the
647 /// starting token. The `force` parameter is used to forcefully break up a
648 /// `<<` token. If `force` is false, then `<<` is only broken when a lifetime
649 /// shows up next. For example, consider the expression:
651 /// foo as bar << test
653 /// The parser needs to know if `bar <<` is the start of a generic path or if
654 /// it's a left-shift token. If `test` were a lifetime, then it's impossible
655 /// for the token to be a left-shift, but if it's not a lifetime, then it's
656 /// considered a left-shift.
658 /// The reason for this is that the only current ambiguity with `<<` is when
659 /// parsing closure types:
661 /// foo::<<'a> ||>();
662 /// impl Foo<<'a> ||>() { ... }
663 fn eat_lt(&mut self, force: bool) -> bool {
665 token::LT => { self.bump(); true }
666 token::BINOP(token::SHL) => {
667 let next_lifetime = self.look_ahead(1, |t| match *t {
668 token::LIFETIME(..) => true,
671 if force || next_lifetime {
672 let span = self.span;
673 let lo = span.lo + BytePos(1);
674 self.replace_token(token::LT, lo, span.hi);
684 fn expect_lt(&mut self) {
685 if !self.eat_lt(true) {
686 let found_token = self.this_token_to_string();
687 let token_str = Parser::token_to_string(&token::LT);
688 self.fatal(format!("expected `{}`, found `{}`",
690 found_token).as_slice())
694 /// Parse a sequence bracketed by `|` and `|`, stopping before the `|`.
695 fn parse_seq_to_before_or<T>(
698 f: |&mut Parser| -> T)
700 let mut first = true;
701 let mut vector = Vec::new();
702 while self.token != token::BINOP(token::OR) &&
703 self.token != token::OROR {
715 /// Expect and consume a GT. if a >> is seen, replace it
716 /// with a single > and continue. If a GT is not seen,
718 pub fn expect_gt(&mut self) {
720 token::GT => self.bump(),
721 token::BINOP(token::SHR) => {
722 let span = self.span;
723 let lo = span.lo + BytePos(1);
724 self.replace_token(token::GT, lo, span.hi)
726 token::BINOPEQ(token::SHR) => {
727 let span = self.span;
728 let lo = span.lo + BytePos(1);
729 self.replace_token(token::GE, lo, span.hi)
732 let span = self.span;
733 let lo = span.lo + BytePos(1);
734 self.replace_token(token::EQ, lo, span.hi)
737 let gt_str = Parser::token_to_string(&token::GT);
738 let this_token_str = self.this_token_to_string();
739 self.fatal(format!("expected `{}`, found `{}`",
741 this_token_str).as_slice())
746 /// Parse a sequence bracketed by '<' and '>', stopping
748 pub fn parse_seq_to_before_gt<T>(
750 sep: Option<token::Token>,
751 f: |&mut Parser| -> T)
753 let mut first = true;
754 let mut v = Vec::new();
755 while self.token != token::GT
756 && self.token != token::BINOP(token::SHR)
757 && self.token != token::GE
758 && self.token != token::BINOPEQ(token::SHR) {
761 if first { first = false; }
762 else { self.expect(t); }
768 return OwnedSlice::from_vec(v);
771 pub fn parse_seq_to_gt<T>(
773 sep: Option<token::Token>,
774 f: |&mut Parser| -> T)
776 let v = self.parse_seq_to_before_gt(sep, f);
781 /// Parse a sequence, including the closing delimiter. The function
782 /// f must consume tokens until reaching the next separator or
784 pub fn parse_seq_to_end<T>(
788 f: |&mut Parser| -> T)
790 let val = self.parse_seq_to_before_end(ket, sep, f);
795 /// Parse a sequence, not including the closing delimiter. The function
796 /// f must consume tokens until reaching the next separator or
798 pub fn parse_seq_to_before_end<T>(
802 f: |&mut Parser| -> T)
804 let mut first: bool = true;
806 while self.token != *ket {
809 if first { first = false; }
810 else { self.expect(t); }
814 if sep.trailing_sep_allowed && self.token == *ket { break; }
820 /// Parse a sequence, including the closing delimiter. The function
821 /// f must consume tokens until reaching the next separator or
823 pub fn parse_unspanned_seq<T>(
828 f: |&mut Parser| -> T)
831 let result = self.parse_seq_to_before_end(ket, sep, f);
836 /// Parse a sequence parameter of enum variant. For consistency purposes,
837 /// these should not be empty.
838 pub fn parse_enum_variant_seq<T>(
843 f: |&mut Parser| -> T)
845 let result = self.parse_unspanned_seq(bra, ket, sep, f);
846 if result.is_empty() {
847 let last_span = self.last_span;
848 self.span_err(last_span,
849 "nullary enum variants are written with no trailing `( )`");
854 // NB: Do not use this function unless you actually plan to place the
855 // spanned list in the AST.
861 f: |&mut Parser| -> T)
862 -> Spanned<Vec<T> > {
863 let lo = self.span.lo;
865 let result = self.parse_seq_to_before_end(ket, sep, f);
866 let hi = self.span.hi;
868 spanned(lo, hi, result)
871 /// Advance the parser by one token
872 pub fn bump(&mut self) {
873 self.last_span = self.span;
874 // Stash token for error recovery (sometimes; clone is not necessarily cheap).
875 self.last_token = if is_ident_or_path(&self.token) {
876 Some(box self.token.clone())
880 let next = if self.buffer_start == self.buffer_end {
881 real_token(self.reader)
883 // Avoid token copies with `replace`.
884 let buffer_start = self.buffer_start as uint;
885 let next_index = (buffer_start + 1) & 3 as uint;
886 self.buffer_start = next_index as int;
888 let placeholder = TokenAndSpan {
889 tok: token::UNDERSCORE,
892 replace(&mut self.buffer[buffer_start], placeholder)
895 self.token = next.tok;
896 self.tokens_consumed += 1u;
899 /// Advance the parser by one token and return the bumped token.
900 pub fn bump_and_get(&mut self) -> token::Token {
901 let old_token = replace(&mut self.token, token::UNDERSCORE);
906 /// EFFECT: replace the current token and span with the given one
907 pub fn replace_token(&mut self,
911 self.last_span = mk_sp(self.span.lo, lo);
913 self.span = mk_sp(lo, hi);
915 pub fn buffer_length(&mut self) -> int {
916 if self.buffer_start <= self.buffer_end {
917 return self.buffer_end - self.buffer_start;
919 return (4 - self.buffer_start) + self.buffer_end;
921 pub fn look_ahead<R>(&mut self, distance: uint, f: |&token::Token| -> R)
923 let dist = distance as int;
924 while self.buffer_length() < dist {
925 self.buffer[self.buffer_end as uint] = real_token(self.reader);
926 self.buffer_end = (self.buffer_end + 1) & 3;
928 f(&self.buffer[((self.buffer_start + dist - 1) & 3) as uint].tok)
930 pub fn fatal(&mut self, m: &str) -> ! {
931 self.sess.span_diagnostic.span_fatal(self.span, m)
933 pub fn span_fatal(&mut self, sp: Span, m: &str) -> ! {
934 self.sess.span_diagnostic.span_fatal(sp, m)
936 pub fn span_note(&mut self, sp: Span, m: &str) {
937 self.sess.span_diagnostic.span_note(sp, m)
939 pub fn bug(&mut self, m: &str) -> ! {
940 self.sess.span_diagnostic.span_bug(self.span, m)
942 pub fn warn(&mut self, m: &str) {
943 self.sess.span_diagnostic.span_warn(self.span, m)
945 pub fn span_warn(&mut self, sp: Span, m: &str) {
946 self.sess.span_diagnostic.span_warn(sp, m)
948 pub fn span_err(&mut self, sp: Span, m: &str) {
949 self.sess.span_diagnostic.span_err(sp, m)
951 pub fn abort_if_errors(&mut self) {
952 self.sess.span_diagnostic.handler().abort_if_errors();
955 pub fn id_to_interned_str(&mut self, id: Ident) -> InternedString {
959 /// Is the current token one of the keywords that signals a bare function
961 pub fn token_is_bare_fn_keyword(&mut self) -> bool {
962 if token::is_keyword(keywords::Fn, &self.token) {
966 if token::is_keyword(keywords::Unsafe, &self.token) ||
967 token::is_keyword(keywords::Once, &self.token) {
968 return self.look_ahead(1, |t| token::is_keyword(keywords::Fn, t))
974 /// Is the current token one of the keywords that signals a closure type?
975 pub fn token_is_closure_keyword(&mut self) -> bool {
976 token::is_keyword(keywords::Unsafe, &self.token) ||
977 token::is_keyword(keywords::Once, &self.token)
980 /// Is the current token one of the keywords that signals an old-style
981 /// closure type (with explicit sigil)?
982 pub fn token_is_old_style_closure_keyword(&mut self) -> bool {
983 token::is_keyword(keywords::Unsafe, &self.token) ||
984 token::is_keyword(keywords::Once, &self.token) ||
985 token::is_keyword(keywords::Fn, &self.token)
988 pub fn token_is_lifetime(tok: &token::Token) -> bool {
990 token::LIFETIME(..) => true,
995 pub fn get_lifetime(&mut self) -> ast::Ident {
997 token::LIFETIME(ref ident) => *ident,
998 _ => self.bug("not a lifetime"),
1002 /// parse a TyBareFn type:
1003 pub fn parse_ty_bare_fn(&mut self) -> Ty_ {
1006 [unsafe] [extern "ABI"] fn <'lt> (S) -> T
1007 ^~~~^ ^~~~^ ^~~~^ ^~^ ^
1010 | | | Argument types
1016 let fn_style = self.parse_unsafety();
1017 let abi = if self.eat_keyword(keywords::Extern) {
1018 self.parse_opt_abi().unwrap_or(abi::C)
1023 self.expect_keyword(keywords::Fn);
1024 let (decl, lifetimes) = self.parse_ty_fn_decl(true);
1025 return TyBareFn(box(GC) BareFnTy {
1028 lifetimes: lifetimes,
1033 /// Parses a procedure type (`proc`). The initial `proc` keyword must
1034 /// already have been parsed.
1035 pub fn parse_proc_type(&mut self) -> Ty_ {
1038 proc <'lt> (S) [:Bounds] -> T
1039 ^~~^ ^~~~^ ^ ^~~~~~~~^ ^
1049 let lifetimes = if self.eat(&token::LT) {
1050 let lifetimes = self.parse_lifetimes();
1057 let (inputs, variadic) = self.parse_fn_args(false, false);
1059 if self.eat(&token::COLON) {
1060 let (_, bounds) = self.parse_ty_param_bounds(false);
1066 let (ret_style, ret_ty) = self.parse_ret_ty();
1067 let decl = P(FnDecl {
1073 TyProc(box(GC) ClosureTy {
1078 lifetimes: lifetimes,
1082 /// Parse a TyClosure type
1083 pub fn parse_ty_closure(&mut self) -> Ty_ {
1086 [unsafe] [once] <'lt> |S| [:Bounds] -> T
1087 ^~~~~~~^ ^~~~~^ ^~~~^ ^ ^~~~~~~~^ ^
1089 | | | | | Return type
1090 | | | | Closure bounds
1091 | | | Argument types
1093 | Once-ness (a.k.a., affine)
1098 let fn_style = self.parse_unsafety();
1099 let onceness = if self.eat_keyword(keywords::Once) {Once} else {Many};
1101 let lifetimes = if self.eat(&token::LT) {
1102 let lifetimes = self.parse_lifetimes();
1110 let (is_unboxed, inputs) = if self.eat(&token::OROR) {
1115 let is_unboxed = self.token == token::BINOP(token::AND) &&
1116 self.look_ahead(1, |t| {
1117 token::is_keyword(keywords::Mut, t)
1119 self.look_ahead(2, |t| *t == token::COLON);
1126 let inputs = self.parse_seq_to_before_or(
1128 |p| p.parse_arg_general(false));
1130 (is_unboxed, inputs)
1133 let (region, bounds) = {
1134 if self.eat(&token::COLON) {
1135 let (region, bounds) = self.parse_ty_param_bounds(true);
1136 (region, Some(bounds))
1142 let (return_style, output) = self.parse_ret_ty();
1143 let decl = P(FnDecl {
1151 TyUnboxedFn(box(GC) UnboxedFnTy {
1155 TyClosure(box(GC) ClosureTy {
1160 lifetimes: lifetimes,
1165 pub fn parse_unsafety(&mut self) -> FnStyle {
1166 if self.eat_keyword(keywords::Unsafe) {
1173 /// Parse a function type (following the 'fn')
1174 pub fn parse_ty_fn_decl(&mut self, allow_variadic: bool)
1175 -> (P<FnDecl>, Vec<ast::Lifetime>) {
1186 let lifetimes = if self.eat(&token::LT) {
1187 let lifetimes = self.parse_lifetimes();
1194 let (inputs, variadic) = self.parse_fn_args(false, allow_variadic);
1195 let (ret_style, ret_ty) = self.parse_ret_ty();
1196 let decl = P(FnDecl {
1205 /// Parse the methods in a trait declaration
1206 pub fn parse_trait_methods(&mut self) -> Vec<TraitMethod> {
1207 self.parse_unspanned_seq(
1212 let attrs = p.parse_outer_attributes();
1215 // NB: at the moment, trait methods are public by default; this
1217 let vis = p.parse_visibility();
1218 let style = p.parse_fn_style();
1219 let ident = p.parse_ident();
1221 let generics = p.parse_generics();
1223 let (explicit_self, d) = p.parse_fn_decl_with_self(|p| {
1224 // This is somewhat dubious; We don't want to allow argument
1225 // names to be left off if there is a definition...
1226 p.parse_arg_general(false)
1229 let hi = p.last_span.hi;
1233 debug!("parse_trait_methods(): parsing required method");
1234 Required(TypeMethod {
1240 explicit_self: explicit_self,
1241 id: ast::DUMMY_NODE_ID,
1242 span: mk_sp(lo, hi),
1247 debug!("parse_trait_methods(): parsing provided method");
1248 let (inner_attrs, body) =
1249 p.parse_inner_attrs_and_block();
1250 let attrs = attrs.append(inner_attrs.as_slice());
1251 Provided(box(GC) ast::Method {
1253 id: ast::DUMMY_NODE_ID,
1254 span: mk_sp(lo, hi),
1255 node: ast::MethDecl(ident, generics, explicit_self, style, d, body, vis)
1260 let token_str = p.this_token_to_string();
1261 p.fatal((format!("expected `;` or `{{` but found `{}`",
1262 token_str)).as_slice())
1268 /// Parse a possibly mutable type
1269 pub fn parse_mt(&mut self) -> MutTy {
1270 let mutbl = self.parse_mutability();
1271 let t = self.parse_ty(true);
1272 MutTy { ty: t, mutbl: mutbl }
1275 /// Parse [mut/const/imm] ID : TY
1276 /// now used only by obsolete record syntax parser...
1277 pub fn parse_ty_field(&mut self) -> TypeField {
1278 let lo = self.span.lo;
1279 let mutbl = self.parse_mutability();
1280 let id = self.parse_ident();
1281 self.expect(&token::COLON);
1282 let ty = self.parse_ty(true);
1283 let hi = ty.span.hi;
1286 mt: MutTy { ty: ty, mutbl: mutbl },
1287 span: mk_sp(lo, hi),
1291 /// Parse optional return type [ -> TY ] in function decl
1292 pub fn parse_ret_ty(&mut self) -> (RetStyle, P<Ty>) {
1293 return if self.eat(&token::RARROW) {
1294 let lo = self.span.lo;
1295 if self.eat(&token::NOT) {
1299 id: ast::DUMMY_NODE_ID,
1301 span: mk_sp(lo, self.last_span.hi)
1305 (Return, self.parse_ty(true))
1308 let pos = self.span.lo;
1312 id: ast::DUMMY_NODE_ID,
1314 span: mk_sp(pos, pos),
1322 /// The second parameter specifies whether the `+` binary operator is
1323 /// allowed in the type grammar.
1324 pub fn parse_ty(&mut self, plus_allowed: bool) -> P<Ty> {
1325 maybe_whole!(no_clone self, NtTy);
1327 let lo = self.span.lo;
1329 let t = if self.token == token::LPAREN {
1331 if self.token == token::RPAREN {
1335 // (t) is a parenthesized ty
1336 // (t,) is the type of a tuple with only one field,
1338 let mut ts = vec!(self.parse_ty(true));
1339 let mut one_tuple = false;
1340 while self.token == token::COMMA {
1342 if self.token != token::RPAREN {
1343 ts.push(self.parse_ty(true));
1350 if ts.len() == 1 && !one_tuple {
1351 self.expect(&token::RPAREN);
1355 self.expect(&token::RPAREN);
1359 } else if self.token == token::AT {
1362 let span = self.last_span;
1363 self.obsolete(span, ObsoleteManagedType);
1364 TyBox(self.parse_ty(plus_allowed))
1365 } else if self.token == token::TILDE {
1368 let last_span = self.last_span;
1371 self.obsolete(last_span, ObsoleteOwnedVector),
1372 _ => self.obsolete(last_span, ObsoleteOwnedType),
1374 TyUniq(self.parse_ty(true))
1375 } else if self.token == token::BINOP(token::STAR) {
1376 // STAR POINTER (bare pointer?)
1378 TyPtr(self.parse_ptr())
1379 } else if self.token == token::LBRACKET {
1381 self.expect(&token::LBRACKET);
1382 let t = self.parse_ty(true);
1384 // Parse the `, ..e` in `[ int, ..e ]`
1385 // where `e` is a const expression
1386 let t = match self.maybe_parse_fixed_vstore() {
1388 Some(suffix) => TyFixedLengthVec(t, suffix)
1390 self.expect(&token::RBRACKET);
1392 } else if self.token == token::BINOP(token::AND) ||
1393 self.token == token::ANDAND {
1396 self.parse_borrowed_pointee()
1397 } else if self.is_keyword(keywords::Extern) ||
1398 self.is_keyword(keywords::Unsafe) ||
1399 self.token_is_bare_fn_keyword() {
1401 self.parse_ty_bare_fn()
1402 } else if self.token_is_closure_keyword() ||
1403 self.token == token::BINOP(token::OR) ||
1404 self.token == token::OROR ||
1405 self.token == token::LT {
1408 // FIXME(pcwalton): Eventually `token::LT` will not unambiguously
1409 // introduce a closure, once procs can have lifetime bounds. We
1410 // will need to refactor the grammar a little bit at that point.
1412 self.parse_ty_closure()
1413 } else if self.eat_keyword(keywords::Typeof) {
1415 // In order to not be ambiguous, the type must be surrounded by parens.
1416 self.expect(&token::LPAREN);
1417 let e = self.parse_expr();
1418 self.expect(&token::RPAREN);
1420 } else if self.eat_keyword(keywords::Proc) {
1421 self.parse_proc_type()
1422 } else if self.token == token::MOD_SEP
1423 || is_ident_or_path(&self.token) {
1425 let mode = if plus_allowed {
1426 LifetimeAndTypesAndBounds
1428 LifetimeAndTypesWithoutColons
1433 } = self.parse_path(mode);
1434 TyPath(path, bounds, ast::DUMMY_NODE_ID)
1435 } else if self.eat(&token::UNDERSCORE) {
1436 // TYPE TO BE INFERRED
1439 let msg = format!("expected type, found token {:?}", self.token);
1440 self.fatal(msg.as_slice());
1443 let sp = mk_sp(lo, self.last_span.hi);
1444 P(Ty {id: ast::DUMMY_NODE_ID, node: t, span: sp})
1447 pub fn parse_borrowed_pointee(&mut self) -> Ty_ {
1448 // look for `&'lt` or `&'foo ` and interpret `foo` as the region name:
1449 let opt_lifetime = self.parse_opt_lifetime();
1451 let mt = self.parse_mt();
1452 return TyRptr(opt_lifetime, mt);
1455 pub fn parse_ptr(&mut self) -> MutTy {
1456 let mutbl = if self.eat_keyword(keywords::Mut) {
1458 } else if self.eat_keyword(keywords::Const) {
1461 let span = self.last_span;
1463 "bare raw pointers are no longer allowed, you should \
1464 likely use `*mut T`, but otherwise `*T` is now \
1465 known as `*const T`");
1468 let t = self.parse_ty(true);
1469 MutTy { ty: t, mutbl: mutbl }
1472 pub fn is_named_argument(&mut self) -> bool {
1473 let offset = match self.token {
1474 token::BINOP(token::AND) => 1,
1476 _ if token::is_keyword(keywords::Mut, &self.token) => 1,
1480 debug!("parser is_named_argument offset:{}", offset);
1483 is_plain_ident_or_underscore(&self.token)
1484 && self.look_ahead(1, |t| *t == token::COLON)
1486 self.look_ahead(offset, |t| is_plain_ident_or_underscore(t))
1487 && self.look_ahead(offset + 1, |t| *t == token::COLON)
1491 /// This version of parse arg doesn't necessarily require
1492 /// identifier names.
1493 pub fn parse_arg_general(&mut self, require_name: bool) -> Arg {
1494 let pat = if require_name || self.is_named_argument() {
1495 debug!("parse_arg_general parse_pat (require_name:{:?})",
1497 let pat = self.parse_pat();
1499 self.expect(&token::COLON);
1502 debug!("parse_arg_general ident_to_pat");
1503 ast_util::ident_to_pat(ast::DUMMY_NODE_ID,
1505 special_idents::invalid)
1508 let t = self.parse_ty(true);
1513 id: ast::DUMMY_NODE_ID,
1517 /// Parse a single function argument
1518 pub fn parse_arg(&mut self) -> Arg {
1519 self.parse_arg_general(true)
1522 /// Parse an argument in a lambda header e.g. |arg, arg|
1523 pub fn parse_fn_block_arg(&mut self) -> Arg {
1524 let pat = self.parse_pat();
1525 let t = if self.eat(&token::COLON) {
1529 id: ast::DUMMY_NODE_ID,
1531 span: mk_sp(self.span.lo, self.span.hi),
1537 id: ast::DUMMY_NODE_ID
1541 pub fn maybe_parse_fixed_vstore(&mut self) -> Option<Gc<ast::Expr>> {
1542 if self.token == token::COMMA &&
1543 self.look_ahead(1, |t| *t == token::DOTDOT) {
1546 Some(self.parse_expr())
1552 /// Matches token_lit = LIT_INTEGER | ...
1553 pub fn lit_from_token(&mut self, tok: &token::Token) -> Lit_ {
1555 token::LIT_BYTE(i) => LitByte(parse::byte_lit(i.as_str()).val0()),
1556 token::LIT_CHAR(i) => LitChar(parse::char_lit(i.as_str()).val0()),
1557 token::LIT_INTEGER(s) => parse::integer_lit(s.as_str(),
1558 &self.sess.span_diagnostic, self.span),
1559 token::LIT_FLOAT(s) => parse::float_lit(s.as_str()),
1560 token::LIT_STR(s) => {
1561 LitStr(token::intern_and_get_ident(parse::str_lit(s.as_str()).as_slice()),
1564 token::LIT_STR_RAW(s, n) => {
1565 LitStr(token::intern_and_get_ident(parse::raw_str_lit(s.as_str()).as_slice()),
1568 token::LIT_BINARY(i) =>
1569 LitBinary(parse::binary_lit(i.as_str())),
1570 token::LIT_BINARY_RAW(i, _) =>
1571 LitBinary(Rc::new(i.as_str().as_bytes().iter().map(|&x| x).collect())),
1572 token::LPAREN => { self.expect(&token::RPAREN); LitNil },
1573 _ => { self.unexpected_last(tok); }
1577 /// Matches lit = true | false | token_lit
1578 pub fn parse_lit(&mut self) -> Lit {
1579 let lo = self.span.lo;
1580 let lit = if self.eat_keyword(keywords::True) {
1582 } else if self.eat_keyword(keywords::False) {
1585 let token = self.bump_and_get();
1586 let lit = self.lit_from_token(&token);
1589 codemap::Spanned { node: lit, span: mk_sp(lo, self.last_span.hi) }
1592 /// matches '-' lit | lit
1593 pub fn parse_literal_maybe_minus(&mut self) -> Gc<Expr> {
1594 let minus_lo = self.span.lo;
1595 let minus_present = self.eat(&token::BINOP(token::MINUS));
1597 let lo = self.span.lo;
1598 let literal = box(GC) self.parse_lit();
1599 let hi = self.span.hi;
1600 let expr = self.mk_expr(lo, hi, ExprLit(literal));
1603 let minus_hi = self.span.hi;
1604 let unary = self.mk_unary(UnNeg, expr);
1605 self.mk_expr(minus_lo, minus_hi, unary)
1611 /// Parses a path and optional type parameter bounds, depending on the
1612 /// mode. The `mode` parameter determines whether lifetimes, types, and/or
1613 /// bounds are permitted and whether `::` must precede type parameter
1615 pub fn parse_path(&mut self, mode: PathParsingMode) -> PathAndBounds {
1616 // Check for a whole path...
1617 let found = match self.token {
1618 INTERPOLATED(token::NtPath(_)) => Some(self.bump_and_get()),
1622 Some(INTERPOLATED(token::NtPath(box path))) => {
1623 return PathAndBounds {
1631 let lo = self.span.lo;
1632 let is_global = self.eat(&token::MOD_SEP);
1634 // Parse any number of segments and bound sets. A segment is an
1635 // identifier followed by an optional lifetime and a set of types.
1636 // A bound set is a set of type parameter bounds.
1637 let mut segments = Vec::new();
1639 // First, parse an identifier.
1640 let identifier = self.parse_ident();
1642 // Parse the '::' before type parameters if it's required. If
1643 // it is required and wasn't present, then we're done.
1644 if mode == LifetimeAndTypesWithColons &&
1645 !self.eat(&token::MOD_SEP) {
1646 segments.push(ast::PathSegment {
1647 identifier: identifier,
1648 lifetimes: Vec::new(),
1649 types: OwnedSlice::empty(),
1654 // Parse the `<` before the lifetime and types, if applicable.
1655 let (any_lifetime_or_types, lifetimes, types) = {
1656 if mode != NoTypesAllowed && self.eat_lt(false) {
1657 let (lifetimes, types) =
1658 self.parse_generic_values_after_lt();
1659 (true, lifetimes, OwnedSlice::from_vec(types))
1661 (false, Vec::new(), OwnedSlice::empty())
1665 // Assemble and push the result.
1666 segments.push(ast::PathSegment {
1667 identifier: identifier,
1668 lifetimes: lifetimes,
1672 // We're done if we don't see a '::', unless the mode required
1673 // a double colon to get here in the first place.
1674 if !(mode == LifetimeAndTypesWithColons &&
1675 !any_lifetime_or_types) {
1676 if !self.eat(&token::MOD_SEP) {
1682 // Next, parse a plus and bounded type parameters, if applicable.
1683 let bounds = if mode == LifetimeAndTypesAndBounds {
1685 if self.eat(&token::BINOP(token::PLUS)) {
1686 let (_, bounds) = self.parse_ty_param_bounds(false);
1687 if bounds.len() == 0 {
1688 let last_span = self.last_span;
1689 self.span_err(last_span,
1690 "at least one type parameter bound \
1691 must be specified after the `+`");
1703 // Assemble the span.
1704 let span = mk_sp(lo, self.last_span.hi);
1706 // Assemble the result.
1717 /// parses 0 or 1 lifetime
1718 pub fn parse_opt_lifetime(&mut self) -> Option<ast::Lifetime> {
1720 token::LIFETIME(..) => {
1721 Some(self.parse_lifetime())
1729 /// Parses a single lifetime
1730 /// Matches lifetime = LIFETIME
1731 pub fn parse_lifetime(&mut self) -> ast::Lifetime {
1733 token::LIFETIME(i) => {
1734 let span = self.span;
1736 return ast::Lifetime {
1737 id: ast::DUMMY_NODE_ID,
1743 self.fatal(format!("expected a lifetime name").as_slice());
1748 // matches lifetimes = ( lifetime ) | ( lifetime , lifetimes )
1749 // actually, it matches the empty one too, but putting that in there
1750 // messes up the grammar....
1751 pub fn parse_lifetimes(&mut self) -> Vec<ast::Lifetime> {
1754 * Parses zero or more comma separated lifetimes.
1755 * Expects each lifetime to be followed by either
1756 * a comma or `>`. Used when parsing type parameter
1757 * lists, where we expect something like `<'a, 'b, T>`.
1760 let mut res = Vec::new();
1763 token::LIFETIME(_) => {
1764 res.push(self.parse_lifetime());
1772 token::COMMA => { self.bump();}
1773 token::GT => { return res; }
1774 token::BINOP(token::SHR) => { return res; }
1776 let msg = format!("expected `,` or `>` after lifetime \
1779 self.fatal(msg.as_slice());
1785 pub fn token_is_mutability(tok: &token::Token) -> bool {
1786 token::is_keyword(keywords::Mut, tok) ||
1787 token::is_keyword(keywords::Const, tok)
1790 /// Parse mutability declaration (mut/const/imm)
1791 pub fn parse_mutability(&mut self) -> Mutability {
1792 if self.eat_keyword(keywords::Mut) {
1799 /// Parse ident COLON expr
1800 pub fn parse_field(&mut self) -> Field {
1801 let lo = self.span.lo;
1802 let i = self.parse_ident();
1803 let hi = self.last_span.hi;
1804 self.expect(&token::COLON);
1805 let e = self.parse_expr();
1807 ident: spanned(lo, hi, i),
1809 span: mk_sp(lo, e.span.hi),
1813 pub fn mk_expr(&mut self, lo: BytePos, hi: BytePos, node: Expr_) -> Gc<Expr> {
1815 id: ast::DUMMY_NODE_ID,
1817 span: mk_sp(lo, hi),
1821 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: Gc<Expr>) -> ast::Expr_ {
1822 ExprUnary(unop, expr)
1825 pub fn mk_binary(&mut self, binop: ast::BinOp,
1826 lhs: Gc<Expr>, rhs: Gc<Expr>) -> ast::Expr_ {
1827 ExprBinary(binop, lhs, rhs)
1830 pub fn mk_call(&mut self, f: Gc<Expr>, args: Vec<Gc<Expr>>) -> ast::Expr_ {
1834 fn mk_method_call(&mut self,
1835 ident: ast::SpannedIdent,
1837 args: Vec<Gc<Expr>>)
1839 ExprMethodCall(ident, tps, args)
1842 pub fn mk_index(&mut self, expr: Gc<Expr>, idx: Gc<Expr>) -> ast::Expr_ {
1843 ExprIndex(expr, idx)
1846 pub fn mk_field(&mut self, expr: Gc<Expr>, ident: ast::SpannedIdent,
1847 tys: Vec<P<Ty>>) -> ast::Expr_ {
1848 ExprField(expr, ident, tys)
1851 pub fn mk_assign_op(&mut self, binop: ast::BinOp,
1852 lhs: Gc<Expr>, rhs: Gc<Expr>) -> ast::Expr_ {
1853 ExprAssignOp(binop, lhs, rhs)
1856 pub fn mk_mac_expr(&mut self, lo: BytePos, hi: BytePos, m: Mac_) -> Gc<Expr> {
1858 id: ast::DUMMY_NODE_ID,
1859 node: ExprMac(codemap::Spanned {node: m, span: mk_sp(lo, hi)}),
1860 span: mk_sp(lo, hi),
1864 pub fn mk_lit_u32(&mut self, i: u32) -> Gc<Expr> {
1865 let span = &self.span;
1866 let lv_lit = box(GC) codemap::Spanned {
1867 node: LitUint(i as u64, TyU32),
1872 id: ast::DUMMY_NODE_ID,
1873 node: ExprLit(lv_lit),
1878 /// At the bottom (top?) of the precedence hierarchy,
1879 /// parse things like parenthesized exprs,
1880 /// macros, return, etc.
1881 pub fn parse_bottom_expr(&mut self) -> Gc<Expr> {
1882 maybe_whole_expr!(self);
1884 let lo = self.span.lo;
1885 let mut hi = self.span.hi;
1892 // (e) is parenthesized e
1893 // (e,) is a tuple with only one field, e
1894 let mut trailing_comma = false;
1895 if self.token == token::RPAREN {
1898 let lit = box(GC) spanned(lo, hi, LitNil);
1899 return self.mk_expr(lo, hi, ExprLit(lit));
1901 let mut es = vec!(self.parse_expr());
1902 self.commit_expr(*es.last().unwrap(), &[], &[token::COMMA, token::RPAREN]);
1903 while self.token == token::COMMA {
1905 if self.token != token::RPAREN {
1906 es.push(self.parse_expr());
1907 self.commit_expr(*es.last().unwrap(), &[], &[token::COMMA, token::RPAREN]);
1910 trailing_comma = true;
1914 self.commit_expr_expecting(*es.last().unwrap(), token::RPAREN);
1916 return if es.len() == 1 && !trailing_comma {
1917 self.mk_expr(lo, hi, ExprParen(*es.get(0)))
1920 self.mk_expr(lo, hi, ExprTup(es))
1925 let blk = self.parse_block_tail(lo, DefaultBlock);
1926 return self.mk_expr(blk.span.lo, blk.span.hi,
1929 token::BINOP(token::OR) | token::OROR => {
1930 return self.parse_lambda_expr();
1932 _ if self.eat_keyword(keywords::Proc) => {
1933 let decl = self.parse_proc_decl();
1934 let body = self.parse_expr();
1935 let fakeblock = P(ast::Block {
1936 view_items: Vec::new(),
1939 id: ast::DUMMY_NODE_ID,
1940 rules: DefaultBlock,
1943 return self.mk_expr(lo, body.span.hi, ExprProc(decl, fakeblock));
1945 // FIXME #13626: Should be able to stick in
1946 // token::SELF_KEYWORD_NAME
1947 token::IDENT(id @ ast::Ident{
1948 name: ast::Name(token::SELF_KEYWORD_NAME_NUM),
1952 let path = ast_util::ident_to_path(mk_sp(lo, hi), id);
1953 ex = ExprPath(path);
1954 hi = self.last_span.hi;
1956 _ if self.eat_keyword(keywords::If) => {
1957 return self.parse_if_expr();
1959 _ if self.eat_keyword(keywords::For) => {
1960 return self.parse_for_expr(None);
1962 _ if self.eat_keyword(keywords::While) => {
1963 return self.parse_while_expr();
1965 _ if Parser::token_is_lifetime(&self.token) => {
1966 let lifetime = self.get_lifetime();
1968 self.expect(&token::COLON);
1969 if self.eat_keyword(keywords::For) {
1970 return self.parse_for_expr(Some(lifetime))
1971 } else if self.eat_keyword(keywords::Loop) {
1972 return self.parse_loop_expr(Some(lifetime))
1974 self.fatal("expected `for` or `loop` after a label")
1977 _ if self.eat_keyword(keywords::Loop) => {
1978 return self.parse_loop_expr(None);
1980 _ if self.eat_keyword(keywords::Continue) => {
1981 let lo = self.span.lo;
1982 let ex = if Parser::token_is_lifetime(&self.token) {
1983 let lifetime = self.get_lifetime();
1985 ExprAgain(Some(lifetime))
1989 let hi = self.span.hi;
1990 return self.mk_expr(lo, hi, ex);
1992 _ if self.eat_keyword(keywords::Match) => {
1993 return self.parse_match_expr();
1995 _ if self.eat_keyword(keywords::Unsafe) => {
1996 return self.parse_block_expr(lo, UnsafeBlock(ast::UserProvided));
1998 token::LBRACKET => {
2001 if self.token == token::RBRACKET {
2004 ex = ExprVec(Vec::new());
2007 let first_expr = self.parse_expr();
2008 if self.token == token::COMMA &&
2009 self.look_ahead(1, |t| *t == token::DOTDOT) {
2010 // Repeating vector syntax: [ 0, ..512 ]
2013 let count = self.parse_expr();
2014 self.expect(&token::RBRACKET);
2015 ex = ExprRepeat(first_expr, count);
2016 } else if self.token == token::COMMA {
2017 // Vector with two or more elements.
2019 let remaining_exprs = self.parse_seq_to_end(
2021 seq_sep_trailing_allowed(token::COMMA),
2024 let mut exprs = vec!(first_expr);
2025 exprs.push_all_move(remaining_exprs);
2026 ex = ExprVec(exprs);
2028 // Vector with one element.
2029 self.expect(&token::RBRACKET);
2030 ex = ExprVec(vec!(first_expr));
2033 hi = self.last_span.hi;
2035 _ if self.eat_keyword(keywords::Return) => {
2036 // RETURN expression
2037 if can_begin_expr(&self.token) {
2038 let e = self.parse_expr();
2040 ex = ExprRet(Some(e));
2041 } else { ex = ExprRet(None); }
2043 _ if self.eat_keyword(keywords::Break) => {
2045 if Parser::token_is_lifetime(&self.token) {
2046 let lifetime = self.get_lifetime();
2048 ex = ExprBreak(Some(lifetime));
2050 ex = ExprBreak(None);
2054 _ if self.token == token::MOD_SEP ||
2055 is_ident(&self.token) && !self.is_keyword(keywords::True) &&
2056 !self.is_keyword(keywords::False) => {
2057 let pth = self.parse_path(LifetimeAndTypesWithColons).path;
2059 // `!`, as an operator, is prefix, so we know this isn't that
2060 if self.token == token::NOT {
2061 // MACRO INVOCATION expression
2064 let ket = token::close_delimiter_for(&self.token)
2065 .unwrap_or_else(|| self.fatal("expected open delimiter"));
2068 let tts = self.parse_seq_to_end(&ket,
2070 |p| p.parse_token_tree());
2071 let hi = self.span.hi;
2073 return self.mk_mac_expr(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT));
2074 } else if self.token == token::LBRACE {
2075 // This is a struct literal, unless we're prohibited from
2076 // parsing struct literals here.
2077 if self.restriction != RESTRICT_NO_STRUCT_LITERAL {
2078 // It's a struct literal.
2080 let mut fields = Vec::new();
2081 let mut base = None;
2083 while self.token != token::RBRACE {
2084 if self.eat(&token::DOTDOT) {
2085 base = Some(self.parse_expr());
2089 fields.push(self.parse_field());
2090 self.commit_expr(fields.last().unwrap().expr,
2091 &[token::COMMA], &[token::RBRACE]);
2094 if fields.len() == 0 && base.is_none() {
2095 let last_span = self.last_span;
2096 self.span_err(last_span,
2097 "structure literal must either have at \
2098 least one field or use functional \
2099 structure update syntax");
2103 self.expect(&token::RBRACE);
2104 ex = ExprStruct(pth, fields, base);
2105 return self.mk_expr(lo, hi, ex);
2113 // other literal expression
2114 let lit = self.parse_lit();
2116 ex = ExprLit(box(GC) lit);
2120 return self.mk_expr(lo, hi, ex);
2123 /// Parse a block or unsafe block
2124 pub fn parse_block_expr(&mut self, lo: BytePos, blk_mode: BlockCheckMode)
2126 self.expect(&token::LBRACE);
2127 let blk = self.parse_block_tail(lo, blk_mode);
2128 return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk));
2131 /// parse a.b or a(13) or a[4] or just a
2132 pub fn parse_dot_or_call_expr(&mut self) -> Gc<Expr> {
2133 let b = self.parse_bottom_expr();
2134 self.parse_dot_or_call_expr_with(b)
2137 pub fn parse_dot_or_call_expr_with(&mut self, e0: Gc<Expr>) -> Gc<Expr> {
2143 if self.eat(&token::DOT) {
2145 token::IDENT(i, _) => {
2146 let dot = self.last_span.hi;
2149 let (_, tys) = if self.eat(&token::MOD_SEP) {
2151 self.parse_generic_values_after_lt()
2153 (Vec::new(), Vec::new())
2156 // expr.f() method call
2159 let mut es = self.parse_unspanned_seq(
2162 seq_sep_trailing_disallowed(token::COMMA),
2165 hi = self.last_span.hi;
2168 let id = spanned(dot, hi, i);
2169 let nd = self.mk_method_call(id, tys, es);
2170 e = self.mk_expr(lo, hi, nd);
2173 let id = spanned(dot, hi, i);
2174 let field = self.mk_field(e, id, tys);
2175 e = self.mk_expr(lo, hi, field)
2179 _ => self.unexpected()
2183 if self.expr_is_complete(e) { break; }
2187 let es = self.parse_unspanned_seq(
2190 seq_sep_trailing_allowed(token::COMMA),
2193 hi = self.last_span.hi;
2195 let nd = self.mk_call(e, es);
2196 e = self.mk_expr(lo, hi, nd);
2200 token::LBRACKET => {
2202 let ix = self.parse_expr();
2204 self.commit_expr_expecting(ix, token::RBRACKET);
2205 let index = self.mk_index(e, ix);
2206 e = self.mk_expr(lo, hi, index)
2215 /// Parse an optional separator followed by a kleene-style
2216 /// repetition token (+ or *).
2217 pub fn parse_sep_and_zerok(&mut self) -> (Option<token::Token>, bool) {
2218 fn parse_zerok(parser: &mut Parser) -> Option<bool> {
2219 match parser.token {
2220 token::BINOP(token::STAR) | token::BINOP(token::PLUS) => {
2221 let zerok = parser.token == token::BINOP(token::STAR);
2229 match parse_zerok(self) {
2230 Some(zerok) => return (None, zerok),
2234 let separator = self.bump_and_get();
2235 match parse_zerok(self) {
2236 Some(zerok) => (Some(separator), zerok),
2237 None => self.fatal("expected `*` or `+`")
2241 /// parse a single token tree from the input.
2242 pub fn parse_token_tree(&mut self) -> TokenTree {
2243 // FIXME #6994: currently, this is too eager. It
2244 // parses token trees but also identifies TTSeq's
2245 // and TTNonterminal's; it's too early to know yet
2246 // whether something will be a nonterminal or a seq
2248 maybe_whole!(deref self, NtTT);
2250 // this is the fall-through for the 'match' below.
2251 // invariants: the current token is not a left-delimiter,
2252 // not an EOF, and not the desired right-delimiter (if
2253 // it were, parse_seq_to_before_end would have prevented
2254 // reaching this point.
2255 fn parse_non_delim_tt_tok(p: &mut Parser) -> TokenTree {
2256 maybe_whole!(deref p, NtTT);
2258 token::RPAREN | token::RBRACE | token::RBRACKET => {
2259 // This is a conservative error: only report the last unclosed delimiter. The
2260 // previous unclosed delimiters could actually be closed! The parser just hasn't
2261 // gotten to them yet.
2262 match p.open_braces.last() {
2264 Some(&sp) => p.span_note(sp, "unclosed delimiter"),
2266 let token_str = p.this_token_to_string();
2267 p.fatal(format!("incorrect close delimiter: `{}`",
2268 token_str).as_slice())
2270 /* we ought to allow different depths of unquotation */
2271 token::DOLLAR if p.quote_depth > 0u => {
2275 if p.token == token::LPAREN {
2276 let seq = p.parse_seq(
2280 |p| p.parse_token_tree()
2282 let (s, z) = p.parse_sep_and_zerok();
2283 let seq = match seq {
2284 Spanned { node, .. } => node,
2286 TTSeq(mk_sp(sp.lo, p.span.hi), Rc::new(seq), s, z)
2288 TTNonterminal(sp, p.parse_ident())
2297 // turn the next token into a TTTok:
2298 fn parse_any_tt_tok(p: &mut Parser) -> TokenTree {
2299 TTTok(p.span, p.bump_and_get())
2302 match (&self.token, token::close_delimiter_for(&self.token)) {
2303 (&token::EOF, _) => {
2304 let open_braces = self.open_braces.clone();
2305 for sp in open_braces.iter() {
2306 self.span_note(*sp, "Did you mean to close this delimiter?");
2308 // There shouldn't really be a span, but it's easier for the test runner
2309 // if we give it one
2310 self.fatal("this file contains an un-closed delimiter ");
2312 (_, Some(close_delim)) => {
2313 // Parse the open delimiter.
2314 self.open_braces.push(self.span);
2315 let mut result = vec!(parse_any_tt_tok(self));
2318 self.parse_seq_to_before_end(&close_delim,
2320 |p| p.parse_token_tree());
2321 result.push_all_move(trees);
2323 // Parse the close delimiter.
2324 result.push(parse_any_tt_tok(self));
2325 self.open_braces.pop().unwrap();
2327 TTDelim(Rc::new(result))
2329 _ => parse_non_delim_tt_tok(self)
2333 // parse a stream of tokens into a list of TokenTree's,
2335 pub fn parse_all_token_trees(&mut self) -> Vec<TokenTree> {
2336 let mut tts = Vec::new();
2337 while self.token != token::EOF {
2338 tts.push(self.parse_token_tree());
2343 pub fn parse_matchers(&mut self) -> Vec<Matcher> {
2344 // unification of Matcher's and TokenTree's would vastly improve
2345 // the interpolation of Matcher's
2346 maybe_whole!(self, NtMatchers);
2347 let mut name_idx = 0u;
2348 match token::close_delimiter_for(&self.token) {
2349 Some(other_delimiter) => {
2351 self.parse_matcher_subseq_upto(&mut name_idx, &other_delimiter)
2353 None => self.fatal("expected open delimiter")
2357 /// This goofy function is necessary to correctly match parens in Matcher's.
2358 /// Otherwise, `$( ( )` would be a valid Matcher, and `$( () )` would be
2359 /// invalid. It's similar to common::parse_seq.
2360 pub fn parse_matcher_subseq_upto(&mut self,
2361 name_idx: &mut uint,
2364 let mut ret_val = Vec::new();
2365 let mut lparens = 0u;
2367 while self.token != *ket || lparens > 0u {
2368 if self.token == token::LPAREN { lparens += 1u; }
2369 if self.token == token::RPAREN { lparens -= 1u; }
2370 ret_val.push(self.parse_matcher(name_idx));
2378 pub fn parse_matcher(&mut self, name_idx: &mut uint) -> Matcher {
2379 let lo = self.span.lo;
2381 let m = if self.token == token::DOLLAR {
2383 if self.token == token::LPAREN {
2384 let name_idx_lo = *name_idx;
2386 let ms = self.parse_matcher_subseq_upto(name_idx,
2389 self.fatal("repetition body must be nonempty");
2391 let (sep, zerok) = self.parse_sep_and_zerok();
2392 MatchSeq(ms, sep, zerok, name_idx_lo, *name_idx)
2394 let bound_to = self.parse_ident();
2395 self.expect(&token::COLON);
2396 let nt_name = self.parse_ident();
2397 let m = MatchNonterminal(bound_to, nt_name, *name_idx);
2402 MatchTok(self.bump_and_get())
2405 return spanned(lo, self.span.hi, m);
2408 /// Parse a prefix-operator expr
2409 pub fn parse_prefix_expr(&mut self) -> Gc<Expr> {
2410 let lo = self.span.lo;
2417 let e = self.parse_prefix_expr();
2419 ex = self.mk_unary(UnNot, e);
2421 token::BINOP(token::MINUS) => {
2423 let e = self.parse_prefix_expr();
2425 ex = self.mk_unary(UnNeg, e);
2427 token::BINOP(token::STAR) => {
2429 let e = self.parse_prefix_expr();
2431 ex = self.mk_unary(UnDeref, e);
2433 token::BINOP(token::AND) | token::ANDAND => {
2435 let m = self.parse_mutability();
2436 let e = self.parse_prefix_expr();
2438 // HACK: turn &[...] into a &-vec
2440 ExprVec(..) if m == MutImmutable => {
2441 ExprVstore(e, ExprVstoreSlice)
2443 ExprVec(..) if m == MutMutable => {
2444 ExprVstore(e, ExprVstoreMutSlice)
2446 _ => ExprAddrOf(m, e)
2451 let span = self.last_span;
2452 self.obsolete(span, ObsoleteManagedExpr);
2453 let e = self.parse_prefix_expr();
2455 ex = self.mk_unary(UnBox, e);
2460 let e = self.parse_prefix_expr();
2462 // HACK: turn ~[...] into a ~-vec
2463 let last_span = self.last_span;
2465 ExprVec(..) | ExprRepeat(..) => {
2466 self.obsolete(last_span, ObsoleteOwnedVector);
2467 ExprVstore(e, ExprVstoreUniq)
2469 ExprLit(lit) if lit_is_str(lit) => {
2470 self.obsolete(last_span, ObsoleteOwnedExpr);
2471 ExprVstore(e, ExprVstoreUniq)
2474 self.obsolete(last_span, ObsoleteOwnedExpr);
2475 self.mk_unary(UnUniq, e)
2479 token::IDENT(_, _) if self.is_keyword(keywords::Box) => {
2482 // Check for a place: `box(PLACE) EXPR`.
2483 if self.eat(&token::LPAREN) {
2484 // Support `box() EXPR` as the default.
2485 if !self.eat(&token::RPAREN) {
2486 let place = self.parse_expr();
2487 self.expect(&token::RPAREN);
2488 let subexpression = self.parse_prefix_expr();
2489 hi = subexpression.span.hi;
2490 ex = ExprBox(place, subexpression);
2491 return self.mk_expr(lo, hi, ex);
2495 // Otherwise, we use the unique pointer default.
2496 let subexpression = self.parse_prefix_expr();
2497 hi = subexpression.span.hi;
2498 // HACK: turn `box [...]` into a boxed-vec
2499 ex = match subexpression.node {
2500 ExprVec(..) | ExprRepeat(..) => {
2501 let last_span = self.last_span;
2502 self.obsolete(last_span, ObsoleteOwnedVector);
2503 ExprVstore(subexpression, ExprVstoreUniq)
2505 ExprLit(lit) if lit_is_str(lit) => {
2506 ExprVstore(subexpression, ExprVstoreUniq)
2508 _ => self.mk_unary(UnUniq, subexpression)
2511 _ => return self.parse_dot_or_call_expr()
2513 return self.mk_expr(lo, hi, ex);
2516 /// Parse an expression of binops
2517 pub fn parse_binops(&mut self) -> Gc<Expr> {
2518 let prefix_expr = self.parse_prefix_expr();
2519 self.parse_more_binops(prefix_expr, 0)
2522 /// Parse an expression of binops of at least min_prec precedence
2523 pub fn parse_more_binops(&mut self, lhs: Gc<Expr>,
2524 min_prec: uint) -> Gc<Expr> {
2525 if self.expr_is_complete(lhs) { return lhs; }
2527 // Prevent dynamic borrow errors later on by limiting the
2528 // scope of the borrows.
2530 let token: &token::Token = &self.token;
2531 let restriction: &restriction = &self.restriction;
2532 match (token, restriction) {
2533 (&token::BINOP(token::OR), &RESTRICT_NO_BAR_OP) => return lhs,
2534 (&token::BINOP(token::OR),
2535 &RESTRICT_NO_BAR_OR_DOUBLEBAR_OP) => return lhs,
2536 (&token::OROR, &RESTRICT_NO_BAR_OR_DOUBLEBAR_OP) => return lhs,
2541 let cur_opt = token_to_binop(&self.token);
2544 let cur_prec = operator_prec(cur_op);
2545 if cur_prec > min_prec {
2547 let expr = self.parse_prefix_expr();
2548 let rhs = self.parse_more_binops(expr, cur_prec);
2549 let binary = self.mk_binary(cur_op, lhs, rhs);
2550 let bin = self.mk_expr(lhs.span.lo, rhs.span.hi, binary);
2551 self.parse_more_binops(bin, min_prec)
2557 if as_prec > min_prec && self.eat_keyword(keywords::As) {
2558 let rhs = self.parse_ty(false);
2559 let _as = self.mk_expr(lhs.span.lo,
2561 ExprCast(lhs, rhs));
2562 self.parse_more_binops(_as, min_prec)
2570 /// Parse an assignment expression....
2571 /// actually, this seems to be the main entry point for
2572 /// parsing an arbitrary expression.
2573 pub fn parse_assign_expr(&mut self) -> Gc<Expr> {
2574 let lo = self.span.lo;
2575 let lhs = self.parse_binops();
2579 let rhs = self.parse_expr();
2580 self.mk_expr(lo, rhs.span.hi, ExprAssign(lhs, rhs))
2582 token::BINOPEQ(op) => {
2584 let rhs = self.parse_expr();
2585 let aop = match op {
2586 token::PLUS => BiAdd,
2587 token::MINUS => BiSub,
2588 token::STAR => BiMul,
2589 token::SLASH => BiDiv,
2590 token::PERCENT => BiRem,
2591 token::CARET => BiBitXor,
2592 token::AND => BiBitAnd,
2593 token::OR => BiBitOr,
2594 token::SHL => BiShl,
2597 let assign_op = self.mk_assign_op(aop, lhs, rhs);
2598 self.mk_expr(lo, rhs.span.hi, assign_op)
2606 /// Parse an 'if' expression ('if' token already eaten)
2607 pub fn parse_if_expr(&mut self) -> Gc<Expr> {
2608 let lo = self.last_span.lo;
2609 let cond = self.parse_expr_res(RESTRICT_NO_STRUCT_LITERAL);
2610 let thn = self.parse_block();
2611 let mut els: Option<Gc<Expr>> = None;
2612 let mut hi = thn.span.hi;
2613 if self.eat_keyword(keywords::Else) {
2614 let elexpr = self.parse_else_expr();
2616 hi = elexpr.span.hi;
2618 self.mk_expr(lo, hi, ExprIf(cond, thn, els))
2621 /// `|args| { ... }` or `{ ...}` like in `do` expressions
2622 pub fn parse_lambda_block_expr(&mut self) -> Gc<Expr> {
2623 self.parse_lambda_expr_(
2626 token::BINOP(token::OR) | token::OROR => {
2627 p.parse_fn_block_decl()
2630 // No argument list - `do foo {`
2634 id: ast::DUMMY_NODE_ID,
2645 let blk = p.parse_block();
2646 p.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk))
2651 pub fn parse_lambda_expr(&mut self) -> Gc<Expr> {
2652 self.parse_lambda_expr_(|p| p.parse_fn_block_decl(),
2656 /// parse something of the form |args| expr
2657 /// this is used both in parsing a lambda expr
2658 /// and in parsing a block expr as e.g. in for...
2659 pub fn parse_lambda_expr_(&mut self,
2660 parse_decl: |&mut Parser| -> P<FnDecl>,
2661 parse_body: |&mut Parser| -> Gc<Expr>)
2663 let lo = self.span.lo;
2664 let decl = parse_decl(self);
2665 let body = parse_body(self);
2666 let fakeblock = P(ast::Block {
2667 view_items: Vec::new(),
2670 id: ast::DUMMY_NODE_ID,
2671 rules: DefaultBlock,
2675 return self.mk_expr(lo, body.span.hi, ExprFnBlock(decl, fakeblock));
2678 pub fn parse_else_expr(&mut self) -> Gc<Expr> {
2679 if self.eat_keyword(keywords::If) {
2680 return self.parse_if_expr();
2682 let blk = self.parse_block();
2683 return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk));
2687 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
2688 pub fn parse_for_expr(&mut self, opt_ident: Option<ast::Ident>) -> Gc<Expr> {
2689 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
2691 let lo = self.last_span.lo;
2692 let pat = self.parse_pat();
2693 self.expect_keyword(keywords::In);
2694 let expr = self.parse_expr_res(RESTRICT_NO_STRUCT_LITERAL);
2695 let loop_block = self.parse_block();
2696 let hi = self.span.hi;
2698 self.mk_expr(lo, hi, ExprForLoop(pat, expr, loop_block, opt_ident))
2701 pub fn parse_while_expr(&mut self) -> Gc<Expr> {
2702 let lo = self.last_span.lo;
2703 let cond = self.parse_expr_res(RESTRICT_NO_STRUCT_LITERAL);
2704 let body = self.parse_block();
2705 let hi = body.span.hi;
2706 return self.mk_expr(lo, hi, ExprWhile(cond, body));
2709 pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::Ident>) -> Gc<Expr> {
2710 let lo = self.last_span.lo;
2711 let body = self.parse_block();
2712 let hi = body.span.hi;
2713 self.mk_expr(lo, hi, ExprLoop(body, opt_ident))
2716 fn parse_match_expr(&mut self) -> Gc<Expr> {
2717 let lo = self.last_span.lo;
2718 let discriminant = self.parse_expr_res(RESTRICT_NO_STRUCT_LITERAL);
2719 self.commit_expr_expecting(discriminant, token::LBRACE);
2720 let mut arms: Vec<Arm> = Vec::new();
2721 while self.token != token::RBRACE {
2722 let attrs = self.parse_outer_attributes();
2723 let pats = self.parse_pats();
2724 let mut guard = None;
2725 if self.eat_keyword(keywords::If) {
2726 guard = Some(self.parse_expr());
2728 self.expect(&token::FAT_ARROW);
2729 let expr = self.parse_expr_res(RESTRICT_STMT_EXPR);
2732 !classify::expr_is_simple_block(expr)
2733 && self.token != token::RBRACE;
2736 self.commit_expr(expr, &[token::COMMA], &[token::RBRACE]);
2738 self.eat(&token::COMMA);
2741 arms.push(ast::Arm {
2748 let hi = self.span.hi;
2750 return self.mk_expr(lo, hi, ExprMatch(discriminant, arms));
2753 /// Parse an expression
2754 pub fn parse_expr(&mut self) -> Gc<Expr> {
2755 return self.parse_expr_res(UNRESTRICTED);
2758 /// Parse an expression, subject to the given restriction
2759 pub fn parse_expr_res(&mut self, r: restriction) -> Gc<Expr> {
2760 let old = self.restriction;
2761 self.restriction = r;
2762 let e = self.parse_assign_expr();
2763 self.restriction = old;
2767 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
2768 fn parse_initializer(&mut self) -> Option<Gc<Expr>> {
2769 if self.token == token::EQ {
2771 Some(self.parse_expr())
2777 /// Parse patterns, separated by '|' s
2778 fn parse_pats(&mut self) -> Vec<Gc<Pat>> {
2779 let mut pats = Vec::new();
2781 pats.push(self.parse_pat());
2782 if self.token == token::BINOP(token::OR) { self.bump(); }
2783 else { return pats; }
2787 fn parse_pat_vec_elements(
2789 ) -> (Vec<Gc<Pat>> , Option<Gc<Pat>>, Vec<Gc<Pat>> ) {
2790 let mut before = Vec::new();
2791 let mut slice = None;
2792 let mut after = Vec::new();
2793 let mut first = true;
2794 let mut before_slice = true;
2796 while self.token != token::RBRACKET {
2797 if first { first = false; }
2798 else { self.expect(&token::COMMA); }
2800 let mut is_slice = false;
2802 if self.token == token::DOTDOT {
2805 before_slice = false;
2810 if self.token == token::COMMA || self.token == token::RBRACKET {
2811 slice = Some(box(GC) ast::Pat {
2812 id: ast::DUMMY_NODE_ID,
2817 let subpat = self.parse_pat();
2819 ast::Pat { node: PatIdent(_, _, _), .. } => {
2820 slice = Some(subpat);
2822 ast::Pat { span, .. } => self.span_fatal(
2823 span, "expected an identifier or nothing"
2828 let subpat = self.parse_pat();
2830 before.push(subpat);
2837 (before, slice, after)
2840 /// Parse the fields of a struct-like pattern
2841 fn parse_pat_fields(&mut self) -> (Vec<ast::FieldPat> , bool) {
2842 let mut fields = Vec::new();
2843 let mut etc = false;
2844 let mut first = true;
2845 while self.token != token::RBRACE {
2849 self.expect(&token::COMMA);
2850 // accept trailing commas
2851 if self.token == token::RBRACE { break }
2854 if self.token == token::DOTDOT {
2856 if self.token != token::RBRACE {
2857 let token_str = self.this_token_to_string();
2858 self.fatal(format!("expected `{}`, found `{}`", "}",
2859 token_str).as_slice())
2865 let bind_type = if self.eat_keyword(keywords::Mut) {
2866 BindByValue(MutMutable)
2867 } else if self.eat_keyword(keywords::Ref) {
2868 BindByRef(self.parse_mutability())
2870 BindByValue(MutImmutable)
2873 let fieldname = self.parse_ident();
2875 let subpat = if self.token == token::COLON {
2877 BindByRef(..) | BindByValue(MutMutable) => {
2878 let token_str = self.this_token_to_string();
2879 self.fatal(format!("unexpected `{}`",
2880 token_str).as_slice())
2888 let fieldpath = codemap::Spanned{span:self.last_span, node: fieldname};
2890 id: ast::DUMMY_NODE_ID,
2891 node: PatIdent(bind_type, fieldpath, None),
2892 span: self.last_span
2895 fields.push(ast::FieldPat { ident: fieldname, pat: subpat });
2897 return (fields, etc);
2900 /// Parse a pattern.
2901 pub fn parse_pat(&mut self) -> Gc<Pat> {
2902 maybe_whole!(self, NtPat);
2904 let lo = self.span.lo;
2909 token::UNDERSCORE => {
2912 hi = self.last_span.hi;
2913 return box(GC) ast::Pat {
2914 id: ast::DUMMY_NODE_ID,
2922 let sub = self.parse_pat();
2924 let last_span = self.last_span;
2926 self.obsolete(last_span, ObsoleteOwnedPattern);
2927 return box(GC) ast::Pat {
2928 id: ast::DUMMY_NODE_ID,
2933 token::BINOP(token::AND) | token::ANDAND => {
2935 let lo = self.span.lo;
2937 let sub = self.parse_pat();
2938 pat = PatRegion(sub);
2939 hi = self.last_span.hi;
2940 return box(GC) ast::Pat {
2941 id: ast::DUMMY_NODE_ID,
2947 // parse (pat,pat,pat,...) as tuple
2949 if self.token == token::RPAREN {
2952 let lit = box(GC) codemap::Spanned {
2954 span: mk_sp(lo, hi)};
2955 let expr = self.mk_expr(lo, hi, ExprLit(lit));
2958 let mut fields = vec!(self.parse_pat());
2959 if self.look_ahead(1, |t| *t != token::RPAREN) {
2960 while self.token == token::COMMA {
2962 if self.token == token::RPAREN { break; }
2963 fields.push(self.parse_pat());
2966 if fields.len() == 1 { self.expect(&token::COMMA); }
2967 self.expect(&token::RPAREN);
2968 pat = PatTup(fields);
2970 hi = self.last_span.hi;
2971 return box(GC) ast::Pat {
2972 id: ast::DUMMY_NODE_ID,
2977 token::LBRACKET => {
2978 // parse [pat,pat,...] as vector pattern
2980 let (before, slice, after) =
2981 self.parse_pat_vec_elements();
2983 self.expect(&token::RBRACKET);
2984 pat = ast::PatVec(before, slice, after);
2985 hi = self.last_span.hi;
2986 return box(GC) ast::Pat {
2987 id: ast::DUMMY_NODE_ID,
2994 // at this point, token != _, ~, &, &&, (, [
2996 if (!is_ident_or_path(&self.token) && self.token != token::MOD_SEP)
2997 || self.is_keyword(keywords::True)
2998 || self.is_keyword(keywords::False) {
2999 // Parse an expression pattern or exp .. exp.
3001 // These expressions are limited to literals (possibly
3002 // preceded by unary-minus) or identifiers.
3003 let val = self.parse_literal_maybe_minus();
3004 if self.eat(&token::DOTDOT) {
3005 let end = if is_ident_or_path(&self.token) {
3006 let path = self.parse_path(LifetimeAndTypesWithColons)
3008 let hi = self.span.hi;
3009 self.mk_expr(lo, hi, ExprPath(path))
3011 self.parse_literal_maybe_minus()
3013 pat = PatRange(val, end);
3017 } else if self.eat_keyword(keywords::Mut) {
3018 pat = self.parse_pat_ident(BindByValue(MutMutable));
3019 } else if self.eat_keyword(keywords::Ref) {
3021 let mutbl = self.parse_mutability();
3022 pat = self.parse_pat_ident(BindByRef(mutbl));
3023 } else if self.eat_keyword(keywords::Box) {
3026 // FIXME(#13910): Rename to `PatBox` and extend to full DST
3028 let sub = self.parse_pat();
3030 hi = self.last_span.hi;
3031 return box(GC) ast::Pat {
3032 id: ast::DUMMY_NODE_ID,
3037 let can_be_enum_or_struct = self.look_ahead(1, |t| {
3039 token::LPAREN | token::LBRACKET | token::LT |
3040 token::LBRACE | token::MOD_SEP => true,
3045 if self.look_ahead(1, |t| *t == token::DOTDOT) {
3046 let start = self.parse_expr_res(RESTRICT_NO_BAR_OP);
3047 self.eat(&token::DOTDOT);
3048 let end = self.parse_expr_res(RESTRICT_NO_BAR_OP);
3049 pat = PatRange(start, end);
3050 } else if is_plain_ident(&self.token) && !can_be_enum_or_struct {
3051 let id = self.parse_ident();
3052 let id_span = self.last_span;
3053 let pth1 = codemap::Spanned{span:id_span, node: id};
3054 if self.eat(&token::NOT) {
3056 let ket = token::close_delimiter_for(&self.token)
3057 .unwrap_or_else(|| self.fatal("expected open delimiter"));
3060 let tts = self.parse_seq_to_end(&ket,
3062 |p| p.parse_token_tree());
3064 let mac = MacInvocTT(ident_to_path(id_span,id), tts, EMPTY_CTXT);
3065 pat = ast::PatMac(codemap::Spanned {node: mac, span: self.span});
3067 let sub = if self.eat(&token::AT) {
3069 Some(self.parse_pat())
3074 pat = PatIdent(BindByValue(MutImmutable), pth1, sub);
3077 // parse an enum pat
3078 let enum_path = self.parse_path(LifetimeAndTypesWithColons)
3084 self.parse_pat_fields();
3086 pat = PatStruct(enum_path, fields, etc);
3089 let mut args: Vec<Gc<Pat>> = Vec::new();
3092 let is_dotdot = self.look_ahead(1, |t| {
3094 token::DOTDOT => true,
3099 // This is a "top constructor only" pat
3102 self.expect(&token::RPAREN);
3103 pat = PatEnum(enum_path, None);
3105 args = self.parse_enum_variant_seq(
3108 seq_sep_trailing_disallowed(token::COMMA),
3111 pat = PatEnum(enum_path, Some(args));
3115 if enum_path.segments.len() == 1 {
3116 // it could still be either an enum
3117 // or an identifier pattern, resolve
3118 // will sort it out:
3119 pat = PatIdent(BindByValue(MutImmutable),
3121 span: enum_path.span,
3122 node: enum_path.segments.get(0)
3126 pat = PatEnum(enum_path, Some(args));
3134 hi = self.last_span.hi;
3136 id: ast::DUMMY_NODE_ID,
3138 span: mk_sp(lo, hi),
3142 /// Parse ident or ident @ pat
3143 /// used by the copy foo and ref foo patterns to give a good
3144 /// error message when parsing mistakes like ref foo(a,b)
3145 fn parse_pat_ident(&mut self,
3146 binding_mode: ast::BindingMode)
3148 if !is_plain_ident(&self.token) {
3149 let last_span = self.last_span;
3150 self.span_fatal(last_span,
3151 "expected identifier, found path");
3153 let ident = self.parse_ident();
3154 let last_span = self.last_span;
3155 let name = codemap::Spanned{span: last_span, node: ident};
3156 let sub = if self.eat(&token::AT) {
3157 Some(self.parse_pat())
3162 // just to be friendly, if they write something like
3164 // we end up here with ( as the current token. This shortly
3165 // leads to a parse error. Note that if there is no explicit
3166 // binding mode then we do not end up here, because the lookahead
3167 // will direct us over to parse_enum_variant()
3168 if self.token == token::LPAREN {
3169 let last_span = self.last_span;
3172 "expected identifier, found enum pattern");
3175 PatIdent(binding_mode, name, sub)
3178 /// Parse a local variable declaration
3179 fn parse_local(&mut self) -> Gc<Local> {
3180 let lo = self.span.lo;
3181 let pat = self.parse_pat();
3184 id: ast::DUMMY_NODE_ID,
3186 span: mk_sp(lo, lo),
3188 if self.eat(&token::COLON) {
3189 ty = self.parse_ty(true);
3191 let init = self.parse_initializer();
3192 box(GC) ast::Local {
3196 id: ast::DUMMY_NODE_ID,
3197 span: mk_sp(lo, self.last_span.hi),
3202 /// Parse a "let" stmt
3203 fn parse_let(&mut self) -> Gc<Decl> {
3204 let lo = self.span.lo;
3205 let local = self.parse_local();
3206 box(GC) spanned(lo, self.last_span.hi, DeclLocal(local))
3209 /// Parse a structure field
3210 fn parse_name_and_ty(&mut self, pr: Visibility,
3211 attrs: Vec<Attribute> ) -> StructField {
3212 let lo = self.span.lo;
3213 if !is_plain_ident(&self.token) {
3214 self.fatal("expected ident");
3216 let name = self.parse_ident();
3217 self.expect(&token::COLON);
3218 let ty = self.parse_ty(true);
3219 spanned(lo, self.last_span.hi, ast::StructField_ {
3220 kind: NamedField(name, pr),
3221 id: ast::DUMMY_NODE_ID,
3227 /// Parse a statement. may include decl.
3228 /// Precondition: any attributes are parsed already
3229 pub fn parse_stmt(&mut self, item_attrs: Vec<Attribute>) -> Gc<Stmt> {
3230 maybe_whole!(self, NtStmt);
3232 fn check_expected_item(p: &mut Parser, found_attrs: bool) {
3233 // If we have attributes then we should have an item
3235 let last_span = p.last_span;
3236 p.span_err(last_span, "expected item after attributes");
3240 let lo = self.span.lo;
3241 if self.is_keyword(keywords::Let) {
3242 check_expected_item(self, !item_attrs.is_empty());
3243 self.expect_keyword(keywords::Let);
3244 let decl = self.parse_let();
3245 return box(GC) spanned(lo, decl.span.hi, StmtDecl(decl, ast::DUMMY_NODE_ID));
3246 } else if is_ident(&self.token)
3247 && !token::is_any_keyword(&self.token)
3248 && self.look_ahead(1, |t| *t == token::NOT) {
3249 // it's a macro invocation:
3251 check_expected_item(self, !item_attrs.is_empty());
3253 // Potential trouble: if we allow macros with paths instead of
3254 // idents, we'd need to look ahead past the whole path here...
3255 let pth = self.parse_path(NoTypesAllowed).path;
3258 let id = if token::close_delimiter_for(&self.token).is_some() {
3259 token::special_idents::invalid // no special identifier
3264 // check that we're pointing at delimiters (need to check
3265 // again after the `if`, because of `parse_ident`
3266 // consuming more tokens).
3267 let (bra, ket) = match token::close_delimiter_for(&self.token) {
3268 Some(ket) => (self.token.clone(), ket),
3270 // we only expect an ident if we didn't parse one
3272 let ident_str = if id.name == token::special_idents::invalid.name {
3277 let tok_str = self.this_token_to_string();
3278 self.fatal(format!("expected {}`(` or `{{`, but found `{}`",
3280 tok_str).as_slice())
3284 let tts = self.parse_unspanned_seq(
3288 |p| p.parse_token_tree()
3290 let hi = self.span.hi;
3292 if id.name == token::special_idents::invalid.name {
3293 return box(GC) spanned(lo, hi, StmtMac(
3294 spanned(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT)), false));
3296 // if it has a special ident, it's definitely an item
3297 return box(GC) spanned(lo, hi, StmtDecl(
3298 box(GC) spanned(lo, hi, DeclItem(
3300 lo, hi, id /*id is good here*/,
3301 ItemMac(spanned(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT))),
3302 Inherited, Vec::new(/*no attrs*/)))),
3303 ast::DUMMY_NODE_ID));
3307 let found_attrs = !item_attrs.is_empty();
3308 match self.parse_item_or_view_item(item_attrs, false) {
3311 let decl = box(GC) spanned(lo, hi, DeclItem(i));
3312 return box(GC) spanned(lo, hi, StmtDecl(decl, ast::DUMMY_NODE_ID));
3314 IoviViewItem(vi) => {
3315 self.span_fatal(vi.span,
3316 "view items must be declared at the top of the block");
3318 IoviForeignItem(_) => {
3319 self.fatal("foreign items are not allowed here");
3321 IoviNone(_) => { /* fallthrough */ }
3324 check_expected_item(self, found_attrs);
3326 // Remainder are line-expr stmts.
3327 let e = self.parse_expr_res(RESTRICT_STMT_EXPR);
3328 return box(GC) spanned(lo, e.span.hi, StmtExpr(e, ast::DUMMY_NODE_ID));
3332 /// Is this expression a successfully-parsed statement?
3333 fn expr_is_complete(&mut self, e: Gc<Expr>) -> bool {
3334 return self.restriction == RESTRICT_STMT_EXPR &&
3335 !classify::expr_requires_semi_to_be_stmt(e);
3338 /// Parse a block. No inner attrs are allowed.
3339 pub fn parse_block(&mut self) -> P<Block> {
3340 maybe_whole!(no_clone self, NtBlock);
3342 let lo = self.span.lo;
3343 self.expect(&token::LBRACE);
3345 return self.parse_block_tail_(lo, DefaultBlock, Vec::new());
3348 /// Parse a block. Inner attrs are allowed.
3349 fn parse_inner_attrs_and_block(&mut self)
3350 -> (Vec<Attribute> , P<Block>) {
3352 maybe_whole!(pair_empty self, NtBlock);
3354 let lo = self.span.lo;
3355 self.expect(&token::LBRACE);
3356 let (inner, next) = self.parse_inner_attrs_and_next();
3358 (inner, self.parse_block_tail_(lo, DefaultBlock, next))
3361 /// Precondition: already parsed the '{' or '#{'
3362 /// I guess that also means "already parsed the 'impure'" if
3363 /// necessary, and this should take a qualifier.
3364 /// Some blocks start with "#{"...
3365 fn parse_block_tail(&mut self, lo: BytePos, s: BlockCheckMode) -> P<Block> {
3366 self.parse_block_tail_(lo, s, Vec::new())
3369 /// Parse the rest of a block expression or function body
3370 fn parse_block_tail_(&mut self, lo: BytePos, s: BlockCheckMode,
3371 first_item_attrs: Vec<Attribute> ) -> P<Block> {
3372 let mut stmts = Vec::new();
3373 let mut expr = None;
3375 // wouldn't it be more uniform to parse view items only, here?
3376 let ParsedItemsAndViewItems {
3377 attrs_remaining: attrs_remaining,
3378 view_items: view_items,
3381 } = self.parse_items_and_view_items(first_item_attrs,
3384 for item in items.iter() {
3385 let decl = box(GC) spanned(item.span.lo, item.span.hi, DeclItem(*item));
3386 stmts.push(box(GC) spanned(item.span.lo, item.span.hi,
3387 StmtDecl(decl, ast::DUMMY_NODE_ID)));
3390 let mut attributes_box = attrs_remaining;
3392 while self.token != token::RBRACE {
3393 // parsing items even when they're not allowed lets us give
3394 // better error messages and recover more gracefully.
3395 attributes_box.push_all(self.parse_outer_attributes().as_slice());
3398 if !attributes_box.is_empty() {
3399 let last_span = self.last_span;
3400 self.span_err(last_span, "expected item after attributes");
3401 attributes_box = Vec::new();
3403 self.bump(); // empty
3406 // fall through and out.
3409 let stmt = self.parse_stmt(attributes_box);
3410 attributes_box = Vec::new();
3412 StmtExpr(e, stmt_id) => {
3413 // expression without semicolon
3414 if classify::stmt_ends_with_semi(&*stmt) {
3415 // Just check for errors and recover; do not eat semicolon yet.
3416 self.commit_stmt(stmt, &[], &[token::SEMI, token::RBRACE]);
3422 let span_with_semi = Span {
3424 hi: self.last_span.hi,
3425 expn_info: stmt.span.expn_info,
3427 stmts.push(box(GC) codemap::Spanned {
3428 node: StmtSemi(e, stmt_id),
3429 span: span_with_semi,
3440 StmtMac(ref m, _) => {
3441 // statement macro; might be an expr
3445 stmts.push(box(GC) codemap::Spanned {
3446 node: StmtMac((*m).clone(), true),
3451 // if a block ends in `m!(arg)` without
3452 // a `;`, it must be an expr
3454 self.mk_mac_expr(stmt.span.lo,
3463 _ => { // all other kinds of statements:
3464 stmts.push(stmt.clone());
3466 if classify::stmt_ends_with_semi(&*stmt) {
3467 self.commit_stmt_expecting(stmt, token::SEMI);
3475 if !attributes_box.is_empty() {
3476 let last_span = self.last_span;
3477 self.span_err(last_span, "expected item after attributes");
3480 let hi = self.span.hi;
3483 view_items: view_items,
3486 id: ast::DUMMY_NODE_ID,
3488 span: mk_sp(lo, hi),
3492 fn parse_unboxed_function_type(&mut self) -> UnboxedFnTy {
3493 let inputs = if self.eat(&token::OROR) {
3498 if self.token == token::BINOP(token::AND) &&
3499 self.look_ahead(1, |t| {
3500 token::is_keyword(keywords::Mut, t)
3502 self.look_ahead(2, |t| *t == token::COLON) {
3508 let inputs = self.parse_seq_to_before_or(&token::COMMA,
3510 p.parse_arg_general(false)
3516 let (return_style, output) = self.parse_ret_ty();
3527 /// matches optbounds = ( ( : ( boundseq )? )? )
3528 /// where boundseq = ( bound + boundseq ) | bound
3529 /// and bound = 'static | ty
3530 /// Returns "None" if there's no colon (e.g. "T");
3531 /// Returns "Some(Empty)" if there's a colon but nothing after (e.g. "T:")
3532 /// Returns "Some(stuff)" otherwise (e.g. "T:stuff").
3533 /// NB: The None/Some distinction is important for issue #7264.
3535 /// Note that the `allow_any_lifetime` argument is a hack for now while the
3536 /// AST doesn't support arbitrary lifetimes in bounds on type parameters. In
3537 /// the future, this flag should be removed, and the return value of this
3538 /// function should be Option<~[TyParamBound]>
3539 fn parse_ty_param_bounds(&mut self, allow_any_lifetime: bool)
3540 -> (Option<ast::Lifetime>,
3541 OwnedSlice<TyParamBound>) {
3542 let mut ret_lifetime = None;
3543 let mut result = vec!();
3546 token::LIFETIME(lifetime) => {
3547 let lifetime_interned_string = token::get_ident(lifetime);
3548 if lifetime_interned_string.equiv(&("'static")) {
3549 result.push(StaticRegionTyParamBound);
3550 if allow_any_lifetime && ret_lifetime.is_none() {
3551 ret_lifetime = Some(ast::Lifetime {
3552 id: ast::DUMMY_NODE_ID,
3557 } else if allow_any_lifetime && ret_lifetime.is_none() {
3558 ret_lifetime = Some(ast::Lifetime {
3559 id: ast::DUMMY_NODE_ID,
3564 result.push(OtherRegionTyParamBound(self.span));
3568 token::MOD_SEP | token::IDENT(..) => {
3569 let tref = self.parse_trait_ref();
3570 result.push(TraitTyParamBound(tref));
3572 token::BINOP(token::OR) | token::OROR => {
3573 let unboxed_function_type =
3574 self.parse_unboxed_function_type();
3575 result.push(UnboxedFnTyParamBound(unboxed_function_type));
3580 if !self.eat(&token::BINOP(token::PLUS)) {
3585 return (ret_lifetime, OwnedSlice::from_vec(result));
3588 fn trait_ref_from_ident(ident: Ident, span: Span) -> ast::TraitRef {
3589 let segment = ast::PathSegment {
3591 lifetimes: Vec::new(),
3592 types: OwnedSlice::empty(),
3594 let path = ast::Path {
3597 segments: vec![segment],
3601 ref_id: ast::DUMMY_NODE_ID,
3605 /// Matches typaram = (unbound`?`)? IDENT optbounds ( EQ ty )?
3606 fn parse_ty_param(&mut self) -> TyParam {
3607 // This is a bit hacky. Currently we are only interested in a single
3608 // unbound, and it may only be `Sized`. To avoid backtracking and other
3609 // complications, we parse an ident, then check for `?`. If we find it,
3610 // we use the ident as the unbound, otherwise, we use it as the name of
3612 let mut span = self.span;
3613 let mut ident = self.parse_ident();
3614 let mut unbound = None;
3615 if self.eat(&token::QUESTION) {
3616 let tref = Parser::trait_ref_from_ident(ident, span);
3617 unbound = Some(TraitTyParamBound(tref));
3619 ident = self.parse_ident();
3623 if self.eat(&token::COLON) {
3624 let (_, bounds) = self.parse_ty_param_bounds(false);
3630 // For typarams we don't care about the difference b/w "<T>" and "<T:>".
3631 let bounds = opt_bounds.unwrap_or_default();
3633 let default = if self.token == token::EQ {
3635 Some(self.parse_ty(true))
3641 id: ast::DUMMY_NODE_ID,
3649 /// Parse a set of optional generic type parameter declarations
3650 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
3651 /// | ( < lifetimes , typaramseq ( , )? > )
3652 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
3653 pub fn parse_generics(&mut self) -> ast::Generics {
3654 if self.eat(&token::LT) {
3655 let lifetimes = self.parse_lifetimes();
3656 let mut seen_default = false;
3657 let ty_params = self.parse_seq_to_gt(Some(token::COMMA), |p| {
3658 p.forbid_lifetime();
3659 let ty_param = p.parse_ty_param();
3660 if ty_param.default.is_some() {
3661 seen_default = true;
3662 } else if seen_default {
3663 let last_span = p.last_span;
3664 p.span_err(last_span,
3665 "type parameters with a default must be trailing");
3669 ast::Generics { lifetimes: lifetimes, ty_params: ty_params }
3671 ast_util::empty_generics()
3675 fn parse_generic_values_after_lt(&mut self) -> (Vec<ast::Lifetime>, Vec<P<Ty>> ) {
3676 let lifetimes = self.parse_lifetimes();
3677 let result = self.parse_seq_to_gt(
3680 p.forbid_lifetime();
3684 (lifetimes, result.into_vec())
3687 fn forbid_lifetime(&mut self) {
3688 if Parser::token_is_lifetime(&self.token) {
3689 let span = self.span;
3690 self.span_fatal(span, "lifetime parameters must be declared \
3691 prior to type parameters");
3695 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
3696 -> (Vec<Arg> , bool) {
3698 let mut args: Vec<Option<Arg>> =
3699 self.parse_unspanned_seq(
3702 seq_sep_trailing_allowed(token::COMMA),
3704 if p.token == token::DOTDOTDOT {
3707 if p.token != token::RPAREN {
3710 "`...` must be last in argument list for variadic function");
3715 "only foreign functions are allowed to be variadic");
3719 Some(p.parse_arg_general(named_args))
3724 let variadic = match args.pop() {
3727 // Need to put back that last arg
3734 if variadic && args.is_empty() {
3736 "variadic function must be declared with at least one named argument");
3739 let args = args.move_iter().map(|x| x.unwrap()).collect();
3744 /// Parse the argument list and result type of a function declaration
3745 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> P<FnDecl> {
3747 let (args, variadic) = self.parse_fn_args(true, allow_variadic);
3748 let (ret_style, ret_ty) = self.parse_ret_ty();
3758 fn is_self_ident(&mut self) -> bool {
3760 token::IDENT(id, false) => id.name == special_idents::self_.name,
3765 fn expect_self_ident(&mut self) -> ast::Ident {
3767 token::IDENT(id, false) if id.name == special_idents::self_.name => {
3772 let token_str = self.this_token_to_string();
3773 self.fatal(format!("expected `self` but found `{}`",
3774 token_str).as_slice())
3779 /// Parse the argument list and result type of a function
3780 /// that may have a self type.
3781 fn parse_fn_decl_with_self(&mut self, parse_arg_fn: |&mut Parser| -> Arg)
3782 -> (ExplicitSelf, P<FnDecl>) {
3783 fn maybe_parse_borrowed_explicit_self(this: &mut Parser)
3784 -> ast::ExplicitSelf_ {
3785 // The following things are possible to see here:
3790 // fn(&'lt mut self)
3792 // We already know that the current token is `&`.
3794 if this.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) {
3796 SelfRegion(None, MutImmutable, this.expect_self_ident())
3797 } else if this.look_ahead(1, |t| Parser::token_is_mutability(t)) &&
3799 |t| token::is_keyword(keywords::Self,
3802 let mutability = this.parse_mutability();
3803 SelfRegion(None, mutability, this.expect_self_ident())
3804 } else if this.look_ahead(1, |t| Parser::token_is_lifetime(t)) &&
3806 |t| token::is_keyword(keywords::Self,
3809 let lifetime = this.parse_lifetime();
3810 SelfRegion(Some(lifetime), MutImmutable, this.expect_self_ident())
3811 } else if this.look_ahead(1, |t| Parser::token_is_lifetime(t)) &&
3812 this.look_ahead(2, |t| {
3813 Parser::token_is_mutability(t)
3815 this.look_ahead(3, |t| token::is_keyword(keywords::Self,
3818 let lifetime = this.parse_lifetime();
3819 let mutability = this.parse_mutability();
3820 SelfRegion(Some(lifetime), mutability, this.expect_self_ident())
3826 self.expect(&token::LPAREN);
3828 // A bit of complexity and lookahead is needed here in order to be
3829 // backwards compatible.
3830 let lo = self.span.lo;
3831 let mut mutbl_self = MutImmutable;
3832 let explicit_self = match self.token {
3833 token::BINOP(token::AND) => {
3834 maybe_parse_borrowed_explicit_self(self)
3837 // We need to make sure it isn't a type
3838 if self.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) {
3840 SelfUniq(self.expect_self_ident())
3845 token::IDENT(..) if self.is_self_ident() => {
3846 SelfValue(self.expect_self_ident())
3848 token::BINOP(token::STAR) => {
3849 // Possibly "*self" or "*mut self" -- not supported. Try to avoid
3850 // emitting cryptic "unexpected token" errors.
3852 let _mutability = if Parser::token_is_mutability(&self.token) {
3853 self.parse_mutability()
3854 } else { MutImmutable };
3855 if self.is_self_ident() {
3856 let span = self.span;
3857 self.span_err(span, "cannot pass self by unsafe pointer");
3860 // error case, making bogus self ident:
3861 SelfValue(special_idents::self_)
3863 _ if Parser::token_is_mutability(&self.token) &&
3864 self.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) => {
3865 mutbl_self = self.parse_mutability();
3866 SelfValue(self.expect_self_ident())
3868 _ if Parser::token_is_mutability(&self.token) &&
3869 self.look_ahead(1, |t| *t == token::TILDE) &&
3870 self.look_ahead(2, |t| token::is_keyword(keywords::Self, t)) => {
3871 mutbl_self = self.parse_mutability();
3873 SelfUniq(self.expect_self_ident())
3878 let explicit_self_sp = mk_sp(lo, self.span.hi);
3880 // shared fall-through for the three cases below. borrowing prevents simply
3881 // writing this as a closure
3882 macro_rules! parse_remaining_arguments {
3885 // If we parsed a self type, expect a comma before the argument list.
3889 let sep = seq_sep_trailing_disallowed(token::COMMA);
3890 let mut fn_inputs = self.parse_seq_to_before_end(
3895 fn_inputs.unshift(Arg::new_self(explicit_self_sp, mutbl_self, $self_id));
3899 vec!(Arg::new_self(explicit_self_sp, mutbl_self, $self_id))
3902 let token_str = self.this_token_to_string();
3903 self.fatal(format!("expected `,` or `)`, found `{}`",
3904 token_str).as_slice())
3910 let fn_inputs = match explicit_self {
3912 let sep = seq_sep_trailing_disallowed(token::COMMA);
3913 self.parse_seq_to_before_end(&token::RPAREN, sep, parse_arg_fn)
3915 SelfValue(id) => parse_remaining_arguments!(id),
3916 SelfRegion(_,_,id) => parse_remaining_arguments!(id),
3917 SelfUniq(id) => parse_remaining_arguments!(id)
3922 self.expect(&token::RPAREN);
3924 let hi = self.span.hi;
3926 let (ret_style, ret_ty) = self.parse_ret_ty();
3928 let fn_decl = P(FnDecl {
3935 (spanned(lo, hi, explicit_self), fn_decl)
3938 /// Parse the |arg, arg| header on a lambda
3939 fn parse_fn_block_decl(&mut self) -> P<FnDecl> {
3940 let inputs_captures = {
3941 if self.eat(&token::OROR) {
3944 self.parse_unspanned_seq(
3945 &token::BINOP(token::OR),
3946 &token::BINOP(token::OR),
3947 seq_sep_trailing_disallowed(token::COMMA),
3948 |p| p.parse_fn_block_arg()
3952 let output = if self.eat(&token::RARROW) {
3956 id: ast::DUMMY_NODE_ID,
3963 inputs: inputs_captures,
3970 /// Parses the `(arg, arg) -> return_type` header on a procedure.
3971 fn parse_proc_decl(&mut self) -> P<FnDecl> {
3973 self.parse_unspanned_seq(&token::LPAREN,
3975 seq_sep_trailing_allowed(token::COMMA),
3976 |p| p.parse_fn_block_arg());
3978 let output = if self.eat(&token::RARROW) {
3982 id: ast::DUMMY_NODE_ID,
3996 /// Parse the name and optional generic types of a function header.
3997 fn parse_fn_header(&mut self) -> (Ident, ast::Generics) {
3998 let id = self.parse_ident();
3999 let generics = self.parse_generics();
4003 fn mk_item(&mut self, lo: BytePos, hi: BytePos, ident: Ident,
4004 node: Item_, vis: Visibility,
4005 attrs: Vec<Attribute>) -> Gc<Item> {
4009 id: ast::DUMMY_NODE_ID,
4016 /// Parse an item-position function declaration.
4017 fn parse_item_fn(&mut self, fn_style: FnStyle, abi: abi::Abi) -> ItemInfo {
4018 let (ident, generics) = self.parse_fn_header();
4019 let decl = self.parse_fn_decl(false);
4020 let (inner_attrs, body) = self.parse_inner_attrs_and_block();
4021 (ident, ItemFn(decl, fn_style, abi, generics, body), Some(inner_attrs))
4024 /// Parse a method in a trait impl, starting with `attrs` attributes.
4025 pub fn parse_method(&mut self,
4026 already_parsed_attrs: Option<Vec<Attribute>>) -> Gc<Method> {
4027 let next_attrs = self.parse_outer_attributes();
4028 let attrs = match already_parsed_attrs {
4029 Some(mut a) => { a.push_all_move(next_attrs); a }
4033 let lo = self.span.lo;
4035 // code copied from parse_macro_use_or_failure... abstraction!
4036 let (method_, hi, new_attrs) = {
4037 if !token::is_any_keyword(&self.token)
4038 && self.look_ahead(1, |t| *t == token::NOT)
4039 && (self.look_ahead(2, |t| *t == token::LPAREN)
4040 || self.look_ahead(2, |t| *t == token::LBRACE)) {
4042 let pth = self.parse_path(NoTypesAllowed).path;
4043 self.expect(&token::NOT);
4045 // eat a matched-delimiter token tree:
4046 let tts = match token::close_delimiter_for(&self.token) {
4049 self.parse_seq_to_end(&ket,
4051 |p| p.parse_token_tree())
4053 None => self.fatal("expected open delimiter")
4055 let m_ = ast::MacInvocTT(pth, tts, EMPTY_CTXT);
4056 let m: ast::Mac = codemap::Spanned { node: m_,
4057 span: mk_sp(self.span.lo,
4059 (ast::MethMac(m), self.span.hi, attrs)
4061 let visa = self.parse_visibility();
4062 let fn_style = self.parse_fn_style();
4063 let ident = self.parse_ident();
4064 let generics = self.parse_generics();
4065 let (explicit_self, decl) = self.parse_fn_decl_with_self(|p| {
4068 let (inner_attrs, body) = self.parse_inner_attrs_and_block();
4069 let new_attrs = attrs.append(inner_attrs.as_slice());
4070 (ast::MethDecl(ident, generics, explicit_self, fn_style, decl, body, visa),
4071 body.span.hi, new_attrs)
4074 box(GC) ast::Method {
4076 id: ast::DUMMY_NODE_ID,
4077 span: mk_sp(lo, hi),
4082 /// Parse trait Foo { ... }
4083 fn parse_item_trait(&mut self) -> ItemInfo {
4084 let ident = self.parse_ident();
4085 let tps = self.parse_generics();
4086 let sized = self.parse_for_sized();
4088 // Parse traits, if necessary.
4090 if self.token == token::COLON {
4092 traits = self.parse_trait_ref_list(&token::LBRACE);
4094 traits = Vec::new();
4097 let meths = self.parse_trait_methods();
4098 (ident, ItemTrait(tps, sized, traits, meths), None)
4101 /// Parses two variants (with the region/type params always optional):
4102 /// impl<T> Foo { ... }
4103 /// impl<T> ToString for ~[T] { ... }
4104 fn parse_item_impl(&mut self) -> ItemInfo {
4105 // First, parse type parameters if necessary.
4106 let generics = self.parse_generics();
4108 // Special case: if the next identifier that follows is '(', don't
4109 // allow this to be parsed as a trait.
4110 let could_be_trait = self.token != token::LPAREN;
4113 let mut ty = self.parse_ty(true);
4115 // Parse traits, if necessary.
4116 let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) {
4117 // New-style trait. Reinterpret the type as a trait.
4118 let opt_trait_ref = match ty.node {
4119 TyPath(ref path, None, node_id) => {
4121 path: /* bad */ (*path).clone(),
4126 self.span_err(ty.span,
4127 "bounded traits are only valid in type position");
4131 self.span_err(ty.span, "not a trait");
4136 ty = self.parse_ty(true);
4142 let mut meths = Vec::new();
4143 self.expect(&token::LBRACE);
4144 let (inner_attrs, next) = self.parse_inner_attrs_and_next();
4145 let mut method_attrs = Some(next);
4146 while !self.eat(&token::RBRACE) {
4147 meths.push(self.parse_method(method_attrs));
4148 method_attrs = None;
4151 let ident = ast_util::impl_pretty_name(&opt_trait, &*ty);
4153 (ident, ItemImpl(generics, opt_trait, ty, meths), Some(inner_attrs))
4156 /// Parse a::B<String,int>
4157 fn parse_trait_ref(&mut self) -> TraitRef {
4159 path: self.parse_path(LifetimeAndTypesWithoutColons).path,
4160 ref_id: ast::DUMMY_NODE_ID,
4164 /// Parse B + C<String,int> + D
4165 fn parse_trait_ref_list(&mut self, ket: &token::Token) -> Vec<TraitRef> {
4166 self.parse_seq_to_before_end(
4168 seq_sep_trailing_disallowed(token::BINOP(token::PLUS)),
4169 |p| p.parse_trait_ref()
4173 /// Parse struct Foo { ... }
4174 fn parse_item_struct(&mut self, is_virtual: bool) -> ItemInfo {
4175 let class_name = self.parse_ident();
4176 let generics = self.parse_generics();
4178 let super_struct = if self.eat(&token::COLON) {
4179 let ty = self.parse_ty(true);
4181 TyPath(_, None, _) => {
4185 self.span_err(ty.span, "not a struct");
4193 let mut fields: Vec<StructField>;
4196 if self.eat(&token::LBRACE) {
4197 // It's a record-like struct.
4198 is_tuple_like = false;
4199 fields = Vec::new();
4200 while self.token != token::RBRACE {
4201 fields.push(self.parse_struct_decl_field());
4203 if fields.len() == 0 {
4204 self.fatal(format!("unit-like struct definition should be \
4205 written as `struct {};`",
4206 token::get_ident(class_name)).as_slice());
4209 } else if self.token == token::LPAREN {
4210 // It's a tuple-like struct.
4211 is_tuple_like = true;
4212 fields = self.parse_unspanned_seq(
4215 seq_sep_trailing_allowed(token::COMMA),
4217 let attrs = p.parse_outer_attributes();
4219 let struct_field_ = ast::StructField_ {
4220 kind: UnnamedField(p.parse_visibility()),
4221 id: ast::DUMMY_NODE_ID,
4222 ty: p.parse_ty(true),
4225 spanned(lo, p.span.hi, struct_field_)
4227 if fields.len() == 0 {
4228 self.fatal(format!("unit-like struct definition should be \
4229 written as `struct {};`",
4230 token::get_ident(class_name)).as_slice());
4232 self.expect(&token::SEMI);
4233 } else if self.eat(&token::SEMI) {
4234 // It's a unit-like struct.
4235 is_tuple_like = true;
4236 fields = Vec::new();
4238 let token_str = self.this_token_to_string();
4239 self.fatal(format!("expected `{}`, `(`, or `;` after struct \
4240 name but found `{}`", "{",
4241 token_str).as_slice())
4244 let _ = ast::DUMMY_NODE_ID; // FIXME: Workaround for crazy bug.
4245 let new_id = ast::DUMMY_NODE_ID;
4247 ItemStruct(box(GC) ast::StructDef {
4249 ctor_id: if is_tuple_like { Some(new_id) } else { None },
4250 super_struct: super_struct,
4251 is_virtual: is_virtual,
4256 /// Parse a structure field declaration
4257 pub fn parse_single_struct_field(&mut self,
4259 attrs: Vec<Attribute> )
4261 let a_var = self.parse_name_and_ty(vis, attrs);
4268 let span = self.span;
4269 let token_str = self.this_token_to_string();
4270 self.span_fatal(span,
4271 format!("expected `,`, or `}}` but found `{}`",
4272 token_str).as_slice())
4278 /// Parse an element of a struct definition
4279 fn parse_struct_decl_field(&mut self) -> StructField {
4281 let attrs = self.parse_outer_attributes();
4283 if self.eat_keyword(keywords::Pub) {
4284 return self.parse_single_struct_field(Public, attrs);
4287 return self.parse_single_struct_field(Inherited, attrs);
4290 /// Parse visiility: PUB, PRIV, or nothing
4291 fn parse_visibility(&mut self) -> Visibility {
4292 if self.eat_keyword(keywords::Pub) { Public }
4296 fn parse_for_sized(&mut self) -> Option<ast::TyParamBound> {
4297 if self.eat_keyword(keywords::For) {
4298 let span = self.span;
4299 let ident = self.parse_ident();
4300 if !self.eat(&token::QUESTION) {
4302 "expected 'Sized?' after `for` in trait item");
4305 let tref = Parser::trait_ref_from_ident(ident, span);
4306 Some(TraitTyParamBound(tref))
4312 /// Given a termination token and a vector of already-parsed
4313 /// attributes (of length 0 or 1), parse all of the items in a module
4314 fn parse_mod_items(&mut self,
4316 first_item_attrs: Vec<Attribute>,
4319 // parse all of the items up to closing or an attribute.
4320 // view items are legal here.
4321 let ParsedItemsAndViewItems {
4322 attrs_remaining: attrs_remaining,
4323 view_items: view_items,
4324 items: starting_items,
4326 } = self.parse_items_and_view_items(first_item_attrs, true, true);
4327 let mut items: Vec<Gc<Item>> = starting_items;
4328 let attrs_remaining_len = attrs_remaining.len();
4330 // don't think this other loop is even necessary....
4332 let mut first = true;
4333 while self.token != term {
4334 let mut attrs = self.parse_outer_attributes();
4336 attrs = attrs_remaining.clone().append(attrs.as_slice());
4339 debug!("parse_mod_items: parse_item_or_view_item(attrs={:?})",
4341 match self.parse_item_or_view_item(attrs,
4342 true /* macros allowed */) {
4343 IoviItem(item) => items.push(item),
4344 IoviViewItem(view_item) => {
4345 self.span_fatal(view_item.span,
4346 "view items must be declared at the top of \
4350 let token_str = self.this_token_to_string();
4351 self.fatal(format!("expected item but found `{}`",
4352 token_str).as_slice())
4357 if first && attrs_remaining_len > 0u {
4358 // We parsed attributes for the first item but didn't find it
4359 let last_span = self.last_span;
4360 self.span_err(last_span, "expected item after attributes");
4364 inner: mk_sp(inner_lo, self.span.lo),
4365 view_items: view_items,
4370 fn parse_item_const(&mut self) -> ItemInfo {
4371 let m = if self.eat_keyword(keywords::Mut) {MutMutable} else {MutImmutable};
4372 let id = self.parse_ident();
4373 self.expect(&token::COLON);
4374 let ty = self.parse_ty(true);
4375 self.expect(&token::EQ);
4376 let e = self.parse_expr();
4377 self.commit_expr_expecting(e, token::SEMI);
4378 (id, ItemStatic(ty, m, e), None)
4381 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
4382 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> ItemInfo {
4383 let id_span = self.span;
4384 let id = self.parse_ident();
4385 if self.token == token::SEMI {
4387 // This mod is in an external file. Let's go get it!
4388 let (m, attrs) = self.eval_src_mod(id, outer_attrs, id_span);
4389 (id, m, Some(attrs))
4391 self.push_mod_path(id, outer_attrs);
4392 self.expect(&token::LBRACE);
4393 let mod_inner_lo = self.span.lo;
4394 let old_owns_directory = self.owns_directory;
4395 self.owns_directory = true;
4396 let (inner, next) = self.parse_inner_attrs_and_next();
4397 let m = self.parse_mod_items(token::RBRACE, next, mod_inner_lo);
4398 self.expect(&token::RBRACE);
4399 self.owns_directory = old_owns_directory;
4400 self.pop_mod_path();
4401 (id, ItemMod(m), Some(inner))
4405 fn push_mod_path(&mut self, id: Ident, attrs: &[Attribute]) {
4406 let default_path = self.id_to_interned_str(id);
4407 let file_path = match ::attr::first_attr_value_str_by_name(attrs,
4410 None => default_path,
4412 self.mod_path_stack.push(file_path)
4415 fn pop_mod_path(&mut self) {
4416 self.mod_path_stack.pop().unwrap();
4419 /// Read a module from a source file.
4420 fn eval_src_mod(&mut self,
4422 outer_attrs: &[ast::Attribute],
4424 -> (ast::Item_, Vec<ast::Attribute> ) {
4425 let mut prefix = Path::new(self.sess.span_diagnostic.cm.span_to_filename(self.span));
4427 let mod_path = Path::new(".").join_many(self.mod_path_stack.as_slice());
4428 let dir_path = prefix.join(&mod_path);
4429 let mod_string = token::get_ident(id);
4430 let (file_path, owns_directory) = match ::attr::first_attr_value_str_by_name(
4431 outer_attrs, "path") {
4432 Some(d) => (dir_path.join(d), true),
4434 let mod_name = mod_string.get().to_string();
4435 let default_path_str = format!("{}.rs", mod_name);
4436 let secondary_path_str = format!("{}/mod.rs", mod_name);
4437 let default_path = dir_path.join(default_path_str.as_slice());
4438 let secondary_path = dir_path.join(secondary_path_str.as_slice());
4439 let default_exists = default_path.exists();
4440 let secondary_exists = secondary_path.exists();
4442 if !self.owns_directory {
4443 self.span_err(id_sp,
4444 "cannot declare a new module at this location");
4445 let this_module = match self.mod_path_stack.last() {
4446 Some(name) => name.get().to_string(),
4447 None => self.root_module_name.get_ref().clone(),
4449 self.span_note(id_sp,
4450 format!("maybe move this module `{0}` \
4451 to its own directory via \
4453 this_module).as_slice());
4454 if default_exists || secondary_exists {
4455 self.span_note(id_sp,
4456 format!("... or maybe `use` the module \
4457 `{}` instead of possibly \
4459 mod_name).as_slice());
4461 self.abort_if_errors();
4464 match (default_exists, secondary_exists) {
4465 (true, false) => (default_path, false),
4466 (false, true) => (secondary_path, true),
4468 self.span_fatal(id_sp,
4469 format!("file not found for module \
4471 mod_name).as_slice());
4476 format!("file for module `{}` found at both {} \
4480 secondary_path_str).as_slice());
4486 self.eval_src_mod_from_path(file_path, owns_directory,
4487 mod_string.get().to_string(), id_sp)
4490 fn eval_src_mod_from_path(&mut self,
4492 owns_directory: bool,
4494 id_sp: Span) -> (ast::Item_, Vec<ast::Attribute> ) {
4495 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
4496 match included_mod_stack.iter().position(|p| *p == path) {
4498 let mut err = String::from_str("circular modules: ");
4499 let len = included_mod_stack.len();
4500 for p in included_mod_stack.slice(i, len).iter() {
4501 err.push_str(p.display().as_maybe_owned().as_slice());
4502 err.push_str(" -> ");
4504 err.push_str(path.display().as_maybe_owned().as_slice());
4505 self.span_fatal(id_sp, err.as_slice());
4509 included_mod_stack.push(path.clone());
4510 drop(included_mod_stack);
4513 new_sub_parser_from_file(self.sess,
4519 let mod_inner_lo = p0.span.lo;
4520 let (mod_attrs, next) = p0.parse_inner_attrs_and_next();
4521 let first_item_outer_attrs = next;
4522 let m0 = p0.parse_mod_items(token::EOF, first_item_outer_attrs, mod_inner_lo);
4523 self.sess.included_mod_stack.borrow_mut().pop();
4524 return (ast::ItemMod(m0), mod_attrs);
4527 /// Parse a function declaration from a foreign module
4528 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility,
4529 attrs: Vec<Attribute>) -> Gc<ForeignItem> {
4530 let lo = self.span.lo;
4531 self.expect_keyword(keywords::Fn);
4533 let (ident, generics) = self.parse_fn_header();
4534 let decl = self.parse_fn_decl(true);
4535 let hi = self.span.hi;
4536 self.expect(&token::SEMI);
4537 box(GC) ast::ForeignItem { ident: ident,
4539 node: ForeignItemFn(decl, generics),
4540 id: ast::DUMMY_NODE_ID,
4541 span: mk_sp(lo, hi),
4545 /// Parse a static item from a foreign module
4546 fn parse_item_foreign_static(&mut self, vis: ast::Visibility,
4547 attrs: Vec<Attribute> ) -> Gc<ForeignItem> {
4548 let lo = self.span.lo;
4550 self.expect_keyword(keywords::Static);
4551 let mutbl = self.eat_keyword(keywords::Mut);
4553 let ident = self.parse_ident();
4554 self.expect(&token::COLON);
4555 let ty = self.parse_ty(true);
4556 let hi = self.span.hi;
4557 self.expect(&token::SEMI);
4558 box(GC) ast::ForeignItem {
4561 node: ForeignItemStatic(ty, mutbl),
4562 id: ast::DUMMY_NODE_ID,
4563 span: mk_sp(lo, hi),
4568 /// Parse safe/unsafe and fn
4569 fn parse_fn_style(&mut self) -> FnStyle {
4570 if self.eat_keyword(keywords::Fn) { NormalFn }
4571 else if self.eat_keyword(keywords::Unsafe) {
4572 self.expect_keyword(keywords::Fn);
4575 else { self.unexpected(); }
4579 /// At this point, this is essentially a wrapper for
4580 /// parse_foreign_items.
4581 fn parse_foreign_mod_items(&mut self,
4583 first_item_attrs: Vec<Attribute> )
4585 let ParsedItemsAndViewItems {
4586 attrs_remaining: attrs_remaining,
4587 view_items: view_items,
4589 foreign_items: foreign_items
4590 } = self.parse_foreign_items(first_item_attrs, true);
4591 if ! attrs_remaining.is_empty() {
4592 let last_span = self.last_span;
4593 self.span_err(last_span,
4594 "expected item after attributes");
4596 assert!(self.token == token::RBRACE);
4599 view_items: view_items,
4600 items: foreign_items
4604 /// Parse extern crate links
4608 /// extern crate url;
4609 /// extern crate foo = "bar";
4610 fn parse_item_extern_crate(&mut self,
4612 visibility: Visibility,
4613 attrs: Vec<Attribute> )
4616 let (maybe_path, ident) = match self.token {
4617 token::IDENT(..) => {
4618 let the_ident = self.parse_ident();
4619 self.expect_one_of(&[], &[token::EQ, token::SEMI]);
4620 let path = if self.token == token::EQ {
4622 Some(self.parse_str())
4625 self.expect(&token::SEMI);
4629 let span = self.span;
4630 let token_str = self.this_token_to_string();
4631 self.span_fatal(span,
4632 format!("expected extern crate name but \
4634 token_str).as_slice());
4638 IoviViewItem(ast::ViewItem {
4639 node: ViewItemExternCrate(ident, maybe_path, ast::DUMMY_NODE_ID),
4642 span: mk_sp(lo, self.last_span.hi)
4646 /// Parse `extern` for foreign ABIs
4649 /// `extern` is expected to have been
4650 /// consumed before calling this method
4656 fn parse_item_foreign_mod(&mut self,
4658 opt_abi: Option<abi::Abi>,
4659 visibility: Visibility,
4660 attrs: Vec<Attribute> )
4663 self.expect(&token::LBRACE);
4665 let abi = opt_abi.unwrap_or(abi::C);
4667 let (inner, next) = self.parse_inner_attrs_and_next();
4668 let m = self.parse_foreign_mod_items(abi, next);
4669 self.expect(&token::RBRACE);
4671 let last_span = self.last_span;
4672 let item = self.mk_item(lo,
4674 special_idents::invalid,
4677 maybe_append(attrs, Some(inner)));
4678 return IoviItem(item);
4681 /// Parse type Foo = Bar;
4682 fn parse_item_type(&mut self) -> ItemInfo {
4683 let ident = self.parse_ident();
4684 let tps = self.parse_generics();
4685 self.expect(&token::EQ);
4686 let ty = self.parse_ty(true);
4687 self.expect(&token::SEMI);
4688 (ident, ItemTy(ty, tps), None)
4691 /// Parse a structure-like enum variant definition
4692 /// this should probably be renamed or refactored...
4693 fn parse_struct_def(&mut self) -> Gc<StructDef> {
4694 let mut fields: Vec<StructField> = Vec::new();
4695 while self.token != token::RBRACE {
4696 fields.push(self.parse_struct_decl_field());
4700 return box(GC) ast::StructDef {
4708 /// Parse the part of an "enum" decl following the '{'
4709 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> EnumDef {
4710 let mut variants = Vec::new();
4711 let mut all_nullary = true;
4712 let mut have_disr = false;
4713 while self.token != token::RBRACE {
4714 let variant_attrs = self.parse_outer_attributes();
4715 let vlo = self.span.lo;
4717 let vis = self.parse_visibility();
4721 let mut args = Vec::new();
4722 let mut disr_expr = None;
4723 ident = self.parse_ident();
4724 if self.eat(&token::LBRACE) {
4725 // Parse a struct variant.
4726 all_nullary = false;
4727 kind = StructVariantKind(self.parse_struct_def());
4728 } else if self.token == token::LPAREN {
4729 all_nullary = false;
4730 let arg_tys = self.parse_enum_variant_seq(
4733 seq_sep_trailing_disallowed(token::COMMA),
4734 |p| p.parse_ty(true)
4736 for ty in arg_tys.move_iter() {
4737 args.push(ast::VariantArg {
4739 id: ast::DUMMY_NODE_ID,
4742 kind = TupleVariantKind(args);
4743 } else if self.eat(&token::EQ) {
4745 disr_expr = Some(self.parse_expr());
4746 kind = TupleVariantKind(args);
4748 kind = TupleVariantKind(Vec::new());
4751 let vr = ast::Variant_ {
4753 attrs: variant_attrs,
4755 id: ast::DUMMY_NODE_ID,
4756 disr_expr: disr_expr,
4759 variants.push(P(spanned(vlo, self.last_span.hi, vr)));
4761 if !self.eat(&token::COMMA) { break; }
4763 self.expect(&token::RBRACE);
4764 if have_disr && !all_nullary {
4765 self.fatal("discriminator values can only be used with a c-like \
4769 ast::EnumDef { variants: variants }
4772 /// Parse an "enum" declaration
4773 fn parse_item_enum(&mut self) -> ItemInfo {
4774 let id = self.parse_ident();
4775 let generics = self.parse_generics();
4776 self.expect(&token::LBRACE);
4778 let enum_definition = self.parse_enum_def(&generics);
4779 (id, ItemEnum(enum_definition, generics), None)
4782 fn fn_expr_lookahead(tok: &token::Token) -> bool {
4784 token::LPAREN | token::AT | token::TILDE | token::BINOP(_) => true,
4789 /// Parses a string as an ABI spec on an extern type or module. Consumes
4790 /// the `extern` keyword, if one is found.
4791 fn parse_opt_abi(&mut self) -> Option<abi::Abi> {
4793 token::LIT_STR(s) | token::LIT_STR_RAW(s, _) => {
4795 let the_string = s.as_str();
4796 match abi::lookup(the_string) {
4797 Some(abi) => Some(abi),
4799 let last_span = self.last_span;
4802 format!("illegal ABI: expected one of [{}], \
4804 abi::all_names().connect(", "),
4805 the_string).as_slice());
4815 /// Parse one of the items or view items allowed by the
4816 /// flags; on failure, return IoviNone.
4817 /// NB: this function no longer parses the items inside an
4819 fn parse_item_or_view_item(&mut self,
4820 attrs: Vec<Attribute> ,
4821 macros_allowed: bool)
4824 INTERPOLATED(token::NtItem(item)) => {
4826 let new_attrs = attrs.append(item.attrs.as_slice());
4827 return IoviItem(box(GC) Item {
4835 let lo = self.span.lo;
4837 let visibility = self.parse_visibility();
4839 // must be a view item:
4840 if self.eat_keyword(keywords::Use) {
4841 // USE ITEM (IoviViewItem)
4842 let view_item = self.parse_use();
4843 self.expect(&token::SEMI);
4844 return IoviViewItem(ast::ViewItem {
4848 span: mk_sp(lo, self.last_span.hi)
4851 // either a view item or an item:
4852 if self.eat_keyword(keywords::Extern) {
4853 let next_is_mod = self.eat_keyword(keywords::Mod);
4855 if next_is_mod || self.eat_keyword(keywords::Crate) {
4857 let last_span = self.last_span;
4858 self.span_err(mk_sp(lo, last_span.hi),
4859 format!("`extern mod` is obsolete, use \
4860 `extern crate` instead \
4861 to refer to external \
4862 crates.").as_slice())
4864 return self.parse_item_extern_crate(lo, visibility, attrs);
4867 let opt_abi = self.parse_opt_abi();
4869 if self.eat_keyword(keywords::Fn) {
4870 // EXTERN FUNCTION ITEM
4871 let abi = opt_abi.unwrap_or(abi::C);
4872 let (ident, item_, extra_attrs) =
4873 self.parse_item_fn(NormalFn, abi);
4874 let last_span = self.last_span;
4875 let item = self.mk_item(lo,
4880 maybe_append(attrs, extra_attrs));
4881 return IoviItem(item);
4882 } else if self.token == token::LBRACE {
4883 return self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs);
4886 let span = self.span;
4887 let token_str = self.this_token_to_string();
4888 self.span_fatal(span,
4889 format!("expected `{}` or `fn` but found `{}`", "{",
4890 token_str).as_slice());
4893 let is_virtual = self.eat_keyword(keywords::Virtual);
4894 if is_virtual && !self.is_keyword(keywords::Struct) {
4895 let span = self.span;
4897 "`virtual` keyword may only be used with `struct`");
4900 // the rest are all guaranteed to be items:
4901 if self.is_keyword(keywords::Static) {
4904 let (ident, item_, extra_attrs) = self.parse_item_const();
4905 let last_span = self.last_span;
4906 let item = self.mk_item(lo,
4911 maybe_append(attrs, extra_attrs));
4912 return IoviItem(item);
4914 if self.is_keyword(keywords::Fn) &&
4915 self.look_ahead(1, |f| !Parser::fn_expr_lookahead(f)) {
4918 let (ident, item_, extra_attrs) =
4919 self.parse_item_fn(NormalFn, abi::Rust);
4920 let last_span = self.last_span;
4921 let item = self.mk_item(lo,
4926 maybe_append(attrs, extra_attrs));
4927 return IoviItem(item);
4929 if self.is_keyword(keywords::Unsafe)
4930 && self.look_ahead(1u, |t| *t != token::LBRACE) {
4931 // UNSAFE FUNCTION ITEM
4933 let abi = if self.eat_keyword(keywords::Extern) {
4934 self.parse_opt_abi().unwrap_or(abi::C)
4938 self.expect_keyword(keywords::Fn);
4939 let (ident, item_, extra_attrs) =
4940 self.parse_item_fn(UnsafeFn, abi);
4941 let last_span = self.last_span;
4942 let item = self.mk_item(lo,
4947 maybe_append(attrs, extra_attrs));
4948 return IoviItem(item);
4950 if self.eat_keyword(keywords::Mod) {
4952 let (ident, item_, extra_attrs) =
4953 self.parse_item_mod(attrs.as_slice());
4954 let last_span = self.last_span;
4955 let item = self.mk_item(lo,
4960 maybe_append(attrs, extra_attrs));
4961 return IoviItem(item);
4963 if self.eat_keyword(keywords::Type) {
4965 let (ident, item_, extra_attrs) = self.parse_item_type();
4966 let last_span = self.last_span;
4967 let item = self.mk_item(lo,
4972 maybe_append(attrs, extra_attrs));
4973 return IoviItem(item);
4975 if self.eat_keyword(keywords::Enum) {
4977 let (ident, item_, extra_attrs) = self.parse_item_enum();
4978 let last_span = self.last_span;
4979 let item = self.mk_item(lo,
4984 maybe_append(attrs, extra_attrs));
4985 return IoviItem(item);
4987 if self.eat_keyword(keywords::Trait) {
4989 let (ident, item_, extra_attrs) = self.parse_item_trait();
4990 let last_span = self.last_span;
4991 let item = self.mk_item(lo,
4996 maybe_append(attrs, extra_attrs));
4997 return IoviItem(item);
4999 if self.eat_keyword(keywords::Impl) {
5001 let (ident, item_, extra_attrs) = self.parse_item_impl();
5002 let last_span = self.last_span;
5003 let item = self.mk_item(lo,
5008 maybe_append(attrs, extra_attrs));
5009 return IoviItem(item);
5011 if self.eat_keyword(keywords::Struct) {
5013 let (ident, item_, extra_attrs) = self.parse_item_struct(is_virtual);
5014 let last_span = self.last_span;
5015 let item = self.mk_item(lo,
5020 maybe_append(attrs, extra_attrs));
5021 return IoviItem(item);
5023 self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility)
5026 /// Parse a foreign item; on failure, return IoviNone.
5027 fn parse_foreign_item(&mut self,
5028 attrs: Vec<Attribute> ,
5029 macros_allowed: bool)
5031 maybe_whole!(iovi self, NtItem);
5032 let lo = self.span.lo;
5034 let visibility = self.parse_visibility();
5036 if self.is_keyword(keywords::Static) {
5037 // FOREIGN STATIC ITEM
5038 let item = self.parse_item_foreign_static(visibility, attrs);
5039 return IoviForeignItem(item);
5041 if self.is_keyword(keywords::Fn) || self.is_keyword(keywords::Unsafe) {
5042 // FOREIGN FUNCTION ITEM
5043 let item = self.parse_item_foreign_fn(visibility, attrs);
5044 return IoviForeignItem(item);
5046 self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility)
5049 /// This is the fall-through for parsing items.
5050 fn parse_macro_use_or_failure(
5052 attrs: Vec<Attribute> ,
5053 macros_allowed: bool,
5055 visibility: Visibility
5056 ) -> ItemOrViewItem {
5057 if macros_allowed && !token::is_any_keyword(&self.token)
5058 && self.look_ahead(1, |t| *t == token::NOT)
5059 && (self.look_ahead(2, |t| is_plain_ident(t))
5060 || self.look_ahead(2, |t| *t == token::LPAREN)
5061 || self.look_ahead(2, |t| *t == token::LBRACE)) {
5062 // MACRO INVOCATION ITEM
5065 let pth = self.parse_path(NoTypesAllowed).path;
5066 self.expect(&token::NOT);
5068 // a 'special' identifier (like what `macro_rules!` uses)
5069 // is optional. We should eventually unify invoc syntax
5071 let id = if is_plain_ident(&self.token) {
5074 token::special_idents::invalid // no special identifier
5076 // eat a matched-delimiter token tree:
5077 let tts = match token::close_delimiter_for(&self.token) {
5080 self.parse_seq_to_end(&ket,
5082 |p| p.parse_token_tree())
5084 None => self.fatal("expected open delimiter")
5086 // single-variant-enum... :
5087 let m = ast::MacInvocTT(pth, tts, EMPTY_CTXT);
5088 let m: ast::Mac = codemap::Spanned { node: m,
5089 span: mk_sp(self.span.lo,
5091 let item_ = ItemMac(m);
5092 let last_span = self.last_span;
5093 let item = self.mk_item(lo,
5099 return IoviItem(item);
5102 // FAILURE TO PARSE ITEM
5103 if visibility != Inherited {
5104 let mut s = String::from_str("unmatched visibility `");
5105 if visibility == Public {
5111 let last_span = self.last_span;
5112 self.span_fatal(last_span, s.as_slice());
5114 return IoviNone(attrs);
5117 pub fn parse_item_with_outer_attributes(&mut self) -> Option<Gc<Item>> {
5118 let attrs = self.parse_outer_attributes();
5119 self.parse_item(attrs)
5122 pub fn parse_item(&mut self, attrs: Vec<Attribute> ) -> Option<Gc<Item>> {
5123 match self.parse_item_or_view_item(attrs, true) {
5124 IoviNone(_) => None,
5126 self.fatal("view items are not allowed here"),
5127 IoviForeignItem(_) =>
5128 self.fatal("foreign items are not allowed here"),
5129 IoviItem(item) => Some(item)
5133 /// Parse, e.g., "use a::b::{z,y}"
5134 fn parse_use(&mut self) -> ViewItem_ {
5135 return ViewItemUse(self.parse_view_path());
5139 /// Matches view_path : MOD? IDENT EQ non_global_path
5140 /// | MOD? non_global_path MOD_SEP LBRACE RBRACE
5141 /// | MOD? non_global_path MOD_SEP LBRACE ident_seq RBRACE
5142 /// | MOD? non_global_path MOD_SEP STAR
5143 /// | MOD? non_global_path
5144 fn parse_view_path(&mut self) -> Gc<ViewPath> {
5145 let lo = self.span.lo;
5147 if self.token == token::LBRACE {
5149 let idents = self.parse_unspanned_seq(
5150 &token::LBRACE, &token::RBRACE,
5151 seq_sep_trailing_allowed(token::COMMA),
5152 |p| p.parse_path_list_ident());
5153 let path = ast::Path {
5154 span: mk_sp(lo, self.span.hi),
5156 segments: Vec::new()
5158 return box(GC) spanned(lo, self.span.hi,
5159 ViewPathList(path, idents, ast::DUMMY_NODE_ID));
5162 let first_ident = self.parse_ident();
5163 let mut path = vec!(first_ident);
5168 let path_lo = self.span.lo;
5169 path = vec!(self.parse_ident());
5170 while self.token == token::MOD_SEP {
5172 let id = self.parse_ident();
5175 let path = ast::Path {
5176 span: mk_sp(path_lo, self.span.hi),
5178 segments: path.move_iter().map(|identifier| {
5180 identifier: identifier,
5181 lifetimes: Vec::new(),
5182 types: OwnedSlice::empty(),
5186 return box(GC) spanned(lo, self.span.hi,
5187 ViewPathSimple(first_ident, path,
5188 ast::DUMMY_NODE_ID));
5192 // foo::bar or foo::{a,b,c} or foo::*
5193 while self.token == token::MOD_SEP {
5197 token::IDENT(i, _) => {
5202 // foo::bar::{a,b,c}
5204 let idents = self.parse_unspanned_seq(
5207 seq_sep_trailing_allowed(token::COMMA),
5208 |p| p.parse_path_list_ident()
5210 let path = ast::Path {
5211 span: mk_sp(lo, self.span.hi),
5213 segments: path.move_iter().map(|identifier| {
5215 identifier: identifier,
5216 lifetimes: Vec::new(),
5217 types: OwnedSlice::empty(),
5221 return box(GC) spanned(lo, self.span.hi,
5222 ViewPathList(path, idents, ast::DUMMY_NODE_ID));
5226 token::BINOP(token::STAR) => {
5228 let path = ast::Path {
5229 span: mk_sp(lo, self.span.hi),
5231 segments: path.move_iter().map(|identifier| {
5233 identifier: identifier,
5234 lifetimes: Vec::new(),
5235 types: OwnedSlice::empty(),
5239 return box(GC) spanned(lo, self.span.hi,
5240 ViewPathGlob(path, ast::DUMMY_NODE_ID));
5249 let last = *path.get(path.len() - 1u);
5250 let path = ast::Path {
5251 span: mk_sp(lo, self.span.hi),
5253 segments: path.move_iter().map(|identifier| {
5255 identifier: identifier,
5256 lifetimes: Vec::new(),
5257 types: OwnedSlice::empty(),
5261 return box(GC) spanned(lo,
5263 ViewPathSimple(last, path, ast::DUMMY_NODE_ID));
5266 /// Parses a sequence of items. Stops when it finds program
5267 /// text that can't be parsed as an item
5268 /// - mod_items uses extern_mod_allowed = true
5269 /// - block_tail_ uses extern_mod_allowed = false
5270 fn parse_items_and_view_items(&mut self,
5271 first_item_attrs: Vec<Attribute> ,
5272 mut extern_mod_allowed: bool,
5273 macros_allowed: bool)
5274 -> ParsedItemsAndViewItems {
5275 let mut attrs = first_item_attrs.append(self.parse_outer_attributes().as_slice());
5276 // First, parse view items.
5277 let mut view_items : Vec<ast::ViewItem> = Vec::new();
5278 let mut items = Vec::new();
5280 // I think this code would probably read better as a single
5281 // loop with a mutable three-state-variable (for extern crates,
5282 // view items, and regular items) ... except that because
5283 // of macros, I'd like to delay that entire check until later.
5285 match self.parse_item_or_view_item(attrs, macros_allowed) {
5286 IoviNone(attrs) => {
5287 return ParsedItemsAndViewItems {
5288 attrs_remaining: attrs,
5289 view_items: view_items,
5291 foreign_items: Vec::new()
5294 IoviViewItem(view_item) => {
5295 match view_item.node {
5296 ViewItemUse(..) => {
5297 // `extern crate` must precede `use`.
5298 extern_mod_allowed = false;
5300 ViewItemExternCrate(..) if !extern_mod_allowed => {
5301 self.span_err(view_item.span,
5302 "\"extern crate\" declarations are \
5305 ViewItemExternCrate(..) => {}
5307 view_items.push(view_item);
5311 attrs = self.parse_outer_attributes();
5314 IoviForeignItem(_) => {
5318 attrs = self.parse_outer_attributes();
5321 // Next, parse items.
5323 match self.parse_item_or_view_item(attrs, macros_allowed) {
5324 IoviNone(returned_attrs) => {
5325 attrs = returned_attrs;
5328 IoviViewItem(view_item) => {
5329 attrs = self.parse_outer_attributes();
5330 self.span_err(view_item.span,
5331 "`use` and `extern crate` declarations must precede items");
5334 attrs = self.parse_outer_attributes();
5337 IoviForeignItem(_) => {
5343 ParsedItemsAndViewItems {
5344 attrs_remaining: attrs,
5345 view_items: view_items,
5347 foreign_items: Vec::new()
5351 /// Parses a sequence of foreign items. Stops when it finds program
5352 /// text that can't be parsed as an item
5353 fn parse_foreign_items(&mut self, first_item_attrs: Vec<Attribute> ,
5354 macros_allowed: bool)
5355 -> ParsedItemsAndViewItems {
5356 let mut attrs = first_item_attrs.append(self.parse_outer_attributes().as_slice());
5357 let mut foreign_items = Vec::new();
5359 match self.parse_foreign_item(attrs, macros_allowed) {
5360 IoviNone(returned_attrs) => {
5361 if self.token == token::RBRACE {
5362 attrs = returned_attrs;
5367 IoviViewItem(view_item) => {
5368 // I think this can't occur:
5369 self.span_err(view_item.span,
5370 "`use` and `extern crate` declarations must precede items");
5373 // FIXME #5668: this will occur for a macro invocation:
5374 self.span_fatal(item.span, "macros cannot expand to foreign items");
5376 IoviForeignItem(foreign_item) => {
5377 foreign_items.push(foreign_item);
5380 attrs = self.parse_outer_attributes();
5383 ParsedItemsAndViewItems {
5384 attrs_remaining: attrs,
5385 view_items: Vec::new(),
5387 foreign_items: foreign_items
5391 /// Parses a source module as a crate. This is the main
5392 /// entry point for the parser.
5393 pub fn parse_crate_mod(&mut self) -> Crate {
5394 let lo = self.span.lo;
5395 // parse the crate's inner attrs, maybe (oops) one
5396 // of the attrs of an item:
5397 let (inner, next) = self.parse_inner_attrs_and_next();
5398 let first_item_outer_attrs = next;
5399 // parse the items inside the crate:
5400 let m = self.parse_mod_items(token::EOF, first_item_outer_attrs, lo);
5405 config: self.cfg.clone(),
5406 span: mk_sp(lo, self.span.lo),
5407 exported_macros: Vec::new(),
5411 pub fn parse_optional_str(&mut self)
5412 -> Option<(InternedString, ast::StrStyle)> {
5413 let (s, style) = match self.token {
5414 token::LIT_STR(s) => (self.id_to_interned_str(s.ident()), ast::CookedStr),
5415 token::LIT_STR_RAW(s, n) => {
5416 (self.id_to_interned_str(s.ident()), ast::RawStr(n))
5424 pub fn parse_str(&mut self) -> (InternedString, StrStyle) {
5425 match self.parse_optional_str() {
5427 _ => self.fatal("expected string literal")