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, 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 // NOTE: after a stage0 snap this should turn into a span_err.
1454 let t = self.parse_ty(true);
1455 MutTy { ty: t, mutbl: mutbl }
1458 pub fn is_named_argument(&mut self) -> bool {
1459 let offset = match self.token {
1460 token::BINOP(token::AND) => 1,
1462 _ if token::is_keyword(keywords::Mut, &self.token) => 1,
1466 debug!("parser is_named_argument offset:{}", offset);
1469 is_plain_ident_or_underscore(&self.token)
1470 && self.look_ahead(1, |t| *t == token::COLON)
1472 self.look_ahead(offset, |t| is_plain_ident_or_underscore(t))
1473 && self.look_ahead(offset + 1, |t| *t == token::COLON)
1477 // This version of parse arg doesn't necessarily require
1478 // identifier names.
1479 pub fn parse_arg_general(&mut self, require_name: bool) -> Arg {
1480 let pat = if require_name || self.is_named_argument() {
1481 debug!("parse_arg_general parse_pat (require_name:{:?})",
1483 let pat = self.parse_pat();
1485 self.expect(&token::COLON);
1488 debug!("parse_arg_general ident_to_pat");
1489 ast_util::ident_to_pat(ast::DUMMY_NODE_ID,
1491 special_idents::invalid)
1494 let t = self.parse_ty(true);
1499 id: ast::DUMMY_NODE_ID,
1503 // parse a single function argument
1504 pub fn parse_arg(&mut self) -> Arg {
1505 self.parse_arg_general(true)
1508 // parse an argument in a lambda header e.g. |arg, arg|
1509 pub fn parse_fn_block_arg(&mut self) -> Arg {
1510 let pat = self.parse_pat();
1511 let t = if self.eat(&token::COLON) {
1515 id: ast::DUMMY_NODE_ID,
1517 span: mk_sp(self.span.lo, self.span.hi),
1523 id: ast::DUMMY_NODE_ID
1527 pub fn maybe_parse_fixed_vstore(&mut self) -> Option<Gc<ast::Expr>> {
1528 if self.token == token::COMMA &&
1529 self.look_ahead(1, |t| *t == token::DOTDOT) {
1532 Some(self.parse_expr())
1538 // matches token_lit = LIT_INT | ...
1539 pub fn lit_from_token(&mut self, tok: &token::Token) -> Lit_ {
1541 token::LIT_BYTE(i) => LitByte(i),
1542 token::LIT_CHAR(i) => LitChar(i),
1543 token::LIT_INT(i, it) => LitInt(i, it),
1544 token::LIT_UINT(u, ut) => LitUint(u, ut),
1545 token::LIT_INT_UNSUFFIXED(i) => LitIntUnsuffixed(i),
1546 token::LIT_FLOAT(s, ft) => {
1547 LitFloat(self.id_to_interned_str(s), ft)
1549 token::LIT_FLOAT_UNSUFFIXED(s) => {
1550 LitFloatUnsuffixed(self.id_to_interned_str(s))
1552 token::LIT_STR(s) => {
1553 LitStr(self.id_to_interned_str(s), ast::CookedStr)
1555 token::LIT_STR_RAW(s, n) => {
1556 LitStr(self.id_to_interned_str(s), ast::RawStr(n))
1558 token::LIT_BINARY_RAW(ref v, _) |
1559 token::LIT_BINARY(ref v) => LitBinary(v.clone()),
1560 token::LPAREN => { self.expect(&token::RPAREN); LitNil },
1561 _ => { self.unexpected_last(tok); }
1565 // matches lit = true | false | token_lit
1566 pub fn parse_lit(&mut self) -> Lit {
1567 let lo = self.span.lo;
1568 let lit = if self.eat_keyword(keywords::True) {
1570 } else if self.eat_keyword(keywords::False) {
1573 let token = self.bump_and_get();
1574 let lit = self.lit_from_token(&token);
1577 codemap::Spanned { node: lit, span: mk_sp(lo, self.last_span.hi) }
1580 // matches '-' lit | lit
1581 pub fn parse_literal_maybe_minus(&mut self) -> Gc<Expr> {
1582 let minus_lo = self.span.lo;
1583 let minus_present = self.eat(&token::BINOP(token::MINUS));
1585 let lo = self.span.lo;
1586 let literal = box(GC) self.parse_lit();
1587 let hi = self.span.hi;
1588 let expr = self.mk_expr(lo, hi, ExprLit(literal));
1591 let minus_hi = self.span.hi;
1592 let unary = self.mk_unary(UnNeg, expr);
1593 self.mk_expr(minus_lo, minus_hi, unary)
1599 /// Parses a path and optional type parameter bounds, depending on the
1600 /// mode. The `mode` parameter determines whether lifetimes, types, and/or
1601 /// bounds are permitted and whether `::` must precede type parameter
1603 pub fn parse_path(&mut self, mode: PathParsingMode) -> PathAndBounds {
1604 // Check for a whole path...
1605 let found = match self.token {
1606 INTERPOLATED(token::NtPath(_)) => Some(self.bump_and_get()),
1610 Some(INTERPOLATED(token::NtPath(box path))) => {
1611 return PathAndBounds {
1619 let lo = self.span.lo;
1620 let is_global = self.eat(&token::MOD_SEP);
1622 // Parse any number of segments and bound sets. A segment is an
1623 // identifier followed by an optional lifetime and a set of types.
1624 // A bound set is a set of type parameter bounds.
1625 let mut segments = Vec::new();
1627 // First, parse an identifier.
1628 let identifier = self.parse_ident();
1630 // Parse the '::' before type parameters if it's required. If
1631 // it is required and wasn't present, then we're done.
1632 if mode == LifetimeAndTypesWithColons &&
1633 !self.eat(&token::MOD_SEP) {
1634 segments.push(ast::PathSegment {
1635 identifier: identifier,
1636 lifetimes: Vec::new(),
1637 types: OwnedSlice::empty(),
1642 // Parse the `<` before the lifetime and types, if applicable.
1643 let (any_lifetime_or_types, lifetimes, types) = {
1644 if mode != NoTypesAllowed && self.eat_lt(false) {
1645 let (lifetimes, types) =
1646 self.parse_generic_values_after_lt();
1647 (true, lifetimes, OwnedSlice::from_vec(types))
1649 (false, Vec::new(), OwnedSlice::empty())
1653 // Assemble and push the result.
1654 segments.push(ast::PathSegment {
1655 identifier: identifier,
1656 lifetimes: lifetimes,
1660 // We're done if we don't see a '::', unless the mode required
1661 // a double colon to get here in the first place.
1662 if !(mode == LifetimeAndTypesWithColons &&
1663 !any_lifetime_or_types) {
1664 if !self.eat(&token::MOD_SEP) {
1670 // Next, parse a plus and bounded type parameters, if applicable.
1671 let bounds = if mode == LifetimeAndTypesAndBounds {
1673 if self.eat(&token::BINOP(token::PLUS)) {
1674 let (_, bounds) = self.parse_ty_param_bounds(false);
1675 if bounds.len() == 0 {
1676 let last_span = self.last_span;
1677 self.span_err(last_span,
1678 "at least one type parameter bound \
1679 must be specified after the `+`");
1691 // Assemble the span.
1692 let span = mk_sp(lo, self.last_span.hi);
1694 // Assemble the result.
1705 /// parses 0 or 1 lifetime
1706 pub fn parse_opt_lifetime(&mut self) -> Option<ast::Lifetime> {
1708 token::LIFETIME(..) => {
1709 Some(self.parse_lifetime())
1717 /// Parses a single lifetime
1718 // matches lifetime = LIFETIME
1719 pub fn parse_lifetime(&mut self) -> ast::Lifetime {
1721 token::LIFETIME(i) => {
1722 let span = self.span;
1724 return ast::Lifetime {
1725 id: ast::DUMMY_NODE_ID,
1731 self.fatal(format!("expected a lifetime name").as_slice());
1736 // matches lifetimes = ( lifetime ) | ( lifetime , lifetimes )
1737 // actually, it matches the empty one too, but putting that in there
1738 // messes up the grammar....
1739 pub fn parse_lifetimes(&mut self) -> Vec<ast::Lifetime> {
1742 * Parses zero or more comma separated lifetimes.
1743 * Expects each lifetime to be followed by either
1744 * a comma or `>`. Used when parsing type parameter
1745 * lists, where we expect something like `<'a, 'b, T>`.
1748 let mut res = Vec::new();
1751 token::LIFETIME(_) => {
1752 res.push(self.parse_lifetime());
1760 token::COMMA => { self.bump();}
1761 token::GT => { return res; }
1762 token::BINOP(token::SHR) => { return res; }
1764 let msg = format!("expected `,` or `>` after lifetime \
1767 self.fatal(msg.as_slice());
1773 pub fn token_is_mutability(tok: &token::Token) -> bool {
1774 token::is_keyword(keywords::Mut, tok) ||
1775 token::is_keyword(keywords::Const, tok)
1778 // parse mutability declaration (mut/const/imm)
1779 pub fn parse_mutability(&mut self) -> Mutability {
1780 if self.eat_keyword(keywords::Mut) {
1787 // parse ident COLON expr
1788 pub fn parse_field(&mut self) -> Field {
1789 let lo = self.span.lo;
1790 let i = self.parse_ident();
1791 let hi = self.last_span.hi;
1792 self.expect(&token::COLON);
1793 let e = self.parse_expr();
1795 ident: spanned(lo, hi, i),
1797 span: mk_sp(lo, e.span.hi),
1801 pub fn mk_expr(&mut self, lo: BytePos, hi: BytePos, node: Expr_) -> Gc<Expr> {
1803 id: ast::DUMMY_NODE_ID,
1805 span: mk_sp(lo, hi),
1809 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: Gc<Expr>) -> ast::Expr_ {
1810 ExprUnary(unop, expr)
1813 pub fn mk_binary(&mut self, binop: ast::BinOp,
1814 lhs: Gc<Expr>, rhs: Gc<Expr>) -> ast::Expr_ {
1815 ExprBinary(binop, lhs, rhs)
1818 pub fn mk_call(&mut self, f: Gc<Expr>, args: Vec<Gc<Expr>>) -> ast::Expr_ {
1822 fn mk_method_call(&mut self,
1823 ident: ast::SpannedIdent,
1825 args: Vec<Gc<Expr>>)
1827 ExprMethodCall(ident, tps, args)
1830 pub fn mk_index(&mut self, expr: Gc<Expr>, idx: Gc<Expr>) -> ast::Expr_ {
1831 ExprIndex(expr, idx)
1834 pub fn mk_field(&mut self, expr: Gc<Expr>, ident: ast::SpannedIdent,
1835 tys: Vec<P<Ty>>) -> ast::Expr_ {
1836 ExprField(expr, ident, tys)
1839 pub fn mk_assign_op(&mut self, binop: ast::BinOp,
1840 lhs: Gc<Expr>, rhs: Gc<Expr>) -> ast::Expr_ {
1841 ExprAssignOp(binop, lhs, rhs)
1844 pub fn mk_mac_expr(&mut self, lo: BytePos, hi: BytePos, m: Mac_) -> Gc<Expr> {
1846 id: ast::DUMMY_NODE_ID,
1847 node: ExprMac(codemap::Spanned {node: m, span: mk_sp(lo, hi)}),
1848 span: mk_sp(lo, hi),
1852 pub fn mk_lit_u32(&mut self, i: u32) -> Gc<Expr> {
1853 let span = &self.span;
1854 let lv_lit = box(GC) codemap::Spanned {
1855 node: LitUint(i as u64, TyU32),
1860 id: ast::DUMMY_NODE_ID,
1861 node: ExprLit(lv_lit),
1866 // at the bottom (top?) of the precedence hierarchy,
1867 // parse things like parenthesized exprs,
1868 // macros, return, etc.
1869 pub fn parse_bottom_expr(&mut self) -> Gc<Expr> {
1870 maybe_whole_expr!(self);
1872 let lo = self.span.lo;
1873 let mut hi = self.span.hi;
1877 if self.token == token::LPAREN {
1879 // (e) is parenthesized e
1880 // (e,) is a tuple with only one field, e
1881 let mut trailing_comma = false;
1882 if self.token == token::RPAREN {
1885 let lit = box(GC) spanned(lo, hi, LitNil);
1886 return self.mk_expr(lo, hi, ExprLit(lit));
1888 let mut es = vec!(self.parse_expr());
1889 self.commit_expr(*es.last().unwrap(), &[], &[token::COMMA, token::RPAREN]);
1890 while self.token == token::COMMA {
1892 if self.token != token::RPAREN {
1893 es.push(self.parse_expr());
1894 self.commit_expr(*es.last().unwrap(), &[], &[token::COMMA, token::RPAREN]);
1897 trailing_comma = true;
1901 self.commit_expr_expecting(*es.last().unwrap(), token::RPAREN);
1903 return if es.len() == 1 && !trailing_comma {
1904 self.mk_expr(lo, hi, ExprParen(*es.get(0)))
1907 self.mk_expr(lo, hi, ExprTup(es))
1909 } else if self.token == token::LBRACE {
1911 let blk = self.parse_block_tail(lo, DefaultBlock);
1912 return self.mk_expr(blk.span.lo, blk.span.hi,
1914 } else if token::is_bar(&self.token) {
1915 return self.parse_lambda_expr();
1916 } else if self.eat_keyword(keywords::Proc) {
1917 let decl = self.parse_proc_decl();
1918 let body = self.parse_expr();
1919 let fakeblock = P(ast::Block {
1920 view_items: Vec::new(),
1923 id: ast::DUMMY_NODE_ID,
1924 rules: DefaultBlock,
1928 return self.mk_expr(lo, body.span.hi, ExprProc(decl, fakeblock));
1929 } else if self.eat_keyword(keywords::Self) {
1930 let path = ast_util::ident_to_path(mk_sp(lo, hi), special_idents::self_);
1931 ex = ExprPath(path);
1932 hi = self.last_span.hi;
1933 } else if self.eat_keyword(keywords::If) {
1934 return self.parse_if_expr();
1935 } else if self.eat_keyword(keywords::For) {
1936 return self.parse_for_expr(None);
1937 } else if self.eat_keyword(keywords::While) {
1938 return self.parse_while_expr();
1939 } else if Parser::token_is_lifetime(&self.token) {
1940 let lifetime = self.get_lifetime();
1942 self.expect(&token::COLON);
1943 if self.eat_keyword(keywords::For) {
1944 return self.parse_for_expr(Some(lifetime))
1945 } else if self.eat_keyword(keywords::Loop) {
1946 return self.parse_loop_expr(Some(lifetime))
1948 self.fatal("expected `for` or `loop` after a label")
1950 } else if self.eat_keyword(keywords::Loop) {
1951 return self.parse_loop_expr(None);
1952 } else if self.eat_keyword(keywords::Continue) {
1953 let lo = self.span.lo;
1954 let ex = if Parser::token_is_lifetime(&self.token) {
1955 let lifetime = self.get_lifetime();
1957 ExprAgain(Some(lifetime))
1961 let hi = self.span.hi;
1962 return self.mk_expr(lo, hi, ex);
1963 } else if self.eat_keyword(keywords::Match) {
1964 return self.parse_match_expr();
1965 } else if self.eat_keyword(keywords::Unsafe) {
1966 return self.parse_block_expr(lo, UnsafeBlock(ast::UserProvided));
1967 } else if self.token == token::LBRACKET {
1970 if self.token == token::RBRACKET {
1973 ex = ExprVec(Vec::new());
1976 let first_expr = self.parse_expr();
1977 if self.token == token::COMMA &&
1978 self.look_ahead(1, |t| *t == token::DOTDOT) {
1979 // Repeating vector syntax: [ 0, ..512 ]
1982 let count = self.parse_expr();
1983 self.expect(&token::RBRACKET);
1984 ex = ExprRepeat(first_expr, count);
1985 } else if self.token == token::COMMA {
1986 // Vector with two or more elements.
1988 let remaining_exprs = self.parse_seq_to_end(
1990 seq_sep_trailing_allowed(token::COMMA),
1993 let mut exprs = vec!(first_expr);
1994 exprs.push_all_move(remaining_exprs);
1995 ex = ExprVec(exprs);
1997 // Vector with one element.
1998 self.expect(&token::RBRACKET);
1999 ex = ExprVec(vec!(first_expr));
2002 hi = self.last_span.hi;
2003 } else if self.eat_keyword(keywords::Return) {
2004 // RETURN expression
2005 if can_begin_expr(&self.token) {
2006 let e = self.parse_expr();
2008 ex = ExprRet(Some(e));
2009 } else { ex = ExprRet(None); }
2010 } else if self.eat_keyword(keywords::Break) {
2012 if Parser::token_is_lifetime(&self.token) {
2013 let lifetime = self.get_lifetime();
2015 ex = ExprBreak(Some(lifetime));
2017 ex = ExprBreak(None);
2020 } else if self.token == token::MOD_SEP ||
2021 is_ident(&self.token) && !self.is_keyword(keywords::True) &&
2022 !self.is_keyword(keywords::False) {
2023 let pth = self.parse_path(LifetimeAndTypesWithColons).path;
2025 // `!`, as an operator, is prefix, so we know this isn't that
2026 if self.token == token::NOT {
2027 // MACRO INVOCATION expression
2030 let ket = token::close_delimiter_for(&self.token)
2031 .unwrap_or_else(|| self.fatal("expected open delimiter"));
2034 let tts = self.parse_seq_to_end(&ket,
2036 |p| p.parse_token_tree());
2037 let hi = self.span.hi;
2039 return self.mk_mac_expr(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT));
2040 } else if self.token == token::LBRACE {
2041 // This is a struct literal, unless we're prohibited from
2042 // parsing struct literals here.
2043 if self.restriction != RESTRICT_NO_STRUCT_LITERAL {
2044 // It's a struct literal.
2046 let mut fields = Vec::new();
2047 let mut base = None;
2049 while self.token != token::RBRACE {
2050 if self.eat(&token::DOTDOT) {
2051 base = Some(self.parse_expr());
2055 fields.push(self.parse_field());
2056 self.commit_expr(fields.last().unwrap().expr,
2057 &[token::COMMA], &[token::RBRACE]);
2060 if fields.len() == 0 && base.is_none() {
2061 let last_span = self.last_span;
2062 self.span_err(last_span,
2063 "structure literal must either have at \
2064 least one field or use functional \
2065 structure update syntax");
2069 self.expect(&token::RBRACE);
2070 ex = ExprStruct(pth, fields, base);
2071 return self.mk_expr(lo, hi, ex);
2078 // other literal expression
2079 let lit = self.parse_lit();
2081 ex = ExprLit(box(GC) lit);
2084 return self.mk_expr(lo, hi, ex);
2087 // parse a block or unsafe block
2088 pub fn parse_block_expr(&mut self, lo: BytePos, blk_mode: BlockCheckMode)
2090 self.expect(&token::LBRACE);
2091 let blk = self.parse_block_tail(lo, blk_mode);
2092 return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk));
2095 // parse a.b or a(13) or a[4] or just a
2096 pub fn parse_dot_or_call_expr(&mut self) -> Gc<Expr> {
2097 let b = self.parse_bottom_expr();
2098 self.parse_dot_or_call_expr_with(b)
2101 pub fn parse_dot_or_call_expr_with(&mut self, e0: Gc<Expr>) -> Gc<Expr> {
2107 if self.eat(&token::DOT) {
2109 token::IDENT(i, _) => {
2110 let dot = self.last_span.hi;
2113 let (_, tys) = if self.eat(&token::MOD_SEP) {
2115 self.parse_generic_values_after_lt()
2117 (Vec::new(), Vec::new())
2120 // expr.f() method call
2123 let mut es = self.parse_unspanned_seq(
2126 seq_sep_trailing_disallowed(token::COMMA),
2129 hi = self.last_span.hi;
2132 let id = spanned(dot, hi, i);
2133 let nd = self.mk_method_call(id, tys, es);
2134 e = self.mk_expr(lo, hi, nd);
2137 let id = spanned(dot, hi, i);
2138 let field = self.mk_field(e, id, tys);
2139 e = self.mk_expr(lo, hi, field)
2143 _ => self.unexpected()
2147 if self.expr_is_complete(e) { break; }
2151 let es = self.parse_unspanned_seq(
2154 seq_sep_trailing_allowed(token::COMMA),
2157 hi = self.last_span.hi;
2159 let nd = self.mk_call(e, es);
2160 e = self.mk_expr(lo, hi, nd);
2164 token::LBRACKET => {
2166 let ix = self.parse_expr();
2168 self.commit_expr_expecting(ix, token::RBRACKET);
2169 let index = self.mk_index(e, ix);
2170 e = self.mk_expr(lo, hi, index)
2179 // parse an optional separator followed by a kleene-style
2180 // repetition token (+ or *).
2181 pub fn parse_sep_and_zerok(&mut self) -> (Option<token::Token>, bool) {
2182 fn parse_zerok(parser: &mut Parser) -> Option<bool> {
2183 match parser.token {
2184 token::BINOP(token::STAR) | token::BINOP(token::PLUS) => {
2185 let zerok = parser.token == token::BINOP(token::STAR);
2193 match parse_zerok(self) {
2194 Some(zerok) => return (None, zerok),
2198 let separator = self.bump_and_get();
2199 match parse_zerok(self) {
2200 Some(zerok) => (Some(separator), zerok),
2201 None => self.fatal("expected `*` or `+`")
2205 // parse a single token tree from the input.
2206 pub fn parse_token_tree(&mut self) -> TokenTree {
2207 // FIXME #6994: currently, this is too eager. It
2208 // parses token trees but also identifies TTSeq's
2209 // and TTNonterminal's; it's too early to know yet
2210 // whether something will be a nonterminal or a seq
2212 maybe_whole!(deref self, NtTT);
2214 // this is the fall-through for the 'match' below.
2215 // invariants: the current token is not a left-delimiter,
2216 // not an EOF, and not the desired right-delimiter (if
2217 // it were, parse_seq_to_before_end would have prevented
2218 // reaching this point.
2219 fn parse_non_delim_tt_tok(p: &mut Parser) -> TokenTree {
2220 maybe_whole!(deref p, NtTT);
2222 token::RPAREN | token::RBRACE | token::RBRACKET => {
2223 // This is a conservative error: only report the last unclosed delimiter. The
2224 // previous unclosed delimiters could actually be closed! The parser just hasn't
2225 // gotten to them yet.
2226 match p.open_braces.last() {
2228 Some(&sp) => p.span_note(sp, "unclosed delimiter"),
2230 let token_str = p.this_token_to_str();
2231 p.fatal(format!("incorrect close delimiter: `{}`",
2232 token_str).as_slice())
2234 /* we ought to allow different depths of unquotation */
2235 token::DOLLAR if p.quote_depth > 0u => {
2239 if p.token == token::LPAREN {
2240 let seq = p.parse_seq(
2244 |p| p.parse_token_tree()
2246 let (s, z) = p.parse_sep_and_zerok();
2247 let seq = match seq {
2248 Spanned { node, .. } => node,
2250 TTSeq(mk_sp(sp.lo, p.span.hi), Rc::new(seq), s, z)
2252 TTNonterminal(sp, p.parse_ident())
2261 // turn the next token into a TTTok:
2262 fn parse_any_tt_tok(p: &mut Parser) -> TokenTree {
2263 TTTok(p.span, p.bump_and_get())
2266 match (&self.token, token::close_delimiter_for(&self.token)) {
2267 (&token::EOF, _) => {
2268 let open_braces = self.open_braces.clone();
2269 for sp in open_braces.iter() {
2270 self.span_note(*sp, "Did you mean to close this delimiter?");
2272 // There shouldn't really be a span, but it's easier for the test runner
2273 // if we give it one
2274 self.fatal("this file contains an un-closed delimiter ");
2276 (_, Some(close_delim)) => {
2277 // Parse the open delimiter.
2278 self.open_braces.push(self.span);
2279 let mut result = vec!(parse_any_tt_tok(self));
2282 self.parse_seq_to_before_end(&close_delim,
2284 |p| p.parse_token_tree());
2285 result.push_all_move(trees);
2287 // Parse the close delimiter.
2288 result.push(parse_any_tt_tok(self));
2289 self.open_braces.pop().unwrap();
2291 TTDelim(Rc::new(result))
2293 _ => parse_non_delim_tt_tok(self)
2297 // parse a stream of tokens into a list of TokenTree's,
2299 pub fn parse_all_token_trees(&mut self) -> Vec<TokenTree> {
2300 let mut tts = Vec::new();
2301 while self.token != token::EOF {
2302 tts.push(self.parse_token_tree());
2307 pub fn parse_matchers(&mut self) -> Vec<Matcher> {
2308 // unification of Matcher's and TokenTree's would vastly improve
2309 // the interpolation of Matcher's
2310 maybe_whole!(self, NtMatchers);
2311 let mut name_idx = 0u;
2312 match token::close_delimiter_for(&self.token) {
2313 Some(other_delimiter) => {
2315 self.parse_matcher_subseq_upto(&mut name_idx, &other_delimiter)
2317 None => self.fatal("expected open delimiter")
2321 // This goofy function is necessary to correctly match parens in Matcher's.
2322 // Otherwise, `$( ( )` would be a valid Matcher, and `$( () )` would be
2323 // invalid. It's similar to common::parse_seq.
2324 pub fn parse_matcher_subseq_upto(&mut self,
2325 name_idx: &mut uint,
2328 let mut ret_val = Vec::new();
2329 let mut lparens = 0u;
2331 while self.token != *ket || lparens > 0u {
2332 if self.token == token::LPAREN { lparens += 1u; }
2333 if self.token == token::RPAREN { lparens -= 1u; }
2334 ret_val.push(self.parse_matcher(name_idx));
2342 pub fn parse_matcher(&mut self, name_idx: &mut uint) -> Matcher {
2343 let lo = self.span.lo;
2345 let m = if self.token == token::DOLLAR {
2347 if self.token == token::LPAREN {
2348 let name_idx_lo = *name_idx;
2350 let ms = self.parse_matcher_subseq_upto(name_idx,
2353 self.fatal("repetition body must be nonempty");
2355 let (sep, zerok) = self.parse_sep_and_zerok();
2356 MatchSeq(ms, sep, zerok, name_idx_lo, *name_idx)
2358 let bound_to = self.parse_ident();
2359 self.expect(&token::COLON);
2360 let nt_name = self.parse_ident();
2361 let m = MatchNonterminal(bound_to, nt_name, *name_idx);
2366 MatchTok(self.bump_and_get())
2369 return spanned(lo, self.span.hi, m);
2372 // parse a prefix-operator expr
2373 pub fn parse_prefix_expr(&mut self) -> Gc<Expr> {
2374 let lo = self.span.lo;
2381 let e = self.parse_prefix_expr();
2383 ex = self.mk_unary(UnNot, e);
2385 token::BINOP(token::MINUS) => {
2387 let e = self.parse_prefix_expr();
2389 ex = self.mk_unary(UnNeg, e);
2391 token::BINOP(token::STAR) => {
2393 let e = self.parse_prefix_expr();
2395 ex = self.mk_unary(UnDeref, e);
2397 token::BINOP(token::AND) | token::ANDAND => {
2399 let _lt = self.parse_opt_lifetime();
2400 let m = self.parse_mutability();
2401 let e = self.parse_prefix_expr();
2403 // HACK: turn &[...] into a &-vec
2405 ExprVec(..) if m == MutImmutable => {
2406 ExprVstore(e, ExprVstoreSlice)
2408 ExprVec(..) if m == MutMutable => {
2409 ExprVstore(e, ExprVstoreMutSlice)
2411 _ => ExprAddrOf(m, e)
2416 let span = self.last_span;
2417 self.obsolete(span, ObsoleteManagedExpr);
2418 let e = self.parse_prefix_expr();
2420 ex = self.mk_unary(UnBox, e);
2425 let e = self.parse_prefix_expr();
2427 // HACK: turn ~[...] into a ~-vec
2428 let last_span = self.last_span;
2430 ExprVec(..) | ExprRepeat(..) => {
2431 self.obsolete(last_span, ObsoleteOwnedVector);
2432 ExprVstore(e, ExprVstoreUniq)
2434 ExprLit(lit) if lit_is_str(lit) => {
2435 self.obsolete(last_span, ObsoleteOwnedExpr);
2436 ExprVstore(e, ExprVstoreUniq)
2439 self.obsolete(last_span, ObsoleteOwnedExpr);
2440 self.mk_unary(UnUniq, e)
2444 token::IDENT(_, _) if self.is_keyword(keywords::Box) => {
2447 // Check for a place: `box(PLACE) EXPR`.
2448 if self.eat(&token::LPAREN) {
2449 // Support `box() EXPR` as the default.
2450 if !self.eat(&token::RPAREN) {
2451 let place = self.parse_expr();
2452 self.expect(&token::RPAREN);
2453 let subexpression = self.parse_prefix_expr();
2454 hi = subexpression.span.hi;
2455 ex = ExprBox(place, subexpression);
2456 return self.mk_expr(lo, hi, ex);
2460 // Otherwise, we use the unique pointer default.
2461 let subexpression = self.parse_prefix_expr();
2462 hi = subexpression.span.hi;
2463 // HACK: turn `box [...]` into a boxed-vec
2464 ex = match subexpression.node {
2465 ExprVec(..) | ExprRepeat(..) => {
2466 let last_span = self.last_span;
2467 self.obsolete(last_span, ObsoleteOwnedVector);
2468 ExprVstore(subexpression, ExprVstoreUniq)
2470 ExprLit(lit) if lit_is_str(lit) => {
2471 ExprVstore(subexpression, ExprVstoreUniq)
2473 _ => self.mk_unary(UnUniq, subexpression)
2476 _ => return self.parse_dot_or_call_expr()
2478 return self.mk_expr(lo, hi, ex);
2481 // parse an expression of binops
2482 pub fn parse_binops(&mut self) -> Gc<Expr> {
2483 let prefix_expr = self.parse_prefix_expr();
2484 self.parse_more_binops(prefix_expr, 0)
2487 // parse an expression of binops of at least min_prec precedence
2488 pub fn parse_more_binops(&mut self, lhs: Gc<Expr>,
2489 min_prec: uint) -> Gc<Expr> {
2490 if self.expr_is_complete(lhs) { return lhs; }
2492 // Prevent dynamic borrow errors later on by limiting the
2493 // scope of the borrows.
2495 let token: &token::Token = &self.token;
2496 let restriction: &restriction = &self.restriction;
2497 match (token, restriction) {
2498 (&token::BINOP(token::OR), &RESTRICT_NO_BAR_OP) => return lhs,
2499 (&token::BINOP(token::OR),
2500 &RESTRICT_NO_BAR_OR_DOUBLEBAR_OP) => return lhs,
2501 (&token::OROR, &RESTRICT_NO_BAR_OR_DOUBLEBAR_OP) => return lhs,
2506 let cur_opt = token_to_binop(&self.token);
2509 let cur_prec = operator_prec(cur_op);
2510 if cur_prec > min_prec {
2512 let expr = self.parse_prefix_expr();
2513 let rhs = self.parse_more_binops(expr, cur_prec);
2514 let binary = self.mk_binary(cur_op, lhs, rhs);
2515 let bin = self.mk_expr(lhs.span.lo, rhs.span.hi, binary);
2516 self.parse_more_binops(bin, min_prec)
2522 if as_prec > min_prec && self.eat_keyword(keywords::As) {
2523 let rhs = self.parse_ty(false);
2524 let _as = self.mk_expr(lhs.span.lo,
2526 ExprCast(lhs, rhs));
2527 self.parse_more_binops(_as, min_prec)
2535 // parse an assignment expression....
2536 // actually, this seems to be the main entry point for
2537 // parsing an arbitrary expression.
2538 pub fn parse_assign_expr(&mut self) -> Gc<Expr> {
2539 let lo = self.span.lo;
2540 let lhs = self.parse_binops();
2544 let rhs = self.parse_expr();
2545 self.mk_expr(lo, rhs.span.hi, ExprAssign(lhs, rhs))
2547 token::BINOPEQ(op) => {
2549 let rhs = self.parse_expr();
2550 let aop = match op {
2551 token::PLUS => BiAdd,
2552 token::MINUS => BiSub,
2553 token::STAR => BiMul,
2554 token::SLASH => BiDiv,
2555 token::PERCENT => BiRem,
2556 token::CARET => BiBitXor,
2557 token::AND => BiBitAnd,
2558 token::OR => BiBitOr,
2559 token::SHL => BiShl,
2562 let assign_op = self.mk_assign_op(aop, lhs, rhs);
2563 self.mk_expr(lo, rhs.span.hi, assign_op)
2571 // parse an 'if' expression ('if' token already eaten)
2572 pub fn parse_if_expr(&mut self) -> Gc<Expr> {
2573 let lo = self.last_span.lo;
2574 let cond = self.parse_expr_res(RESTRICT_NO_STRUCT_LITERAL);
2575 let thn = self.parse_block();
2576 let mut els: Option<Gc<Expr>> = None;
2577 let mut hi = thn.span.hi;
2578 if self.eat_keyword(keywords::Else) {
2579 let elexpr = self.parse_else_expr();
2581 hi = elexpr.span.hi;
2583 self.mk_expr(lo, hi, ExprIf(cond, thn, els))
2586 // `|args| { ... }` or `{ ...}` like in `do` expressions
2587 pub fn parse_lambda_block_expr(&mut self) -> Gc<Expr> {
2588 self.parse_lambda_expr_(
2591 token::BINOP(token::OR) | token::OROR => {
2592 p.parse_fn_block_decl()
2595 // No argument list - `do foo {`
2599 id: ast::DUMMY_NODE_ID,
2610 let blk = p.parse_block();
2611 p.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk))
2616 pub fn parse_lambda_expr(&mut self) -> Gc<Expr> {
2617 self.parse_lambda_expr_(|p| p.parse_fn_block_decl(),
2621 // parse something of the form |args| expr
2622 // this is used both in parsing a lambda expr
2623 // and in parsing a block expr as e.g. in for...
2624 pub fn parse_lambda_expr_(&mut self,
2625 parse_decl: |&mut Parser| -> P<FnDecl>,
2626 parse_body: |&mut Parser| -> Gc<Expr>)
2628 let lo = self.span.lo;
2629 let decl = parse_decl(self);
2630 let body = parse_body(self);
2631 let fakeblock = P(ast::Block {
2632 view_items: Vec::new(),
2635 id: ast::DUMMY_NODE_ID,
2636 rules: DefaultBlock,
2640 return self.mk_expr(lo, body.span.hi, ExprFnBlock(decl, fakeblock));
2643 pub fn parse_else_expr(&mut self) -> Gc<Expr> {
2644 if self.eat_keyword(keywords::If) {
2645 return self.parse_if_expr();
2647 let blk = self.parse_block();
2648 return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk));
2652 // parse a 'for' .. 'in' expression ('for' token already eaten)
2653 pub fn parse_for_expr(&mut self, opt_ident: Option<ast::Ident>) -> Gc<Expr> {
2654 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
2656 let lo = self.last_span.lo;
2657 let pat = self.parse_pat();
2658 self.expect_keyword(keywords::In);
2659 let expr = self.parse_expr_res(RESTRICT_NO_STRUCT_LITERAL);
2660 let loop_block = self.parse_block();
2661 let hi = self.span.hi;
2663 self.mk_expr(lo, hi, ExprForLoop(pat, expr, loop_block, opt_ident))
2666 pub fn parse_while_expr(&mut self) -> Gc<Expr> {
2667 let lo = self.last_span.lo;
2668 let cond = self.parse_expr_res(RESTRICT_NO_STRUCT_LITERAL);
2669 let body = self.parse_block();
2670 let hi = body.span.hi;
2671 return self.mk_expr(lo, hi, ExprWhile(cond, body));
2674 pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::Ident>) -> Gc<Expr> {
2675 let lo = self.last_span.lo;
2676 let body = self.parse_block();
2677 let hi = body.span.hi;
2678 self.mk_expr(lo, hi, ExprLoop(body, opt_ident))
2681 fn parse_match_expr(&mut self) -> Gc<Expr> {
2682 let lo = self.last_span.lo;
2683 let discriminant = self.parse_expr_res(RESTRICT_NO_STRUCT_LITERAL);
2684 self.commit_expr_expecting(discriminant, token::LBRACE);
2685 let mut arms: Vec<Arm> = Vec::new();
2686 while self.token != token::RBRACE {
2687 let attrs = self.parse_outer_attributes();
2688 let pats = self.parse_pats();
2689 let mut guard = None;
2690 if self.eat_keyword(keywords::If) {
2691 guard = Some(self.parse_expr());
2693 self.expect(&token::FAT_ARROW);
2694 let expr = self.parse_expr_res(RESTRICT_STMT_EXPR);
2697 !classify::expr_is_simple_block(expr)
2698 && self.token != token::RBRACE;
2701 self.commit_expr(expr, &[token::COMMA], &[token::RBRACE]);
2703 self.eat(&token::COMMA);
2706 arms.push(ast::Arm {
2713 let hi = self.span.hi;
2715 return self.mk_expr(lo, hi, ExprMatch(discriminant, arms));
2718 // parse an expression
2719 pub fn parse_expr(&mut self) -> Gc<Expr> {
2720 return self.parse_expr_res(UNRESTRICTED);
2723 // parse an expression, subject to the given restriction
2724 fn parse_expr_res(&mut self, r: restriction) -> Gc<Expr> {
2725 let old = self.restriction;
2726 self.restriction = r;
2727 let e = self.parse_assign_expr();
2728 self.restriction = old;
2732 // parse the RHS of a local variable declaration (e.g. '= 14;')
2733 fn parse_initializer(&mut self) -> Option<Gc<Expr>> {
2734 if self.token == token::EQ {
2736 Some(self.parse_expr())
2742 // parse patterns, separated by '|' s
2743 fn parse_pats(&mut self) -> Vec<Gc<Pat>> {
2744 let mut pats = Vec::new();
2746 pats.push(self.parse_pat());
2747 if self.token == token::BINOP(token::OR) { self.bump(); }
2748 else { return pats; }
2752 fn parse_pat_vec_elements(
2754 ) -> (Vec<Gc<Pat>> , Option<Gc<Pat>>, Vec<Gc<Pat>> ) {
2755 let mut before = Vec::new();
2756 let mut slice = None;
2757 let mut after = Vec::new();
2758 let mut first = true;
2759 let mut before_slice = true;
2761 while self.token != token::RBRACKET {
2762 if first { first = false; }
2763 else { self.expect(&token::COMMA); }
2765 let mut is_slice = false;
2767 if self.token == token::DOTDOT {
2770 before_slice = false;
2775 if self.token == token::COMMA || self.token == token::RBRACKET {
2776 slice = Some(box(GC) ast::Pat {
2777 id: ast::DUMMY_NODE_ID,
2782 let subpat = self.parse_pat();
2784 ast::Pat { node: PatIdent(_, _, _), .. } => {
2785 slice = Some(subpat);
2787 ast::Pat { span, .. } => self.span_fatal(
2788 span, "expected an identifier or nothing"
2793 let subpat = self.parse_pat();
2795 before.push(subpat);
2802 (before, slice, after)
2805 // parse the fields of a struct-like pattern
2806 fn parse_pat_fields(&mut self) -> (Vec<ast::FieldPat> , bool) {
2807 let mut fields = Vec::new();
2808 let mut etc = false;
2809 let mut first = true;
2810 while self.token != token::RBRACE {
2814 self.expect(&token::COMMA);
2815 // accept trailing commas
2816 if self.token == token::RBRACE { break }
2819 if self.token == token::DOTDOT {
2821 if self.token != token::RBRACE {
2822 let token_str = self.this_token_to_str();
2823 self.fatal(format!("expected `{}`, found `{}`", "}",
2824 token_str).as_slice())
2830 let bind_type = if self.eat_keyword(keywords::Mut) {
2831 BindByValue(MutMutable)
2832 } else if self.eat_keyword(keywords::Ref) {
2833 BindByRef(self.parse_mutability())
2835 BindByValue(MutImmutable)
2838 let fieldname = self.parse_ident();
2840 let subpat = if self.token == token::COLON {
2842 BindByRef(..) | BindByValue(MutMutable) => {
2843 let token_str = self.this_token_to_str();
2844 self.fatal(format!("unexpected `{}`",
2845 token_str).as_slice())
2853 let fieldpath = ast_util::ident_to_path(self.last_span,
2856 id: ast::DUMMY_NODE_ID,
2857 node: PatIdent(bind_type, fieldpath, None),
2858 span: self.last_span
2861 fields.push(ast::FieldPat { ident: fieldname, pat: subpat });
2863 return (fields, etc);
2867 pub fn parse_pat(&mut self) -> Gc<Pat> {
2868 maybe_whole!(self, NtPat);
2870 let lo = self.span.lo;
2875 token::UNDERSCORE => {
2878 hi = self.last_span.hi;
2879 return box(GC) ast::Pat {
2880 id: ast::DUMMY_NODE_ID,
2888 let sub = self.parse_pat();
2890 let last_span = self.last_span;
2892 self.obsolete(last_span, ObsoleteOwnedPattern);
2893 return box(GC) ast::Pat {
2894 id: ast::DUMMY_NODE_ID,
2899 token::BINOP(token::AND) | token::ANDAND => {
2901 let lo = self.span.lo;
2903 let sub = self.parse_pat();
2904 pat = PatRegion(sub);
2905 hi = self.last_span.hi;
2906 return box(GC) ast::Pat {
2907 id: ast::DUMMY_NODE_ID,
2913 // parse (pat,pat,pat,...) as tuple
2915 if self.token == token::RPAREN {
2918 let lit = box(GC) codemap::Spanned {
2920 span: mk_sp(lo, hi)};
2921 let expr = self.mk_expr(lo, hi, ExprLit(lit));
2924 let mut fields = vec!(self.parse_pat());
2925 if self.look_ahead(1, |t| *t != token::RPAREN) {
2926 while self.token == token::COMMA {
2928 if self.token == token::RPAREN { break; }
2929 fields.push(self.parse_pat());
2932 if fields.len() == 1 { self.expect(&token::COMMA); }
2933 self.expect(&token::RPAREN);
2934 pat = PatTup(fields);
2936 hi = self.last_span.hi;
2937 return box(GC) ast::Pat {
2938 id: ast::DUMMY_NODE_ID,
2943 token::LBRACKET => {
2944 // parse [pat,pat,...] as vector pattern
2946 let (before, slice, after) =
2947 self.parse_pat_vec_elements();
2949 self.expect(&token::RBRACKET);
2950 pat = ast::PatVec(before, slice, after);
2951 hi = self.last_span.hi;
2952 return box(GC) ast::Pat {
2953 id: ast::DUMMY_NODE_ID,
2961 if (!is_ident_or_path(&self.token) && self.token != token::MOD_SEP)
2962 || self.is_keyword(keywords::True)
2963 || self.is_keyword(keywords::False) {
2964 // Parse an expression pattern or exp .. exp.
2966 // These expressions are limited to literals (possibly
2967 // preceded by unary-minus) or identifiers.
2968 let val = self.parse_literal_maybe_minus();
2969 if self.eat(&token::DOTDOT) {
2970 let end = if is_ident_or_path(&self.token) {
2971 let path = self.parse_path(LifetimeAndTypesWithColons)
2973 let hi = self.span.hi;
2974 self.mk_expr(lo, hi, ExprPath(path))
2976 self.parse_literal_maybe_minus()
2978 pat = PatRange(val, end);
2982 } else if self.eat_keyword(keywords::Mut) {
2983 pat = self.parse_pat_ident(BindByValue(MutMutable));
2984 } else if self.eat_keyword(keywords::Ref) {
2986 let mutbl = self.parse_mutability();
2987 pat = self.parse_pat_ident(BindByRef(mutbl));
2988 } else if self.eat_keyword(keywords::Box) {
2991 // FIXME(#13910): Rename to `PatBox` and extend to full DST
2993 let sub = self.parse_pat();
2995 hi = self.last_span.hi;
2996 return box(GC) ast::Pat {
2997 id: ast::DUMMY_NODE_ID,
3002 let can_be_enum_or_struct = self.look_ahead(1, |t| {
3004 token::LPAREN | token::LBRACKET | token::LT |
3005 token::LBRACE | token::MOD_SEP => true,
3010 if self.look_ahead(1, |t| *t == token::DOTDOT) {
3011 let start = self.parse_expr_res(RESTRICT_NO_BAR_OP);
3012 self.eat(&token::DOTDOT);
3013 let end = self.parse_expr_res(RESTRICT_NO_BAR_OP);
3014 pat = PatRange(start, end);
3015 } else if is_plain_ident(&self.token) && !can_be_enum_or_struct {
3016 let name = self.parse_path(NoTypesAllowed).path;
3017 if self.eat(&token::NOT) {
3019 let ket = token::close_delimiter_for(&self.token)
3020 .unwrap_or_else(|| self.fatal("expected open delimiter"));
3023 let tts = self.parse_seq_to_end(&ket,
3025 |p| p.parse_token_tree());
3027 let mac = MacInvocTT(name, tts, EMPTY_CTXT);
3028 pat = ast::PatMac(codemap::Spanned {node: mac, span: self.span});
3030 let sub = if self.eat(&token::AT) {
3032 Some(self.parse_pat())
3037 pat = PatIdent(BindByValue(MutImmutable), name, sub);
3040 // parse an enum pat
3041 let enum_path = self.parse_path(LifetimeAndTypesWithColons)
3047 self.parse_pat_fields();
3049 pat = PatStruct(enum_path, fields, etc);
3052 let mut args: Vec<Gc<Pat>> = Vec::new();
3055 let is_dotdot = self.look_ahead(1, |t| {
3057 token::DOTDOT => true,
3062 // This is a "top constructor only" pat
3065 self.expect(&token::RPAREN);
3066 pat = PatEnum(enum_path, None);
3068 args = self.parse_enum_variant_seq(
3071 seq_sep_trailing_disallowed(token::COMMA),
3074 pat = PatEnum(enum_path, Some(args));
3078 if enum_path.segments.len() == 1 {
3079 // it could still be either an enum
3080 // or an identifier pattern, resolve
3081 // will sort it out:
3082 pat = PatIdent(BindByValue(MutImmutable),
3086 pat = PatEnum(enum_path, Some(args));
3094 hi = self.last_span.hi;
3096 id: ast::DUMMY_NODE_ID,
3098 span: mk_sp(lo, hi),
3102 // parse ident or ident @ pat
3103 // used by the copy foo and ref foo patterns to give a good
3104 // error message when parsing mistakes like ref foo(a,b)
3105 fn parse_pat_ident(&mut self,
3106 binding_mode: ast::BindingMode)
3108 if !is_plain_ident(&self.token) {
3109 let last_span = self.last_span;
3110 self.span_fatal(last_span,
3111 "expected identifier, found path");
3113 // why a path here, and not just an identifier?
3114 let name = self.parse_path(NoTypesAllowed).path;
3115 let sub = if self.eat(&token::AT) {
3116 Some(self.parse_pat())
3121 // just to be friendly, if they write something like
3123 // we end up here with ( as the current token. This shortly
3124 // leads to a parse error. Note that if there is no explicit
3125 // binding mode then we do not end up here, because the lookahead
3126 // will direct us over to parse_enum_variant()
3127 if self.token == token::LPAREN {
3128 let last_span = self.last_span;
3131 "expected identifier, found enum pattern");
3134 PatIdent(binding_mode, name, sub)
3137 // parse a local variable declaration
3138 fn parse_local(&mut self) -> Gc<Local> {
3139 let lo = self.span.lo;
3140 let pat = self.parse_pat();
3143 id: ast::DUMMY_NODE_ID,
3145 span: mk_sp(lo, lo),
3147 if self.eat(&token::COLON) {
3148 ty = self.parse_ty(true);
3150 let init = self.parse_initializer();
3151 box(GC) ast::Local {
3155 id: ast::DUMMY_NODE_ID,
3156 span: mk_sp(lo, self.last_span.hi),
3161 // parse a "let" stmt
3162 fn parse_let(&mut self) -> Gc<Decl> {
3163 let lo = self.span.lo;
3164 let local = self.parse_local();
3165 box(GC) spanned(lo, self.last_span.hi, DeclLocal(local))
3168 // parse a structure field
3169 fn parse_name_and_ty(&mut self, pr: Visibility,
3170 attrs: Vec<Attribute> ) -> StructField {
3171 let lo = self.span.lo;
3172 if !is_plain_ident(&self.token) {
3173 self.fatal("expected ident");
3175 let name = self.parse_ident();
3176 self.expect(&token::COLON);
3177 let ty = self.parse_ty(true);
3178 spanned(lo, self.last_span.hi, ast::StructField_ {
3179 kind: NamedField(name, pr),
3180 id: ast::DUMMY_NODE_ID,
3186 // parse a statement. may include decl.
3187 // precondition: any attributes are parsed already
3188 pub fn parse_stmt(&mut self, item_attrs: Vec<Attribute>) -> Gc<Stmt> {
3189 maybe_whole!(self, NtStmt);
3191 fn check_expected_item(p: &mut Parser, found_attrs: bool) {
3192 // If we have attributes then we should have an item
3194 let last_span = p.last_span;
3195 p.span_err(last_span, "expected item after attributes");
3199 let lo = self.span.lo;
3200 if self.is_keyword(keywords::Let) {
3201 check_expected_item(self, !item_attrs.is_empty());
3202 self.expect_keyword(keywords::Let);
3203 let decl = self.parse_let();
3204 return box(GC) spanned(lo, decl.span.hi, StmtDecl(decl, ast::DUMMY_NODE_ID));
3205 } else if is_ident(&self.token)
3206 && !token::is_any_keyword(&self.token)
3207 && self.look_ahead(1, |t| *t == token::NOT) {
3208 // parse a macro invocation. Looks like there's serious
3209 // overlap here; if this clause doesn't catch it (and it
3210 // won't, for brace-delimited macros) it will fall through
3211 // to the macro clause of parse_item_or_view_item. This
3212 // could use some cleanup, it appears to me.
3214 // whoops! I now have a guess: I'm guessing the "parens-only"
3215 // rule here is deliberate, to allow macro users to use parens
3216 // for things that should be parsed as stmt_mac, and braces
3217 // for things that should expand into items. Tricky, and
3218 // somewhat awkward... and probably undocumented. Of course,
3219 // I could just be wrong.
3221 check_expected_item(self, !item_attrs.is_empty());
3223 // Potential trouble: if we allow macros with paths instead of
3224 // idents, we'd need to look ahead past the whole path here...
3225 let pth = self.parse_path(NoTypesAllowed).path;
3228 let id = if token::close_delimiter_for(&self.token).is_some() {
3229 token::special_idents::invalid // no special identifier
3234 // check that we're pointing at delimiters (need to check
3235 // again after the `if`, because of `parse_ident`
3236 // consuming more tokens).
3237 let (bra, ket) = match token::close_delimiter_for(&self.token) {
3238 Some(ket) => (self.token.clone(), ket),
3240 // we only expect an ident if we didn't parse one
3242 let ident_str = if id == token::special_idents::invalid {
3247 let tok_str = self.this_token_to_str();
3248 self.fatal(format!("expected {}`(` or `{{`, but found `{}`",
3250 tok_str).as_slice())
3254 let tts = self.parse_unspanned_seq(
3258 |p| p.parse_token_tree()
3260 let hi = self.span.hi;
3262 if id == token::special_idents::invalid {
3263 return box(GC) spanned(lo, hi, StmtMac(
3264 spanned(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT)), false));
3266 // if it has a special ident, it's definitely an item
3267 return box(GC) spanned(lo, hi, StmtDecl(
3268 box(GC) spanned(lo, hi, DeclItem(
3270 lo, hi, id /*id is good here*/,
3271 ItemMac(spanned(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT))),
3272 Inherited, Vec::new(/*no attrs*/)))),
3273 ast::DUMMY_NODE_ID));
3277 let found_attrs = !item_attrs.is_empty();
3278 match self.parse_item_or_view_item(item_attrs, false) {
3281 let decl = box(GC) spanned(lo, hi, DeclItem(i));
3282 return box(GC) spanned(lo, hi, StmtDecl(decl, ast::DUMMY_NODE_ID));
3284 IoviViewItem(vi) => {
3285 self.span_fatal(vi.span,
3286 "view items must be declared at the top of the block");
3288 IoviForeignItem(_) => {
3289 self.fatal("foreign items are not allowed here");
3291 IoviNone(_) => { /* fallthrough */ }
3294 check_expected_item(self, found_attrs);
3296 // Remainder are line-expr stmts.
3297 let e = self.parse_expr_res(RESTRICT_STMT_EXPR);
3298 return box(GC) spanned(lo, e.span.hi, StmtExpr(e, ast::DUMMY_NODE_ID));
3302 // is this expression a successfully-parsed statement?
3303 fn expr_is_complete(&mut self, e: Gc<Expr>) -> bool {
3304 return self.restriction == RESTRICT_STMT_EXPR &&
3305 !classify::expr_requires_semi_to_be_stmt(e);
3308 // parse a block. No inner attrs are allowed.
3309 pub fn parse_block(&mut self) -> P<Block> {
3310 maybe_whole!(no_clone self, NtBlock);
3312 let lo = self.span.lo;
3313 self.expect(&token::LBRACE);
3315 return self.parse_block_tail_(lo, DefaultBlock, Vec::new());
3318 // parse a block. Inner attrs are allowed.
3319 fn parse_inner_attrs_and_block(&mut self)
3320 -> (Vec<Attribute> , P<Block>) {
3322 maybe_whole!(pair_empty self, NtBlock);
3324 let lo = self.span.lo;
3325 self.expect(&token::LBRACE);
3326 let (inner, next) = self.parse_inner_attrs_and_next();
3328 (inner, self.parse_block_tail_(lo, DefaultBlock, next))
3331 // Precondition: already parsed the '{' or '#{'
3332 // I guess that also means "already parsed the 'impure'" if
3333 // necessary, and this should take a qualifier.
3334 // some blocks start with "#{"...
3335 fn parse_block_tail(&mut self, lo: BytePos, s: BlockCheckMode) -> P<Block> {
3336 self.parse_block_tail_(lo, s, Vec::new())
3339 // parse the rest of a block expression or function body
3340 fn parse_block_tail_(&mut self, lo: BytePos, s: BlockCheckMode,
3341 first_item_attrs: Vec<Attribute> ) -> P<Block> {
3342 let mut stmts = Vec::new();
3343 let mut expr = None;
3345 // wouldn't it be more uniform to parse view items only, here?
3346 let ParsedItemsAndViewItems {
3347 attrs_remaining: attrs_remaining,
3348 view_items: view_items,
3351 } = self.parse_items_and_view_items(first_item_attrs,
3354 for item in items.iter() {
3355 let decl = box(GC) spanned(item.span.lo, item.span.hi, DeclItem(*item));
3356 stmts.push(box(GC) spanned(item.span.lo, item.span.hi,
3357 StmtDecl(decl, ast::DUMMY_NODE_ID)));
3360 let mut attributes_box = attrs_remaining;
3362 while self.token != token::RBRACE {
3363 // parsing items even when they're not allowed lets us give
3364 // better error messages and recover more gracefully.
3365 attributes_box.push_all(self.parse_outer_attributes().as_slice());
3368 if !attributes_box.is_empty() {
3369 let last_span = self.last_span;
3370 self.span_err(last_span, "expected item after attributes");
3371 attributes_box = Vec::new();
3373 self.bump(); // empty
3376 // fall through and out.
3379 let stmt = self.parse_stmt(attributes_box);
3380 attributes_box = Vec::new();
3382 StmtExpr(e, stmt_id) => {
3383 // expression without semicolon
3384 if classify::stmt_ends_with_semi(&*stmt) {
3385 // Just check for errors and recover; do not eat semicolon yet.
3386 self.commit_stmt(stmt, &[], &[token::SEMI, token::RBRACE]);
3392 let span_with_semi = Span {
3394 hi: self.last_span.hi,
3395 expn_info: stmt.span.expn_info,
3397 stmts.push(box(GC) codemap::Spanned {
3398 node: StmtSemi(e, stmt_id),
3399 span: span_with_semi,
3410 StmtMac(ref m, _) => {
3411 // statement macro; might be an expr
3415 stmts.push(box(GC) codemap::Spanned {
3416 node: StmtMac((*m).clone(), true),
3421 // if a block ends in `m!(arg)` without
3422 // a `;`, it must be an expr
3424 self.mk_mac_expr(stmt.span.lo,
3433 _ => { // all other kinds of statements:
3434 stmts.push(stmt.clone());
3436 if classify::stmt_ends_with_semi(&*stmt) {
3437 self.commit_stmt_expecting(stmt, token::SEMI);
3445 if !attributes_box.is_empty() {
3446 let last_span = self.last_span;
3447 self.span_err(last_span, "expected item after attributes");
3450 let hi = self.span.hi;
3453 view_items: view_items,
3456 id: ast::DUMMY_NODE_ID,
3458 span: mk_sp(lo, hi),
3462 fn parse_unboxed_function_type(&mut self) -> UnboxedFnTy {
3463 let inputs = if self.eat(&token::OROR) {
3468 if self.token == token::BINOP(token::AND) &&
3469 self.look_ahead(1, |t| {
3470 token::is_keyword(keywords::Mut, t)
3472 self.look_ahead(2, |t| *t == token::COLON) {
3478 let inputs = self.parse_seq_to_before_or(&token::COMMA,
3480 p.parse_arg_general(false)
3486 let (return_style, output) = self.parse_ret_ty();
3497 // matches bounds = ( boundseq )?
3498 // where boundseq = ( bound + boundseq ) | bound
3499 // and bound = 'static | ty
3500 // Returns "None" if there's no colon (e.g. "T");
3501 // Returns "Some(Empty)" if there's a colon but nothing after (e.g. "T:")
3502 // Returns "Some(stuff)" otherwise (e.g. "T:stuff").
3503 // NB: The None/Some distinction is important for issue #7264.
3505 // Note that the `allow_any_lifetime` argument is a hack for now while the
3506 // AST doesn't support arbitrary lifetimes in bounds on type parameters. In
3507 // the future, this flag should be removed, and the return value of this
3508 // function should be Option<~[TyParamBound]>
3509 fn parse_ty_param_bounds(&mut self, allow_any_lifetime: bool)
3510 -> (Option<ast::Lifetime>,
3511 OwnedSlice<TyParamBound>) {
3512 let mut ret_lifetime = None;
3513 let mut result = vec!();
3516 token::LIFETIME(lifetime) => {
3517 let lifetime_interned_string = token::get_ident(lifetime);
3518 if lifetime_interned_string.equiv(&("'static")) {
3519 result.push(StaticRegionTyParamBound);
3520 if allow_any_lifetime && ret_lifetime.is_none() {
3521 ret_lifetime = Some(ast::Lifetime {
3522 id: ast::DUMMY_NODE_ID,
3527 } else if allow_any_lifetime && ret_lifetime.is_none() {
3528 ret_lifetime = Some(ast::Lifetime {
3529 id: ast::DUMMY_NODE_ID,
3534 result.push(OtherRegionTyParamBound(self.span));
3538 token::MOD_SEP | token::IDENT(..) => {
3539 let tref = self.parse_trait_ref();
3540 result.push(TraitTyParamBound(tref));
3542 token::BINOP(token::OR) | token::OROR => {
3543 let unboxed_function_type =
3544 self.parse_unboxed_function_type();
3545 result.push(UnboxedFnTyParamBound(unboxed_function_type));
3550 if !self.eat(&token::BINOP(token::PLUS)) {
3555 return (ret_lifetime, OwnedSlice::from_vec(result));
3558 // matches typaram = type? IDENT optbounds ( EQ ty )?
3559 fn parse_ty_param(&mut self) -> TyParam {
3560 let sized = self.parse_sized();
3561 let span = self.span;
3562 let ident = self.parse_ident();
3564 if self.eat(&token::COLON) {
3565 let (_, bounds) = self.parse_ty_param_bounds(false);
3571 // For typarams we don't care about the difference b/w "<T>" and "<T:>".
3572 let bounds = opt_bounds.unwrap_or_default();
3574 let default = if self.token == token::EQ {
3576 Some(self.parse_ty(true))
3582 id: ast::DUMMY_NODE_ID,
3590 // parse a set of optional generic type parameter declarations
3591 // matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
3592 // | ( < lifetimes , typaramseq ( , )? > )
3593 // where typaramseq = ( typaram ) | ( typaram , typaramseq )
3594 pub fn parse_generics(&mut self) -> ast::Generics {
3595 if self.eat(&token::LT) {
3596 let lifetimes = self.parse_lifetimes();
3597 let mut seen_default = false;
3598 let ty_params = self.parse_seq_to_gt(Some(token::COMMA), |p| {
3599 p.forbid_lifetime();
3600 let ty_param = p.parse_ty_param();
3601 if ty_param.default.is_some() {
3602 seen_default = true;
3603 } else if seen_default {
3604 let last_span = p.last_span;
3605 p.span_err(last_span,
3606 "type parameters with a default must be trailing");
3610 ast::Generics { lifetimes: lifetimes, ty_params: ty_params }
3612 ast_util::empty_generics()
3616 fn parse_generic_values_after_lt(&mut self) -> (Vec<ast::Lifetime>, Vec<P<Ty>> ) {
3617 let lifetimes = self.parse_lifetimes();
3618 let result = self.parse_seq_to_gt(
3621 p.forbid_lifetime();
3625 (lifetimes, result.into_vec())
3628 fn forbid_lifetime(&mut self) {
3629 if Parser::token_is_lifetime(&self.token) {
3630 let span = self.span;
3631 self.span_fatal(span, "lifetime parameters must be declared \
3632 prior to type parameters");
3636 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
3637 -> (Vec<Arg> , bool) {
3639 let mut args: Vec<Option<Arg>> =
3640 self.parse_unspanned_seq(
3643 seq_sep_trailing_allowed(token::COMMA),
3645 if p.token == token::DOTDOTDOT {
3648 if p.token != token::RPAREN {
3651 "`...` must be last in argument list for variadic function");
3656 "only foreign functions are allowed to be variadic");
3660 Some(p.parse_arg_general(named_args))
3665 let variadic = match args.pop() {
3668 // Need to put back that last arg
3675 if variadic && args.is_empty() {
3677 "variadic function must be declared with at least one named argument");
3680 let args = args.move_iter().map(|x| x.unwrap()).collect();
3685 // parse the argument list and result type of a function declaration
3686 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> P<FnDecl> {
3688 let (args, variadic) = self.parse_fn_args(true, allow_variadic);
3689 let (ret_style, ret_ty) = self.parse_ret_ty();
3699 fn is_self_ident(&mut self) -> bool {
3701 token::IDENT(id, false) => id.name == special_idents::self_.name,
3706 fn expect_self_ident(&mut self) {
3707 if !self.is_self_ident() {
3708 let token_str = self.this_token_to_str();
3709 self.fatal(format!("expected `self` but found `{}`",
3710 token_str).as_slice())
3715 // parse the argument list and result type of a function
3716 // that may have a self type.
3717 fn parse_fn_decl_with_self(&mut self, parse_arg_fn: |&mut Parser| -> Arg)
3718 -> (ExplicitSelf, P<FnDecl>) {
3719 fn maybe_parse_borrowed_explicit_self(this: &mut Parser)
3720 -> ast::ExplicitSelf_ {
3721 // The following things are possible to see here:
3726 // fn(&'lt mut self)
3728 // We already know that the current token is `&`.
3730 if this.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) {
3732 this.expect_self_ident();
3733 SelfRegion(None, MutImmutable)
3734 } else if this.look_ahead(1, |t| Parser::token_is_mutability(t)) &&
3736 |t| token::is_keyword(keywords::Self,
3739 let mutability = this.parse_mutability();
3740 this.expect_self_ident();
3741 SelfRegion(None, mutability)
3742 } else if this.look_ahead(1, |t| Parser::token_is_lifetime(t)) &&
3744 |t| token::is_keyword(keywords::Self,
3747 let lifetime = this.parse_lifetime();
3748 this.expect_self_ident();
3749 SelfRegion(Some(lifetime), MutImmutable)
3750 } else if this.look_ahead(1, |t| Parser::token_is_lifetime(t)) &&
3751 this.look_ahead(2, |t| {
3752 Parser::token_is_mutability(t)
3754 this.look_ahead(3, |t| token::is_keyword(keywords::Self,
3757 let lifetime = this.parse_lifetime();
3758 let mutability = this.parse_mutability();
3759 this.expect_self_ident();
3760 SelfRegion(Some(lifetime), mutability)
3766 self.expect(&token::LPAREN);
3768 // A bit of complexity and lookahead is needed here in order to be
3769 // backwards compatible.
3770 let lo = self.span.lo;
3771 let mut mutbl_self = MutImmutable;
3772 let explicit_self = match self.token {
3773 token::BINOP(token::AND) => {
3774 maybe_parse_borrowed_explicit_self(self)
3777 // We need to make sure it isn't a type
3778 if self.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) {
3780 self.expect_self_ident();
3786 token::IDENT(..) if self.is_self_ident() => {
3790 token::BINOP(token::STAR) => {
3791 // Possibly "*self" or "*mut self" -- not supported. Try to avoid
3792 // emitting cryptic "unexpected token" errors.
3794 let _mutability = if Parser::token_is_mutability(&self.token) {
3795 self.parse_mutability()
3796 } else { MutImmutable };
3797 if self.is_self_ident() {
3798 let span = self.span;
3799 self.span_err(span, "cannot pass self by unsafe pointer");
3804 _ if Parser::token_is_mutability(&self.token) &&
3805 self.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) => {
3806 mutbl_self = self.parse_mutability();
3807 self.expect_self_ident();
3810 _ if Parser::token_is_mutability(&self.token) &&
3811 self.look_ahead(1, |t| *t == token::TILDE) &&
3812 self.look_ahead(2, |t| token::is_keyword(keywords::Self, t)) => {
3813 mutbl_self = self.parse_mutability();
3815 self.expect_self_ident();
3821 let explicit_self_sp = mk_sp(lo, self.span.hi);
3823 // If we parsed a self type, expect a comma before the argument list.
3824 let fn_inputs = if explicit_self != SelfStatic {
3828 let sep = seq_sep_trailing_disallowed(token::COMMA);
3829 let mut fn_inputs = self.parse_seq_to_before_end(
3834 fn_inputs.unshift(Arg::new_self(explicit_self_sp, mutbl_self));
3838 vec!(Arg::new_self(explicit_self_sp, mutbl_self))
3841 let token_str = self.this_token_to_str();
3842 self.fatal(format!("expected `,` or `)`, found `{}`",
3843 token_str).as_slice())
3847 let sep = seq_sep_trailing_disallowed(token::COMMA);
3848 self.parse_seq_to_before_end(&token::RPAREN, sep, parse_arg_fn)
3851 self.expect(&token::RPAREN);
3853 let hi = self.span.hi;
3855 let (ret_style, ret_ty) = self.parse_ret_ty();
3857 let fn_decl = P(FnDecl {
3864 (spanned(lo, hi, explicit_self), fn_decl)
3867 // parse the |arg, arg| header on a lambda
3868 fn parse_fn_block_decl(&mut self) -> P<FnDecl> {
3869 let inputs_captures = {
3870 if self.eat(&token::OROR) {
3873 self.parse_unspanned_seq(
3874 &token::BINOP(token::OR),
3875 &token::BINOP(token::OR),
3876 seq_sep_trailing_disallowed(token::COMMA),
3877 |p| p.parse_fn_block_arg()
3881 let output = if self.eat(&token::RARROW) {
3885 id: ast::DUMMY_NODE_ID,
3892 inputs: inputs_captures,
3899 // Parses the `(arg, arg) -> return_type` header on a procedure.
3900 fn parse_proc_decl(&mut self) -> P<FnDecl> {
3902 self.parse_unspanned_seq(&token::LPAREN,
3904 seq_sep_trailing_allowed(token::COMMA),
3905 |p| p.parse_fn_block_arg());
3907 let output = if self.eat(&token::RARROW) {
3911 id: ast::DUMMY_NODE_ID,
3925 // parse the name and optional generic types of a function header.
3926 fn parse_fn_header(&mut self) -> (Ident, ast::Generics) {
3927 let id = self.parse_ident();
3928 let generics = self.parse_generics();
3932 fn mk_item(&mut self, lo: BytePos, hi: BytePos, ident: Ident,
3933 node: Item_, vis: Visibility,
3934 attrs: Vec<Attribute>) -> Gc<Item> {
3938 id: ast::DUMMY_NODE_ID,
3945 // parse an item-position function declaration.
3946 fn parse_item_fn(&mut self, fn_style: FnStyle, abi: abi::Abi) -> ItemInfo {
3947 let (ident, generics) = self.parse_fn_header();
3948 let decl = self.parse_fn_decl(false);
3949 let (inner_attrs, body) = self.parse_inner_attrs_and_block();
3950 (ident, ItemFn(decl, fn_style, abi, generics, body), Some(inner_attrs))
3953 // parse a method in a trait impl, starting with `attrs` attributes.
3954 fn parse_method(&mut self,
3955 already_parsed_attrs: Option<Vec<Attribute>>) -> Gc<Method> {
3956 let next_attrs = self.parse_outer_attributes();
3957 let attrs = match already_parsed_attrs {
3958 Some(mut a) => { a.push_all_move(next_attrs); a }
3962 let lo = self.span.lo;
3964 let visa = self.parse_visibility();
3965 let fn_style = self.parse_fn_style();
3966 let ident = self.parse_ident();
3967 let generics = self.parse_generics();
3968 let (explicit_self, decl) = self.parse_fn_decl_with_self(|p| {
3972 let (inner_attrs, body) = self.parse_inner_attrs_and_block();
3973 let hi = body.span.hi;
3974 let attrs = attrs.append(inner_attrs.as_slice());
3975 box(GC) ast::Method {
3979 explicit_self: explicit_self,
3983 id: ast::DUMMY_NODE_ID,
3984 span: mk_sp(lo, hi),
3989 // parse trait Foo { ... }
3990 fn parse_item_trait(&mut self) -> ItemInfo {
3991 let ident = self.parse_ident();
3992 let tps = self.parse_generics();
3993 let sized = self.parse_for_sized();
3995 // Parse traits, if necessary.
3997 if self.token == token::COLON {
3999 traits = self.parse_trait_ref_list(&token::LBRACE);
4001 traits = Vec::new();
4004 let meths = self.parse_trait_methods();
4005 (ident, ItemTrait(tps, sized, traits, meths), None)
4008 // Parses two variants (with the region/type params always optional):
4009 // impl<T> Foo { ... }
4010 // impl<T> ToStr for ~[T] { ... }
4011 fn parse_item_impl(&mut self) -> ItemInfo {
4012 // First, parse type parameters if necessary.
4013 let generics = self.parse_generics();
4015 // Special case: if the next identifier that follows is '(', don't
4016 // allow this to be parsed as a trait.
4017 let could_be_trait = self.token != token::LPAREN;
4020 let mut ty = self.parse_ty(true);
4022 // Parse traits, if necessary.
4023 let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) {
4024 // New-style trait. Reinterpret the type as a trait.
4025 let opt_trait_ref = match ty.node {
4026 TyPath(ref path, None, node_id) => {
4028 path: /* bad */ (*path).clone(),
4033 self.span_err(ty.span,
4034 "bounded traits are only valid in type position");
4038 self.span_err(ty.span, "not a trait");
4043 ty = self.parse_ty(true);
4049 let mut meths = Vec::new();
4050 self.expect(&token::LBRACE);
4051 let (inner_attrs, next) = self.parse_inner_attrs_and_next();
4052 let mut method_attrs = Some(next);
4053 while !self.eat(&token::RBRACE) {
4054 meths.push(self.parse_method(method_attrs));
4055 method_attrs = None;
4058 let ident = ast_util::impl_pretty_name(&opt_trait, &*ty);
4060 (ident, ItemImpl(generics, opt_trait, ty, meths), Some(inner_attrs))
4063 // parse a::B<String,int>
4064 fn parse_trait_ref(&mut self) -> TraitRef {
4066 path: self.parse_path(LifetimeAndTypesWithoutColons).path,
4067 ref_id: ast::DUMMY_NODE_ID,
4071 // parse B + C<String,int> + D
4072 fn parse_trait_ref_list(&mut self, ket: &token::Token) -> Vec<TraitRef> {
4073 self.parse_seq_to_before_end(
4075 seq_sep_trailing_disallowed(token::BINOP(token::PLUS)),
4076 |p| p.parse_trait_ref()
4080 // parse struct Foo { ... }
4081 fn parse_item_struct(&mut self, is_virtual: bool) -> ItemInfo {
4082 let class_name = self.parse_ident();
4083 let generics = self.parse_generics();
4085 let super_struct = if self.eat(&token::COLON) {
4086 let ty = self.parse_ty(true);
4088 TyPath(_, None, _) => {
4092 self.span_err(ty.span, "not a struct");
4100 let mut fields: Vec<StructField>;
4103 if self.eat(&token::LBRACE) {
4104 // It's a record-like struct.
4105 is_tuple_like = false;
4106 fields = Vec::new();
4107 while self.token != token::RBRACE {
4108 fields.push(self.parse_struct_decl_field());
4110 if fields.len() == 0 {
4111 self.fatal(format!("unit-like struct definition should be \
4112 written as `struct {};`",
4113 token::get_ident(class_name)).as_slice());
4116 } else if self.token == token::LPAREN {
4117 // It's a tuple-like struct.
4118 is_tuple_like = true;
4119 fields = self.parse_unspanned_seq(
4122 seq_sep_trailing_allowed(token::COMMA),
4124 let attrs = p.parse_outer_attributes();
4126 let struct_field_ = ast::StructField_ {
4127 kind: UnnamedField(p.parse_visibility()),
4128 id: ast::DUMMY_NODE_ID,
4129 ty: p.parse_ty(true),
4132 spanned(lo, p.span.hi, struct_field_)
4134 if fields.len() == 0 {
4135 self.fatal(format!("unit-like struct definition should be \
4136 written as `struct {};`",
4137 token::get_ident(class_name)).as_slice());
4139 self.expect(&token::SEMI);
4140 } else if self.eat(&token::SEMI) {
4141 // It's a unit-like struct.
4142 is_tuple_like = true;
4143 fields = Vec::new();
4145 let token_str = self.this_token_to_str();
4146 self.fatal(format!("expected `{}`, `(`, or `;` after struct \
4147 name but found `{}`", "{",
4148 token_str).as_slice())
4151 let _ = ast::DUMMY_NODE_ID; // FIXME: Workaround for crazy bug.
4152 let new_id = ast::DUMMY_NODE_ID;
4154 ItemStruct(box(GC) ast::StructDef {
4156 ctor_id: if is_tuple_like { Some(new_id) } else { None },
4157 super_struct: super_struct,
4158 is_virtual: is_virtual,
4163 // parse a structure field declaration
4164 pub fn parse_single_struct_field(&mut self,
4166 attrs: Vec<Attribute> )
4168 let a_var = self.parse_name_and_ty(vis, attrs);
4175 let span = self.span;
4176 let token_str = self.this_token_to_str();
4177 self.span_fatal(span,
4178 format!("expected `,`, or `}}` but found `{}`",
4179 token_str).as_slice())
4185 // parse an element of a struct definition
4186 fn parse_struct_decl_field(&mut self) -> StructField {
4188 let attrs = self.parse_outer_attributes();
4190 if self.eat_keyword(keywords::Pub) {
4191 return self.parse_single_struct_field(Public, attrs);
4194 return self.parse_single_struct_field(Inherited, attrs);
4197 // parse visiility: PUB, PRIV, or nothing
4198 fn parse_visibility(&mut self) -> Visibility {
4199 if self.eat_keyword(keywords::Pub) { Public }
4203 fn parse_sized(&mut self) -> Sized {
4204 if self.eat_keyword(keywords::Type) { DynSize }
4208 fn parse_for_sized(&mut self) -> Sized {
4209 if self.eat_keyword(keywords::For) {
4210 if !self.eat_keyword(keywords::Type) {
4211 let last_span = self.last_span;
4212 self.span_err(last_span,
4213 "expected 'type' after for in trait item");
4221 // given a termination token and a vector of already-parsed
4222 // attributes (of length 0 or 1), parse all of the items in a module
4223 fn parse_mod_items(&mut self,
4225 first_item_attrs: Vec<Attribute>,
4228 // parse all of the items up to closing or an attribute.
4229 // view items are legal here.
4230 let ParsedItemsAndViewItems {
4231 attrs_remaining: attrs_remaining,
4232 view_items: view_items,
4233 items: starting_items,
4235 } = self.parse_items_and_view_items(first_item_attrs, true, true);
4236 let mut items: Vec<Gc<Item>> = starting_items;
4237 let attrs_remaining_len = attrs_remaining.len();
4239 // don't think this other loop is even necessary....
4241 let mut first = true;
4242 while self.token != term {
4243 let mut attrs = self.parse_outer_attributes();
4245 attrs = attrs_remaining.clone().append(attrs.as_slice());
4248 debug!("parse_mod_items: parse_item_or_view_item(attrs={:?})",
4250 match self.parse_item_or_view_item(attrs,
4251 true /* macros allowed */) {
4252 IoviItem(item) => items.push(item),
4253 IoviViewItem(view_item) => {
4254 self.span_fatal(view_item.span,
4255 "view items must be declared at the top of \
4259 let token_str = self.this_token_to_str();
4260 self.fatal(format!("expected item but found `{}`",
4261 token_str).as_slice())
4266 if first && attrs_remaining_len > 0u {
4267 // We parsed attributes for the first item but didn't find it
4268 let last_span = self.last_span;
4269 self.span_err(last_span, "expected item after attributes");
4273 inner: mk_sp(inner_lo, self.span.lo),
4274 view_items: view_items,
4279 fn parse_item_const(&mut self) -> ItemInfo {
4280 let m = if self.eat_keyword(keywords::Mut) {MutMutable} else {MutImmutable};
4281 let id = self.parse_ident();
4282 self.expect(&token::COLON);
4283 let ty = self.parse_ty(true);
4284 self.expect(&token::EQ);
4285 let e = self.parse_expr();
4286 self.commit_expr_expecting(e, token::SEMI);
4287 (id, ItemStatic(ty, m, e), None)
4290 // parse a `mod <foo> { ... }` or `mod <foo>;` item
4291 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> ItemInfo {
4292 let id_span = self.span;
4293 let id = self.parse_ident();
4294 if self.token == token::SEMI {
4296 // This mod is in an external file. Let's go get it!
4297 let (m, attrs) = self.eval_src_mod(id, outer_attrs, id_span);
4298 (id, m, Some(attrs))
4300 self.push_mod_path(id, outer_attrs);
4301 self.expect(&token::LBRACE);
4302 let mod_inner_lo = self.span.lo;
4303 let old_owns_directory = self.owns_directory;
4304 self.owns_directory = true;
4305 let (inner, next) = self.parse_inner_attrs_and_next();
4306 let m = self.parse_mod_items(token::RBRACE, next, mod_inner_lo);
4307 self.expect(&token::RBRACE);
4308 self.owns_directory = old_owns_directory;
4309 self.pop_mod_path();
4310 (id, ItemMod(m), Some(inner))
4314 fn push_mod_path(&mut self, id: Ident, attrs: &[Attribute]) {
4315 let default_path = self.id_to_interned_str(id);
4316 let file_path = match ::attr::first_attr_value_str_by_name(attrs,
4319 None => default_path,
4321 self.mod_path_stack.push(file_path)
4324 fn pop_mod_path(&mut self) {
4325 self.mod_path_stack.pop().unwrap();
4328 // read a module from a source file.
4329 fn eval_src_mod(&mut self,
4331 outer_attrs: &[ast::Attribute],
4333 -> (ast::Item_, Vec<ast::Attribute> ) {
4334 let mut prefix = Path::new(self.sess.span_diagnostic.cm.span_to_filename(self.span));
4336 let mod_path = Path::new(".").join_many(self.mod_path_stack.as_slice());
4337 let dir_path = prefix.join(&mod_path);
4338 let mod_string = token::get_ident(id);
4339 let (file_path, owns_directory) = match ::attr::first_attr_value_str_by_name(
4340 outer_attrs, "path") {
4341 Some(d) => (dir_path.join(d), true),
4343 let mod_name = mod_string.get().to_string();
4344 let default_path_str = format!("{}.rs", mod_name);
4345 let secondary_path_str = format!("{}/mod.rs", mod_name);
4346 let default_path = dir_path.join(default_path_str.as_slice());
4347 let secondary_path = dir_path.join(secondary_path_str.as_slice());
4348 let default_exists = default_path.exists();
4349 let secondary_exists = secondary_path.exists();
4351 if !self.owns_directory {
4352 self.span_err(id_sp,
4353 "cannot declare a new module at this location");
4354 let this_module = match self.mod_path_stack.last() {
4355 Some(name) => name.get().to_string(),
4356 None => self.root_module_name.get_ref().clone(),
4358 self.span_note(id_sp,
4359 format!("maybe move this module `{0}` \
4360 to its own directory via \
4362 this_module).as_slice());
4363 if default_exists || secondary_exists {
4364 self.span_note(id_sp,
4365 format!("... or maybe `use` the module \
4366 `{}` instead of possibly \
4368 mod_name).as_slice());
4370 self.abort_if_errors();
4373 match (default_exists, secondary_exists) {
4374 (true, false) => (default_path, false),
4375 (false, true) => (secondary_path, true),
4377 self.span_fatal(id_sp,
4378 format!("file not found for module \
4380 mod_name).as_slice());
4385 format!("file for module `{}` found at both {} \
4389 secondary_path_str).as_slice());
4395 self.eval_src_mod_from_path(file_path, owns_directory,
4396 mod_string.get().to_string(), id_sp)
4399 fn eval_src_mod_from_path(&mut self,
4401 owns_directory: bool,
4403 id_sp: Span) -> (ast::Item_, Vec<ast::Attribute> ) {
4404 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
4405 match included_mod_stack.iter().position(|p| *p == path) {
4407 let mut err = String::from_str("circular modules: ");
4408 let len = included_mod_stack.len();
4409 for p in included_mod_stack.slice(i, len).iter() {
4410 err.push_str(p.display().as_maybe_owned().as_slice());
4411 err.push_str(" -> ");
4413 err.push_str(path.display().as_maybe_owned().as_slice());
4414 self.span_fatal(id_sp, err.as_slice());
4418 included_mod_stack.push(path.clone());
4419 drop(included_mod_stack);
4422 new_sub_parser_from_file(self.sess,
4428 let mod_inner_lo = p0.span.lo;
4429 let (mod_attrs, next) = p0.parse_inner_attrs_and_next();
4430 let first_item_outer_attrs = next;
4431 let m0 = p0.parse_mod_items(token::EOF, first_item_outer_attrs, mod_inner_lo);
4432 self.sess.included_mod_stack.borrow_mut().pop();
4433 return (ast::ItemMod(m0), mod_attrs);
4436 // parse a function declaration from a foreign module
4437 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility,
4438 attrs: Vec<Attribute>) -> Gc<ForeignItem> {
4439 let lo = self.span.lo;
4440 self.expect_keyword(keywords::Fn);
4442 let (ident, generics) = self.parse_fn_header();
4443 let decl = self.parse_fn_decl(true);
4444 let hi = self.span.hi;
4445 self.expect(&token::SEMI);
4446 box(GC) ast::ForeignItem { ident: ident,
4448 node: ForeignItemFn(decl, generics),
4449 id: ast::DUMMY_NODE_ID,
4450 span: mk_sp(lo, hi),
4454 // parse a static item from a foreign module
4455 fn parse_item_foreign_static(&mut self, vis: ast::Visibility,
4456 attrs: Vec<Attribute> ) -> Gc<ForeignItem> {
4457 let lo = self.span.lo;
4459 self.expect_keyword(keywords::Static);
4460 let mutbl = self.eat_keyword(keywords::Mut);
4462 let ident = self.parse_ident();
4463 self.expect(&token::COLON);
4464 let ty = self.parse_ty(true);
4465 let hi = self.span.hi;
4466 self.expect(&token::SEMI);
4467 box(GC) ast::ForeignItem {
4470 node: ForeignItemStatic(ty, mutbl),
4471 id: ast::DUMMY_NODE_ID,
4472 span: mk_sp(lo, hi),
4477 // parse safe/unsafe and fn
4478 fn parse_fn_style(&mut self) -> FnStyle {
4479 if self.eat_keyword(keywords::Fn) { NormalFn }
4480 else if self.eat_keyword(keywords::Unsafe) {
4481 self.expect_keyword(keywords::Fn);
4484 else { self.unexpected(); }
4488 // at this point, this is essentially a wrapper for
4489 // parse_foreign_items.
4490 fn parse_foreign_mod_items(&mut self,
4492 first_item_attrs: Vec<Attribute> )
4494 let ParsedItemsAndViewItems {
4495 attrs_remaining: attrs_remaining,
4496 view_items: view_items,
4498 foreign_items: foreign_items
4499 } = self.parse_foreign_items(first_item_attrs, true);
4500 if ! attrs_remaining.is_empty() {
4501 let last_span = self.last_span;
4502 self.span_err(last_span,
4503 "expected item after attributes");
4505 assert!(self.token == token::RBRACE);
4508 view_items: view_items,
4509 items: foreign_items
4513 /// Parse extern crate links
4517 /// extern crate url;
4518 /// extern crate foo = "bar";
4519 fn parse_item_extern_crate(&mut self,
4521 visibility: Visibility,
4522 attrs: Vec<Attribute> )
4525 let (maybe_path, ident) = match self.token {
4526 token::IDENT(..) => {
4527 let the_ident = self.parse_ident();
4528 self.expect_one_of(&[], &[token::EQ, token::SEMI]);
4529 let path = if self.token == token::EQ {
4531 Some(self.parse_str())
4534 self.expect(&token::SEMI);
4538 let span = self.span;
4539 let token_str = self.this_token_to_str();
4540 self.span_fatal(span,
4541 format!("expected extern crate name but \
4543 token_str).as_slice());
4547 IoviViewItem(ast::ViewItem {
4548 node: ViewItemExternCrate(ident, maybe_path, ast::DUMMY_NODE_ID),
4551 span: mk_sp(lo, self.last_span.hi)
4555 /// Parse `extern` for foreign ABIs
4558 /// `extern` is expected to have been
4559 /// consumed before calling this method
4565 fn parse_item_foreign_mod(&mut self,
4567 opt_abi: Option<abi::Abi>,
4568 visibility: Visibility,
4569 attrs: Vec<Attribute> )
4572 self.expect(&token::LBRACE);
4574 let abi = opt_abi.unwrap_or(abi::C);
4576 let (inner, next) = self.parse_inner_attrs_and_next();
4577 let m = self.parse_foreign_mod_items(abi, next);
4578 self.expect(&token::RBRACE);
4580 let last_span = self.last_span;
4581 let item = self.mk_item(lo,
4583 special_idents::invalid,
4586 maybe_append(attrs, Some(inner)));
4587 return IoviItem(item);
4590 // parse type Foo = Bar;
4591 fn parse_item_type(&mut self) -> ItemInfo {
4592 let ident = self.parse_ident();
4593 let tps = self.parse_generics();
4594 self.expect(&token::EQ);
4595 let ty = self.parse_ty(true);
4596 self.expect(&token::SEMI);
4597 (ident, ItemTy(ty, tps), None)
4600 // parse a structure-like enum variant definition
4601 // this should probably be renamed or refactored...
4602 fn parse_struct_def(&mut self) -> Gc<StructDef> {
4603 let mut fields: Vec<StructField> = Vec::new();
4604 while self.token != token::RBRACE {
4605 fields.push(self.parse_struct_decl_field());
4609 return box(GC) ast::StructDef {
4617 // parse the part of an "enum" decl following the '{'
4618 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> EnumDef {
4619 let mut variants = Vec::new();
4620 let mut all_nullary = true;
4621 let mut have_disr = false;
4622 while self.token != token::RBRACE {
4623 let variant_attrs = self.parse_outer_attributes();
4624 let vlo = self.span.lo;
4626 let vis = self.parse_visibility();
4630 let mut args = Vec::new();
4631 let mut disr_expr = None;
4632 ident = self.parse_ident();
4633 if self.eat(&token::LBRACE) {
4634 // Parse a struct variant.
4635 all_nullary = false;
4636 kind = StructVariantKind(self.parse_struct_def());
4637 } else if self.token == token::LPAREN {
4638 all_nullary = false;
4639 let arg_tys = self.parse_enum_variant_seq(
4642 seq_sep_trailing_disallowed(token::COMMA),
4643 |p| p.parse_ty(true)
4645 for ty in arg_tys.move_iter() {
4646 args.push(ast::VariantArg {
4648 id: ast::DUMMY_NODE_ID,
4651 kind = TupleVariantKind(args);
4652 } else if self.eat(&token::EQ) {
4654 disr_expr = Some(self.parse_expr());
4655 kind = TupleVariantKind(args);
4657 kind = TupleVariantKind(Vec::new());
4660 let vr = ast::Variant_ {
4662 attrs: variant_attrs,
4664 id: ast::DUMMY_NODE_ID,
4665 disr_expr: disr_expr,
4668 variants.push(P(spanned(vlo, self.last_span.hi, vr)));
4670 if !self.eat(&token::COMMA) { break; }
4672 self.expect(&token::RBRACE);
4673 if have_disr && !all_nullary {
4674 self.fatal("discriminator values can only be used with a c-like \
4678 ast::EnumDef { variants: variants }
4681 // parse an "enum" declaration
4682 fn parse_item_enum(&mut self) -> ItemInfo {
4683 let id = self.parse_ident();
4684 let generics = self.parse_generics();
4685 self.expect(&token::LBRACE);
4687 let enum_definition = self.parse_enum_def(&generics);
4688 (id, ItemEnum(enum_definition, generics), None)
4691 fn fn_expr_lookahead(tok: &token::Token) -> bool {
4693 token::LPAREN | token::AT | token::TILDE | token::BINOP(_) => true,
4698 // Parses a string as an ABI spec on an extern type or module. Consumes
4699 // the `extern` keyword, if one is found.
4700 fn parse_opt_abi(&mut self) -> Option<abi::Abi> {
4702 token::LIT_STR(s) | token::LIT_STR_RAW(s, _) => {
4704 let identifier_string = token::get_ident(s);
4705 let the_string = identifier_string.get();
4706 match abi::lookup(the_string) {
4707 Some(abi) => Some(abi),
4709 let last_span = self.last_span;
4712 format!("illegal ABI: expected one of [{}], \
4714 abi::all_names().connect(", "),
4715 the_string).as_slice());
4725 // parse one of the items or view items allowed by the
4726 // flags; on failure, return IoviNone.
4727 // NB: this function no longer parses the items inside an
4729 fn parse_item_or_view_item(&mut self,
4730 attrs: Vec<Attribute> ,
4731 macros_allowed: bool)
4734 INTERPOLATED(token::NtItem(item)) => {
4736 let new_attrs = attrs.append(item.attrs.as_slice());
4737 return IoviItem(box(GC) Item {
4745 let lo = self.span.lo;
4747 let visibility = self.parse_visibility();
4749 // must be a view item:
4750 if self.eat_keyword(keywords::Use) {
4751 // USE ITEM (IoviViewItem)
4752 let view_item = self.parse_use();
4753 self.expect(&token::SEMI);
4754 return IoviViewItem(ast::ViewItem {
4758 span: mk_sp(lo, self.last_span.hi)
4761 // either a view item or an item:
4762 if self.eat_keyword(keywords::Extern) {
4763 let next_is_mod = self.eat_keyword(keywords::Mod);
4765 if next_is_mod || self.eat_keyword(keywords::Crate) {
4767 let last_span = self.last_span;
4768 self.span_err(mk_sp(lo, last_span.hi),
4769 format!("`extern mod` is obsolete, use \
4770 `extern crate` instead \
4771 to refer to external \
4772 crates.").as_slice())
4774 return self.parse_item_extern_crate(lo, visibility, attrs);
4777 let opt_abi = self.parse_opt_abi();
4779 if self.eat_keyword(keywords::Fn) {
4780 // EXTERN FUNCTION ITEM
4781 let abi = opt_abi.unwrap_or(abi::C);
4782 let (ident, item_, extra_attrs) =
4783 self.parse_item_fn(NormalFn, abi);
4784 let last_span = self.last_span;
4785 let item = self.mk_item(lo,
4790 maybe_append(attrs, extra_attrs));
4791 return IoviItem(item);
4792 } else if self.token == token::LBRACE {
4793 return self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs);
4796 let span = self.span;
4797 let token_str = self.this_token_to_str();
4798 self.span_fatal(span,
4799 format!("expected `{}` or `fn` but found `{}`", "{",
4800 token_str).as_slice());
4803 let is_virtual = self.eat_keyword(keywords::Virtual);
4804 if is_virtual && !self.is_keyword(keywords::Struct) {
4805 let span = self.span;
4807 "`virtual` keyword may only be used with `struct`");
4810 // the rest are all guaranteed to be items:
4811 if self.is_keyword(keywords::Static) {
4814 let (ident, item_, extra_attrs) = self.parse_item_const();
4815 let last_span = self.last_span;
4816 let item = self.mk_item(lo,
4821 maybe_append(attrs, extra_attrs));
4822 return IoviItem(item);
4824 if self.is_keyword(keywords::Fn) &&
4825 self.look_ahead(1, |f| !Parser::fn_expr_lookahead(f)) {
4828 let (ident, item_, extra_attrs) =
4829 self.parse_item_fn(NormalFn, abi::Rust);
4830 let last_span = self.last_span;
4831 let item = self.mk_item(lo,
4836 maybe_append(attrs, extra_attrs));
4837 return IoviItem(item);
4839 if self.is_keyword(keywords::Unsafe)
4840 && self.look_ahead(1u, |t| *t != token::LBRACE) {
4841 // UNSAFE FUNCTION ITEM
4843 let abi = if self.eat_keyword(keywords::Extern) {
4844 self.parse_opt_abi().unwrap_or(abi::C)
4848 self.expect_keyword(keywords::Fn);
4849 let (ident, item_, extra_attrs) =
4850 self.parse_item_fn(UnsafeFn, abi);
4851 let last_span = self.last_span;
4852 let item = self.mk_item(lo,
4857 maybe_append(attrs, extra_attrs));
4858 return IoviItem(item);
4860 if self.eat_keyword(keywords::Mod) {
4862 let (ident, item_, extra_attrs) =
4863 self.parse_item_mod(attrs.as_slice());
4864 let last_span = self.last_span;
4865 let item = self.mk_item(lo,
4870 maybe_append(attrs, extra_attrs));
4871 return IoviItem(item);
4873 if self.eat_keyword(keywords::Type) {
4875 let (ident, item_, extra_attrs) = self.parse_item_type();
4876 let last_span = self.last_span;
4877 let item = self.mk_item(lo,
4882 maybe_append(attrs, extra_attrs));
4883 return IoviItem(item);
4885 if self.eat_keyword(keywords::Enum) {
4887 let (ident, item_, extra_attrs) = self.parse_item_enum();
4888 let last_span = self.last_span;
4889 let item = self.mk_item(lo,
4894 maybe_append(attrs, extra_attrs));
4895 return IoviItem(item);
4897 if self.eat_keyword(keywords::Trait) {
4899 let (ident, item_, extra_attrs) = self.parse_item_trait();
4900 let last_span = self.last_span;
4901 let item = self.mk_item(lo,
4906 maybe_append(attrs, extra_attrs));
4907 return IoviItem(item);
4909 if self.eat_keyword(keywords::Impl) {
4911 let (ident, item_, extra_attrs) = self.parse_item_impl();
4912 let last_span = self.last_span;
4913 let item = self.mk_item(lo,
4918 maybe_append(attrs, extra_attrs));
4919 return IoviItem(item);
4921 if self.eat_keyword(keywords::Struct) {
4923 let (ident, item_, extra_attrs) = self.parse_item_struct(is_virtual);
4924 let last_span = self.last_span;
4925 let item = self.mk_item(lo,
4930 maybe_append(attrs, extra_attrs));
4931 return IoviItem(item);
4933 self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility)
4936 // parse a foreign item; on failure, return IoviNone.
4937 fn parse_foreign_item(&mut self,
4938 attrs: Vec<Attribute> ,
4939 macros_allowed: bool)
4941 maybe_whole!(iovi self, NtItem);
4942 let lo = self.span.lo;
4944 let visibility = self.parse_visibility();
4946 if self.is_keyword(keywords::Static) {
4947 // FOREIGN STATIC ITEM
4948 let item = self.parse_item_foreign_static(visibility, attrs);
4949 return IoviForeignItem(item);
4951 if self.is_keyword(keywords::Fn) || self.is_keyword(keywords::Unsafe) {
4952 // FOREIGN FUNCTION ITEM
4953 let item = self.parse_item_foreign_fn(visibility, attrs);
4954 return IoviForeignItem(item);
4956 self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility)
4959 // this is the fall-through for parsing items.
4960 fn parse_macro_use_or_failure(
4962 attrs: Vec<Attribute> ,
4963 macros_allowed: bool,
4965 visibility: Visibility
4966 ) -> ItemOrViewItem {
4967 if macros_allowed && !token::is_any_keyword(&self.token)
4968 && self.look_ahead(1, |t| *t == token::NOT)
4969 && (self.look_ahead(2, |t| is_plain_ident(t))
4970 || self.look_ahead(2, |t| *t == token::LPAREN)
4971 || self.look_ahead(2, |t| *t == token::LBRACE)) {
4972 // MACRO INVOCATION ITEM
4975 let pth = self.parse_path(NoTypesAllowed).path;
4976 self.expect(&token::NOT);
4978 // a 'special' identifier (like what `macro_rules!` uses)
4979 // is optional. We should eventually unify invoc syntax
4981 let id = if is_plain_ident(&self.token) {
4984 token::special_idents::invalid // no special identifier
4986 // eat a matched-delimiter token tree:
4987 let tts = match token::close_delimiter_for(&self.token) {
4990 self.parse_seq_to_end(&ket,
4992 |p| p.parse_token_tree())
4994 None => self.fatal("expected open delimiter")
4996 // single-variant-enum... :
4997 let m = ast::MacInvocTT(pth, tts, EMPTY_CTXT);
4998 let m: ast::Mac = codemap::Spanned { node: m,
4999 span: mk_sp(self.span.lo,
5001 let item_ = ItemMac(m);
5002 let last_span = self.last_span;
5003 let item = self.mk_item(lo,
5009 return IoviItem(item);
5012 // FAILURE TO PARSE ITEM
5013 if visibility != Inherited {
5014 let mut s = String::from_str("unmatched visibility `");
5015 if visibility == Public {
5021 let last_span = self.last_span;
5022 self.span_fatal(last_span, s.as_slice());
5024 return IoviNone(attrs);
5027 pub fn parse_item_with_outer_attributes(&mut self) -> Option<Gc<Item>> {
5028 let attrs = self.parse_outer_attributes();
5029 self.parse_item(attrs)
5032 pub fn parse_item(&mut self, attrs: Vec<Attribute> ) -> Option<Gc<Item>> {
5033 match self.parse_item_or_view_item(attrs, true) {
5034 IoviNone(_) => None,
5036 self.fatal("view items are not allowed here"),
5037 IoviForeignItem(_) =>
5038 self.fatal("foreign items are not allowed here"),
5039 IoviItem(item) => Some(item)
5043 // parse, e.g., "use a::b::{z,y}"
5044 fn parse_use(&mut self) -> ViewItem_ {
5045 return ViewItemUse(self.parse_view_path());
5049 // matches view_path : MOD? IDENT EQ non_global_path
5050 // | MOD? non_global_path MOD_SEP LBRACE RBRACE
5051 // | MOD? non_global_path MOD_SEP LBRACE ident_seq RBRACE
5052 // | MOD? non_global_path MOD_SEP STAR
5053 // | MOD? non_global_path
5054 fn parse_view_path(&mut self) -> Gc<ViewPath> {
5055 let lo = self.span.lo;
5057 if self.token == token::LBRACE {
5059 let idents = self.parse_unspanned_seq(
5060 &token::LBRACE, &token::RBRACE,
5061 seq_sep_trailing_allowed(token::COMMA),
5062 |p| p.parse_path_list_ident());
5063 let path = ast::Path {
5064 span: mk_sp(lo, self.span.hi),
5066 segments: Vec::new()
5068 return box(GC) spanned(lo, self.span.hi,
5069 ViewPathList(path, idents, ast::DUMMY_NODE_ID));
5072 let first_ident = self.parse_ident();
5073 let mut path = vec!(first_ident);
5078 let path_lo = self.span.lo;
5079 path = vec!(self.parse_ident());
5080 while self.token == token::MOD_SEP {
5082 let id = self.parse_ident();
5085 let path = ast::Path {
5086 span: mk_sp(path_lo, self.span.hi),
5088 segments: path.move_iter().map(|identifier| {
5090 identifier: identifier,
5091 lifetimes: Vec::new(),
5092 types: OwnedSlice::empty(),
5096 return box(GC) spanned(lo, self.span.hi,
5097 ViewPathSimple(first_ident, path,
5098 ast::DUMMY_NODE_ID));
5102 // foo::bar or foo::{a,b,c} or foo::*
5103 while self.token == token::MOD_SEP {
5107 token::IDENT(i, _) => {
5112 // foo::bar::{a,b,c}
5114 let idents = self.parse_unspanned_seq(
5117 seq_sep_trailing_allowed(token::COMMA),
5118 |p| p.parse_path_list_ident()
5120 let path = ast::Path {
5121 span: mk_sp(lo, self.span.hi),
5123 segments: path.move_iter().map(|identifier| {
5125 identifier: identifier,
5126 lifetimes: Vec::new(),
5127 types: OwnedSlice::empty(),
5131 return box(GC) spanned(lo, self.span.hi,
5132 ViewPathList(path, idents, ast::DUMMY_NODE_ID));
5136 token::BINOP(token::STAR) => {
5138 let path = ast::Path {
5139 span: mk_sp(lo, self.span.hi),
5141 segments: path.move_iter().map(|identifier| {
5143 identifier: identifier,
5144 lifetimes: Vec::new(),
5145 types: OwnedSlice::empty(),
5149 return box(GC) spanned(lo, self.span.hi,
5150 ViewPathGlob(path, ast::DUMMY_NODE_ID));
5159 let last = *path.get(path.len() - 1u);
5160 let path = ast::Path {
5161 span: mk_sp(lo, self.span.hi),
5163 segments: path.move_iter().map(|identifier| {
5165 identifier: identifier,
5166 lifetimes: Vec::new(),
5167 types: OwnedSlice::empty(),
5171 return box(GC) spanned(lo,
5173 ViewPathSimple(last, path, ast::DUMMY_NODE_ID));
5176 // Parses a sequence of items. Stops when it finds program
5177 // text that can't be parsed as an item
5178 // - mod_items uses extern_mod_allowed = true
5179 // - block_tail_ uses extern_mod_allowed = false
5180 fn parse_items_and_view_items(&mut self,
5181 first_item_attrs: Vec<Attribute> ,
5182 mut extern_mod_allowed: bool,
5183 macros_allowed: bool)
5184 -> ParsedItemsAndViewItems {
5185 let mut attrs = first_item_attrs.append(self.parse_outer_attributes().as_slice());
5186 // First, parse view items.
5187 let mut view_items : Vec<ast::ViewItem> = Vec::new();
5188 let mut items = Vec::new();
5190 // I think this code would probably read better as a single
5191 // loop with a mutable three-state-variable (for extern crates,
5192 // view items, and regular items) ... except that because
5193 // of macros, I'd like to delay that entire check until later.
5195 match self.parse_item_or_view_item(attrs, macros_allowed) {
5196 IoviNone(attrs) => {
5197 return ParsedItemsAndViewItems {
5198 attrs_remaining: attrs,
5199 view_items: view_items,
5201 foreign_items: Vec::new()
5204 IoviViewItem(view_item) => {
5205 match view_item.node {
5206 ViewItemUse(..) => {
5207 // `extern crate` must precede `use`.
5208 extern_mod_allowed = false;
5210 ViewItemExternCrate(..) if !extern_mod_allowed => {
5211 self.span_err(view_item.span,
5212 "\"extern crate\" declarations are \
5215 ViewItemExternCrate(..) => {}
5217 view_items.push(view_item);
5221 attrs = self.parse_outer_attributes();
5224 IoviForeignItem(_) => {
5228 attrs = self.parse_outer_attributes();
5231 // Next, parse items.
5233 match self.parse_item_or_view_item(attrs, macros_allowed) {
5234 IoviNone(returned_attrs) => {
5235 attrs = returned_attrs;
5238 IoviViewItem(view_item) => {
5239 attrs = self.parse_outer_attributes();
5240 self.span_err(view_item.span,
5241 "`use` and `extern crate` declarations must precede items");
5244 attrs = self.parse_outer_attributes();
5247 IoviForeignItem(_) => {
5253 ParsedItemsAndViewItems {
5254 attrs_remaining: attrs,
5255 view_items: view_items,
5257 foreign_items: Vec::new()
5261 // Parses a sequence of foreign items. Stops when it finds program
5262 // text that can't be parsed as an item
5263 fn parse_foreign_items(&mut self, first_item_attrs: Vec<Attribute> ,
5264 macros_allowed: bool)
5265 -> ParsedItemsAndViewItems {
5266 let mut attrs = first_item_attrs.append(self.parse_outer_attributes().as_slice());
5267 let mut foreign_items = Vec::new();
5269 match self.parse_foreign_item(attrs, macros_allowed) {
5270 IoviNone(returned_attrs) => {
5271 if self.token == token::RBRACE {
5272 attrs = returned_attrs;
5277 IoviViewItem(view_item) => {
5278 // I think this can't occur:
5279 self.span_err(view_item.span,
5280 "`use` and `extern crate` declarations must precede items");
5283 // FIXME #5668: this will occur for a macro invocation:
5284 self.span_fatal(item.span, "macros cannot expand to foreign items");
5286 IoviForeignItem(foreign_item) => {
5287 foreign_items.push(foreign_item);
5290 attrs = self.parse_outer_attributes();
5293 ParsedItemsAndViewItems {
5294 attrs_remaining: attrs,
5295 view_items: Vec::new(),
5297 foreign_items: foreign_items
5301 // Parses a source module as a crate. This is the main
5302 // entry point for the parser.
5303 pub fn parse_crate_mod(&mut self) -> Crate {
5304 let lo = self.span.lo;
5305 // parse the crate's inner attrs, maybe (oops) one
5306 // of the attrs of an item:
5307 let (inner, next) = self.parse_inner_attrs_and_next();
5308 let first_item_outer_attrs = next;
5309 // parse the items inside the crate:
5310 let m = self.parse_mod_items(token::EOF, first_item_outer_attrs, lo);
5315 config: self.cfg.clone(),
5316 span: mk_sp(lo, self.span.lo)
5320 pub fn parse_optional_str(&mut self)
5321 -> Option<(InternedString, ast::StrStyle)> {
5322 let (s, style) = match self.token {
5323 token::LIT_STR(s) => (self.id_to_interned_str(s), ast::CookedStr),
5324 token::LIT_STR_RAW(s, n) => {
5325 (self.id_to_interned_str(s), ast::RawStr(n))
5333 pub fn parse_str(&mut self) -> (InternedString, StrStyle) {
5334 match self.parse_optional_str() {
5336 _ => self.fatal("expected string literal")