1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
14 use ast::{BareFnTy, ClosureTy};
15 use ast::{RegionTyParamBound, TraitTyParamBound};
16 use ast::{ProvidedMethod, 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::{CaptureByRef, CaptureByValue, CaptureClause};
21 use ast::{Crate, CrateConfig, Decl, DeclItem};
22 use ast::{DeclLocal, DefaultBlock, UnDeref, BiDiv, EMPTY_CTXT, EnumDef, ExplicitSelf};
23 use ast::{Expr, Expr_, ExprAddrOf, ExprMatch, ExprAgain};
24 use ast::{ExprAssign, ExprAssignOp, ExprBinary, ExprBlock, ExprBox};
25 use ast::{ExprBreak, ExprCall, ExprCast};
26 use ast::{ExprField, ExprTupField, ExprFnBlock, ExprIf, ExprIndex};
27 use ast::{ExprLit, ExprLoop, ExprMac};
28 use ast::{ExprMethodCall, ExprParen, ExprPath, ExprProc};
29 use ast::{ExprRepeat, ExprRet, ExprStruct, ExprTup, ExprUnary, ExprUnboxedFn};
30 use ast::{ExprVec, ExprWhile, ExprForLoop, Field, FnDecl};
31 use ast::{Once, Many};
32 use ast::{FnUnboxedClosureKind, FnMutUnboxedClosureKind};
33 use ast::{FnOnceUnboxedClosureKind};
34 use ast::{ForeignItem, ForeignItemStatic, ForeignItemFn, ForeignMod};
35 use ast::{Ident, NormalFn, Inherited, ImplItem, Item, Item_, ItemStatic};
36 use ast::{ItemEnum, ItemFn, ItemForeignMod, ItemImpl};
37 use ast::{ItemMac, ItemMod, ItemStruct, ItemTrait, ItemTy, Lit, Lit_};
38 use ast::{LitBool, LitChar, LitByte, LitBinary};
39 use ast::{LitNil, LitStr, LitInt, Local, LocalLet};
40 use ast::{MutImmutable, MutMutable, Mac_, MacInvocTT, Matcher, MatchNonterminal};
41 use ast::{MatchSeq, MatchTok, Method, MutTy, BiMul, Mutability};
42 use ast::{MethodImplItem};
43 use ast::{NamedField, UnNeg, NoReturn, UnNot, P, Pat, PatEnum};
44 use ast::{PatIdent, PatLit, PatRange, PatRegion, PatStruct};
45 use ast::{PatTup, PatBox, PatWild, PatWildMulti, PatWildSingle};
46 use ast::{BiRem, RequiredMethod};
47 use ast::{RetStyle, Return, BiShl, BiShr, Stmt, StmtDecl};
48 use ast::{StmtExpr, StmtSemi, StmtMac, StructDef, StructField};
49 use ast::{StructVariantKind, BiSub};
51 use ast::{SelfExplicit, SelfRegion, SelfStatic, SelfValue};
52 use ast::{TokenTree, TraitItem, TraitRef, TTDelim, TTSeq, TTTok};
53 use ast::{TTNonterminal, TupleVariantKind, Ty, Ty_, TyBot, TyBox};
54 use ast::{TypeField, TyFixedLengthVec, TyClosure, TyProc, TyBareFn};
55 use ast::{TyTypeof, TyInfer, TypeMethod};
56 use ast::{TyNil, TyParam, TyParamBound, TyParen, TyPath, TyPtr, TyRptr};
57 use ast::{TyTup, TyU32, TyUnboxedFn, TyUniq, TyVec, UnUniq};
58 use ast::{UnboxedClosureKind, UnboxedFnTy, UnboxedFnTyParamBound};
59 use ast::{UnnamedField, UnsafeBlock};
60 use ast::{UnsafeFn, ViewItem, ViewItem_, ViewItemExternCrate, ViewItemUse};
61 use ast::{ViewPath, ViewPathGlob, ViewPathList, ViewPathSimple};
62 use ast::{Visibility, WhereClause, WherePredicate};
64 use ast_util::{as_prec, ident_to_path, operator_prec};
67 use codemap::{Span, BytePos, Spanned, spanned, mk_sp};
70 use parse::attr::ParserAttr;
72 use parse::common::{SeqSep, seq_sep_none};
73 use parse::common::{seq_sep_trailing_allowed};
74 use parse::lexer::Reader;
75 use parse::lexer::TokenAndSpan;
76 use parse::obsolete::*;
77 use parse::token::{INTERPOLATED, InternedString, can_begin_expr};
78 use parse::token::{is_ident, is_ident_or_path, is_plain_ident};
79 use parse::token::{keywords, special_idents, token_to_binop};
81 use parse::{new_sub_parser_from_file, ParseSess};
82 use owned_slice::OwnedSlice;
84 use std::collections::HashSet;
85 use std::mem::replace;
87 use std::gc::{Gc, GC};
90 #[allow(non_camel_case_types)]
91 #[deriving(PartialEq)]
92 pub enum restriction {
96 RESTRICT_NO_BAR_OR_DOUBLEBAR_OP,
97 RESTRICT_NO_STRUCT_LITERAL,
100 type ItemInfo = (Ident, Item_, Option<Vec<Attribute> >);
102 /// How to parse a path. There are four different kinds of paths, all of which
103 /// are parsed somewhat differently.
104 #[deriving(PartialEq)]
105 pub enum PathParsingMode {
106 /// A path with no type parameters; e.g. `foo::bar::Baz`
108 /// A path with a lifetime and type parameters, with no double colons
109 /// before the type parameters; e.g. `foo::bar<'a>::Baz<T>`
110 LifetimeAndTypesWithoutColons,
111 /// A path with a lifetime and type parameters with double colons before
112 /// the type parameters; e.g. `foo::bar::<'a>::Baz::<T>`
113 LifetimeAndTypesWithColons,
114 /// A path with a lifetime and type parameters with bounds before the last
115 /// set of type parameters only; e.g. `foo::bar<'a>::Baz+X+Y<T>` This
116 /// form does not use extra double colons.
117 LifetimeAndTypesAndBounds,
120 /// A path paired with optional type bounds.
121 pub struct PathAndBounds {
123 pub bounds: Option<ast::TyParamBounds>,
126 enum ItemOrViewItem {
127 /// Indicates a failure to parse any kind of item. The attributes are
129 IoviNone(Vec<Attribute>),
131 IoviForeignItem(Gc<ForeignItem>),
132 IoviViewItem(ViewItem)
136 /// Possibly accept an `INTERPOLATED` expression (a pre-parsed expression
137 /// dropped into the token stream, which happens while parsing the
138 /// result of macro expansion)
139 /// Placement of these is not as complex as I feared it would be.
140 /// The important thing is to make sure that lookahead doesn't balk
141 /// at INTERPOLATED tokens
142 macro_rules! maybe_whole_expr (
145 let found = match $p.token {
146 INTERPOLATED(token::NtExpr(e)) => {
149 INTERPOLATED(token::NtPath(_)) => {
150 // FIXME: The following avoids an issue with lexical borrowck scopes,
151 // but the clone is unfortunate.
152 let pt = match $p.token {
153 INTERPOLATED(token::NtPath(ref pt)) => (**pt).clone(),
157 Some($p.mk_expr(span.lo, span.hi, ExprPath(pt)))
159 INTERPOLATED(token::NtBlock(b)) => {
161 Some($p.mk_expr(span.lo, span.hi, ExprBlock(b)))
176 /// As maybe_whole_expr, but for things other than expressions
177 macro_rules! maybe_whole (
178 ($p:expr, $constructor:ident) => (
180 let found = match ($p).token {
181 INTERPOLATED(token::$constructor(_)) => {
182 Some(($p).bump_and_get())
187 Some(INTERPOLATED(token::$constructor(x))) => {
194 (no_clone $p:expr, $constructor:ident) => (
196 let found = match ($p).token {
197 INTERPOLATED(token::$constructor(_)) => {
198 Some(($p).bump_and_get())
203 Some(INTERPOLATED(token::$constructor(x))) => {
210 (deref $p:expr, $constructor:ident) => (
212 let found = match ($p).token {
213 INTERPOLATED(token::$constructor(_)) => {
214 Some(($p).bump_and_get())
219 Some(INTERPOLATED(token::$constructor(x))) => {
226 (Some $p:expr, $constructor:ident) => (
228 let found = match ($p).token {
229 INTERPOLATED(token::$constructor(_)) => {
230 Some(($p).bump_and_get())
235 Some(INTERPOLATED(token::$constructor(x))) => {
236 return Some(x.clone()),
242 (iovi $p:expr, $constructor:ident) => (
244 let found = match ($p).token {
245 INTERPOLATED(token::$constructor(_)) => {
246 Some(($p).bump_and_get())
251 Some(INTERPOLATED(token::$constructor(x))) => {
252 return IoviItem(x.clone())
258 (pair_empty $p:expr, $constructor:ident) => (
260 let found = match ($p).token {
261 INTERPOLATED(token::$constructor(_)) => {
262 Some(($p).bump_and_get())
267 Some(INTERPOLATED(token::$constructor(x))) => {
268 return (Vec::new(), x)
277 fn maybe_append(lhs: Vec<Attribute> , rhs: Option<Vec<Attribute> >)
281 Some(ref attrs) => lhs.append(attrs.as_slice())
286 struct ParsedItemsAndViewItems {
287 attrs_remaining: Vec<Attribute>,
288 view_items: Vec<ViewItem>,
289 items: Vec<Gc<Item>>,
290 foreign_items: Vec<Gc<ForeignItem>>
293 /* ident is handled by common.rs */
295 pub struct Parser<'a> {
296 pub sess: &'a ParseSess,
297 /// the current token:
298 pub token: token::Token,
299 /// the span of the current token:
301 /// the span of the prior token:
303 pub cfg: CrateConfig,
304 /// the previous token or None (only stashed sometimes).
305 pub last_token: Option<Box<token::Token>>,
306 pub buffer: [TokenAndSpan, ..4],
307 pub buffer_start: int,
309 pub tokens_consumed: uint,
310 pub restriction: restriction,
311 pub quote_depth: uint, // not (yet) related to the quasiquoter
312 pub reader: Box<Reader+'a>,
313 pub interner: Rc<token::IdentInterner>,
314 /// The set of seen errors about obsolete syntax. Used to suppress
315 /// extra detail when the same error is seen twice
316 pub obsolete_set: HashSet<ObsoleteSyntax>,
317 /// Used to determine the path to externally loaded source files
318 pub mod_path_stack: Vec<InternedString>,
319 /// Stack of spans of open delimiters. Used for error message.
320 pub open_braces: Vec<Span>,
321 /// Flag if this parser "owns" the directory that it is currently parsing
322 /// in. This will affect how nested files are looked up.
323 pub owns_directory: bool,
324 /// Name of the root module this parser originated from. If `None`, then the
325 /// name is not known. This does not change while the parser is descending
326 /// into modules, and sub-parsers have new values for this name.
327 pub root_module_name: Option<String>,
330 fn is_plain_ident_or_underscore(t: &token::Token) -> bool {
331 is_plain_ident(t) || *t == token::UNDERSCORE
334 /// Get a token the parser cares about
335 fn real_token(rdr: &mut Reader) -> TokenAndSpan {
336 let mut t = rdr.next_token();
339 token::WS | token::COMMENT | token::SHEBANG(_) => {
340 t = rdr.next_token();
348 impl<'a> Parser<'a> {
349 pub fn new(sess: &'a ParseSess,
350 cfg: ast::CrateConfig,
351 mut rdr: Box<Reader+'a>)
354 let tok0 = real_token(&mut *rdr);
356 let placeholder = TokenAndSpan {
357 tok: token::UNDERSCORE,
363 interner: token::get_ident_interner(),
379 restriction: UNRESTRICTED,
381 obsolete_set: HashSet::new(),
382 mod_path_stack: Vec::new(),
383 open_braces: Vec::new(),
384 owns_directory: true,
385 root_module_name: None,
389 /// Convert a token to a string using self's reader
390 pub fn token_to_string(token: &token::Token) -> String {
391 token::to_string(token)
394 /// Convert the current token to a string using self's reader
395 pub fn this_token_to_string(&mut self) -> String {
396 Parser::token_to_string(&self.token)
399 pub fn unexpected_last(&mut self, t: &token::Token) -> ! {
400 let token_str = Parser::token_to_string(t);
401 let last_span = self.last_span;
402 self.span_fatal(last_span, format!("unexpected token: `{}`",
403 token_str).as_slice());
406 pub fn unexpected(&mut self) -> ! {
407 let this_token = self.this_token_to_string();
408 self.fatal(format!("unexpected token: `{}`", this_token).as_slice());
411 /// Expect and consume the token t. Signal an error if
412 /// the next token is not t.
413 pub fn expect(&mut self, t: &token::Token) {
414 if self.token == *t {
417 let token_str = Parser::token_to_string(t);
418 let this_token_str = self.this_token_to_string();
419 self.fatal(format!("expected `{}`, found `{}`",
421 this_token_str).as_slice())
425 /// Expect next token to be edible or inedible token. If edible,
426 /// then consume it; if inedible, then return without consuming
427 /// anything. Signal a fatal error if next token is unexpected.
428 pub fn expect_one_of(&mut self,
429 edible: &[token::Token],
430 inedible: &[token::Token]) {
431 fn tokens_to_string(tokens: &[token::Token]) -> String {
432 let mut i = tokens.iter();
433 // This might be a sign we need a connect method on Iterator.
435 .map_or("".to_string(), |t| Parser::token_to_string(t));
439 b.push_str(Parser::token_to_string(a).as_slice());
443 if edible.contains(&self.token) {
445 } else if inedible.contains(&self.token) {
446 // leave it in the input
448 let expected = edible.iter().map(|x| (*x).clone()).collect::<Vec<_>>().append(inedible);
449 let expect = tokens_to_string(expected.as_slice());
450 let actual = self.this_token_to_string();
452 (if expected.len() != 1 {
453 (format!("expected one of `{}`, found `{}`",
457 (format!("expected `{}`, found `{}`",
465 /// Check for erroneous `ident { }`; if matches, signal error and
466 /// recover (without consuming any expected input token). Returns
467 /// true if and only if input was consumed for recovery.
468 pub fn check_for_erroneous_unit_struct_expecting(&mut self, expected: &[token::Token]) -> bool {
469 if self.token == token::LBRACE
470 && expected.iter().all(|t| *t != token::LBRACE)
471 && self.look_ahead(1, |t| *t == token::RBRACE) {
472 // matched; signal non-fatal error and recover.
473 let span = self.span;
475 "unit-like struct construction is written with no trailing `{ }`");
476 self.eat(&token::LBRACE);
477 self.eat(&token::RBRACE);
484 /// Commit to parsing a complete expression `e` expected to be
485 /// followed by some token from the set edible + inedible. Recover
486 /// from anticipated input errors, discarding erroneous characters.
487 pub fn commit_expr(&mut self, e: Gc<Expr>, edible: &[token::Token],
488 inedible: &[token::Token]) {
489 debug!("commit_expr {:?}", e);
492 // might be unit-struct construction; check for recoverableinput error.
493 let expected = edible.iter().map(|x| (*x).clone()).collect::<Vec<_>>()
495 self.check_for_erroneous_unit_struct_expecting(
496 expected.as_slice());
500 self.expect_one_of(edible, inedible)
503 pub fn commit_expr_expecting(&mut self, e: Gc<Expr>, edible: token::Token) {
504 self.commit_expr(e, &[edible], &[])
507 /// Commit to parsing a complete statement `s`, which expects to be
508 /// followed by some token from the set edible + inedible. Check
509 /// for recoverable input errors, discarding erroneous characters.
510 pub fn commit_stmt(&mut self, s: Gc<Stmt>, edible: &[token::Token],
511 inedible: &[token::Token]) {
512 debug!("commit_stmt {:?}", s);
513 let _s = s; // unused, but future checks might want to inspect `s`.
516 .map_or(false, |t| is_ident_or_path(&**t)) {
517 let expected = edible.iter().map(|x| (*x).clone()).collect::<Vec<_>>()
518 .append(inedible.as_slice());
519 self.check_for_erroneous_unit_struct_expecting(
520 expected.as_slice());
522 self.expect_one_of(edible, inedible)
525 pub fn commit_stmt_expecting(&mut self, s: Gc<Stmt>, edible: token::Token) {
526 self.commit_stmt(s, &[edible], &[])
529 pub fn parse_ident(&mut self) -> ast::Ident {
530 self.check_strict_keywords();
531 self.check_reserved_keywords();
533 token::IDENT(i, _) => {
537 token::INTERPOLATED(token::NtIdent(..)) => {
538 self.bug("ident interpolation not converted to real token");
541 let token_str = self.this_token_to_string();
542 self.fatal((format!("expected ident, found `{}`",
543 token_str)).as_slice())
548 pub fn parse_path_list_item(&mut self) -> ast::PathListItem {
549 let lo = self.span.lo;
550 let node = if self.eat_keyword(keywords::Mod) {
551 ast::PathListMod { id: ast::DUMMY_NODE_ID }
553 let ident = self.parse_ident();
554 ast::PathListIdent { name: ident, id: ast::DUMMY_NODE_ID }
556 let hi = self.last_span.hi;
557 spanned(lo, hi, node)
560 /// Consume token 'tok' if it exists. Returns true if the given
561 /// token was present, false otherwise.
562 pub fn eat(&mut self, tok: &token::Token) -> bool {
563 let is_present = self.token == *tok;
564 if is_present { self.bump() }
568 pub fn is_keyword(&mut self, kw: keywords::Keyword) -> bool {
569 token::is_keyword(kw, &self.token)
572 /// If the next token is the given keyword, eat it and return
573 /// true. Otherwise, return false.
574 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
576 token::IDENT(sid, false) if kw.to_name() == sid.name => {
584 /// If the given word is not a keyword, signal an error.
585 /// If the next token is not the given word, signal an error.
586 /// Otherwise, eat it.
587 pub fn expect_keyword(&mut self, kw: keywords::Keyword) {
588 if !self.eat_keyword(kw) {
589 let id_interned_str = token::get_name(kw.to_name());
590 let token_str = self.this_token_to_string();
591 self.fatal(format!("expected `{}`, found `{}`",
592 id_interned_str, token_str).as_slice())
596 /// Signal an error if the given string is a strict keyword
597 pub fn check_strict_keywords(&mut self) {
598 if token::is_strict_keyword(&self.token) {
599 let token_str = self.this_token_to_string();
600 let span = self.span;
602 format!("expected identifier, found keyword `{}`",
603 token_str).as_slice());
607 /// Signal an error if the current token is a reserved keyword
608 pub fn check_reserved_keywords(&mut self) {
609 if token::is_reserved_keyword(&self.token) {
610 let token_str = self.this_token_to_string();
611 self.fatal(format!("`{}` is a reserved keyword",
612 token_str).as_slice())
616 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
617 /// `&` and continue. If an `&` is not seen, signal an error.
618 fn expect_and(&mut self) {
620 token::BINOP(token::AND) => self.bump(),
622 let span = self.span;
623 let lo = span.lo + BytePos(1);
624 self.replace_token(token::BINOP(token::AND), lo, span.hi)
627 let token_str = self.this_token_to_string();
629 Parser::token_to_string(&token::BINOP(token::AND));
630 self.fatal(format!("expected `{}`, found `{}`",
632 token_str).as_slice())
637 /// Expect and consume a `|`. If `||` is seen, replace it with a single
638 /// `|` and continue. If a `|` is not seen, signal an error.
639 fn expect_or(&mut self) {
641 token::BINOP(token::OR) => self.bump(),
643 let span = self.span;
644 let lo = span.lo + BytePos(1);
645 self.replace_token(token::BINOP(token::OR), lo, span.hi)
648 let found_token = self.this_token_to_string();
650 Parser::token_to_string(&token::BINOP(token::OR));
651 self.fatal(format!("expected `{}`, found `{}`",
653 found_token).as_slice())
658 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
659 /// `<` and continue. If a `<` is not seen, return false.
661 /// This is meant to be used when parsing generics on a path to get the
662 /// starting token. The `force` parameter is used to forcefully break up a
663 /// `<<` token. If `force` is false, then `<<` is only broken when a lifetime
664 /// shows up next. For example, consider the expression:
666 /// foo as bar << test
668 /// The parser needs to know if `bar <<` is the start of a generic path or if
669 /// it's a left-shift token. If `test` were a lifetime, then it's impossible
670 /// for the token to be a left-shift, but if it's not a lifetime, then it's
671 /// considered a left-shift.
673 /// The reason for this is that the only current ambiguity with `<<` is when
674 /// parsing closure types:
676 /// foo::<<'a> ||>();
677 /// impl Foo<<'a> ||>() { ... }
678 fn eat_lt(&mut self, force: bool) -> bool {
680 token::LT => { self.bump(); true }
681 token::BINOP(token::SHL) => {
682 let next_lifetime = self.look_ahead(1, |t| match *t {
683 token::LIFETIME(..) => true,
686 if force || next_lifetime {
687 let span = self.span;
688 let lo = span.lo + BytePos(1);
689 self.replace_token(token::LT, lo, span.hi);
699 fn expect_lt(&mut self) {
700 if !self.eat_lt(true) {
701 let found_token = self.this_token_to_string();
702 let token_str = Parser::token_to_string(&token::LT);
703 self.fatal(format!("expected `{}`, found `{}`",
705 found_token).as_slice())
709 /// Parse a sequence bracketed by `|` and `|`, stopping before the `|`.
710 fn parse_seq_to_before_or<T>(
713 f: |&mut Parser| -> T)
715 let mut first = true;
716 let mut vector = Vec::new();
717 while self.token != token::BINOP(token::OR) &&
718 self.token != token::OROR {
730 /// Expect and consume a GT. if a >> is seen, replace it
731 /// with a single > and continue. If a GT is not seen,
733 pub fn expect_gt(&mut self) {
735 token::GT => self.bump(),
736 token::BINOP(token::SHR) => {
737 let span = self.span;
738 let lo = span.lo + BytePos(1);
739 self.replace_token(token::GT, lo, span.hi)
741 token::BINOPEQ(token::SHR) => {
742 let span = self.span;
743 let lo = span.lo + BytePos(1);
744 self.replace_token(token::GE, lo, span.hi)
747 let span = self.span;
748 let lo = span.lo + BytePos(1);
749 self.replace_token(token::EQ, lo, span.hi)
752 let gt_str = Parser::token_to_string(&token::GT);
753 let this_token_str = self.this_token_to_string();
754 self.fatal(format!("expected `{}`, found `{}`",
756 this_token_str).as_slice())
761 /// Parse a sequence bracketed by '<' and '>', stopping
763 pub fn parse_seq_to_before_gt<T>(
765 sep: Option<token::Token>,
766 f: |&mut Parser| -> T)
768 let mut v = Vec::new();
769 // This loop works by alternating back and forth between parsing types
770 // and commas. For example, given a string `A, B,>`, the parser would
771 // first parse `A`, then a comma, then `B`, then a comma. After that it
772 // would encounter a `>` and stop. This lets the parser handle trailing
773 // commas in generic parameters, because it can stop either after
774 // parsing a type or after parsing a comma.
775 for i in iter::count(0u, 1) {
776 if self.token == token::GT
777 || self.token == token::BINOP(token::SHR)
778 || self.token == token::GE
779 || self.token == token::BINOPEQ(token::SHR) {
786 sep.as_ref().map(|t| self.expect(t));
789 return OwnedSlice::from_vec(v);
792 pub fn parse_seq_to_gt<T>(
794 sep: Option<token::Token>,
795 f: |&mut Parser| -> T)
797 let v = self.parse_seq_to_before_gt(sep, f);
802 /// Parse a sequence, including the closing delimiter. The function
803 /// f must consume tokens until reaching the next separator or
805 pub fn parse_seq_to_end<T>(
809 f: |&mut Parser| -> T)
811 let val = self.parse_seq_to_before_end(ket, sep, f);
816 /// Parse a sequence, not including the closing delimiter. The function
817 /// f must consume tokens until reaching the next separator or
819 pub fn parse_seq_to_before_end<T>(
823 f: |&mut Parser| -> T)
825 let mut first: bool = true;
827 while self.token != *ket {
830 if first { first = false; }
831 else { self.expect(t); }
835 if sep.trailing_sep_allowed && self.token == *ket { break; }
841 /// Parse a sequence, including the closing delimiter. The function
842 /// f must consume tokens until reaching the next separator or
844 pub fn parse_unspanned_seq<T>(
849 f: |&mut Parser| -> T)
852 let result = self.parse_seq_to_before_end(ket, sep, f);
857 /// Parse a sequence parameter of enum variant. For consistency purposes,
858 /// these should not be empty.
859 pub fn parse_enum_variant_seq<T>(
864 f: |&mut Parser| -> T)
866 let result = self.parse_unspanned_seq(bra, ket, sep, f);
867 if result.is_empty() {
868 let last_span = self.last_span;
869 self.span_err(last_span,
870 "nullary enum variants are written with no trailing `( )`");
875 // NB: Do not use this function unless you actually plan to place the
876 // spanned list in the AST.
882 f: |&mut Parser| -> T)
883 -> Spanned<Vec<T> > {
884 let lo = self.span.lo;
886 let result = self.parse_seq_to_before_end(ket, sep, f);
887 let hi = self.span.hi;
889 spanned(lo, hi, result)
892 /// Advance the parser by one token
893 pub fn bump(&mut self) {
894 self.last_span = self.span;
895 // Stash token for error recovery (sometimes; clone is not necessarily cheap).
896 self.last_token = if is_ident_or_path(&self.token) {
897 Some(box self.token.clone())
901 let next = if self.buffer_start == self.buffer_end {
902 real_token(&mut *self.reader)
904 // Avoid token copies with `replace`.
905 let buffer_start = self.buffer_start as uint;
906 let next_index = (buffer_start + 1) & 3 as uint;
907 self.buffer_start = next_index as int;
909 let placeholder = TokenAndSpan {
910 tok: token::UNDERSCORE,
913 replace(&mut self.buffer[buffer_start], placeholder)
916 self.token = next.tok;
917 self.tokens_consumed += 1u;
920 /// Advance the parser by one token and return the bumped token.
921 pub fn bump_and_get(&mut self) -> token::Token {
922 let old_token = replace(&mut self.token, token::UNDERSCORE);
927 /// EFFECT: replace the current token and span with the given one
928 pub fn replace_token(&mut self,
932 self.last_span = mk_sp(self.span.lo, lo);
934 self.span = mk_sp(lo, hi);
936 pub fn buffer_length(&mut self) -> int {
937 if self.buffer_start <= self.buffer_end {
938 return self.buffer_end - self.buffer_start;
940 return (4 - self.buffer_start) + self.buffer_end;
942 pub fn look_ahead<R>(&mut self, distance: uint, f: |&token::Token| -> R)
944 let dist = distance as int;
945 while self.buffer_length() < dist {
946 self.buffer[self.buffer_end as uint] = real_token(&mut *self.reader);
947 self.buffer_end = (self.buffer_end + 1) & 3;
949 f(&self.buffer[((self.buffer_start + dist - 1) & 3) as uint].tok)
951 pub fn fatal(&mut self, m: &str) -> ! {
952 self.sess.span_diagnostic.span_fatal(self.span, m)
954 pub fn span_fatal(&mut self, sp: Span, m: &str) -> ! {
955 self.sess.span_diagnostic.span_fatal(sp, m)
957 pub fn span_note(&mut self, sp: Span, m: &str) {
958 self.sess.span_diagnostic.span_note(sp, m)
960 pub fn bug(&mut self, m: &str) -> ! {
961 self.sess.span_diagnostic.span_bug(self.span, m)
963 pub fn warn(&mut self, m: &str) {
964 self.sess.span_diagnostic.span_warn(self.span, m)
966 pub fn span_warn(&mut self, sp: Span, m: &str) {
967 self.sess.span_diagnostic.span_warn(sp, m)
969 pub fn span_err(&mut self, sp: Span, m: &str) {
970 self.sess.span_diagnostic.span_err(sp, m)
972 pub fn abort_if_errors(&mut self) {
973 self.sess.span_diagnostic.handler().abort_if_errors();
976 pub fn id_to_interned_str(&mut self, id: Ident) -> InternedString {
980 /// Is the current token one of the keywords that signals a bare function
982 pub fn token_is_bare_fn_keyword(&mut self) -> bool {
983 if token::is_keyword(keywords::Fn, &self.token) {
987 if token::is_keyword(keywords::Unsafe, &self.token) ||
988 token::is_keyword(keywords::Once, &self.token) {
989 return self.look_ahead(1, |t| token::is_keyword(keywords::Fn, t))
995 /// Is the current token one of the keywords that signals a closure type?
996 pub fn token_is_closure_keyword(&mut self) -> bool {
997 token::is_keyword(keywords::Unsafe, &self.token) ||
998 token::is_keyword(keywords::Once, &self.token)
1001 /// Is the current token one of the keywords that signals an old-style
1002 /// closure type (with explicit sigil)?
1003 pub fn token_is_old_style_closure_keyword(&mut self) -> bool {
1004 token::is_keyword(keywords::Unsafe, &self.token) ||
1005 token::is_keyword(keywords::Once, &self.token) ||
1006 token::is_keyword(keywords::Fn, &self.token)
1009 pub fn token_is_lifetime(tok: &token::Token) -> bool {
1011 token::LIFETIME(..) => true,
1016 pub fn get_lifetime(&mut self) -> ast::Ident {
1018 token::LIFETIME(ref ident) => *ident,
1019 _ => self.bug("not a lifetime"),
1023 /// parse a TyBareFn type:
1024 pub fn parse_ty_bare_fn(&mut self) -> Ty_ {
1027 [unsafe] [extern "ABI"] fn <'lt> (S) -> T
1028 ^~~~^ ^~~~^ ^~~~^ ^~^ ^
1031 | | | Argument types
1037 let fn_style = self.parse_unsafety();
1038 let abi = if self.eat_keyword(keywords::Extern) {
1039 self.parse_opt_abi().unwrap_or(abi::C)
1044 self.expect_keyword(keywords::Fn);
1045 let (decl, lifetimes) = self.parse_ty_fn_decl(true);
1046 return TyBareFn(box(GC) BareFnTy {
1049 lifetimes: lifetimes,
1054 /// Parses a procedure type (`proc`). The initial `proc` keyword must
1055 /// already have been parsed.
1056 pub fn parse_proc_type(&mut self) -> Ty_ {
1059 proc <'lt> (S) [:Bounds] -> T
1060 ^~~^ ^~~~^ ^ ^~~~~~~~^ ^
1070 let lifetime_defs = if self.eat(&token::LT) {
1071 let lifetime_defs = self.parse_lifetime_defs();
1078 let (inputs, variadic) = self.parse_fn_args(false, false);
1079 let bounds = self.parse_colon_then_ty_param_bounds();
1080 let (ret_style, ret_ty) = self.parse_ret_ty();
1081 let decl = P(FnDecl {
1087 TyProc(box(GC) ClosureTy {
1092 lifetimes: lifetime_defs,
1096 /// Parses an optional unboxed closure kind (`&:`, `&mut:`, or `:`).
1097 pub fn parse_optional_unboxed_closure_kind(&mut self)
1098 -> Option<UnboxedClosureKind> {
1099 if self.token == token::BINOP(token::AND) &&
1100 self.look_ahead(1, |t| {
1101 token::is_keyword(keywords::Mut, t)
1103 self.look_ahead(2, |t| *t == token::COLON) {
1107 return Some(FnMutUnboxedClosureKind)
1110 if self.token == token::BINOP(token::AND) &&
1111 self.look_ahead(1, |t| *t == token::COLON) {
1114 return Some(FnUnboxedClosureKind)
1117 if self.eat(&token::COLON) {
1118 return Some(FnOnceUnboxedClosureKind)
1124 /// Parse a TyClosure type
1125 pub fn parse_ty_closure(&mut self) -> Ty_ {
1128 [unsafe] [once] <'lt> |S| [:Bounds] -> T
1129 ^~~~~~~^ ^~~~~^ ^~~~^ ^ ^~~~~~~~^ ^
1131 | | | | | Return type
1132 | | | | Closure bounds
1133 | | | Argument types
1135 | Once-ness (a.k.a., affine)
1140 let fn_style = self.parse_unsafety();
1141 let onceness = if self.eat_keyword(keywords::Once) {Once} else {Many};
1143 let lifetime_defs = if self.eat(&token::LT) {
1144 let lifetime_defs = self.parse_lifetime_defs();
1152 let (optional_unboxed_closure_kind, inputs) = if self.eat(&token::OROR) {
1157 let optional_unboxed_closure_kind =
1158 self.parse_optional_unboxed_closure_kind();
1160 let inputs = self.parse_seq_to_before_or(
1162 |p| p.parse_arg_general(false));
1164 (optional_unboxed_closure_kind, inputs)
1167 let bounds = self.parse_colon_then_ty_param_bounds();
1169 let (return_style, output) = self.parse_ret_ty();
1170 let decl = P(FnDecl {
1177 match optional_unboxed_closure_kind {
1178 Some(unboxed_closure_kind) => {
1179 TyUnboxedFn(box(GC) UnboxedFnTy {
1180 kind: unboxed_closure_kind,
1185 TyClosure(box(GC) ClosureTy {
1190 lifetimes: lifetime_defs,
1196 pub fn parse_unsafety(&mut self) -> FnStyle {
1197 if self.eat_keyword(keywords::Unsafe) {
1204 /// Parse a function type (following the 'fn')
1205 pub fn parse_ty_fn_decl(&mut self, allow_variadic: bool)
1206 -> (P<FnDecl>, Vec<ast::LifetimeDef>) {
1217 let lifetime_defs = if self.eat(&token::LT) {
1218 let lifetime_defs = self.parse_lifetime_defs();
1225 let (inputs, variadic) = self.parse_fn_args(false, allow_variadic);
1226 let (ret_style, ret_ty) = self.parse_ret_ty();
1227 let decl = P(FnDecl {
1233 (decl, lifetime_defs)
1236 /// Parse the methods in a trait declaration
1237 pub fn parse_trait_methods(&mut self) -> Vec<TraitItem> {
1238 self.parse_unspanned_seq(
1243 let attrs = p.parse_outer_attributes();
1246 // NB: at the moment, trait methods are public by default; this
1248 let vis = p.parse_visibility();
1249 let abi = if p.eat_keyword(keywords::Extern) {
1250 p.parse_opt_abi().unwrap_or(abi::C)
1251 } else if attr::contains_name(attrs.as_slice(),
1252 "rust_call_abi_hack") {
1253 // FIXME(stage0, pcwalton): Remove this awful hack after a
1254 // snapshot, and change to `extern "rust-call" fn`.
1259 let style = p.parse_fn_style();
1260 let ident = p.parse_ident();
1262 let mut generics = p.parse_generics();
1264 let (explicit_self, d) = p.parse_fn_decl_with_self(|p| {
1265 // This is somewhat dubious; We don't want to allow argument
1266 // names to be left off if there is a definition...
1267 p.parse_arg_general(false)
1270 p.parse_where_clause(&mut generics);
1272 let hi = p.last_span.hi;
1276 debug!("parse_trait_methods(): parsing required method");
1277 RequiredMethod(TypeMethod {
1284 explicit_self: explicit_self,
1285 id: ast::DUMMY_NODE_ID,
1286 span: mk_sp(lo, hi),
1291 debug!("parse_trait_methods(): parsing provided method");
1292 let (inner_attrs, body) =
1293 p.parse_inner_attrs_and_block();
1294 let attrs = attrs.append(inner_attrs.as_slice());
1295 ProvidedMethod(box(GC) ast::Method {
1297 id: ast::DUMMY_NODE_ID,
1298 span: mk_sp(lo, hi),
1299 node: ast::MethDecl(ident,
1311 let token_str = p.this_token_to_string();
1312 p.fatal((format!("expected `;` or `{{`, found `{}`",
1313 token_str)).as_slice())
1319 /// Parse a possibly mutable type
1320 pub fn parse_mt(&mut self) -> MutTy {
1321 let mutbl = self.parse_mutability();
1322 let t = self.parse_ty(true);
1323 MutTy { ty: t, mutbl: mutbl }
1326 /// Parse [mut/const/imm] ID : TY
1327 /// now used only by obsolete record syntax parser...
1328 pub fn parse_ty_field(&mut self) -> TypeField {
1329 let lo = self.span.lo;
1330 let mutbl = self.parse_mutability();
1331 let id = self.parse_ident();
1332 self.expect(&token::COLON);
1333 let ty = self.parse_ty(true);
1334 let hi = ty.span.hi;
1337 mt: MutTy { ty: ty, mutbl: mutbl },
1338 span: mk_sp(lo, hi),
1342 /// Parse optional return type [ -> TY ] in function decl
1343 pub fn parse_ret_ty(&mut self) -> (RetStyle, P<Ty>) {
1344 return if self.eat(&token::RARROW) {
1345 let lo = self.span.lo;
1346 if self.eat(&token::NOT) {
1350 id: ast::DUMMY_NODE_ID,
1352 span: mk_sp(lo, self.last_span.hi)
1356 (Return, self.parse_ty(true))
1359 let pos = self.span.lo;
1363 id: ast::DUMMY_NODE_ID,
1365 span: mk_sp(pos, pos),
1373 /// The second parameter specifies whether the `+` binary operator is
1374 /// allowed in the type grammar.
1375 pub fn parse_ty(&mut self, plus_allowed: bool) -> P<Ty> {
1376 maybe_whole!(no_clone self, NtTy);
1378 let lo = self.span.lo;
1380 let t = if self.token == token::LPAREN {
1382 if self.token == token::RPAREN {
1386 // (t) is a parenthesized ty
1387 // (t,) is the type of a tuple with only one field,
1389 let mut ts = vec!(self.parse_ty(true));
1390 let mut one_tuple = false;
1391 while self.token == token::COMMA {
1393 if self.token != token::RPAREN {
1394 ts.push(self.parse_ty(true));
1401 if ts.len() == 1 && !one_tuple {
1402 self.expect(&token::RPAREN);
1406 self.expect(&token::RPAREN);
1410 } else if self.token == token::AT {
1413 let span = self.last_span;
1414 self.obsolete(span, ObsoleteManagedType);
1415 TyBox(self.parse_ty(plus_allowed))
1416 } else if self.token == token::TILDE {
1419 let last_span = self.last_span;
1421 token::LBRACKET => self.obsolete(last_span, ObsoleteOwnedVector),
1422 _ => self.obsolete(last_span, ObsoleteOwnedType)
1424 TyUniq(self.parse_ty(false))
1425 } else if self.token == token::BINOP(token::STAR) {
1426 // STAR POINTER (bare pointer?)
1428 TyPtr(self.parse_ptr())
1429 } else if self.token == token::LBRACKET {
1431 self.expect(&token::LBRACKET);
1432 let t = self.parse_ty(true);
1434 // Parse the `, ..e` in `[ int, ..e ]`
1435 // where `e` is a const expression
1436 let t = match self.maybe_parse_fixed_vstore() {
1438 Some(suffix) => TyFixedLengthVec(t, suffix)
1440 self.expect(&token::RBRACKET);
1442 } else if self.token == token::BINOP(token::AND) ||
1443 self.token == token::ANDAND {
1446 self.parse_borrowed_pointee()
1447 } else if self.is_keyword(keywords::Extern) ||
1448 self.is_keyword(keywords::Unsafe) ||
1449 self.token_is_bare_fn_keyword() {
1451 self.parse_ty_bare_fn()
1452 } else if self.token_is_closure_keyword() ||
1453 self.token == token::BINOP(token::OR) ||
1454 self.token == token::OROR ||
1455 self.token == token::LT {
1458 // FIXME(pcwalton): Eventually `token::LT` will not unambiguously
1459 // introduce a closure, once procs can have lifetime bounds. We
1460 // will need to refactor the grammar a little bit at that point.
1462 self.parse_ty_closure()
1463 } else if self.eat_keyword(keywords::Typeof) {
1465 // In order to not be ambiguous, the type must be surrounded by parens.
1466 self.expect(&token::LPAREN);
1467 let e = self.parse_expr();
1468 self.expect(&token::RPAREN);
1470 } else if self.eat_keyword(keywords::Proc) {
1471 self.parse_proc_type()
1472 } else if self.token == token::MOD_SEP
1473 || is_ident_or_path(&self.token) {
1475 let mode = if plus_allowed {
1476 LifetimeAndTypesAndBounds
1478 LifetimeAndTypesWithoutColons
1483 } = self.parse_path(mode);
1484 TyPath(path, bounds, ast::DUMMY_NODE_ID)
1485 } else if self.eat(&token::UNDERSCORE) {
1486 // TYPE TO BE INFERRED
1489 let msg = format!("expected type, found token {:?}", self.token);
1490 self.fatal(msg.as_slice());
1493 let sp = mk_sp(lo, self.last_span.hi);
1494 P(Ty {id: ast::DUMMY_NODE_ID, node: t, span: sp})
1497 pub fn parse_borrowed_pointee(&mut self) -> Ty_ {
1498 // look for `&'lt` or `&'foo ` and interpret `foo` as the region name:
1499 let opt_lifetime = self.parse_opt_lifetime();
1501 let mt = self.parse_mt();
1502 return TyRptr(opt_lifetime, mt);
1505 pub fn parse_ptr(&mut self) -> MutTy {
1506 let mutbl = if self.eat_keyword(keywords::Mut) {
1508 } else if self.eat_keyword(keywords::Const) {
1511 let span = self.last_span;
1513 "bare raw pointers are no longer allowed, you should \
1514 likely use `*mut T`, but otherwise `*T` is now \
1515 known as `*const T`");
1518 let t = self.parse_ty(true);
1519 MutTy { ty: t, mutbl: mutbl }
1522 pub fn is_named_argument(&mut self) -> bool {
1523 let offset = match self.token {
1524 token::BINOP(token::AND) => 1,
1526 _ if token::is_keyword(keywords::Mut, &self.token) => 1,
1530 debug!("parser is_named_argument offset:{}", offset);
1533 is_plain_ident_or_underscore(&self.token)
1534 && self.look_ahead(1, |t| *t == token::COLON)
1536 self.look_ahead(offset, |t| is_plain_ident_or_underscore(t))
1537 && self.look_ahead(offset + 1, |t| *t == token::COLON)
1541 /// This version of parse arg doesn't necessarily require
1542 /// identifier names.
1543 pub fn parse_arg_general(&mut self, require_name: bool) -> Arg {
1544 let pat = if require_name || self.is_named_argument() {
1545 debug!("parse_arg_general parse_pat (require_name:{:?})",
1547 let pat = self.parse_pat();
1549 self.expect(&token::COLON);
1552 debug!("parse_arg_general ident_to_pat");
1553 ast_util::ident_to_pat(ast::DUMMY_NODE_ID,
1555 special_idents::invalid)
1558 let t = self.parse_ty(true);
1563 id: ast::DUMMY_NODE_ID,
1567 /// Parse a single function argument
1568 pub fn parse_arg(&mut self) -> Arg {
1569 self.parse_arg_general(true)
1572 /// Parse an argument in a lambda header e.g. |arg, arg|
1573 pub fn parse_fn_block_arg(&mut self) -> Arg {
1574 let pat = self.parse_pat();
1575 let t = if self.eat(&token::COLON) {
1579 id: ast::DUMMY_NODE_ID,
1581 span: mk_sp(self.span.lo, self.span.hi),
1587 id: ast::DUMMY_NODE_ID
1591 pub fn maybe_parse_fixed_vstore(&mut self) -> Option<Gc<ast::Expr>> {
1592 if self.token == token::COMMA &&
1593 self.look_ahead(1, |t| *t == token::DOTDOT) {
1596 Some(self.parse_expr())
1602 /// Matches token_lit = LIT_INTEGER | ...
1603 pub fn lit_from_token(&mut self, tok: &token::Token) -> Lit_ {
1605 token::LIT_BYTE(i) => LitByte(parse::byte_lit(i.as_str()).val0()),
1606 token::LIT_CHAR(i) => LitChar(parse::char_lit(i.as_str()).val0()),
1607 token::LIT_INTEGER(s) => parse::integer_lit(s.as_str(),
1608 &self.sess.span_diagnostic, self.span),
1609 token::LIT_FLOAT(s) => parse::float_lit(s.as_str()),
1610 token::LIT_STR(s) => {
1611 LitStr(token::intern_and_get_ident(parse::str_lit(s.as_str()).as_slice()),
1614 token::LIT_STR_RAW(s, n) => {
1615 LitStr(token::intern_and_get_ident(parse::raw_str_lit(s.as_str()).as_slice()),
1618 token::LIT_BINARY(i) =>
1619 LitBinary(parse::binary_lit(i.as_str())),
1620 token::LIT_BINARY_RAW(i, _) =>
1621 LitBinary(Rc::new(i.as_str().as_bytes().iter().map(|&x| x).collect())),
1622 token::LPAREN => { self.expect(&token::RPAREN); LitNil },
1623 _ => { self.unexpected_last(tok); }
1627 /// Matches lit = true | false | token_lit
1628 pub fn parse_lit(&mut self) -> Lit {
1629 let lo = self.span.lo;
1630 let lit = if self.eat_keyword(keywords::True) {
1632 } else if self.eat_keyword(keywords::False) {
1635 let token = self.bump_and_get();
1636 let lit = self.lit_from_token(&token);
1639 codemap::Spanned { node: lit, span: mk_sp(lo, self.last_span.hi) }
1642 /// matches '-' lit | lit
1643 pub fn parse_literal_maybe_minus(&mut self) -> Gc<Expr> {
1644 let minus_lo = self.span.lo;
1645 let minus_present = self.eat(&token::BINOP(token::MINUS));
1647 let lo = self.span.lo;
1648 let literal = box(GC) self.parse_lit();
1649 let hi = self.span.hi;
1650 let expr = self.mk_expr(lo, hi, ExprLit(literal));
1653 let minus_hi = self.span.hi;
1654 let unary = self.mk_unary(UnNeg, expr);
1655 self.mk_expr(minus_lo, minus_hi, unary)
1661 /// Parses a path and optional type parameter bounds, depending on the
1662 /// mode. The `mode` parameter determines whether lifetimes, types, and/or
1663 /// bounds are permitted and whether `::` must precede type parameter
1665 pub fn parse_path(&mut self, mode: PathParsingMode) -> PathAndBounds {
1666 // Check for a whole path...
1667 let found = match self.token {
1668 INTERPOLATED(token::NtPath(_)) => Some(self.bump_and_get()),
1672 Some(INTERPOLATED(token::NtPath(box path))) => {
1673 return PathAndBounds {
1681 let lo = self.span.lo;
1682 let is_global = self.eat(&token::MOD_SEP);
1684 // Parse any number of segments and bound sets. A segment is an
1685 // identifier followed by an optional lifetime and a set of types.
1686 // A bound set is a set of type parameter bounds.
1687 let mut segments = Vec::new();
1689 // First, parse an identifier.
1690 let identifier = self.parse_ident();
1692 // Parse the '::' before type parameters if it's required. If
1693 // it is required and wasn't present, then we're done.
1694 if mode == LifetimeAndTypesWithColons &&
1695 !self.eat(&token::MOD_SEP) {
1696 segments.push(ast::PathSegment {
1697 identifier: identifier,
1698 lifetimes: Vec::new(),
1699 types: OwnedSlice::empty(),
1704 // Parse the `<` before the lifetime and types, if applicable.
1705 let (any_lifetime_or_types, lifetimes, types) = {
1706 if mode != NoTypesAllowed && self.eat_lt(false) {
1707 let (lifetimes, types) =
1708 self.parse_generic_values_after_lt();
1709 (true, lifetimes, OwnedSlice::from_vec(types))
1711 (false, Vec::new(), OwnedSlice::empty())
1715 // Assemble and push the result.
1716 segments.push(ast::PathSegment {
1717 identifier: identifier,
1718 lifetimes: lifetimes,
1722 // We're done if we don't see a '::', unless the mode required
1723 // a double colon to get here in the first place.
1724 if !(mode == LifetimeAndTypesWithColons &&
1725 !any_lifetime_or_types) {
1726 if !self.eat(&token::MOD_SEP) {
1732 // Next, parse a plus and bounded type parameters, if
1733 // applicable. We need to remember whether the separate was
1734 // present for later, because in some contexts it's a parse
1737 if mode == LifetimeAndTypesAndBounds &&
1738 self.eat(&token::BINOP(token::PLUS))
1740 let bounds = self.parse_ty_param_bounds();
1742 // For some reason that I do not fully understand, we
1743 // do not permit an empty list in the case where it is
1744 // introduced by a `+`, but we do for `:` and other
1745 // separators. -nmatsakis
1746 if bounds.len() == 0 {
1747 let last_span = self.last_span;
1748 self.span_err(last_span,
1749 "at least one type parameter bound \
1750 must be specified");
1759 // Assemble the span.
1760 let span = mk_sp(lo, self.last_span.hi);
1762 // Assemble the result.
1773 /// parses 0 or 1 lifetime
1774 pub fn parse_opt_lifetime(&mut self) -> Option<ast::Lifetime> {
1776 token::LIFETIME(..) => {
1777 Some(self.parse_lifetime())
1785 /// Parses a single lifetime
1786 /// Matches lifetime = LIFETIME
1787 pub fn parse_lifetime(&mut self) -> ast::Lifetime {
1789 token::LIFETIME(i) => {
1790 let span = self.span;
1792 return ast::Lifetime {
1793 id: ast::DUMMY_NODE_ID,
1799 self.fatal(format!("expected a lifetime name").as_slice());
1804 pub fn parse_lifetime_defs(&mut self) -> Vec<ast::LifetimeDef> {
1806 * Parses `lifetime_defs = [ lifetime_defs { ',' lifetime_defs } ]`
1807 * where `lifetime_def = lifetime [':' lifetimes]`
1810 let mut res = Vec::new();
1813 token::LIFETIME(_) => {
1814 let lifetime = self.parse_lifetime();
1816 if self.eat(&token::COLON) {
1817 self.parse_lifetimes(token::BINOP(token::PLUS))
1821 res.push(ast::LifetimeDef { lifetime: lifetime,
1831 token::COMMA => { self.bump(); }
1832 token::GT => { return res; }
1833 token::BINOP(token::SHR) => { return res; }
1835 let msg = format!("expected `,` or `>` after lifetime \
1838 self.fatal(msg.as_slice());
1844 // matches lifetimes = ( lifetime ) | ( lifetime , lifetimes )
1845 // actually, it matches the empty one too, but putting that in there
1846 // messes up the grammar....
1847 pub fn parse_lifetimes(&mut self, sep: token::Token) -> Vec<ast::Lifetime> {
1849 * Parses zero or more comma separated lifetimes.
1850 * Expects each lifetime to be followed by either
1851 * a comma or `>`. Used when parsing type parameter
1852 * lists, where we expect something like `<'a, 'b, T>`.
1855 let mut res = Vec::new();
1858 token::LIFETIME(_) => {
1859 res.push(self.parse_lifetime());
1866 if self.token != sep {
1874 pub fn token_is_mutability(tok: &token::Token) -> bool {
1875 token::is_keyword(keywords::Mut, tok) ||
1876 token::is_keyword(keywords::Const, tok)
1879 /// Parse mutability declaration (mut/const/imm)
1880 pub fn parse_mutability(&mut self) -> Mutability {
1881 if self.eat_keyword(keywords::Mut) {
1888 /// Parse ident COLON expr
1889 pub fn parse_field(&mut self) -> Field {
1890 let lo = self.span.lo;
1891 let i = self.parse_ident();
1892 let hi = self.last_span.hi;
1893 self.expect(&token::COLON);
1894 let e = self.parse_expr();
1896 ident: spanned(lo, hi, i),
1898 span: mk_sp(lo, e.span.hi),
1902 pub fn mk_expr(&mut self, lo: BytePos, hi: BytePos, node: Expr_) -> Gc<Expr> {
1904 id: ast::DUMMY_NODE_ID,
1906 span: mk_sp(lo, hi),
1910 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: Gc<Expr>) -> ast::Expr_ {
1911 ExprUnary(unop, expr)
1914 pub fn mk_binary(&mut self, binop: ast::BinOp,
1915 lhs: Gc<Expr>, rhs: Gc<Expr>) -> ast::Expr_ {
1916 ExprBinary(binop, lhs, rhs)
1919 pub fn mk_call(&mut self, f: Gc<Expr>, args: Vec<Gc<Expr>>) -> ast::Expr_ {
1923 fn mk_method_call(&mut self,
1924 ident: ast::SpannedIdent,
1926 args: Vec<Gc<Expr>>)
1928 ExprMethodCall(ident, tps, args)
1931 pub fn mk_index(&mut self, expr: Gc<Expr>, idx: Gc<Expr>) -> ast::Expr_ {
1932 ExprIndex(expr, idx)
1935 pub fn mk_field(&mut self, expr: Gc<Expr>, ident: ast::SpannedIdent,
1936 tys: Vec<P<Ty>>) -> ast::Expr_ {
1937 ExprField(expr, ident, tys)
1940 pub fn mk_tup_field(&mut self, expr: Gc<Expr>, idx: codemap::Spanned<uint>,
1941 tys: Vec<P<Ty>>) -> ast::Expr_ {
1942 ExprTupField(expr, idx, tys)
1945 pub fn mk_assign_op(&mut self, binop: ast::BinOp,
1946 lhs: Gc<Expr>, rhs: Gc<Expr>) -> ast::Expr_ {
1947 ExprAssignOp(binop, lhs, rhs)
1950 pub fn mk_mac_expr(&mut self, lo: BytePos, hi: BytePos, m: Mac_) -> Gc<Expr> {
1952 id: ast::DUMMY_NODE_ID,
1953 node: ExprMac(codemap::Spanned {node: m, span: mk_sp(lo, hi)}),
1954 span: mk_sp(lo, hi),
1958 pub fn mk_lit_u32(&mut self, i: u32) -> Gc<Expr> {
1959 let span = &self.span;
1960 let lv_lit = box(GC) codemap::Spanned {
1961 node: LitInt(i as u64, ast::UnsignedIntLit(TyU32)),
1966 id: ast::DUMMY_NODE_ID,
1967 node: ExprLit(lv_lit),
1972 /// At the bottom (top?) of the precedence hierarchy,
1973 /// parse things like parenthesized exprs,
1974 /// macros, return, etc.
1975 pub fn parse_bottom_expr(&mut self) -> Gc<Expr> {
1976 maybe_whole_expr!(self);
1978 let lo = self.span.lo;
1979 let mut hi = self.span.hi;
1986 // (e) is parenthesized e
1987 // (e,) is a tuple with only one field, e
1988 let mut trailing_comma = false;
1989 if self.token == token::RPAREN {
1992 let lit = box(GC) spanned(lo, hi, LitNil);
1993 return self.mk_expr(lo, hi, ExprLit(lit));
1995 let mut es = vec!(self.parse_expr());
1996 self.commit_expr(*es.last().unwrap(), &[], &[token::COMMA, token::RPAREN]);
1997 while self.token == token::COMMA {
1999 if self.token != token::RPAREN {
2000 es.push(self.parse_expr());
2001 self.commit_expr(*es.last().unwrap(), &[], &[token::COMMA, token::RPAREN]);
2004 trailing_comma = true;
2008 self.commit_expr_expecting(*es.last().unwrap(), token::RPAREN);
2010 return if es.len() == 1 && !trailing_comma {
2011 self.mk_expr(lo, hi, ExprParen(*es.get(0)))
2014 self.mk_expr(lo, hi, ExprTup(es))
2019 let blk = self.parse_block_tail(lo, DefaultBlock);
2020 return self.mk_expr(blk.span.lo, blk.span.hi,
2023 token::BINOP(token::OR) | token::OROR => {
2024 return self.parse_lambda_expr(CaptureByValue);
2026 // FIXME #13626: Should be able to stick in
2027 // token::SELF_KEYWORD_NAME
2028 token::IDENT(id @ ast::Ident{
2029 name: ast::Name(token::SELF_KEYWORD_NAME_NUM),
2033 let path = ast_util::ident_to_path(mk_sp(lo, hi), id);
2034 ex = ExprPath(path);
2035 hi = self.last_span.hi;
2037 token::LBRACKET => {
2040 if self.token == token::RBRACKET {
2043 ex = ExprVec(Vec::new());
2046 let first_expr = self.parse_expr();
2047 if self.token == token::COMMA &&
2048 self.look_ahead(1, |t| *t == token::DOTDOT) {
2049 // Repeating vector syntax: [ 0, ..512 ]
2052 let count = self.parse_expr();
2053 self.expect(&token::RBRACKET);
2054 ex = ExprRepeat(first_expr, count);
2055 } else if self.token == token::COMMA {
2056 // Vector with two or more elements.
2058 let remaining_exprs = self.parse_seq_to_end(
2060 seq_sep_trailing_allowed(token::COMMA),
2063 let mut exprs = vec!(first_expr);
2064 exprs.push_all_move(remaining_exprs);
2065 ex = ExprVec(exprs);
2067 // Vector with one element.
2068 self.expect(&token::RBRACKET);
2069 ex = ExprVec(vec!(first_expr));
2072 hi = self.last_span.hi;
2075 if self.eat_keyword(keywords::Ref) {
2076 return self.parse_lambda_expr(CaptureByRef);
2078 if self.eat_keyword(keywords::Proc) {
2079 let decl = self.parse_proc_decl();
2080 let body = self.parse_expr();
2081 let fakeblock = P(ast::Block {
2082 view_items: Vec::new(),
2085 id: ast::DUMMY_NODE_ID,
2086 rules: DefaultBlock,
2089 return self.mk_expr(lo, body.span.hi, ExprProc(decl, fakeblock));
2091 if self.eat_keyword(keywords::If) {
2092 return self.parse_if_expr();
2094 if self.eat_keyword(keywords::For) {
2095 return self.parse_for_expr(None);
2097 if self.eat_keyword(keywords::While) {
2098 return self.parse_while_expr(None);
2100 if Parser::token_is_lifetime(&self.token) {
2101 let lifetime = self.get_lifetime();
2103 self.expect(&token::COLON);
2104 if self.eat_keyword(keywords::While) {
2105 return self.parse_while_expr(Some(lifetime))
2107 if self.eat_keyword(keywords::For) {
2108 return self.parse_for_expr(Some(lifetime))
2110 if self.eat_keyword(keywords::Loop) {
2111 return self.parse_loop_expr(Some(lifetime))
2113 self.fatal("expected `while`, `for`, or `loop` after a label")
2115 if self.eat_keyword(keywords::Loop) {
2116 return self.parse_loop_expr(None);
2118 if self.eat_keyword(keywords::Continue) {
2119 let lo = self.span.lo;
2120 let ex = if Parser::token_is_lifetime(&self.token) {
2121 let lifetime = self.get_lifetime();
2123 ExprAgain(Some(lifetime))
2127 let hi = self.span.hi;
2128 return self.mk_expr(lo, hi, ex);
2130 if self.eat_keyword(keywords::Match) {
2131 return self.parse_match_expr();
2133 if self.eat_keyword(keywords::Unsafe) {
2134 return self.parse_block_expr(
2136 UnsafeBlock(ast::UserProvided));
2138 if self.eat_keyword(keywords::Return) {
2139 // RETURN expression
2140 if can_begin_expr(&self.token) {
2141 let e = self.parse_expr();
2143 ex = ExprRet(Some(e));
2147 } else if self.eat_keyword(keywords::Break) {
2149 if Parser::token_is_lifetime(&self.token) {
2150 let lifetime = self.get_lifetime();
2152 ex = ExprBreak(Some(lifetime));
2154 ex = ExprBreak(None);
2157 } else if self.token == token::MOD_SEP ||
2158 is_ident(&self.token) &&
2159 !self.is_keyword(keywords::True) &&
2160 !self.is_keyword(keywords::False) {
2162 self.parse_path(LifetimeAndTypesWithColons).path;
2164 // `!`, as an operator, is prefix, so we know this isn't that
2165 if self.token == token::NOT {
2166 // MACRO INVOCATION expression
2169 let ket = token::close_delimiter_for(&self.token)
2170 .unwrap_or_else(|| {
2171 self.fatal("expected open delimiter")
2175 let tts = self.parse_seq_to_end(
2178 |p| p.parse_token_tree());
2179 let hi = self.span.hi;
2181 return self.mk_mac_expr(lo,
2187 if self.token == token::LBRACE {
2188 // This is a struct literal, unless we're prohibited
2189 // from parsing struct literals here.
2190 if self.restriction != RESTRICT_NO_STRUCT_LITERAL {
2191 // It's a struct literal.
2193 let mut fields = Vec::new();
2194 let mut base = None;
2196 while self.token != token::RBRACE {
2197 if self.eat(&token::DOTDOT) {
2198 base = Some(self.parse_expr());
2202 fields.push(self.parse_field());
2203 self.commit_expr(fields.last().unwrap().expr,
2208 if fields.len() == 0 && base.is_none() {
2209 let last_span = self.last_span;
2210 self.span_err(last_span,
2211 "structure literal must either \
2212 have at least one field or use \
2213 functional structure update \
2218 self.expect(&token::RBRACE);
2219 ex = ExprStruct(pth, fields, base);
2220 return self.mk_expr(lo, hi, ex);
2227 // other literal expression
2228 let lit = self.parse_lit();
2230 ex = ExprLit(box(GC) lit);
2235 return self.mk_expr(lo, hi, ex);
2238 /// Parse a block or unsafe block
2239 pub fn parse_block_expr(&mut self, lo: BytePos, blk_mode: BlockCheckMode)
2241 self.expect(&token::LBRACE);
2242 let blk = self.parse_block_tail(lo, blk_mode);
2243 return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk));
2246 /// parse a.b or a(13) or a[4] or just a
2247 pub fn parse_dot_or_call_expr(&mut self) -> Gc<Expr> {
2248 let b = self.parse_bottom_expr();
2249 self.parse_dot_or_call_expr_with(b)
2252 pub fn parse_dot_or_call_expr_with(&mut self, e0: Gc<Expr>) -> Gc<Expr> {
2258 if self.eat(&token::DOT) {
2260 token::IDENT(i, _) => {
2261 let dot = self.last_span.hi;
2264 let (_, tys) = if self.eat(&token::MOD_SEP) {
2266 self.parse_generic_values_after_lt()
2268 (Vec::new(), Vec::new())
2271 // expr.f() method call
2274 let mut es = self.parse_unspanned_seq(
2277 seq_sep_trailing_allowed(token::COMMA),
2280 hi = self.last_span.hi;
2283 let id = spanned(dot, hi, i);
2284 let nd = self.mk_method_call(id, tys, es);
2285 e = self.mk_expr(lo, hi, nd);
2288 let id = spanned(dot, hi, i);
2289 let field = self.mk_field(e, id, tys);
2290 e = self.mk_expr(lo, hi, field)
2294 token::LIT_INTEGER(n) => {
2295 let index = n.as_str();
2296 let dot = self.last_span.hi;
2299 let (_, tys) = if self.eat(&token::MOD_SEP) {
2301 self.parse_generic_values_after_lt()
2303 (Vec::new(), Vec::new())
2306 let num = from_str::<uint>(index);
2309 let id = spanned(dot, hi, n);
2310 let field = self.mk_tup_field(e, id, tys);
2311 e = self.mk_expr(lo, hi, field);
2314 let last_span = self.last_span;
2315 self.span_err(last_span, "invalid tuple or tuple struct index");
2319 token::LIT_FLOAT(n) => {
2321 let last_span = self.last_span;
2322 self.span_err(last_span,
2323 format!("unexpected token: `{}`", n.as_str()).as_slice());
2324 self.span_note(last_span,
2325 "try parenthesizing the first index; e.g., `(foo.0).1`");
2326 self.abort_if_errors();
2329 _ => self.unexpected()
2333 if self.expr_is_complete(e) { break; }
2337 let es = self.parse_unspanned_seq(
2340 seq_sep_trailing_allowed(token::COMMA),
2343 hi = self.last_span.hi;
2345 let nd = self.mk_call(e, es);
2346 e = self.mk_expr(lo, hi, nd);
2350 token::LBRACKET => {
2352 let ix = self.parse_expr();
2354 self.commit_expr_expecting(ix, token::RBRACKET);
2355 let index = self.mk_index(e, ix);
2356 e = self.mk_expr(lo, hi, index)
2365 /// Parse an optional separator followed by a kleene-style
2366 /// repetition token (+ or *).
2367 pub fn parse_sep_and_zerok(&mut self) -> (Option<token::Token>, bool) {
2368 fn parse_zerok(parser: &mut Parser) -> Option<bool> {
2369 match parser.token {
2370 token::BINOP(token::STAR) | token::BINOP(token::PLUS) => {
2371 let zerok = parser.token == token::BINOP(token::STAR);
2379 match parse_zerok(self) {
2380 Some(zerok) => return (None, zerok),
2384 let separator = self.bump_and_get();
2385 match parse_zerok(self) {
2386 Some(zerok) => (Some(separator), zerok),
2387 None => self.fatal("expected `*` or `+`")
2391 /// parse a single token tree from the input.
2392 pub fn parse_token_tree(&mut self) -> TokenTree {
2393 // FIXME #6994: currently, this is too eager. It
2394 // parses token trees but also identifies TTSeq's
2395 // and TTNonterminal's; it's too early to know yet
2396 // whether something will be a nonterminal or a seq
2398 maybe_whole!(deref self, NtTT);
2400 // this is the fall-through for the 'match' below.
2401 // invariants: the current token is not a left-delimiter,
2402 // not an EOF, and not the desired right-delimiter (if
2403 // it were, parse_seq_to_before_end would have prevented
2404 // reaching this point.
2405 fn parse_non_delim_tt_tok(p: &mut Parser) -> TokenTree {
2406 maybe_whole!(deref p, NtTT);
2408 token::RPAREN | token::RBRACE | token::RBRACKET => {
2409 // This is a conservative error: only report the last unclosed delimiter. The
2410 // previous unclosed delimiters could actually be closed! The parser just hasn't
2411 // gotten to them yet.
2412 match p.open_braces.last() {
2414 Some(&sp) => p.span_note(sp, "unclosed delimiter"),
2416 let token_str = p.this_token_to_string();
2417 p.fatal(format!("incorrect close delimiter: `{}`",
2418 token_str).as_slice())
2420 /* we ought to allow different depths of unquotation */
2421 token::DOLLAR if p.quote_depth > 0u => {
2425 if p.token == token::LPAREN {
2426 let seq = p.parse_seq(
2430 |p| p.parse_token_tree()
2432 let (s, z) = p.parse_sep_and_zerok();
2433 let seq = match seq {
2434 Spanned { node, .. } => node,
2436 TTSeq(mk_sp(sp.lo, p.span.hi), Rc::new(seq), s, z)
2438 TTNonterminal(sp, p.parse_ident())
2447 // turn the next token into a TTTok:
2448 fn parse_any_tt_tok(p: &mut Parser) -> TokenTree {
2449 TTTok(p.span, p.bump_and_get())
2452 match (&self.token, token::close_delimiter_for(&self.token)) {
2453 (&token::EOF, _) => {
2454 let open_braces = self.open_braces.clone();
2455 for sp in open_braces.iter() {
2456 self.span_note(*sp, "Did you mean to close this delimiter?");
2458 // There shouldn't really be a span, but it's easier for the test runner
2459 // if we give it one
2460 self.fatal("this file contains an un-closed delimiter ");
2462 (_, Some(close_delim)) => {
2463 // Parse the open delimiter.
2464 self.open_braces.push(self.span);
2465 let mut result = vec!(parse_any_tt_tok(self));
2468 self.parse_seq_to_before_end(&close_delim,
2470 |p| p.parse_token_tree());
2471 result.push_all_move(trees);
2473 // Parse the close delimiter.
2474 result.push(parse_any_tt_tok(self));
2475 self.open_braces.pop().unwrap();
2477 TTDelim(Rc::new(result))
2479 _ => parse_non_delim_tt_tok(self)
2483 // parse a stream of tokens into a list of TokenTree's,
2485 pub fn parse_all_token_trees(&mut self) -> Vec<TokenTree> {
2486 let mut tts = Vec::new();
2487 while self.token != token::EOF {
2488 tts.push(self.parse_token_tree());
2493 pub fn parse_matchers(&mut self) -> Vec<Matcher> {
2494 // unification of Matcher's and TokenTree's would vastly improve
2495 // the interpolation of Matcher's
2496 maybe_whole!(self, NtMatchers);
2497 let mut name_idx = 0u;
2498 match token::close_delimiter_for(&self.token) {
2499 Some(other_delimiter) => {
2501 self.parse_matcher_subseq_upto(&mut name_idx, &other_delimiter)
2503 None => self.fatal("expected open delimiter")
2507 /// This goofy function is necessary to correctly match parens in Matcher's.
2508 /// Otherwise, `$( ( )` would be a valid Matcher, and `$( () )` would be
2509 /// invalid. It's similar to common::parse_seq.
2510 pub fn parse_matcher_subseq_upto(&mut self,
2511 name_idx: &mut uint,
2514 let mut ret_val = Vec::new();
2515 let mut lparens = 0u;
2517 while self.token != *ket || lparens > 0u {
2518 if self.token == token::LPAREN { lparens += 1u; }
2519 if self.token == token::RPAREN { lparens -= 1u; }
2520 ret_val.push(self.parse_matcher(name_idx));
2528 pub fn parse_matcher(&mut self, name_idx: &mut uint) -> Matcher {
2529 let lo = self.span.lo;
2531 let m = if self.token == token::DOLLAR {
2533 if self.token == token::LPAREN {
2534 let name_idx_lo = *name_idx;
2536 let ms = self.parse_matcher_subseq_upto(name_idx,
2539 self.fatal("repetition body must be nonempty");
2541 let (sep, zerok) = self.parse_sep_and_zerok();
2542 MatchSeq(ms, sep, zerok, name_idx_lo, *name_idx)
2544 let bound_to = self.parse_ident();
2545 self.expect(&token::COLON);
2546 let nt_name = self.parse_ident();
2547 let m = MatchNonterminal(bound_to, nt_name, *name_idx);
2552 MatchTok(self.bump_and_get())
2555 return spanned(lo, self.span.hi, m);
2558 /// Parse a prefix-operator expr
2559 pub fn parse_prefix_expr(&mut self) -> Gc<Expr> {
2560 let lo = self.span.lo;
2567 let e = self.parse_prefix_expr();
2569 ex = self.mk_unary(UnNot, e);
2571 token::BINOP(token::MINUS) => {
2573 let e = self.parse_prefix_expr();
2575 ex = self.mk_unary(UnNeg, e);
2577 token::BINOP(token::STAR) => {
2579 let e = self.parse_prefix_expr();
2581 ex = self.mk_unary(UnDeref, e);
2583 token::BINOP(token::AND) | token::ANDAND => {
2585 let m = self.parse_mutability();
2586 let e = self.parse_prefix_expr();
2588 ex = ExprAddrOf(m, e);
2592 let span = self.last_span;
2593 self.obsolete(span, ObsoleteManagedExpr);
2594 let e = self.parse_prefix_expr();
2596 ex = self.mk_unary(UnBox, e);
2600 let last_span = self.last_span;
2602 token::LBRACKET => self.obsolete(last_span, ObsoleteOwnedVector),
2603 _ => self.obsolete(last_span, ObsoleteOwnedExpr)
2606 let e = self.parse_prefix_expr();
2608 ex = self.mk_unary(UnUniq, e);
2610 token::IDENT(_, _) => {
2611 if !self.is_keyword(keywords::Box) {
2612 return self.parse_dot_or_call_expr();
2617 // Check for a place: `box(PLACE) EXPR`.
2618 if self.eat(&token::LPAREN) {
2619 // Support `box() EXPR` as the default.
2620 if !self.eat(&token::RPAREN) {
2621 let place = self.parse_expr();
2622 self.expect(&token::RPAREN);
2623 let subexpression = self.parse_prefix_expr();
2624 hi = subexpression.span.hi;
2625 ex = ExprBox(place, subexpression);
2626 return self.mk_expr(lo, hi, ex);
2630 // Otherwise, we use the unique pointer default.
2631 let subexpression = self.parse_prefix_expr();
2632 hi = subexpression.span.hi;
2633 ex = self.mk_unary(UnUniq, subexpression);
2635 _ => return self.parse_dot_or_call_expr()
2637 return self.mk_expr(lo, hi, ex);
2640 /// Parse an expression of binops
2641 pub fn parse_binops(&mut self) -> Gc<Expr> {
2642 let prefix_expr = self.parse_prefix_expr();
2643 self.parse_more_binops(prefix_expr, 0)
2646 /// Parse an expression of binops of at least min_prec precedence
2647 pub fn parse_more_binops(&mut self, lhs: Gc<Expr>,
2648 min_prec: uint) -> Gc<Expr> {
2649 if self.expr_is_complete(lhs) { return lhs; }
2651 // Prevent dynamic borrow errors later on by limiting the
2652 // scope of the borrows.
2654 let token: &token::Token = &self.token;
2655 let restriction: &restriction = &self.restriction;
2656 match (token, restriction) {
2657 (&token::BINOP(token::OR), &RESTRICT_NO_BAR_OP) => return lhs,
2658 (&token::BINOP(token::OR),
2659 &RESTRICT_NO_BAR_OR_DOUBLEBAR_OP) => return lhs,
2660 (&token::OROR, &RESTRICT_NO_BAR_OR_DOUBLEBAR_OP) => return lhs,
2665 let cur_opt = token_to_binop(&self.token);
2668 let cur_prec = operator_prec(cur_op);
2669 if cur_prec > min_prec {
2671 let expr = self.parse_prefix_expr();
2672 let rhs = self.parse_more_binops(expr, cur_prec);
2673 let binary = self.mk_binary(cur_op, lhs, rhs);
2674 let bin = self.mk_expr(lhs.span.lo, rhs.span.hi, binary);
2675 self.parse_more_binops(bin, min_prec)
2681 if as_prec > min_prec && self.eat_keyword(keywords::As) {
2682 let rhs = self.parse_ty(false);
2683 let _as = self.mk_expr(lhs.span.lo,
2685 ExprCast(lhs, rhs));
2686 self.parse_more_binops(_as, min_prec)
2694 /// Parse an assignment expression....
2695 /// actually, this seems to be the main entry point for
2696 /// parsing an arbitrary expression.
2697 pub fn parse_assign_expr(&mut self) -> Gc<Expr> {
2698 let lo = self.span.lo;
2699 let lhs = self.parse_binops();
2703 let rhs = self.parse_expr();
2704 self.mk_expr(lo, rhs.span.hi, ExprAssign(lhs, rhs))
2706 token::BINOPEQ(op) => {
2708 let rhs = self.parse_expr();
2709 let aop = match op {
2710 token::PLUS => BiAdd,
2711 token::MINUS => BiSub,
2712 token::STAR => BiMul,
2713 token::SLASH => BiDiv,
2714 token::PERCENT => BiRem,
2715 token::CARET => BiBitXor,
2716 token::AND => BiBitAnd,
2717 token::OR => BiBitOr,
2718 token::SHL => BiShl,
2721 let assign_op = self.mk_assign_op(aop, lhs, rhs);
2722 self.mk_expr(lo, rhs.span.hi, assign_op)
2730 /// Parse an 'if' expression ('if' token already eaten)
2731 pub fn parse_if_expr(&mut self) -> Gc<Expr> {
2732 let lo = self.last_span.lo;
2733 let cond = self.parse_expr_res(RESTRICT_NO_STRUCT_LITERAL);
2734 let thn = self.parse_block();
2735 let mut els: Option<Gc<Expr>> = None;
2736 let mut hi = thn.span.hi;
2737 if self.eat_keyword(keywords::Else) {
2738 let elexpr = self.parse_else_expr();
2740 hi = elexpr.span.hi;
2742 self.mk_expr(lo, hi, ExprIf(cond, thn, els))
2746 pub fn parse_lambda_expr(&mut self, capture_clause: CaptureClause)
2748 let lo = self.span.lo;
2749 let (decl, optional_unboxed_closure_kind) =
2750 self.parse_fn_block_decl();
2751 let body = self.parse_expr();
2752 let fakeblock = P(ast::Block {
2753 view_items: Vec::new(),
2756 id: ast::DUMMY_NODE_ID,
2757 rules: DefaultBlock,
2761 match optional_unboxed_closure_kind {
2762 Some(unboxed_closure_kind) => {
2765 ExprUnboxedFn(capture_clause,
2766 unboxed_closure_kind,
2773 ExprFnBlock(capture_clause, decl, fakeblock))
2778 pub fn parse_else_expr(&mut self) -> Gc<Expr> {
2779 if self.eat_keyword(keywords::If) {
2780 return self.parse_if_expr();
2782 let blk = self.parse_block();
2783 return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk));
2787 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
2788 pub fn parse_for_expr(&mut self, opt_ident: Option<ast::Ident>) -> Gc<Expr> {
2789 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
2791 let lo = self.last_span.lo;
2792 let pat = self.parse_pat();
2793 self.expect_keyword(keywords::In);
2794 let expr = self.parse_expr_res(RESTRICT_NO_STRUCT_LITERAL);
2795 let loop_block = self.parse_block();
2796 let hi = self.span.hi;
2798 self.mk_expr(lo, hi, ExprForLoop(pat, expr, loop_block, opt_ident))
2801 pub fn parse_while_expr(&mut self, opt_ident: Option<ast::Ident>) -> Gc<Expr> {
2802 let lo = self.last_span.lo;
2803 let cond = self.parse_expr_res(RESTRICT_NO_STRUCT_LITERAL);
2804 let body = self.parse_block();
2805 let hi = body.span.hi;
2806 return self.mk_expr(lo, hi, ExprWhile(cond, body, opt_ident));
2809 pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::Ident>) -> Gc<Expr> {
2810 let lo = self.last_span.lo;
2811 let body = self.parse_block();
2812 let hi = body.span.hi;
2813 self.mk_expr(lo, hi, ExprLoop(body, opt_ident))
2816 fn parse_match_expr(&mut self) -> Gc<Expr> {
2817 let lo = self.last_span.lo;
2818 let discriminant = self.parse_expr_res(RESTRICT_NO_STRUCT_LITERAL);
2819 self.commit_expr_expecting(discriminant, token::LBRACE);
2820 let mut arms: Vec<Arm> = Vec::new();
2821 while self.token != token::RBRACE {
2822 arms.push(self.parse_arm());
2824 let hi = self.span.hi;
2826 return self.mk_expr(lo, hi, ExprMatch(discriminant, arms));
2829 pub fn parse_arm(&mut self) -> Arm {
2830 let attrs = self.parse_outer_attributes();
2831 let pats = self.parse_pats();
2832 let mut guard = None;
2833 if self.eat_keyword(keywords::If) {
2834 guard = Some(self.parse_expr());
2836 self.expect(&token::FAT_ARROW);
2837 let expr = self.parse_expr_res(RESTRICT_STMT_EXPR);
2840 !classify::expr_is_simple_block(expr)
2841 && self.token != token::RBRACE;
2844 self.commit_expr(expr, &[token::COMMA], &[token::RBRACE]);
2846 self.eat(&token::COMMA);
2857 /// Parse an expression
2858 pub fn parse_expr(&mut self) -> Gc<Expr> {
2859 return self.parse_expr_res(UNRESTRICTED);
2862 /// Parse an expression, subject to the given restriction
2863 pub fn parse_expr_res(&mut self, r: restriction) -> Gc<Expr> {
2864 let old = self.restriction;
2865 self.restriction = r;
2866 let e = self.parse_assign_expr();
2867 self.restriction = old;
2871 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
2872 fn parse_initializer(&mut self) -> Option<Gc<Expr>> {
2873 if self.token == token::EQ {
2875 Some(self.parse_expr())
2881 /// Parse patterns, separated by '|' s
2882 fn parse_pats(&mut self) -> Vec<Gc<Pat>> {
2883 let mut pats = Vec::new();
2885 pats.push(self.parse_pat());
2886 if self.token == token::BINOP(token::OR) { self.bump(); }
2887 else { return pats; }
2891 fn parse_pat_vec_elements(
2893 ) -> (Vec<Gc<Pat>> , Option<Gc<Pat>>, Vec<Gc<Pat>> ) {
2894 let mut before = Vec::new();
2895 let mut slice = None;
2896 let mut after = Vec::new();
2897 let mut first = true;
2898 let mut before_slice = true;
2900 while self.token != token::RBRACKET {
2904 self.expect(&token::COMMA);
2908 if self.token == token::DOTDOT {
2911 if self.token == token::COMMA ||
2912 self.token == token::RBRACKET {
2913 slice = Some(box(GC) ast::Pat {
2914 id: ast::DUMMY_NODE_ID,
2915 node: PatWild(PatWildMulti),
2918 before_slice = false;
2920 let _ = self.parse_pat();
2921 let span = self.span;
2922 self.obsolete(span, ObsoleteSubsliceMatch);
2928 let subpat = self.parse_pat();
2929 if before_slice && self.token == token::DOTDOT {
2931 slice = Some(subpat);
2932 before_slice = false;
2933 } else if before_slice {
2934 before.push(subpat);
2940 (before, slice, after)
2943 /// Parse the fields of a struct-like pattern
2944 fn parse_pat_fields(&mut self) -> (Vec<ast::FieldPat> , bool) {
2945 let mut fields = Vec::new();
2946 let mut etc = false;
2947 let mut first = true;
2948 while self.token != token::RBRACE {
2952 self.expect(&token::COMMA);
2953 // accept trailing commas
2954 if self.token == token::RBRACE { break }
2957 if self.token == token::DOTDOT {
2959 if self.token != token::RBRACE {
2960 let token_str = self.this_token_to_string();
2961 self.fatal(format!("expected `{}`, found `{}`", "}",
2962 token_str).as_slice())
2968 let bind_type = if self.eat_keyword(keywords::Mut) {
2969 BindByValue(MutMutable)
2970 } else if self.eat_keyword(keywords::Ref) {
2971 BindByRef(self.parse_mutability())
2973 BindByValue(MutImmutable)
2976 let fieldname = self.parse_ident();
2978 let subpat = if self.token == token::COLON {
2980 BindByRef(..) | BindByValue(MutMutable) => {
2981 let token_str = self.this_token_to_string();
2982 self.fatal(format!("unexpected `{}`",
2983 token_str).as_slice())
2991 let fieldpath = codemap::Spanned{span:self.last_span, node: fieldname};
2993 id: ast::DUMMY_NODE_ID,
2994 node: PatIdent(bind_type, fieldpath, None),
2995 span: self.last_span
2998 fields.push(ast::FieldPat { ident: fieldname, pat: subpat });
3000 return (fields, etc);
3003 /// Parse a pattern.
3004 pub fn parse_pat(&mut self) -> Gc<Pat> {
3005 maybe_whole!(self, NtPat);
3007 let lo = self.span.lo;
3012 token::UNDERSCORE => {
3014 pat = PatWild(PatWildSingle);
3015 hi = self.last_span.hi;
3016 return box(GC) ast::Pat {
3017 id: ast::DUMMY_NODE_ID,
3025 let sub = self.parse_pat();
3027 let last_span = self.last_span;
3029 self.obsolete(last_span, ObsoleteOwnedPattern);
3030 return box(GC) ast::Pat {
3031 id: ast::DUMMY_NODE_ID,
3036 token::BINOP(token::AND) | token::ANDAND => {
3038 let lo = self.span.lo;
3040 let sub = self.parse_pat();
3041 pat = PatRegion(sub);
3042 hi = self.last_span.hi;
3043 return box(GC) ast::Pat {
3044 id: ast::DUMMY_NODE_ID,
3050 // parse (pat,pat,pat,...) as tuple
3052 if self.token == token::RPAREN {
3055 let lit = box(GC) codemap::Spanned {
3057 span: mk_sp(lo, hi)};
3058 let expr = self.mk_expr(lo, hi, ExprLit(lit));
3061 let mut fields = vec!(self.parse_pat());
3062 if self.look_ahead(1, |t| *t != token::RPAREN) {
3063 while self.token == token::COMMA {
3065 if self.token == token::RPAREN { break; }
3066 fields.push(self.parse_pat());
3069 if fields.len() == 1 { self.expect(&token::COMMA); }
3070 self.expect(&token::RPAREN);
3071 pat = PatTup(fields);
3073 hi = self.last_span.hi;
3074 return box(GC) ast::Pat {
3075 id: ast::DUMMY_NODE_ID,
3080 token::LBRACKET => {
3081 // parse [pat,pat,...] as vector pattern
3083 let (before, slice, after) =
3084 self.parse_pat_vec_elements();
3086 self.expect(&token::RBRACKET);
3087 pat = ast::PatVec(before, slice, after);
3088 hi = self.last_span.hi;
3089 return box(GC) ast::Pat {
3090 id: ast::DUMMY_NODE_ID,
3097 // at this point, token != _, ~, &, &&, (, [
3099 if (!is_ident_or_path(&self.token) && self.token != token::MOD_SEP)
3100 || self.is_keyword(keywords::True)
3101 || self.is_keyword(keywords::False) {
3102 // Parse an expression pattern or exp .. exp.
3104 // These expressions are limited to literals (possibly
3105 // preceded by unary-minus) or identifiers.
3106 let val = self.parse_literal_maybe_minus();
3107 if self.token == token::DOTDOT &&
3108 self.look_ahead(1, |t| {
3109 *t != token::COMMA && *t != token::RBRACKET
3112 let end = if is_ident_or_path(&self.token) {
3113 let path = self.parse_path(LifetimeAndTypesWithColons)
3115 let hi = self.span.hi;
3116 self.mk_expr(lo, hi, ExprPath(path))
3118 self.parse_literal_maybe_minus()
3120 pat = PatRange(val, end);
3124 } else if self.eat_keyword(keywords::Mut) {
3125 pat = self.parse_pat_ident(BindByValue(MutMutable));
3126 } else if self.eat_keyword(keywords::Ref) {
3128 let mutbl = self.parse_mutability();
3129 pat = self.parse_pat_ident(BindByRef(mutbl));
3130 } else if self.eat_keyword(keywords::Box) {
3133 // FIXME(#13910): Rename to `PatBox` and extend to full DST
3135 let sub = self.parse_pat();
3137 hi = self.last_span.hi;
3138 return box(GC) ast::Pat {
3139 id: ast::DUMMY_NODE_ID,
3144 let can_be_enum_or_struct = self.look_ahead(1, |t| {
3146 token::LPAREN | token::LBRACKET | token::LT |
3147 token::LBRACE | token::MOD_SEP => true,
3152 if self.look_ahead(1, |t| *t == token::DOTDOT) &&
3153 self.look_ahead(2, |t| {
3154 *t != token::COMMA && *t != token::RBRACKET
3156 let start = self.parse_expr_res(RESTRICT_NO_BAR_OP);
3157 self.eat(&token::DOTDOT);
3158 let end = self.parse_expr_res(RESTRICT_NO_BAR_OP);
3159 pat = PatRange(start, end);
3160 } else if is_plain_ident(&self.token) && !can_be_enum_or_struct {
3161 let id = self.parse_ident();
3162 let id_span = self.last_span;
3163 let pth1 = codemap::Spanned{span:id_span, node: id};
3164 if self.eat(&token::NOT) {
3166 let ket = token::close_delimiter_for(&self.token)
3167 .unwrap_or_else(|| self.fatal("expected open delimiter"));
3170 let tts = self.parse_seq_to_end(&ket,
3172 |p| p.parse_token_tree());
3174 let mac = MacInvocTT(ident_to_path(id_span,id), tts, EMPTY_CTXT);
3175 pat = ast::PatMac(codemap::Spanned {node: mac, span: self.span});
3177 let sub = if self.eat(&token::AT) {
3179 Some(self.parse_pat())
3184 pat = PatIdent(BindByValue(MutImmutable), pth1, sub);
3187 // parse an enum pat
3188 let enum_path = self.parse_path(LifetimeAndTypesWithColons)
3194 self.parse_pat_fields();
3196 pat = PatStruct(enum_path, fields, etc);
3199 let mut args: Vec<Gc<Pat>> = Vec::new();
3202 let is_dotdot = self.look_ahead(1, |t| {
3204 token::DOTDOT => true,
3209 // This is a "top constructor only" pat
3212 self.expect(&token::RPAREN);
3213 pat = PatEnum(enum_path, None);
3215 args = self.parse_enum_variant_seq(
3218 seq_sep_trailing_allowed(token::COMMA),
3221 pat = PatEnum(enum_path, Some(args));
3225 if !enum_path.global &&
3226 enum_path.segments.len() == 1 &&
3235 // it could still be either an enum
3236 // or an identifier pattern, resolve
3237 // will sort it out:
3238 pat = PatIdent(BindByValue(MutImmutable),
3240 span: enum_path.span,
3241 node: enum_path.segments.get(0)
3245 pat = PatEnum(enum_path, Some(args));
3253 hi = self.last_span.hi;
3255 id: ast::DUMMY_NODE_ID,
3257 span: mk_sp(lo, hi),
3261 /// Parse ident or ident @ pat
3262 /// used by the copy foo and ref foo patterns to give a good
3263 /// error message when parsing mistakes like ref foo(a,b)
3264 fn parse_pat_ident(&mut self,
3265 binding_mode: ast::BindingMode)
3267 if !is_plain_ident(&self.token) {
3268 let last_span = self.last_span;
3269 self.span_fatal(last_span,
3270 "expected identifier, found path");
3272 let ident = self.parse_ident();
3273 let last_span = self.last_span;
3274 let name = codemap::Spanned{span: last_span, node: ident};
3275 let sub = if self.eat(&token::AT) {
3276 Some(self.parse_pat())
3281 // just to be friendly, if they write something like
3283 // we end up here with ( as the current token. This shortly
3284 // leads to a parse error. Note that if there is no explicit
3285 // binding mode then we do not end up here, because the lookahead
3286 // will direct us over to parse_enum_variant()
3287 if self.token == token::LPAREN {
3288 let last_span = self.last_span;
3291 "expected identifier, found enum pattern");
3294 PatIdent(binding_mode, name, sub)
3297 /// Parse a local variable declaration
3298 fn parse_local(&mut self) -> Gc<Local> {
3299 let lo = self.span.lo;
3300 let pat = self.parse_pat();
3303 id: ast::DUMMY_NODE_ID,
3305 span: mk_sp(lo, lo),
3307 if self.eat(&token::COLON) {
3308 ty = self.parse_ty(true);
3310 let init = self.parse_initializer();
3311 box(GC) ast::Local {
3315 id: ast::DUMMY_NODE_ID,
3316 span: mk_sp(lo, self.last_span.hi),
3321 /// Parse a "let" stmt
3322 fn parse_let(&mut self) -> Gc<Decl> {
3323 let lo = self.span.lo;
3324 let local = self.parse_local();
3325 box(GC) spanned(lo, self.last_span.hi, DeclLocal(local))
3328 /// Parse a structure field
3329 fn parse_name_and_ty(&mut self, pr: Visibility,
3330 attrs: Vec<Attribute> ) -> StructField {
3331 let lo = self.span.lo;
3332 if !is_plain_ident(&self.token) {
3333 self.fatal("expected ident");
3335 let name = self.parse_ident();
3336 self.expect(&token::COLON);
3337 let ty = self.parse_ty(true);
3338 spanned(lo, self.last_span.hi, ast::StructField_ {
3339 kind: NamedField(name, pr),
3340 id: ast::DUMMY_NODE_ID,
3346 /// Parse a statement. may include decl.
3347 /// Precondition: any attributes are parsed already
3348 pub fn parse_stmt(&mut self, item_attrs: Vec<Attribute>) -> Gc<Stmt> {
3349 maybe_whole!(self, NtStmt);
3351 fn check_expected_item(p: &mut Parser, found_attrs: bool) {
3352 // If we have attributes then we should have an item
3354 let last_span = p.last_span;
3355 p.span_err(last_span, "expected item after attributes");
3359 let lo = self.span.lo;
3360 if self.is_keyword(keywords::Let) {
3361 check_expected_item(self, !item_attrs.is_empty());
3362 self.expect_keyword(keywords::Let);
3363 let decl = self.parse_let();
3364 return box(GC) spanned(lo, decl.span.hi, StmtDecl(decl, ast::DUMMY_NODE_ID));
3365 } else if is_ident(&self.token)
3366 && !token::is_any_keyword(&self.token)
3367 && self.look_ahead(1, |t| *t == token::NOT) {
3368 // it's a macro invocation:
3370 check_expected_item(self, !item_attrs.is_empty());
3372 // Potential trouble: if we allow macros with paths instead of
3373 // idents, we'd need to look ahead past the whole path here...
3374 let pth = self.parse_path(NoTypesAllowed).path;
3377 let id = if token::close_delimiter_for(&self.token).is_some() {
3378 token::special_idents::invalid // no special identifier
3383 // check that we're pointing at delimiters (need to check
3384 // again after the `if`, because of `parse_ident`
3385 // consuming more tokens).
3386 let (bra, ket) = match token::close_delimiter_for(&self.token) {
3387 Some(ket) => (self.token.clone(), ket),
3389 // we only expect an ident if we didn't parse one
3391 let ident_str = if id.name == token::special_idents::invalid.name {
3396 let tok_str = self.this_token_to_string();
3397 self.fatal(format!("expected {}`(` or `{{`, found `{}`",
3399 tok_str).as_slice())
3403 let tts = self.parse_unspanned_seq(
3407 |p| p.parse_token_tree()
3409 let hi = self.span.hi;
3411 if id.name == token::special_idents::invalid.name {
3412 return box(GC) spanned(lo, hi, StmtMac(
3413 spanned(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT)), false));
3415 // if it has a special ident, it's definitely an item
3416 return box(GC) spanned(lo, hi, StmtDecl(
3417 box(GC) spanned(lo, hi, DeclItem(
3419 lo, hi, id /*id is good here*/,
3420 ItemMac(spanned(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT))),
3421 Inherited, Vec::new(/*no attrs*/)))),
3422 ast::DUMMY_NODE_ID));
3426 let found_attrs = !item_attrs.is_empty();
3427 match self.parse_item_or_view_item(item_attrs, false) {
3430 let decl = box(GC) spanned(lo, hi, DeclItem(i));
3431 return box(GC) spanned(lo, hi, StmtDecl(decl, ast::DUMMY_NODE_ID));
3433 IoviViewItem(vi) => {
3434 self.span_fatal(vi.span,
3435 "view items must be declared at the top of the block");
3437 IoviForeignItem(_) => {
3438 self.fatal("foreign items are not allowed here");
3440 IoviNone(_) => { /* fallthrough */ }
3443 check_expected_item(self, found_attrs);
3445 // Remainder are line-expr stmts.
3446 let e = self.parse_expr_res(RESTRICT_STMT_EXPR);
3447 return box(GC) spanned(lo, e.span.hi, StmtExpr(e, ast::DUMMY_NODE_ID));
3451 /// Is this expression a successfully-parsed statement?
3452 fn expr_is_complete(&mut self, e: Gc<Expr>) -> bool {
3453 return self.restriction == RESTRICT_STMT_EXPR &&
3454 !classify::expr_requires_semi_to_be_stmt(e);
3457 /// Parse a block. No inner attrs are allowed.
3458 pub fn parse_block(&mut self) -> P<Block> {
3459 maybe_whole!(no_clone self, NtBlock);
3461 let lo = self.span.lo;
3462 self.expect(&token::LBRACE);
3464 return self.parse_block_tail_(lo, DefaultBlock, Vec::new());
3467 /// Parse a block. Inner attrs are allowed.
3468 fn parse_inner_attrs_and_block(&mut self)
3469 -> (Vec<Attribute> , P<Block>) {
3471 maybe_whole!(pair_empty self, NtBlock);
3473 let lo = self.span.lo;
3474 self.expect(&token::LBRACE);
3475 let (inner, next) = self.parse_inner_attrs_and_next();
3477 (inner, self.parse_block_tail_(lo, DefaultBlock, next))
3480 /// Precondition: already parsed the '{' or '#{'
3481 /// I guess that also means "already parsed the 'impure'" if
3482 /// necessary, and this should take a qualifier.
3483 /// Some blocks start with "#{"...
3484 fn parse_block_tail(&mut self, lo: BytePos, s: BlockCheckMode) -> P<Block> {
3485 self.parse_block_tail_(lo, s, Vec::new())
3488 /// Parse the rest of a block expression or function body
3489 fn parse_block_tail_(&mut self, lo: BytePos, s: BlockCheckMode,
3490 first_item_attrs: Vec<Attribute> ) -> P<Block> {
3491 let mut stmts = Vec::new();
3492 let mut expr = None;
3494 // wouldn't it be more uniform to parse view items only, here?
3495 let ParsedItemsAndViewItems {
3496 attrs_remaining: attrs_remaining,
3497 view_items: view_items,
3500 } = self.parse_items_and_view_items(first_item_attrs,
3503 for item in items.iter() {
3504 let decl = box(GC) spanned(item.span.lo, item.span.hi, DeclItem(*item));
3505 stmts.push(box(GC) spanned(item.span.lo, item.span.hi,
3506 StmtDecl(decl, ast::DUMMY_NODE_ID)));
3509 let mut attributes_box = attrs_remaining;
3511 while self.token != token::RBRACE {
3512 // parsing items even when they're not allowed lets us give
3513 // better error messages and recover more gracefully.
3514 attributes_box.push_all(self.parse_outer_attributes().as_slice());
3517 if !attributes_box.is_empty() {
3518 let last_span = self.last_span;
3519 self.span_err(last_span, "expected item after attributes");
3520 attributes_box = Vec::new();
3522 self.bump(); // empty
3525 // fall through and out.
3528 let stmt = self.parse_stmt(attributes_box);
3529 attributes_box = Vec::new();
3531 StmtExpr(e, stmt_id) => {
3532 // expression without semicolon
3533 if classify::stmt_ends_with_semi(&*stmt) {
3534 // Just check for errors and recover; do not eat semicolon yet.
3535 self.commit_stmt(stmt, &[], &[token::SEMI, token::RBRACE]);
3541 let span_with_semi = Span {
3543 hi: self.last_span.hi,
3544 expn_info: stmt.span.expn_info,
3546 stmts.push(box(GC) codemap::Spanned {
3547 node: StmtSemi(e, stmt_id),
3548 span: span_with_semi,
3559 StmtMac(ref m, _) => {
3560 // statement macro; might be an expr
3564 stmts.push(box(GC) codemap::Spanned {
3565 node: StmtMac((*m).clone(), true),
3570 // if a block ends in `m!(arg)` without
3571 // a `;`, it must be an expr
3573 self.mk_mac_expr(stmt.span.lo,
3582 _ => { // all other kinds of statements:
3583 stmts.push(stmt.clone());
3585 if classify::stmt_ends_with_semi(&*stmt) {
3586 self.commit_stmt_expecting(stmt, token::SEMI);
3594 if !attributes_box.is_empty() {
3595 let last_span = self.last_span;
3596 self.span_err(last_span, "expected item after attributes");
3599 let hi = self.span.hi;
3602 view_items: view_items,
3605 id: ast::DUMMY_NODE_ID,
3607 span: mk_sp(lo, hi),
3611 fn parse_unboxed_function_type(&mut self) -> UnboxedFnTy {
3612 let (optional_unboxed_closure_kind, inputs) =
3613 if self.eat(&token::OROR) {
3618 let optional_unboxed_closure_kind =
3619 self.parse_optional_unboxed_closure_kind();
3621 let inputs = self.parse_seq_to_before_or(&token::COMMA,
3623 p.parse_arg_general(false)
3626 (optional_unboxed_closure_kind, inputs)
3629 let (return_style, output) = self.parse_ret_ty();
3637 kind: match optional_unboxed_closure_kind {
3639 None => FnMutUnboxedClosureKind,
3644 // Parses a sequence of bounds if a `:` is found,
3645 // otherwise returns empty list.
3646 fn parse_colon_then_ty_param_bounds(&mut self)
3647 -> OwnedSlice<TyParamBound>
3649 if !self.eat(&token::COLON) {
3652 self.parse_ty_param_bounds()
3656 // matches bounds = ( boundseq )?
3657 // where boundseq = ( bound + boundseq ) | bound
3658 // and bound = 'region | ty
3659 // NB: The None/Some distinction is important for issue #7264.
3660 fn parse_ty_param_bounds(&mut self)
3661 -> OwnedSlice<TyParamBound>
3663 let mut result = vec!();
3666 token::LIFETIME(lifetime) => {
3667 result.push(RegionTyParamBound(ast::Lifetime {
3668 id: ast::DUMMY_NODE_ID,
3674 token::MOD_SEP | token::IDENT(..) => {
3675 let tref = self.parse_trait_ref();
3676 result.push(TraitTyParamBound(tref));
3678 token::BINOP(token::OR) | token::OROR => {
3679 let unboxed_function_type =
3680 self.parse_unboxed_function_type();
3681 result.push(UnboxedFnTyParamBound(unboxed_function_type));
3686 if !self.eat(&token::BINOP(token::PLUS)) {
3691 return OwnedSlice::from_vec(result);
3694 fn trait_ref_from_ident(ident: Ident, span: Span) -> ast::TraitRef {
3695 let segment = ast::PathSegment {
3697 lifetimes: Vec::new(),
3698 types: OwnedSlice::empty(),
3700 let path = ast::Path {
3703 segments: vec![segment],
3707 ref_id: ast::DUMMY_NODE_ID,
3711 /// Matches typaram = (unbound`?`)? IDENT optbounds ( EQ ty )?
3712 fn parse_ty_param(&mut self) -> TyParam {
3713 // This is a bit hacky. Currently we are only interested in a single
3714 // unbound, and it may only be `Sized`. To avoid backtracking and other
3715 // complications, we parse an ident, then check for `?`. If we find it,
3716 // we use the ident as the unbound, otherwise, we use it as the name of
3718 let mut span = self.span;
3719 let mut ident = self.parse_ident();
3720 let mut unbound = None;
3721 if self.eat(&token::QUESTION) {
3722 let tref = Parser::trait_ref_from_ident(ident, span);
3723 unbound = Some(TraitTyParamBound(tref));
3725 ident = self.parse_ident();
3728 let bounds = self.parse_colon_then_ty_param_bounds();
3730 let default = if self.token == token::EQ {
3732 Some(self.parse_ty(true))
3738 id: ast::DUMMY_NODE_ID,
3746 /// Parse a set of optional generic type parameter declarations. Where
3747 /// clauses are not parsed here, and must be added later via
3748 /// `parse_where_clause()`.
3750 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
3751 /// | ( < lifetimes , typaramseq ( , )? > )
3752 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
3753 pub fn parse_generics(&mut self) -> ast::Generics {
3754 if self.eat(&token::LT) {
3755 let lifetime_defs = self.parse_lifetime_defs();
3756 let mut seen_default = false;
3757 let ty_params = self.parse_seq_to_gt(Some(token::COMMA), |p| {
3758 p.forbid_lifetime();
3759 let ty_param = p.parse_ty_param();
3760 if ty_param.default.is_some() {
3761 seen_default = true;
3762 } else if seen_default {
3763 let last_span = p.last_span;
3764 p.span_err(last_span,
3765 "type parameters with a default must be trailing");
3770 lifetimes: lifetime_defs,
3771 ty_params: ty_params,
3772 where_clause: WhereClause {
3773 id: ast::DUMMY_NODE_ID,
3774 predicates: Vec::new(),
3778 ast_util::empty_generics()
3782 fn parse_generic_values_after_lt(&mut self) -> (Vec<ast::Lifetime>, Vec<P<Ty>> ) {
3783 let lifetimes = self.parse_lifetimes(token::COMMA);
3784 let result = self.parse_seq_to_gt(
3787 p.forbid_lifetime();
3791 (lifetimes, result.into_vec())
3794 fn forbid_lifetime(&mut self) {
3795 if Parser::token_is_lifetime(&self.token) {
3796 let span = self.span;
3797 self.span_fatal(span, "lifetime parameters must be declared \
3798 prior to type parameters");
3802 /// Parses an optional `where` clause and places it in `generics`.
3803 fn parse_where_clause(&mut self, generics: &mut ast::Generics) {
3804 if !self.eat_keyword(keywords::Where) {
3808 let mut parsed_something = false;
3810 let lo = self.span.lo;
3811 let ident = match self.token {
3812 token::IDENT(..) => self.parse_ident(),
3815 self.expect(&token::COLON);
3817 let bounds = self.parse_ty_param_bounds();
3818 let hi = self.span.hi;
3819 let span = mk_sp(lo, hi);
3821 if bounds.len() == 0 {
3823 "each predicate in a `where` clause must have \
3824 at least one bound in it");
3827 generics.where_clause.predicates.push(ast::WherePredicate {
3828 id: ast::DUMMY_NODE_ID,
3833 parsed_something = true;
3835 if !self.eat(&token::COMMA) {
3840 if !parsed_something {
3841 let last_span = self.last_span;
3842 self.span_err(last_span,
3843 "a `where` clause must have at least one predicate \
3848 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
3849 -> (Vec<Arg> , bool) {
3851 let mut args: Vec<Option<Arg>> =
3852 self.parse_unspanned_seq(
3855 seq_sep_trailing_allowed(token::COMMA),
3857 if p.token == token::DOTDOTDOT {
3860 if p.token != token::RPAREN {
3863 "`...` must be last in argument list for variadic function");
3868 "only foreign functions are allowed to be variadic");
3872 Some(p.parse_arg_general(named_args))
3877 let variadic = match args.pop() {
3880 // Need to put back that last arg
3887 if variadic && args.is_empty() {
3889 "variadic function must be declared with at least one named argument");
3892 let args = args.move_iter().map(|x| x.unwrap()).collect();
3897 /// Parse the argument list and result type of a function declaration
3898 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> P<FnDecl> {
3900 let (args, variadic) = self.parse_fn_args(true, allow_variadic);
3901 let (ret_style, ret_ty) = self.parse_ret_ty();
3911 fn is_self_ident(&mut self) -> bool {
3913 token::IDENT(id, false) => id.name == special_idents::self_.name,
3918 fn expect_self_ident(&mut self) -> ast::Ident {
3920 token::IDENT(id, false) if id.name == special_idents::self_.name => {
3925 let token_str = self.this_token_to_string();
3926 self.fatal(format!("expected `self`, found `{}`",
3927 token_str).as_slice())
3932 /// Parse the argument list and result type of a function
3933 /// that may have a self type.
3934 fn parse_fn_decl_with_self(&mut self, parse_arg_fn: |&mut Parser| -> Arg)
3935 -> (ExplicitSelf, P<FnDecl>) {
3936 fn maybe_parse_borrowed_explicit_self(this: &mut Parser)
3937 -> ast::ExplicitSelf_ {
3938 // The following things are possible to see here:
3943 // fn(&'lt mut self)
3945 // We already know that the current token is `&`.
3947 if this.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) {
3949 SelfRegion(None, MutImmutable, this.expect_self_ident())
3950 } else if this.look_ahead(1, |t| Parser::token_is_mutability(t)) &&
3952 |t| token::is_keyword(keywords::Self,
3955 let mutability = this.parse_mutability();
3956 SelfRegion(None, mutability, this.expect_self_ident())
3957 } else if this.look_ahead(1, |t| Parser::token_is_lifetime(t)) &&
3959 |t| token::is_keyword(keywords::Self,
3962 let lifetime = this.parse_lifetime();
3963 SelfRegion(Some(lifetime), MutImmutable, this.expect_self_ident())
3964 } else if this.look_ahead(1, |t| Parser::token_is_lifetime(t)) &&
3965 this.look_ahead(2, |t| {
3966 Parser::token_is_mutability(t)
3968 this.look_ahead(3, |t| token::is_keyword(keywords::Self,
3971 let lifetime = this.parse_lifetime();
3972 let mutability = this.parse_mutability();
3973 SelfRegion(Some(lifetime), mutability, this.expect_self_ident())
3979 self.expect(&token::LPAREN);
3981 // A bit of complexity and lookahead is needed here in order to be
3982 // backwards compatible.
3983 let lo = self.span.lo;
3984 let mut mutbl_self = MutImmutable;
3985 let explicit_self = match self.token {
3986 token::BINOP(token::AND) => {
3987 maybe_parse_borrowed_explicit_self(self)
3990 // We need to make sure it isn't a type
3991 if self.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) {
3993 drop(self.expect_self_ident());
3994 let last_span = self.last_span;
3995 self.obsolete(last_span, ObsoleteOwnedSelf)
3999 token::BINOP(token::STAR) => {
4000 // Possibly "*self" or "*mut self" -- not supported. Try to avoid
4001 // emitting cryptic "unexpected token" errors.
4003 let _mutability = if Parser::token_is_mutability(&self.token) {
4004 self.parse_mutability()
4008 if self.is_self_ident() {
4009 let span = self.span;
4010 self.span_err(span, "cannot pass self by unsafe pointer");
4013 // error case, making bogus self ident:
4014 SelfValue(special_idents::self_)
4016 token::IDENT(..) => {
4017 if self.is_self_ident() {
4018 let self_ident = self.expect_self_ident();
4020 // Determine whether this is the fully explicit form, `self:
4022 if self.eat(&token::COLON) {
4023 SelfExplicit(self.parse_ty(false), self_ident)
4025 SelfValue(self_ident)
4027 } else if Parser::token_is_mutability(&self.token) &&
4028 self.look_ahead(1, |t| {
4029 token::is_keyword(keywords::Self, t)
4031 mutbl_self = self.parse_mutability();
4032 let self_ident = self.expect_self_ident();
4034 // Determine whether this is the fully explicit form,
4036 if self.eat(&token::COLON) {
4037 SelfExplicit(self.parse_ty(false), self_ident)
4039 SelfValue(self_ident)
4041 } else if Parser::token_is_mutability(&self.token) &&
4042 self.look_ahead(1, |t| *t == token::TILDE) &&
4043 self.look_ahead(2, |t| {
4044 token::is_keyword(keywords::Self, t)
4046 mutbl_self = self.parse_mutability();
4048 drop(self.expect_self_ident());
4049 let last_span = self.last_span;
4050 self.obsolete(last_span, ObsoleteOwnedSelf);
4059 let explicit_self_sp = mk_sp(lo, self.span.hi);
4061 // shared fall-through for the three cases below. borrowing prevents simply
4062 // writing this as a closure
4063 macro_rules! parse_remaining_arguments {
4066 // If we parsed a self type, expect a comma before the argument list.
4070 let sep = seq_sep_trailing_allowed(token::COMMA);
4071 let mut fn_inputs = self.parse_seq_to_before_end(
4076 fn_inputs.unshift(Arg::new_self(explicit_self_sp, mutbl_self, $self_id));
4080 vec!(Arg::new_self(explicit_self_sp, mutbl_self, $self_id))
4083 let token_str = self.this_token_to_string();
4084 self.fatal(format!("expected `,` or `)`, found `{}`",
4085 token_str).as_slice())
4091 let fn_inputs = match explicit_self {
4093 let sep = seq_sep_trailing_allowed(token::COMMA);
4094 self.parse_seq_to_before_end(&token::RPAREN, sep, parse_arg_fn)
4096 SelfValue(id) => parse_remaining_arguments!(id),
4097 SelfRegion(_,_,id) => parse_remaining_arguments!(id),
4098 SelfExplicit(_,id) => parse_remaining_arguments!(id),
4102 self.expect(&token::RPAREN);
4104 let hi = self.span.hi;
4106 let (ret_style, ret_ty) = self.parse_ret_ty();
4108 let fn_decl = P(FnDecl {
4115 (spanned(lo, hi, explicit_self), fn_decl)
4118 // parse the |arg, arg| header on a lambda
4119 fn parse_fn_block_decl(&mut self)
4120 -> (P<FnDecl>, Option<UnboxedClosureKind>) {
4121 let (optional_unboxed_closure_kind, inputs_captures) = {
4122 if self.eat(&token::OROR) {
4125 self.expect(&token::BINOP(token::OR));
4126 let optional_unboxed_closure_kind =
4127 self.parse_optional_unboxed_closure_kind();
4128 let args = self.parse_seq_to_before_end(
4129 &token::BINOP(token::OR),
4130 seq_sep_trailing_allowed(token::COMMA),
4131 |p| p.parse_fn_block_arg()
4134 (optional_unboxed_closure_kind, args)
4137 let output = if self.eat(&token::RARROW) {
4141 id: ast::DUMMY_NODE_ID,
4148 inputs: inputs_captures,
4152 }), optional_unboxed_closure_kind)
4155 /// Parses the `(arg, arg) -> return_type` header on a procedure.
4156 fn parse_proc_decl(&mut self) -> P<FnDecl> {
4158 self.parse_unspanned_seq(&token::LPAREN,
4160 seq_sep_trailing_allowed(token::COMMA),
4161 |p| p.parse_fn_block_arg());
4163 let output = if self.eat(&token::RARROW) {
4167 id: ast::DUMMY_NODE_ID,
4181 /// Parse the name and optional generic types of a function header.
4182 fn parse_fn_header(&mut self) -> (Ident, ast::Generics) {
4183 let id = self.parse_ident();
4184 let generics = self.parse_generics();
4188 fn mk_item(&mut self, lo: BytePos, hi: BytePos, ident: Ident,
4189 node: Item_, vis: Visibility,
4190 attrs: Vec<Attribute>) -> Gc<Item> {
4194 id: ast::DUMMY_NODE_ID,
4201 /// Parse an item-position function declaration.
4202 fn parse_item_fn(&mut self, fn_style: FnStyle, abi: abi::Abi) -> ItemInfo {
4203 let (ident, mut generics) = self.parse_fn_header();
4204 let decl = self.parse_fn_decl(false);
4205 self.parse_where_clause(&mut generics);
4206 let (inner_attrs, body) = self.parse_inner_attrs_and_block();
4207 (ident, ItemFn(decl, fn_style, abi, generics, body), Some(inner_attrs))
4210 /// Parse a method in a trait impl, starting with `attrs` attributes.
4211 pub fn parse_method(&mut self,
4212 already_parsed_attrs: Option<Vec<Attribute>>)
4214 let next_attrs = self.parse_outer_attributes();
4215 let attrs = match already_parsed_attrs {
4216 Some(mut a) => { a.push_all_move(next_attrs); a }
4220 let lo = self.span.lo;
4222 // code copied from parse_macro_use_or_failure... abstraction!
4223 let (method_, hi, new_attrs) = {
4224 if !token::is_any_keyword(&self.token)
4225 && self.look_ahead(1, |t| *t == token::NOT)
4226 && (self.look_ahead(2, |t| *t == token::LPAREN)
4227 || self.look_ahead(2, |t| *t == token::LBRACE)) {
4229 let pth = self.parse_path(NoTypesAllowed).path;
4230 self.expect(&token::NOT);
4232 // eat a matched-delimiter token tree:
4233 let tts = match token::close_delimiter_for(&self.token) {
4236 self.parse_seq_to_end(&ket,
4238 |p| p.parse_token_tree())
4240 None => self.fatal("expected open delimiter")
4242 let m_ = ast::MacInvocTT(pth, tts, EMPTY_CTXT);
4243 let m: ast::Mac = codemap::Spanned { node: m_,
4244 span: mk_sp(self.span.lo,
4246 (ast::MethMac(m), self.span.hi, attrs)
4248 let visa = self.parse_visibility();
4249 let abi = if self.eat_keyword(keywords::Extern) {
4250 self.parse_opt_abi().unwrap_or(abi::C)
4251 } else if attr::contains_name(attrs.as_slice(),
4252 "rust_call_abi_hack") {
4253 // FIXME(stage0, pcwalton): Remove this awful hack after a
4254 // snapshot, and change to `extern "rust-call" fn`.
4259 let fn_style = self.parse_fn_style();
4260 let ident = self.parse_ident();
4261 let mut generics = self.parse_generics();
4262 let (explicit_self, decl) = self.parse_fn_decl_with_self(|p| {
4265 self.parse_where_clause(&mut generics);
4266 let (inner_attrs, body) = self.parse_inner_attrs_and_block();
4267 let new_attrs = attrs.append(inner_attrs.as_slice());
4268 (ast::MethDecl(ident,
4276 body.span.hi, new_attrs)
4279 box(GC) ast::Method {
4281 id: ast::DUMMY_NODE_ID,
4282 span: mk_sp(lo, hi),
4287 /// Parse trait Foo { ... }
4288 fn parse_item_trait(&mut self) -> ItemInfo {
4289 let ident = self.parse_ident();
4290 let mut tps = self.parse_generics();
4291 let sized = self.parse_for_sized();
4293 // Parse supertrait bounds.
4294 let bounds = self.parse_colon_then_ty_param_bounds();
4296 self.parse_where_clause(&mut tps);
4298 let meths = self.parse_trait_methods();
4299 (ident, ItemTrait(tps, sized, bounds, meths), None)
4302 fn parse_impl_items(&mut self) -> (Vec<ImplItem>, Vec<Attribute>) {
4303 let mut impl_items = Vec::new();
4304 self.expect(&token::LBRACE);
4305 let (inner_attrs, next) = self.parse_inner_attrs_and_next();
4306 let mut method_attrs = Some(next);
4307 while !self.eat(&token::RBRACE) {
4308 impl_items.push(MethodImplItem(self.parse_method(method_attrs)));
4309 method_attrs = None;
4311 (impl_items, inner_attrs)
4314 /// Parses two variants (with the region/type params always optional):
4315 /// impl<T> Foo { ... }
4316 /// impl<T> ToString for ~[T] { ... }
4317 fn parse_item_impl(&mut self) -> ItemInfo {
4318 // First, parse type parameters if necessary.
4319 let mut generics = self.parse_generics();
4321 // Special case: if the next identifier that follows is '(', don't
4322 // allow this to be parsed as a trait.
4323 let could_be_trait = self.token != token::LPAREN;
4326 let mut ty = self.parse_ty(true);
4328 // Parse traits, if necessary.
4329 let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) {
4330 // New-style trait. Reinterpret the type as a trait.
4331 let opt_trait_ref = match ty.node {
4332 TyPath(ref path, None, node_id) => {
4333 Some(TraitRef { path: (*path).clone(),
4336 TyPath(_, Some(_), _) => {
4337 self.span_err(ty.span,
4338 "bounded traits are only valid in type position");
4342 self.span_err(ty.span, "not a trait");
4347 ty = self.parse_ty(true);
4353 self.parse_where_clause(&mut generics);
4354 let (impl_items, attrs) = self.parse_impl_items();
4356 let ident = ast_util::impl_pretty_name(&opt_trait, &*ty);
4359 ItemImpl(generics, opt_trait, ty, impl_items),
4363 /// Parse a::B<String,int>
4364 fn parse_trait_ref(&mut self) -> TraitRef {
4366 path: self.parse_path(LifetimeAndTypesWithoutColons).path,
4367 ref_id: ast::DUMMY_NODE_ID,
4371 /// Parse struct Foo { ... }
4372 fn parse_item_struct(&mut self, is_virtual: bool) -> ItemInfo {
4373 let class_name = self.parse_ident();
4374 let mut generics = self.parse_generics();
4376 let super_struct = if self.eat(&token::COLON) {
4377 let ty = self.parse_ty(true);
4379 TyPath(_, None, _) => {
4383 self.span_err(ty.span, "not a struct");
4391 self.parse_where_clause(&mut generics);
4393 let mut fields: Vec<StructField>;
4396 if self.eat(&token::LBRACE) {
4397 // It's a record-like struct.
4398 is_tuple_like = false;
4399 fields = Vec::new();
4400 while self.token != token::RBRACE {
4401 fields.push(self.parse_struct_decl_field());
4403 if fields.len() == 0 {
4404 self.fatal(format!("unit-like struct definition should be \
4405 written as `struct {};`",
4406 token::get_ident(class_name)).as_slice());
4409 } else if self.token == token::LPAREN {
4410 // It's a tuple-like struct.
4411 is_tuple_like = true;
4412 fields = self.parse_unspanned_seq(
4415 seq_sep_trailing_allowed(token::COMMA),
4417 let attrs = p.parse_outer_attributes();
4419 let struct_field_ = ast::StructField_ {
4420 kind: UnnamedField(p.parse_visibility()),
4421 id: ast::DUMMY_NODE_ID,
4422 ty: p.parse_ty(true),
4425 spanned(lo, p.span.hi, struct_field_)
4427 if fields.len() == 0 {
4428 self.fatal(format!("unit-like struct definition should be \
4429 written as `struct {};`",
4430 token::get_ident(class_name)).as_slice());
4432 self.expect(&token::SEMI);
4433 } else if self.eat(&token::SEMI) {
4434 // It's a unit-like struct.
4435 is_tuple_like = true;
4436 fields = Vec::new();
4438 let token_str = self.this_token_to_string();
4439 self.fatal(format!("expected `{}`, `(`, or `;` after struct \
4440 name, found `{}`", "{",
4441 token_str).as_slice())
4444 let _ = ast::DUMMY_NODE_ID; // FIXME: Workaround for crazy bug.
4445 let new_id = ast::DUMMY_NODE_ID;
4447 ItemStruct(box(GC) ast::StructDef {
4449 ctor_id: if is_tuple_like { Some(new_id) } else { None },
4450 super_struct: super_struct,
4451 is_virtual: is_virtual,
4456 /// Parse a structure field declaration
4457 pub fn parse_single_struct_field(&mut self,
4459 attrs: Vec<Attribute> )
4461 let a_var = self.parse_name_and_ty(vis, attrs);
4468 let span = self.span;
4469 let token_str = self.this_token_to_string();
4470 self.span_fatal(span,
4471 format!("expected `,`, or `}}`, found `{}`",
4472 token_str).as_slice())
4478 /// Parse an element of a struct definition
4479 fn parse_struct_decl_field(&mut self) -> StructField {
4481 let attrs = self.parse_outer_attributes();
4483 if self.eat_keyword(keywords::Pub) {
4484 return self.parse_single_struct_field(Public, attrs);
4487 return self.parse_single_struct_field(Inherited, attrs);
4490 /// Parse visibility: PUB, PRIV, or nothing
4491 fn parse_visibility(&mut self) -> Visibility {
4492 if self.eat_keyword(keywords::Pub) { Public }
4496 fn parse_for_sized(&mut self) -> Option<ast::TyParamBound> {
4497 if self.eat_keyword(keywords::For) {
4498 let span = self.span;
4499 let ident = self.parse_ident();
4500 if !self.eat(&token::QUESTION) {
4502 "expected 'Sized?' after `for` in trait item");
4505 let tref = Parser::trait_ref_from_ident(ident, span);
4506 Some(TraitTyParamBound(tref))
4512 /// Given a termination token and a vector of already-parsed
4513 /// attributes (of length 0 or 1), parse all of the items in a module
4514 fn parse_mod_items(&mut self,
4516 first_item_attrs: Vec<Attribute>,
4519 // parse all of the items up to closing or an attribute.
4520 // view items are legal here.
4521 let ParsedItemsAndViewItems {
4522 attrs_remaining: attrs_remaining,
4523 view_items: view_items,
4524 items: starting_items,
4526 } = self.parse_items_and_view_items(first_item_attrs, true, true);
4527 let mut items: Vec<Gc<Item>> = starting_items;
4528 let attrs_remaining_len = attrs_remaining.len();
4530 // don't think this other loop is even necessary....
4532 let mut first = true;
4533 while self.token != term {
4534 let mut attrs = self.parse_outer_attributes();
4536 attrs = attrs_remaining.clone().append(attrs.as_slice());
4539 debug!("parse_mod_items: parse_item_or_view_item(attrs={:?})",
4541 match self.parse_item_or_view_item(attrs,
4542 true /* macros allowed */) {
4543 IoviItem(item) => items.push(item),
4544 IoviViewItem(view_item) => {
4545 self.span_fatal(view_item.span,
4546 "view items must be declared at the top of \
4550 let token_str = self.this_token_to_string();
4551 self.fatal(format!("expected item, found `{}`",
4552 token_str).as_slice())
4557 if first && attrs_remaining_len > 0u {
4558 // We parsed attributes for the first item but didn't find it
4559 let last_span = self.last_span;
4560 self.span_err(last_span, "expected item after attributes");
4564 inner: mk_sp(inner_lo, self.span.lo),
4565 view_items: view_items,
4570 fn parse_item_const(&mut self) -> ItemInfo {
4571 let m = if self.eat_keyword(keywords::Mut) {MutMutable} else {MutImmutable};
4572 let id = self.parse_ident();
4573 self.expect(&token::COLON);
4574 let ty = self.parse_ty(true);
4575 self.expect(&token::EQ);
4576 let e = self.parse_expr();
4577 self.commit_expr_expecting(e, token::SEMI);
4578 (id, ItemStatic(ty, m, e), None)
4581 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
4582 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> ItemInfo {
4583 let id_span = self.span;
4584 let id = self.parse_ident();
4585 if self.token == token::SEMI {
4587 // This mod is in an external file. Let's go get it!
4588 let (m, attrs) = self.eval_src_mod(id, outer_attrs, id_span);
4589 (id, m, Some(attrs))
4591 self.push_mod_path(id, outer_attrs);
4592 self.expect(&token::LBRACE);
4593 let mod_inner_lo = self.span.lo;
4594 let old_owns_directory = self.owns_directory;
4595 self.owns_directory = true;
4596 let (inner, next) = self.parse_inner_attrs_and_next();
4597 let m = self.parse_mod_items(token::RBRACE, next, mod_inner_lo);
4598 self.expect(&token::RBRACE);
4599 self.owns_directory = old_owns_directory;
4600 self.pop_mod_path();
4601 (id, ItemMod(m), Some(inner))
4605 fn push_mod_path(&mut self, id: Ident, attrs: &[Attribute]) {
4606 let default_path = self.id_to_interned_str(id);
4607 let file_path = match ::attr::first_attr_value_str_by_name(attrs,
4610 None => default_path,
4612 self.mod_path_stack.push(file_path)
4615 fn pop_mod_path(&mut self) {
4616 self.mod_path_stack.pop().unwrap();
4619 /// Read a module from a source file.
4620 fn eval_src_mod(&mut self,
4622 outer_attrs: &[ast::Attribute],
4624 -> (ast::Item_, Vec<ast::Attribute> ) {
4625 let mut prefix = Path::new(self.sess.span_diagnostic.cm.span_to_filename(self.span));
4627 let mod_path = Path::new(".").join_many(self.mod_path_stack.as_slice());
4628 let dir_path = prefix.join(&mod_path);
4629 let mod_string = token::get_ident(id);
4630 let (file_path, owns_directory) = match ::attr::first_attr_value_str_by_name(
4631 outer_attrs, "path") {
4632 Some(d) => (dir_path.join(d), true),
4634 let mod_name = mod_string.get().to_string();
4635 let default_path_str = format!("{}.rs", mod_name);
4636 let secondary_path_str = format!("{}/mod.rs", mod_name);
4637 let default_path = dir_path.join(default_path_str.as_slice());
4638 let secondary_path = dir_path.join(secondary_path_str.as_slice());
4639 let default_exists = default_path.exists();
4640 let secondary_exists = secondary_path.exists();
4642 if !self.owns_directory {
4643 self.span_err(id_sp,
4644 "cannot declare a new module at this location");
4645 let this_module = match self.mod_path_stack.last() {
4646 Some(name) => name.get().to_string(),
4647 None => self.root_module_name.get_ref().clone(),
4649 self.span_note(id_sp,
4650 format!("maybe move this module `{0}` \
4651 to its own directory via \
4653 this_module).as_slice());
4654 if default_exists || secondary_exists {
4655 self.span_note(id_sp,
4656 format!("... or maybe `use` the module \
4657 `{}` instead of possibly \
4659 mod_name).as_slice());
4661 self.abort_if_errors();
4664 match (default_exists, secondary_exists) {
4665 (true, false) => (default_path, false),
4666 (false, true) => (secondary_path, true),
4668 self.span_fatal(id_sp,
4669 format!("file not found for module \
4671 mod_name).as_slice());
4676 format!("file for module `{}` found at both {} \
4680 secondary_path_str).as_slice());
4686 self.eval_src_mod_from_path(file_path, owns_directory,
4687 mod_string.get().to_string(), id_sp)
4690 fn eval_src_mod_from_path(&mut self,
4692 owns_directory: bool,
4694 id_sp: Span) -> (ast::Item_, Vec<ast::Attribute> ) {
4695 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
4696 match included_mod_stack.iter().position(|p| *p == path) {
4698 let mut err = String::from_str("circular modules: ");
4699 let len = included_mod_stack.len();
4700 for p in included_mod_stack.slice(i, len).iter() {
4701 err.push_str(p.display().as_maybe_owned().as_slice());
4702 err.push_str(" -> ");
4704 err.push_str(path.display().as_maybe_owned().as_slice());
4705 self.span_fatal(id_sp, err.as_slice());
4709 included_mod_stack.push(path.clone());
4710 drop(included_mod_stack);
4713 new_sub_parser_from_file(self.sess,
4719 let mod_inner_lo = p0.span.lo;
4720 let (mod_attrs, next) = p0.parse_inner_attrs_and_next();
4721 let first_item_outer_attrs = next;
4722 let m0 = p0.parse_mod_items(token::EOF, first_item_outer_attrs, mod_inner_lo);
4723 self.sess.included_mod_stack.borrow_mut().pop();
4724 return (ast::ItemMod(m0), mod_attrs);
4727 /// Parse a function declaration from a foreign module
4728 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility,
4729 attrs: Vec<Attribute>) -> Gc<ForeignItem> {
4730 let lo = self.span.lo;
4731 self.expect_keyword(keywords::Fn);
4733 let (ident, mut generics) = self.parse_fn_header();
4734 let decl = self.parse_fn_decl(true);
4735 self.parse_where_clause(&mut generics);
4736 let hi = self.span.hi;
4737 self.expect(&token::SEMI);
4738 box(GC) ast::ForeignItem { ident: ident,
4740 node: ForeignItemFn(decl, generics),
4741 id: ast::DUMMY_NODE_ID,
4742 span: mk_sp(lo, hi),
4746 /// Parse a static item from a foreign module
4747 fn parse_item_foreign_static(&mut self, vis: ast::Visibility,
4748 attrs: Vec<Attribute> ) -> Gc<ForeignItem> {
4749 let lo = self.span.lo;
4751 self.expect_keyword(keywords::Static);
4752 let mutbl = self.eat_keyword(keywords::Mut);
4754 let ident = self.parse_ident();
4755 self.expect(&token::COLON);
4756 let ty = self.parse_ty(true);
4757 let hi = self.span.hi;
4758 self.expect(&token::SEMI);
4759 box(GC) ast::ForeignItem {
4762 node: ForeignItemStatic(ty, mutbl),
4763 id: ast::DUMMY_NODE_ID,
4764 span: mk_sp(lo, hi),
4769 /// Parse safe/unsafe and fn
4770 fn parse_fn_style(&mut self) -> FnStyle {
4771 if self.eat_keyword(keywords::Fn) { NormalFn }
4772 else if self.eat_keyword(keywords::Unsafe) {
4773 self.expect_keyword(keywords::Fn);
4776 else { self.unexpected(); }
4780 /// At this point, this is essentially a wrapper for
4781 /// parse_foreign_items.
4782 fn parse_foreign_mod_items(&mut self,
4784 first_item_attrs: Vec<Attribute> )
4786 let ParsedItemsAndViewItems {
4787 attrs_remaining: attrs_remaining,
4788 view_items: view_items,
4790 foreign_items: foreign_items
4791 } = self.parse_foreign_items(first_item_attrs, true);
4792 if ! attrs_remaining.is_empty() {
4793 let last_span = self.last_span;
4794 self.span_err(last_span,
4795 "expected item after attributes");
4797 assert!(self.token == token::RBRACE);
4800 view_items: view_items,
4801 items: foreign_items
4805 /// Parse extern crate links
4809 /// extern crate url;
4810 /// extern crate foo = "bar"; //deprecated
4811 /// extern crate "bar" as foo;
4812 fn parse_item_extern_crate(&mut self,
4814 visibility: Visibility,
4815 attrs: Vec<Attribute> )
4818 let (maybe_path, ident) = match self.token {
4819 token::IDENT(..) => {
4820 let the_ident = self.parse_ident();
4821 self.expect_one_of(&[], &[token::EQ, token::SEMI]);
4822 let path = if self.token == token::EQ {
4824 let path = self.parse_str();
4825 let span = self.span;
4826 self.obsolete(span, ObsoleteExternCrateRenaming);
4830 self.expect(&token::SEMI);
4833 token::LIT_STR(..) | token::LIT_STR_RAW(..) => {
4834 let path = self.parse_str();
4835 self.expect_keyword(keywords::As);
4836 let the_ident = self.parse_ident();
4837 self.expect(&token::SEMI);
4838 (Some(path), the_ident)
4841 let span = self.span;
4842 let token_str = self.this_token_to_string();
4843 self.span_fatal(span,
4844 format!("expected extern crate name but \
4846 token_str).as_slice());
4850 IoviViewItem(ast::ViewItem {
4851 node: ViewItemExternCrate(ident, maybe_path, ast::DUMMY_NODE_ID),
4854 span: mk_sp(lo, self.last_span.hi)
4858 /// Parse `extern` for foreign ABIs
4861 /// `extern` is expected to have been
4862 /// consumed before calling this method
4868 fn parse_item_foreign_mod(&mut self,
4870 opt_abi: Option<abi::Abi>,
4871 visibility: Visibility,
4872 attrs: Vec<Attribute> )
4875 self.expect(&token::LBRACE);
4877 let abi = opt_abi.unwrap_or(abi::C);
4879 let (inner, next) = self.parse_inner_attrs_and_next();
4880 let m = self.parse_foreign_mod_items(abi, next);
4881 self.expect(&token::RBRACE);
4883 let last_span = self.last_span;
4884 let item = self.mk_item(lo,
4886 special_idents::invalid,
4889 maybe_append(attrs, Some(inner)));
4890 return IoviItem(item);
4893 /// Parse type Foo = Bar;
4894 fn parse_item_type(&mut self) -> ItemInfo {
4895 let ident = self.parse_ident();
4896 let mut tps = self.parse_generics();
4897 self.parse_where_clause(&mut tps);
4898 self.expect(&token::EQ);
4899 let ty = self.parse_ty(true);
4900 self.expect(&token::SEMI);
4901 (ident, ItemTy(ty, tps), None)
4904 /// Parse a structure-like enum variant definition
4905 /// this should probably be renamed or refactored...
4906 fn parse_struct_def(&mut self) -> Gc<StructDef> {
4907 let mut fields: Vec<StructField> = Vec::new();
4908 while self.token != token::RBRACE {
4909 fields.push(self.parse_struct_decl_field());
4913 return box(GC) ast::StructDef {
4921 /// Parse the part of an "enum" decl following the '{'
4922 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> EnumDef {
4923 let mut variants = Vec::new();
4924 let mut all_nullary = true;
4925 let mut have_disr = false;
4926 while self.token != token::RBRACE {
4927 let variant_attrs = self.parse_outer_attributes();
4928 let vlo = self.span.lo;
4930 let vis = self.parse_visibility();
4934 let mut args = Vec::new();
4935 let mut disr_expr = None;
4936 ident = self.parse_ident();
4937 if self.eat(&token::LBRACE) {
4938 // Parse a struct variant.
4939 all_nullary = false;
4940 kind = StructVariantKind(self.parse_struct_def());
4941 } else if self.token == token::LPAREN {
4942 all_nullary = false;
4943 let arg_tys = self.parse_enum_variant_seq(
4946 seq_sep_trailing_allowed(token::COMMA),
4947 |p| p.parse_ty(true)
4949 for ty in arg_tys.move_iter() {
4950 args.push(ast::VariantArg {
4952 id: ast::DUMMY_NODE_ID,
4955 kind = TupleVariantKind(args);
4956 } else if self.eat(&token::EQ) {
4958 disr_expr = Some(self.parse_expr());
4959 kind = TupleVariantKind(args);
4961 kind = TupleVariantKind(Vec::new());
4964 let vr = ast::Variant_ {
4966 attrs: variant_attrs,
4968 id: ast::DUMMY_NODE_ID,
4969 disr_expr: disr_expr,
4972 variants.push(P(spanned(vlo, self.last_span.hi, vr)));
4974 if !self.eat(&token::COMMA) { break; }
4976 self.expect(&token::RBRACE);
4977 if have_disr && !all_nullary {
4978 self.fatal("discriminator values can only be used with a c-like \
4982 ast::EnumDef { variants: variants }
4985 /// Parse an "enum" declaration
4986 fn parse_item_enum(&mut self) -> ItemInfo {
4987 let id = self.parse_ident();
4988 let mut generics = self.parse_generics();
4989 self.parse_where_clause(&mut generics);
4990 self.expect(&token::LBRACE);
4992 let enum_definition = self.parse_enum_def(&generics);
4993 (id, ItemEnum(enum_definition, generics), None)
4996 fn fn_expr_lookahead(tok: &token::Token) -> bool {
4998 token::LPAREN | token::AT | token::TILDE | token::BINOP(_) => true,
5003 /// Parses a string as an ABI spec on an extern type or module. Consumes
5004 /// the `extern` keyword, if one is found.
5005 fn parse_opt_abi(&mut self) -> Option<abi::Abi> {
5007 token::LIT_STR(s) | token::LIT_STR_RAW(s, _) => {
5009 let the_string = s.as_str();
5010 match abi::lookup(the_string) {
5011 Some(abi) => Some(abi),
5013 let last_span = self.last_span;
5016 format!("illegal ABI: expected one of [{}], \
5018 abi::all_names().connect(", "),
5019 the_string).as_slice());
5029 /// Parse one of the items or view items allowed by the
5030 /// flags; on failure, return IoviNone.
5031 /// NB: this function no longer parses the items inside an
5033 fn parse_item_or_view_item(&mut self,
5034 attrs: Vec<Attribute> ,
5035 macros_allowed: bool)
5038 INTERPOLATED(token::NtItem(item)) => {
5040 let new_attrs = attrs.append(item.attrs.as_slice());
5041 return IoviItem(box(GC) Item {
5049 let lo = self.span.lo;
5051 let visibility = self.parse_visibility();
5053 // must be a view item:
5054 if self.eat_keyword(keywords::Use) {
5055 // USE ITEM (IoviViewItem)
5056 let view_item = self.parse_use();
5057 self.expect(&token::SEMI);
5058 return IoviViewItem(ast::ViewItem {
5062 span: mk_sp(lo, self.last_span.hi)
5065 // either a view item or an item:
5066 if self.eat_keyword(keywords::Extern) {
5067 let next_is_mod = self.eat_keyword(keywords::Mod);
5069 if next_is_mod || self.eat_keyword(keywords::Crate) {
5071 let last_span = self.last_span;
5072 self.span_err(mk_sp(lo, last_span.hi),
5073 format!("`extern mod` is obsolete, use \
5074 `extern crate` instead \
5075 to refer to external \
5076 crates.").as_slice())
5078 return self.parse_item_extern_crate(lo, visibility, attrs);
5081 let opt_abi = self.parse_opt_abi();
5083 if self.eat_keyword(keywords::Fn) {
5084 // EXTERN FUNCTION ITEM
5085 let abi = opt_abi.unwrap_or(abi::C);
5086 let (ident, item_, extra_attrs) =
5087 self.parse_item_fn(NormalFn, abi);
5088 let last_span = self.last_span;
5089 let item = self.mk_item(lo,
5094 maybe_append(attrs, extra_attrs));
5095 return IoviItem(item);
5096 } else if self.token == token::LBRACE {
5097 return self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs);
5100 let span = self.span;
5101 let token_str = self.this_token_to_string();
5102 self.span_fatal(span,
5103 format!("expected `{}` or `fn`, found `{}`", "{",
5104 token_str).as_slice());
5107 let is_virtual = self.eat_keyword(keywords::Virtual);
5108 if is_virtual && !self.is_keyword(keywords::Struct) {
5109 let span = self.span;
5111 "`virtual` keyword may only be used with `struct`");
5114 // the rest are all guaranteed to be items:
5115 if self.is_keyword(keywords::Static) {
5118 let (ident, item_, extra_attrs) = self.parse_item_const();
5119 let last_span = self.last_span;
5120 let item = self.mk_item(lo,
5125 maybe_append(attrs, extra_attrs));
5126 return IoviItem(item);
5128 if self.is_keyword(keywords::Fn) &&
5129 self.look_ahead(1, |f| !Parser::fn_expr_lookahead(f)) {
5132 let (ident, item_, extra_attrs) =
5133 self.parse_item_fn(NormalFn, abi::Rust);
5134 let last_span = self.last_span;
5135 let item = self.mk_item(lo,
5140 maybe_append(attrs, extra_attrs));
5141 return IoviItem(item);
5143 if self.is_keyword(keywords::Unsafe)
5144 && self.look_ahead(1u, |t| *t != token::LBRACE) {
5145 // UNSAFE FUNCTION ITEM
5147 let abi = if self.eat_keyword(keywords::Extern) {
5148 self.parse_opt_abi().unwrap_or(abi::C)
5152 self.expect_keyword(keywords::Fn);
5153 let (ident, item_, extra_attrs) =
5154 self.parse_item_fn(UnsafeFn, abi);
5155 let last_span = self.last_span;
5156 let item = self.mk_item(lo,
5161 maybe_append(attrs, extra_attrs));
5162 return IoviItem(item);
5164 if self.eat_keyword(keywords::Mod) {
5166 let (ident, item_, extra_attrs) =
5167 self.parse_item_mod(attrs.as_slice());
5168 let last_span = self.last_span;
5169 let item = self.mk_item(lo,
5174 maybe_append(attrs, extra_attrs));
5175 return IoviItem(item);
5177 if self.eat_keyword(keywords::Type) {
5179 let (ident, item_, extra_attrs) = self.parse_item_type();
5180 let last_span = self.last_span;
5181 let item = self.mk_item(lo,
5186 maybe_append(attrs, extra_attrs));
5187 return IoviItem(item);
5189 if self.eat_keyword(keywords::Enum) {
5191 let (ident, item_, extra_attrs) = self.parse_item_enum();
5192 let last_span = self.last_span;
5193 let item = self.mk_item(lo,
5198 maybe_append(attrs, extra_attrs));
5199 return IoviItem(item);
5201 if self.eat_keyword(keywords::Trait) {
5203 let (ident, item_, extra_attrs) = self.parse_item_trait();
5204 let last_span = self.last_span;
5205 let item = self.mk_item(lo,
5210 maybe_append(attrs, extra_attrs));
5211 return IoviItem(item);
5213 if self.eat_keyword(keywords::Impl) {
5215 let (ident, item_, extra_attrs) = self.parse_item_impl();
5216 let last_span = self.last_span;
5217 let item = self.mk_item(lo,
5222 maybe_append(attrs, extra_attrs));
5223 return IoviItem(item);
5225 if self.eat_keyword(keywords::Struct) {
5227 let (ident, item_, extra_attrs) = self.parse_item_struct(is_virtual);
5228 let last_span = self.last_span;
5229 let item = self.mk_item(lo,
5234 maybe_append(attrs, extra_attrs));
5235 return IoviItem(item);
5237 self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility)
5240 /// Parse a foreign item; on failure, return IoviNone.
5241 fn parse_foreign_item(&mut self,
5242 attrs: Vec<Attribute> ,
5243 macros_allowed: bool)
5245 maybe_whole!(iovi self, NtItem);
5246 let lo = self.span.lo;
5248 let visibility = self.parse_visibility();
5250 if self.is_keyword(keywords::Static) {
5251 // FOREIGN STATIC ITEM
5252 let item = self.parse_item_foreign_static(visibility, attrs);
5253 return IoviForeignItem(item);
5255 if self.is_keyword(keywords::Fn) || self.is_keyword(keywords::Unsafe) {
5256 // FOREIGN FUNCTION ITEM
5257 let item = self.parse_item_foreign_fn(visibility, attrs);
5258 return IoviForeignItem(item);
5260 self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility)
5263 /// This is the fall-through for parsing items.
5264 fn parse_macro_use_or_failure(
5266 attrs: Vec<Attribute> ,
5267 macros_allowed: bool,
5269 visibility: Visibility
5270 ) -> ItemOrViewItem {
5271 if macros_allowed && !token::is_any_keyword(&self.token)
5272 && self.look_ahead(1, |t| *t == token::NOT)
5273 && (self.look_ahead(2, |t| is_plain_ident(t))
5274 || self.look_ahead(2, |t| *t == token::LPAREN)
5275 || self.look_ahead(2, |t| *t == token::LBRACE)) {
5276 // MACRO INVOCATION ITEM
5279 let pth = self.parse_path(NoTypesAllowed).path;
5280 self.expect(&token::NOT);
5282 // a 'special' identifier (like what `macro_rules!` uses)
5283 // is optional. We should eventually unify invoc syntax
5285 let id = if is_plain_ident(&self.token) {
5288 token::special_idents::invalid // no special identifier
5290 // eat a matched-delimiter token tree:
5291 let tts = match token::close_delimiter_for(&self.token) {
5294 self.parse_seq_to_end(&ket,
5296 |p| p.parse_token_tree())
5298 None => self.fatal("expected open delimiter")
5300 // single-variant-enum... :
5301 let m = ast::MacInvocTT(pth, tts, EMPTY_CTXT);
5302 let m: ast::Mac = codemap::Spanned { node: m,
5303 span: mk_sp(self.span.lo,
5305 let item_ = ItemMac(m);
5306 let last_span = self.last_span;
5307 let item = self.mk_item(lo,
5313 return IoviItem(item);
5316 // FAILURE TO PARSE ITEM
5317 if visibility != Inherited {
5318 let mut s = String::from_str("unmatched visibility `");
5319 if visibility == Public {
5325 let last_span = self.last_span;
5326 self.span_fatal(last_span, s.as_slice());
5328 return IoviNone(attrs);
5331 pub fn parse_item_with_outer_attributes(&mut self) -> Option<Gc<Item>> {
5332 let attrs = self.parse_outer_attributes();
5333 self.parse_item(attrs)
5336 pub fn parse_item(&mut self, attrs: Vec<Attribute> ) -> Option<Gc<Item>> {
5337 match self.parse_item_or_view_item(attrs, true) {
5338 IoviNone(_) => None,
5340 self.fatal("view items are not allowed here"),
5341 IoviForeignItem(_) =>
5342 self.fatal("foreign items are not allowed here"),
5343 IoviItem(item) => Some(item)
5347 /// Parse, e.g., "use a::b::{z,y}"
5348 fn parse_use(&mut self) -> ViewItem_ {
5349 return ViewItemUse(self.parse_view_path());
5353 /// Matches view_path : MOD? IDENT EQ non_global_path
5354 /// | MOD? non_global_path MOD_SEP LBRACE RBRACE
5355 /// | MOD? non_global_path MOD_SEP LBRACE ident_seq RBRACE
5356 /// | MOD? non_global_path MOD_SEP STAR
5357 /// | MOD? non_global_path
5358 fn parse_view_path(&mut self) -> Gc<ViewPath> {
5359 let lo = self.span.lo;
5361 if self.token == token::LBRACE {
5363 let idents = self.parse_unspanned_seq(
5364 &token::LBRACE, &token::RBRACE,
5365 seq_sep_trailing_allowed(token::COMMA),
5366 |p| p.parse_path_list_item());
5367 let path = ast::Path {
5368 span: mk_sp(lo, self.span.hi),
5370 segments: Vec::new()
5372 return box(GC) spanned(lo, self.span.hi,
5373 ViewPathList(path, idents, ast::DUMMY_NODE_ID));
5376 let first_ident = self.parse_ident();
5377 let mut path = vec!(first_ident);
5382 let path_lo = self.span.lo;
5383 path = vec!(self.parse_ident());
5384 while self.token == token::MOD_SEP {
5386 let id = self.parse_ident();
5389 let span = mk_sp(path_lo, self.span.hi);
5390 self.obsolete(span, ObsoleteImportRenaming);
5391 let path = ast::Path {
5394 segments: path.move_iter().map(|identifier| {
5396 identifier: identifier,
5397 lifetimes: Vec::new(),
5398 types: OwnedSlice::empty(),
5402 return box(GC) spanned(lo, self.span.hi,
5403 ViewPathSimple(first_ident, path,
5404 ast::DUMMY_NODE_ID));
5408 // foo::bar or foo::{a,b,c} or foo::*
5409 while self.token == token::MOD_SEP {
5413 token::IDENT(i, _) => {
5418 // foo::bar::{a,b,c}
5420 let idents = self.parse_unspanned_seq(
5423 seq_sep_trailing_allowed(token::COMMA),
5424 |p| p.parse_path_list_item()
5426 let path = ast::Path {
5427 span: mk_sp(lo, self.span.hi),
5429 segments: path.move_iter().map(|identifier| {
5431 identifier: identifier,
5432 lifetimes: Vec::new(),
5433 types: OwnedSlice::empty(),
5437 return box(GC) spanned(lo, self.span.hi,
5438 ViewPathList(path, idents, ast::DUMMY_NODE_ID));
5442 token::BINOP(token::STAR) => {
5444 let path = ast::Path {
5445 span: mk_sp(lo, self.span.hi),
5447 segments: path.move_iter().map(|identifier| {
5449 identifier: identifier,
5450 lifetimes: Vec::new(),
5451 types: OwnedSlice::empty(),
5455 return box(GC) spanned(lo, self.span.hi,
5456 ViewPathGlob(path, ast::DUMMY_NODE_ID));
5465 let mut rename_to = *path.get(path.len() - 1u);
5466 let path = ast::Path {
5467 span: mk_sp(lo, self.span.hi),
5469 segments: path.move_iter().map(|identifier| {
5471 identifier: identifier,
5472 lifetimes: Vec::new(),
5473 types: OwnedSlice::empty(),
5477 if self.eat_keyword(keywords::As) {
5478 rename_to = self.parse_ident()
5480 return box(GC) spanned(lo,
5482 ViewPathSimple(rename_to, path, ast::DUMMY_NODE_ID));
5485 /// Parses a sequence of items. Stops when it finds program
5486 /// text that can't be parsed as an item
5487 /// - mod_items uses extern_mod_allowed = true
5488 /// - block_tail_ uses extern_mod_allowed = false
5489 fn parse_items_and_view_items(&mut self,
5490 first_item_attrs: Vec<Attribute> ,
5491 mut extern_mod_allowed: bool,
5492 macros_allowed: bool)
5493 -> ParsedItemsAndViewItems {
5494 let mut attrs = first_item_attrs.append(self.parse_outer_attributes().as_slice());
5495 // First, parse view items.
5496 let mut view_items : Vec<ast::ViewItem> = Vec::new();
5497 let mut items = Vec::new();
5499 // I think this code would probably read better as a single
5500 // loop with a mutable three-state-variable (for extern crates,
5501 // view items, and regular items) ... except that because
5502 // of macros, I'd like to delay that entire check until later.
5504 match self.parse_item_or_view_item(attrs, macros_allowed) {
5505 IoviNone(attrs) => {
5506 return ParsedItemsAndViewItems {
5507 attrs_remaining: attrs,
5508 view_items: view_items,
5510 foreign_items: Vec::new()
5513 IoviViewItem(view_item) => {
5514 match view_item.node {
5515 ViewItemUse(..) => {
5516 // `extern crate` must precede `use`.
5517 extern_mod_allowed = false;
5519 ViewItemExternCrate(..) if !extern_mod_allowed => {
5520 self.span_err(view_item.span,
5521 "\"extern crate\" declarations are \
5524 ViewItemExternCrate(..) => {}
5526 view_items.push(view_item);
5530 attrs = self.parse_outer_attributes();
5533 IoviForeignItem(_) => {
5537 attrs = self.parse_outer_attributes();
5540 // Next, parse items.
5542 match self.parse_item_or_view_item(attrs, macros_allowed) {
5543 IoviNone(returned_attrs) => {
5544 attrs = returned_attrs;
5547 IoviViewItem(view_item) => {
5548 attrs = self.parse_outer_attributes();
5549 self.span_err(view_item.span,
5550 "`use` and `extern crate` declarations must precede items");
5553 attrs = self.parse_outer_attributes();
5556 IoviForeignItem(_) => {
5562 ParsedItemsAndViewItems {
5563 attrs_remaining: attrs,
5564 view_items: view_items,
5566 foreign_items: Vec::new()
5570 /// Parses a sequence of foreign items. Stops when it finds program
5571 /// text that can't be parsed as an item
5572 fn parse_foreign_items(&mut self, first_item_attrs: Vec<Attribute> ,
5573 macros_allowed: bool)
5574 -> ParsedItemsAndViewItems {
5575 let mut attrs = first_item_attrs.append(self.parse_outer_attributes().as_slice());
5576 let mut foreign_items = Vec::new();
5578 match self.parse_foreign_item(attrs, macros_allowed) {
5579 IoviNone(returned_attrs) => {
5580 if self.token == token::RBRACE {
5581 attrs = returned_attrs;
5586 IoviViewItem(view_item) => {
5587 // I think this can't occur:
5588 self.span_err(view_item.span,
5589 "`use` and `extern crate` declarations must precede items");
5592 // FIXME #5668: this will occur for a macro invocation:
5593 self.span_fatal(item.span, "macros cannot expand to foreign items");
5595 IoviForeignItem(foreign_item) => {
5596 foreign_items.push(foreign_item);
5599 attrs = self.parse_outer_attributes();
5602 ParsedItemsAndViewItems {
5603 attrs_remaining: attrs,
5604 view_items: Vec::new(),
5606 foreign_items: foreign_items
5610 /// Parses a source module as a crate. This is the main
5611 /// entry point for the parser.
5612 pub fn parse_crate_mod(&mut self) -> Crate {
5613 let lo = self.span.lo;
5614 // parse the crate's inner attrs, maybe (oops) one
5615 // of the attrs of an item:
5616 let (inner, next) = self.parse_inner_attrs_and_next();
5617 let first_item_outer_attrs = next;
5618 // parse the items inside the crate:
5619 let m = self.parse_mod_items(token::EOF, first_item_outer_attrs, lo);
5624 config: self.cfg.clone(),
5625 span: mk_sp(lo, self.span.lo),
5626 exported_macros: Vec::new(),
5630 pub fn parse_optional_str(&mut self)
5631 -> Option<(InternedString, ast::StrStyle)> {
5632 let (s, style) = match self.token {
5633 token::LIT_STR(s) => (self.id_to_interned_str(s.ident()), ast::CookedStr),
5634 token::LIT_STR_RAW(s, n) => {
5635 (self.id_to_interned_str(s.ident()), ast::RawStr(n))
5643 pub fn parse_str(&mut self) -> (InternedString, StrStyle) {
5644 match self.parse_optional_str() {
5646 _ => self.fatal("expected string literal")