1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
14 use ast::{BareFnTy, ClosureTy};
15 use ast::{StaticRegionTyParamBound, OtherRegionTyParamBound, TraitTyParamBound};
16 use ast::{Provided, Public, FnStyle};
17 use ast::{Mod, BiAdd, Arg, Arm, Attribute, BindByRef, BindByValue};
18 use ast::{BiBitAnd, BiBitOr, BiBitXor, Block};
19 use ast::{BlockCheckMode, UnBox};
20 use ast::{Crate, CrateConfig, Decl, DeclItem};
21 use ast::{DeclLocal, DefaultBlock, UnDeref, BiDiv, EMPTY_CTXT, EnumDef, ExplicitSelf};
22 use ast::{Expr, Expr_, ExprAddrOf, ExprMatch, ExprAgain};
23 use ast::{ExprAssign, ExprAssignOp, ExprBinary, ExprBlock, ExprBox};
24 use ast::{ExprBreak, ExprCall, ExprCast};
25 use ast::{ExprField, ExprFnBlock, ExprIf, ExprIndex};
26 use ast::{ExprLit, ExprLoop, ExprMac};
27 use ast::{ExprMethodCall, ExprParen, ExprPath, ExprProc};
28 use ast::{ExprRepeat, ExprRet, ExprStruct, ExprTup, ExprUnary};
29 use ast::{ExprVec, ExprVstore, ExprVstoreSlice};
30 use ast::{ExprVstoreMutSlice, ExprWhile, ExprForLoop, Field, FnDecl};
31 use ast::{ExprVstoreUniq, Once, Many};
32 use ast::{ForeignItem, ForeignItemStatic, ForeignItemFn, ForeignMod};
33 use ast::{Ident, NormalFn, Inherited, Item, Item_, ItemStatic};
34 use ast::{ItemEnum, ItemFn, ItemForeignMod, ItemImpl};
35 use ast::{ItemMac, ItemMod, ItemStruct, ItemTrait, ItemTy, Lit, Lit_};
36 use ast::{LitBool, LitFloat, LitFloatUnsuffixed, LitInt, LitChar, LitByte, LitBinary};
37 use ast::{LitIntUnsuffixed, LitNil, LitStr, LitUint, Local, LocalLet};
38 use ast::{MutImmutable, MutMutable, Mac_, MacInvocTT, Matcher, MatchNonterminal};
39 use ast::{MatchSeq, MatchTok, Method, MutTy, BiMul, Mutability};
40 use ast::{NamedField, UnNeg, NoReturn, UnNot, P, Pat, PatEnum};
41 use ast::{PatIdent, PatLit, PatRange, PatRegion, PatStruct};
42 use ast::{PatTup, PatBox, PatWild, PatWildMulti};
43 use ast::{BiRem, Required};
44 use ast::{RetStyle, Return, BiShl, BiShr, Stmt, StmtDecl};
45 use ast::{Sized, DynSize, StaticSize};
46 use ast::{StmtExpr, StmtSemi, StmtMac, StructDef, StructField};
47 use ast::{StructVariantKind, BiSub};
49 use ast::{SelfRegion, SelfStatic, SelfUniq, SelfValue};
50 use ast::{TokenTree, TraitMethod, TraitRef, TTDelim, TTSeq, TTTok};
51 use ast::{TTNonterminal, TupleVariantKind, Ty, Ty_, TyBot, TyBox};
52 use ast::{TypeField, TyFixedLengthVec, TyClosure, TyProc, TyBareFn};
53 use ast::{TyTypeof, TyInfer, TypeMethod};
54 use ast::{TyNil, TyParam, TyParamBound, TyParen, TyPath, TyPtr, TyRptr};
55 use ast::{TyTup, TyU32, TyUnboxedFn, TyUniq, TyVec, UnUniq};
56 use ast::{UnboxedFnTy, UnboxedFnTyParamBound, UnnamedField, UnsafeBlock};
57 use ast::{UnsafeFn, ViewItem, ViewItem_, ViewItemExternCrate, ViewItemUse};
58 use ast::{ViewPath, ViewPathGlob, ViewPathList, ViewPathSimple};
61 use ast_util::{as_prec, ident_to_path, lit_is_str, operator_prec};
63 use codemap::{Span, BytePos, Spanned, spanned, mk_sp};
65 use parse::attr::ParserAttr;
67 use parse::common::{SeqSep, seq_sep_none};
68 use parse::common::{seq_sep_trailing_disallowed, seq_sep_trailing_allowed};
69 use parse::lexer::Reader;
70 use parse::lexer::TokenAndSpan;
71 use parse::obsolete::*;
72 use parse::token::{INTERPOLATED, InternedString, can_begin_expr};
73 use parse::token::{is_ident, is_ident_or_path, is_plain_ident};
74 use parse::token::{keywords, special_idents, token_to_binop};
76 use parse::{new_sub_parser_from_file, ParseSess};
77 use owned_slice::OwnedSlice;
79 use std::collections::HashSet;
80 use std::mem::replace;
82 use std::gc::{Gc, GC};
84 #[allow(non_camel_case_types)]
85 #[deriving(PartialEq)]
86 pub enum restriction {
90 RESTRICT_NO_BAR_OR_DOUBLEBAR_OP,
91 RESTRICT_NO_STRUCT_LITERAL,
94 type ItemInfo = (Ident, Item_, Option<Vec<Attribute> >);
96 /// How to parse a path. There are four different kinds of paths, all of which
97 /// are parsed somewhat differently.
98 #[deriving(PartialEq)]
99 pub enum PathParsingMode {
100 /// A path with no type parameters; e.g. `foo::bar::Baz`
102 /// A path with a lifetime and type parameters, with no double colons
103 /// before the type parameters; e.g. `foo::bar<'a>::Baz<T>`
104 LifetimeAndTypesWithoutColons,
105 /// A path with a lifetime and type parameters with double colons before
106 /// the type parameters; e.g. `foo::bar::<'a>::Baz::<T>`
107 LifetimeAndTypesWithColons,
108 /// A path with a lifetime and type parameters with bounds before the last
109 /// set of type parameters only; e.g. `foo::bar<'a>::Baz+X+Y<T>` This
110 /// form does not use extra double colons.
111 LifetimeAndTypesAndBounds,
114 /// A path paired with optional type bounds.
115 pub struct PathAndBounds {
117 pub bounds: Option<OwnedSlice<TyParamBound>>,
120 enum ItemOrViewItem {
121 // Indicates a failure to parse any kind of item. The attributes are
123 IoviNone(Vec<Attribute>),
125 IoviForeignItem(Gc<ForeignItem>),
126 IoviViewItem(ViewItem)
130 // Possibly accept an `INTERPOLATED` expression (a pre-parsed expression
131 // dropped into the token stream, which happens while parsing the
132 // result of macro expansion)
133 /* Placement of these is not as complex as I feared it would be.
134 The important thing is to make sure that lookahead doesn't balk
135 at INTERPOLATED tokens */
136 macro_rules! maybe_whole_expr (
139 let found = match $p.token {
140 INTERPOLATED(token::NtExpr(e)) => {
143 INTERPOLATED(token::NtPath(_)) => {
144 // FIXME: The following avoids an issue with lexical borrowck scopes,
145 // but the clone is unfortunate.
146 let pt = match $p.token {
147 INTERPOLATED(token::NtPath(ref pt)) => (**pt).clone(),
151 Some($p.mk_expr(span.lo, span.hi, ExprPath(pt)))
153 INTERPOLATED(token::NtBlock(b)) => {
155 Some($p.mk_expr(span.lo, span.hi, ExprBlock(b)))
170 // As above, but for things other than expressions
171 macro_rules! maybe_whole (
172 ($p:expr, $constructor:ident) => (
174 let found = match ($p).token {
175 INTERPOLATED(token::$constructor(_)) => {
176 Some(($p).bump_and_get())
181 Some(INTERPOLATED(token::$constructor(x))) => {
188 (no_clone $p:expr, $constructor:ident) => (
190 let found = match ($p).token {
191 INTERPOLATED(token::$constructor(_)) => {
192 Some(($p).bump_and_get())
197 Some(INTERPOLATED(token::$constructor(x))) => {
204 (deref $p:expr, $constructor:ident) => (
206 let found = match ($p).token {
207 INTERPOLATED(token::$constructor(_)) => {
208 Some(($p).bump_and_get())
213 Some(INTERPOLATED(token::$constructor(x))) => {
220 (Some $p:expr, $constructor:ident) => (
222 let found = match ($p).token {
223 INTERPOLATED(token::$constructor(_)) => {
224 Some(($p).bump_and_get())
229 Some(INTERPOLATED(token::$constructor(x))) => {
230 return Some(x.clone()),
236 (iovi $p:expr, $constructor:ident) => (
238 let found = match ($p).token {
239 INTERPOLATED(token::$constructor(_)) => {
240 Some(($p).bump_and_get())
245 Some(INTERPOLATED(token::$constructor(x))) => {
246 return IoviItem(x.clone())
252 (pair_empty $p:expr, $constructor:ident) => (
254 let found = match ($p).token {
255 INTERPOLATED(token::$constructor(_)) => {
256 Some(($p).bump_and_get())
261 Some(INTERPOLATED(token::$constructor(x))) => {
262 return (Vec::new(), x)
271 fn maybe_append(lhs: Vec<Attribute> , rhs: Option<Vec<Attribute> >)
275 Some(ref attrs) => lhs.append(attrs.as_slice())
280 struct ParsedItemsAndViewItems {
281 attrs_remaining: Vec<Attribute>,
282 view_items: Vec<ViewItem>,
283 items: Vec<Gc<Item>>,
284 foreign_items: Vec<Gc<ForeignItem>>
287 /* ident is handled by common.rs */
289 pub struct Parser<'a> {
290 pub sess: &'a ParseSess,
291 // the current token:
292 pub token: token::Token,
293 // the span of the current token:
295 // the span of the prior token:
297 pub cfg: CrateConfig,
298 // the previous token or None (only stashed sometimes).
299 pub last_token: Option<Box<token::Token>>,
300 pub buffer: [TokenAndSpan, ..4],
301 pub buffer_start: int,
303 pub tokens_consumed: uint,
304 pub restriction: restriction,
305 pub quote_depth: uint, // not (yet) related to the quasiquoter
306 pub reader: Box<Reader>,
307 pub interner: Rc<token::IdentInterner>,
308 /// The set of seen errors about obsolete syntax. Used to suppress
309 /// extra detail when the same error is seen twice
310 pub obsolete_set: HashSet<ObsoleteSyntax>,
311 /// Used to determine the path to externally loaded source files
312 pub mod_path_stack: Vec<InternedString>,
313 /// Stack of spans of open delimiters. Used for error message.
314 pub open_braces: Vec<Span>,
315 /// Flag if this parser "owns" the directory that it is currently parsing
316 /// in. This will affect how nested files are looked up.
317 pub owns_directory: bool,
318 /// Name of the root module this parser originated from. If `None`, then the
319 /// name is not known. This does not change while the parser is descending
320 /// into modules, and sub-parsers have new values for this name.
321 pub root_module_name: Option<String>,
324 fn is_plain_ident_or_underscore(t: &token::Token) -> bool {
325 is_plain_ident(t) || *t == token::UNDERSCORE
328 impl<'a> Parser<'a> {
329 pub fn new(sess: &'a ParseSess, cfg: ast::CrateConfig,
330 mut rdr: Box<Reader>) -> Parser<'a> {
331 let tok0 = rdr.next_token();
333 let placeholder = TokenAndSpan {
334 tok: token::UNDERSCORE,
340 interner: token::get_ident_interner(),
356 restriction: UNRESTRICTED,
358 obsolete_set: HashSet::new(),
359 mod_path_stack: Vec::new(),
360 open_braces: Vec::new(),
361 owns_directory: true,
362 root_module_name: None,
365 // convert a token to a string using self's reader
366 pub fn token_to_str(token: &token::Token) -> String {
370 // convert the current token to a string using self's reader
371 pub fn this_token_to_str(&mut self) -> String {
372 Parser::token_to_str(&self.token)
375 pub fn unexpected_last(&mut self, t: &token::Token) -> ! {
376 let token_str = Parser::token_to_str(t);
377 let last_span = self.last_span;
378 self.span_fatal(last_span, format!("unexpected token: `{}`",
379 token_str).as_slice());
382 pub fn unexpected(&mut self) -> ! {
383 let this_token = self.this_token_to_str();
384 self.fatal(format!("unexpected token: `{}`", this_token).as_slice());
387 // expect and consume the token t. Signal an error if
388 // the next token is not t.
389 pub fn expect(&mut self, t: &token::Token) {
390 if self.token == *t {
393 let token_str = Parser::token_to_str(t);
394 let this_token_str = self.this_token_to_str();
395 self.fatal(format!("expected `{}` but found `{}`",
397 this_token_str).as_slice())
401 // Expect next token to be edible or inedible token. If edible,
402 // then consume it; if inedible, then return without consuming
403 // anything. Signal a fatal error if next token is unexpected.
404 pub fn expect_one_of(&mut self,
405 edible: &[token::Token],
406 inedible: &[token::Token]) {
407 fn tokens_to_str(tokens: &[token::Token]) -> String {
408 let mut i = tokens.iter();
409 // This might be a sign we need a connect method on Iterator.
411 .map_or("".to_string(), |t| Parser::token_to_str(t));
415 b.push_str(Parser::token_to_str(a).as_slice());
419 if edible.contains(&self.token) {
421 } else if inedible.contains(&self.token) {
422 // leave it in the input
424 let expected = edible.iter().map(|x| (*x).clone()).collect::<Vec<_>>().append(inedible);
425 let expect = tokens_to_str(expected.as_slice());
426 let actual = self.this_token_to_str();
428 (if expected.len() != 1 {
429 (format!("expected one of `{}` but found `{}`",
433 (format!("expected `{}` but found `{}`",
441 // Check for erroneous `ident { }`; if matches, signal error and
442 // recover (without consuming any expected input token). Returns
443 // true if and only if input was consumed for recovery.
444 pub fn check_for_erroneous_unit_struct_expecting(&mut self, expected: &[token::Token]) -> bool {
445 if self.token == token::LBRACE
446 && expected.iter().all(|t| *t != token::LBRACE)
447 && self.look_ahead(1, |t| *t == token::RBRACE) {
448 // matched; signal non-fatal error and recover.
449 let span = self.span;
451 "unit-like struct construction is written with no trailing `{ }`");
452 self.eat(&token::LBRACE);
453 self.eat(&token::RBRACE);
460 // Commit to parsing a complete expression `e` expected to be
461 // followed by some token from the set edible + inedible. Recover
462 // from anticipated input errors, discarding erroneous characters.
463 pub fn commit_expr(&mut self, e: Gc<Expr>, edible: &[token::Token],
464 inedible: &[token::Token]) {
465 debug!("commit_expr {:?}", e);
468 // might be unit-struct construction; check for recoverableinput error.
469 let expected = edible.iter().map(|x| (*x).clone()).collect::<Vec<_>>()
471 self.check_for_erroneous_unit_struct_expecting(
472 expected.as_slice());
476 self.expect_one_of(edible, inedible)
479 pub fn commit_expr_expecting(&mut self, e: Gc<Expr>, edible: token::Token) {
480 self.commit_expr(e, &[edible], &[])
483 // Commit to parsing a complete statement `s`, which expects to be
484 // followed by some token from the set edible + inedible. Check
485 // for recoverable input errors, discarding erroneous characters.
486 pub fn commit_stmt(&mut self, s: Gc<Stmt>, edible: &[token::Token],
487 inedible: &[token::Token]) {
488 debug!("commit_stmt {:?}", s);
489 let _s = s; // unused, but future checks might want to inspect `s`.
490 if self.last_token.as_ref().map_or(false, |t| is_ident_or_path(*t)) {
491 let expected = edible.iter().map(|x| (*x).clone()).collect::<Vec<_>>()
492 .append(inedible.as_slice());
493 self.check_for_erroneous_unit_struct_expecting(
494 expected.as_slice());
496 self.expect_one_of(edible, inedible)
499 pub fn commit_stmt_expecting(&mut self, s: Gc<Stmt>, edible: token::Token) {
500 self.commit_stmt(s, &[edible], &[])
503 pub fn parse_ident(&mut self) -> ast::Ident {
504 self.check_strict_keywords();
505 self.check_reserved_keywords();
507 token::IDENT(i, _) => {
511 token::INTERPOLATED(token::NtIdent(..)) => {
512 self.bug("ident interpolation not converted to real token");
515 let token_str = self.this_token_to_str();
516 self.fatal((format!("expected ident, found `{}`",
517 token_str)).as_slice())
522 pub fn parse_path_list_ident(&mut self) -> ast::PathListIdent {
523 let lo = self.span.lo;
524 let ident = self.parse_ident();
525 let hi = self.last_span.hi;
526 spanned(lo, hi, ast::PathListIdent_ { name: ident,
527 id: ast::DUMMY_NODE_ID })
530 // consume token 'tok' if it exists. Returns true if the given
531 // token was present, false otherwise.
532 pub fn eat(&mut self, tok: &token::Token) -> bool {
533 let is_present = self.token == *tok;
534 if is_present { self.bump() }
538 pub fn is_keyword(&mut self, kw: keywords::Keyword) -> bool {
539 token::is_keyword(kw, &self.token)
542 // if the next token is the given keyword, eat it and return
543 // true. Otherwise, return false.
544 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
545 let is_kw = match self.token {
546 token::IDENT(sid, false) => kw.to_ident().name == sid.name,
549 if is_kw { self.bump() }
553 // if the given word is not a keyword, signal an error.
554 // if the next token is not the given word, signal an error.
555 // otherwise, eat it.
556 pub fn expect_keyword(&mut self, kw: keywords::Keyword) {
557 if !self.eat_keyword(kw) {
558 let id_interned_str = token::get_ident(kw.to_ident());
559 let token_str = self.this_token_to_str();
560 self.fatal(format!("expected `{}`, found `{}`",
561 id_interned_str, token_str).as_slice())
565 // signal an error if the given string is a strict keyword
566 pub fn check_strict_keywords(&mut self) {
567 if token::is_strict_keyword(&self.token) {
568 let token_str = self.this_token_to_str();
569 let span = self.span;
571 format!("found `{}` in ident position",
572 token_str).as_slice());
576 // signal an error if the current token is a reserved keyword
577 pub fn check_reserved_keywords(&mut self) {
578 if token::is_reserved_keyword(&self.token) {
579 let token_str = self.this_token_to_str();
580 self.fatal(format!("`{}` is a reserved keyword",
581 token_str).as_slice())
585 // Expect and consume an `&`. If `&&` is seen, replace it with a single
586 // `&` and continue. If an `&` is not seen, signal an error.
587 fn expect_and(&mut self) {
589 token::BINOP(token::AND) => self.bump(),
591 let span = self.span;
592 let lo = span.lo + BytePos(1);
593 self.replace_token(token::BINOP(token::AND), lo, span.hi)
596 let token_str = self.this_token_to_str();
598 Parser::token_to_str(&token::BINOP(token::AND));
599 self.fatal(format!("expected `{}`, found `{}`",
601 token_str).as_slice())
606 // Expect and consume a `|`. If `||` is seen, replace it with a single
607 // `|` and continue. If a `|` is not seen, signal an error.
608 fn expect_or(&mut self) {
610 token::BINOP(token::OR) => self.bump(),
612 let span = self.span;
613 let lo = span.lo + BytePos(1);
614 self.replace_token(token::BINOP(token::OR), lo, span.hi)
617 let found_token = self.this_token_to_str();
619 Parser::token_to_str(&token::BINOP(token::OR));
620 self.fatal(format!("expected `{}`, found `{}`",
622 found_token).as_slice())
627 // Attempt to consume a `<`. If `<<` is seen, replace it with a single
628 // `<` and continue. If a `<` is not seen, return false.
630 // This is meant to be used when parsing generics on a path to get the
631 // starting token. The `force` parameter is used to forcefully break up a
632 // `<<` token. If `force` is false, then `<<` is only broken when a lifetime
633 // shows up next. For example, consider the expression:
635 // foo as bar << test
637 // The parser needs to know if `bar <<` is the start of a generic path or if
638 // it's a left-shift token. If `test` were a lifetime, then it's impossible
639 // for the token to be a left-shift, but if it's not a lifetime, then it's
640 // considered a left-shift.
642 // The reason for this is that the only current ambiguity with `<<` is when
643 // parsing closure types:
646 // impl Foo<<'a> ||>() { ... }
647 fn eat_lt(&mut self, force: bool) -> bool {
649 token::LT => { self.bump(); true }
650 token::BINOP(token::SHL) => {
651 let next_lifetime = self.look_ahead(1, |t| match *t {
652 token::LIFETIME(..) => true,
655 if force || next_lifetime {
656 let span = self.span;
657 let lo = span.lo + BytePos(1);
658 self.replace_token(token::LT, lo, span.hi);
668 fn expect_lt(&mut self) {
669 if !self.eat_lt(true) {
670 let found_token = self.this_token_to_str();
671 let token_str = Parser::token_to_str(&token::LT);
672 self.fatal(format!("expected `{}`, found `{}`",
674 found_token).as_slice())
678 // Parse a sequence bracketed by `|` and `|`, stopping before the `|`.
679 fn parse_seq_to_before_or<T>(
682 f: |&mut Parser| -> T)
684 let mut first = true;
685 let mut vector = Vec::new();
686 while self.token != token::BINOP(token::OR) &&
687 self.token != token::OROR {
699 // expect and consume a GT. if a >> is seen, replace it
700 // with a single > and continue. If a GT is not seen,
702 pub fn expect_gt(&mut self) {
704 token::GT => self.bump(),
705 token::BINOP(token::SHR) => {
706 let span = self.span;
707 let lo = span.lo + BytePos(1);
708 self.replace_token(token::GT, lo, span.hi)
710 token::BINOPEQ(token::SHR) => {
711 let span = self.span;
712 let lo = span.lo + BytePos(1);
713 self.replace_token(token::GE, lo, span.hi)
716 let span = self.span;
717 let lo = span.lo + BytePos(1);
718 self.replace_token(token::EQ, lo, span.hi)
721 let gt_str = Parser::token_to_str(&token::GT);
722 let this_token_str = self.this_token_to_str();
723 self.fatal(format!("expected `{}`, found `{}`",
725 this_token_str).as_slice())
730 // parse a sequence bracketed by '<' and '>', stopping
732 pub fn parse_seq_to_before_gt<T>(
734 sep: Option<token::Token>,
735 f: |&mut Parser| -> T)
737 let mut first = true;
738 let mut v = Vec::new();
739 while self.token != token::GT
740 && self.token != token::BINOP(token::SHR)
741 && self.token != token::GE
742 && self.token != token::BINOPEQ(token::SHR) {
745 if first { first = false; }
746 else { self.expect(t); }
752 return OwnedSlice::from_vec(v);
755 pub fn parse_seq_to_gt<T>(
757 sep: Option<token::Token>,
758 f: |&mut Parser| -> T)
760 let v = self.parse_seq_to_before_gt(sep, f);
765 // parse a sequence, including the closing delimiter. The function
766 // f must consume tokens until reaching the next separator or
768 pub fn parse_seq_to_end<T>(
772 f: |&mut Parser| -> T)
774 let val = self.parse_seq_to_before_end(ket, sep, f);
779 // parse a sequence, not including the closing delimiter. The function
780 // f must consume tokens until reaching the next separator or
782 pub fn parse_seq_to_before_end<T>(
786 f: |&mut Parser| -> T)
788 let mut first: bool = true;
790 while self.token != *ket {
793 if first { first = false; }
794 else { self.expect(t); }
798 if sep.trailing_sep_allowed && self.token == *ket { break; }
804 // parse a sequence, including the closing delimiter. The function
805 // f must consume tokens until reaching the next separator or
807 pub fn parse_unspanned_seq<T>(
812 f: |&mut Parser| -> T)
815 let result = self.parse_seq_to_before_end(ket, sep, f);
820 // parse a sequence parameter of enum variant. For consistency purposes,
821 // these should not be empty.
822 pub fn parse_enum_variant_seq<T>(
827 f: |&mut Parser| -> T)
829 let result = self.parse_unspanned_seq(bra, ket, sep, f);
830 if result.is_empty() {
831 let last_span = self.last_span;
832 self.span_err(last_span,
833 "nullary enum variants are written with no trailing `( )`");
838 // NB: Do not use this function unless you actually plan to place the
839 // spanned list in the AST.
845 f: |&mut Parser| -> T)
846 -> Spanned<Vec<T> > {
847 let lo = self.span.lo;
849 let result = self.parse_seq_to_before_end(ket, sep, f);
850 let hi = self.span.hi;
852 spanned(lo, hi, result)
855 // advance the parser by one token
856 pub fn bump(&mut self) {
857 self.last_span = self.span;
858 // Stash token for error recovery (sometimes; clone is not necessarily cheap).
859 self.last_token = if is_ident_or_path(&self.token) {
860 Some(box self.token.clone())
864 let next = if self.buffer_start == self.buffer_end {
865 self.reader.next_token()
867 // Avoid token copies with `replace`.
868 let buffer_start = self.buffer_start as uint;
869 let next_index = (buffer_start + 1) & 3 as uint;
870 self.buffer_start = next_index as int;
872 let placeholder = TokenAndSpan {
873 tok: token::UNDERSCORE,
876 replace(&mut self.buffer[buffer_start], placeholder)
879 self.token = next.tok;
880 self.tokens_consumed += 1u;
883 // Advance the parser by one token and return the bumped token.
884 pub fn bump_and_get(&mut self) -> token::Token {
885 let old_token = replace(&mut self.token, token::UNDERSCORE);
890 // EFFECT: replace the current token and span with the given one
891 pub fn replace_token(&mut self,
895 self.last_span = mk_sp(self.span.lo, lo);
897 self.span = mk_sp(lo, hi);
899 pub fn buffer_length(&mut self) -> int {
900 if self.buffer_start <= self.buffer_end {
901 return self.buffer_end - self.buffer_start;
903 return (4 - self.buffer_start) + self.buffer_end;
905 pub fn look_ahead<R>(&mut self, distance: uint, f: |&token::Token| -> R)
907 let dist = distance as int;
908 while self.buffer_length() < dist {
909 self.buffer[self.buffer_end as uint] = self.reader.next_token();
910 self.buffer_end = (self.buffer_end + 1) & 3;
912 f(&self.buffer[((self.buffer_start + dist - 1) & 3) as uint].tok)
914 pub fn fatal(&mut self, m: &str) -> ! {
915 self.sess.span_diagnostic.span_fatal(self.span, m)
917 pub fn span_fatal(&mut self, sp: Span, m: &str) -> ! {
918 self.sess.span_diagnostic.span_fatal(sp, m)
920 pub fn span_note(&mut self, sp: Span, m: &str) {
921 self.sess.span_diagnostic.span_note(sp, m)
923 pub fn bug(&mut self, m: &str) -> ! {
924 self.sess.span_diagnostic.span_bug(self.span, m)
926 pub fn warn(&mut self, m: &str) {
927 self.sess.span_diagnostic.span_warn(self.span, m)
929 pub fn span_warn(&mut self, sp: Span, m: &str) {
930 self.sess.span_diagnostic.span_warn(sp, m)
932 pub fn span_err(&mut self, sp: Span, m: &str) {
933 self.sess.span_diagnostic.span_err(sp, m)
935 pub fn abort_if_errors(&mut self) {
936 self.sess.span_diagnostic.handler().abort_if_errors();
939 pub fn id_to_interned_str(&mut self, id: Ident) -> InternedString {
943 // Is the current token one of the keywords that signals a bare function
945 pub fn token_is_bare_fn_keyword(&mut self) -> bool {
946 if token::is_keyword(keywords::Fn, &self.token) {
950 if token::is_keyword(keywords::Unsafe, &self.token) ||
951 token::is_keyword(keywords::Once, &self.token) {
952 return self.look_ahead(1, |t| token::is_keyword(keywords::Fn, t))
958 // Is the current token one of the keywords that signals a closure type?
959 pub fn token_is_closure_keyword(&mut self) -> bool {
960 token::is_keyword(keywords::Unsafe, &self.token) ||
961 token::is_keyword(keywords::Once, &self.token)
964 // Is the current token one of the keywords that signals an old-style
965 // closure type (with explicit sigil)?
966 pub fn token_is_old_style_closure_keyword(&mut self) -> bool {
967 token::is_keyword(keywords::Unsafe, &self.token) ||
968 token::is_keyword(keywords::Once, &self.token) ||
969 token::is_keyword(keywords::Fn, &self.token)
972 pub fn token_is_lifetime(tok: &token::Token) -> bool {
974 token::LIFETIME(..) => true,
979 pub fn get_lifetime(&mut self) -> ast::Ident {
981 token::LIFETIME(ref ident) => *ident,
982 _ => self.bug("not a lifetime"),
986 // parse a TyBareFn type:
987 pub fn parse_ty_bare_fn(&mut self) -> Ty_ {
990 [unsafe] [extern "ABI"] fn <'lt> (S) -> T
991 ^~~~^ ^~~~^ ^~~~^ ^~^ ^
1000 let fn_style = self.parse_unsafety();
1001 let abi = if self.eat_keyword(keywords::Extern) {
1002 self.parse_opt_abi().unwrap_or(abi::C)
1007 self.expect_keyword(keywords::Fn);
1008 let (decl, lifetimes) = self.parse_ty_fn_decl(true);
1009 return TyBareFn(box(GC) BareFnTy {
1012 lifetimes: lifetimes,
1017 // Parses a procedure type (`proc`). The initial `proc` keyword must
1018 // already have been parsed.
1019 pub fn parse_proc_type(&mut self) -> Ty_ {
1022 proc <'lt> (S) [:Bounds] -> T
1023 ^~~^ ^~~~^ ^ ^~~~~~~~^ ^
1033 let lifetimes = if self.eat(&token::LT) {
1034 let lifetimes = self.parse_lifetimes();
1041 let (inputs, variadic) = self.parse_fn_args(false, false);
1043 if self.eat(&token::COLON) {
1044 let (_, bounds) = self.parse_ty_param_bounds(false);
1050 let (ret_style, ret_ty) = self.parse_ret_ty();
1051 let decl = P(FnDecl {
1057 TyProc(box(GC) ClosureTy {
1062 lifetimes: lifetimes,
1066 // parse a TyClosure type
1067 pub fn parse_ty_closure(&mut self) -> Ty_ {
1070 [unsafe] [once] <'lt> |S| [:Bounds] -> T
1071 ^~~~~~~^ ^~~~~^ ^~~~^ ^ ^~~~~~~~^ ^
1073 | | | | | Return type
1074 | | | | Closure bounds
1075 | | | Argument types
1077 | Once-ness (a.k.a., affine)
1082 let fn_style = self.parse_unsafety();
1083 let onceness = if self.eat_keyword(keywords::Once) {Once} else {Many};
1085 let lifetimes = if self.eat(&token::LT) {
1086 let lifetimes = self.parse_lifetimes();
1094 let (is_unboxed, inputs) = if self.eat(&token::OROR) {
1099 let is_unboxed = 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);
1110 let inputs = self.parse_seq_to_before_or(
1112 |p| p.parse_arg_general(false));
1114 (is_unboxed, inputs)
1117 let (region, bounds) = {
1118 if self.eat(&token::COLON) {
1119 let (region, bounds) = self.parse_ty_param_bounds(true);
1120 (region, Some(bounds))
1126 let (return_style, output) = self.parse_ret_ty();
1127 let decl = P(FnDecl {
1135 TyUnboxedFn(box(GC) UnboxedFnTy {
1139 TyClosure(box(GC) ClosureTy {
1144 lifetimes: lifetimes,
1149 pub fn parse_unsafety(&mut self) -> FnStyle {
1150 if self.eat_keyword(keywords::Unsafe) {
1157 // parse a function type (following the 'fn')
1158 pub fn parse_ty_fn_decl(&mut self, allow_variadic: bool)
1159 -> (P<FnDecl>, Vec<ast::Lifetime>) {
1170 let lifetimes = if self.eat(&token::LT) {
1171 let lifetimes = self.parse_lifetimes();
1178 let (inputs, variadic) = self.parse_fn_args(false, allow_variadic);
1179 let (ret_style, ret_ty) = self.parse_ret_ty();
1180 let decl = P(FnDecl {
1189 // parse the methods in a trait declaration
1190 pub fn parse_trait_methods(&mut self) -> Vec<TraitMethod> {
1191 self.parse_unspanned_seq(
1196 let attrs = p.parse_outer_attributes();
1199 // NB: at the moment, trait methods are public by default; this
1201 let vis = p.parse_visibility();
1202 let style = p.parse_fn_style();
1203 let ident = p.parse_ident();
1205 let generics = p.parse_generics();
1207 let (explicit_self, d) = p.parse_fn_decl_with_self(|p| {
1208 // This is somewhat dubious; We don't want to allow argument
1209 // names to be left off if there is a definition...
1210 p.parse_arg_general(false)
1213 let hi = p.last_span.hi;
1217 debug!("parse_trait_methods(): parsing required method");
1218 Required(TypeMethod {
1224 explicit_self: explicit_self,
1225 id: ast::DUMMY_NODE_ID,
1226 span: mk_sp(lo, hi),
1231 debug!("parse_trait_methods(): parsing provided method");
1232 let (inner_attrs, body) =
1233 p.parse_inner_attrs_and_block();
1234 let attrs = attrs.append(inner_attrs.as_slice());
1235 Provided(box(GC) ast::Method {
1239 explicit_self: explicit_self,
1243 id: ast::DUMMY_NODE_ID,
1244 span: mk_sp(lo, hi),
1250 let token_str = p.this_token_to_str();
1251 p.fatal((format!("expected `;` or `{{` but found `{}`",
1252 token_str)).as_slice())
1258 // parse a possibly mutable type
1259 pub fn parse_mt(&mut self) -> MutTy {
1260 let mutbl = self.parse_mutability();
1261 let t = self.parse_ty(true);
1262 MutTy { ty: t, mutbl: mutbl }
1265 // parse [mut/const/imm] ID : TY
1266 // now used only by obsolete record syntax parser...
1267 pub fn parse_ty_field(&mut self) -> TypeField {
1268 let lo = self.span.lo;
1269 let mutbl = self.parse_mutability();
1270 let id = self.parse_ident();
1271 self.expect(&token::COLON);
1272 let ty = self.parse_ty(true);
1273 let hi = ty.span.hi;
1276 mt: MutTy { ty: ty, mutbl: mutbl },
1277 span: mk_sp(lo, hi),
1281 // parse optional return type [ -> TY ] in function decl
1282 pub fn parse_ret_ty(&mut self) -> (RetStyle, P<Ty>) {
1283 return if self.eat(&token::RARROW) {
1284 let lo = self.span.lo;
1285 if self.eat(&token::NOT) {
1289 id: ast::DUMMY_NODE_ID,
1291 span: mk_sp(lo, self.last_span.hi)
1295 (Return, self.parse_ty(true))
1298 let pos = self.span.lo;
1302 id: ast::DUMMY_NODE_ID,
1304 span: mk_sp(pos, pos),
1312 /// The second parameter specifies whether the `+` binary operator is
1313 /// allowed in the type grammar.
1314 pub fn parse_ty(&mut self, plus_allowed: bool) -> P<Ty> {
1315 maybe_whole!(no_clone self, NtTy);
1317 let lo = self.span.lo;
1319 let t = if self.token == token::LPAREN {
1321 if self.token == token::RPAREN {
1325 // (t) is a parenthesized ty
1326 // (t,) is the type of a tuple with only one field,
1328 let mut ts = vec!(self.parse_ty(true));
1329 let mut one_tuple = false;
1330 while self.token == token::COMMA {
1332 if self.token != token::RPAREN {
1333 ts.push(self.parse_ty(true));
1340 if ts.len() == 1 && !one_tuple {
1341 self.expect(&token::RPAREN);
1345 self.expect(&token::RPAREN);
1349 } else if self.token == token::AT {
1352 let span = self.last_span;
1353 self.obsolete(span, ObsoleteManagedType);
1354 TyBox(self.parse_ty(plus_allowed))
1355 } else if self.token == token::TILDE {
1358 let last_span = self.last_span;
1361 self.obsolete(last_span, ObsoleteOwnedVector),
1362 _ => self.obsolete(last_span, ObsoleteOwnedType),
1364 TyUniq(self.parse_ty(true))
1365 } else if self.token == token::BINOP(token::STAR) {
1366 // STAR POINTER (bare pointer?)
1368 TyPtr(self.parse_ptr())
1369 } else if self.token == token::LBRACKET {
1371 self.expect(&token::LBRACKET);
1372 let t = self.parse_ty(true);
1374 // Parse the `, ..e` in `[ int, ..e ]`
1375 // where `e` is a const expression
1376 let t = match self.maybe_parse_fixed_vstore() {
1378 Some(suffix) => TyFixedLengthVec(t, suffix)
1380 self.expect(&token::RBRACKET);
1382 } else if self.token == token::BINOP(token::AND) ||
1383 self.token == token::ANDAND {
1386 self.parse_borrowed_pointee()
1387 } else if self.is_keyword(keywords::Extern) ||
1388 self.is_keyword(keywords::Unsafe) ||
1389 self.token_is_bare_fn_keyword() {
1391 self.parse_ty_bare_fn()
1392 } else if self.token_is_closure_keyword() ||
1393 self.token == token::BINOP(token::OR) ||
1394 self.token == token::OROR ||
1395 self.token == token::LT {
1398 // FIXME(pcwalton): Eventually `token::LT` will not unambiguously
1399 // introduce a closure, once procs can have lifetime bounds. We
1400 // will need to refactor the grammar a little bit at that point.
1402 self.parse_ty_closure()
1403 } else if self.eat_keyword(keywords::Typeof) {
1405 // In order to not be ambiguous, the type must be surrounded by parens.
1406 self.expect(&token::LPAREN);
1407 let e = self.parse_expr();
1408 self.expect(&token::RPAREN);
1410 } else if self.eat_keyword(keywords::Proc) {
1411 self.parse_proc_type()
1412 } else if self.token == token::MOD_SEP
1413 || is_ident_or_path(&self.token) {
1415 let mode = if plus_allowed {
1416 LifetimeAndTypesAndBounds
1418 LifetimeAndTypesWithoutColons
1423 } = self.parse_path(mode);
1424 TyPath(path, bounds, ast::DUMMY_NODE_ID)
1425 } else if self.eat(&token::UNDERSCORE) {
1426 // TYPE TO BE INFERRED
1429 let msg = format!("expected type, found token {:?}", self.token);
1430 self.fatal(msg.as_slice());
1433 let sp = mk_sp(lo, self.last_span.hi);
1434 P(Ty {id: ast::DUMMY_NODE_ID, node: t, span: sp})
1437 pub fn parse_borrowed_pointee(&mut self) -> Ty_ {
1438 // look for `&'lt` or `&'foo ` and interpret `foo` as the region name:
1439 let opt_lifetime = self.parse_opt_lifetime();
1441 let mt = self.parse_mt();
1442 return TyRptr(opt_lifetime, mt);
1445 pub fn parse_ptr(&mut self) -> MutTy {
1446 let mutbl = if self.eat_keyword(keywords::Mut) {
1448 } else if self.eat_keyword(keywords::Const) {
1451 let span = self.last_span;
1453 "bare raw pointers are no longer allowed, you should \
1454 likely use `*mut T`, but otherwise `*T` is now \
1455 known as `*const T`");
1458 let t = self.parse_ty(true);
1459 MutTy { ty: t, mutbl: mutbl }
1462 pub fn is_named_argument(&mut self) -> bool {
1463 let offset = match self.token {
1464 token::BINOP(token::AND) => 1,
1466 _ if token::is_keyword(keywords::Mut, &self.token) => 1,
1470 debug!("parser is_named_argument offset:{}", offset);
1473 is_plain_ident_or_underscore(&self.token)
1474 && self.look_ahead(1, |t| *t == token::COLON)
1476 self.look_ahead(offset, |t| is_plain_ident_or_underscore(t))
1477 && self.look_ahead(offset + 1, |t| *t == token::COLON)
1481 // This version of parse arg doesn't necessarily require
1482 // identifier names.
1483 pub fn parse_arg_general(&mut self, require_name: bool) -> Arg {
1484 let pat = if require_name || self.is_named_argument() {
1485 debug!("parse_arg_general parse_pat (require_name:{:?})",
1487 let pat = self.parse_pat();
1489 self.expect(&token::COLON);
1492 debug!("parse_arg_general ident_to_pat");
1493 ast_util::ident_to_pat(ast::DUMMY_NODE_ID,
1495 special_idents::invalid)
1498 let t = self.parse_ty(true);
1503 id: ast::DUMMY_NODE_ID,
1507 // parse a single function argument
1508 pub fn parse_arg(&mut self) -> Arg {
1509 self.parse_arg_general(true)
1512 // parse an argument in a lambda header e.g. |arg, arg|
1513 pub fn parse_fn_block_arg(&mut self) -> Arg {
1514 let pat = self.parse_pat();
1515 let t = if self.eat(&token::COLON) {
1519 id: ast::DUMMY_NODE_ID,
1521 span: mk_sp(self.span.lo, self.span.hi),
1527 id: ast::DUMMY_NODE_ID
1531 pub fn maybe_parse_fixed_vstore(&mut self) -> Option<Gc<ast::Expr>> {
1532 if self.token == token::COMMA &&
1533 self.look_ahead(1, |t| *t == token::DOTDOT) {
1536 Some(self.parse_expr())
1542 // matches token_lit = LIT_INT | ...
1543 pub fn lit_from_token(&mut self, tok: &token::Token) -> Lit_ {
1545 token::LIT_BYTE(i) => LitByte(i),
1546 token::LIT_CHAR(i) => LitChar(i),
1547 token::LIT_INT(i, it) => LitInt(i, it),
1548 token::LIT_UINT(u, ut) => LitUint(u, ut),
1549 token::LIT_INT_UNSUFFIXED(i) => LitIntUnsuffixed(i),
1550 token::LIT_FLOAT(s, ft) => {
1551 LitFloat(self.id_to_interned_str(s), ft)
1553 token::LIT_FLOAT_UNSUFFIXED(s) => {
1554 LitFloatUnsuffixed(self.id_to_interned_str(s))
1556 token::LIT_STR(s) => {
1557 LitStr(self.id_to_interned_str(s), ast::CookedStr)
1559 token::LIT_STR_RAW(s, n) => {
1560 LitStr(self.id_to_interned_str(s), ast::RawStr(n))
1562 token::LIT_BINARY_RAW(ref v, _) |
1563 token::LIT_BINARY(ref v) => LitBinary(v.clone()),
1564 token::LPAREN => { self.expect(&token::RPAREN); LitNil },
1565 _ => { self.unexpected_last(tok); }
1569 // matches lit = true | false | token_lit
1570 pub fn parse_lit(&mut self) -> Lit {
1571 let lo = self.span.lo;
1572 let lit = if self.eat_keyword(keywords::True) {
1574 } else if self.eat_keyword(keywords::False) {
1577 let token = self.bump_and_get();
1578 let lit = self.lit_from_token(&token);
1581 codemap::Spanned { node: lit, span: mk_sp(lo, self.last_span.hi) }
1584 // matches '-' lit | lit
1585 pub fn parse_literal_maybe_minus(&mut self) -> Gc<Expr> {
1586 let minus_lo = self.span.lo;
1587 let minus_present = self.eat(&token::BINOP(token::MINUS));
1589 let lo = self.span.lo;
1590 let literal = box(GC) self.parse_lit();
1591 let hi = self.span.hi;
1592 let expr = self.mk_expr(lo, hi, ExprLit(literal));
1595 let minus_hi = self.span.hi;
1596 let unary = self.mk_unary(UnNeg, expr);
1597 self.mk_expr(minus_lo, minus_hi, unary)
1603 /// Parses a path and optional type parameter bounds, depending on the
1604 /// mode. The `mode` parameter determines whether lifetimes, types, and/or
1605 /// bounds are permitted and whether `::` must precede type parameter
1607 pub fn parse_path(&mut self, mode: PathParsingMode) -> PathAndBounds {
1608 // Check for a whole path...
1609 let found = match self.token {
1610 INTERPOLATED(token::NtPath(_)) => Some(self.bump_and_get()),
1614 Some(INTERPOLATED(token::NtPath(box path))) => {
1615 return PathAndBounds {
1623 let lo = self.span.lo;
1624 let is_global = self.eat(&token::MOD_SEP);
1626 // Parse any number of segments and bound sets. A segment is an
1627 // identifier followed by an optional lifetime and a set of types.
1628 // A bound set is a set of type parameter bounds.
1629 let mut segments = Vec::new();
1631 // First, parse an identifier.
1632 let identifier = self.parse_ident();
1634 // Parse the '::' before type parameters if it's required. If
1635 // it is required and wasn't present, then we're done.
1636 if mode == LifetimeAndTypesWithColons &&
1637 !self.eat(&token::MOD_SEP) {
1638 segments.push(ast::PathSegment {
1639 identifier: identifier,
1640 lifetimes: Vec::new(),
1641 types: OwnedSlice::empty(),
1646 // Parse the `<` before the lifetime and types, if applicable.
1647 let (any_lifetime_or_types, lifetimes, types) = {
1648 if mode != NoTypesAllowed && self.eat_lt(false) {
1649 let (lifetimes, types) =
1650 self.parse_generic_values_after_lt();
1651 (true, lifetimes, OwnedSlice::from_vec(types))
1653 (false, Vec::new(), OwnedSlice::empty())
1657 // Assemble and push the result.
1658 segments.push(ast::PathSegment {
1659 identifier: identifier,
1660 lifetimes: lifetimes,
1664 // We're done if we don't see a '::', unless the mode required
1665 // a double colon to get here in the first place.
1666 if !(mode == LifetimeAndTypesWithColons &&
1667 !any_lifetime_or_types) {
1668 if !self.eat(&token::MOD_SEP) {
1674 // Next, parse a plus and bounded type parameters, if applicable.
1675 let bounds = if mode == LifetimeAndTypesAndBounds {
1677 if self.eat(&token::BINOP(token::PLUS)) {
1678 let (_, bounds) = self.parse_ty_param_bounds(false);
1679 if bounds.len() == 0 {
1680 let last_span = self.last_span;
1681 self.span_err(last_span,
1682 "at least one type parameter bound \
1683 must be specified after the `+`");
1695 // Assemble the span.
1696 let span = mk_sp(lo, self.last_span.hi);
1698 // Assemble the result.
1709 /// parses 0 or 1 lifetime
1710 pub fn parse_opt_lifetime(&mut self) -> Option<ast::Lifetime> {
1712 token::LIFETIME(..) => {
1713 Some(self.parse_lifetime())
1721 /// Parses a single lifetime
1722 // matches lifetime = LIFETIME
1723 pub fn parse_lifetime(&mut self) -> ast::Lifetime {
1725 token::LIFETIME(i) => {
1726 let span = self.span;
1728 return ast::Lifetime {
1729 id: ast::DUMMY_NODE_ID,
1735 self.fatal(format!("expected a lifetime name").as_slice());
1740 // matches lifetimes = ( lifetime ) | ( lifetime , lifetimes )
1741 // actually, it matches the empty one too, but putting that in there
1742 // messes up the grammar....
1743 pub fn parse_lifetimes(&mut self) -> Vec<ast::Lifetime> {
1746 * Parses zero or more comma separated lifetimes.
1747 * Expects each lifetime to be followed by either
1748 * a comma or `>`. Used when parsing type parameter
1749 * lists, where we expect something like `<'a, 'b, T>`.
1752 let mut res = Vec::new();
1755 token::LIFETIME(_) => {
1756 res.push(self.parse_lifetime());
1764 token::COMMA => { self.bump();}
1765 token::GT => { return res; }
1766 token::BINOP(token::SHR) => { return res; }
1768 let msg = format!("expected `,` or `>` after lifetime \
1771 self.fatal(msg.as_slice());
1777 pub fn token_is_mutability(tok: &token::Token) -> bool {
1778 token::is_keyword(keywords::Mut, tok) ||
1779 token::is_keyword(keywords::Const, tok)
1782 // parse mutability declaration (mut/const/imm)
1783 pub fn parse_mutability(&mut self) -> Mutability {
1784 if self.eat_keyword(keywords::Mut) {
1791 // parse ident COLON expr
1792 pub fn parse_field(&mut self) -> Field {
1793 let lo = self.span.lo;
1794 let i = self.parse_ident();
1795 let hi = self.last_span.hi;
1796 self.expect(&token::COLON);
1797 let e = self.parse_expr();
1799 ident: spanned(lo, hi, i),
1801 span: mk_sp(lo, e.span.hi),
1805 pub fn mk_expr(&mut self, lo: BytePos, hi: BytePos, node: Expr_) -> Gc<Expr> {
1807 id: ast::DUMMY_NODE_ID,
1809 span: mk_sp(lo, hi),
1813 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: Gc<Expr>) -> ast::Expr_ {
1814 ExprUnary(unop, expr)
1817 pub fn mk_binary(&mut self, binop: ast::BinOp,
1818 lhs: Gc<Expr>, rhs: Gc<Expr>) -> ast::Expr_ {
1819 ExprBinary(binop, lhs, rhs)
1822 pub fn mk_call(&mut self, f: Gc<Expr>, args: Vec<Gc<Expr>>) -> ast::Expr_ {
1826 fn mk_method_call(&mut self,
1827 ident: ast::SpannedIdent,
1829 args: Vec<Gc<Expr>>)
1831 ExprMethodCall(ident, tps, args)
1834 pub fn mk_index(&mut self, expr: Gc<Expr>, idx: Gc<Expr>) -> ast::Expr_ {
1835 ExprIndex(expr, idx)
1838 pub fn mk_field(&mut self, expr: Gc<Expr>, ident: ast::SpannedIdent,
1839 tys: Vec<P<Ty>>) -> ast::Expr_ {
1840 ExprField(expr, ident, tys)
1843 pub fn mk_assign_op(&mut self, binop: ast::BinOp,
1844 lhs: Gc<Expr>, rhs: Gc<Expr>) -> ast::Expr_ {
1845 ExprAssignOp(binop, lhs, rhs)
1848 pub fn mk_mac_expr(&mut self, lo: BytePos, hi: BytePos, m: Mac_) -> Gc<Expr> {
1850 id: ast::DUMMY_NODE_ID,
1851 node: ExprMac(codemap::Spanned {node: m, span: mk_sp(lo, hi)}),
1852 span: mk_sp(lo, hi),
1856 pub fn mk_lit_u32(&mut self, i: u32) -> Gc<Expr> {
1857 let span = &self.span;
1858 let lv_lit = box(GC) codemap::Spanned {
1859 node: LitUint(i as u64, TyU32),
1864 id: ast::DUMMY_NODE_ID,
1865 node: ExprLit(lv_lit),
1870 // at the bottom (top?) of the precedence hierarchy,
1871 // parse things like parenthesized exprs,
1872 // macros, return, etc.
1873 pub fn parse_bottom_expr(&mut self) -> Gc<Expr> {
1874 maybe_whole_expr!(self);
1876 let lo = self.span.lo;
1877 let mut hi = self.span.hi;
1881 if self.token == token::LPAREN {
1883 // (e) is parenthesized e
1884 // (e,) is a tuple with only one field, e
1885 let mut trailing_comma = false;
1886 if self.token == token::RPAREN {
1889 let lit = box(GC) spanned(lo, hi, LitNil);
1890 return self.mk_expr(lo, hi, ExprLit(lit));
1892 let mut es = vec!(self.parse_expr());
1893 self.commit_expr(*es.last().unwrap(), &[], &[token::COMMA, token::RPAREN]);
1894 while self.token == token::COMMA {
1896 if self.token != token::RPAREN {
1897 es.push(self.parse_expr());
1898 self.commit_expr(*es.last().unwrap(), &[], &[token::COMMA, token::RPAREN]);
1901 trailing_comma = true;
1905 self.commit_expr_expecting(*es.last().unwrap(), token::RPAREN);
1907 return if es.len() == 1 && !trailing_comma {
1908 self.mk_expr(lo, hi, ExprParen(*es.get(0)))
1911 self.mk_expr(lo, hi, ExprTup(es))
1913 } else if self.token == token::LBRACE {
1915 let blk = self.parse_block_tail(lo, DefaultBlock);
1916 return self.mk_expr(blk.span.lo, blk.span.hi,
1918 } else if token::is_bar(&self.token) {
1919 return self.parse_lambda_expr();
1920 } else if self.eat_keyword(keywords::Proc) {
1921 let decl = self.parse_proc_decl();
1922 let body = self.parse_expr();
1923 let fakeblock = P(ast::Block {
1924 view_items: Vec::new(),
1927 id: ast::DUMMY_NODE_ID,
1928 rules: DefaultBlock,
1932 return self.mk_expr(lo, body.span.hi, ExprProc(decl, fakeblock));
1933 } else if self.eat_keyword(keywords::Self) {
1934 let path = ast_util::ident_to_path(mk_sp(lo, hi), special_idents::self_);
1935 ex = ExprPath(path);
1936 hi = self.last_span.hi;
1937 } else if self.eat_keyword(keywords::If) {
1938 return self.parse_if_expr();
1939 } else if self.eat_keyword(keywords::For) {
1940 return self.parse_for_expr(None);
1941 } else if self.eat_keyword(keywords::While) {
1942 return self.parse_while_expr();
1943 } else if Parser::token_is_lifetime(&self.token) {
1944 let lifetime = self.get_lifetime();
1946 self.expect(&token::COLON);
1947 if self.eat_keyword(keywords::For) {
1948 return self.parse_for_expr(Some(lifetime))
1949 } else if self.eat_keyword(keywords::Loop) {
1950 return self.parse_loop_expr(Some(lifetime))
1952 self.fatal("expected `for` or `loop` after a label")
1954 } else if self.eat_keyword(keywords::Loop) {
1955 return self.parse_loop_expr(None);
1956 } else if self.eat_keyword(keywords::Continue) {
1957 let lo = self.span.lo;
1958 let ex = if Parser::token_is_lifetime(&self.token) {
1959 let lifetime = self.get_lifetime();
1961 ExprAgain(Some(lifetime))
1965 let hi = self.span.hi;
1966 return self.mk_expr(lo, hi, ex);
1967 } else if self.eat_keyword(keywords::Match) {
1968 return self.parse_match_expr();
1969 } else if self.eat_keyword(keywords::Unsafe) {
1970 return self.parse_block_expr(lo, UnsafeBlock(ast::UserProvided));
1971 } else if self.token == token::LBRACKET {
1974 if self.token == token::RBRACKET {
1977 ex = ExprVec(Vec::new());
1980 let first_expr = self.parse_expr();
1981 if self.token == token::COMMA &&
1982 self.look_ahead(1, |t| *t == token::DOTDOT) {
1983 // Repeating vector syntax: [ 0, ..512 ]
1986 let count = self.parse_expr();
1987 self.expect(&token::RBRACKET);
1988 ex = ExprRepeat(first_expr, count);
1989 } else if self.token == token::COMMA {
1990 // Vector with two or more elements.
1992 let remaining_exprs = self.parse_seq_to_end(
1994 seq_sep_trailing_allowed(token::COMMA),
1997 let mut exprs = vec!(first_expr);
1998 exprs.push_all_move(remaining_exprs);
1999 ex = ExprVec(exprs);
2001 // Vector with one element.
2002 self.expect(&token::RBRACKET);
2003 ex = ExprVec(vec!(first_expr));
2006 hi = self.last_span.hi;
2007 } else if self.eat_keyword(keywords::Return) {
2008 // RETURN expression
2009 if can_begin_expr(&self.token) {
2010 let e = self.parse_expr();
2012 ex = ExprRet(Some(e));
2013 } else { ex = ExprRet(None); }
2014 } else if self.eat_keyword(keywords::Break) {
2016 if Parser::token_is_lifetime(&self.token) {
2017 let lifetime = self.get_lifetime();
2019 ex = ExprBreak(Some(lifetime));
2021 ex = ExprBreak(None);
2024 } else if self.token == token::MOD_SEP ||
2025 is_ident(&self.token) && !self.is_keyword(keywords::True) &&
2026 !self.is_keyword(keywords::False) {
2027 let pth = self.parse_path(LifetimeAndTypesWithColons).path;
2029 // `!`, as an operator, is prefix, so we know this isn't that
2030 if self.token == token::NOT {
2031 // MACRO INVOCATION expression
2034 let ket = token::close_delimiter_for(&self.token)
2035 .unwrap_or_else(|| self.fatal("expected open delimiter"));
2038 let tts = self.parse_seq_to_end(&ket,
2040 |p| p.parse_token_tree());
2041 let hi = self.span.hi;
2043 return self.mk_mac_expr(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT));
2044 } else if self.token == token::LBRACE {
2045 // This is a struct literal, unless we're prohibited from
2046 // parsing struct literals here.
2047 if self.restriction != RESTRICT_NO_STRUCT_LITERAL {
2048 // It's a struct literal.
2050 let mut fields = Vec::new();
2051 let mut base = None;
2053 while self.token != token::RBRACE {
2054 if self.eat(&token::DOTDOT) {
2055 base = Some(self.parse_expr());
2059 fields.push(self.parse_field());
2060 self.commit_expr(fields.last().unwrap().expr,
2061 &[token::COMMA], &[token::RBRACE]);
2064 if fields.len() == 0 && base.is_none() {
2065 let last_span = self.last_span;
2066 self.span_err(last_span,
2067 "structure literal must either have at \
2068 least one field or use functional \
2069 structure update syntax");
2073 self.expect(&token::RBRACE);
2074 ex = ExprStruct(pth, fields, base);
2075 return self.mk_expr(lo, hi, ex);
2082 // other literal expression
2083 let lit = self.parse_lit();
2085 ex = ExprLit(box(GC) lit);
2088 return self.mk_expr(lo, hi, ex);
2091 // parse a block or unsafe block
2092 pub fn parse_block_expr(&mut self, lo: BytePos, blk_mode: BlockCheckMode)
2094 self.expect(&token::LBRACE);
2095 let blk = self.parse_block_tail(lo, blk_mode);
2096 return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk));
2099 // parse a.b or a(13) or a[4] or just a
2100 pub fn parse_dot_or_call_expr(&mut self) -> Gc<Expr> {
2101 let b = self.parse_bottom_expr();
2102 self.parse_dot_or_call_expr_with(b)
2105 pub fn parse_dot_or_call_expr_with(&mut self, e0: Gc<Expr>) -> Gc<Expr> {
2111 if self.eat(&token::DOT) {
2113 token::IDENT(i, _) => {
2114 let dot = self.last_span.hi;
2117 let (_, tys) = if self.eat(&token::MOD_SEP) {
2119 self.parse_generic_values_after_lt()
2121 (Vec::new(), Vec::new())
2124 // expr.f() method call
2127 let mut es = self.parse_unspanned_seq(
2130 seq_sep_trailing_disallowed(token::COMMA),
2133 hi = self.last_span.hi;
2136 let id = spanned(dot, hi, i);
2137 let nd = self.mk_method_call(id, tys, es);
2138 e = self.mk_expr(lo, hi, nd);
2141 let id = spanned(dot, hi, i);
2142 let field = self.mk_field(e, id, tys);
2143 e = self.mk_expr(lo, hi, field)
2147 _ => self.unexpected()
2151 if self.expr_is_complete(e) { break; }
2155 let es = self.parse_unspanned_seq(
2158 seq_sep_trailing_allowed(token::COMMA),
2161 hi = self.last_span.hi;
2163 let nd = self.mk_call(e, es);
2164 e = self.mk_expr(lo, hi, nd);
2168 token::LBRACKET => {
2170 let ix = self.parse_expr();
2172 self.commit_expr_expecting(ix, token::RBRACKET);
2173 let index = self.mk_index(e, ix);
2174 e = self.mk_expr(lo, hi, index)
2183 // parse an optional separator followed by a kleene-style
2184 // repetition token (+ or *).
2185 pub fn parse_sep_and_zerok(&mut self) -> (Option<token::Token>, bool) {
2186 fn parse_zerok(parser: &mut Parser) -> Option<bool> {
2187 match parser.token {
2188 token::BINOP(token::STAR) | token::BINOP(token::PLUS) => {
2189 let zerok = parser.token == token::BINOP(token::STAR);
2197 match parse_zerok(self) {
2198 Some(zerok) => return (None, zerok),
2202 let separator = self.bump_and_get();
2203 match parse_zerok(self) {
2204 Some(zerok) => (Some(separator), zerok),
2205 None => self.fatal("expected `*` or `+`")
2209 // parse a single token tree from the input.
2210 pub fn parse_token_tree(&mut self) -> TokenTree {
2211 // FIXME #6994: currently, this is too eager. It
2212 // parses token trees but also identifies TTSeq's
2213 // and TTNonterminal's; it's too early to know yet
2214 // whether something will be a nonterminal or a seq
2216 maybe_whole!(deref self, NtTT);
2218 // this is the fall-through for the 'match' below.
2219 // invariants: the current token is not a left-delimiter,
2220 // not an EOF, and not the desired right-delimiter (if
2221 // it were, parse_seq_to_before_end would have prevented
2222 // reaching this point.
2223 fn parse_non_delim_tt_tok(p: &mut Parser) -> TokenTree {
2224 maybe_whole!(deref p, NtTT);
2226 token::RPAREN | token::RBRACE | token::RBRACKET => {
2227 // This is a conservative error: only report the last unclosed delimiter. The
2228 // previous unclosed delimiters could actually be closed! The parser just hasn't
2229 // gotten to them yet.
2230 match p.open_braces.last() {
2232 Some(&sp) => p.span_note(sp, "unclosed delimiter"),
2234 let token_str = p.this_token_to_str();
2235 p.fatal(format!("incorrect close delimiter: `{}`",
2236 token_str).as_slice())
2238 /* we ought to allow different depths of unquotation */
2239 token::DOLLAR if p.quote_depth > 0u => {
2243 if p.token == token::LPAREN {
2244 let seq = p.parse_seq(
2248 |p| p.parse_token_tree()
2250 let (s, z) = p.parse_sep_and_zerok();
2251 let seq = match seq {
2252 Spanned { node, .. } => node,
2254 TTSeq(mk_sp(sp.lo, p.span.hi), Rc::new(seq), s, z)
2256 TTNonterminal(sp, p.parse_ident())
2265 // turn the next token into a TTTok:
2266 fn parse_any_tt_tok(p: &mut Parser) -> TokenTree {
2267 TTTok(p.span, p.bump_and_get())
2270 match (&self.token, token::close_delimiter_for(&self.token)) {
2271 (&token::EOF, _) => {
2272 let open_braces = self.open_braces.clone();
2273 for sp in open_braces.iter() {
2274 self.span_note(*sp, "Did you mean to close this delimiter?");
2276 // There shouldn't really be a span, but it's easier for the test runner
2277 // if we give it one
2278 self.fatal("this file contains an un-closed delimiter ");
2280 (_, Some(close_delim)) => {
2281 // Parse the open delimiter.
2282 self.open_braces.push(self.span);
2283 let mut result = vec!(parse_any_tt_tok(self));
2286 self.parse_seq_to_before_end(&close_delim,
2288 |p| p.parse_token_tree());
2289 result.push_all_move(trees);
2291 // Parse the close delimiter.
2292 result.push(parse_any_tt_tok(self));
2293 self.open_braces.pop().unwrap();
2295 TTDelim(Rc::new(result))
2297 _ => parse_non_delim_tt_tok(self)
2301 // parse a stream of tokens into a list of TokenTree's,
2303 pub fn parse_all_token_trees(&mut self) -> Vec<TokenTree> {
2304 let mut tts = Vec::new();
2305 while self.token != token::EOF {
2306 tts.push(self.parse_token_tree());
2311 pub fn parse_matchers(&mut self) -> Vec<Matcher> {
2312 // unification of Matcher's and TokenTree's would vastly improve
2313 // the interpolation of Matcher's
2314 maybe_whole!(self, NtMatchers);
2315 let mut name_idx = 0u;
2316 match token::close_delimiter_for(&self.token) {
2317 Some(other_delimiter) => {
2319 self.parse_matcher_subseq_upto(&mut name_idx, &other_delimiter)
2321 None => self.fatal("expected open delimiter")
2325 // This goofy function is necessary to correctly match parens in Matcher's.
2326 // Otherwise, `$( ( )` would be a valid Matcher, and `$( () )` would be
2327 // invalid. It's similar to common::parse_seq.
2328 pub fn parse_matcher_subseq_upto(&mut self,
2329 name_idx: &mut uint,
2332 let mut ret_val = Vec::new();
2333 let mut lparens = 0u;
2335 while self.token != *ket || lparens > 0u {
2336 if self.token == token::LPAREN { lparens += 1u; }
2337 if self.token == token::RPAREN { lparens -= 1u; }
2338 ret_val.push(self.parse_matcher(name_idx));
2346 pub fn parse_matcher(&mut self, name_idx: &mut uint) -> Matcher {
2347 let lo = self.span.lo;
2349 let m = if self.token == token::DOLLAR {
2351 if self.token == token::LPAREN {
2352 let name_idx_lo = *name_idx;
2354 let ms = self.parse_matcher_subseq_upto(name_idx,
2357 self.fatal("repetition body must be nonempty");
2359 let (sep, zerok) = self.parse_sep_and_zerok();
2360 MatchSeq(ms, sep, zerok, name_idx_lo, *name_idx)
2362 let bound_to = self.parse_ident();
2363 self.expect(&token::COLON);
2364 let nt_name = self.parse_ident();
2365 let m = MatchNonterminal(bound_to, nt_name, *name_idx);
2370 MatchTok(self.bump_and_get())
2373 return spanned(lo, self.span.hi, m);
2376 // parse a prefix-operator expr
2377 pub fn parse_prefix_expr(&mut self) -> Gc<Expr> {
2378 let lo = self.span.lo;
2385 let e = self.parse_prefix_expr();
2387 ex = self.mk_unary(UnNot, e);
2389 token::BINOP(token::MINUS) => {
2391 let e = self.parse_prefix_expr();
2393 ex = self.mk_unary(UnNeg, e);
2395 token::BINOP(token::STAR) => {
2397 let e = self.parse_prefix_expr();
2399 ex = self.mk_unary(UnDeref, e);
2401 token::BINOP(token::AND) | token::ANDAND => {
2403 let _lt = self.parse_opt_lifetime();
2404 let m = self.parse_mutability();
2405 let e = self.parse_prefix_expr();
2407 // HACK: turn &[...] into a &-vec
2409 ExprVec(..) if m == MutImmutable => {
2410 ExprVstore(e, ExprVstoreSlice)
2412 ExprVec(..) if m == MutMutable => {
2413 ExprVstore(e, ExprVstoreMutSlice)
2415 _ => ExprAddrOf(m, e)
2420 let span = self.last_span;
2421 self.obsolete(span, ObsoleteManagedExpr);
2422 let e = self.parse_prefix_expr();
2424 ex = self.mk_unary(UnBox, e);
2429 let e = self.parse_prefix_expr();
2431 // HACK: turn ~[...] into a ~-vec
2432 let last_span = self.last_span;
2434 ExprVec(..) | ExprRepeat(..) => {
2435 self.obsolete(last_span, ObsoleteOwnedVector);
2436 ExprVstore(e, ExprVstoreUniq)
2438 ExprLit(lit) if lit_is_str(lit) => {
2439 self.obsolete(last_span, ObsoleteOwnedExpr);
2440 ExprVstore(e, ExprVstoreUniq)
2443 self.obsolete(last_span, ObsoleteOwnedExpr);
2444 self.mk_unary(UnUniq, e)
2448 token::IDENT(_, _) if self.is_keyword(keywords::Box) => {
2451 // Check for a place: `box(PLACE) EXPR`.
2452 if self.eat(&token::LPAREN) {
2453 // Support `box() EXPR` as the default.
2454 if !self.eat(&token::RPAREN) {
2455 let place = self.parse_expr();
2456 self.expect(&token::RPAREN);
2457 let subexpression = self.parse_prefix_expr();
2458 hi = subexpression.span.hi;
2459 ex = ExprBox(place, subexpression);
2460 return self.mk_expr(lo, hi, ex);
2464 // Otherwise, we use the unique pointer default.
2465 let subexpression = self.parse_prefix_expr();
2466 hi = subexpression.span.hi;
2467 // HACK: turn `box [...]` into a boxed-vec
2468 ex = match subexpression.node {
2469 ExprVec(..) | ExprRepeat(..) => {
2470 let last_span = self.last_span;
2471 self.obsolete(last_span, ObsoleteOwnedVector);
2472 ExprVstore(subexpression, ExprVstoreUniq)
2474 ExprLit(lit) if lit_is_str(lit) => {
2475 ExprVstore(subexpression, ExprVstoreUniq)
2477 _ => self.mk_unary(UnUniq, subexpression)
2480 _ => return self.parse_dot_or_call_expr()
2482 return self.mk_expr(lo, hi, ex);
2485 // parse an expression of binops
2486 pub fn parse_binops(&mut self) -> Gc<Expr> {
2487 let prefix_expr = self.parse_prefix_expr();
2488 self.parse_more_binops(prefix_expr, 0)
2491 // parse an expression of binops of at least min_prec precedence
2492 pub fn parse_more_binops(&mut self, lhs: Gc<Expr>,
2493 min_prec: uint) -> Gc<Expr> {
2494 if self.expr_is_complete(lhs) { return lhs; }
2496 // Prevent dynamic borrow errors later on by limiting the
2497 // scope of the borrows.
2499 let token: &token::Token = &self.token;
2500 let restriction: &restriction = &self.restriction;
2501 match (token, restriction) {
2502 (&token::BINOP(token::OR), &RESTRICT_NO_BAR_OP) => return lhs,
2503 (&token::BINOP(token::OR),
2504 &RESTRICT_NO_BAR_OR_DOUBLEBAR_OP) => return lhs,
2505 (&token::OROR, &RESTRICT_NO_BAR_OR_DOUBLEBAR_OP) => return lhs,
2510 let cur_opt = token_to_binop(&self.token);
2513 let cur_prec = operator_prec(cur_op);
2514 if cur_prec > min_prec {
2516 let expr = self.parse_prefix_expr();
2517 let rhs = self.parse_more_binops(expr, cur_prec);
2518 let binary = self.mk_binary(cur_op, lhs, rhs);
2519 let bin = self.mk_expr(lhs.span.lo, rhs.span.hi, binary);
2520 self.parse_more_binops(bin, min_prec)
2526 if as_prec > min_prec && self.eat_keyword(keywords::As) {
2527 let rhs = self.parse_ty(false);
2528 let _as = self.mk_expr(lhs.span.lo,
2530 ExprCast(lhs, rhs));
2531 self.parse_more_binops(_as, min_prec)
2539 // parse an assignment expression....
2540 // actually, this seems to be the main entry point for
2541 // parsing an arbitrary expression.
2542 pub fn parse_assign_expr(&mut self) -> Gc<Expr> {
2543 let lo = self.span.lo;
2544 let lhs = self.parse_binops();
2548 let rhs = self.parse_expr();
2549 self.mk_expr(lo, rhs.span.hi, ExprAssign(lhs, rhs))
2551 token::BINOPEQ(op) => {
2553 let rhs = self.parse_expr();
2554 let aop = match op {
2555 token::PLUS => BiAdd,
2556 token::MINUS => BiSub,
2557 token::STAR => BiMul,
2558 token::SLASH => BiDiv,
2559 token::PERCENT => BiRem,
2560 token::CARET => BiBitXor,
2561 token::AND => BiBitAnd,
2562 token::OR => BiBitOr,
2563 token::SHL => BiShl,
2566 let assign_op = self.mk_assign_op(aop, lhs, rhs);
2567 self.mk_expr(lo, rhs.span.hi, assign_op)
2575 // parse an 'if' expression ('if' token already eaten)
2576 pub fn parse_if_expr(&mut self) -> Gc<Expr> {
2577 let lo = self.last_span.lo;
2578 let cond = self.parse_expr_res(RESTRICT_NO_STRUCT_LITERAL);
2579 let thn = self.parse_block();
2580 let mut els: Option<Gc<Expr>> = None;
2581 let mut hi = thn.span.hi;
2582 if self.eat_keyword(keywords::Else) {
2583 let elexpr = self.parse_else_expr();
2585 hi = elexpr.span.hi;
2587 self.mk_expr(lo, hi, ExprIf(cond, thn, els))
2590 // `|args| { ... }` or `{ ...}` like in `do` expressions
2591 pub fn parse_lambda_block_expr(&mut self) -> Gc<Expr> {
2592 self.parse_lambda_expr_(
2595 token::BINOP(token::OR) | token::OROR => {
2596 p.parse_fn_block_decl()
2599 // No argument list - `do foo {`
2603 id: ast::DUMMY_NODE_ID,
2614 let blk = p.parse_block();
2615 p.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk))
2620 pub fn parse_lambda_expr(&mut self) -> Gc<Expr> {
2621 self.parse_lambda_expr_(|p| p.parse_fn_block_decl(),
2625 // parse something of the form |args| expr
2626 // this is used both in parsing a lambda expr
2627 // and in parsing a block expr as e.g. in for...
2628 pub fn parse_lambda_expr_(&mut self,
2629 parse_decl: |&mut Parser| -> P<FnDecl>,
2630 parse_body: |&mut Parser| -> Gc<Expr>)
2632 let lo = self.span.lo;
2633 let decl = parse_decl(self);
2634 let body = parse_body(self);
2635 let fakeblock = P(ast::Block {
2636 view_items: Vec::new(),
2639 id: ast::DUMMY_NODE_ID,
2640 rules: DefaultBlock,
2644 return self.mk_expr(lo, body.span.hi, ExprFnBlock(decl, fakeblock));
2647 pub fn parse_else_expr(&mut self) -> Gc<Expr> {
2648 if self.eat_keyword(keywords::If) {
2649 return self.parse_if_expr();
2651 let blk = self.parse_block();
2652 return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk));
2656 // parse a 'for' .. 'in' expression ('for' token already eaten)
2657 pub fn parse_for_expr(&mut self, opt_ident: Option<ast::Ident>) -> Gc<Expr> {
2658 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
2660 let lo = self.last_span.lo;
2661 let pat = self.parse_pat();
2662 self.expect_keyword(keywords::In);
2663 let expr = self.parse_expr_res(RESTRICT_NO_STRUCT_LITERAL);
2664 let loop_block = self.parse_block();
2665 let hi = self.span.hi;
2667 self.mk_expr(lo, hi, ExprForLoop(pat, expr, loop_block, opt_ident))
2670 pub fn parse_while_expr(&mut self) -> Gc<Expr> {
2671 let lo = self.last_span.lo;
2672 let cond = self.parse_expr_res(RESTRICT_NO_STRUCT_LITERAL);
2673 let body = self.parse_block();
2674 let hi = body.span.hi;
2675 return self.mk_expr(lo, hi, ExprWhile(cond, body));
2678 pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::Ident>) -> Gc<Expr> {
2679 let lo = self.last_span.lo;
2680 let body = self.parse_block();
2681 let hi = body.span.hi;
2682 self.mk_expr(lo, hi, ExprLoop(body, opt_ident))
2685 fn parse_match_expr(&mut self) -> Gc<Expr> {
2686 let lo = self.last_span.lo;
2687 let discriminant = self.parse_expr_res(RESTRICT_NO_STRUCT_LITERAL);
2688 self.commit_expr_expecting(discriminant, token::LBRACE);
2689 let mut arms: Vec<Arm> = Vec::new();
2690 while self.token != token::RBRACE {
2691 let attrs = self.parse_outer_attributes();
2692 let pats = self.parse_pats();
2693 let mut guard = None;
2694 if self.eat_keyword(keywords::If) {
2695 guard = Some(self.parse_expr());
2697 self.expect(&token::FAT_ARROW);
2698 let expr = self.parse_expr_res(RESTRICT_STMT_EXPR);
2701 !classify::expr_is_simple_block(expr)
2702 && self.token != token::RBRACE;
2705 self.commit_expr(expr, &[token::COMMA], &[token::RBRACE]);
2707 self.eat(&token::COMMA);
2710 arms.push(ast::Arm {
2717 let hi = self.span.hi;
2719 return self.mk_expr(lo, hi, ExprMatch(discriminant, arms));
2722 // parse an expression
2723 pub fn parse_expr(&mut self) -> Gc<Expr> {
2724 return self.parse_expr_res(UNRESTRICTED);
2727 // parse an expression, subject to the given restriction
2728 pub fn parse_expr_res(&mut self, r: restriction) -> Gc<Expr> {
2729 let old = self.restriction;
2730 self.restriction = r;
2731 let e = self.parse_assign_expr();
2732 self.restriction = old;
2736 // parse the RHS of a local variable declaration (e.g. '= 14;')
2737 fn parse_initializer(&mut self) -> Option<Gc<Expr>> {
2738 if self.token == token::EQ {
2740 Some(self.parse_expr())
2746 // parse patterns, separated by '|' s
2747 fn parse_pats(&mut self) -> Vec<Gc<Pat>> {
2748 let mut pats = Vec::new();
2750 pats.push(self.parse_pat());
2751 if self.token == token::BINOP(token::OR) { self.bump(); }
2752 else { return pats; }
2756 fn parse_pat_vec_elements(
2758 ) -> (Vec<Gc<Pat>> , Option<Gc<Pat>>, Vec<Gc<Pat>> ) {
2759 let mut before = Vec::new();
2760 let mut slice = None;
2761 let mut after = Vec::new();
2762 let mut first = true;
2763 let mut before_slice = true;
2765 while self.token != token::RBRACKET {
2766 if first { first = false; }
2767 else { self.expect(&token::COMMA); }
2769 let mut is_slice = false;
2771 if self.token == token::DOTDOT {
2774 before_slice = false;
2779 if self.token == token::COMMA || self.token == token::RBRACKET {
2780 slice = Some(box(GC) ast::Pat {
2781 id: ast::DUMMY_NODE_ID,
2786 let subpat = self.parse_pat();
2788 ast::Pat { node: PatIdent(_, _, _), .. } => {
2789 slice = Some(subpat);
2791 ast::Pat { span, .. } => self.span_fatal(
2792 span, "expected an identifier or nothing"
2797 let subpat = self.parse_pat();
2799 before.push(subpat);
2806 (before, slice, after)
2809 // parse the fields of a struct-like pattern
2810 fn parse_pat_fields(&mut self) -> (Vec<ast::FieldPat> , bool) {
2811 let mut fields = Vec::new();
2812 let mut etc = false;
2813 let mut first = true;
2814 while self.token != token::RBRACE {
2818 self.expect(&token::COMMA);
2819 // accept trailing commas
2820 if self.token == token::RBRACE { break }
2823 if self.token == token::DOTDOT {
2825 if self.token != token::RBRACE {
2826 let token_str = self.this_token_to_str();
2827 self.fatal(format!("expected `{}`, found `{}`", "}",
2828 token_str).as_slice())
2834 let bind_type = if self.eat_keyword(keywords::Mut) {
2835 BindByValue(MutMutable)
2836 } else if self.eat_keyword(keywords::Ref) {
2837 BindByRef(self.parse_mutability())
2839 BindByValue(MutImmutable)
2842 let fieldname = self.parse_ident();
2844 let subpat = if self.token == token::COLON {
2846 BindByRef(..) | BindByValue(MutMutable) => {
2847 let token_str = self.this_token_to_str();
2848 self.fatal(format!("unexpected `{}`",
2849 token_str).as_slice())
2857 let fieldpath = codemap::Spanned{span:self.last_span, node: fieldname};
2859 id: ast::DUMMY_NODE_ID,
2860 node: PatIdent(bind_type, fieldpath, None),
2861 span: self.last_span
2864 fields.push(ast::FieldPat { ident: fieldname, pat: subpat });
2866 return (fields, etc);
2870 pub fn parse_pat(&mut self) -> Gc<Pat> {
2871 maybe_whole!(self, NtPat);
2873 let lo = self.span.lo;
2878 token::UNDERSCORE => {
2881 hi = self.last_span.hi;
2882 return box(GC) ast::Pat {
2883 id: ast::DUMMY_NODE_ID,
2891 let sub = self.parse_pat();
2893 let last_span = self.last_span;
2895 self.obsolete(last_span, ObsoleteOwnedPattern);
2896 return box(GC) ast::Pat {
2897 id: ast::DUMMY_NODE_ID,
2902 token::BINOP(token::AND) | token::ANDAND => {
2904 let lo = self.span.lo;
2906 let sub = self.parse_pat();
2907 pat = PatRegion(sub);
2908 hi = self.last_span.hi;
2909 return box(GC) ast::Pat {
2910 id: ast::DUMMY_NODE_ID,
2916 // parse (pat,pat,pat,...) as tuple
2918 if self.token == token::RPAREN {
2921 let lit = box(GC) codemap::Spanned {
2923 span: mk_sp(lo, hi)};
2924 let expr = self.mk_expr(lo, hi, ExprLit(lit));
2927 let mut fields = vec!(self.parse_pat());
2928 if self.look_ahead(1, |t| *t != token::RPAREN) {
2929 while self.token == token::COMMA {
2931 if self.token == token::RPAREN { break; }
2932 fields.push(self.parse_pat());
2935 if fields.len() == 1 { self.expect(&token::COMMA); }
2936 self.expect(&token::RPAREN);
2937 pat = PatTup(fields);
2939 hi = self.last_span.hi;
2940 return box(GC) ast::Pat {
2941 id: ast::DUMMY_NODE_ID,
2946 token::LBRACKET => {
2947 // parse [pat,pat,...] as vector pattern
2949 let (before, slice, after) =
2950 self.parse_pat_vec_elements();
2952 self.expect(&token::RBRACKET);
2953 pat = ast::PatVec(before, slice, after);
2954 hi = self.last_span.hi;
2955 return box(GC) ast::Pat {
2956 id: ast::DUMMY_NODE_ID,
2963 // at this point, token != _, ~, &, &&, (, [
2965 if (!is_ident_or_path(&self.token) && self.token != token::MOD_SEP)
2966 || self.is_keyword(keywords::True)
2967 || self.is_keyword(keywords::False) {
2968 // Parse an expression pattern or exp .. exp.
2970 // These expressions are limited to literals (possibly
2971 // preceded by unary-minus) or identifiers.
2972 let val = self.parse_literal_maybe_minus();
2973 if self.eat(&token::DOTDOT) {
2974 let end = if is_ident_or_path(&self.token) {
2975 let path = self.parse_path(LifetimeAndTypesWithColons)
2977 let hi = self.span.hi;
2978 self.mk_expr(lo, hi, ExprPath(path))
2980 self.parse_literal_maybe_minus()
2982 pat = PatRange(val, end);
2986 } else if self.eat_keyword(keywords::Mut) {
2987 pat = self.parse_pat_ident(BindByValue(MutMutable));
2988 } else if self.eat_keyword(keywords::Ref) {
2990 let mutbl = self.parse_mutability();
2991 pat = self.parse_pat_ident(BindByRef(mutbl));
2992 } else if self.eat_keyword(keywords::Box) {
2995 // FIXME(#13910): Rename to `PatBox` and extend to full DST
2997 let sub = self.parse_pat();
2999 hi = self.last_span.hi;
3000 return box(GC) ast::Pat {
3001 id: ast::DUMMY_NODE_ID,
3006 let can_be_enum_or_struct = self.look_ahead(1, |t| {
3008 token::LPAREN | token::LBRACKET | token::LT |
3009 token::LBRACE | token::MOD_SEP => true,
3014 if self.look_ahead(1, |t| *t == token::DOTDOT) {
3015 let start = self.parse_expr_res(RESTRICT_NO_BAR_OP);
3016 self.eat(&token::DOTDOT);
3017 let end = self.parse_expr_res(RESTRICT_NO_BAR_OP);
3018 pat = PatRange(start, end);
3019 } else if is_plain_ident(&self.token) && !can_be_enum_or_struct {
3020 let id = self.parse_ident();
3021 let id_span = self.last_span;
3022 let pth1 = codemap::Spanned{span:id_span, node: id};
3023 if self.eat(&token::NOT) {
3025 let ket = token::close_delimiter_for(&self.token)
3026 .unwrap_or_else(|| self.fatal("expected open delimiter"));
3029 let tts = self.parse_seq_to_end(&ket,
3031 |p| p.parse_token_tree());
3033 let mac = MacInvocTT(ident_to_path(id_span,id), tts, EMPTY_CTXT);
3034 pat = ast::PatMac(codemap::Spanned {node: mac, span: self.span});
3036 let sub = if self.eat(&token::AT) {
3038 Some(self.parse_pat())
3043 pat = PatIdent(BindByValue(MutImmutable), pth1, sub);
3046 // parse an enum pat
3047 let enum_path = self.parse_path(LifetimeAndTypesWithColons)
3053 self.parse_pat_fields();
3055 pat = PatStruct(enum_path, fields, etc);
3058 let mut args: Vec<Gc<Pat>> = Vec::new();
3061 let is_dotdot = self.look_ahead(1, |t| {
3063 token::DOTDOT => true,
3068 // This is a "top constructor only" pat
3071 self.expect(&token::RPAREN);
3072 pat = PatEnum(enum_path, None);
3074 args = self.parse_enum_variant_seq(
3077 seq_sep_trailing_disallowed(token::COMMA),
3080 pat = PatEnum(enum_path, Some(args));
3084 if enum_path.segments.len() == 1 {
3085 // it could still be either an enum
3086 // or an identifier pattern, resolve
3087 // will sort it out:
3088 pat = PatIdent(BindByValue(MutImmutable),
3090 span: enum_path.span,
3091 node: enum_path.segments.get(0)
3095 pat = PatEnum(enum_path, Some(args));
3103 hi = self.last_span.hi;
3105 id: ast::DUMMY_NODE_ID,
3107 span: mk_sp(lo, hi),
3111 // parse ident or ident @ pat
3112 // used by the copy foo and ref foo patterns to give a good
3113 // error message when parsing mistakes like ref foo(a,b)
3114 fn parse_pat_ident(&mut self,
3115 binding_mode: ast::BindingMode)
3117 if !is_plain_ident(&self.token) {
3118 let last_span = self.last_span;
3119 self.span_fatal(last_span,
3120 "expected identifier, found path");
3122 // why a path here, and not just an identifier?
3123 let name = codemap::Spanned{span: self.last_span, node: self.parse_ident()};
3124 let sub = if self.eat(&token::AT) {
3125 Some(self.parse_pat())
3130 // just to be friendly, if they write something like
3132 // we end up here with ( as the current token. This shortly
3133 // leads to a parse error. Note that if there is no explicit
3134 // binding mode then we do not end up here, because the lookahead
3135 // will direct us over to parse_enum_variant()
3136 if self.token == token::LPAREN {
3137 let last_span = self.last_span;
3140 "expected identifier, found enum pattern");
3143 PatIdent(binding_mode, name, sub)
3146 // parse a local variable declaration
3147 fn parse_local(&mut self) -> Gc<Local> {
3148 let lo = self.span.lo;
3149 let pat = self.parse_pat();
3152 id: ast::DUMMY_NODE_ID,
3154 span: mk_sp(lo, lo),
3156 if self.eat(&token::COLON) {
3157 ty = self.parse_ty(true);
3159 let init = self.parse_initializer();
3160 box(GC) ast::Local {
3164 id: ast::DUMMY_NODE_ID,
3165 span: mk_sp(lo, self.last_span.hi),
3170 // parse a "let" stmt
3171 fn parse_let(&mut self) -> Gc<Decl> {
3172 let lo = self.span.lo;
3173 let local = self.parse_local();
3174 box(GC) spanned(lo, self.last_span.hi, DeclLocal(local))
3177 // parse a structure field
3178 fn parse_name_and_ty(&mut self, pr: Visibility,
3179 attrs: Vec<Attribute> ) -> StructField {
3180 let lo = self.span.lo;
3181 if !is_plain_ident(&self.token) {
3182 self.fatal("expected ident");
3184 let name = self.parse_ident();
3185 self.expect(&token::COLON);
3186 let ty = self.parse_ty(true);
3187 spanned(lo, self.last_span.hi, ast::StructField_ {
3188 kind: NamedField(name, pr),
3189 id: ast::DUMMY_NODE_ID,
3195 // parse a statement. may include decl.
3196 // precondition: any attributes are parsed already
3197 pub fn parse_stmt(&mut self, item_attrs: Vec<Attribute>) -> Gc<Stmt> {
3198 maybe_whole!(self, NtStmt);
3200 fn check_expected_item(p: &mut Parser, found_attrs: bool) {
3201 // If we have attributes then we should have an item
3203 let last_span = p.last_span;
3204 p.span_err(last_span, "expected item after attributes");
3208 let lo = self.span.lo;
3209 if self.is_keyword(keywords::Let) {
3210 check_expected_item(self, !item_attrs.is_empty());
3211 self.expect_keyword(keywords::Let);
3212 let decl = self.parse_let();
3213 return box(GC) spanned(lo, decl.span.hi, StmtDecl(decl, ast::DUMMY_NODE_ID));
3214 } else if is_ident(&self.token)
3215 && !token::is_any_keyword(&self.token)
3216 && self.look_ahead(1, |t| *t == token::NOT) {
3217 // parse a macro invocation. Looks like there's serious
3218 // overlap here; if this clause doesn't catch it (and it
3219 // won't, for brace-delimited macros) it will fall through
3220 // to the macro clause of parse_item_or_view_item. This
3221 // could use some cleanup, it appears to me.
3223 // whoops! I now have a guess: I'm guessing the "parens-only"
3224 // rule here is deliberate, to allow macro users to use parens
3225 // for things that should be parsed as stmt_mac, and braces
3226 // for things that should expand into items. Tricky, and
3227 // somewhat awkward... and probably undocumented. Of course,
3228 // I could just be wrong.
3230 check_expected_item(self, !item_attrs.is_empty());
3232 // Potential trouble: if we allow macros with paths instead of
3233 // idents, we'd need to look ahead past the whole path here...
3234 let pth = self.parse_path(NoTypesAllowed).path;
3237 let id = if token::close_delimiter_for(&self.token).is_some() {
3238 token::special_idents::invalid // no special identifier
3243 // check that we're pointing at delimiters (need to check
3244 // again after the `if`, because of `parse_ident`
3245 // consuming more tokens).
3246 let (bra, ket) = match token::close_delimiter_for(&self.token) {
3247 Some(ket) => (self.token.clone(), ket),
3249 // we only expect an ident if we didn't parse one
3251 let ident_str = if id.name == token::special_idents::invalid.name {
3256 let tok_str = self.this_token_to_str();
3257 self.fatal(format!("expected {}`(` or `{{`, but found `{}`",
3259 tok_str).as_slice())
3263 let tts = self.parse_unspanned_seq(
3267 |p| p.parse_token_tree()
3269 let hi = self.span.hi;
3271 if id.name == token::special_idents::invalid.name {
3272 return box(GC) spanned(lo, hi, StmtMac(
3273 spanned(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT)), false));
3275 // if it has a special ident, it's definitely an item
3276 return box(GC) spanned(lo, hi, StmtDecl(
3277 box(GC) spanned(lo, hi, DeclItem(
3279 lo, hi, id /*id is good here*/,
3280 ItemMac(spanned(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT))),
3281 Inherited, Vec::new(/*no attrs*/)))),
3282 ast::DUMMY_NODE_ID));
3286 let found_attrs = !item_attrs.is_empty();
3287 match self.parse_item_or_view_item(item_attrs, false) {
3290 let decl = box(GC) spanned(lo, hi, DeclItem(i));
3291 return box(GC) spanned(lo, hi, StmtDecl(decl, ast::DUMMY_NODE_ID));
3293 IoviViewItem(vi) => {
3294 self.span_fatal(vi.span,
3295 "view items must be declared at the top of the block");
3297 IoviForeignItem(_) => {
3298 self.fatal("foreign items are not allowed here");
3300 IoviNone(_) => { /* fallthrough */ }
3303 check_expected_item(self, found_attrs);
3305 // Remainder are line-expr stmts.
3306 let e = self.parse_expr_res(RESTRICT_STMT_EXPR);
3307 return box(GC) spanned(lo, e.span.hi, StmtExpr(e, ast::DUMMY_NODE_ID));
3311 // is this expression a successfully-parsed statement?
3312 fn expr_is_complete(&mut self, e: Gc<Expr>) -> bool {
3313 return self.restriction == RESTRICT_STMT_EXPR &&
3314 !classify::expr_requires_semi_to_be_stmt(e);
3317 // parse a block. No inner attrs are allowed.
3318 pub fn parse_block(&mut self) -> P<Block> {
3319 maybe_whole!(no_clone self, NtBlock);
3321 let lo = self.span.lo;
3322 self.expect(&token::LBRACE);
3324 return self.parse_block_tail_(lo, DefaultBlock, Vec::new());
3327 // parse a block. Inner attrs are allowed.
3328 fn parse_inner_attrs_and_block(&mut self)
3329 -> (Vec<Attribute> , P<Block>) {
3331 maybe_whole!(pair_empty self, NtBlock);
3333 let lo = self.span.lo;
3334 self.expect(&token::LBRACE);
3335 let (inner, next) = self.parse_inner_attrs_and_next();
3337 (inner, self.parse_block_tail_(lo, DefaultBlock, next))
3340 // Precondition: already parsed the '{' or '#{'
3341 // I guess that also means "already parsed the 'impure'" if
3342 // necessary, and this should take a qualifier.
3343 // some blocks start with "#{"...
3344 fn parse_block_tail(&mut self, lo: BytePos, s: BlockCheckMode) -> P<Block> {
3345 self.parse_block_tail_(lo, s, Vec::new())
3348 // parse the rest of a block expression or function body
3349 fn parse_block_tail_(&mut self, lo: BytePos, s: BlockCheckMode,
3350 first_item_attrs: Vec<Attribute> ) -> P<Block> {
3351 let mut stmts = Vec::new();
3352 let mut expr = None;
3354 // wouldn't it be more uniform to parse view items only, here?
3355 let ParsedItemsAndViewItems {
3356 attrs_remaining: attrs_remaining,
3357 view_items: view_items,
3360 } = self.parse_items_and_view_items(first_item_attrs,
3363 for item in items.iter() {
3364 let decl = box(GC) spanned(item.span.lo, item.span.hi, DeclItem(*item));
3365 stmts.push(box(GC) spanned(item.span.lo, item.span.hi,
3366 StmtDecl(decl, ast::DUMMY_NODE_ID)));
3369 let mut attributes_box = attrs_remaining;
3371 while self.token != token::RBRACE {
3372 // parsing items even when they're not allowed lets us give
3373 // better error messages and recover more gracefully.
3374 attributes_box.push_all(self.parse_outer_attributes().as_slice());
3377 if !attributes_box.is_empty() {
3378 let last_span = self.last_span;
3379 self.span_err(last_span, "expected item after attributes");
3380 attributes_box = Vec::new();
3382 self.bump(); // empty
3385 // fall through and out.
3388 let stmt = self.parse_stmt(attributes_box);
3389 attributes_box = Vec::new();
3391 StmtExpr(e, stmt_id) => {
3392 // expression without semicolon
3393 if classify::stmt_ends_with_semi(&*stmt) {
3394 // Just check for errors and recover; do not eat semicolon yet.
3395 self.commit_stmt(stmt, &[], &[token::SEMI, token::RBRACE]);
3401 let span_with_semi = Span {
3403 hi: self.last_span.hi,
3404 expn_info: stmt.span.expn_info,
3406 stmts.push(box(GC) codemap::Spanned {
3407 node: StmtSemi(e, stmt_id),
3408 span: span_with_semi,
3419 StmtMac(ref m, _) => {
3420 // statement macro; might be an expr
3424 stmts.push(box(GC) codemap::Spanned {
3425 node: StmtMac((*m).clone(), true),
3430 // if a block ends in `m!(arg)` without
3431 // a `;`, it must be an expr
3433 self.mk_mac_expr(stmt.span.lo,
3442 _ => { // all other kinds of statements:
3443 stmts.push(stmt.clone());
3445 if classify::stmt_ends_with_semi(&*stmt) {
3446 self.commit_stmt_expecting(stmt, token::SEMI);
3454 if !attributes_box.is_empty() {
3455 let last_span = self.last_span;
3456 self.span_err(last_span, "expected item after attributes");
3459 let hi = self.span.hi;
3462 view_items: view_items,
3465 id: ast::DUMMY_NODE_ID,
3467 span: mk_sp(lo, hi),
3471 fn parse_unboxed_function_type(&mut self) -> UnboxedFnTy {
3472 let inputs = if self.eat(&token::OROR) {
3477 if self.token == token::BINOP(token::AND) &&
3478 self.look_ahead(1, |t| {
3479 token::is_keyword(keywords::Mut, t)
3481 self.look_ahead(2, |t| *t == token::COLON) {
3487 let inputs = self.parse_seq_to_before_or(&token::COMMA,
3489 p.parse_arg_general(false)
3495 let (return_style, output) = self.parse_ret_ty();
3506 // matches bounds = ( boundseq )?
3507 // where boundseq = ( bound + boundseq ) | bound
3508 // and bound = 'static | ty
3509 // Returns "None" if there's no colon (e.g. "T");
3510 // Returns "Some(Empty)" if there's a colon but nothing after (e.g. "T:")
3511 // Returns "Some(stuff)" otherwise (e.g. "T:stuff").
3512 // NB: The None/Some distinction is important for issue #7264.
3514 // Note that the `allow_any_lifetime` argument is a hack for now while the
3515 // AST doesn't support arbitrary lifetimes in bounds on type parameters. In
3516 // the future, this flag should be removed, and the return value of this
3517 // function should be Option<~[TyParamBound]>
3518 fn parse_ty_param_bounds(&mut self, allow_any_lifetime: bool)
3519 -> (Option<ast::Lifetime>,
3520 OwnedSlice<TyParamBound>) {
3521 let mut ret_lifetime = None;
3522 let mut result = vec!();
3525 token::LIFETIME(lifetime) => {
3526 let lifetime_interned_string = token::get_ident(lifetime);
3527 if lifetime_interned_string.equiv(&("'static")) {
3528 result.push(StaticRegionTyParamBound);
3529 if allow_any_lifetime && ret_lifetime.is_none() {
3530 ret_lifetime = Some(ast::Lifetime {
3531 id: ast::DUMMY_NODE_ID,
3536 } else if allow_any_lifetime && ret_lifetime.is_none() {
3537 ret_lifetime = Some(ast::Lifetime {
3538 id: ast::DUMMY_NODE_ID,
3543 result.push(OtherRegionTyParamBound(self.span));
3547 token::MOD_SEP | token::IDENT(..) => {
3548 let tref = self.parse_trait_ref();
3549 result.push(TraitTyParamBound(tref));
3551 token::BINOP(token::OR) | token::OROR => {
3552 let unboxed_function_type =
3553 self.parse_unboxed_function_type();
3554 result.push(UnboxedFnTyParamBound(unboxed_function_type));
3559 if !self.eat(&token::BINOP(token::PLUS)) {
3564 return (ret_lifetime, OwnedSlice::from_vec(result));
3567 // matches typaram = type? IDENT optbounds ( EQ ty )?
3568 fn parse_ty_param(&mut self) -> TyParam {
3569 let sized = self.parse_sized();
3570 let span = self.span;
3571 let ident = self.parse_ident();
3573 if self.eat(&token::COLON) {
3574 let (_, bounds) = self.parse_ty_param_bounds(false);
3580 // For typarams we don't care about the difference b/w "<T>" and "<T:>".
3581 let bounds = opt_bounds.unwrap_or_default();
3583 let default = if self.token == token::EQ {
3585 Some(self.parse_ty(true))
3591 id: ast::DUMMY_NODE_ID,
3599 // parse a set of optional generic type parameter declarations
3600 // matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
3601 // | ( < lifetimes , typaramseq ( , )? > )
3602 // where typaramseq = ( typaram ) | ( typaram , typaramseq )
3603 pub fn parse_generics(&mut self) -> ast::Generics {
3604 if self.eat(&token::LT) {
3605 let lifetimes = self.parse_lifetimes();
3606 let mut seen_default = false;
3607 let ty_params = self.parse_seq_to_gt(Some(token::COMMA), |p| {
3608 p.forbid_lifetime();
3609 let ty_param = p.parse_ty_param();
3610 if ty_param.default.is_some() {
3611 seen_default = true;
3612 } else if seen_default {
3613 let last_span = p.last_span;
3614 p.span_err(last_span,
3615 "type parameters with a default must be trailing");
3619 ast::Generics { lifetimes: lifetimes, ty_params: ty_params }
3621 ast_util::empty_generics()
3625 fn parse_generic_values_after_lt(&mut self) -> (Vec<ast::Lifetime>, Vec<P<Ty>> ) {
3626 let lifetimes = self.parse_lifetimes();
3627 let result = self.parse_seq_to_gt(
3630 p.forbid_lifetime();
3634 (lifetimes, result.into_vec())
3637 fn forbid_lifetime(&mut self) {
3638 if Parser::token_is_lifetime(&self.token) {
3639 let span = self.span;
3640 self.span_fatal(span, "lifetime parameters must be declared \
3641 prior to type parameters");
3645 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
3646 -> (Vec<Arg> , bool) {
3648 let mut args: Vec<Option<Arg>> =
3649 self.parse_unspanned_seq(
3652 seq_sep_trailing_allowed(token::COMMA),
3654 if p.token == token::DOTDOTDOT {
3657 if p.token != token::RPAREN {
3660 "`...` must be last in argument list for variadic function");
3665 "only foreign functions are allowed to be variadic");
3669 Some(p.parse_arg_general(named_args))
3674 let variadic = match args.pop() {
3677 // Need to put back that last arg
3684 if variadic && args.is_empty() {
3686 "variadic function must be declared with at least one named argument");
3689 let args = args.move_iter().map(|x| x.unwrap()).collect();
3694 // parse the argument list and result type of a function declaration
3695 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> P<FnDecl> {
3697 let (args, variadic) = self.parse_fn_args(true, allow_variadic);
3698 let (ret_style, ret_ty) = self.parse_ret_ty();
3708 fn is_self_ident(&mut self) -> bool {
3710 token::IDENT(id, false) => id.name == special_idents::self_.name,
3715 fn expect_self_ident(&mut self) {
3716 if !self.is_self_ident() {
3717 let token_str = self.this_token_to_str();
3718 self.fatal(format!("expected `self` but found `{}`",
3719 token_str).as_slice())
3724 // parse the argument list and result type of a function
3725 // that may have a self type.
3726 fn parse_fn_decl_with_self(&mut self, parse_arg_fn: |&mut Parser| -> Arg)
3727 -> (ExplicitSelf, P<FnDecl>) {
3728 fn maybe_parse_borrowed_explicit_self(this: &mut Parser)
3729 -> ast::ExplicitSelf_ {
3730 // The following things are possible to see here:
3735 // fn(&'lt mut self)
3737 // We already know that the current token is `&`.
3739 if this.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) {
3741 this.expect_self_ident();
3742 SelfRegion(None, MutImmutable)
3743 } else if this.look_ahead(1, |t| Parser::token_is_mutability(t)) &&
3745 |t| token::is_keyword(keywords::Self,
3748 let mutability = this.parse_mutability();
3749 this.expect_self_ident();
3750 SelfRegion(None, mutability)
3751 } else if this.look_ahead(1, |t| Parser::token_is_lifetime(t)) &&
3753 |t| token::is_keyword(keywords::Self,
3756 let lifetime = this.parse_lifetime();
3757 this.expect_self_ident();
3758 SelfRegion(Some(lifetime), MutImmutable)
3759 } else if this.look_ahead(1, |t| Parser::token_is_lifetime(t)) &&
3760 this.look_ahead(2, |t| {
3761 Parser::token_is_mutability(t)
3763 this.look_ahead(3, |t| token::is_keyword(keywords::Self,
3766 let lifetime = this.parse_lifetime();
3767 let mutability = this.parse_mutability();
3768 this.expect_self_ident();
3769 SelfRegion(Some(lifetime), mutability)
3775 self.expect(&token::LPAREN);
3777 // A bit of complexity and lookahead is needed here in order to be
3778 // backwards compatible.
3779 let lo = self.span.lo;
3780 let mut mutbl_self = MutImmutable;
3781 let explicit_self = match self.token {
3782 token::BINOP(token::AND) => {
3783 maybe_parse_borrowed_explicit_self(self)
3786 // We need to make sure it isn't a type
3787 if self.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) {
3789 self.expect_self_ident();
3795 token::IDENT(..) if self.is_self_ident() => {
3799 token::BINOP(token::STAR) => {
3800 // Possibly "*self" or "*mut self" -- not supported. Try to avoid
3801 // emitting cryptic "unexpected token" errors.
3803 let _mutability = if Parser::token_is_mutability(&self.token) {
3804 self.parse_mutability()
3805 } else { MutImmutable };
3806 if self.is_self_ident() {
3807 let span = self.span;
3808 self.span_err(span, "cannot pass self by unsafe pointer");
3813 _ if Parser::token_is_mutability(&self.token) &&
3814 self.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) => {
3815 mutbl_self = self.parse_mutability();
3816 self.expect_self_ident();
3819 _ if Parser::token_is_mutability(&self.token) &&
3820 self.look_ahead(1, |t| *t == token::TILDE) &&
3821 self.look_ahead(2, |t| token::is_keyword(keywords::Self, t)) => {
3822 mutbl_self = self.parse_mutability();
3824 self.expect_self_ident();
3830 let explicit_self_sp = mk_sp(lo, self.span.hi);
3832 // If we parsed a self type, expect a comma before the argument list.
3833 let fn_inputs = if explicit_self != SelfStatic {
3837 let sep = seq_sep_trailing_disallowed(token::COMMA);
3838 let mut fn_inputs = self.parse_seq_to_before_end(
3843 fn_inputs.unshift(Arg::new_self(explicit_self_sp, mutbl_self));
3847 vec!(Arg::new_self(explicit_self_sp, mutbl_self))
3850 let token_str = self.this_token_to_str();
3851 self.fatal(format!("expected `,` or `)`, found `{}`",
3852 token_str).as_slice())
3856 let sep = seq_sep_trailing_disallowed(token::COMMA);
3857 self.parse_seq_to_before_end(&token::RPAREN, sep, parse_arg_fn)
3860 self.expect(&token::RPAREN);
3862 let hi = self.span.hi;
3864 let (ret_style, ret_ty) = self.parse_ret_ty();
3866 let fn_decl = P(FnDecl {
3873 (spanned(lo, hi, explicit_self), fn_decl)
3876 // parse the |arg, arg| header on a lambda
3877 fn parse_fn_block_decl(&mut self) -> P<FnDecl> {
3878 let inputs_captures = {
3879 if self.eat(&token::OROR) {
3882 self.parse_unspanned_seq(
3883 &token::BINOP(token::OR),
3884 &token::BINOP(token::OR),
3885 seq_sep_trailing_disallowed(token::COMMA),
3886 |p| p.parse_fn_block_arg()
3890 let output = if self.eat(&token::RARROW) {
3894 id: ast::DUMMY_NODE_ID,
3901 inputs: inputs_captures,
3908 // Parses the `(arg, arg) -> return_type` header on a procedure.
3909 fn parse_proc_decl(&mut self) -> P<FnDecl> {
3911 self.parse_unspanned_seq(&token::LPAREN,
3913 seq_sep_trailing_allowed(token::COMMA),
3914 |p| p.parse_fn_block_arg());
3916 let output = if self.eat(&token::RARROW) {
3920 id: ast::DUMMY_NODE_ID,
3934 // parse the name and optional generic types of a function header.
3935 fn parse_fn_header(&mut self) -> (Ident, ast::Generics) {
3936 let id = self.parse_ident();
3937 let generics = self.parse_generics();
3941 fn mk_item(&mut self, lo: BytePos, hi: BytePos, ident: Ident,
3942 node: Item_, vis: Visibility,
3943 attrs: Vec<Attribute>) -> Gc<Item> {
3947 id: ast::DUMMY_NODE_ID,
3954 // parse an item-position function declaration.
3955 fn parse_item_fn(&mut self, fn_style: FnStyle, abi: abi::Abi) -> ItemInfo {
3956 let (ident, generics) = self.parse_fn_header();
3957 let decl = self.parse_fn_decl(false);
3958 let (inner_attrs, body) = self.parse_inner_attrs_and_block();
3959 (ident, ItemFn(decl, fn_style, abi, generics, body), Some(inner_attrs))
3962 // parse a method in a trait impl, starting with `attrs` attributes.
3963 fn parse_method(&mut self,
3964 already_parsed_attrs: Option<Vec<Attribute>>) -> Gc<Method> {
3965 let next_attrs = self.parse_outer_attributes();
3966 let attrs = match already_parsed_attrs {
3967 Some(mut a) => { a.push_all_move(next_attrs); a }
3971 let lo = self.span.lo;
3973 let visa = self.parse_visibility();
3974 let fn_style = self.parse_fn_style();
3975 let ident = self.parse_ident();
3976 let generics = self.parse_generics();
3977 let (explicit_self, decl) = self.parse_fn_decl_with_self(|p| {
3981 let (inner_attrs, body) = self.parse_inner_attrs_and_block();
3982 let hi = body.span.hi;
3983 let attrs = attrs.append(inner_attrs.as_slice());
3984 box(GC) ast::Method {
3988 explicit_self: explicit_self,
3992 id: ast::DUMMY_NODE_ID,
3993 span: mk_sp(lo, hi),
3998 // parse trait Foo { ... }
3999 fn parse_item_trait(&mut self) -> ItemInfo {
4000 let ident = self.parse_ident();
4001 let tps = self.parse_generics();
4002 let sized = self.parse_for_sized();
4004 // Parse traits, if necessary.
4006 if self.token == token::COLON {
4008 traits = self.parse_trait_ref_list(&token::LBRACE);
4010 traits = Vec::new();
4013 let meths = self.parse_trait_methods();
4014 (ident, ItemTrait(tps, sized, traits, meths), None)
4017 // Parses two variants (with the region/type params always optional):
4018 // impl<T> Foo { ... }
4019 // impl<T> ToStr for ~[T] { ... }
4020 fn parse_item_impl(&mut self) -> ItemInfo {
4021 // First, parse type parameters if necessary.
4022 let generics = self.parse_generics();
4024 // Special case: if the next identifier that follows is '(', don't
4025 // allow this to be parsed as a trait.
4026 let could_be_trait = self.token != token::LPAREN;
4029 let mut ty = self.parse_ty(true);
4031 // Parse traits, if necessary.
4032 let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) {
4033 // New-style trait. Reinterpret the type as a trait.
4034 let opt_trait_ref = match ty.node {
4035 TyPath(ref path, None, node_id) => {
4037 path: /* bad */ (*path).clone(),
4042 self.span_err(ty.span,
4043 "bounded traits are only valid in type position");
4047 self.span_err(ty.span, "not a trait");
4052 ty = self.parse_ty(true);
4058 let mut meths = Vec::new();
4059 self.expect(&token::LBRACE);
4060 let (inner_attrs, next) = self.parse_inner_attrs_and_next();
4061 let mut method_attrs = Some(next);
4062 while !self.eat(&token::RBRACE) {
4063 meths.push(self.parse_method(method_attrs));
4064 method_attrs = None;
4067 let ident = ast_util::impl_pretty_name(&opt_trait, &*ty);
4069 (ident, ItemImpl(generics, opt_trait, ty, meths), Some(inner_attrs))
4072 // parse a::B<String,int>
4073 fn parse_trait_ref(&mut self) -> TraitRef {
4075 path: self.parse_path(LifetimeAndTypesWithoutColons).path,
4076 ref_id: ast::DUMMY_NODE_ID,
4080 // parse B + C<String,int> + D
4081 fn parse_trait_ref_list(&mut self, ket: &token::Token) -> Vec<TraitRef> {
4082 self.parse_seq_to_before_end(
4084 seq_sep_trailing_disallowed(token::BINOP(token::PLUS)),
4085 |p| p.parse_trait_ref()
4089 // parse struct Foo { ... }
4090 fn parse_item_struct(&mut self, is_virtual: bool) -> ItemInfo {
4091 let class_name = self.parse_ident();
4092 let generics = self.parse_generics();
4094 let super_struct = if self.eat(&token::COLON) {
4095 let ty = self.parse_ty(true);
4097 TyPath(_, None, _) => {
4101 self.span_err(ty.span, "not a struct");
4109 let mut fields: Vec<StructField>;
4112 if self.eat(&token::LBRACE) {
4113 // It's a record-like struct.
4114 is_tuple_like = false;
4115 fields = Vec::new();
4116 while self.token != token::RBRACE {
4117 fields.push(self.parse_struct_decl_field());
4119 if fields.len() == 0 {
4120 self.fatal(format!("unit-like struct definition should be \
4121 written as `struct {};`",
4122 token::get_ident(class_name)).as_slice());
4125 } else if self.token == token::LPAREN {
4126 // It's a tuple-like struct.
4127 is_tuple_like = true;
4128 fields = self.parse_unspanned_seq(
4131 seq_sep_trailing_allowed(token::COMMA),
4133 let attrs = p.parse_outer_attributes();
4135 let struct_field_ = ast::StructField_ {
4136 kind: UnnamedField(p.parse_visibility()),
4137 id: ast::DUMMY_NODE_ID,
4138 ty: p.parse_ty(true),
4141 spanned(lo, p.span.hi, struct_field_)
4143 if fields.len() == 0 {
4144 self.fatal(format!("unit-like struct definition should be \
4145 written as `struct {};`",
4146 token::get_ident(class_name)).as_slice());
4148 self.expect(&token::SEMI);
4149 } else if self.eat(&token::SEMI) {
4150 // It's a unit-like struct.
4151 is_tuple_like = true;
4152 fields = Vec::new();
4154 let token_str = self.this_token_to_str();
4155 self.fatal(format!("expected `{}`, `(`, or `;` after struct \
4156 name but found `{}`", "{",
4157 token_str).as_slice())
4160 let _ = ast::DUMMY_NODE_ID; // FIXME: Workaround for crazy bug.
4161 let new_id = ast::DUMMY_NODE_ID;
4163 ItemStruct(box(GC) ast::StructDef {
4165 ctor_id: if is_tuple_like { Some(new_id) } else { None },
4166 super_struct: super_struct,
4167 is_virtual: is_virtual,
4172 // parse a structure field declaration
4173 pub fn parse_single_struct_field(&mut self,
4175 attrs: Vec<Attribute> )
4177 let a_var = self.parse_name_and_ty(vis, attrs);
4184 let span = self.span;
4185 let token_str = self.this_token_to_str();
4186 self.span_fatal(span,
4187 format!("expected `,`, or `}}` but found `{}`",
4188 token_str).as_slice())
4194 // parse an element of a struct definition
4195 fn parse_struct_decl_field(&mut self) -> StructField {
4197 let attrs = self.parse_outer_attributes();
4199 if self.eat_keyword(keywords::Pub) {
4200 return self.parse_single_struct_field(Public, attrs);
4203 return self.parse_single_struct_field(Inherited, attrs);
4206 // parse visiility: PUB, PRIV, or nothing
4207 fn parse_visibility(&mut self) -> Visibility {
4208 if self.eat_keyword(keywords::Pub) { Public }
4212 fn parse_sized(&mut self) -> Sized {
4213 if self.eat_keyword(keywords::Type) { DynSize }
4217 fn parse_for_sized(&mut self) -> Sized {
4218 if self.eat_keyword(keywords::For) {
4219 if !self.eat_keyword(keywords::Type) {
4220 let last_span = self.last_span;
4221 self.span_err(last_span,
4222 "expected 'type' after for in trait item");
4230 // given a termination token and a vector of already-parsed
4231 // attributes (of length 0 or 1), parse all of the items in a module
4232 fn parse_mod_items(&mut self,
4234 first_item_attrs: Vec<Attribute>,
4237 // parse all of the items up to closing or an attribute.
4238 // view items are legal here.
4239 let ParsedItemsAndViewItems {
4240 attrs_remaining: attrs_remaining,
4241 view_items: view_items,
4242 items: starting_items,
4244 } = self.parse_items_and_view_items(first_item_attrs, true, true);
4245 let mut items: Vec<Gc<Item>> = starting_items;
4246 let attrs_remaining_len = attrs_remaining.len();
4248 // don't think this other loop is even necessary....
4250 let mut first = true;
4251 while self.token != term {
4252 let mut attrs = self.parse_outer_attributes();
4254 attrs = attrs_remaining.clone().append(attrs.as_slice());
4257 debug!("parse_mod_items: parse_item_or_view_item(attrs={:?})",
4259 match self.parse_item_or_view_item(attrs,
4260 true /* macros allowed */) {
4261 IoviItem(item) => items.push(item),
4262 IoviViewItem(view_item) => {
4263 self.span_fatal(view_item.span,
4264 "view items must be declared at the top of \
4268 let token_str = self.this_token_to_str();
4269 self.fatal(format!("expected item but found `{}`",
4270 token_str).as_slice())
4275 if first && attrs_remaining_len > 0u {
4276 // We parsed attributes for the first item but didn't find it
4277 let last_span = self.last_span;
4278 self.span_err(last_span, "expected item after attributes");
4282 inner: mk_sp(inner_lo, self.span.lo),
4283 view_items: view_items,
4288 fn parse_item_const(&mut self) -> ItemInfo {
4289 let m = if self.eat_keyword(keywords::Mut) {MutMutable} else {MutImmutable};
4290 let id = self.parse_ident();
4291 self.expect(&token::COLON);
4292 let ty = self.parse_ty(true);
4293 self.expect(&token::EQ);
4294 let e = self.parse_expr();
4295 self.commit_expr_expecting(e, token::SEMI);
4296 (id, ItemStatic(ty, m, e), None)
4299 // parse a `mod <foo> { ... }` or `mod <foo>;` item
4300 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> ItemInfo {
4301 let id_span = self.span;
4302 let id = self.parse_ident();
4303 if self.token == token::SEMI {
4305 // This mod is in an external file. Let's go get it!
4306 let (m, attrs) = self.eval_src_mod(id, outer_attrs, id_span);
4307 (id, m, Some(attrs))
4309 self.push_mod_path(id, outer_attrs);
4310 self.expect(&token::LBRACE);
4311 let mod_inner_lo = self.span.lo;
4312 let old_owns_directory = self.owns_directory;
4313 self.owns_directory = true;
4314 let (inner, next) = self.parse_inner_attrs_and_next();
4315 let m = self.parse_mod_items(token::RBRACE, next, mod_inner_lo);
4316 self.expect(&token::RBRACE);
4317 self.owns_directory = old_owns_directory;
4318 self.pop_mod_path();
4319 (id, ItemMod(m), Some(inner))
4323 fn push_mod_path(&mut self, id: Ident, attrs: &[Attribute]) {
4324 let default_path = self.id_to_interned_str(id);
4325 let file_path = match ::attr::first_attr_value_str_by_name(attrs,
4328 None => default_path,
4330 self.mod_path_stack.push(file_path)
4333 fn pop_mod_path(&mut self) {
4334 self.mod_path_stack.pop().unwrap();
4337 // read a module from a source file.
4338 fn eval_src_mod(&mut self,
4340 outer_attrs: &[ast::Attribute],
4342 -> (ast::Item_, Vec<ast::Attribute> ) {
4343 let mut prefix = Path::new(self.sess.span_diagnostic.cm.span_to_filename(self.span));
4345 let mod_path = Path::new(".").join_many(self.mod_path_stack.as_slice());
4346 let dir_path = prefix.join(&mod_path);
4347 let mod_string = token::get_ident(id);
4348 let (file_path, owns_directory) = match ::attr::first_attr_value_str_by_name(
4349 outer_attrs, "path") {
4350 Some(d) => (dir_path.join(d), true),
4352 let mod_name = mod_string.get().to_string();
4353 let default_path_str = format!("{}.rs", mod_name);
4354 let secondary_path_str = format!("{}/mod.rs", mod_name);
4355 let default_path = dir_path.join(default_path_str.as_slice());
4356 let secondary_path = dir_path.join(secondary_path_str.as_slice());
4357 let default_exists = default_path.exists();
4358 let secondary_exists = secondary_path.exists();
4360 if !self.owns_directory {
4361 self.span_err(id_sp,
4362 "cannot declare a new module at this location");
4363 let this_module = match self.mod_path_stack.last() {
4364 Some(name) => name.get().to_string(),
4365 None => self.root_module_name.get_ref().clone(),
4367 self.span_note(id_sp,
4368 format!("maybe move this module `{0}` \
4369 to its own directory via \
4371 this_module).as_slice());
4372 if default_exists || secondary_exists {
4373 self.span_note(id_sp,
4374 format!("... or maybe `use` the module \
4375 `{}` instead of possibly \
4377 mod_name).as_slice());
4379 self.abort_if_errors();
4382 match (default_exists, secondary_exists) {
4383 (true, false) => (default_path, false),
4384 (false, true) => (secondary_path, true),
4386 self.span_fatal(id_sp,
4387 format!("file not found for module \
4389 mod_name).as_slice());
4394 format!("file for module `{}` found at both {} \
4398 secondary_path_str).as_slice());
4404 self.eval_src_mod_from_path(file_path, owns_directory,
4405 mod_string.get().to_string(), id_sp)
4408 fn eval_src_mod_from_path(&mut self,
4410 owns_directory: bool,
4412 id_sp: Span) -> (ast::Item_, Vec<ast::Attribute> ) {
4413 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
4414 match included_mod_stack.iter().position(|p| *p == path) {
4416 let mut err = String::from_str("circular modules: ");
4417 let len = included_mod_stack.len();
4418 for p in included_mod_stack.slice(i, len).iter() {
4419 err.push_str(p.display().as_maybe_owned().as_slice());
4420 err.push_str(" -> ");
4422 err.push_str(path.display().as_maybe_owned().as_slice());
4423 self.span_fatal(id_sp, err.as_slice());
4427 included_mod_stack.push(path.clone());
4428 drop(included_mod_stack);
4431 new_sub_parser_from_file(self.sess,
4437 let mod_inner_lo = p0.span.lo;
4438 let (mod_attrs, next) = p0.parse_inner_attrs_and_next();
4439 let first_item_outer_attrs = next;
4440 let m0 = p0.parse_mod_items(token::EOF, first_item_outer_attrs, mod_inner_lo);
4441 self.sess.included_mod_stack.borrow_mut().pop();
4442 return (ast::ItemMod(m0), mod_attrs);
4445 // parse a function declaration from a foreign module
4446 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility,
4447 attrs: Vec<Attribute>) -> Gc<ForeignItem> {
4448 let lo = self.span.lo;
4449 self.expect_keyword(keywords::Fn);
4451 let (ident, generics) = self.parse_fn_header();
4452 let decl = self.parse_fn_decl(true);
4453 let hi = self.span.hi;
4454 self.expect(&token::SEMI);
4455 box(GC) ast::ForeignItem { ident: ident,
4457 node: ForeignItemFn(decl, generics),
4458 id: ast::DUMMY_NODE_ID,
4459 span: mk_sp(lo, hi),
4463 // parse a static item from a foreign module
4464 fn parse_item_foreign_static(&mut self, vis: ast::Visibility,
4465 attrs: Vec<Attribute> ) -> Gc<ForeignItem> {
4466 let lo = self.span.lo;
4468 self.expect_keyword(keywords::Static);
4469 let mutbl = self.eat_keyword(keywords::Mut);
4471 let ident = self.parse_ident();
4472 self.expect(&token::COLON);
4473 let ty = self.parse_ty(true);
4474 let hi = self.span.hi;
4475 self.expect(&token::SEMI);
4476 box(GC) ast::ForeignItem {
4479 node: ForeignItemStatic(ty, mutbl),
4480 id: ast::DUMMY_NODE_ID,
4481 span: mk_sp(lo, hi),
4486 // parse safe/unsafe and fn
4487 fn parse_fn_style(&mut self) -> FnStyle {
4488 if self.eat_keyword(keywords::Fn) { NormalFn }
4489 else if self.eat_keyword(keywords::Unsafe) {
4490 self.expect_keyword(keywords::Fn);
4493 else { self.unexpected(); }
4497 // at this point, this is essentially a wrapper for
4498 // parse_foreign_items.
4499 fn parse_foreign_mod_items(&mut self,
4501 first_item_attrs: Vec<Attribute> )
4503 let ParsedItemsAndViewItems {
4504 attrs_remaining: attrs_remaining,
4505 view_items: view_items,
4507 foreign_items: foreign_items
4508 } = self.parse_foreign_items(first_item_attrs, true);
4509 if ! attrs_remaining.is_empty() {
4510 let last_span = self.last_span;
4511 self.span_err(last_span,
4512 "expected item after attributes");
4514 assert!(self.token == token::RBRACE);
4517 view_items: view_items,
4518 items: foreign_items
4522 /// Parse extern crate links
4526 /// extern crate url;
4527 /// extern crate foo = "bar";
4528 fn parse_item_extern_crate(&mut self,
4530 visibility: Visibility,
4531 attrs: Vec<Attribute> )
4534 let (maybe_path, ident) = match self.token {
4535 token::IDENT(..) => {
4536 let the_ident = self.parse_ident();
4537 self.expect_one_of(&[], &[token::EQ, token::SEMI]);
4538 let path = if self.token == token::EQ {
4540 Some(self.parse_str())
4543 self.expect(&token::SEMI);
4547 let span = self.span;
4548 let token_str = self.this_token_to_str();
4549 self.span_fatal(span,
4550 format!("expected extern crate name but \
4552 token_str).as_slice());
4556 IoviViewItem(ast::ViewItem {
4557 node: ViewItemExternCrate(ident, maybe_path, ast::DUMMY_NODE_ID),
4560 span: mk_sp(lo, self.last_span.hi)
4564 /// Parse `extern` for foreign ABIs
4567 /// `extern` is expected to have been
4568 /// consumed before calling this method
4574 fn parse_item_foreign_mod(&mut self,
4576 opt_abi: Option<abi::Abi>,
4577 visibility: Visibility,
4578 attrs: Vec<Attribute> )
4581 self.expect(&token::LBRACE);
4583 let abi = opt_abi.unwrap_or(abi::C);
4585 let (inner, next) = self.parse_inner_attrs_and_next();
4586 let m = self.parse_foreign_mod_items(abi, next);
4587 self.expect(&token::RBRACE);
4589 let last_span = self.last_span;
4590 let item = self.mk_item(lo,
4592 special_idents::invalid,
4595 maybe_append(attrs, Some(inner)));
4596 return IoviItem(item);
4599 // parse type Foo = Bar;
4600 fn parse_item_type(&mut self) -> ItemInfo {
4601 let ident = self.parse_ident();
4602 let tps = self.parse_generics();
4603 self.expect(&token::EQ);
4604 let ty = self.parse_ty(true);
4605 self.expect(&token::SEMI);
4606 (ident, ItemTy(ty, tps), None)
4609 // parse a structure-like enum variant definition
4610 // this should probably be renamed or refactored...
4611 fn parse_struct_def(&mut self) -> Gc<StructDef> {
4612 let mut fields: Vec<StructField> = Vec::new();
4613 while self.token != token::RBRACE {
4614 fields.push(self.parse_struct_decl_field());
4618 return box(GC) ast::StructDef {
4626 // parse the part of an "enum" decl following the '{'
4627 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> EnumDef {
4628 let mut variants = Vec::new();
4629 let mut all_nullary = true;
4630 let mut have_disr = false;
4631 while self.token != token::RBRACE {
4632 let variant_attrs = self.parse_outer_attributes();
4633 let vlo = self.span.lo;
4635 let vis = self.parse_visibility();
4639 let mut args = Vec::new();
4640 let mut disr_expr = None;
4641 ident = self.parse_ident();
4642 if self.eat(&token::LBRACE) {
4643 // Parse a struct variant.
4644 all_nullary = false;
4645 kind = StructVariantKind(self.parse_struct_def());
4646 } else if self.token == token::LPAREN {
4647 all_nullary = false;
4648 let arg_tys = self.parse_enum_variant_seq(
4651 seq_sep_trailing_disallowed(token::COMMA),
4652 |p| p.parse_ty(true)
4654 for ty in arg_tys.move_iter() {
4655 args.push(ast::VariantArg {
4657 id: ast::DUMMY_NODE_ID,
4660 kind = TupleVariantKind(args);
4661 } else if self.eat(&token::EQ) {
4663 disr_expr = Some(self.parse_expr());
4664 kind = TupleVariantKind(args);
4666 kind = TupleVariantKind(Vec::new());
4669 let vr = ast::Variant_ {
4671 attrs: variant_attrs,
4673 id: ast::DUMMY_NODE_ID,
4674 disr_expr: disr_expr,
4677 variants.push(P(spanned(vlo, self.last_span.hi, vr)));
4679 if !self.eat(&token::COMMA) { break; }
4681 self.expect(&token::RBRACE);
4682 if have_disr && !all_nullary {
4683 self.fatal("discriminator values can only be used with a c-like \
4687 ast::EnumDef { variants: variants }
4690 // parse an "enum" declaration
4691 fn parse_item_enum(&mut self) -> ItemInfo {
4692 let id = self.parse_ident();
4693 let generics = self.parse_generics();
4694 self.expect(&token::LBRACE);
4696 let enum_definition = self.parse_enum_def(&generics);
4697 (id, ItemEnum(enum_definition, generics), None)
4700 fn fn_expr_lookahead(tok: &token::Token) -> bool {
4702 token::LPAREN | token::AT | token::TILDE | token::BINOP(_) => true,
4707 // Parses a string as an ABI spec on an extern type or module. Consumes
4708 // the `extern` keyword, if one is found.
4709 fn parse_opt_abi(&mut self) -> Option<abi::Abi> {
4711 token::LIT_STR(s) | token::LIT_STR_RAW(s, _) => {
4713 let identifier_string = token::get_ident(s);
4714 let the_string = identifier_string.get();
4715 match abi::lookup(the_string) {
4716 Some(abi) => Some(abi),
4718 let last_span = self.last_span;
4721 format!("illegal ABI: expected one of [{}], \
4723 abi::all_names().connect(", "),
4724 the_string).as_slice());
4734 // parse one of the items or view items allowed by the
4735 // flags; on failure, return IoviNone.
4736 // NB: this function no longer parses the items inside an
4738 fn parse_item_or_view_item(&mut self,
4739 attrs: Vec<Attribute> ,
4740 macros_allowed: bool)
4743 INTERPOLATED(token::NtItem(item)) => {
4745 let new_attrs = attrs.append(item.attrs.as_slice());
4746 return IoviItem(box(GC) Item {
4754 let lo = self.span.lo;
4756 let visibility = self.parse_visibility();
4758 // must be a view item:
4759 if self.eat_keyword(keywords::Use) {
4760 // USE ITEM (IoviViewItem)
4761 let view_item = self.parse_use();
4762 self.expect(&token::SEMI);
4763 return IoviViewItem(ast::ViewItem {
4767 span: mk_sp(lo, self.last_span.hi)
4770 // either a view item or an item:
4771 if self.eat_keyword(keywords::Extern) {
4772 let next_is_mod = self.eat_keyword(keywords::Mod);
4774 if next_is_mod || self.eat_keyword(keywords::Crate) {
4776 let last_span = self.last_span;
4777 self.span_err(mk_sp(lo, last_span.hi),
4778 format!("`extern mod` is obsolete, use \
4779 `extern crate` instead \
4780 to refer to external \
4781 crates.").as_slice())
4783 return self.parse_item_extern_crate(lo, visibility, attrs);
4786 let opt_abi = self.parse_opt_abi();
4788 if self.eat_keyword(keywords::Fn) {
4789 // EXTERN FUNCTION ITEM
4790 let abi = opt_abi.unwrap_or(abi::C);
4791 let (ident, item_, extra_attrs) =
4792 self.parse_item_fn(NormalFn, abi);
4793 let last_span = self.last_span;
4794 let item = self.mk_item(lo,
4799 maybe_append(attrs, extra_attrs));
4800 return IoviItem(item);
4801 } else if self.token == token::LBRACE {
4802 return self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs);
4805 let span = self.span;
4806 let token_str = self.this_token_to_str();
4807 self.span_fatal(span,
4808 format!("expected `{}` or `fn` but found `{}`", "{",
4809 token_str).as_slice());
4812 let is_virtual = self.eat_keyword(keywords::Virtual);
4813 if is_virtual && !self.is_keyword(keywords::Struct) {
4814 let span = self.span;
4816 "`virtual` keyword may only be used with `struct`");
4819 // the rest are all guaranteed to be items:
4820 if self.is_keyword(keywords::Static) {
4823 let (ident, item_, extra_attrs) = self.parse_item_const();
4824 let last_span = self.last_span;
4825 let item = self.mk_item(lo,
4830 maybe_append(attrs, extra_attrs));
4831 return IoviItem(item);
4833 if self.is_keyword(keywords::Fn) &&
4834 self.look_ahead(1, |f| !Parser::fn_expr_lookahead(f)) {
4837 let (ident, item_, extra_attrs) =
4838 self.parse_item_fn(NormalFn, abi::Rust);
4839 let last_span = self.last_span;
4840 let item = self.mk_item(lo,
4845 maybe_append(attrs, extra_attrs));
4846 return IoviItem(item);
4848 if self.is_keyword(keywords::Unsafe)
4849 && self.look_ahead(1u, |t| *t != token::LBRACE) {
4850 // UNSAFE FUNCTION ITEM
4852 let abi = if self.eat_keyword(keywords::Extern) {
4853 self.parse_opt_abi().unwrap_or(abi::C)
4857 self.expect_keyword(keywords::Fn);
4858 let (ident, item_, extra_attrs) =
4859 self.parse_item_fn(UnsafeFn, abi);
4860 let last_span = self.last_span;
4861 let item = self.mk_item(lo,
4866 maybe_append(attrs, extra_attrs));
4867 return IoviItem(item);
4869 if self.eat_keyword(keywords::Mod) {
4871 let (ident, item_, extra_attrs) =
4872 self.parse_item_mod(attrs.as_slice());
4873 let last_span = self.last_span;
4874 let item = self.mk_item(lo,
4879 maybe_append(attrs, extra_attrs));
4880 return IoviItem(item);
4882 if self.eat_keyword(keywords::Type) {
4884 let (ident, item_, extra_attrs) = self.parse_item_type();
4885 let last_span = self.last_span;
4886 let item = self.mk_item(lo,
4891 maybe_append(attrs, extra_attrs));
4892 return IoviItem(item);
4894 if self.eat_keyword(keywords::Enum) {
4896 let (ident, item_, extra_attrs) = self.parse_item_enum();
4897 let last_span = self.last_span;
4898 let item = self.mk_item(lo,
4903 maybe_append(attrs, extra_attrs));
4904 return IoviItem(item);
4906 if self.eat_keyword(keywords::Trait) {
4908 let (ident, item_, extra_attrs) = self.parse_item_trait();
4909 let last_span = self.last_span;
4910 let item = self.mk_item(lo,
4915 maybe_append(attrs, extra_attrs));
4916 return IoviItem(item);
4918 if self.eat_keyword(keywords::Impl) {
4920 let (ident, item_, extra_attrs) = self.parse_item_impl();
4921 let last_span = self.last_span;
4922 let item = self.mk_item(lo,
4927 maybe_append(attrs, extra_attrs));
4928 return IoviItem(item);
4930 if self.eat_keyword(keywords::Struct) {
4932 let (ident, item_, extra_attrs) = self.parse_item_struct(is_virtual);
4933 let last_span = self.last_span;
4934 let item = self.mk_item(lo,
4939 maybe_append(attrs, extra_attrs));
4940 return IoviItem(item);
4942 self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility)
4945 // parse a foreign item; on failure, return IoviNone.
4946 fn parse_foreign_item(&mut self,
4947 attrs: Vec<Attribute> ,
4948 macros_allowed: bool)
4950 maybe_whole!(iovi self, NtItem);
4951 let lo = self.span.lo;
4953 let visibility = self.parse_visibility();
4955 if self.is_keyword(keywords::Static) {
4956 // FOREIGN STATIC ITEM
4957 let item = self.parse_item_foreign_static(visibility, attrs);
4958 return IoviForeignItem(item);
4960 if self.is_keyword(keywords::Fn) || self.is_keyword(keywords::Unsafe) {
4961 // FOREIGN FUNCTION ITEM
4962 let item = self.parse_item_foreign_fn(visibility, attrs);
4963 return IoviForeignItem(item);
4965 self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility)
4968 // this is the fall-through for parsing items.
4969 fn parse_macro_use_or_failure(
4971 attrs: Vec<Attribute> ,
4972 macros_allowed: bool,
4974 visibility: Visibility
4975 ) -> ItemOrViewItem {
4976 if macros_allowed && !token::is_any_keyword(&self.token)
4977 && self.look_ahead(1, |t| *t == token::NOT)
4978 && (self.look_ahead(2, |t| is_plain_ident(t))
4979 || self.look_ahead(2, |t| *t == token::LPAREN)
4980 || self.look_ahead(2, |t| *t == token::LBRACE)) {
4981 // MACRO INVOCATION ITEM
4984 let pth = self.parse_path(NoTypesAllowed).path;
4985 self.expect(&token::NOT);
4987 // a 'special' identifier (like what `macro_rules!` uses)
4988 // is optional. We should eventually unify invoc syntax
4990 let id = if is_plain_ident(&self.token) {
4993 token::special_idents::invalid // no special identifier
4995 // eat a matched-delimiter token tree:
4996 let tts = match token::close_delimiter_for(&self.token) {
4999 self.parse_seq_to_end(&ket,
5001 |p| p.parse_token_tree())
5003 None => self.fatal("expected open delimiter")
5005 // single-variant-enum... :
5006 let m = ast::MacInvocTT(pth, tts, EMPTY_CTXT);
5007 let m: ast::Mac = codemap::Spanned { node: m,
5008 span: mk_sp(self.span.lo,
5010 let item_ = ItemMac(m);
5011 let last_span = self.last_span;
5012 let item = self.mk_item(lo,
5018 return IoviItem(item);
5021 // FAILURE TO PARSE ITEM
5022 if visibility != Inherited {
5023 let mut s = String::from_str("unmatched visibility `");
5024 if visibility == Public {
5030 let last_span = self.last_span;
5031 self.span_fatal(last_span, s.as_slice());
5033 return IoviNone(attrs);
5036 pub fn parse_item_with_outer_attributes(&mut self) -> Option<Gc<Item>> {
5037 let attrs = self.parse_outer_attributes();
5038 self.parse_item(attrs)
5041 pub fn parse_item(&mut self, attrs: Vec<Attribute> ) -> Option<Gc<Item>> {
5042 match self.parse_item_or_view_item(attrs, true) {
5043 IoviNone(_) => None,
5045 self.fatal("view items are not allowed here"),
5046 IoviForeignItem(_) =>
5047 self.fatal("foreign items are not allowed here"),
5048 IoviItem(item) => Some(item)
5052 // parse, e.g., "use a::b::{z,y}"
5053 fn parse_use(&mut self) -> ViewItem_ {
5054 return ViewItemUse(self.parse_view_path());
5058 // matches view_path : MOD? IDENT EQ non_global_path
5059 // | MOD? non_global_path MOD_SEP LBRACE RBRACE
5060 // | MOD? non_global_path MOD_SEP LBRACE ident_seq RBRACE
5061 // | MOD? non_global_path MOD_SEP STAR
5062 // | MOD? non_global_path
5063 fn parse_view_path(&mut self) -> Gc<ViewPath> {
5064 let lo = self.span.lo;
5066 if self.token == token::LBRACE {
5068 let idents = self.parse_unspanned_seq(
5069 &token::LBRACE, &token::RBRACE,
5070 seq_sep_trailing_allowed(token::COMMA),
5071 |p| p.parse_path_list_ident());
5072 let path = ast::Path {
5073 span: mk_sp(lo, self.span.hi),
5075 segments: Vec::new()
5077 return box(GC) spanned(lo, self.span.hi,
5078 ViewPathList(path, idents, ast::DUMMY_NODE_ID));
5081 let first_ident = self.parse_ident();
5082 let mut path = vec!(first_ident);
5087 let path_lo = self.span.lo;
5088 path = vec!(self.parse_ident());
5089 while self.token == token::MOD_SEP {
5091 let id = self.parse_ident();
5094 let path = ast::Path {
5095 span: mk_sp(path_lo, self.span.hi),
5097 segments: path.move_iter().map(|identifier| {
5099 identifier: identifier,
5100 lifetimes: Vec::new(),
5101 types: OwnedSlice::empty(),
5105 return box(GC) spanned(lo, self.span.hi,
5106 ViewPathSimple(first_ident, path,
5107 ast::DUMMY_NODE_ID));
5111 // foo::bar or foo::{a,b,c} or foo::*
5112 while self.token == token::MOD_SEP {
5116 token::IDENT(i, _) => {
5121 // foo::bar::{a,b,c}
5123 let idents = self.parse_unspanned_seq(
5126 seq_sep_trailing_allowed(token::COMMA),
5127 |p| p.parse_path_list_ident()
5129 let path = ast::Path {
5130 span: mk_sp(lo, self.span.hi),
5132 segments: path.move_iter().map(|identifier| {
5134 identifier: identifier,
5135 lifetimes: Vec::new(),
5136 types: OwnedSlice::empty(),
5140 return box(GC) spanned(lo, self.span.hi,
5141 ViewPathList(path, idents, ast::DUMMY_NODE_ID));
5145 token::BINOP(token::STAR) => {
5147 let path = ast::Path {
5148 span: mk_sp(lo, self.span.hi),
5150 segments: path.move_iter().map(|identifier| {
5152 identifier: identifier,
5153 lifetimes: Vec::new(),
5154 types: OwnedSlice::empty(),
5158 return box(GC) spanned(lo, self.span.hi,
5159 ViewPathGlob(path, ast::DUMMY_NODE_ID));
5168 let last = *path.get(path.len() - 1u);
5169 let path = ast::Path {
5170 span: mk_sp(lo, self.span.hi),
5172 segments: path.move_iter().map(|identifier| {
5174 identifier: identifier,
5175 lifetimes: Vec::new(),
5176 types: OwnedSlice::empty(),
5180 return box(GC) spanned(lo,
5182 ViewPathSimple(last, path, ast::DUMMY_NODE_ID));
5185 // Parses a sequence of items. Stops when it finds program
5186 // text that can't be parsed as an item
5187 // - mod_items uses extern_mod_allowed = true
5188 // - block_tail_ uses extern_mod_allowed = false
5189 fn parse_items_and_view_items(&mut self,
5190 first_item_attrs: Vec<Attribute> ,
5191 mut extern_mod_allowed: bool,
5192 macros_allowed: bool)
5193 -> ParsedItemsAndViewItems {
5194 let mut attrs = first_item_attrs.append(self.parse_outer_attributes().as_slice());
5195 // First, parse view items.
5196 let mut view_items : Vec<ast::ViewItem> = Vec::new();
5197 let mut items = Vec::new();
5199 // I think this code would probably read better as a single
5200 // loop with a mutable three-state-variable (for extern crates,
5201 // view items, and regular items) ... except that because
5202 // of macros, I'd like to delay that entire check until later.
5204 match self.parse_item_or_view_item(attrs, macros_allowed) {
5205 IoviNone(attrs) => {
5206 return ParsedItemsAndViewItems {
5207 attrs_remaining: attrs,
5208 view_items: view_items,
5210 foreign_items: Vec::new()
5213 IoviViewItem(view_item) => {
5214 match view_item.node {
5215 ViewItemUse(..) => {
5216 // `extern crate` must precede `use`.
5217 extern_mod_allowed = false;
5219 ViewItemExternCrate(..) if !extern_mod_allowed => {
5220 self.span_err(view_item.span,
5221 "\"extern crate\" declarations are \
5224 ViewItemExternCrate(..) => {}
5226 view_items.push(view_item);
5230 attrs = self.parse_outer_attributes();
5233 IoviForeignItem(_) => {
5237 attrs = self.parse_outer_attributes();
5240 // Next, parse items.
5242 match self.parse_item_or_view_item(attrs, macros_allowed) {
5243 IoviNone(returned_attrs) => {
5244 attrs = returned_attrs;
5247 IoviViewItem(view_item) => {
5248 attrs = self.parse_outer_attributes();
5249 self.span_err(view_item.span,
5250 "`use` and `extern crate` declarations must precede items");
5253 attrs = self.parse_outer_attributes();
5256 IoviForeignItem(_) => {
5262 ParsedItemsAndViewItems {
5263 attrs_remaining: attrs,
5264 view_items: view_items,
5266 foreign_items: Vec::new()
5270 // Parses a sequence of foreign items. Stops when it finds program
5271 // text that can't be parsed as an item
5272 fn parse_foreign_items(&mut self, first_item_attrs: Vec<Attribute> ,
5273 macros_allowed: bool)
5274 -> ParsedItemsAndViewItems {
5275 let mut attrs = first_item_attrs.append(self.parse_outer_attributes().as_slice());
5276 let mut foreign_items = Vec::new();
5278 match self.parse_foreign_item(attrs, macros_allowed) {
5279 IoviNone(returned_attrs) => {
5280 if self.token == token::RBRACE {
5281 attrs = returned_attrs;
5286 IoviViewItem(view_item) => {
5287 // I think this can't occur:
5288 self.span_err(view_item.span,
5289 "`use` and `extern crate` declarations must precede items");
5292 // FIXME #5668: this will occur for a macro invocation:
5293 self.span_fatal(item.span, "macros cannot expand to foreign items");
5295 IoviForeignItem(foreign_item) => {
5296 foreign_items.push(foreign_item);
5299 attrs = self.parse_outer_attributes();
5302 ParsedItemsAndViewItems {
5303 attrs_remaining: attrs,
5304 view_items: Vec::new(),
5306 foreign_items: foreign_items
5310 // Parses a source module as a crate. This is the main
5311 // entry point for the parser.
5312 pub fn parse_crate_mod(&mut self) -> Crate {
5313 let lo = self.span.lo;
5314 // parse the crate's inner attrs, maybe (oops) one
5315 // of the attrs of an item:
5316 let (inner, next) = self.parse_inner_attrs_and_next();
5317 let first_item_outer_attrs = next;
5318 // parse the items inside the crate:
5319 let m = self.parse_mod_items(token::EOF, first_item_outer_attrs, lo);
5324 config: self.cfg.clone(),
5325 span: mk_sp(lo, self.span.lo)
5329 pub fn parse_optional_str(&mut self)
5330 -> Option<(InternedString, ast::StrStyle)> {
5331 let (s, style) = match self.token {
5332 token::LIT_STR(s) => (self.id_to_interned_str(s), ast::CookedStr),
5333 token::LIT_STR_RAW(s, n) => {
5334 (self.id_to_interned_str(s), ast::RawStr(n))
5342 pub fn parse_str(&mut self) -> (InternedString, StrStyle) {
5343 match self.parse_optional_str() {
5345 _ => self.fatal("expected string literal")