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, 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(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(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(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 span = self.last_span;
1421 token::IDENT(ref ident, _)
1422 if "str" == token::get_ident(*ident).get() => {
1423 // This is OK (for now).
1425 token::LBRACKET => {} // Also OK.
1426 _ => self.obsolete(span, ObsoleteOwnedType)
1428 TyUniq(self.parse_ty(false))
1429 } else if self.token == token::BINOP(token::STAR) {
1430 // STAR POINTER (bare pointer?)
1432 TyPtr(self.parse_ptr())
1433 } else if self.token == token::LBRACKET {
1435 self.expect(&token::LBRACKET);
1436 let t = self.parse_ty(true);
1438 // Parse the `, ..e` in `[ int, ..e ]`
1439 // where `e` is a const expression
1440 let t = match self.maybe_parse_fixed_vstore() {
1442 Some(suffix) => TyFixedLengthVec(t, suffix)
1444 self.expect(&token::RBRACKET);
1446 } else if self.token == token::BINOP(token::AND) ||
1447 self.token == token::ANDAND {
1450 self.parse_borrowed_pointee()
1451 } else if self.is_keyword(keywords::Extern) ||
1452 self.is_keyword(keywords::Unsafe) ||
1453 self.token_is_bare_fn_keyword() {
1455 self.parse_ty_bare_fn()
1456 } else if self.token_is_closure_keyword() ||
1457 self.token == token::BINOP(token::OR) ||
1458 self.token == token::OROR ||
1459 self.token == token::LT {
1462 // FIXME(pcwalton): Eventually `token::LT` will not unambiguously
1463 // introduce a closure, once procs can have lifetime bounds. We
1464 // will need to refactor the grammar a little bit at that point.
1466 self.parse_ty_closure()
1467 } else if self.eat_keyword(keywords::Typeof) {
1469 // In order to not be ambiguous, the type must be surrounded by parens.
1470 self.expect(&token::LPAREN);
1471 let e = self.parse_expr();
1472 self.expect(&token::RPAREN);
1474 } else if self.eat_keyword(keywords::Proc) {
1475 self.parse_proc_type()
1476 } else if self.token == token::MOD_SEP
1477 || is_ident_or_path(&self.token) {
1479 let mode = if plus_allowed {
1480 LifetimeAndTypesAndBounds
1482 LifetimeAndTypesWithoutColons
1487 } = self.parse_path(mode);
1488 TyPath(path, bounds, ast::DUMMY_NODE_ID)
1489 } else if self.eat(&token::UNDERSCORE) {
1490 // TYPE TO BE INFERRED
1493 let msg = format!("expected type, found token {:?}", self.token);
1494 self.fatal(msg.as_slice());
1497 let sp = mk_sp(lo, self.last_span.hi);
1498 P(Ty {id: ast::DUMMY_NODE_ID, node: t, span: sp})
1501 pub fn parse_borrowed_pointee(&mut self) -> Ty_ {
1502 // look for `&'lt` or `&'foo ` and interpret `foo` as the region name:
1503 let opt_lifetime = self.parse_opt_lifetime();
1505 let mt = self.parse_mt();
1506 return TyRptr(opt_lifetime, mt);
1509 pub fn parse_ptr(&mut self) -> MutTy {
1510 let mutbl = if self.eat_keyword(keywords::Mut) {
1512 } else if self.eat_keyword(keywords::Const) {
1515 let span = self.last_span;
1517 "bare raw pointers are no longer allowed, you should \
1518 likely use `*mut T`, but otherwise `*T` is now \
1519 known as `*const T`");
1522 let t = self.parse_ty(true);
1523 MutTy { ty: t, mutbl: mutbl }
1526 pub fn is_named_argument(&mut self) -> bool {
1527 let offset = match self.token {
1528 token::BINOP(token::AND) => 1,
1530 _ if token::is_keyword(keywords::Mut, &self.token) => 1,
1534 debug!("parser is_named_argument offset:{}", offset);
1537 is_plain_ident_or_underscore(&self.token)
1538 && self.look_ahead(1, |t| *t == token::COLON)
1540 self.look_ahead(offset, |t| is_plain_ident_or_underscore(t))
1541 && self.look_ahead(offset + 1, |t| *t == token::COLON)
1545 /// This version of parse arg doesn't necessarily require
1546 /// identifier names.
1547 pub fn parse_arg_general(&mut self, require_name: bool) -> Arg {
1548 let pat = if require_name || self.is_named_argument() {
1549 debug!("parse_arg_general parse_pat (require_name:{:?})",
1551 let pat = self.parse_pat();
1553 self.expect(&token::COLON);
1556 debug!("parse_arg_general ident_to_pat");
1557 ast_util::ident_to_pat(ast::DUMMY_NODE_ID,
1559 special_idents::invalid)
1562 let t = self.parse_ty(true);
1567 id: ast::DUMMY_NODE_ID,
1571 /// Parse a single function argument
1572 pub fn parse_arg(&mut self) -> Arg {
1573 self.parse_arg_general(true)
1576 /// Parse an argument in a lambda header e.g. |arg, arg|
1577 pub fn parse_fn_block_arg(&mut self) -> Arg {
1578 let pat = self.parse_pat();
1579 let t = if self.eat(&token::COLON) {
1583 id: ast::DUMMY_NODE_ID,
1585 span: mk_sp(self.span.lo, self.span.hi),
1591 id: ast::DUMMY_NODE_ID
1595 pub fn maybe_parse_fixed_vstore(&mut self) -> Option<Gc<ast::Expr>> {
1596 if self.token == token::COMMA &&
1597 self.look_ahead(1, |t| *t == token::DOTDOT) {
1600 Some(self.parse_expr())
1606 /// Matches token_lit = LIT_INTEGER | ...
1607 pub fn lit_from_token(&mut self, tok: &token::Token) -> Lit_ {
1609 token::LIT_BYTE(i) => LitByte(parse::byte_lit(i.as_str()).val0()),
1610 token::LIT_CHAR(i) => LitChar(parse::char_lit(i.as_str()).val0()),
1611 token::LIT_INTEGER(s) => parse::integer_lit(s.as_str(),
1612 &self.sess.span_diagnostic, self.span),
1613 token::LIT_FLOAT(s) => parse::float_lit(s.as_str()),
1614 token::LIT_STR(s) => {
1615 LitStr(token::intern_and_get_ident(parse::str_lit(s.as_str()).as_slice()),
1618 token::LIT_STR_RAW(s, n) => {
1619 LitStr(token::intern_and_get_ident(parse::raw_str_lit(s.as_str()).as_slice()),
1622 token::LIT_BINARY(i) =>
1623 LitBinary(parse::binary_lit(i.as_str())),
1624 token::LIT_BINARY_RAW(i, _) =>
1625 LitBinary(Rc::new(i.as_str().as_bytes().iter().map(|&x| x).collect())),
1626 token::LPAREN => { self.expect(&token::RPAREN); LitNil },
1627 _ => { self.unexpected_last(tok); }
1631 /// Matches lit = true | false | token_lit
1632 pub fn parse_lit(&mut self) -> Lit {
1633 let lo = self.span.lo;
1634 let lit = if self.eat_keyword(keywords::True) {
1636 } else if self.eat_keyword(keywords::False) {
1639 let token = self.bump_and_get();
1640 let lit = self.lit_from_token(&token);
1643 codemap::Spanned { node: lit, span: mk_sp(lo, self.last_span.hi) }
1646 /// matches '-' lit | lit
1647 pub fn parse_literal_maybe_minus(&mut self) -> Gc<Expr> {
1648 let minus_lo = self.span.lo;
1649 let minus_present = self.eat(&token::BINOP(token::MINUS));
1651 let lo = self.span.lo;
1652 let literal = box(GC) self.parse_lit();
1653 let hi = self.span.hi;
1654 let expr = self.mk_expr(lo, hi, ExprLit(literal));
1657 let minus_hi = self.span.hi;
1658 let unary = self.mk_unary(UnNeg, expr);
1659 self.mk_expr(minus_lo, minus_hi, unary)
1665 /// Parses a path and optional type parameter bounds, depending on the
1666 /// mode. The `mode` parameter determines whether lifetimes, types, and/or
1667 /// bounds are permitted and whether `::` must precede type parameter
1669 pub fn parse_path(&mut self, mode: PathParsingMode) -> PathAndBounds {
1670 // Check for a whole path...
1671 let found = match self.token {
1672 INTERPOLATED(token::NtPath(_)) => Some(self.bump_and_get()),
1676 Some(INTERPOLATED(token::NtPath(box path))) => {
1677 return PathAndBounds {
1685 let lo = self.span.lo;
1686 let is_global = self.eat(&token::MOD_SEP);
1688 // Parse any number of segments and bound sets. A segment is an
1689 // identifier followed by an optional lifetime and a set of types.
1690 // A bound set is a set of type parameter bounds.
1691 let mut segments = Vec::new();
1693 // First, parse an identifier.
1694 let identifier = self.parse_ident();
1696 // Parse the '::' before type parameters if it's required. If
1697 // it is required and wasn't present, then we're done.
1698 if mode == LifetimeAndTypesWithColons &&
1699 !self.eat(&token::MOD_SEP) {
1700 segments.push(ast::PathSegment {
1701 identifier: identifier,
1702 lifetimes: Vec::new(),
1703 types: OwnedSlice::empty(),
1708 // Parse the `<` before the lifetime and types, if applicable.
1709 let (any_lifetime_or_types, lifetimes, types) = {
1710 if mode != NoTypesAllowed && self.eat_lt(false) {
1711 let (lifetimes, types) =
1712 self.parse_generic_values_after_lt();
1713 (true, lifetimes, OwnedSlice::from_vec(types))
1715 (false, Vec::new(), OwnedSlice::empty())
1719 // Assemble and push the result.
1720 segments.push(ast::PathSegment {
1721 identifier: identifier,
1722 lifetimes: lifetimes,
1726 // We're done if we don't see a '::', unless the mode required
1727 // a double colon to get here in the first place.
1728 if !(mode == LifetimeAndTypesWithColons &&
1729 !any_lifetime_or_types) {
1730 if !self.eat(&token::MOD_SEP) {
1736 // Next, parse a plus and bounded type parameters, if
1737 // applicable. We need to remember whether the separate was
1738 // present for later, because in some contexts it's a parse
1741 if mode == LifetimeAndTypesAndBounds &&
1742 self.eat(&token::BINOP(token::PLUS))
1744 let bounds = self.parse_ty_param_bounds();
1746 // For some reason that I do not fully understand, we
1747 // do not permit an empty list in the case where it is
1748 // introduced by a `+`, but we do for `:` and other
1749 // separators. -nmatsakis
1750 if bounds.len() == 0 {
1751 let last_span = self.last_span;
1752 self.span_err(last_span,
1753 "at least one type parameter bound \
1754 must be specified");
1763 // Assemble the span.
1764 let span = mk_sp(lo, self.last_span.hi);
1766 // Assemble the result.
1777 /// parses 0 or 1 lifetime
1778 pub fn parse_opt_lifetime(&mut self) -> Option<ast::Lifetime> {
1780 token::LIFETIME(..) => {
1781 Some(self.parse_lifetime())
1789 /// Parses a single lifetime
1790 /// Matches lifetime = LIFETIME
1791 pub fn parse_lifetime(&mut self) -> ast::Lifetime {
1793 token::LIFETIME(i) => {
1794 let span = self.span;
1796 return ast::Lifetime {
1797 id: ast::DUMMY_NODE_ID,
1803 self.fatal(format!("expected a lifetime name").as_slice());
1808 pub fn parse_lifetime_defs(&mut self) -> Vec<ast::LifetimeDef> {
1810 * Parses `lifetime_defs = [ lifetime_defs { ',' lifetime_defs } ]`
1811 * where `lifetime_def = lifetime [':' lifetimes]`
1814 let mut res = Vec::new();
1817 token::LIFETIME(_) => {
1818 let lifetime = self.parse_lifetime();
1820 if self.eat(&token::COLON) {
1821 self.parse_lifetimes(token::BINOP(token::PLUS))
1825 res.push(ast::LifetimeDef { lifetime: lifetime,
1835 token::COMMA => { self.bump(); }
1836 token::GT => { return res; }
1837 token::BINOP(token::SHR) => { return res; }
1839 let msg = format!("expected `,` or `>` after lifetime \
1842 self.fatal(msg.as_slice());
1848 // matches lifetimes = ( lifetime ) | ( lifetime , lifetimes )
1849 // actually, it matches the empty one too, but putting that in there
1850 // messes up the grammar....
1851 pub fn parse_lifetimes(&mut self, sep: token::Token) -> Vec<ast::Lifetime> {
1853 * Parses zero or more comma separated lifetimes.
1854 * Expects each lifetime to be followed by either
1855 * a comma or `>`. Used when parsing type parameter
1856 * lists, where we expect something like `<'a, 'b, T>`.
1859 let mut res = Vec::new();
1862 token::LIFETIME(_) => {
1863 res.push(self.parse_lifetime());
1870 if self.token != sep {
1878 pub fn token_is_mutability(tok: &token::Token) -> bool {
1879 token::is_keyword(keywords::Mut, tok) ||
1880 token::is_keyword(keywords::Const, tok)
1883 /// Parse mutability declaration (mut/const/imm)
1884 pub fn parse_mutability(&mut self) -> Mutability {
1885 if self.eat_keyword(keywords::Mut) {
1892 /// Parse ident COLON expr
1893 pub fn parse_field(&mut self) -> Field {
1894 let lo = self.span.lo;
1895 let i = self.parse_ident();
1896 let hi = self.last_span.hi;
1897 self.expect(&token::COLON);
1898 let e = self.parse_expr();
1900 ident: spanned(lo, hi, i),
1902 span: mk_sp(lo, e.span.hi),
1906 pub fn mk_expr(&mut self, lo: BytePos, hi: BytePos, node: Expr_) -> Gc<Expr> {
1908 id: ast::DUMMY_NODE_ID,
1910 span: mk_sp(lo, hi),
1914 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: Gc<Expr>) -> ast::Expr_ {
1915 ExprUnary(unop, expr)
1918 pub fn mk_binary(&mut self, binop: ast::BinOp,
1919 lhs: Gc<Expr>, rhs: Gc<Expr>) -> ast::Expr_ {
1920 ExprBinary(binop, lhs, rhs)
1923 pub fn mk_call(&mut self, f: Gc<Expr>, args: Vec<Gc<Expr>>) -> ast::Expr_ {
1927 fn mk_method_call(&mut self,
1928 ident: ast::SpannedIdent,
1930 args: Vec<Gc<Expr>>)
1932 ExprMethodCall(ident, tps, args)
1935 pub fn mk_index(&mut self, expr: Gc<Expr>, idx: Gc<Expr>) -> ast::Expr_ {
1936 ExprIndex(expr, idx)
1939 pub fn mk_field(&mut self, expr: Gc<Expr>, ident: ast::SpannedIdent,
1940 tys: Vec<P<Ty>>) -> ast::Expr_ {
1941 ExprField(expr, ident, tys)
1944 pub fn mk_assign_op(&mut self, binop: ast::BinOp,
1945 lhs: Gc<Expr>, rhs: Gc<Expr>) -> ast::Expr_ {
1946 ExprAssignOp(binop, lhs, rhs)
1949 pub fn mk_mac_expr(&mut self, lo: BytePos, hi: BytePos, m: Mac_) -> Gc<Expr> {
1951 id: ast::DUMMY_NODE_ID,
1952 node: ExprMac(codemap::Spanned {node: m, span: mk_sp(lo, hi)}),
1953 span: mk_sp(lo, hi),
1957 pub fn mk_lit_u32(&mut self, i: u32) -> Gc<Expr> {
1958 let span = &self.span;
1959 let lv_lit = box(GC) codemap::Spanned {
1960 node: LitInt(i as u64, ast::UnsignedIntLit(TyU32)),
1965 id: ast::DUMMY_NODE_ID,
1966 node: ExprLit(lv_lit),
1971 /// At the bottom (top?) of the precedence hierarchy,
1972 /// parse things like parenthesized exprs,
1973 /// macros, return, etc.
1974 pub fn parse_bottom_expr(&mut self) -> Gc<Expr> {
1975 maybe_whole_expr!(self);
1977 let lo = self.span.lo;
1978 let mut hi = self.span.hi;
1985 // (e) is parenthesized e
1986 // (e,) is a tuple with only one field, e
1987 let mut trailing_comma = false;
1988 if self.token == token::RPAREN {
1991 let lit = box(GC) spanned(lo, hi, LitNil);
1992 return self.mk_expr(lo, hi, ExprLit(lit));
1994 let mut es = vec!(self.parse_expr());
1995 self.commit_expr(*es.last().unwrap(), &[], &[token::COMMA, token::RPAREN]);
1996 while self.token == token::COMMA {
1998 if self.token != token::RPAREN {
1999 es.push(self.parse_expr());
2000 self.commit_expr(*es.last().unwrap(), &[], &[token::COMMA, token::RPAREN]);
2003 trailing_comma = true;
2007 self.commit_expr_expecting(*es.last().unwrap(), token::RPAREN);
2009 return if es.len() == 1 && !trailing_comma {
2010 self.mk_expr(lo, hi, ExprParen(*es.get(0)))
2013 self.mk_expr(lo, hi, ExprTup(es))
2018 let blk = self.parse_block_tail(lo, DefaultBlock);
2019 return self.mk_expr(blk.span.lo, blk.span.hi,
2022 token::BINOP(token::OR) | token::OROR => {
2023 return self.parse_lambda_expr(CaptureByValue);
2025 // FIXME #13626: Should be able to stick in
2026 // token::SELF_KEYWORD_NAME
2027 token::IDENT(id @ ast::Ident{
2028 name: ast::Name(token::SELF_KEYWORD_NAME_NUM),
2032 let path = ast_util::ident_to_path(mk_sp(lo, hi), id);
2033 ex = ExprPath(path);
2034 hi = self.last_span.hi;
2036 token::LBRACKET => {
2039 if self.token == token::RBRACKET {
2042 ex = ExprVec(Vec::new());
2045 let first_expr = self.parse_expr();
2046 if self.token == token::COMMA &&
2047 self.look_ahead(1, |t| *t == token::DOTDOT) {
2048 // Repeating vector syntax: [ 0, ..512 ]
2051 let count = self.parse_expr();
2052 self.expect(&token::RBRACKET);
2053 ex = ExprRepeat(first_expr, count);
2054 } else if self.token == token::COMMA {
2055 // Vector with two or more elements.
2057 let remaining_exprs = self.parse_seq_to_end(
2059 seq_sep_trailing_allowed(token::COMMA),
2062 let mut exprs = vec!(first_expr);
2063 exprs.push_all_move(remaining_exprs);
2064 ex = ExprVec(exprs);
2066 // Vector with one element.
2067 self.expect(&token::RBRACKET);
2068 ex = ExprVec(vec!(first_expr));
2071 hi = self.last_span.hi;
2074 if self.eat_keyword(keywords::Ref) {
2075 return self.parse_lambda_expr(CaptureByRef);
2077 if self.eat_keyword(keywords::Proc) {
2078 let decl = self.parse_proc_decl();
2079 let body = self.parse_expr();
2080 let fakeblock = P(ast::Block {
2081 view_items: Vec::new(),
2084 id: ast::DUMMY_NODE_ID,
2085 rules: DefaultBlock,
2088 return self.mk_expr(lo, body.span.hi, ExprProc(decl, fakeblock));
2090 if self.eat_keyword(keywords::If) {
2091 return self.parse_if_expr();
2093 if self.eat_keyword(keywords::For) {
2094 return self.parse_for_expr(None);
2096 if self.eat_keyword(keywords::While) {
2097 return self.parse_while_expr(None);
2099 if Parser::token_is_lifetime(&self.token) {
2100 let lifetime = self.get_lifetime();
2102 self.expect(&token::COLON);
2103 if self.eat_keyword(keywords::While) {
2104 return self.parse_while_expr(Some(lifetime))
2106 if self.eat_keyword(keywords::For) {
2107 return self.parse_for_expr(Some(lifetime))
2109 if self.eat_keyword(keywords::Loop) {
2110 return self.parse_loop_expr(Some(lifetime))
2112 self.fatal("expected `while`, `for`, or `loop` after a label")
2114 if self.eat_keyword(keywords::Loop) {
2115 return self.parse_loop_expr(None);
2117 if self.eat_keyword(keywords::Continue) {
2118 let lo = self.span.lo;
2119 let ex = if Parser::token_is_lifetime(&self.token) {
2120 let lifetime = self.get_lifetime();
2122 ExprAgain(Some(lifetime))
2126 let hi = self.span.hi;
2127 return self.mk_expr(lo, hi, ex);
2129 if self.eat_keyword(keywords::Match) {
2130 return self.parse_match_expr();
2132 if self.eat_keyword(keywords::Unsafe) {
2133 return self.parse_block_expr(
2135 UnsafeBlock(ast::UserProvided));
2137 if self.eat_keyword(keywords::Return) {
2138 // RETURN expression
2139 if can_begin_expr(&self.token) {
2140 let e = self.parse_expr();
2142 ex = ExprRet(Some(e));
2146 } else if self.eat_keyword(keywords::Break) {
2148 if Parser::token_is_lifetime(&self.token) {
2149 let lifetime = self.get_lifetime();
2151 ex = ExprBreak(Some(lifetime));
2153 ex = ExprBreak(None);
2156 } else if self.token == token::MOD_SEP ||
2157 is_ident(&self.token) &&
2158 !self.is_keyword(keywords::True) &&
2159 !self.is_keyword(keywords::False) {
2161 self.parse_path(LifetimeAndTypesWithColons).path;
2163 // `!`, as an operator, is prefix, so we know this isn't that
2164 if self.token == token::NOT {
2165 // MACRO INVOCATION expression
2168 let ket = token::close_delimiter_for(&self.token)
2169 .unwrap_or_else(|| {
2170 self.fatal("expected open delimiter")
2174 let tts = self.parse_seq_to_end(
2177 |p| p.parse_token_tree());
2178 let hi = self.span.hi;
2180 return self.mk_mac_expr(lo,
2186 if self.token == token::LBRACE {
2187 // This is a struct literal, unless we're prohibited
2188 // from parsing struct literals here.
2189 if self.restriction != RESTRICT_NO_STRUCT_LITERAL {
2190 // It's a struct literal.
2192 let mut fields = Vec::new();
2193 let mut base = None;
2195 while self.token != token::RBRACE {
2196 if self.eat(&token::DOTDOT) {
2197 base = Some(self.parse_expr());
2201 fields.push(self.parse_field());
2202 self.commit_expr(fields.last().unwrap().expr,
2207 if fields.len() == 0 && base.is_none() {
2208 let last_span = self.last_span;
2209 self.span_err(last_span,
2210 "structure literal must either \
2211 have at least one field or use \
2212 functional structure update \
2217 self.expect(&token::RBRACE);
2218 ex = ExprStruct(pth, fields, base);
2219 return self.mk_expr(lo, hi, ex);
2226 // other literal expression
2227 let lit = self.parse_lit();
2229 ex = ExprLit(box(GC) lit);
2234 return self.mk_expr(lo, hi, ex);
2237 /// Parse a block or unsafe block
2238 pub fn parse_block_expr(&mut self, lo: BytePos, blk_mode: BlockCheckMode)
2240 self.expect(&token::LBRACE);
2241 let blk = self.parse_block_tail(lo, blk_mode);
2242 return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk));
2245 /// parse a.b or a(13) or a[4] or just a
2246 pub fn parse_dot_or_call_expr(&mut self) -> Gc<Expr> {
2247 let b = self.parse_bottom_expr();
2248 self.parse_dot_or_call_expr_with(b)
2251 pub fn parse_dot_or_call_expr_with(&mut self, e0: Gc<Expr>) -> Gc<Expr> {
2257 if self.eat(&token::DOT) {
2259 token::IDENT(i, _) => {
2260 let dot = self.last_span.hi;
2263 let (_, tys) = if self.eat(&token::MOD_SEP) {
2265 self.parse_generic_values_after_lt()
2267 (Vec::new(), Vec::new())
2270 // expr.f() method call
2273 let mut es = self.parse_unspanned_seq(
2276 seq_sep_trailing_allowed(token::COMMA),
2279 hi = self.last_span.hi;
2282 let id = spanned(dot, hi, i);
2283 let nd = self.mk_method_call(id, tys, es);
2284 e = self.mk_expr(lo, hi, nd);
2287 let id = spanned(dot, hi, i);
2288 let field = self.mk_field(e, id, tys);
2289 e = self.mk_expr(lo, hi, field)
2293 _ => self.unexpected()
2297 if self.expr_is_complete(e) { break; }
2301 let es = self.parse_unspanned_seq(
2304 seq_sep_trailing_allowed(token::COMMA),
2307 hi = self.last_span.hi;
2309 let nd = self.mk_call(e, es);
2310 e = self.mk_expr(lo, hi, nd);
2314 token::LBRACKET => {
2316 let ix = self.parse_expr();
2318 self.commit_expr_expecting(ix, token::RBRACKET);
2319 let index = self.mk_index(e, ix);
2320 e = self.mk_expr(lo, hi, index)
2329 /// Parse an optional separator followed by a kleene-style
2330 /// repetition token (+ or *).
2331 pub fn parse_sep_and_zerok(&mut self) -> (Option<token::Token>, bool) {
2332 fn parse_zerok(parser: &mut Parser) -> Option<bool> {
2333 match parser.token {
2334 token::BINOP(token::STAR) | token::BINOP(token::PLUS) => {
2335 let zerok = parser.token == token::BINOP(token::STAR);
2343 match parse_zerok(self) {
2344 Some(zerok) => return (None, zerok),
2348 let separator = self.bump_and_get();
2349 match parse_zerok(self) {
2350 Some(zerok) => (Some(separator), zerok),
2351 None => self.fatal("expected `*` or `+`")
2355 /// parse a single token tree from the input.
2356 pub fn parse_token_tree(&mut self) -> TokenTree {
2357 // FIXME #6994: currently, this is too eager. It
2358 // parses token trees but also identifies TTSeq's
2359 // and TTNonterminal's; it's too early to know yet
2360 // whether something will be a nonterminal or a seq
2362 maybe_whole!(deref self, NtTT);
2364 // this is the fall-through for the 'match' below.
2365 // invariants: the current token is not a left-delimiter,
2366 // not an EOF, and not the desired right-delimiter (if
2367 // it were, parse_seq_to_before_end would have prevented
2368 // reaching this point.
2369 fn parse_non_delim_tt_tok(p: &mut Parser) -> TokenTree {
2370 maybe_whole!(deref p, NtTT);
2372 token::RPAREN | token::RBRACE | token::RBRACKET => {
2373 // This is a conservative error: only report the last unclosed delimiter. The
2374 // previous unclosed delimiters could actually be closed! The parser just hasn't
2375 // gotten to them yet.
2376 match p.open_braces.last() {
2378 Some(&sp) => p.span_note(sp, "unclosed delimiter"),
2380 let token_str = p.this_token_to_string();
2381 p.fatal(format!("incorrect close delimiter: `{}`",
2382 token_str).as_slice())
2384 /* we ought to allow different depths of unquotation */
2385 token::DOLLAR if p.quote_depth > 0u => {
2389 if p.token == token::LPAREN {
2390 let seq = p.parse_seq(
2394 |p| p.parse_token_tree()
2396 let (s, z) = p.parse_sep_and_zerok();
2397 let seq = match seq {
2398 Spanned { node, .. } => node,
2400 TTSeq(mk_sp(sp.lo, p.span.hi), Rc::new(seq), s, z)
2402 TTNonterminal(sp, p.parse_ident())
2411 // turn the next token into a TTTok:
2412 fn parse_any_tt_tok(p: &mut Parser) -> TokenTree {
2413 TTTok(p.span, p.bump_and_get())
2416 match (&self.token, token::close_delimiter_for(&self.token)) {
2417 (&token::EOF, _) => {
2418 let open_braces = self.open_braces.clone();
2419 for sp in open_braces.iter() {
2420 self.span_note(*sp, "Did you mean to close this delimiter?");
2422 // There shouldn't really be a span, but it's easier for the test runner
2423 // if we give it one
2424 self.fatal("this file contains an un-closed delimiter ");
2426 (_, Some(close_delim)) => {
2427 // Parse the open delimiter.
2428 self.open_braces.push(self.span);
2429 let mut result = vec!(parse_any_tt_tok(self));
2432 self.parse_seq_to_before_end(&close_delim,
2434 |p| p.parse_token_tree());
2435 result.push_all_move(trees);
2437 // Parse the close delimiter.
2438 result.push(parse_any_tt_tok(self));
2439 self.open_braces.pop().unwrap();
2441 TTDelim(Rc::new(result))
2443 _ => parse_non_delim_tt_tok(self)
2447 // parse a stream of tokens into a list of TokenTree's,
2449 pub fn parse_all_token_trees(&mut self) -> Vec<TokenTree> {
2450 let mut tts = Vec::new();
2451 while self.token != token::EOF {
2452 tts.push(self.parse_token_tree());
2457 pub fn parse_matchers(&mut self) -> Vec<Matcher> {
2458 // unification of Matcher's and TokenTree's would vastly improve
2459 // the interpolation of Matcher's
2460 maybe_whole!(self, NtMatchers);
2461 let mut name_idx = 0u;
2462 match token::close_delimiter_for(&self.token) {
2463 Some(other_delimiter) => {
2465 self.parse_matcher_subseq_upto(&mut name_idx, &other_delimiter)
2467 None => self.fatal("expected open delimiter")
2471 /// This goofy function is necessary to correctly match parens in Matcher's.
2472 /// Otherwise, `$( ( )` would be a valid Matcher, and `$( () )` would be
2473 /// invalid. It's similar to common::parse_seq.
2474 pub fn parse_matcher_subseq_upto(&mut self,
2475 name_idx: &mut uint,
2478 let mut ret_val = Vec::new();
2479 let mut lparens = 0u;
2481 while self.token != *ket || lparens > 0u {
2482 if self.token == token::LPAREN { lparens += 1u; }
2483 if self.token == token::RPAREN { lparens -= 1u; }
2484 ret_val.push(self.parse_matcher(name_idx));
2492 pub fn parse_matcher(&mut self, name_idx: &mut uint) -> Matcher {
2493 let lo = self.span.lo;
2495 let m = if self.token == token::DOLLAR {
2497 if self.token == token::LPAREN {
2498 let name_idx_lo = *name_idx;
2500 let ms = self.parse_matcher_subseq_upto(name_idx,
2503 self.fatal("repetition body must be nonempty");
2505 let (sep, zerok) = self.parse_sep_and_zerok();
2506 MatchSeq(ms, sep, zerok, name_idx_lo, *name_idx)
2508 let bound_to = self.parse_ident();
2509 self.expect(&token::COLON);
2510 let nt_name = self.parse_ident();
2511 let m = MatchNonterminal(bound_to, nt_name, *name_idx);
2516 MatchTok(self.bump_and_get())
2519 return spanned(lo, self.span.hi, m);
2522 /// Parse a prefix-operator expr
2523 pub fn parse_prefix_expr(&mut self) -> Gc<Expr> {
2524 let lo = self.span.lo;
2531 let e = self.parse_prefix_expr();
2533 ex = self.mk_unary(UnNot, e);
2535 token::BINOP(token::MINUS) => {
2537 let e = self.parse_prefix_expr();
2539 ex = self.mk_unary(UnNeg, e);
2541 token::BINOP(token::STAR) => {
2543 let e = self.parse_prefix_expr();
2545 ex = self.mk_unary(UnDeref, e);
2547 token::BINOP(token::AND) | token::ANDAND => {
2549 let m = self.parse_mutability();
2550 let e = self.parse_prefix_expr();
2552 ex = ExprAddrOf(m, e);
2556 let span = self.last_span;
2557 self.obsolete(span, ObsoleteManagedExpr);
2558 let e = self.parse_prefix_expr();
2560 ex = self.mk_unary(UnBox, e);
2564 let span = self.last_span;
2566 token::LIT_STR(_) => {
2567 // This is OK (for now).
2569 token::LBRACKET => {} // Also OK.
2570 _ => self.obsolete(span, ObsoleteOwnedExpr)
2573 let e = self.parse_prefix_expr();
2575 ex = self.mk_unary(UnUniq, e);
2577 token::IDENT(_, _) => {
2578 if !self.is_keyword(keywords::Box) {
2579 return self.parse_dot_or_call_expr();
2584 // Check for a place: `box(PLACE) EXPR`.
2585 if self.eat(&token::LPAREN) {
2586 // Support `box() EXPR` as the default.
2587 if !self.eat(&token::RPAREN) {
2588 let place = self.parse_expr();
2589 self.expect(&token::RPAREN);
2590 let subexpression = self.parse_prefix_expr();
2591 hi = subexpression.span.hi;
2592 ex = ExprBox(place, subexpression);
2593 return self.mk_expr(lo, hi, ex);
2597 // Otherwise, we use the unique pointer default.
2598 let subexpression = self.parse_prefix_expr();
2599 hi = subexpression.span.hi;
2600 ex = self.mk_unary(UnUniq, subexpression);
2602 _ => return self.parse_dot_or_call_expr()
2604 return self.mk_expr(lo, hi, ex);
2607 /// Parse an expression of binops
2608 pub fn parse_binops(&mut self) -> Gc<Expr> {
2609 let prefix_expr = self.parse_prefix_expr();
2610 self.parse_more_binops(prefix_expr, 0)
2613 /// Parse an expression of binops of at least min_prec precedence
2614 pub fn parse_more_binops(&mut self, lhs: Gc<Expr>,
2615 min_prec: uint) -> Gc<Expr> {
2616 if self.expr_is_complete(lhs) { return lhs; }
2618 // Prevent dynamic borrow errors later on by limiting the
2619 // scope of the borrows.
2621 let token: &token::Token = &self.token;
2622 let restriction: &restriction = &self.restriction;
2623 match (token, restriction) {
2624 (&token::BINOP(token::OR), &RESTRICT_NO_BAR_OP) => return lhs,
2625 (&token::BINOP(token::OR),
2626 &RESTRICT_NO_BAR_OR_DOUBLEBAR_OP) => return lhs,
2627 (&token::OROR, &RESTRICT_NO_BAR_OR_DOUBLEBAR_OP) => return lhs,
2632 let cur_opt = token_to_binop(&self.token);
2635 let cur_prec = operator_prec(cur_op);
2636 if cur_prec > min_prec {
2638 let expr = self.parse_prefix_expr();
2639 let rhs = self.parse_more_binops(expr, cur_prec);
2640 let binary = self.mk_binary(cur_op, lhs, rhs);
2641 let bin = self.mk_expr(lhs.span.lo, rhs.span.hi, binary);
2642 self.parse_more_binops(bin, min_prec)
2648 if as_prec > min_prec && self.eat_keyword(keywords::As) {
2649 let rhs = self.parse_ty(false);
2650 let _as = self.mk_expr(lhs.span.lo,
2652 ExprCast(lhs, rhs));
2653 self.parse_more_binops(_as, min_prec)
2661 /// Parse an assignment expression....
2662 /// actually, this seems to be the main entry point for
2663 /// parsing an arbitrary expression.
2664 pub fn parse_assign_expr(&mut self) -> Gc<Expr> {
2665 let lo = self.span.lo;
2666 let lhs = self.parse_binops();
2670 let rhs = self.parse_expr();
2671 self.mk_expr(lo, rhs.span.hi, ExprAssign(lhs, rhs))
2673 token::BINOPEQ(op) => {
2675 let rhs = self.parse_expr();
2676 let aop = match op {
2677 token::PLUS => BiAdd,
2678 token::MINUS => BiSub,
2679 token::STAR => BiMul,
2680 token::SLASH => BiDiv,
2681 token::PERCENT => BiRem,
2682 token::CARET => BiBitXor,
2683 token::AND => BiBitAnd,
2684 token::OR => BiBitOr,
2685 token::SHL => BiShl,
2688 let assign_op = self.mk_assign_op(aop, lhs, rhs);
2689 self.mk_expr(lo, rhs.span.hi, assign_op)
2697 /// Parse an 'if' expression ('if' token already eaten)
2698 pub fn parse_if_expr(&mut self) -> Gc<Expr> {
2699 let lo = self.last_span.lo;
2700 let cond = self.parse_expr_res(RESTRICT_NO_STRUCT_LITERAL);
2701 let thn = self.parse_block();
2702 let mut els: Option<Gc<Expr>> = None;
2703 let mut hi = thn.span.hi;
2704 if self.eat_keyword(keywords::Else) {
2705 let elexpr = self.parse_else_expr();
2707 hi = elexpr.span.hi;
2709 self.mk_expr(lo, hi, ExprIf(cond, thn, els))
2713 pub fn parse_lambda_expr(&mut self, capture_clause: CaptureClause)
2715 let lo = self.span.lo;
2716 let (decl, optional_unboxed_closure_kind) =
2717 self.parse_fn_block_decl();
2718 let body = self.parse_expr();
2719 let fakeblock = P(ast::Block {
2720 view_items: Vec::new(),
2723 id: ast::DUMMY_NODE_ID,
2724 rules: DefaultBlock,
2728 match optional_unboxed_closure_kind {
2729 Some(unboxed_closure_kind) => {
2732 ExprUnboxedFn(capture_clause,
2733 unboxed_closure_kind,
2740 ExprFnBlock(capture_clause, decl, fakeblock))
2745 pub fn parse_else_expr(&mut self) -> Gc<Expr> {
2746 if self.eat_keyword(keywords::If) {
2747 return self.parse_if_expr();
2749 let blk = self.parse_block();
2750 return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk));
2754 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
2755 pub fn parse_for_expr(&mut self, opt_ident: Option<ast::Ident>) -> Gc<Expr> {
2756 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
2758 let lo = self.last_span.lo;
2759 let pat = self.parse_pat();
2760 self.expect_keyword(keywords::In);
2761 let expr = self.parse_expr_res(RESTRICT_NO_STRUCT_LITERAL);
2762 let loop_block = self.parse_block();
2763 let hi = self.span.hi;
2765 self.mk_expr(lo, hi, ExprForLoop(pat, expr, loop_block, opt_ident))
2768 pub fn parse_while_expr(&mut self, opt_ident: Option<ast::Ident>) -> Gc<Expr> {
2769 let lo = self.last_span.lo;
2770 let cond = self.parse_expr_res(RESTRICT_NO_STRUCT_LITERAL);
2771 let body = self.parse_block();
2772 let hi = body.span.hi;
2773 return self.mk_expr(lo, hi, ExprWhile(cond, body, opt_ident));
2776 pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::Ident>) -> Gc<Expr> {
2777 let lo = self.last_span.lo;
2778 let body = self.parse_block();
2779 let hi = body.span.hi;
2780 self.mk_expr(lo, hi, ExprLoop(body, opt_ident))
2783 fn parse_match_expr(&mut self) -> Gc<Expr> {
2784 let lo = self.last_span.lo;
2785 let discriminant = self.parse_expr_res(RESTRICT_NO_STRUCT_LITERAL);
2786 self.commit_expr_expecting(discriminant, token::LBRACE);
2787 let mut arms: Vec<Arm> = Vec::new();
2788 while self.token != token::RBRACE {
2789 arms.push(self.parse_arm());
2791 let hi = self.span.hi;
2793 return self.mk_expr(lo, hi, ExprMatch(discriminant, arms));
2796 pub fn parse_arm(&mut self) -> Arm {
2797 let attrs = self.parse_outer_attributes();
2798 let pats = self.parse_pats();
2799 let mut guard = None;
2800 if self.eat_keyword(keywords::If) {
2801 guard = Some(self.parse_expr());
2803 self.expect(&token::FAT_ARROW);
2804 let expr = self.parse_expr_res(RESTRICT_STMT_EXPR);
2807 !classify::expr_is_simple_block(expr)
2808 && self.token != token::RBRACE;
2811 self.commit_expr(expr, &[token::COMMA], &[token::RBRACE]);
2813 self.eat(&token::COMMA);
2824 /// Parse an expression
2825 pub fn parse_expr(&mut self) -> Gc<Expr> {
2826 return self.parse_expr_res(UNRESTRICTED);
2829 /// Parse an expression, subject to the given restriction
2830 pub fn parse_expr_res(&mut self, r: restriction) -> Gc<Expr> {
2831 let old = self.restriction;
2832 self.restriction = r;
2833 let e = self.parse_assign_expr();
2834 self.restriction = old;
2838 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
2839 fn parse_initializer(&mut self) -> Option<Gc<Expr>> {
2840 if self.token == token::EQ {
2842 Some(self.parse_expr())
2848 /// Parse patterns, separated by '|' s
2849 fn parse_pats(&mut self) -> Vec<Gc<Pat>> {
2850 let mut pats = Vec::new();
2852 pats.push(self.parse_pat());
2853 if self.token == token::BINOP(token::OR) { self.bump(); }
2854 else { return pats; }
2858 fn parse_pat_vec_elements(
2860 ) -> (Vec<Gc<Pat>> , Option<Gc<Pat>>, Vec<Gc<Pat>> ) {
2861 let mut before = Vec::new();
2862 let mut slice = None;
2863 let mut after = Vec::new();
2864 let mut first = true;
2865 let mut before_slice = true;
2867 while self.token != token::RBRACKET {
2868 if first { first = false; }
2869 else { self.expect(&token::COMMA); }
2871 let mut is_slice = false;
2873 if self.token == token::DOTDOT {
2876 before_slice = false;
2881 if self.token == token::COMMA || self.token == token::RBRACKET {
2882 slice = Some(box(GC) ast::Pat {
2883 id: ast::DUMMY_NODE_ID,
2884 node: PatWild(PatWildMulti),
2888 let subpat = self.parse_pat();
2890 ast::Pat { node: PatIdent(_, _, _), .. } => {
2891 slice = Some(subpat);
2893 ast::Pat { span, .. } => self.span_fatal(
2894 span, "expected an identifier or nothing"
2899 let subpat = self.parse_pat();
2901 before.push(subpat);
2908 (before, slice, after)
2911 /// Parse the fields of a struct-like pattern
2912 fn parse_pat_fields(&mut self) -> (Vec<ast::FieldPat> , bool) {
2913 let mut fields = Vec::new();
2914 let mut etc = false;
2915 let mut first = true;
2916 while self.token != token::RBRACE {
2920 self.expect(&token::COMMA);
2921 // accept trailing commas
2922 if self.token == token::RBRACE { break }
2925 if self.token == token::DOTDOT {
2927 if self.token != token::RBRACE {
2928 let token_str = self.this_token_to_string();
2929 self.fatal(format!("expected `{}`, found `{}`", "}",
2930 token_str).as_slice())
2936 let bind_type = if self.eat_keyword(keywords::Mut) {
2937 BindByValue(MutMutable)
2938 } else if self.eat_keyword(keywords::Ref) {
2939 BindByRef(self.parse_mutability())
2941 BindByValue(MutImmutable)
2944 let fieldname = self.parse_ident();
2946 let subpat = if self.token == token::COLON {
2948 BindByRef(..) | BindByValue(MutMutable) => {
2949 let token_str = self.this_token_to_string();
2950 self.fatal(format!("unexpected `{}`",
2951 token_str).as_slice())
2959 let fieldpath = codemap::Spanned{span:self.last_span, node: fieldname};
2961 id: ast::DUMMY_NODE_ID,
2962 node: PatIdent(bind_type, fieldpath, None),
2963 span: self.last_span
2966 fields.push(ast::FieldPat { ident: fieldname, pat: subpat });
2968 return (fields, etc);
2971 /// Parse a pattern.
2972 pub fn parse_pat(&mut self) -> Gc<Pat> {
2973 maybe_whole!(self, NtPat);
2975 let lo = self.span.lo;
2980 token::UNDERSCORE => {
2982 pat = PatWild(PatWildSingle);
2983 hi = self.last_span.hi;
2984 return box(GC) ast::Pat {
2985 id: ast::DUMMY_NODE_ID,
2993 let sub = self.parse_pat();
2995 let last_span = self.last_span;
2997 self.obsolete(last_span, ObsoleteOwnedPattern);
2998 return box(GC) ast::Pat {
2999 id: ast::DUMMY_NODE_ID,
3004 token::BINOP(token::AND) | token::ANDAND => {
3006 let lo = self.span.lo;
3008 let sub = self.parse_pat();
3009 pat = PatRegion(sub);
3010 hi = self.last_span.hi;
3011 return box(GC) ast::Pat {
3012 id: ast::DUMMY_NODE_ID,
3018 // parse (pat,pat,pat,...) as tuple
3020 if self.token == token::RPAREN {
3023 let lit = box(GC) codemap::Spanned {
3025 span: mk_sp(lo, hi)};
3026 let expr = self.mk_expr(lo, hi, ExprLit(lit));
3029 let mut fields = vec!(self.parse_pat());
3030 if self.look_ahead(1, |t| *t != token::RPAREN) {
3031 while self.token == token::COMMA {
3033 if self.token == token::RPAREN { break; }
3034 fields.push(self.parse_pat());
3037 if fields.len() == 1 { self.expect(&token::COMMA); }
3038 self.expect(&token::RPAREN);
3039 pat = PatTup(fields);
3041 hi = self.last_span.hi;
3042 return box(GC) ast::Pat {
3043 id: ast::DUMMY_NODE_ID,
3048 token::LBRACKET => {
3049 // parse [pat,pat,...] as vector pattern
3051 let (before, slice, after) =
3052 self.parse_pat_vec_elements();
3054 self.expect(&token::RBRACKET);
3055 pat = ast::PatVec(before, slice, after);
3056 hi = self.last_span.hi;
3057 return box(GC) ast::Pat {
3058 id: ast::DUMMY_NODE_ID,
3065 // at this point, token != _, ~, &, &&, (, [
3067 if (!is_ident_or_path(&self.token) && self.token != token::MOD_SEP)
3068 || self.is_keyword(keywords::True)
3069 || self.is_keyword(keywords::False) {
3070 // Parse an expression pattern or exp .. exp.
3072 // These expressions are limited to literals (possibly
3073 // preceded by unary-minus) or identifiers.
3074 let val = self.parse_literal_maybe_minus();
3075 if self.eat(&token::DOTDOT) {
3076 let end = if is_ident_or_path(&self.token) {
3077 let path = self.parse_path(LifetimeAndTypesWithColons)
3079 let hi = self.span.hi;
3080 self.mk_expr(lo, hi, ExprPath(path))
3082 self.parse_literal_maybe_minus()
3084 pat = PatRange(val, end);
3088 } else if self.eat_keyword(keywords::Mut) {
3089 pat = self.parse_pat_ident(BindByValue(MutMutable));
3090 } else if self.eat_keyword(keywords::Ref) {
3092 let mutbl = self.parse_mutability();
3093 pat = self.parse_pat_ident(BindByRef(mutbl));
3094 } else if self.eat_keyword(keywords::Box) {
3097 // FIXME(#13910): Rename to `PatBox` and extend to full DST
3099 let sub = self.parse_pat();
3101 hi = self.last_span.hi;
3102 return box(GC) ast::Pat {
3103 id: ast::DUMMY_NODE_ID,
3108 let can_be_enum_or_struct = self.look_ahead(1, |t| {
3110 token::LPAREN | token::LBRACKET | token::LT |
3111 token::LBRACE | token::MOD_SEP => true,
3116 if self.look_ahead(1, |t| *t == token::DOTDOT) {
3117 let start = self.parse_expr_res(RESTRICT_NO_BAR_OP);
3118 self.eat(&token::DOTDOT);
3119 let end = self.parse_expr_res(RESTRICT_NO_BAR_OP);
3120 pat = PatRange(start, end);
3121 } else if is_plain_ident(&self.token) && !can_be_enum_or_struct {
3122 let id = self.parse_ident();
3123 let id_span = self.last_span;
3124 let pth1 = codemap::Spanned{span:id_span, node: id};
3125 if self.eat(&token::NOT) {
3127 let ket = token::close_delimiter_for(&self.token)
3128 .unwrap_or_else(|| self.fatal("expected open delimiter"));
3131 let tts = self.parse_seq_to_end(&ket,
3133 |p| p.parse_token_tree());
3135 let mac = MacInvocTT(ident_to_path(id_span,id), tts, EMPTY_CTXT);
3136 pat = ast::PatMac(codemap::Spanned {node: mac, span: self.span});
3138 let sub = if self.eat(&token::AT) {
3140 Some(self.parse_pat())
3145 pat = PatIdent(BindByValue(MutImmutable), pth1, sub);
3148 // parse an enum pat
3149 let enum_path = self.parse_path(LifetimeAndTypesWithColons)
3155 self.parse_pat_fields();
3157 pat = PatStruct(enum_path, fields, etc);
3160 let mut args: Vec<Gc<Pat>> = Vec::new();
3163 let is_dotdot = self.look_ahead(1, |t| {
3165 token::DOTDOT => true,
3170 // This is a "top constructor only" pat
3173 self.expect(&token::RPAREN);
3174 pat = PatEnum(enum_path, None);
3176 args = self.parse_enum_variant_seq(
3179 seq_sep_trailing_allowed(token::COMMA),
3182 pat = PatEnum(enum_path, Some(args));
3186 if !enum_path.global &&
3187 enum_path.segments.len() == 1 &&
3196 // it could still be either an enum
3197 // or an identifier pattern, resolve
3198 // will sort it out:
3199 pat = PatIdent(BindByValue(MutImmutable),
3201 span: enum_path.span,
3202 node: enum_path.segments.get(0)
3206 pat = PatEnum(enum_path, Some(args));
3214 hi = self.last_span.hi;
3216 id: ast::DUMMY_NODE_ID,
3218 span: mk_sp(lo, hi),
3222 /// Parse ident or ident @ pat
3223 /// used by the copy foo and ref foo patterns to give a good
3224 /// error message when parsing mistakes like ref foo(a,b)
3225 fn parse_pat_ident(&mut self,
3226 binding_mode: ast::BindingMode)
3228 if !is_plain_ident(&self.token) {
3229 let last_span = self.last_span;
3230 self.span_fatal(last_span,
3231 "expected identifier, found path");
3233 let ident = self.parse_ident();
3234 let last_span = self.last_span;
3235 let name = codemap::Spanned{span: last_span, node: ident};
3236 let sub = if self.eat(&token::AT) {
3237 Some(self.parse_pat())
3242 // just to be friendly, if they write something like
3244 // we end up here with ( as the current token. This shortly
3245 // leads to a parse error. Note that if there is no explicit
3246 // binding mode then we do not end up here, because the lookahead
3247 // will direct us over to parse_enum_variant()
3248 if self.token == token::LPAREN {
3249 let last_span = self.last_span;
3252 "expected identifier, found enum pattern");
3255 PatIdent(binding_mode, name, sub)
3258 /// Parse a local variable declaration
3259 fn parse_local(&mut self) -> Gc<Local> {
3260 let lo = self.span.lo;
3261 let pat = self.parse_pat();
3264 id: ast::DUMMY_NODE_ID,
3266 span: mk_sp(lo, lo),
3268 if self.eat(&token::COLON) {
3269 ty = self.parse_ty(true);
3271 let init = self.parse_initializer();
3272 box(GC) ast::Local {
3276 id: ast::DUMMY_NODE_ID,
3277 span: mk_sp(lo, self.last_span.hi),
3282 /// Parse a "let" stmt
3283 fn parse_let(&mut self) -> Gc<Decl> {
3284 let lo = self.span.lo;
3285 let local = self.parse_local();
3286 box(GC) spanned(lo, self.last_span.hi, DeclLocal(local))
3289 /// Parse a structure field
3290 fn parse_name_and_ty(&mut self, pr: Visibility,
3291 attrs: Vec<Attribute> ) -> StructField {
3292 let lo = self.span.lo;
3293 if !is_plain_ident(&self.token) {
3294 self.fatal("expected ident");
3296 let name = self.parse_ident();
3297 self.expect(&token::COLON);
3298 let ty = self.parse_ty(true);
3299 spanned(lo, self.last_span.hi, ast::StructField_ {
3300 kind: NamedField(name, pr),
3301 id: ast::DUMMY_NODE_ID,
3307 /// Parse a statement. may include decl.
3308 /// Precondition: any attributes are parsed already
3309 pub fn parse_stmt(&mut self, item_attrs: Vec<Attribute>) -> Gc<Stmt> {
3310 maybe_whole!(self, NtStmt);
3312 fn check_expected_item(p: &mut Parser, found_attrs: bool) {
3313 // If we have attributes then we should have an item
3315 let last_span = p.last_span;
3316 p.span_err(last_span, "expected item after attributes");
3320 let lo = self.span.lo;
3321 if self.is_keyword(keywords::Let) {
3322 check_expected_item(self, !item_attrs.is_empty());
3323 self.expect_keyword(keywords::Let);
3324 let decl = self.parse_let();
3325 return box(GC) spanned(lo, decl.span.hi, StmtDecl(decl, ast::DUMMY_NODE_ID));
3326 } else if is_ident(&self.token)
3327 && !token::is_any_keyword(&self.token)
3328 && self.look_ahead(1, |t| *t == token::NOT) {
3329 // it's a macro invocation:
3331 check_expected_item(self, !item_attrs.is_empty());
3333 // Potential trouble: if we allow macros with paths instead of
3334 // idents, we'd need to look ahead past the whole path here...
3335 let pth = self.parse_path(NoTypesAllowed).path;
3338 let id = if token::close_delimiter_for(&self.token).is_some() {
3339 token::special_idents::invalid // no special identifier
3344 // check that we're pointing at delimiters (need to check
3345 // again after the `if`, because of `parse_ident`
3346 // consuming more tokens).
3347 let (bra, ket) = match token::close_delimiter_for(&self.token) {
3348 Some(ket) => (self.token.clone(), ket),
3350 // we only expect an ident if we didn't parse one
3352 let ident_str = if id.name == token::special_idents::invalid.name {
3357 let tok_str = self.this_token_to_string();
3358 self.fatal(format!("expected {}`(` or `{{`, found `{}`",
3360 tok_str).as_slice())
3364 let tts = self.parse_unspanned_seq(
3368 |p| p.parse_token_tree()
3370 let hi = self.span.hi;
3372 if id.name == token::special_idents::invalid.name {
3373 return box(GC) spanned(lo, hi, StmtMac(
3374 spanned(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT)), false));
3376 // if it has a special ident, it's definitely an item
3377 return box(GC) spanned(lo, hi, StmtDecl(
3378 box(GC) spanned(lo, hi, DeclItem(
3380 lo, hi, id /*id is good here*/,
3381 ItemMac(spanned(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT))),
3382 Inherited, Vec::new(/*no attrs*/)))),
3383 ast::DUMMY_NODE_ID));
3387 let found_attrs = !item_attrs.is_empty();
3388 match self.parse_item_or_view_item(item_attrs, false) {
3391 let decl = box(GC) spanned(lo, hi, DeclItem(i));
3392 return box(GC) spanned(lo, hi, StmtDecl(decl, ast::DUMMY_NODE_ID));
3394 IoviViewItem(vi) => {
3395 self.span_fatal(vi.span,
3396 "view items must be declared at the top of the block");
3398 IoviForeignItem(_) => {
3399 self.fatal("foreign items are not allowed here");
3401 IoviNone(_) => { /* fallthrough */ }
3404 check_expected_item(self, found_attrs);
3406 // Remainder are line-expr stmts.
3407 let e = self.parse_expr_res(RESTRICT_STMT_EXPR);
3408 return box(GC) spanned(lo, e.span.hi, StmtExpr(e, ast::DUMMY_NODE_ID));
3412 /// Is this expression a successfully-parsed statement?
3413 fn expr_is_complete(&mut self, e: Gc<Expr>) -> bool {
3414 return self.restriction == RESTRICT_STMT_EXPR &&
3415 !classify::expr_requires_semi_to_be_stmt(e);
3418 /// Parse a block. No inner attrs are allowed.
3419 pub fn parse_block(&mut self) -> P<Block> {
3420 maybe_whole!(no_clone self, NtBlock);
3422 let lo = self.span.lo;
3423 self.expect(&token::LBRACE);
3425 return self.parse_block_tail_(lo, DefaultBlock, Vec::new());
3428 /// Parse a block. Inner attrs are allowed.
3429 fn parse_inner_attrs_and_block(&mut self)
3430 -> (Vec<Attribute> , P<Block>) {
3432 maybe_whole!(pair_empty self, NtBlock);
3434 let lo = self.span.lo;
3435 self.expect(&token::LBRACE);
3436 let (inner, next) = self.parse_inner_attrs_and_next();
3438 (inner, self.parse_block_tail_(lo, DefaultBlock, next))
3441 /// Precondition: already parsed the '{' or '#{'
3442 /// I guess that also means "already parsed the 'impure'" if
3443 /// necessary, and this should take a qualifier.
3444 /// Some blocks start with "#{"...
3445 fn parse_block_tail(&mut self, lo: BytePos, s: BlockCheckMode) -> P<Block> {
3446 self.parse_block_tail_(lo, s, Vec::new())
3449 /// Parse the rest of a block expression or function body
3450 fn parse_block_tail_(&mut self, lo: BytePos, s: BlockCheckMode,
3451 first_item_attrs: Vec<Attribute> ) -> P<Block> {
3452 let mut stmts = Vec::new();
3453 let mut expr = None;
3455 // wouldn't it be more uniform to parse view items only, here?
3456 let ParsedItemsAndViewItems {
3457 attrs_remaining: attrs_remaining,
3458 view_items: view_items,
3461 } = self.parse_items_and_view_items(first_item_attrs,
3464 for item in items.iter() {
3465 let decl = box(GC) spanned(item.span.lo, item.span.hi, DeclItem(*item));
3466 stmts.push(box(GC) spanned(item.span.lo, item.span.hi,
3467 StmtDecl(decl, ast::DUMMY_NODE_ID)));
3470 let mut attributes_box = attrs_remaining;
3472 while self.token != token::RBRACE {
3473 // parsing items even when they're not allowed lets us give
3474 // better error messages and recover more gracefully.
3475 attributes_box.push_all(self.parse_outer_attributes().as_slice());
3478 if !attributes_box.is_empty() {
3479 let last_span = self.last_span;
3480 self.span_err(last_span, "expected item after attributes");
3481 attributes_box = Vec::new();
3483 self.bump(); // empty
3486 // fall through and out.
3489 let stmt = self.parse_stmt(attributes_box);
3490 attributes_box = Vec::new();
3492 StmtExpr(e, stmt_id) => {
3493 // expression without semicolon
3494 if classify::stmt_ends_with_semi(&*stmt) {
3495 // Just check for errors and recover; do not eat semicolon yet.
3496 self.commit_stmt(stmt, &[], &[token::SEMI, token::RBRACE]);
3502 let span_with_semi = Span {
3504 hi: self.last_span.hi,
3505 expn_info: stmt.span.expn_info,
3507 stmts.push(box(GC) codemap::Spanned {
3508 node: StmtSemi(e, stmt_id),
3509 span: span_with_semi,
3520 StmtMac(ref m, _) => {
3521 // statement macro; might be an expr
3525 stmts.push(box(GC) codemap::Spanned {
3526 node: StmtMac((*m).clone(), true),
3531 // if a block ends in `m!(arg)` without
3532 // a `;`, it must be an expr
3534 self.mk_mac_expr(stmt.span.lo,
3543 _ => { // all other kinds of statements:
3544 stmts.push(stmt.clone());
3546 if classify::stmt_ends_with_semi(&*stmt) {
3547 self.commit_stmt_expecting(stmt, token::SEMI);
3555 if !attributes_box.is_empty() {
3556 let last_span = self.last_span;
3557 self.span_err(last_span, "expected item after attributes");
3560 let hi = self.span.hi;
3563 view_items: view_items,
3566 id: ast::DUMMY_NODE_ID,
3568 span: mk_sp(lo, hi),
3572 fn parse_unboxed_function_type(&mut self) -> UnboxedFnTy {
3573 let (optional_unboxed_closure_kind, inputs) =
3574 if self.eat(&token::OROR) {
3579 let optional_unboxed_closure_kind =
3580 self.parse_optional_unboxed_closure_kind();
3582 let inputs = self.parse_seq_to_before_or(&token::COMMA,
3584 p.parse_arg_general(false)
3587 (optional_unboxed_closure_kind, inputs)
3590 let (return_style, output) = self.parse_ret_ty();
3598 kind: match optional_unboxed_closure_kind {
3600 None => FnMutUnboxedClosureKind,
3605 // Parses a sequence of bounds if a `:` is found,
3606 // otherwise returns empty list.
3607 fn parse_colon_then_ty_param_bounds(&mut self)
3608 -> OwnedSlice<TyParamBound>
3610 if !self.eat(&token::COLON) {
3613 self.parse_ty_param_bounds()
3617 // matches bounds = ( boundseq )?
3618 // where boundseq = ( bound + boundseq ) | bound
3619 // and bound = 'region | ty
3620 // NB: The None/Some distinction is important for issue #7264.
3621 fn parse_ty_param_bounds(&mut self)
3622 -> OwnedSlice<TyParamBound>
3624 let mut result = vec!();
3627 token::LIFETIME(lifetime) => {
3628 result.push(RegionTyParamBound(ast::Lifetime {
3629 id: ast::DUMMY_NODE_ID,
3635 token::MOD_SEP | token::IDENT(..) => {
3636 let tref = self.parse_trait_ref();
3637 result.push(TraitTyParamBound(tref));
3639 token::BINOP(token::OR) | token::OROR => {
3640 let unboxed_function_type =
3641 self.parse_unboxed_function_type();
3642 result.push(UnboxedFnTyParamBound(unboxed_function_type));
3647 if !self.eat(&token::BINOP(token::PLUS)) {
3652 return OwnedSlice::from_vec(result);
3655 fn trait_ref_from_ident(ident: Ident, span: Span) -> ast::TraitRef {
3656 let segment = ast::PathSegment {
3658 lifetimes: Vec::new(),
3659 types: OwnedSlice::empty(),
3661 let path = ast::Path {
3664 segments: vec![segment],
3668 ref_id: ast::DUMMY_NODE_ID,
3672 /// Matches typaram = (unbound`?`)? IDENT optbounds ( EQ ty )?
3673 fn parse_ty_param(&mut self) -> TyParam {
3674 // This is a bit hacky. Currently we are only interested in a single
3675 // unbound, and it may only be `Sized`. To avoid backtracking and other
3676 // complications, we parse an ident, then check for `?`. If we find it,
3677 // we use the ident as the unbound, otherwise, we use it as the name of
3679 let mut span = self.span;
3680 let mut ident = self.parse_ident();
3681 let mut unbound = None;
3682 if self.eat(&token::QUESTION) {
3683 let tref = Parser::trait_ref_from_ident(ident, span);
3684 unbound = Some(TraitTyParamBound(tref));
3686 ident = self.parse_ident();
3689 let bounds = self.parse_colon_then_ty_param_bounds();
3691 let default = if self.token == token::EQ {
3693 Some(self.parse_ty(true))
3699 id: ast::DUMMY_NODE_ID,
3707 /// Parse a set of optional generic type parameter declarations. Where
3708 /// clauses are not parsed here, and must be added later via
3709 /// `parse_where_clause()`.
3711 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
3712 /// | ( < lifetimes , typaramseq ( , )? > )
3713 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
3714 pub fn parse_generics(&mut self) -> ast::Generics {
3715 if self.eat(&token::LT) {
3716 let lifetime_defs = self.parse_lifetime_defs();
3717 let mut seen_default = false;
3718 let ty_params = self.parse_seq_to_gt(Some(token::COMMA), |p| {
3719 p.forbid_lifetime();
3720 let ty_param = p.parse_ty_param();
3721 if ty_param.default.is_some() {
3722 seen_default = true;
3723 } else if seen_default {
3724 let last_span = p.last_span;
3725 p.span_err(last_span,
3726 "type parameters with a default must be trailing");
3731 lifetimes: lifetime_defs,
3732 ty_params: ty_params,
3733 where_clause: WhereClause {
3734 id: ast::DUMMY_NODE_ID,
3735 predicates: Vec::new(),
3739 ast_util::empty_generics()
3743 fn parse_generic_values_after_lt(&mut self) -> (Vec<ast::Lifetime>, Vec<P<Ty>> ) {
3744 let lifetimes = self.parse_lifetimes(token::COMMA);
3745 let result = self.parse_seq_to_gt(
3748 p.forbid_lifetime();
3752 (lifetimes, result.into_vec())
3755 fn forbid_lifetime(&mut self) {
3756 if Parser::token_is_lifetime(&self.token) {
3757 let span = self.span;
3758 self.span_fatal(span, "lifetime parameters must be declared \
3759 prior to type parameters");
3763 /// Parses an optional `where` clause and places it in `generics`.
3764 fn parse_where_clause(&mut self, generics: &mut ast::Generics) {
3765 if !self.eat_keyword(keywords::Where) {
3769 let mut parsed_something = false;
3771 let lo = self.span.lo;
3772 let ident = match self.token {
3773 token::IDENT(..) => self.parse_ident(),
3776 self.expect(&token::COLON);
3778 let bounds = self.parse_ty_param_bounds();
3779 let hi = self.span.hi;
3780 let span = mk_sp(lo, hi);
3782 if bounds.len() == 0 {
3784 "each predicate in a `where` clause must have \
3785 at least one bound in it");
3788 generics.where_clause.predicates.push(ast::WherePredicate {
3789 id: ast::DUMMY_NODE_ID,
3794 parsed_something = true;
3796 if !self.eat(&token::COMMA) {
3801 if !parsed_something {
3802 let last_span = self.last_span;
3803 self.span_err(last_span,
3804 "a `where` clause must have at least one predicate \
3809 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
3810 -> (Vec<Arg> , bool) {
3812 let mut args: Vec<Option<Arg>> =
3813 self.parse_unspanned_seq(
3816 seq_sep_trailing_allowed(token::COMMA),
3818 if p.token == token::DOTDOTDOT {
3821 if p.token != token::RPAREN {
3824 "`...` must be last in argument list for variadic function");
3829 "only foreign functions are allowed to be variadic");
3833 Some(p.parse_arg_general(named_args))
3838 let variadic = match args.pop() {
3841 // Need to put back that last arg
3848 if variadic && args.is_empty() {
3850 "variadic function must be declared with at least one named argument");
3853 let args = args.move_iter().map(|x| x.unwrap()).collect();
3858 /// Parse the argument list and result type of a function declaration
3859 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> P<FnDecl> {
3861 let (args, variadic) = self.parse_fn_args(true, allow_variadic);
3862 let (ret_style, ret_ty) = self.parse_ret_ty();
3872 fn is_self_ident(&mut self) -> bool {
3874 token::IDENT(id, false) => id.name == special_idents::self_.name,
3879 fn expect_self_ident(&mut self) -> ast::Ident {
3881 token::IDENT(id, false) if id.name == special_idents::self_.name => {
3886 let token_str = self.this_token_to_string();
3887 self.fatal(format!("expected `self`, found `{}`",
3888 token_str).as_slice())
3893 /// Parse the argument list and result type of a function
3894 /// that may have a self type.
3895 fn parse_fn_decl_with_self(&mut self, parse_arg_fn: |&mut Parser| -> Arg)
3896 -> (ExplicitSelf, P<FnDecl>) {
3897 fn maybe_parse_borrowed_explicit_self(this: &mut Parser)
3898 -> ast::ExplicitSelf_ {
3899 // The following things are possible to see here:
3904 // fn(&'lt mut self)
3906 // We already know that the current token is `&`.
3908 if this.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) {
3910 SelfRegion(None, MutImmutable, this.expect_self_ident())
3911 } else if this.look_ahead(1, |t| Parser::token_is_mutability(t)) &&
3913 |t| token::is_keyword(keywords::Self,
3916 let mutability = this.parse_mutability();
3917 SelfRegion(None, mutability, this.expect_self_ident())
3918 } else if this.look_ahead(1, |t| Parser::token_is_lifetime(t)) &&
3920 |t| token::is_keyword(keywords::Self,
3923 let lifetime = this.parse_lifetime();
3924 SelfRegion(Some(lifetime), MutImmutable, this.expect_self_ident())
3925 } else if this.look_ahead(1, |t| Parser::token_is_lifetime(t)) &&
3926 this.look_ahead(2, |t| {
3927 Parser::token_is_mutability(t)
3929 this.look_ahead(3, |t| token::is_keyword(keywords::Self,
3932 let lifetime = this.parse_lifetime();
3933 let mutability = this.parse_mutability();
3934 SelfRegion(Some(lifetime), mutability, this.expect_self_ident())
3940 self.expect(&token::LPAREN);
3942 // A bit of complexity and lookahead is needed here in order to be
3943 // backwards compatible.
3944 let lo = self.span.lo;
3945 let mut mutbl_self = MutImmutable;
3946 let explicit_self = match self.token {
3947 token::BINOP(token::AND) => {
3948 maybe_parse_borrowed_explicit_self(self)
3951 // We need to make sure it isn't a type
3952 if self.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) {
3954 drop(self.expect_self_ident());
3955 let last_span = self.last_span;
3956 self.obsolete(last_span, ObsoleteOwnedSelf)
3960 token::BINOP(token::STAR) => {
3961 // Possibly "*self" or "*mut self" -- not supported. Try to avoid
3962 // emitting cryptic "unexpected token" errors.
3964 let _mutability = if Parser::token_is_mutability(&self.token) {
3965 self.parse_mutability()
3969 if self.is_self_ident() {
3970 let span = self.span;
3971 self.span_err(span, "cannot pass self by unsafe pointer");
3974 // error case, making bogus self ident:
3975 SelfValue(special_idents::self_)
3977 token::IDENT(..) => {
3978 if self.is_self_ident() {
3979 let self_ident = self.expect_self_ident();
3981 // Determine whether this is the fully explicit form, `self:
3983 if self.eat(&token::COLON) {
3984 SelfExplicit(self.parse_ty(false), self_ident)
3986 SelfValue(self_ident)
3988 } else if Parser::token_is_mutability(&self.token) &&
3989 self.look_ahead(1, |t| {
3990 token::is_keyword(keywords::Self, t)
3992 mutbl_self = self.parse_mutability();
3993 let self_ident = self.expect_self_ident();
3995 // Determine whether this is the fully explicit form,
3997 if self.eat(&token::COLON) {
3998 SelfExplicit(self.parse_ty(false), self_ident)
4000 SelfValue(self_ident)
4002 } else if Parser::token_is_mutability(&self.token) &&
4003 self.look_ahead(1, |t| *t == token::TILDE) &&
4004 self.look_ahead(2, |t| {
4005 token::is_keyword(keywords::Self, t)
4007 mutbl_self = self.parse_mutability();
4009 drop(self.expect_self_ident());
4010 let last_span = self.last_span;
4011 self.obsolete(last_span, ObsoleteOwnedSelf);
4020 let explicit_self_sp = mk_sp(lo, self.span.hi);
4022 // shared fall-through for the three cases below. borrowing prevents simply
4023 // writing this as a closure
4024 macro_rules! parse_remaining_arguments {
4027 // If we parsed a self type, expect a comma before the argument list.
4031 let sep = seq_sep_trailing_allowed(token::COMMA);
4032 let mut fn_inputs = self.parse_seq_to_before_end(
4037 fn_inputs.unshift(Arg::new_self(explicit_self_sp, mutbl_self, $self_id));
4041 vec!(Arg::new_self(explicit_self_sp, mutbl_self, $self_id))
4044 let token_str = self.this_token_to_string();
4045 self.fatal(format!("expected `,` or `)`, found `{}`",
4046 token_str).as_slice())
4052 let fn_inputs = match explicit_self {
4054 let sep = seq_sep_trailing_allowed(token::COMMA);
4055 self.parse_seq_to_before_end(&token::RPAREN, sep, parse_arg_fn)
4057 SelfValue(id) => parse_remaining_arguments!(id),
4058 SelfRegion(_,_,id) => parse_remaining_arguments!(id),
4059 SelfExplicit(_,id) => parse_remaining_arguments!(id),
4063 self.expect(&token::RPAREN);
4065 let hi = self.span.hi;
4067 let (ret_style, ret_ty) = self.parse_ret_ty();
4069 let fn_decl = P(FnDecl {
4076 (spanned(lo, hi, explicit_self), fn_decl)
4079 // parse the |arg, arg| header on a lambda
4080 fn parse_fn_block_decl(&mut self)
4081 -> (P<FnDecl>, Option<UnboxedClosureKind>) {
4082 let (optional_unboxed_closure_kind, inputs_captures) = {
4083 if self.eat(&token::OROR) {
4086 self.expect(&token::BINOP(token::OR));
4087 let optional_unboxed_closure_kind =
4088 self.parse_optional_unboxed_closure_kind();
4089 let args = self.parse_seq_to_before_end(
4090 &token::BINOP(token::OR),
4091 seq_sep_trailing_allowed(token::COMMA),
4092 |p| p.parse_fn_block_arg()
4095 (optional_unboxed_closure_kind, args)
4098 let output = if self.eat(&token::RARROW) {
4102 id: ast::DUMMY_NODE_ID,
4109 inputs: inputs_captures,
4113 }), optional_unboxed_closure_kind)
4116 /// Parses the `(arg, arg) -> return_type` header on a procedure.
4117 fn parse_proc_decl(&mut self) -> P<FnDecl> {
4119 self.parse_unspanned_seq(&token::LPAREN,
4121 seq_sep_trailing_allowed(token::COMMA),
4122 |p| p.parse_fn_block_arg());
4124 let output = if self.eat(&token::RARROW) {
4128 id: ast::DUMMY_NODE_ID,
4142 /// Parse the name and optional generic types of a function header.
4143 fn parse_fn_header(&mut self) -> (Ident, ast::Generics) {
4144 let id = self.parse_ident();
4145 let generics = self.parse_generics();
4149 fn mk_item(&mut self, lo: BytePos, hi: BytePos, ident: Ident,
4150 node: Item_, vis: Visibility,
4151 attrs: Vec<Attribute>) -> Gc<Item> {
4155 id: ast::DUMMY_NODE_ID,
4162 /// Parse an item-position function declaration.
4163 fn parse_item_fn(&mut self, fn_style: FnStyle, abi: abi::Abi) -> ItemInfo {
4164 let (ident, mut generics) = self.parse_fn_header();
4165 let decl = self.parse_fn_decl(false);
4166 self.parse_where_clause(&mut generics);
4167 let (inner_attrs, body) = self.parse_inner_attrs_and_block();
4168 (ident, ItemFn(decl, fn_style, abi, generics, body), Some(inner_attrs))
4171 /// Parse a method in a trait impl, starting with `attrs` attributes.
4172 pub fn parse_method(&mut self,
4173 already_parsed_attrs: Option<Vec<Attribute>>)
4175 let next_attrs = self.parse_outer_attributes();
4176 let attrs = match already_parsed_attrs {
4177 Some(mut a) => { a.push_all_move(next_attrs); a }
4181 let lo = self.span.lo;
4183 // code copied from parse_macro_use_or_failure... abstraction!
4184 let (method_, hi, new_attrs) = {
4185 if !token::is_any_keyword(&self.token)
4186 && self.look_ahead(1, |t| *t == token::NOT)
4187 && (self.look_ahead(2, |t| *t == token::LPAREN)
4188 || self.look_ahead(2, |t| *t == token::LBRACE)) {
4190 let pth = self.parse_path(NoTypesAllowed).path;
4191 self.expect(&token::NOT);
4193 // eat a matched-delimiter token tree:
4194 let tts = match token::close_delimiter_for(&self.token) {
4197 self.parse_seq_to_end(&ket,
4199 |p| p.parse_token_tree())
4201 None => self.fatal("expected open delimiter")
4203 let m_ = ast::MacInvocTT(pth, tts, EMPTY_CTXT);
4204 let m: ast::Mac = codemap::Spanned { node: m_,
4205 span: mk_sp(self.span.lo,
4207 (ast::MethMac(m), self.span.hi, attrs)
4209 let visa = self.parse_visibility();
4210 let abi = if self.eat_keyword(keywords::Extern) {
4211 self.parse_opt_abi().unwrap_or(abi::C)
4212 } else if attr::contains_name(attrs.as_slice(),
4213 "rust_call_abi_hack") {
4214 // FIXME(stage0, pcwalton): Remove this awful hack after a
4215 // snapshot, and change to `extern "rust-call" fn`.
4220 let fn_style = self.parse_fn_style();
4221 let ident = self.parse_ident();
4222 let mut generics = self.parse_generics();
4223 let (explicit_self, decl) = self.parse_fn_decl_with_self(|p| {
4226 self.parse_where_clause(&mut generics);
4227 let (inner_attrs, body) = self.parse_inner_attrs_and_block();
4228 let new_attrs = attrs.append(inner_attrs.as_slice());
4229 (ast::MethDecl(ident,
4237 body.span.hi, new_attrs)
4240 box(GC) ast::Method {
4242 id: ast::DUMMY_NODE_ID,
4243 span: mk_sp(lo, hi),
4248 /// Parse trait Foo { ... }
4249 fn parse_item_trait(&mut self) -> ItemInfo {
4250 let ident = self.parse_ident();
4251 let mut tps = self.parse_generics();
4252 let sized = self.parse_for_sized();
4254 // Parse supertrait bounds.
4255 let bounds = self.parse_colon_then_ty_param_bounds();
4257 self.parse_where_clause(&mut tps);
4259 let meths = self.parse_trait_methods();
4260 (ident, ItemTrait(tps, sized, bounds, meths), None)
4263 fn parse_impl_items(&mut self) -> (Vec<ImplItem>, Vec<Attribute>) {
4264 let mut impl_items = Vec::new();
4265 self.expect(&token::LBRACE);
4266 let (inner_attrs, next) = self.parse_inner_attrs_and_next();
4267 let mut method_attrs = Some(next);
4268 while !self.eat(&token::RBRACE) {
4269 impl_items.push(MethodImplItem(self.parse_method(method_attrs)));
4270 method_attrs = None;
4272 (impl_items, inner_attrs)
4275 /// Parses two variants (with the region/type params always optional):
4276 /// impl<T> Foo { ... }
4277 /// impl<T> ToString for ~[T] { ... }
4278 fn parse_item_impl(&mut self) -> ItemInfo {
4279 // First, parse type parameters if necessary.
4280 let mut generics = self.parse_generics();
4282 // Special case: if the next identifier that follows is '(', don't
4283 // allow this to be parsed as a trait.
4284 let could_be_trait = self.token != token::LPAREN;
4287 let mut ty = self.parse_ty(true);
4289 // Parse traits, if necessary.
4290 let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) {
4291 // New-style trait. Reinterpret the type as a trait.
4292 let opt_trait_ref = match ty.node {
4293 TyPath(ref path, None, node_id) => {
4294 Some(TraitRef { path: (*path).clone(),
4297 TyPath(_, Some(_), _) => {
4298 self.span_err(ty.span,
4299 "bounded traits are only valid in type position");
4303 self.span_err(ty.span, "not a trait");
4308 ty = self.parse_ty(true);
4314 self.parse_where_clause(&mut generics);
4315 let (impl_items, attrs) = self.parse_impl_items();
4317 let ident = ast_util::impl_pretty_name(&opt_trait, &*ty);
4320 ItemImpl(generics, opt_trait, ty, impl_items),
4324 /// Parse a::B<String,int>
4325 fn parse_trait_ref(&mut self) -> TraitRef {
4327 path: self.parse_path(LifetimeAndTypesWithoutColons).path,
4328 ref_id: ast::DUMMY_NODE_ID,
4332 /// Parse struct Foo { ... }
4333 fn parse_item_struct(&mut self, is_virtual: bool) -> ItemInfo {
4334 let class_name = self.parse_ident();
4335 let mut generics = self.parse_generics();
4337 let super_struct = if self.eat(&token::COLON) {
4338 let ty = self.parse_ty(true);
4340 TyPath(_, None, _) => {
4344 self.span_err(ty.span, "not a struct");
4352 self.parse_where_clause(&mut generics);
4354 let mut fields: Vec<StructField>;
4357 if self.eat(&token::LBRACE) {
4358 // It's a record-like struct.
4359 is_tuple_like = false;
4360 fields = Vec::new();
4361 while self.token != token::RBRACE {
4362 fields.push(self.parse_struct_decl_field());
4364 if fields.len() == 0 {
4365 self.fatal(format!("unit-like struct definition should be \
4366 written as `struct {};`",
4367 token::get_ident(class_name)).as_slice());
4370 } else if self.token == token::LPAREN {
4371 // It's a tuple-like struct.
4372 is_tuple_like = true;
4373 fields = self.parse_unspanned_seq(
4376 seq_sep_trailing_allowed(token::COMMA),
4378 let attrs = p.parse_outer_attributes();
4380 let struct_field_ = ast::StructField_ {
4381 kind: UnnamedField(p.parse_visibility()),
4382 id: ast::DUMMY_NODE_ID,
4383 ty: p.parse_ty(true),
4386 spanned(lo, p.span.hi, struct_field_)
4388 if fields.len() == 0 {
4389 self.fatal(format!("unit-like struct definition should be \
4390 written as `struct {};`",
4391 token::get_ident(class_name)).as_slice());
4393 self.expect(&token::SEMI);
4394 } else if self.eat(&token::SEMI) {
4395 // It's a unit-like struct.
4396 is_tuple_like = true;
4397 fields = Vec::new();
4399 let token_str = self.this_token_to_string();
4400 self.fatal(format!("expected `{}`, `(`, or `;` after struct \
4401 name, found `{}`", "{",
4402 token_str).as_slice())
4405 let _ = ast::DUMMY_NODE_ID; // FIXME: Workaround for crazy bug.
4406 let new_id = ast::DUMMY_NODE_ID;
4408 ItemStruct(box(GC) ast::StructDef {
4410 ctor_id: if is_tuple_like { Some(new_id) } else { None },
4411 super_struct: super_struct,
4412 is_virtual: is_virtual,
4417 /// Parse a structure field declaration
4418 pub fn parse_single_struct_field(&mut self,
4420 attrs: Vec<Attribute> )
4422 let a_var = self.parse_name_and_ty(vis, attrs);
4429 let span = self.span;
4430 let token_str = self.this_token_to_string();
4431 self.span_fatal(span,
4432 format!("expected `,`, or `}}`, found `{}`",
4433 token_str).as_slice())
4439 /// Parse an element of a struct definition
4440 fn parse_struct_decl_field(&mut self) -> StructField {
4442 let attrs = self.parse_outer_attributes();
4444 if self.eat_keyword(keywords::Pub) {
4445 return self.parse_single_struct_field(Public, attrs);
4448 return self.parse_single_struct_field(Inherited, attrs);
4451 /// Parse visibility: PUB, PRIV, or nothing
4452 fn parse_visibility(&mut self) -> Visibility {
4453 if self.eat_keyword(keywords::Pub) { Public }
4457 fn parse_for_sized(&mut self) -> Option<ast::TyParamBound> {
4458 if self.eat_keyword(keywords::For) {
4459 let span = self.span;
4460 let ident = self.parse_ident();
4461 if !self.eat(&token::QUESTION) {
4463 "expected 'Sized?' after `for` in trait item");
4466 let tref = Parser::trait_ref_from_ident(ident, span);
4467 Some(TraitTyParamBound(tref))
4473 /// Given a termination token and a vector of already-parsed
4474 /// attributes (of length 0 or 1), parse all of the items in a module
4475 fn parse_mod_items(&mut self,
4477 first_item_attrs: Vec<Attribute>,
4480 // parse all of the items up to closing or an attribute.
4481 // view items are legal here.
4482 let ParsedItemsAndViewItems {
4483 attrs_remaining: attrs_remaining,
4484 view_items: view_items,
4485 items: starting_items,
4487 } = self.parse_items_and_view_items(first_item_attrs, true, true);
4488 let mut items: Vec<Gc<Item>> = starting_items;
4489 let attrs_remaining_len = attrs_remaining.len();
4491 // don't think this other loop is even necessary....
4493 let mut first = true;
4494 while self.token != term {
4495 let mut attrs = self.parse_outer_attributes();
4497 attrs = attrs_remaining.clone().append(attrs.as_slice());
4500 debug!("parse_mod_items: parse_item_or_view_item(attrs={:?})",
4502 match self.parse_item_or_view_item(attrs,
4503 true /* macros allowed */) {
4504 IoviItem(item) => items.push(item),
4505 IoviViewItem(view_item) => {
4506 self.span_fatal(view_item.span,
4507 "view items must be declared at the top of \
4511 let token_str = self.this_token_to_string();
4512 self.fatal(format!("expected item, found `{}`",
4513 token_str).as_slice())
4518 if first && attrs_remaining_len > 0u {
4519 // We parsed attributes for the first item but didn't find it
4520 let last_span = self.last_span;
4521 self.span_err(last_span, "expected item after attributes");
4525 inner: mk_sp(inner_lo, self.span.lo),
4526 view_items: view_items,
4531 fn parse_item_const(&mut self) -> ItemInfo {
4532 let m = if self.eat_keyword(keywords::Mut) {MutMutable} else {MutImmutable};
4533 let id = self.parse_ident();
4534 self.expect(&token::COLON);
4535 let ty = self.parse_ty(true);
4536 self.expect(&token::EQ);
4537 let e = self.parse_expr();
4538 self.commit_expr_expecting(e, token::SEMI);
4539 (id, ItemStatic(ty, m, e), None)
4542 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
4543 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> ItemInfo {
4544 let id_span = self.span;
4545 let id = self.parse_ident();
4546 if self.token == token::SEMI {
4548 // This mod is in an external file. Let's go get it!
4549 let (m, attrs) = self.eval_src_mod(id, outer_attrs, id_span);
4550 (id, m, Some(attrs))
4552 self.push_mod_path(id, outer_attrs);
4553 self.expect(&token::LBRACE);
4554 let mod_inner_lo = self.span.lo;
4555 let old_owns_directory = self.owns_directory;
4556 self.owns_directory = true;
4557 let (inner, next) = self.parse_inner_attrs_and_next();
4558 let m = self.parse_mod_items(token::RBRACE, next, mod_inner_lo);
4559 self.expect(&token::RBRACE);
4560 self.owns_directory = old_owns_directory;
4561 self.pop_mod_path();
4562 (id, ItemMod(m), Some(inner))
4566 fn push_mod_path(&mut self, id: Ident, attrs: &[Attribute]) {
4567 let default_path = self.id_to_interned_str(id);
4568 let file_path = match ::attr::first_attr_value_str_by_name(attrs,
4571 None => default_path,
4573 self.mod_path_stack.push(file_path)
4576 fn pop_mod_path(&mut self) {
4577 self.mod_path_stack.pop().unwrap();
4580 /// Read a module from a source file.
4581 fn eval_src_mod(&mut self,
4583 outer_attrs: &[ast::Attribute],
4585 -> (ast::Item_, Vec<ast::Attribute> ) {
4586 let mut prefix = Path::new(self.sess.span_diagnostic.cm.span_to_filename(self.span));
4588 let mod_path = Path::new(".").join_many(self.mod_path_stack.as_slice());
4589 let dir_path = prefix.join(&mod_path);
4590 let mod_string = token::get_ident(id);
4591 let (file_path, owns_directory) = match ::attr::first_attr_value_str_by_name(
4592 outer_attrs, "path") {
4593 Some(d) => (dir_path.join(d), true),
4595 let mod_name = mod_string.get().to_string();
4596 let default_path_str = format!("{}.rs", mod_name);
4597 let secondary_path_str = format!("{}/mod.rs", mod_name);
4598 let default_path = dir_path.join(default_path_str.as_slice());
4599 let secondary_path = dir_path.join(secondary_path_str.as_slice());
4600 let default_exists = default_path.exists();
4601 let secondary_exists = secondary_path.exists();
4603 if !self.owns_directory {
4604 self.span_err(id_sp,
4605 "cannot declare a new module at this location");
4606 let this_module = match self.mod_path_stack.last() {
4607 Some(name) => name.get().to_string(),
4608 None => self.root_module_name.get_ref().clone(),
4610 self.span_note(id_sp,
4611 format!("maybe move this module `{0}` \
4612 to its own directory via \
4614 this_module).as_slice());
4615 if default_exists || secondary_exists {
4616 self.span_note(id_sp,
4617 format!("... or maybe `use` the module \
4618 `{}` instead of possibly \
4620 mod_name).as_slice());
4622 self.abort_if_errors();
4625 match (default_exists, secondary_exists) {
4626 (true, false) => (default_path, false),
4627 (false, true) => (secondary_path, true),
4629 self.span_fatal(id_sp,
4630 format!("file not found for module \
4632 mod_name).as_slice());
4637 format!("file for module `{}` found at both {} \
4641 secondary_path_str).as_slice());
4647 self.eval_src_mod_from_path(file_path, owns_directory,
4648 mod_string.get().to_string(), id_sp)
4651 fn eval_src_mod_from_path(&mut self,
4653 owns_directory: bool,
4655 id_sp: Span) -> (ast::Item_, Vec<ast::Attribute> ) {
4656 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
4657 match included_mod_stack.iter().position(|p| *p == path) {
4659 let mut err = String::from_str("circular modules: ");
4660 let len = included_mod_stack.len();
4661 for p in included_mod_stack.slice(i, len).iter() {
4662 err.push_str(p.display().as_maybe_owned().as_slice());
4663 err.push_str(" -> ");
4665 err.push_str(path.display().as_maybe_owned().as_slice());
4666 self.span_fatal(id_sp, err.as_slice());
4670 included_mod_stack.push(path.clone());
4671 drop(included_mod_stack);
4674 new_sub_parser_from_file(self.sess,
4680 let mod_inner_lo = p0.span.lo;
4681 let (mod_attrs, next) = p0.parse_inner_attrs_and_next();
4682 let first_item_outer_attrs = next;
4683 let m0 = p0.parse_mod_items(token::EOF, first_item_outer_attrs, mod_inner_lo);
4684 self.sess.included_mod_stack.borrow_mut().pop();
4685 return (ast::ItemMod(m0), mod_attrs);
4688 /// Parse a function declaration from a foreign module
4689 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility,
4690 attrs: Vec<Attribute>) -> Gc<ForeignItem> {
4691 let lo = self.span.lo;
4692 self.expect_keyword(keywords::Fn);
4694 let (ident, mut generics) = self.parse_fn_header();
4695 let decl = self.parse_fn_decl(true);
4696 self.parse_where_clause(&mut generics);
4697 let hi = self.span.hi;
4698 self.expect(&token::SEMI);
4699 box(GC) ast::ForeignItem { ident: ident,
4701 node: ForeignItemFn(decl, generics),
4702 id: ast::DUMMY_NODE_ID,
4703 span: mk_sp(lo, hi),
4707 /// Parse a static item from a foreign module
4708 fn parse_item_foreign_static(&mut self, vis: ast::Visibility,
4709 attrs: Vec<Attribute> ) -> Gc<ForeignItem> {
4710 let lo = self.span.lo;
4712 self.expect_keyword(keywords::Static);
4713 let mutbl = self.eat_keyword(keywords::Mut);
4715 let ident = self.parse_ident();
4716 self.expect(&token::COLON);
4717 let ty = self.parse_ty(true);
4718 let hi = self.span.hi;
4719 self.expect(&token::SEMI);
4720 box(GC) ast::ForeignItem {
4723 node: ForeignItemStatic(ty, mutbl),
4724 id: ast::DUMMY_NODE_ID,
4725 span: mk_sp(lo, hi),
4730 /// Parse safe/unsafe and fn
4731 fn parse_fn_style(&mut self) -> FnStyle {
4732 if self.eat_keyword(keywords::Fn) { NormalFn }
4733 else if self.eat_keyword(keywords::Unsafe) {
4734 self.expect_keyword(keywords::Fn);
4737 else { self.unexpected(); }
4741 /// At this point, this is essentially a wrapper for
4742 /// parse_foreign_items.
4743 fn parse_foreign_mod_items(&mut self,
4745 first_item_attrs: Vec<Attribute> )
4747 let ParsedItemsAndViewItems {
4748 attrs_remaining: attrs_remaining,
4749 view_items: view_items,
4751 foreign_items: foreign_items
4752 } = self.parse_foreign_items(first_item_attrs, true);
4753 if ! attrs_remaining.is_empty() {
4754 let last_span = self.last_span;
4755 self.span_err(last_span,
4756 "expected item after attributes");
4758 assert!(self.token == token::RBRACE);
4761 view_items: view_items,
4762 items: foreign_items
4766 /// Parse extern crate links
4770 /// extern crate url;
4771 /// extern crate foo = "bar"; //deprecated
4772 /// extern crate "bar" as foo;
4773 fn parse_item_extern_crate(&mut self,
4775 visibility: Visibility,
4776 attrs: Vec<Attribute> )
4779 let (maybe_path, ident) = match self.token {
4780 token::IDENT(..) => {
4781 let the_ident = self.parse_ident();
4782 self.expect_one_of(&[], &[token::EQ, token::SEMI]);
4783 // NOTE - #16689 change this to a warning once
4784 // the 'as' support is in stage0
4785 let path = if self.token == token::EQ {
4787 Some(self.parse_str())
4790 self.expect(&token::SEMI);
4793 token::LIT_STR(..) | token::LIT_STR_RAW(..) => {
4794 let path = self.parse_str();
4795 self.expect_keyword(keywords::As);
4796 let the_ident = self.parse_ident();
4797 self.expect(&token::SEMI);
4798 (Some(path), the_ident)
4801 let span = self.span;
4802 let token_str = self.this_token_to_string();
4803 self.span_fatal(span,
4804 format!("expected extern crate name but \
4806 token_str).as_slice());
4810 IoviViewItem(ast::ViewItem {
4811 node: ViewItemExternCrate(ident, maybe_path, ast::DUMMY_NODE_ID),
4814 span: mk_sp(lo, self.last_span.hi)
4818 /// Parse `extern` for foreign ABIs
4821 /// `extern` is expected to have been
4822 /// consumed before calling this method
4828 fn parse_item_foreign_mod(&mut self,
4830 opt_abi: Option<abi::Abi>,
4831 visibility: Visibility,
4832 attrs: Vec<Attribute> )
4835 self.expect(&token::LBRACE);
4837 let abi = opt_abi.unwrap_or(abi::C);
4839 let (inner, next) = self.parse_inner_attrs_and_next();
4840 let m = self.parse_foreign_mod_items(abi, next);
4841 self.expect(&token::RBRACE);
4843 let last_span = self.last_span;
4844 let item = self.mk_item(lo,
4846 special_idents::invalid,
4849 maybe_append(attrs, Some(inner)));
4850 return IoviItem(item);
4853 /// Parse type Foo = Bar;
4854 fn parse_item_type(&mut self) -> ItemInfo {
4855 let ident = self.parse_ident();
4856 let mut tps = self.parse_generics();
4857 self.parse_where_clause(&mut tps);
4858 self.expect(&token::EQ);
4859 let ty = self.parse_ty(true);
4860 self.expect(&token::SEMI);
4861 (ident, ItemTy(ty, tps), None)
4864 /// Parse a structure-like enum variant definition
4865 /// this should probably be renamed or refactored...
4866 fn parse_struct_def(&mut self) -> Gc<StructDef> {
4867 let mut fields: Vec<StructField> = Vec::new();
4868 while self.token != token::RBRACE {
4869 fields.push(self.parse_struct_decl_field());
4873 return box(GC) ast::StructDef {
4881 /// Parse the part of an "enum" decl following the '{'
4882 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> EnumDef {
4883 let mut variants = Vec::new();
4884 let mut all_nullary = true;
4885 let mut have_disr = false;
4886 while self.token != token::RBRACE {
4887 let variant_attrs = self.parse_outer_attributes();
4888 let vlo = self.span.lo;
4890 let vis = self.parse_visibility();
4894 let mut args = Vec::new();
4895 let mut disr_expr = None;
4896 ident = self.parse_ident();
4897 if self.eat(&token::LBRACE) {
4898 // Parse a struct variant.
4899 all_nullary = false;
4900 kind = StructVariantKind(self.parse_struct_def());
4901 } else if self.token == token::LPAREN {
4902 all_nullary = false;
4903 let arg_tys = self.parse_enum_variant_seq(
4906 seq_sep_trailing_allowed(token::COMMA),
4907 |p| p.parse_ty(true)
4909 for ty in arg_tys.move_iter() {
4910 args.push(ast::VariantArg {
4912 id: ast::DUMMY_NODE_ID,
4915 kind = TupleVariantKind(args);
4916 } else if self.eat(&token::EQ) {
4918 disr_expr = Some(self.parse_expr());
4919 kind = TupleVariantKind(args);
4921 kind = TupleVariantKind(Vec::new());
4924 let vr = ast::Variant_ {
4926 attrs: variant_attrs,
4928 id: ast::DUMMY_NODE_ID,
4929 disr_expr: disr_expr,
4932 variants.push(P(spanned(vlo, self.last_span.hi, vr)));
4934 if !self.eat(&token::COMMA) { break; }
4936 self.expect(&token::RBRACE);
4937 if have_disr && !all_nullary {
4938 self.fatal("discriminator values can only be used with a c-like \
4942 ast::EnumDef { variants: variants }
4945 /// Parse an "enum" declaration
4946 fn parse_item_enum(&mut self) -> ItemInfo {
4947 let id = self.parse_ident();
4948 let mut generics = self.parse_generics();
4949 self.parse_where_clause(&mut generics);
4950 self.expect(&token::LBRACE);
4952 let enum_definition = self.parse_enum_def(&generics);
4953 (id, ItemEnum(enum_definition, generics), None)
4956 fn fn_expr_lookahead(tok: &token::Token) -> bool {
4958 token::LPAREN | token::AT | token::TILDE | token::BINOP(_) => true,
4963 /// Parses a string as an ABI spec on an extern type or module. Consumes
4964 /// the `extern` keyword, if one is found.
4965 fn parse_opt_abi(&mut self) -> Option<abi::Abi> {
4967 token::LIT_STR(s) | token::LIT_STR_RAW(s, _) => {
4969 let the_string = s.as_str();
4970 match abi::lookup(the_string) {
4971 Some(abi) => Some(abi),
4973 let last_span = self.last_span;
4976 format!("illegal ABI: expected one of [{}], \
4978 abi::all_names().connect(", "),
4979 the_string).as_slice());
4989 /// Parse one of the items or view items allowed by the
4990 /// flags; on failure, return IoviNone.
4991 /// NB: this function no longer parses the items inside an
4993 fn parse_item_or_view_item(&mut self,
4994 attrs: Vec<Attribute> ,
4995 macros_allowed: bool)
4998 INTERPOLATED(token::NtItem(item)) => {
5000 let new_attrs = attrs.append(item.attrs.as_slice());
5001 return IoviItem(box(GC) Item {
5009 let lo = self.span.lo;
5011 let visibility = self.parse_visibility();
5013 // must be a view item:
5014 if self.eat_keyword(keywords::Use) {
5015 // USE ITEM (IoviViewItem)
5016 let view_item = self.parse_use();
5017 self.expect(&token::SEMI);
5018 return IoviViewItem(ast::ViewItem {
5022 span: mk_sp(lo, self.last_span.hi)
5025 // either a view item or an item:
5026 if self.eat_keyword(keywords::Extern) {
5027 let next_is_mod = self.eat_keyword(keywords::Mod);
5029 if next_is_mod || self.eat_keyword(keywords::Crate) {
5031 let last_span = self.last_span;
5032 self.span_err(mk_sp(lo, last_span.hi),
5033 format!("`extern mod` is obsolete, use \
5034 `extern crate` instead \
5035 to refer to external \
5036 crates.").as_slice())
5038 return self.parse_item_extern_crate(lo, visibility, attrs);
5041 let opt_abi = self.parse_opt_abi();
5043 if self.eat_keyword(keywords::Fn) {
5044 // EXTERN FUNCTION ITEM
5045 let abi = opt_abi.unwrap_or(abi::C);
5046 let (ident, item_, extra_attrs) =
5047 self.parse_item_fn(NormalFn, abi);
5048 let last_span = self.last_span;
5049 let item = self.mk_item(lo,
5054 maybe_append(attrs, extra_attrs));
5055 return IoviItem(item);
5056 } else if self.token == token::LBRACE {
5057 return self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs);
5060 let span = self.span;
5061 let token_str = self.this_token_to_string();
5062 self.span_fatal(span,
5063 format!("expected `{}` or `fn`, found `{}`", "{",
5064 token_str).as_slice());
5067 let is_virtual = self.eat_keyword(keywords::Virtual);
5068 if is_virtual && !self.is_keyword(keywords::Struct) {
5069 let span = self.span;
5071 "`virtual` keyword may only be used with `struct`");
5074 // the rest are all guaranteed to be items:
5075 if self.is_keyword(keywords::Static) {
5078 let (ident, item_, extra_attrs) = self.parse_item_const();
5079 let last_span = self.last_span;
5080 let item = self.mk_item(lo,
5085 maybe_append(attrs, extra_attrs));
5086 return IoviItem(item);
5088 if self.is_keyword(keywords::Fn) &&
5089 self.look_ahead(1, |f| !Parser::fn_expr_lookahead(f)) {
5092 let (ident, item_, extra_attrs) =
5093 self.parse_item_fn(NormalFn, abi::Rust);
5094 let last_span = self.last_span;
5095 let item = self.mk_item(lo,
5100 maybe_append(attrs, extra_attrs));
5101 return IoviItem(item);
5103 if self.is_keyword(keywords::Unsafe)
5104 && self.look_ahead(1u, |t| *t != token::LBRACE) {
5105 // UNSAFE FUNCTION ITEM
5107 let abi = if self.eat_keyword(keywords::Extern) {
5108 self.parse_opt_abi().unwrap_or(abi::C)
5112 self.expect_keyword(keywords::Fn);
5113 let (ident, item_, extra_attrs) =
5114 self.parse_item_fn(UnsafeFn, abi);
5115 let last_span = self.last_span;
5116 let item = self.mk_item(lo,
5121 maybe_append(attrs, extra_attrs));
5122 return IoviItem(item);
5124 if self.eat_keyword(keywords::Mod) {
5126 let (ident, item_, extra_attrs) =
5127 self.parse_item_mod(attrs.as_slice());
5128 let last_span = self.last_span;
5129 let item = self.mk_item(lo,
5134 maybe_append(attrs, extra_attrs));
5135 return IoviItem(item);
5137 if self.eat_keyword(keywords::Type) {
5139 let (ident, item_, extra_attrs) = self.parse_item_type();
5140 let last_span = self.last_span;
5141 let item = self.mk_item(lo,
5146 maybe_append(attrs, extra_attrs));
5147 return IoviItem(item);
5149 if self.eat_keyword(keywords::Enum) {
5151 let (ident, item_, extra_attrs) = self.parse_item_enum();
5152 let last_span = self.last_span;
5153 let item = self.mk_item(lo,
5158 maybe_append(attrs, extra_attrs));
5159 return IoviItem(item);
5161 if self.eat_keyword(keywords::Trait) {
5163 let (ident, item_, extra_attrs) = self.parse_item_trait();
5164 let last_span = self.last_span;
5165 let item = self.mk_item(lo,
5170 maybe_append(attrs, extra_attrs));
5171 return IoviItem(item);
5173 if self.eat_keyword(keywords::Impl) {
5175 let (ident, item_, extra_attrs) = self.parse_item_impl();
5176 let last_span = self.last_span;
5177 let item = self.mk_item(lo,
5182 maybe_append(attrs, extra_attrs));
5183 return IoviItem(item);
5185 if self.eat_keyword(keywords::Struct) {
5187 let (ident, item_, extra_attrs) = self.parse_item_struct(is_virtual);
5188 let last_span = self.last_span;
5189 let item = self.mk_item(lo,
5194 maybe_append(attrs, extra_attrs));
5195 return IoviItem(item);
5197 self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility)
5200 /// Parse a foreign item; on failure, return IoviNone.
5201 fn parse_foreign_item(&mut self,
5202 attrs: Vec<Attribute> ,
5203 macros_allowed: bool)
5205 maybe_whole!(iovi self, NtItem);
5206 let lo = self.span.lo;
5208 let visibility = self.parse_visibility();
5210 if self.is_keyword(keywords::Static) {
5211 // FOREIGN STATIC ITEM
5212 let item = self.parse_item_foreign_static(visibility, attrs);
5213 return IoviForeignItem(item);
5215 if self.is_keyword(keywords::Fn) || self.is_keyword(keywords::Unsafe) {
5216 // FOREIGN FUNCTION ITEM
5217 let item = self.parse_item_foreign_fn(visibility, attrs);
5218 return IoviForeignItem(item);
5220 self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility)
5223 /// This is the fall-through for parsing items.
5224 fn parse_macro_use_or_failure(
5226 attrs: Vec<Attribute> ,
5227 macros_allowed: bool,
5229 visibility: Visibility
5230 ) -> ItemOrViewItem {
5231 if macros_allowed && !token::is_any_keyword(&self.token)
5232 && self.look_ahead(1, |t| *t == token::NOT)
5233 && (self.look_ahead(2, |t| is_plain_ident(t))
5234 || self.look_ahead(2, |t| *t == token::LPAREN)
5235 || self.look_ahead(2, |t| *t == token::LBRACE)) {
5236 // MACRO INVOCATION ITEM
5239 let pth = self.parse_path(NoTypesAllowed).path;
5240 self.expect(&token::NOT);
5242 // a 'special' identifier (like what `macro_rules!` uses)
5243 // is optional. We should eventually unify invoc syntax
5245 let id = if is_plain_ident(&self.token) {
5248 token::special_idents::invalid // no special identifier
5250 // eat a matched-delimiter token tree:
5251 let tts = match token::close_delimiter_for(&self.token) {
5254 self.parse_seq_to_end(&ket,
5256 |p| p.parse_token_tree())
5258 None => self.fatal("expected open delimiter")
5260 // single-variant-enum... :
5261 let m = ast::MacInvocTT(pth, tts, EMPTY_CTXT);
5262 let m: ast::Mac = codemap::Spanned { node: m,
5263 span: mk_sp(self.span.lo,
5265 let item_ = ItemMac(m);
5266 let last_span = self.last_span;
5267 let item = self.mk_item(lo,
5273 return IoviItem(item);
5276 // FAILURE TO PARSE ITEM
5277 if visibility != Inherited {
5278 let mut s = String::from_str("unmatched visibility `");
5279 if visibility == Public {
5285 let last_span = self.last_span;
5286 self.span_fatal(last_span, s.as_slice());
5288 return IoviNone(attrs);
5291 pub fn parse_item_with_outer_attributes(&mut self) -> Option<Gc<Item>> {
5292 let attrs = self.parse_outer_attributes();
5293 self.parse_item(attrs)
5296 pub fn parse_item(&mut self, attrs: Vec<Attribute> ) -> Option<Gc<Item>> {
5297 match self.parse_item_or_view_item(attrs, true) {
5298 IoviNone(_) => None,
5300 self.fatal("view items are not allowed here"),
5301 IoviForeignItem(_) =>
5302 self.fatal("foreign items are not allowed here"),
5303 IoviItem(item) => Some(item)
5307 /// Parse, e.g., "use a::b::{z,y}"
5308 fn parse_use(&mut self) -> ViewItem_ {
5309 return ViewItemUse(self.parse_view_path());
5313 /// Matches view_path : MOD? IDENT EQ non_global_path
5314 /// | MOD? non_global_path MOD_SEP LBRACE RBRACE
5315 /// | MOD? non_global_path MOD_SEP LBRACE ident_seq RBRACE
5316 /// | MOD? non_global_path MOD_SEP STAR
5317 /// | MOD? non_global_path
5318 fn parse_view_path(&mut self) -> Gc<ViewPath> {
5319 let lo = self.span.lo;
5321 if self.token == token::LBRACE {
5323 let idents = self.parse_unspanned_seq(
5324 &token::LBRACE, &token::RBRACE,
5325 seq_sep_trailing_allowed(token::COMMA),
5326 |p| p.parse_path_list_item());
5327 let path = ast::Path {
5328 span: mk_sp(lo, self.span.hi),
5330 segments: Vec::new()
5332 return box(GC) spanned(lo, self.span.hi,
5333 ViewPathList(path, idents, ast::DUMMY_NODE_ID));
5336 let first_ident = self.parse_ident();
5337 let mut path = vec!(first_ident);
5342 let path_lo = self.span.lo;
5343 path = vec!(self.parse_ident());
5344 while self.token == token::MOD_SEP {
5346 let id = self.parse_ident();
5349 let span = mk_sp(path_lo, self.span.hi);
5350 self.obsolete(span, ObsoleteImportRenaming);
5351 let path = ast::Path {
5354 segments: path.move_iter().map(|identifier| {
5356 identifier: identifier,
5357 lifetimes: Vec::new(),
5358 types: OwnedSlice::empty(),
5362 return box(GC) spanned(lo, self.span.hi,
5363 ViewPathSimple(first_ident, path,
5364 ast::DUMMY_NODE_ID));
5368 // foo::bar or foo::{a,b,c} or foo::*
5369 while self.token == token::MOD_SEP {
5373 token::IDENT(i, _) => {
5378 // foo::bar::{a,b,c}
5380 let idents = self.parse_unspanned_seq(
5383 seq_sep_trailing_allowed(token::COMMA),
5384 |p| p.parse_path_list_item()
5386 let path = ast::Path {
5387 span: mk_sp(lo, self.span.hi),
5389 segments: path.move_iter().map(|identifier| {
5391 identifier: identifier,
5392 lifetimes: Vec::new(),
5393 types: OwnedSlice::empty(),
5397 return box(GC) spanned(lo, self.span.hi,
5398 ViewPathList(path, idents, ast::DUMMY_NODE_ID));
5402 token::BINOP(token::STAR) => {
5404 let path = ast::Path {
5405 span: mk_sp(lo, self.span.hi),
5407 segments: path.move_iter().map(|identifier| {
5409 identifier: identifier,
5410 lifetimes: Vec::new(),
5411 types: OwnedSlice::empty(),
5415 return box(GC) spanned(lo, self.span.hi,
5416 ViewPathGlob(path, ast::DUMMY_NODE_ID));
5425 let mut rename_to = *path.get(path.len() - 1u);
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 if self.eat_keyword(keywords::As) {
5438 rename_to = self.parse_ident()
5440 return box(GC) spanned(lo,
5442 ViewPathSimple(rename_to, path, ast::DUMMY_NODE_ID));
5445 /// Parses a sequence of items. Stops when it finds program
5446 /// text that can't be parsed as an item
5447 /// - mod_items uses extern_mod_allowed = true
5448 /// - block_tail_ uses extern_mod_allowed = false
5449 fn parse_items_and_view_items(&mut self,
5450 first_item_attrs: Vec<Attribute> ,
5451 mut extern_mod_allowed: bool,
5452 macros_allowed: bool)
5453 -> ParsedItemsAndViewItems {
5454 let mut attrs = first_item_attrs.append(self.parse_outer_attributes().as_slice());
5455 // First, parse view items.
5456 let mut view_items : Vec<ast::ViewItem> = Vec::new();
5457 let mut items = Vec::new();
5459 // I think this code would probably read better as a single
5460 // loop with a mutable three-state-variable (for extern crates,
5461 // view items, and regular items) ... except that because
5462 // of macros, I'd like to delay that entire check until later.
5464 match self.parse_item_or_view_item(attrs, macros_allowed) {
5465 IoviNone(attrs) => {
5466 return ParsedItemsAndViewItems {
5467 attrs_remaining: attrs,
5468 view_items: view_items,
5470 foreign_items: Vec::new()
5473 IoviViewItem(view_item) => {
5474 match view_item.node {
5475 ViewItemUse(..) => {
5476 // `extern crate` must precede `use`.
5477 extern_mod_allowed = false;
5479 ViewItemExternCrate(..) if !extern_mod_allowed => {
5480 self.span_err(view_item.span,
5481 "\"extern crate\" declarations are \
5484 ViewItemExternCrate(..) => {}
5486 view_items.push(view_item);
5490 attrs = self.parse_outer_attributes();
5493 IoviForeignItem(_) => {
5497 attrs = self.parse_outer_attributes();
5500 // Next, parse items.
5502 match self.parse_item_or_view_item(attrs, macros_allowed) {
5503 IoviNone(returned_attrs) => {
5504 attrs = returned_attrs;
5507 IoviViewItem(view_item) => {
5508 attrs = self.parse_outer_attributes();
5509 self.span_err(view_item.span,
5510 "`use` and `extern crate` declarations must precede items");
5513 attrs = self.parse_outer_attributes();
5516 IoviForeignItem(_) => {
5522 ParsedItemsAndViewItems {
5523 attrs_remaining: attrs,
5524 view_items: view_items,
5526 foreign_items: Vec::new()
5530 /// Parses a sequence of foreign items. Stops when it finds program
5531 /// text that can't be parsed as an item
5532 fn parse_foreign_items(&mut self, first_item_attrs: Vec<Attribute> ,
5533 macros_allowed: bool)
5534 -> ParsedItemsAndViewItems {
5535 let mut attrs = first_item_attrs.append(self.parse_outer_attributes().as_slice());
5536 let mut foreign_items = Vec::new();
5538 match self.parse_foreign_item(attrs, macros_allowed) {
5539 IoviNone(returned_attrs) => {
5540 if self.token == token::RBRACE {
5541 attrs = returned_attrs;
5546 IoviViewItem(view_item) => {
5547 // I think this can't occur:
5548 self.span_err(view_item.span,
5549 "`use` and `extern crate` declarations must precede items");
5552 // FIXME #5668: this will occur for a macro invocation:
5553 self.span_fatal(item.span, "macros cannot expand to foreign items");
5555 IoviForeignItem(foreign_item) => {
5556 foreign_items.push(foreign_item);
5559 attrs = self.parse_outer_attributes();
5562 ParsedItemsAndViewItems {
5563 attrs_remaining: attrs,
5564 view_items: Vec::new(),
5566 foreign_items: foreign_items
5570 /// Parses a source module as a crate. This is the main
5571 /// entry point for the parser.
5572 pub fn parse_crate_mod(&mut self) -> Crate {
5573 let lo = self.span.lo;
5574 // parse the crate's inner attrs, maybe (oops) one
5575 // of the attrs of an item:
5576 let (inner, next) = self.parse_inner_attrs_and_next();
5577 let first_item_outer_attrs = next;
5578 // parse the items inside the crate:
5579 let m = self.parse_mod_items(token::EOF, first_item_outer_attrs, lo);
5584 config: self.cfg.clone(),
5585 span: mk_sp(lo, self.span.lo),
5586 exported_macros: Vec::new(),
5590 pub fn parse_optional_str(&mut self)
5591 -> Option<(InternedString, ast::StrStyle)> {
5592 let (s, style) = match self.token {
5593 token::LIT_STR(s) => (self.id_to_interned_str(s.ident()), ast::CookedStr),
5594 token::LIT_STR_RAW(s, n) => {
5595 (self.id_to_interned_str(s.ident()), ast::RawStr(n))
5603 pub fn parse_str(&mut self) -> (InternedString, StrStyle) {
5604 match self.parse_optional_str() {
5606 _ => self.fatal("expected string literal")