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};
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;
84 #[allow(non_camel_case_types)]
85 #[deriving(PartialEq)]
86 pub enum restriction {
90 RESTRICT_NO_BAR_OR_DOUBLEBAR_OP,
93 type ItemInfo = (Ident, Item_, Option<Vec<Attribute> >);
95 /// How to parse a path. There are four different kinds of paths, all of which
96 /// are parsed somewhat differently.
97 #[deriving(PartialEq)]
98 pub enum PathParsingMode {
99 /// A path with no type parameters; e.g. `foo::bar::Baz`
101 /// A path with a lifetime and type parameters, with no double colons
102 /// before the type parameters; e.g. `foo::bar<'a>::Baz<T>`
103 LifetimeAndTypesWithoutColons,
104 /// A path with a lifetime and type parameters with double colons before
105 /// the type parameters; e.g. `foo::bar::<'a>::Baz::<T>`
106 LifetimeAndTypesWithColons,
107 /// A path with a lifetime and type parameters with bounds before the last
108 /// set of type parameters only; e.g. `foo::bar<'a>::Baz+X+Y<T>` This
109 /// form does not use extra double colons.
110 LifetimeAndTypesAndBounds,
113 /// A path paired with optional type bounds.
114 pub struct PathAndBounds {
116 pub bounds: Option<OwnedSlice<TyParamBound>>,
119 enum ItemOrViewItem {
120 // Indicates a failure to parse any kind of item. The attributes are
122 IoviNone(Vec<Attribute>),
124 IoviForeignItem(Gc<ForeignItem>),
125 IoviViewItem(ViewItem)
129 // Possibly accept an `INTERPOLATED` expression (a pre-parsed expression
130 // dropped into the token stream, which happens while parsing the
131 // result of macro expansion)
132 /* Placement of these is not as complex as I feared it would be.
133 The important thing is to make sure that lookahead doesn't balk
134 at INTERPOLATED tokens */
135 macro_rules! maybe_whole_expr (
138 let found = match $p.token {
139 INTERPOLATED(token::NtExpr(e)) => {
142 INTERPOLATED(token::NtPath(_)) => {
143 // FIXME: The following avoids an issue with lexical borrowck scopes,
144 // but the clone is unfortunate.
145 let pt = match $p.token {
146 INTERPOLATED(token::NtPath(ref pt)) => (**pt).clone(),
149 Some($p.mk_expr($p.span.lo, $p.span.hi, ExprPath(pt)))
151 INTERPOLATED(token::NtBlock(b)) => {
152 Some($p.mk_expr($p.span.lo, $p.span.hi, ExprBlock(b)))
167 // As above, but for things other than expressions
168 macro_rules! maybe_whole (
169 ($p:expr, $constructor:ident) => (
171 let found = match ($p).token {
172 INTERPOLATED(token::$constructor(_)) => {
173 Some(($p).bump_and_get())
178 Some(INTERPOLATED(token::$constructor(x))) => {
185 (no_clone $p:expr, $constructor:ident) => (
187 let found = match ($p).token {
188 INTERPOLATED(token::$constructor(_)) => {
189 Some(($p).bump_and_get())
194 Some(INTERPOLATED(token::$constructor(x))) => {
201 (deref $p:expr, $constructor:ident) => (
203 let found = match ($p).token {
204 INTERPOLATED(token::$constructor(_)) => {
205 Some(($p).bump_and_get())
210 Some(INTERPOLATED(token::$constructor(x))) => {
217 (Some $p:expr, $constructor:ident) => (
219 let found = match ($p).token {
220 INTERPOLATED(token::$constructor(_)) => {
221 Some(($p).bump_and_get())
226 Some(INTERPOLATED(token::$constructor(x))) => {
227 return Some(x.clone()),
233 (iovi $p:expr, $constructor:ident) => (
235 let found = match ($p).token {
236 INTERPOLATED(token::$constructor(_)) => {
237 Some(($p).bump_and_get())
242 Some(INTERPOLATED(token::$constructor(x))) => {
243 return IoviItem(x.clone())
249 (pair_empty $p:expr, $constructor:ident) => (
251 let found = match ($p).token {
252 INTERPOLATED(token::$constructor(_)) => {
253 Some(($p).bump_and_get())
258 Some(INTERPOLATED(token::$constructor(x))) => {
259 return (Vec::new(), x)
268 fn maybe_append(lhs: Vec<Attribute> , rhs: Option<Vec<Attribute> >)
272 Some(ref attrs) => lhs.append(attrs.as_slice())
277 struct ParsedItemsAndViewItems {
278 attrs_remaining: Vec<Attribute>,
279 view_items: Vec<ViewItem>,
280 items: Vec<Gc<Item>>,
281 foreign_items: Vec<Gc<ForeignItem>>
284 /* ident is handled by common.rs */
286 pub struct Parser<'a> {
287 pub sess: &'a ParseSess,
288 // the current token:
289 pub token: token::Token,
290 // the span of the current token:
292 // the span of the prior token:
294 pub cfg: CrateConfig,
295 // the previous token or None (only stashed sometimes).
296 pub last_token: Option<Box<token::Token>>,
297 pub buffer: [TokenAndSpan, ..4],
298 pub buffer_start: int,
300 pub tokens_consumed: uint,
301 pub restriction: restriction,
302 pub quote_depth: uint, // not (yet) related to the quasiquoter
303 pub reader: Box<Reader:>,
304 pub interner: Rc<token::IdentInterner>,
305 /// The set of seen errors about obsolete syntax. Used to suppress
306 /// extra detail when the same error is seen twice
307 pub obsolete_set: HashSet<ObsoleteSyntax>,
308 /// Used to determine the path to externally loaded source files
309 pub mod_path_stack: Vec<InternedString>,
310 /// Stack of spans of open delimiters. Used for error message.
311 pub open_braces: Vec<Span>,
312 /// Flag if this parser "owns" the directory that it is currently parsing
313 /// in. This will affect how nested files are looked up.
314 pub owns_directory: bool,
315 /// Name of the root module this parser originated from. If `None`, then the
316 /// name is not known. This does not change while the parser is descending
317 /// into modules, and sub-parsers have new values for this name.
318 pub root_module_name: Option<String>,
321 fn is_plain_ident_or_underscore(t: &token::Token) -> bool {
322 is_plain_ident(t) || *t == token::UNDERSCORE
325 impl<'a> Parser<'a> {
326 pub fn new(sess: &'a ParseSess, cfg: ast::CrateConfig, mut rdr: Box<Reader:>) -> Parser<'a> {
327 let tok0 = rdr.next_token();
329 let placeholder = TokenAndSpan {
330 tok: token::UNDERSCORE,
336 interner: token::get_ident_interner(),
352 restriction: UNRESTRICTED,
354 obsolete_set: HashSet::new(),
355 mod_path_stack: Vec::new(),
356 open_braces: Vec::new(),
357 owns_directory: true,
358 root_module_name: None,
361 // convert a token to a string using self's reader
362 pub fn token_to_str(token: &token::Token) -> String {
366 // convert the current token to a string using self's reader
367 pub fn this_token_to_str(&mut self) -> String {
368 Parser::token_to_str(&self.token)
371 pub fn unexpected_last(&mut self, t: &token::Token) -> ! {
372 let token_str = Parser::token_to_str(t);
373 self.span_fatal(self.last_span, format!("unexpected token: `{}`",
374 token_str).as_slice());
377 pub fn unexpected(&mut self) -> ! {
378 let this_token = self.this_token_to_str();
379 self.fatal(format!("unexpected token: `{}`", this_token).as_slice());
382 // expect and consume the token t. Signal an error if
383 // the next token is not t.
384 pub fn expect(&mut self, t: &token::Token) {
385 if self.token == *t {
388 let token_str = Parser::token_to_str(t);
389 let this_token_str = self.this_token_to_str();
390 self.fatal(format!("expected `{}` but found `{}`",
392 this_token_str).as_slice())
396 // Expect next token to be edible or inedible token. If edible,
397 // then consume it; if inedible, then return without consuming
398 // anything. Signal a fatal error if next token is unexpected.
399 pub fn expect_one_of(&mut self,
400 edible: &[token::Token],
401 inedible: &[token::Token]) {
402 fn tokens_to_str(tokens: &[token::Token]) -> String {
403 let mut i = tokens.iter();
404 // This might be a sign we need a connect method on Iterator.
406 .map_or("".to_string(), |t| Parser::token_to_str(t));
410 b.push_str(Parser::token_to_str(a).as_slice());
414 if edible.contains(&self.token) {
416 } else if inedible.contains(&self.token) {
417 // leave it in the input
419 let expected = edible.iter().map(|x| (*x).clone()).collect::<Vec<_>>().append(inedible);
420 let expect = tokens_to_str(expected.as_slice());
421 let actual = self.this_token_to_str();
423 (if expected.len() != 1 {
424 (format!("expected one of `{}` but found `{}`",
428 (format!("expected `{}` but found `{}`",
436 // Check for erroneous `ident { }`; if matches, signal error and
437 // recover (without consuming any expected input token). Returns
438 // true if and only if input was consumed for recovery.
439 pub fn check_for_erroneous_unit_struct_expecting(&mut self, expected: &[token::Token]) -> bool {
440 if self.token == token::LBRACE
441 && expected.iter().all(|t| *t != token::LBRACE)
442 && self.look_ahead(1, |t| *t == token::RBRACE) {
443 // matched; signal non-fatal error and recover.
444 self.span_err(self.span,
445 "unit-like struct construction is written with no trailing `{ }`");
446 self.eat(&token::LBRACE);
447 self.eat(&token::RBRACE);
454 // Commit to parsing a complete expression `e` expected to be
455 // followed by some token from the set edible + inedible. Recover
456 // from anticipated input errors, discarding erroneous characters.
457 pub fn commit_expr(&mut self, e: Gc<Expr>, edible: &[token::Token],
458 inedible: &[token::Token]) {
459 debug!("commit_expr {:?}", e);
462 // might be unit-struct construction; check for recoverableinput error.
463 let expected = edible.iter().map(|x| (*x).clone()).collect::<Vec<_>>()
465 self.check_for_erroneous_unit_struct_expecting(
466 expected.as_slice());
470 self.expect_one_of(edible, inedible)
473 pub fn commit_expr_expecting(&mut self, e: Gc<Expr>, edible: token::Token) {
474 self.commit_expr(e, &[edible], &[])
477 // Commit to parsing a complete statement `s`, which expects to be
478 // followed by some token from the set edible + inedible. Check
479 // for recoverable input errors, discarding erroneous characters.
480 pub fn commit_stmt(&mut self, s: Gc<Stmt>, edible: &[token::Token],
481 inedible: &[token::Token]) {
482 debug!("commit_stmt {:?}", s);
483 let _s = s; // unused, but future checks might want to inspect `s`.
484 if self.last_token.as_ref().map_or(false, |t| is_ident_or_path(*t)) {
485 let expected = edible.iter().map(|x| (*x).clone()).collect::<Vec<_>>()
486 .append(inedible.as_slice());
487 self.check_for_erroneous_unit_struct_expecting(
488 expected.as_slice());
490 self.expect_one_of(edible, inedible)
493 pub fn commit_stmt_expecting(&mut self, s: Gc<Stmt>, edible: token::Token) {
494 self.commit_stmt(s, &[edible], &[])
497 pub fn parse_ident(&mut self) -> ast::Ident {
498 self.check_strict_keywords();
499 self.check_reserved_keywords();
501 token::IDENT(i, _) => {
505 token::INTERPOLATED(token::NtIdent(..)) => {
506 self.bug("ident interpolation not converted to real token");
509 let token_str = self.this_token_to_str();
510 self.fatal((format!("expected ident, found `{}`",
511 token_str)).as_slice())
516 pub fn parse_path_list_ident(&mut self) -> ast::PathListIdent {
517 let lo = self.span.lo;
518 let ident = self.parse_ident();
519 let hi = self.last_span.hi;
520 spanned(lo, hi, ast::PathListIdent_ { name: ident,
521 id: ast::DUMMY_NODE_ID })
524 // consume token 'tok' if it exists. Returns true if the given
525 // token was present, false otherwise.
526 pub fn eat(&mut self, tok: &token::Token) -> bool {
527 let is_present = self.token == *tok;
528 if is_present { self.bump() }
532 pub fn is_keyword(&mut self, kw: keywords::Keyword) -> bool {
533 token::is_keyword(kw, &self.token)
536 // if the next token is the given keyword, eat it and return
537 // true. Otherwise, return false.
538 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
539 let is_kw = match self.token {
540 token::IDENT(sid, false) => kw.to_ident().name == sid.name,
543 if is_kw { self.bump() }
547 // if the given word is not a keyword, signal an error.
548 // if the next token is not the given word, signal an error.
549 // otherwise, eat it.
550 pub fn expect_keyword(&mut self, kw: keywords::Keyword) {
551 if !self.eat_keyword(kw) {
552 let id_interned_str = token::get_ident(kw.to_ident());
553 let token_str = self.this_token_to_str();
554 self.fatal(format!("expected `{}`, found `{}`",
555 id_interned_str, token_str).as_slice())
559 // signal an error if the given string is a strict keyword
560 pub fn check_strict_keywords(&mut self) {
561 if token::is_strict_keyword(&self.token) {
562 let token_str = self.this_token_to_str();
563 self.span_err(self.span,
564 format!("found `{}` in ident position",
565 token_str).as_slice());
569 // signal an error if the current token is a reserved keyword
570 pub fn check_reserved_keywords(&mut self) {
571 if token::is_reserved_keyword(&self.token) {
572 let token_str = self.this_token_to_str();
573 self.fatal(format!("`{}` is a reserved keyword",
574 token_str).as_slice())
578 // Expect and consume an `&`. If `&&` is seen, replace it with a single
579 // `&` and continue. If an `&` is not seen, signal an error.
580 fn expect_and(&mut self) {
582 token::BINOP(token::AND) => self.bump(),
584 let lo = self.span.lo + BytePos(1);
585 self.replace_token(token::BINOP(token::AND), lo, self.span.hi)
588 let token_str = self.this_token_to_str();
590 Parser::token_to_str(&token::BINOP(token::AND));
591 self.fatal(format!("expected `{}`, found `{}`",
593 token_str).as_slice())
598 // Expect and consume a `|`. If `||` is seen, replace it with a single
599 // `|` and continue. If a `|` is not seen, signal an error.
600 fn expect_or(&mut self) {
602 token::BINOP(token::OR) => self.bump(),
604 let lo = self.span.lo + BytePos(1);
605 self.replace_token(token::BINOP(token::OR), lo, self.span.hi)
608 let found_token = self.this_token_to_str();
610 Parser::token_to_str(&token::BINOP(token::OR));
611 self.fatal(format!("expected `{}`, found `{}`",
613 found_token).as_slice())
618 // Attempt to consume a `<`. If `<<` is seen, replace it with a single
619 // `<` and continue. If a `<` is not seen, return false.
621 // This is meant to be used when parsing generics on a path to get the
622 // starting token. The `force` parameter is used to forcefully break up a
623 // `<<` token. If `force` is false, then `<<` is only broken when a lifetime
624 // shows up next. For example, consider the expression:
626 // foo as bar << test
628 // The parser needs to know if `bar <<` is the start of a generic path or if
629 // it's a left-shift token. If `test` were a lifetime, then it's impossible
630 // for the token to be a left-shift, but if it's not a lifetime, then it's
631 // considered a left-shift.
633 // The reason for this is that the only current ambiguity with `<<` is when
634 // parsing closure types:
637 // impl Foo<<'a> ||>() { ... }
638 fn eat_lt(&mut self, force: bool) -> bool {
640 token::LT => { self.bump(); true }
641 token::BINOP(token::SHL) => {
642 let next_lifetime = self.look_ahead(1, |t| match *t {
643 token::LIFETIME(..) => true,
646 if force || next_lifetime {
647 let lo = self.span.lo + BytePos(1);
648 self.replace_token(token::LT, lo, self.span.hi);
658 fn expect_lt(&mut self) {
659 if !self.eat_lt(true) {
660 let found_token = self.this_token_to_str();
661 let token_str = Parser::token_to_str(&token::LT);
662 self.fatal(format!("expected `{}`, found `{}`",
664 found_token).as_slice())
668 // Parse a sequence bracketed by `|` and `|`, stopping before the `|`.
669 fn parse_seq_to_before_or<T>(
672 f: |&mut Parser| -> T)
674 let mut first = true;
675 let mut vector = Vec::new();
676 while self.token != token::BINOP(token::OR) &&
677 self.token != token::OROR {
689 // expect and consume a GT. if a >> is seen, replace it
690 // with a single > and continue. If a GT is not seen,
692 pub fn expect_gt(&mut self) {
694 token::GT => self.bump(),
695 token::BINOP(token::SHR) => {
696 let lo = self.span.lo + BytePos(1);
697 self.replace_token(token::GT, lo, self.span.hi)
700 let gt_str = Parser::token_to_str(&token::GT);
701 let this_token_str = self.this_token_to_str();
702 self.fatal(format!("expected `{}`, found `{}`",
704 this_token_str).as_slice())
709 // parse a sequence bracketed by '<' and '>', stopping
711 pub fn parse_seq_to_before_gt<T>(
713 sep: Option<token::Token>,
714 f: |&mut Parser| -> T)
716 let mut first = true;
717 let mut v = Vec::new();
718 while self.token != token::GT
719 && self.token != token::BINOP(token::SHR) {
722 if first { first = false; }
723 else { self.expect(t); }
729 return OwnedSlice::from_vec(v);
732 pub fn parse_seq_to_gt<T>(
734 sep: Option<token::Token>,
735 f: |&mut Parser| -> T)
737 let v = self.parse_seq_to_before_gt(sep, f);
742 // parse a sequence, including the closing delimiter. The function
743 // f must consume tokens until reaching the next separator or
745 pub fn parse_seq_to_end<T>(
749 f: |&mut Parser| -> T)
751 let val = self.parse_seq_to_before_end(ket, sep, f);
756 // parse a sequence, not including the closing delimiter. The function
757 // f must consume tokens until reaching the next separator or
759 pub fn parse_seq_to_before_end<T>(
763 f: |&mut Parser| -> T)
765 let mut first: bool = true;
767 while self.token != *ket {
770 if first { first = false; }
771 else { self.expect(t); }
775 if sep.trailing_sep_allowed && self.token == *ket { break; }
781 // parse a sequence, including the closing delimiter. The function
782 // f must consume tokens until reaching the next separator or
784 pub fn parse_unspanned_seq<T>(
789 f: |&mut Parser| -> T)
792 let result = self.parse_seq_to_before_end(ket, sep, f);
797 // parse a sequence parameter of enum variant. For consistency purposes,
798 // these should not be empty.
799 pub fn parse_enum_variant_seq<T>(
804 f: |&mut Parser| -> T)
806 let result = self.parse_unspanned_seq(bra, ket, sep, f);
807 if result.is_empty() {
808 self.span_err(self.last_span,
809 "nullary enum variants are written with no trailing `( )`");
814 // NB: Do not use this function unless you actually plan to place the
815 // spanned list in the AST.
821 f: |&mut Parser| -> T)
822 -> Spanned<Vec<T> > {
823 let lo = self.span.lo;
825 let result = self.parse_seq_to_before_end(ket, sep, f);
826 let hi = self.span.hi;
828 spanned(lo, hi, result)
831 // advance the parser by one token
832 pub fn bump(&mut self) {
833 self.last_span = self.span;
834 // Stash token for error recovery (sometimes; clone is not necessarily cheap).
835 self.last_token = if is_ident_or_path(&self.token) {
836 Some(box self.token.clone())
840 let next = if self.buffer_start == self.buffer_end {
841 self.reader.next_token()
843 // Avoid token copies with `replace`.
844 let buffer_start = self.buffer_start as uint;
845 let next_index = (buffer_start + 1) & 3 as uint;
846 self.buffer_start = next_index as int;
848 let placeholder = TokenAndSpan {
849 tok: token::UNDERSCORE,
852 replace(&mut self.buffer[buffer_start], placeholder)
855 self.token = next.tok;
856 self.tokens_consumed += 1u;
859 // Advance the parser by one token and return the bumped token.
860 pub fn bump_and_get(&mut self) -> token::Token {
861 let old_token = replace(&mut self.token, token::UNDERSCORE);
866 // EFFECT: replace the current token and span with the given one
867 pub fn replace_token(&mut self,
871 self.last_span = mk_sp(self.span.lo, lo);
873 self.span = mk_sp(lo, hi);
875 pub fn buffer_length(&mut self) -> int {
876 if self.buffer_start <= self.buffer_end {
877 return self.buffer_end - self.buffer_start;
879 return (4 - self.buffer_start) + self.buffer_end;
881 pub fn look_ahead<R>(&mut self, distance: uint, f: |&token::Token| -> R)
883 let dist = distance as int;
884 while self.buffer_length() < dist {
885 self.buffer[self.buffer_end as uint] = self.reader.next_token();
886 self.buffer_end = (self.buffer_end + 1) & 3;
888 f(&self.buffer[((self.buffer_start + dist - 1) & 3) as uint].tok)
890 pub fn fatal(&mut self, m: &str) -> ! {
891 self.sess.span_diagnostic.span_fatal(self.span, m)
893 pub fn span_fatal(&mut self, sp: Span, m: &str) -> ! {
894 self.sess.span_diagnostic.span_fatal(sp, m)
896 pub fn span_note(&mut self, sp: Span, m: &str) {
897 self.sess.span_diagnostic.span_note(sp, m)
899 pub fn bug(&mut self, m: &str) -> ! {
900 self.sess.span_diagnostic.span_bug(self.span, m)
902 pub fn warn(&mut self, m: &str) {
903 self.sess.span_diagnostic.span_warn(self.span, m)
905 pub fn span_warn(&mut self, sp: Span, m: &str) {
906 self.sess.span_diagnostic.span_warn(sp, m)
908 pub fn span_err(&mut self, sp: Span, m: &str) {
909 self.sess.span_diagnostic.span_err(sp, m)
911 pub fn abort_if_errors(&mut self) {
912 self.sess.span_diagnostic.handler().abort_if_errors();
915 pub fn id_to_interned_str(&mut self, id: Ident) -> InternedString {
919 // Is the current token one of the keywords that signals a bare function
921 pub fn token_is_bare_fn_keyword(&mut self) -> bool {
922 if token::is_keyword(keywords::Fn, &self.token) {
926 if token::is_keyword(keywords::Unsafe, &self.token) ||
927 token::is_keyword(keywords::Once, &self.token) {
928 return self.look_ahead(1, |t| token::is_keyword(keywords::Fn, t))
934 // Is the current token one of the keywords that signals a closure type?
935 pub fn token_is_closure_keyword(&mut self) -> bool {
936 token::is_keyword(keywords::Unsafe, &self.token) ||
937 token::is_keyword(keywords::Once, &self.token)
940 // Is the current token one of the keywords that signals an old-style
941 // closure type (with explicit sigil)?
942 pub fn token_is_old_style_closure_keyword(&mut self) -> bool {
943 token::is_keyword(keywords::Unsafe, &self.token) ||
944 token::is_keyword(keywords::Once, &self.token) ||
945 token::is_keyword(keywords::Fn, &self.token)
948 pub fn token_is_lifetime(tok: &token::Token) -> bool {
950 token::LIFETIME(..) => true,
955 pub fn get_lifetime(&mut self) -> ast::Ident {
957 token::LIFETIME(ref ident) => *ident,
958 _ => self.bug("not a lifetime"),
962 // parse a TyBareFn type:
963 pub fn parse_ty_bare_fn(&mut self) -> Ty_ {
966 [unsafe] [extern "ABI"] fn <'lt> (S) -> T
967 ^~~~^ ^~~~^ ^~~~^ ^~^ ^
976 let fn_style = self.parse_unsafety();
977 let abi = if self.eat_keyword(keywords::Extern) {
978 self.parse_opt_abi().unwrap_or(abi::C)
983 self.expect_keyword(keywords::Fn);
984 let (decl, lifetimes) = self.parse_ty_fn_decl(true);
985 return TyBareFn(box(GC) BareFnTy {
988 lifetimes: lifetimes,
993 // Parses a procedure type (`proc`). The initial `proc` keyword must
994 // already have been parsed.
995 pub fn parse_proc_type(&mut self) -> Ty_ {
998 proc <'lt> (S) [:Bounds] -> T
999 ^~~^ ^~~~^ ^ ^~~~~~~~^ ^
1009 let lifetimes = if self.eat(&token::LT) {
1010 let lifetimes = self.parse_lifetimes();
1017 let (inputs, variadic) = self.parse_fn_args(false, false);
1019 if self.eat(&token::COLON) {
1020 let (_, bounds) = self.parse_ty_param_bounds(false);
1026 let (ret_style, ret_ty) = self.parse_ret_ty();
1027 let decl = P(FnDecl {
1033 TyProc(box(GC) ClosureTy {
1038 lifetimes: lifetimes,
1042 // parse a TyClosure type
1043 pub fn parse_ty_closure(&mut self) -> Ty_ {
1046 [unsafe] [once] <'lt> |S| [:Bounds] -> T
1047 ^~~~~~~^ ^~~~~^ ^~~~^ ^ ^~~~~~~~^ ^
1049 | | | | | Return type
1050 | | | | Closure bounds
1051 | | | Argument types
1053 | Once-ness (a.k.a., affine)
1058 let fn_style = self.parse_unsafety();
1059 let onceness = if self.eat_keyword(keywords::Once) {Once} else {Many};
1061 let lifetimes = if self.eat(&token::LT) {
1062 let lifetimes = self.parse_lifetimes();
1070 let (is_unboxed, inputs) = if self.eat(&token::OROR) {
1075 let is_unboxed = self.token == token::BINOP(token::AND) &&
1076 self.look_ahead(1, |t| {
1077 token::is_keyword(keywords::Mut, t)
1079 self.look_ahead(2, |t| *t == token::COLON);
1086 let inputs = self.parse_seq_to_before_or(
1088 |p| p.parse_arg_general(false));
1090 (is_unboxed, inputs)
1093 let (region, bounds) = {
1094 if self.eat(&token::COLON) {
1095 let (region, bounds) = self.parse_ty_param_bounds(true);
1096 (region, Some(bounds))
1102 let (return_style, output) = self.parse_ret_ty();
1103 let decl = P(FnDecl {
1111 TyUnboxedFn(box(GC) UnboxedFnTy {
1115 TyClosure(box(GC) ClosureTy {
1120 lifetimes: lifetimes,
1125 pub fn parse_unsafety(&mut self) -> FnStyle {
1126 if self.eat_keyword(keywords::Unsafe) {
1133 // parse a function type (following the 'fn')
1134 pub fn parse_ty_fn_decl(&mut self, allow_variadic: bool)
1135 -> (P<FnDecl>, Vec<ast::Lifetime>) {
1146 let lifetimes = if self.eat(&token::LT) {
1147 let lifetimes = self.parse_lifetimes();
1154 let (inputs, variadic) = self.parse_fn_args(false, allow_variadic);
1155 let (ret_style, ret_ty) = self.parse_ret_ty();
1156 let decl = P(FnDecl {
1165 // parse the methods in a trait declaration
1166 pub fn parse_trait_methods(&mut self) -> Vec<TraitMethod> {
1167 self.parse_unspanned_seq(
1172 let attrs = p.parse_outer_attributes();
1175 // NB: at the moment, trait methods are public by default; this
1177 let vis = p.parse_visibility();
1178 let style = p.parse_fn_style();
1179 let ident = p.parse_ident();
1181 let generics = p.parse_generics();
1183 let (explicit_self, d) = p.parse_fn_decl_with_self(|p| {
1184 // This is somewhat dubious; We don't want to allow argument
1185 // names to be left off if there is a definition...
1186 p.parse_arg_general(false)
1189 let hi = p.last_span.hi;
1193 debug!("parse_trait_methods(): parsing required method");
1194 Required(TypeMethod {
1200 explicit_self: explicit_self,
1201 id: ast::DUMMY_NODE_ID,
1202 span: mk_sp(lo, hi),
1207 debug!("parse_trait_methods(): parsing provided method");
1208 let (inner_attrs, body) =
1209 p.parse_inner_attrs_and_block();
1210 let attrs = attrs.append(inner_attrs.as_slice());
1211 Provided(box(GC) ast::Method {
1215 explicit_self: explicit_self,
1219 id: ast::DUMMY_NODE_ID,
1220 span: mk_sp(lo, hi),
1227 let token_str = p.this_token_to_str();
1228 p.fatal((format!("expected `;` or `\\{` but found `{}`",
1229 token_str)).as_slice())
1233 let token_str = p.this_token_to_str();
1234 p.fatal((format!("expected `;` or `{{` but found `{}`",
1235 token_str)).as_slice())
1241 // parse a possibly mutable type
1242 pub fn parse_mt(&mut self) -> MutTy {
1243 let mutbl = self.parse_mutability();
1244 let t = self.parse_ty(true);
1245 MutTy { ty: t, mutbl: mutbl }
1248 // parse [mut/const/imm] ID : TY
1249 // now used only by obsolete record syntax parser...
1250 pub fn parse_ty_field(&mut self) -> TypeField {
1251 let lo = self.span.lo;
1252 let mutbl = self.parse_mutability();
1253 let id = self.parse_ident();
1254 self.expect(&token::COLON);
1255 let ty = self.parse_ty(true);
1256 let hi = ty.span.hi;
1259 mt: MutTy { ty: ty, mutbl: mutbl },
1260 span: mk_sp(lo, hi),
1264 // parse optional return type [ -> TY ] in function decl
1265 pub fn parse_ret_ty(&mut self) -> (RetStyle, P<Ty>) {
1266 return if self.eat(&token::RARROW) {
1267 let lo = self.span.lo;
1268 if self.eat(&token::NOT) {
1272 id: ast::DUMMY_NODE_ID,
1274 span: mk_sp(lo, self.last_span.hi)
1278 (Return, self.parse_ty(true))
1281 let pos = self.span.lo;
1285 id: ast::DUMMY_NODE_ID,
1287 span: mk_sp(pos, pos),
1295 /// The second parameter specifies whether the `+` binary operator is
1296 /// allowed in the type grammar.
1297 pub fn parse_ty(&mut self, plus_allowed: bool) -> P<Ty> {
1298 maybe_whole!(no_clone self, NtTy);
1300 let lo = self.span.lo;
1302 let t = if self.token == token::LPAREN {
1304 if self.token == token::RPAREN {
1308 // (t) is a parenthesized ty
1309 // (t,) is the type of a tuple with only one field,
1311 let mut ts = vec!(self.parse_ty(true));
1312 let mut one_tuple = false;
1313 while self.token == token::COMMA {
1315 if self.token != token::RPAREN {
1316 ts.push(self.parse_ty(true));
1323 if ts.len() == 1 && !one_tuple {
1324 self.expect(&token::RPAREN);
1328 self.expect(&token::RPAREN);
1332 } else if self.token == token::AT {
1335 TyBox(self.parse_ty(plus_allowed))
1336 } else if self.token == token::TILDE {
1341 self.obsolete(self.last_span, ObsoleteOwnedVector),
1342 _ => self.obsolete(self.last_span, ObsoleteOwnedType),
1344 TyUniq(self.parse_ty(true))
1345 } else if self.token == token::BINOP(token::STAR) {
1346 // STAR POINTER (bare pointer?)
1348 TyPtr(self.parse_mt())
1349 } else if self.token == token::LBRACKET {
1351 self.expect(&token::LBRACKET);
1352 let t = self.parse_ty(true);
1354 // Parse the `, ..e` in `[ int, ..e ]`
1355 // where `e` is a const expression
1356 let t = match self.maybe_parse_fixed_vstore() {
1358 Some(suffix) => TyFixedLengthVec(t, suffix)
1360 self.expect(&token::RBRACKET);
1362 } else if self.token == token::BINOP(token::AND) ||
1363 self.token == token::ANDAND {
1366 self.parse_borrowed_pointee()
1367 } else if self.is_keyword(keywords::Extern) ||
1368 self.is_keyword(keywords::Unsafe) ||
1369 self.token_is_bare_fn_keyword() {
1371 self.parse_ty_bare_fn()
1372 } else if self.token_is_closure_keyword() ||
1373 self.token == token::BINOP(token::OR) ||
1374 self.token == token::OROR ||
1375 self.token == token::LT {
1378 // FIXME(pcwalton): Eventually `token::LT` will not unambiguously
1379 // introduce a closure, once procs can have lifetime bounds. We
1380 // will need to refactor the grammar a little bit at that point.
1382 self.parse_ty_closure()
1383 } else if self.eat_keyword(keywords::Typeof) {
1385 // In order to not be ambiguous, the type must be surrounded by parens.
1386 self.expect(&token::LPAREN);
1387 let e = self.parse_expr();
1388 self.expect(&token::RPAREN);
1390 } else if self.eat_keyword(keywords::Proc) {
1391 self.parse_proc_type()
1392 } else if self.token == token::MOD_SEP
1393 || is_ident_or_path(&self.token) {
1395 let mode = if plus_allowed {
1396 LifetimeAndTypesAndBounds
1398 LifetimeAndTypesWithoutColons
1403 } = self.parse_path(mode);
1404 TyPath(path, bounds, ast::DUMMY_NODE_ID)
1405 } else if self.eat(&token::UNDERSCORE) {
1406 // TYPE TO BE INFERRED
1409 let msg = format!("expected type, found token {:?}", self.token);
1410 self.fatal(msg.as_slice());
1413 let sp = mk_sp(lo, self.last_span.hi);
1414 P(Ty {id: ast::DUMMY_NODE_ID, node: t, span: sp})
1417 pub fn parse_borrowed_pointee(&mut self) -> Ty_ {
1418 // look for `&'lt` or `&'foo ` and interpret `foo` as the region name:
1419 let opt_lifetime = self.parse_opt_lifetime();
1421 let mt = self.parse_mt();
1422 return TyRptr(opt_lifetime, mt);
1425 pub fn is_named_argument(&mut self) -> bool {
1426 let offset = match self.token {
1427 token::BINOP(token::AND) => 1,
1429 _ if token::is_keyword(keywords::Mut, &self.token) => 1,
1433 debug!("parser is_named_argument offset:{}", offset);
1436 is_plain_ident_or_underscore(&self.token)
1437 && self.look_ahead(1, |t| *t == token::COLON)
1439 self.look_ahead(offset, |t| is_plain_ident_or_underscore(t))
1440 && self.look_ahead(offset + 1, |t| *t == token::COLON)
1444 // This version of parse arg doesn't necessarily require
1445 // identifier names.
1446 pub fn parse_arg_general(&mut self, require_name: bool) -> Arg {
1447 let pat = if require_name || self.is_named_argument() {
1448 debug!("parse_arg_general parse_pat (require_name:{:?})",
1450 let pat = self.parse_pat();
1452 self.expect(&token::COLON);
1455 debug!("parse_arg_general ident_to_pat");
1456 ast_util::ident_to_pat(ast::DUMMY_NODE_ID,
1458 special_idents::invalid)
1461 let t = self.parse_ty(true);
1466 id: ast::DUMMY_NODE_ID,
1470 // parse a single function argument
1471 pub fn parse_arg(&mut self) -> Arg {
1472 self.parse_arg_general(true)
1475 // parse an argument in a lambda header e.g. |arg, arg|
1476 pub fn parse_fn_block_arg(&mut self) -> Arg {
1477 let pat = self.parse_pat();
1478 let t = if self.eat(&token::COLON) {
1482 id: ast::DUMMY_NODE_ID,
1484 span: mk_sp(self.span.lo, self.span.hi),
1490 id: ast::DUMMY_NODE_ID
1494 pub fn maybe_parse_fixed_vstore(&mut self) -> Option<Gc<ast::Expr>> {
1495 if self.token == token::COMMA &&
1496 self.look_ahead(1, |t| *t == token::DOTDOT) {
1499 Some(self.parse_expr())
1505 // matches token_lit = LIT_INT | ...
1506 pub fn lit_from_token(&mut self, tok: &token::Token) -> Lit_ {
1508 token::LIT_CHAR(i) => LitChar(i),
1509 token::LIT_INT(i, it) => LitInt(i, it),
1510 token::LIT_UINT(u, ut) => LitUint(u, ut),
1511 token::LIT_INT_UNSUFFIXED(i) => LitIntUnsuffixed(i),
1512 token::LIT_FLOAT(s, ft) => {
1513 LitFloat(self.id_to_interned_str(s), ft)
1515 token::LIT_FLOAT_UNSUFFIXED(s) => {
1516 LitFloatUnsuffixed(self.id_to_interned_str(s))
1518 token::LIT_STR(s) => {
1519 LitStr(self.id_to_interned_str(s), ast::CookedStr)
1521 token::LIT_STR_RAW(s, n) => {
1522 LitStr(self.id_to_interned_str(s), ast::RawStr(n))
1524 token::LPAREN => { self.expect(&token::RPAREN); LitNil },
1525 _ => { self.unexpected_last(tok); }
1529 // matches lit = true | false | token_lit
1530 pub fn parse_lit(&mut self) -> Lit {
1531 let lo = self.span.lo;
1532 let lit = if self.eat_keyword(keywords::True) {
1534 } else if self.eat_keyword(keywords::False) {
1537 let token = self.bump_and_get();
1538 let lit = self.lit_from_token(&token);
1541 codemap::Spanned { node: lit, span: mk_sp(lo, self.last_span.hi) }
1544 // matches '-' lit | lit
1545 pub fn parse_literal_maybe_minus(&mut self) -> Gc<Expr> {
1546 let minus_lo = self.span.lo;
1547 let minus_present = self.eat(&token::BINOP(token::MINUS));
1549 let lo = self.span.lo;
1550 let literal = box(GC) self.parse_lit();
1551 let hi = self.span.hi;
1552 let expr = self.mk_expr(lo, hi, ExprLit(literal));
1555 let minus_hi = self.span.hi;
1556 let unary = self.mk_unary(UnNeg, expr);
1557 self.mk_expr(minus_lo, minus_hi, unary)
1563 /// Parses a path and optional type parameter bounds, depending on the
1564 /// mode. The `mode` parameter determines whether lifetimes, types, and/or
1565 /// bounds are permitted and whether `::` must precede type parameter
1567 pub fn parse_path(&mut self, mode: PathParsingMode) -> PathAndBounds {
1568 // Check for a whole path...
1569 let found = match self.token {
1570 INTERPOLATED(token::NtPath(_)) => Some(self.bump_and_get()),
1574 Some(INTERPOLATED(token::NtPath(box path))) => {
1575 return PathAndBounds {
1583 let lo = self.span.lo;
1584 let is_global = self.eat(&token::MOD_SEP);
1586 // Parse any number of segments and bound sets. A segment is an
1587 // identifier followed by an optional lifetime and a set of types.
1588 // A bound set is a set of type parameter bounds.
1589 let mut segments = Vec::new();
1591 // First, parse an identifier.
1592 let identifier = self.parse_ident();
1594 // Parse the '::' before type parameters if it's required. If
1595 // it is required and wasn't present, then we're done.
1596 if mode == LifetimeAndTypesWithColons &&
1597 !self.eat(&token::MOD_SEP) {
1598 segments.push(ast::PathSegment {
1599 identifier: identifier,
1600 lifetimes: Vec::new(),
1601 types: OwnedSlice::empty(),
1606 // Parse the `<` before the lifetime and types, if applicable.
1607 let (any_lifetime_or_types, lifetimes, types) = {
1608 if mode != NoTypesAllowed && self.eat_lt(false) {
1609 let (lifetimes, types) =
1610 self.parse_generic_values_after_lt();
1611 (true, lifetimes, OwnedSlice::from_vec(types))
1613 (false, Vec::new(), OwnedSlice::empty())
1617 // Assemble and push the result.
1618 segments.push(ast::PathSegment {
1619 identifier: identifier,
1620 lifetimes: lifetimes,
1624 // We're done if we don't see a '::', unless the mode required
1625 // a double colon to get here in the first place.
1626 if !(mode == LifetimeAndTypesWithColons &&
1627 !any_lifetime_or_types) {
1628 if !self.eat(&token::MOD_SEP) {
1634 // Next, parse a plus and bounded type parameters, if applicable.
1636 // NOTE(stage0, pcwalton): Remove `token::COLON` after a snapshot.
1637 let bounds = if mode == LifetimeAndTypesAndBounds {
1639 if self.eat(&token::BINOP(token::PLUS)) ||
1640 self.eat(&token::COLON) {
1641 let (_, bounds) = self.parse_ty_param_bounds(false);
1652 // Assemble the span.
1653 let span = mk_sp(lo, self.last_span.hi);
1655 // Assemble the result.
1666 /// parses 0 or 1 lifetime
1667 pub fn parse_opt_lifetime(&mut self) -> Option<ast::Lifetime> {
1669 token::LIFETIME(..) => {
1670 Some(self.parse_lifetime())
1678 /// Parses a single lifetime
1679 // matches lifetime = LIFETIME
1680 pub fn parse_lifetime(&mut self) -> ast::Lifetime {
1682 token::LIFETIME(i) => {
1683 let span = self.span;
1685 return ast::Lifetime {
1686 id: ast::DUMMY_NODE_ID,
1692 self.fatal(format!("expected a lifetime name").as_slice());
1697 // matches lifetimes = ( lifetime ) | ( lifetime , lifetimes )
1698 // actually, it matches the empty one too, but putting that in there
1699 // messes up the grammar....
1700 pub fn parse_lifetimes(&mut self) -> Vec<ast::Lifetime> {
1703 * Parses zero or more comma separated lifetimes.
1704 * Expects each lifetime to be followed by either
1705 * a comma or `>`. Used when parsing type parameter
1706 * lists, where we expect something like `<'a, 'b, T>`.
1709 let mut res = Vec::new();
1712 token::LIFETIME(_) => {
1713 res.push(self.parse_lifetime());
1721 token::COMMA => { self.bump();}
1722 token::GT => { return res; }
1723 token::BINOP(token::SHR) => { return res; }
1725 let msg = format!("expected `,` or `>` after lifetime \
1728 self.fatal(msg.as_slice());
1734 pub fn token_is_mutability(tok: &token::Token) -> bool {
1735 token::is_keyword(keywords::Mut, tok) ||
1736 token::is_keyword(keywords::Const, tok)
1739 // parse mutability declaration (mut/const/imm)
1740 pub fn parse_mutability(&mut self) -> Mutability {
1741 if self.eat_keyword(keywords::Mut) {
1748 // parse ident COLON expr
1749 pub fn parse_field(&mut self) -> Field {
1750 let lo = self.span.lo;
1751 let i = self.parse_ident();
1752 let hi = self.last_span.hi;
1753 self.expect(&token::COLON);
1754 let e = self.parse_expr();
1756 ident: spanned(lo, hi, i),
1758 span: mk_sp(lo, e.span.hi),
1762 pub fn mk_expr(&mut self, lo: BytePos, hi: BytePos, node: Expr_) -> Gc<Expr> {
1764 id: ast::DUMMY_NODE_ID,
1766 span: mk_sp(lo, hi),
1770 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: Gc<Expr>) -> ast::Expr_ {
1771 ExprUnary(unop, expr)
1774 pub fn mk_binary(&mut self, binop: ast::BinOp,
1775 lhs: Gc<Expr>, rhs: Gc<Expr>) -> ast::Expr_ {
1776 ExprBinary(binop, lhs, rhs)
1779 pub fn mk_call(&mut self, f: Gc<Expr>, args: Vec<Gc<Expr>>) -> ast::Expr_ {
1783 fn mk_method_call(&mut self,
1784 ident: ast::SpannedIdent,
1786 args: Vec<Gc<Expr>>)
1788 ExprMethodCall(ident, tps, args)
1791 pub fn mk_index(&mut self, expr: Gc<Expr>, idx: Gc<Expr>) -> ast::Expr_ {
1792 ExprIndex(expr, idx)
1795 pub fn mk_field(&mut self, expr: Gc<Expr>, ident: Ident,
1796 tys: Vec<P<Ty>>) -> ast::Expr_ {
1797 ExprField(expr, ident, tys)
1800 pub fn mk_assign_op(&mut self, binop: ast::BinOp,
1801 lhs: Gc<Expr>, rhs: Gc<Expr>) -> ast::Expr_ {
1802 ExprAssignOp(binop, lhs, rhs)
1805 pub fn mk_mac_expr(&mut self, lo: BytePos, hi: BytePos, m: Mac_) -> Gc<Expr> {
1807 id: ast::DUMMY_NODE_ID,
1808 node: ExprMac(codemap::Spanned {node: m, span: mk_sp(lo, hi)}),
1809 span: mk_sp(lo, hi),
1813 pub fn mk_lit_u32(&mut self, i: u32) -> Gc<Expr> {
1814 let span = &self.span;
1815 let lv_lit = box(GC) codemap::Spanned {
1816 node: LitUint(i as u64, TyU32),
1821 id: ast::DUMMY_NODE_ID,
1822 node: ExprLit(lv_lit),
1827 // at the bottom (top?) of the precedence hierarchy,
1828 // parse things like parenthesized exprs,
1829 // macros, return, etc.
1830 pub fn parse_bottom_expr(&mut self) -> Gc<Expr> {
1831 maybe_whole_expr!(self);
1833 let lo = self.span.lo;
1834 let mut hi = self.span.hi;
1838 if self.token == token::LPAREN {
1840 // (e) is parenthesized e
1841 // (e,) is a tuple with only one field, e
1842 let mut trailing_comma = false;
1843 if self.token == token::RPAREN {
1846 let lit = box(GC) spanned(lo, hi, LitNil);
1847 return self.mk_expr(lo, hi, ExprLit(lit));
1849 let mut es = vec!(self.parse_expr());
1850 self.commit_expr(*es.last().unwrap(), &[], &[token::COMMA, token::RPAREN]);
1851 while self.token == token::COMMA {
1853 if self.token != token::RPAREN {
1854 es.push(self.parse_expr());
1855 self.commit_expr(*es.last().unwrap(), &[], &[token::COMMA, token::RPAREN]);
1858 trailing_comma = true;
1862 self.commit_expr_expecting(*es.last().unwrap(), token::RPAREN);
1864 return if es.len() == 1 && !trailing_comma {
1865 self.mk_expr(lo, hi, ExprParen(*es.get(0)))
1868 self.mk_expr(lo, hi, ExprTup(es))
1870 } else if self.token == token::LBRACE {
1872 let blk = self.parse_block_tail(lo, DefaultBlock);
1873 return self.mk_expr(blk.span.lo, blk.span.hi,
1875 } else if token::is_bar(&self.token) {
1876 return self.parse_lambda_expr();
1877 } else if self.eat_keyword(keywords::Proc) {
1878 let decl = self.parse_proc_decl();
1879 let body = self.parse_expr();
1880 let fakeblock = P(ast::Block {
1881 view_items: Vec::new(),
1884 id: ast::DUMMY_NODE_ID,
1885 rules: DefaultBlock,
1889 return self.mk_expr(lo, body.span.hi, ExprProc(decl, fakeblock));
1890 } else if self.eat_keyword(keywords::Self) {
1891 let path = ast_util::ident_to_path(mk_sp(lo, hi), special_idents::self_);
1892 ex = ExprPath(path);
1893 hi = self.last_span.hi;
1894 } else if self.eat_keyword(keywords::If) {
1895 return self.parse_if_expr();
1896 } else if self.eat_keyword(keywords::For) {
1897 return self.parse_for_expr(None);
1898 } else if self.eat_keyword(keywords::While) {
1899 return self.parse_while_expr();
1900 } else if Parser::token_is_lifetime(&self.token) {
1901 let lifetime = self.get_lifetime();
1903 self.expect(&token::COLON);
1904 if self.eat_keyword(keywords::For) {
1905 return self.parse_for_expr(Some(lifetime))
1906 } else if self.eat_keyword(keywords::Loop) {
1907 return self.parse_loop_expr(Some(lifetime))
1909 self.fatal("expected `for` or `loop` after a label")
1911 } else if self.eat_keyword(keywords::Loop) {
1912 return self.parse_loop_expr(None);
1913 } else if self.eat_keyword(keywords::Continue) {
1914 let lo = self.span.lo;
1915 let ex = if Parser::token_is_lifetime(&self.token) {
1916 let lifetime = self.get_lifetime();
1918 ExprAgain(Some(lifetime))
1922 let hi = self.span.hi;
1923 return self.mk_expr(lo, hi, ex);
1924 } else if self.eat_keyword(keywords::Match) {
1925 return self.parse_match_expr();
1926 } else if self.eat_keyword(keywords::Unsafe) {
1927 return self.parse_block_expr(lo, UnsafeBlock(ast::UserProvided));
1928 } else if self.token == token::LBRACKET {
1931 if self.token == token::RBRACKET {
1934 ex = ExprVec(Vec::new());
1937 let first_expr = self.parse_expr();
1938 if self.token == token::COMMA &&
1939 self.look_ahead(1, |t| *t == token::DOTDOT) {
1940 // Repeating vector syntax: [ 0, ..512 ]
1943 let count = self.parse_expr();
1944 self.expect(&token::RBRACKET);
1945 ex = ExprRepeat(first_expr, count);
1946 } else if self.token == token::COMMA {
1947 // Vector with two or more elements.
1949 let remaining_exprs = self.parse_seq_to_end(
1951 seq_sep_trailing_allowed(token::COMMA),
1954 let mut exprs = vec!(first_expr);
1955 exprs.push_all_move(remaining_exprs);
1956 ex = ExprVec(exprs);
1958 // Vector with one element.
1959 self.expect(&token::RBRACKET);
1960 ex = ExprVec(vec!(first_expr));
1963 hi = self.last_span.hi;
1964 } else if self.eat_keyword(keywords::Return) {
1965 // RETURN expression
1966 if can_begin_expr(&self.token) {
1967 let e = self.parse_expr();
1969 ex = ExprRet(Some(e));
1970 } else { ex = ExprRet(None); }
1971 } else if self.eat_keyword(keywords::Break) {
1973 if Parser::token_is_lifetime(&self.token) {
1974 let lifetime = self.get_lifetime();
1976 ex = ExprBreak(Some(lifetime));
1978 ex = ExprBreak(None);
1981 } else if self.token == token::MOD_SEP ||
1982 is_ident(&self.token) && !self.is_keyword(keywords::True) &&
1983 !self.is_keyword(keywords::False) {
1984 let pth = self.parse_path(LifetimeAndTypesWithColons).path;
1986 // `!`, as an operator, is prefix, so we know this isn't that
1987 if self.token == token::NOT {
1988 // MACRO INVOCATION expression
1991 let ket = token::close_delimiter_for(&self.token)
1992 .unwrap_or_else(|| self.fatal("expected open delimiter"));
1995 let tts = self.parse_seq_to_end(&ket,
1997 |p| p.parse_token_tree());
1998 let hi = self.span.hi;
2000 return self.mk_mac_expr(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT));
2001 } else if self.token == token::LBRACE {
2002 // This might be a struct literal.
2003 if self.looking_at_struct_literal() {
2004 // It's a struct literal.
2006 let mut fields = Vec::new();
2007 let mut base = None;
2009 while self.token != token::RBRACE {
2010 if self.eat(&token::DOTDOT) {
2011 base = Some(self.parse_expr());
2015 fields.push(self.parse_field());
2016 self.commit_expr(fields.last().unwrap().expr,
2017 &[token::COMMA], &[token::RBRACE]);
2021 self.expect(&token::RBRACE);
2022 ex = ExprStruct(pth, fields, base);
2023 return self.mk_expr(lo, hi, ex);
2030 // other literal expression
2031 let lit = self.parse_lit();
2033 ex = ExprLit(box(GC) lit);
2036 return self.mk_expr(lo, hi, ex);
2039 // parse a block or unsafe block
2040 pub fn parse_block_expr(&mut self, lo: BytePos, blk_mode: BlockCheckMode)
2042 self.expect(&token::LBRACE);
2043 let blk = self.parse_block_tail(lo, blk_mode);
2044 return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk));
2047 // parse a.b or a(13) or a[4] or just a
2048 pub fn parse_dot_or_call_expr(&mut self) -> Gc<Expr> {
2049 let b = self.parse_bottom_expr();
2050 self.parse_dot_or_call_expr_with(b)
2053 pub fn parse_dot_or_call_expr_with(&mut self, e0: Gc<Expr>) -> Gc<Expr> {
2059 if self.eat(&token::DOT) {
2061 token::IDENT(i, _) => {
2062 let dot = self.last_span.hi;
2065 let (_, tys) = if self.eat(&token::MOD_SEP) {
2067 self.parse_generic_values_after_lt()
2069 (Vec::new(), Vec::new())
2072 // expr.f() method call
2075 let mut es = self.parse_unspanned_seq(
2078 seq_sep_trailing_disallowed(token::COMMA),
2081 hi = self.last_span.hi;
2084 let id = spanned(dot, hi, i);
2085 let nd = self.mk_method_call(id, tys, es);
2086 e = self.mk_expr(lo, hi, nd);
2089 let field = self.mk_field(e, i, tys);
2090 e = self.mk_expr(lo, hi, field)
2094 _ => self.unexpected()
2098 if self.expr_is_complete(e) { break; }
2102 let es = self.parse_unspanned_seq(
2105 seq_sep_trailing_allowed(token::COMMA),
2108 hi = self.last_span.hi;
2110 let nd = self.mk_call(e, es);
2111 e = self.mk_expr(lo, hi, nd);
2115 token::LBRACKET => {
2117 let ix = self.parse_expr();
2119 self.commit_expr_expecting(ix, token::RBRACKET);
2120 let index = self.mk_index(e, ix);
2121 e = self.mk_expr(lo, hi, index)
2130 // parse an optional separator followed by a kleene-style
2131 // repetition token (+ or *).
2132 pub fn parse_sep_and_zerok(&mut self) -> (Option<token::Token>, bool) {
2133 fn parse_zerok(parser: &mut Parser) -> Option<bool> {
2134 match parser.token {
2135 token::BINOP(token::STAR) | token::BINOP(token::PLUS) => {
2136 let zerok = parser.token == token::BINOP(token::STAR);
2144 match parse_zerok(self) {
2145 Some(zerok) => return (None, zerok),
2149 let separator = self.bump_and_get();
2150 match parse_zerok(self) {
2151 Some(zerok) => (Some(separator), zerok),
2152 None => self.fatal("expected `*` or `+`")
2156 // parse a single token tree from the input.
2157 pub fn parse_token_tree(&mut self) -> TokenTree {
2158 // FIXME #6994: currently, this is too eager. It
2159 // parses token trees but also identifies TTSeq's
2160 // and TTNonterminal's; it's too early to know yet
2161 // whether something will be a nonterminal or a seq
2163 maybe_whole!(deref self, NtTT);
2165 // this is the fall-through for the 'match' below.
2166 // invariants: the current token is not a left-delimiter,
2167 // not an EOF, and not the desired right-delimiter (if
2168 // it were, parse_seq_to_before_end would have prevented
2169 // reaching this point.
2170 fn parse_non_delim_tt_tok(p: &mut Parser) -> TokenTree {
2171 maybe_whole!(deref p, NtTT);
2173 token::RPAREN | token::RBRACE | token::RBRACKET => {
2174 // This is a conservative error: only report the last unclosed delimiter. The
2175 // previous unclosed delimiters could actually be closed! The parser just hasn't
2176 // gotten to them yet.
2177 match p.open_braces.last() {
2179 Some(&sp) => p.span_note(sp, "unclosed delimiter"),
2181 let token_str = p.this_token_to_str();
2182 p.fatal(format!("incorrect close delimiter: `{}`",
2183 token_str).as_slice())
2185 /* we ought to allow different depths of unquotation */
2186 token::DOLLAR if p.quote_depth > 0u => {
2190 if p.token == token::LPAREN {
2191 let seq = p.parse_seq(
2195 |p| p.parse_token_tree()
2197 let (s, z) = p.parse_sep_and_zerok();
2198 let seq = match seq {
2199 Spanned { node, .. } => node,
2201 TTSeq(mk_sp(sp.lo, p.span.hi), Rc::new(seq), s, z)
2203 TTNonterminal(sp, p.parse_ident())
2212 // turn the next token into a TTTok:
2213 fn parse_any_tt_tok(p: &mut Parser) -> TokenTree {
2214 TTTok(p.span, p.bump_and_get())
2217 match (&self.token, token::close_delimiter_for(&self.token)) {
2218 (&token::EOF, _) => {
2219 let open_braces = self.open_braces.clone();
2220 for sp in open_braces.iter() {
2221 self.span_note(*sp, "Did you mean to close this delimiter?");
2223 // There shouldn't really be a span, but it's easier for the test runner
2224 // if we give it one
2225 self.fatal("this file contains an un-closed delimiter ");
2227 (_, Some(close_delim)) => {
2228 // Parse the open delimiter.
2229 self.open_braces.push(self.span);
2230 let mut result = vec!(parse_any_tt_tok(self));
2233 self.parse_seq_to_before_end(&close_delim,
2235 |p| p.parse_token_tree());
2236 result.push_all_move(trees);
2238 // Parse the close delimiter.
2239 result.push(parse_any_tt_tok(self));
2240 self.open_braces.pop().unwrap();
2242 TTDelim(Rc::new(result))
2244 _ => parse_non_delim_tt_tok(self)
2248 // parse a stream of tokens into a list of TokenTree's,
2250 pub fn parse_all_token_trees(&mut self) -> Vec<TokenTree> {
2251 let mut tts = Vec::new();
2252 while self.token != token::EOF {
2253 tts.push(self.parse_token_tree());
2258 pub fn parse_matchers(&mut self) -> Vec<Matcher> {
2259 // unification of Matcher's and TokenTree's would vastly improve
2260 // the interpolation of Matcher's
2261 maybe_whole!(self, NtMatchers);
2262 let mut name_idx = 0u;
2263 match token::close_delimiter_for(&self.token) {
2264 Some(other_delimiter) => {
2266 self.parse_matcher_subseq_upto(&mut name_idx, &other_delimiter)
2268 None => self.fatal("expected open delimiter")
2272 // This goofy function is necessary to correctly match parens in Matcher's.
2273 // Otherwise, `$( ( )` would be a valid Matcher, and `$( () )` would be
2274 // invalid. It's similar to common::parse_seq.
2275 pub fn parse_matcher_subseq_upto(&mut self,
2276 name_idx: &mut uint,
2279 let mut ret_val = Vec::new();
2280 let mut lparens = 0u;
2282 while self.token != *ket || lparens > 0u {
2283 if self.token == token::LPAREN { lparens += 1u; }
2284 if self.token == token::RPAREN { lparens -= 1u; }
2285 ret_val.push(self.parse_matcher(name_idx));
2293 pub fn parse_matcher(&mut self, name_idx: &mut uint) -> Matcher {
2294 let lo = self.span.lo;
2296 let m = if self.token == token::DOLLAR {
2298 if self.token == token::LPAREN {
2299 let name_idx_lo = *name_idx;
2301 let ms = self.parse_matcher_subseq_upto(name_idx,
2304 self.fatal("repetition body must be nonempty");
2306 let (sep, zerok) = self.parse_sep_and_zerok();
2307 MatchSeq(ms, sep, zerok, name_idx_lo, *name_idx)
2309 let bound_to = self.parse_ident();
2310 self.expect(&token::COLON);
2311 let nt_name = self.parse_ident();
2312 let m = MatchNonterminal(bound_to, nt_name, *name_idx);
2317 MatchTok(self.bump_and_get())
2320 return spanned(lo, self.span.hi, m);
2323 // parse a prefix-operator expr
2324 pub fn parse_prefix_expr(&mut self) -> Gc<Expr> {
2325 let lo = self.span.lo;
2332 let e = self.parse_prefix_expr();
2334 ex = self.mk_unary(UnNot, e);
2336 token::BINOP(token::MINUS) => {
2338 let e = self.parse_prefix_expr();
2340 ex = self.mk_unary(UnNeg, e);
2342 token::BINOP(token::STAR) => {
2344 let e = self.parse_prefix_expr();
2346 ex = self.mk_unary(UnDeref, e);
2348 token::BINOP(token::AND) | token::ANDAND => {
2350 let _lt = self.parse_opt_lifetime();
2351 let m = self.parse_mutability();
2352 let e = self.parse_prefix_expr();
2354 // HACK: turn &[...] into a &-vec
2356 ExprVec(..) if m == MutImmutable => {
2357 ExprVstore(e, ExprVstoreSlice)
2359 ExprVec(..) if m == MutMutable => {
2360 ExprVstore(e, ExprVstoreMutSlice)
2362 _ => ExprAddrOf(m, e)
2367 let e = self.parse_prefix_expr();
2369 // HACK: pretending @[] is a (removed) @-vec
2370 ex = self.mk_unary(UnBox, e);
2375 let e = self.parse_prefix_expr();
2377 // HACK: turn ~[...] into a ~-vec
2379 ExprVec(..) | ExprRepeat(..) => {
2380 self.obsolete(self.last_span, ObsoleteOwnedVector);
2381 ExprVstore(e, ExprVstoreUniq)
2383 ExprLit(lit) if lit_is_str(lit) => {
2384 self.obsolete(self.last_span, ObsoleteOwnedExpr);
2385 ExprVstore(e, ExprVstoreUniq)
2388 self.obsolete(self.last_span, ObsoleteOwnedExpr);
2389 self.mk_unary(UnUniq, e)
2393 token::IDENT(_, _) if self.is_keyword(keywords::Box) => {
2396 // Check for a place: `box(PLACE) EXPR`.
2397 if self.eat(&token::LPAREN) {
2398 // Support `box() EXPR` as the default.
2399 if !self.eat(&token::RPAREN) {
2400 let place = self.parse_expr();
2401 self.expect(&token::RPAREN);
2402 let subexpression = self.parse_prefix_expr();
2403 hi = subexpression.span.hi;
2404 ex = ExprBox(place, subexpression);
2405 return self.mk_expr(lo, hi, ex);
2409 // Otherwise, we use the unique pointer default.
2410 let subexpression = self.parse_prefix_expr();
2411 hi = subexpression.span.hi;
2412 // HACK: turn `box [...]` into a boxed-vec
2413 ex = match subexpression.node {
2414 ExprVec(..) | ExprRepeat(..) => {
2415 self.obsolete(self.last_span, ObsoleteOwnedVector);
2416 ExprVstore(subexpression, ExprVstoreUniq)
2418 ExprLit(lit) if lit_is_str(lit) => {
2419 ExprVstore(subexpression, ExprVstoreUniq)
2421 _ => self.mk_unary(UnUniq, subexpression)
2424 _ => return self.parse_dot_or_call_expr()
2426 return self.mk_expr(lo, hi, ex);
2429 // parse an expression of binops
2430 pub fn parse_binops(&mut self) -> Gc<Expr> {
2431 let prefix_expr = self.parse_prefix_expr();
2432 self.parse_more_binops(prefix_expr, 0)
2435 // parse an expression of binops of at least min_prec precedence
2436 pub fn parse_more_binops(&mut self, lhs: Gc<Expr>,
2437 min_prec: uint) -> Gc<Expr> {
2438 if self.expr_is_complete(lhs) { return lhs; }
2440 // Prevent dynamic borrow errors later on by limiting the
2441 // scope of the borrows.
2443 let token: &token::Token = &self.token;
2444 let restriction: &restriction = &self.restriction;
2445 match (token, restriction) {
2446 (&token::BINOP(token::OR), &RESTRICT_NO_BAR_OP) => return lhs,
2447 (&token::BINOP(token::OR),
2448 &RESTRICT_NO_BAR_OR_DOUBLEBAR_OP) => return lhs,
2449 (&token::OROR, &RESTRICT_NO_BAR_OR_DOUBLEBAR_OP) => return lhs,
2454 let cur_opt = token_to_binop(&self.token);
2457 let cur_prec = operator_prec(cur_op);
2458 if cur_prec > min_prec {
2460 let expr = self.parse_prefix_expr();
2461 let rhs = self.parse_more_binops(expr, cur_prec);
2462 let binary = self.mk_binary(cur_op, lhs, rhs);
2463 let bin = self.mk_expr(lhs.span.lo, rhs.span.hi, binary);
2464 self.parse_more_binops(bin, min_prec)
2470 if as_prec > min_prec && self.eat_keyword(keywords::As) {
2471 let rhs = self.parse_ty(false);
2472 let _as = self.mk_expr(lhs.span.lo,
2474 ExprCast(lhs, rhs));
2475 self.parse_more_binops(_as, min_prec)
2483 // parse an assignment expression....
2484 // actually, this seems to be the main entry point for
2485 // parsing an arbitrary expression.
2486 pub fn parse_assign_expr(&mut self) -> Gc<Expr> {
2487 let lo = self.span.lo;
2488 let lhs = self.parse_binops();
2492 let rhs = self.parse_expr();
2493 self.mk_expr(lo, rhs.span.hi, ExprAssign(lhs, rhs))
2495 token::BINOPEQ(op) => {
2497 let rhs = self.parse_expr();
2498 let aop = match op {
2499 token::PLUS => BiAdd,
2500 token::MINUS => BiSub,
2501 token::STAR => BiMul,
2502 token::SLASH => BiDiv,
2503 token::PERCENT => BiRem,
2504 token::CARET => BiBitXor,
2505 token::AND => BiBitAnd,
2506 token::OR => BiBitOr,
2507 token::SHL => BiShl,
2510 let assign_op = self.mk_assign_op(aop, lhs, rhs);
2511 self.mk_expr(lo, rhs.span.hi, assign_op)
2519 // parse an 'if' expression ('if' token already eaten)
2520 pub fn parse_if_expr(&mut self) -> Gc<Expr> {
2521 let lo = self.last_span.lo;
2522 let cond = self.parse_expr();
2523 let thn = self.parse_block();
2524 let mut els: Option<Gc<Expr>> = None;
2525 let mut hi = thn.span.hi;
2526 if self.eat_keyword(keywords::Else) {
2527 let elexpr = self.parse_else_expr();
2529 hi = elexpr.span.hi;
2531 self.mk_expr(lo, hi, ExprIf(cond, thn, els))
2534 // `|args| { ... }` or `{ ...}` like in `do` expressions
2535 pub fn parse_lambda_block_expr(&mut self) -> Gc<Expr> {
2536 self.parse_lambda_expr_(
2539 token::BINOP(token::OR) | token::OROR => {
2540 p.parse_fn_block_decl()
2543 // No argument list - `do foo {`
2547 id: ast::DUMMY_NODE_ID,
2558 let blk = p.parse_block();
2559 p.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk))
2564 pub fn parse_lambda_expr(&mut self) -> Gc<Expr> {
2565 self.parse_lambda_expr_(|p| p.parse_fn_block_decl(),
2569 // parse something of the form |args| expr
2570 // this is used both in parsing a lambda expr
2571 // and in parsing a block expr as e.g. in for...
2572 pub fn parse_lambda_expr_(&mut self,
2573 parse_decl: |&mut Parser| -> P<FnDecl>,
2574 parse_body: |&mut Parser| -> Gc<Expr>)
2576 let lo = self.span.lo;
2577 let decl = parse_decl(self);
2578 let body = parse_body(self);
2579 let fakeblock = P(ast::Block {
2580 view_items: Vec::new(),
2583 id: ast::DUMMY_NODE_ID,
2584 rules: DefaultBlock,
2588 return self.mk_expr(lo, body.span.hi, ExprFnBlock(decl, fakeblock));
2591 pub fn parse_else_expr(&mut self) -> Gc<Expr> {
2592 if self.eat_keyword(keywords::If) {
2593 return self.parse_if_expr();
2595 let blk = self.parse_block();
2596 return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk));
2600 // parse a 'for' .. 'in' expression ('for' token already eaten)
2601 pub fn parse_for_expr(&mut self, opt_ident: Option<ast::Ident>) -> Gc<Expr> {
2602 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
2604 let lo = self.last_span.lo;
2605 let pat = self.parse_pat();
2606 self.expect_keyword(keywords::In);
2607 let expr = self.parse_expr();
2608 let loop_block = self.parse_block();
2609 let hi = self.span.hi;
2611 self.mk_expr(lo, hi, ExprForLoop(pat, expr, loop_block, opt_ident))
2614 pub fn parse_while_expr(&mut self) -> Gc<Expr> {
2615 let lo = self.last_span.lo;
2616 let cond = self.parse_expr();
2617 let body = self.parse_block();
2618 let hi = body.span.hi;
2619 return self.mk_expr(lo, hi, ExprWhile(cond, body));
2622 pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::Ident>) -> Gc<Expr> {
2623 let lo = self.last_span.lo;
2624 let body = self.parse_block();
2625 let hi = body.span.hi;
2626 self.mk_expr(lo, hi, ExprLoop(body, opt_ident))
2629 // For distinguishing between struct literals and blocks
2630 fn looking_at_struct_literal(&mut self) -> bool {
2631 self.token == token::LBRACE &&
2632 ((self.look_ahead(1, |t| token::is_plain_ident(t)) &&
2633 self.look_ahead(2, |t| *t == token::COLON))
2634 || self.look_ahead(1, |t| *t == token::DOTDOT))
2637 fn parse_match_expr(&mut self) -> Gc<Expr> {
2638 let lo = self.last_span.lo;
2639 let discriminant = self.parse_expr();
2640 self.commit_expr_expecting(discriminant, token::LBRACE);
2641 let mut arms: Vec<Arm> = Vec::new();
2642 while self.token != token::RBRACE {
2643 let attrs = self.parse_outer_attributes();
2644 let pats = self.parse_pats();
2645 let mut guard = None;
2646 if self.eat_keyword(keywords::If) {
2647 guard = Some(self.parse_expr());
2649 self.expect(&token::FAT_ARROW);
2650 let expr = self.parse_expr_res(RESTRICT_STMT_EXPR);
2653 !classify::expr_is_simple_block(expr)
2654 && self.token != token::RBRACE;
2657 self.commit_expr(expr, &[token::COMMA], &[token::RBRACE]);
2659 self.eat(&token::COMMA);
2662 arms.push(ast::Arm {
2669 let hi = self.span.hi;
2671 return self.mk_expr(lo, hi, ExprMatch(discriminant, arms));
2674 // parse an expression
2675 pub fn parse_expr(&mut self) -> Gc<Expr> {
2676 return self.parse_expr_res(UNRESTRICTED);
2679 // parse an expression, subject to the given restriction
2680 fn parse_expr_res(&mut self, r: restriction) -> Gc<Expr> {
2681 let old = self.restriction;
2682 self.restriction = r;
2683 let e = self.parse_assign_expr();
2684 self.restriction = old;
2688 // parse the RHS of a local variable declaration (e.g. '= 14;')
2689 fn parse_initializer(&mut self) -> Option<Gc<Expr>> {
2690 if self.token == token::EQ {
2692 Some(self.parse_expr())
2698 // parse patterns, separated by '|' s
2699 fn parse_pats(&mut self) -> Vec<Gc<Pat>> {
2700 let mut pats = Vec::new();
2702 pats.push(self.parse_pat());
2703 if self.token == token::BINOP(token::OR) { self.bump(); }
2704 else { return pats; }
2708 fn parse_pat_vec_elements(
2710 ) -> (Vec<Gc<Pat>> , Option<Gc<Pat>>, Vec<Gc<Pat>> ) {
2711 let mut before = Vec::new();
2712 let mut slice = None;
2713 let mut after = Vec::new();
2714 let mut first = true;
2715 let mut before_slice = true;
2717 while self.token != token::RBRACKET {
2718 if first { first = false; }
2719 else { self.expect(&token::COMMA); }
2721 let mut is_slice = false;
2723 if self.token == token::DOTDOT {
2726 before_slice = false;
2731 if self.token == token::COMMA || self.token == token::RBRACKET {
2732 slice = Some(box(GC) ast::Pat {
2733 id: ast::DUMMY_NODE_ID,
2738 let subpat = self.parse_pat();
2740 ast::Pat { node: PatIdent(_, _, _), .. } => {
2741 slice = Some(subpat);
2743 ast::Pat { span, .. } => self.span_fatal(
2744 span, "expected an identifier or nothing"
2749 let subpat = self.parse_pat();
2751 before.push(subpat);
2758 (before, slice, after)
2761 // parse the fields of a struct-like pattern
2762 fn parse_pat_fields(&mut self) -> (Vec<ast::FieldPat> , bool) {
2763 let mut fields = Vec::new();
2764 let mut etc = false;
2765 let mut first = true;
2766 while self.token != token::RBRACE {
2770 self.expect(&token::COMMA);
2771 // accept trailing commas
2772 if self.token == token::RBRACE { break }
2775 if self.token == token::DOTDOT {
2777 if self.token != token::RBRACE {
2778 let token_str = self.this_token_to_str();
2779 self.fatal(format!("expected `{}`, found `{}`", "}",
2780 token_str).as_slice())
2786 let bind_type = if self.eat_keyword(keywords::Mut) {
2787 BindByValue(MutMutable)
2788 } else if self.eat_keyword(keywords::Ref) {
2789 BindByRef(self.parse_mutability())
2791 BindByValue(MutImmutable)
2794 let fieldname = self.parse_ident();
2796 let subpat = if self.token == token::COLON {
2798 BindByRef(..) | BindByValue(MutMutable) => {
2799 let token_str = self.this_token_to_str();
2800 self.fatal(format!("unexpected `{}`",
2801 token_str).as_slice())
2809 let fieldpath = ast_util::ident_to_path(self.last_span,
2812 id: ast::DUMMY_NODE_ID,
2813 node: PatIdent(bind_type, fieldpath, None),
2814 span: self.last_span
2817 fields.push(ast::FieldPat { ident: fieldname, pat: subpat });
2819 return (fields, etc);
2823 pub fn parse_pat(&mut self) -> Gc<Pat> {
2824 maybe_whole!(self, NtPat);
2826 let lo = self.span.lo;
2831 token::UNDERSCORE => {
2834 hi = self.last_span.hi;
2835 return box(GC) ast::Pat {
2836 id: ast::DUMMY_NODE_ID,
2844 let sub = self.parse_pat();
2846 hi = self.last_span.hi;
2847 self.obsolete(self.last_span, ObsoleteOwnedPattern);
2848 return box(GC) ast::Pat {
2849 id: ast::DUMMY_NODE_ID,
2854 token::BINOP(token::AND) | token::ANDAND => {
2856 let lo = self.span.lo;
2858 let sub = self.parse_pat();
2859 pat = PatRegion(sub);
2860 hi = self.last_span.hi;
2861 return box(GC) ast::Pat {
2862 id: ast::DUMMY_NODE_ID,
2868 // parse (pat,pat,pat,...) as tuple
2870 if self.token == token::RPAREN {
2873 let lit = box(GC) codemap::Spanned {
2875 span: mk_sp(lo, hi)};
2876 let expr = self.mk_expr(lo, hi, ExprLit(lit));
2879 let mut fields = vec!(self.parse_pat());
2880 if self.look_ahead(1, |t| *t != token::RPAREN) {
2881 while self.token == token::COMMA {
2883 if self.token == token::RPAREN { break; }
2884 fields.push(self.parse_pat());
2887 if fields.len() == 1 { self.expect(&token::COMMA); }
2888 self.expect(&token::RPAREN);
2889 pat = PatTup(fields);
2891 hi = self.last_span.hi;
2892 return box(GC) ast::Pat {
2893 id: ast::DUMMY_NODE_ID,
2898 token::LBRACKET => {
2899 // parse [pat,pat,...] as vector pattern
2901 let (before, slice, after) =
2902 self.parse_pat_vec_elements();
2904 self.expect(&token::RBRACKET);
2905 pat = ast::PatVec(before, slice, after);
2906 hi = self.last_span.hi;
2907 return box(GC) ast::Pat {
2908 id: ast::DUMMY_NODE_ID,
2916 if (!is_ident_or_path(&self.token) && self.token != token::MOD_SEP)
2917 || self.is_keyword(keywords::True)
2918 || self.is_keyword(keywords::False) {
2919 // Parse an expression pattern or exp .. exp.
2921 // These expressions are limited to literals (possibly
2922 // preceded by unary-minus) or identifiers.
2923 let val = self.parse_literal_maybe_minus();
2924 if self.eat(&token::DOTDOT) {
2925 let end = if is_ident_or_path(&self.token) {
2926 let path = self.parse_path(LifetimeAndTypesWithColons)
2928 let hi = self.span.hi;
2929 self.mk_expr(lo, hi, ExprPath(path))
2931 self.parse_literal_maybe_minus()
2933 pat = PatRange(val, end);
2937 } else if self.eat_keyword(keywords::Mut) {
2938 pat = self.parse_pat_ident(BindByValue(MutMutable));
2939 } else if self.eat_keyword(keywords::Ref) {
2941 let mutbl = self.parse_mutability();
2942 pat = self.parse_pat_ident(BindByRef(mutbl));
2943 } else if self.eat_keyword(keywords::Box) {
2946 // FIXME(#13910): Rename to `PatBox` and extend to full DST
2948 let sub = self.parse_pat();
2950 hi = self.last_span.hi;
2951 return box(GC) ast::Pat {
2952 id: ast::DUMMY_NODE_ID,
2957 let can_be_enum_or_struct = self.look_ahead(1, |t| {
2959 token::LPAREN | token::LBRACKET | token::LT |
2960 token::LBRACE | token::MOD_SEP => true,
2965 if self.look_ahead(1, |t| *t == token::DOTDOT) {
2966 let start = self.parse_expr_res(RESTRICT_NO_BAR_OP);
2967 self.eat(&token::DOTDOT);
2968 let end = self.parse_expr_res(RESTRICT_NO_BAR_OP);
2969 pat = PatRange(start, end);
2970 } else if is_plain_ident(&self.token) && !can_be_enum_or_struct {
2971 let name = self.parse_path(NoTypesAllowed).path;
2972 if self.eat(&token::NOT) {
2974 let ket = token::close_delimiter_for(&self.token)
2975 .unwrap_or_else(|| self.fatal("expected open delimiter"));
2978 let tts = self.parse_seq_to_end(&ket,
2980 |p| p.parse_token_tree());
2982 let mac = MacInvocTT(name, tts, EMPTY_CTXT);
2983 pat = ast::PatMac(codemap::Spanned {node: mac, span: self.span});
2985 let sub = if self.eat(&token::AT) {
2987 Some(self.parse_pat())
2992 pat = PatIdent(BindByValue(MutImmutable), name, sub);
2995 // parse an enum pat
2996 let enum_path = self.parse_path(LifetimeAndTypesWithColons)
3002 self.parse_pat_fields();
3004 pat = PatStruct(enum_path, fields, etc);
3007 let mut args: Vec<Gc<Pat>> = Vec::new();
3010 let is_dotdot = self.look_ahead(1, |t| {
3012 token::DOTDOT => true,
3017 // This is a "top constructor only" pat
3020 self.expect(&token::RPAREN);
3021 pat = PatEnum(enum_path, None);
3023 args = self.parse_enum_variant_seq(
3026 seq_sep_trailing_disallowed(token::COMMA),
3029 pat = PatEnum(enum_path, Some(args));
3033 if enum_path.segments.len() == 1 {
3034 // it could still be either an enum
3035 // or an identifier pattern, resolve
3036 // will sort it out:
3037 pat = PatIdent(BindByValue(MutImmutable),
3041 pat = PatEnum(enum_path, Some(args));
3049 hi = self.last_span.hi;
3051 id: ast::DUMMY_NODE_ID,
3053 span: mk_sp(lo, hi),
3057 // parse ident or ident @ pat
3058 // used by the copy foo and ref foo patterns to give a good
3059 // error message when parsing mistakes like ref foo(a,b)
3060 fn parse_pat_ident(&mut self,
3061 binding_mode: ast::BindingMode)
3063 if !is_plain_ident(&self.token) {
3064 self.span_fatal(self.last_span,
3065 "expected identifier, found path");
3067 // why a path here, and not just an identifier?
3068 let name = self.parse_path(NoTypesAllowed).path;
3069 let sub = if self.eat(&token::AT) {
3070 Some(self.parse_pat())
3075 // just to be friendly, if they write something like
3077 // we end up here with ( as the current token. This shortly
3078 // leads to a parse error. Note that if there is no explicit
3079 // binding mode then we do not end up here, because the lookahead
3080 // will direct us over to parse_enum_variant()
3081 if self.token == token::LPAREN {
3084 "expected identifier, found enum pattern");
3087 PatIdent(binding_mode, name, sub)
3090 // parse a local variable declaration
3091 fn parse_local(&mut self) -> Gc<Local> {
3092 let lo = self.span.lo;
3093 let pat = self.parse_pat();
3096 id: ast::DUMMY_NODE_ID,
3098 span: mk_sp(lo, lo),
3100 if self.eat(&token::COLON) {
3101 ty = self.parse_ty(true);
3103 let init = self.parse_initializer();
3104 box(GC) ast::Local {
3108 id: ast::DUMMY_NODE_ID,
3109 span: mk_sp(lo, self.last_span.hi),
3114 // parse a "let" stmt
3115 fn parse_let(&mut self) -> Gc<Decl> {
3116 let lo = self.span.lo;
3117 let local = self.parse_local();
3118 box(GC) spanned(lo, self.last_span.hi, DeclLocal(local))
3121 // parse a structure field
3122 fn parse_name_and_ty(&mut self, pr: Visibility,
3123 attrs: Vec<Attribute> ) -> StructField {
3124 let lo = self.span.lo;
3125 if !is_plain_ident(&self.token) {
3126 self.fatal("expected ident");
3128 let name = self.parse_ident();
3129 self.expect(&token::COLON);
3130 let ty = self.parse_ty(true);
3131 spanned(lo, self.last_span.hi, ast::StructField_ {
3132 kind: NamedField(name, pr),
3133 id: ast::DUMMY_NODE_ID,
3139 // parse a statement. may include decl.
3140 // precondition: any attributes are parsed already
3141 pub fn parse_stmt(&mut self, item_attrs: Vec<Attribute>) -> Gc<Stmt> {
3142 maybe_whole!(self, NtStmt);
3144 fn check_expected_item(p: &mut Parser, found_attrs: bool) {
3145 // If we have attributes then we should have an item
3147 p.span_err(p.last_span, "expected item after attributes");
3151 let lo = self.span.lo;
3152 if self.is_keyword(keywords::Let) {
3153 check_expected_item(self, !item_attrs.is_empty());
3154 self.expect_keyword(keywords::Let);
3155 let decl = self.parse_let();
3156 return box(GC) spanned(lo, decl.span.hi, StmtDecl(decl, ast::DUMMY_NODE_ID));
3157 } else if is_ident(&self.token)
3158 && !token::is_any_keyword(&self.token)
3159 && self.look_ahead(1, |t| *t == token::NOT) {
3160 // parse a macro invocation. Looks like there's serious
3161 // overlap here; if this clause doesn't catch it (and it
3162 // won't, for brace-delimited macros) it will fall through
3163 // to the macro clause of parse_item_or_view_item. This
3164 // could use some cleanup, it appears to me.
3166 // whoops! I now have a guess: I'm guessing the "parens-only"
3167 // rule here is deliberate, to allow macro users to use parens
3168 // for things that should be parsed as stmt_mac, and braces
3169 // for things that should expand into items. Tricky, and
3170 // somewhat awkward... and probably undocumented. Of course,
3171 // I could just be wrong.
3173 check_expected_item(self, !item_attrs.is_empty());
3175 // Potential trouble: if we allow macros with paths instead of
3176 // idents, we'd need to look ahead past the whole path here...
3177 let pth = self.parse_path(NoTypesAllowed).path;
3180 let id = if token::close_delimiter_for(&self.token).is_some() {
3181 token::special_idents::invalid // no special identifier
3186 // check that we're pointing at delimiters (need to check
3187 // again after the `if`, because of `parse_ident`
3188 // consuming more tokens).
3189 let (bra, ket) = match token::close_delimiter_for(&self.token) {
3190 Some(ket) => (self.token.clone(), ket),
3193 // we only expect an ident if we didn't parse one
3195 let ident_str = if id == token::special_idents::invalid {
3200 let tok_str = self.this_token_to_str();
3201 self.fatal(format!("expected {}`(` or `\\{`, but found `{}`",
3203 tok_str).as_slice())
3207 // we only expect an ident if we didn't parse one
3209 let ident_str = if id == token::special_idents::invalid {
3214 let tok_str = self.this_token_to_str();
3215 self.fatal(format!("expected {}`(` or `{{`, but found `{}`",
3217 tok_str).as_slice())
3221 let tts = self.parse_unspanned_seq(
3225 |p| p.parse_token_tree()
3227 let hi = self.span.hi;
3229 if id == token::special_idents::invalid {
3230 return box(GC) spanned(lo, hi, StmtMac(
3231 spanned(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT)), false));
3233 // if it has a special ident, it's definitely an item
3234 return box(GC) spanned(lo, hi, StmtDecl(
3235 box(GC) spanned(lo, hi, DeclItem(
3237 lo, hi, id /*id is good here*/,
3238 ItemMac(spanned(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT))),
3239 Inherited, Vec::new(/*no attrs*/)))),
3240 ast::DUMMY_NODE_ID));
3244 let found_attrs = !item_attrs.is_empty();
3245 match self.parse_item_or_view_item(item_attrs, false) {
3248 let decl = box(GC) spanned(lo, hi, DeclItem(i));
3249 return box(GC) spanned(lo, hi, StmtDecl(decl, ast::DUMMY_NODE_ID));
3251 IoviViewItem(vi) => {
3252 self.span_fatal(vi.span,
3253 "view items must be declared at the top of the block");
3255 IoviForeignItem(_) => {
3256 self.fatal("foreign items are not allowed here");
3258 IoviNone(_) => { /* fallthrough */ }
3261 check_expected_item(self, found_attrs);
3263 // Remainder are line-expr stmts.
3264 let e = self.parse_expr_res(RESTRICT_STMT_EXPR);
3265 return box(GC) spanned(lo, e.span.hi, StmtExpr(e, ast::DUMMY_NODE_ID));
3269 // is this expression a successfully-parsed statement?
3270 fn expr_is_complete(&mut self, e: Gc<Expr>) -> bool {
3271 return self.restriction == RESTRICT_STMT_EXPR &&
3272 !classify::expr_requires_semi_to_be_stmt(e);
3275 // parse a block. No inner attrs are allowed.
3276 pub fn parse_block(&mut self) -> P<Block> {
3277 maybe_whole!(no_clone self, NtBlock);
3279 let lo = self.span.lo;
3280 self.expect(&token::LBRACE);
3282 return self.parse_block_tail_(lo, DefaultBlock, Vec::new());
3285 // parse a block. Inner attrs are allowed.
3286 fn parse_inner_attrs_and_block(&mut self)
3287 -> (Vec<Attribute> , P<Block>) {
3289 maybe_whole!(pair_empty self, NtBlock);
3291 let lo = self.span.lo;
3292 self.expect(&token::LBRACE);
3293 let (inner, next) = self.parse_inner_attrs_and_next();
3295 (inner, self.parse_block_tail_(lo, DefaultBlock, next))
3298 // Precondition: already parsed the '{' or '#{'
3299 // I guess that also means "already parsed the 'impure'" if
3300 // necessary, and this should take a qualifier.
3301 // some blocks start with "#{"...
3302 fn parse_block_tail(&mut self, lo: BytePos, s: BlockCheckMode) -> P<Block> {
3303 self.parse_block_tail_(lo, s, Vec::new())
3306 // parse the rest of a block expression or function body
3307 fn parse_block_tail_(&mut self, lo: BytePos, s: BlockCheckMode,
3308 first_item_attrs: Vec<Attribute> ) -> P<Block> {
3309 let mut stmts = Vec::new();
3310 let mut expr = None;
3312 // wouldn't it be more uniform to parse view items only, here?
3313 let ParsedItemsAndViewItems {
3314 attrs_remaining: attrs_remaining,
3315 view_items: view_items,
3318 } = self.parse_items_and_view_items(first_item_attrs,
3321 for item in items.iter() {
3322 let decl = box(GC) spanned(item.span.lo, item.span.hi, DeclItem(*item));
3323 stmts.push(box(GC) spanned(item.span.lo, item.span.hi,
3324 StmtDecl(decl, ast::DUMMY_NODE_ID)));
3327 let mut attributes_box = attrs_remaining;
3329 while self.token != token::RBRACE {
3330 // parsing items even when they're not allowed lets us give
3331 // better error messages and recover more gracefully.
3332 attributes_box.push_all(self.parse_outer_attributes().as_slice());
3335 if !attributes_box.is_empty() {
3336 self.span_err(self.last_span, "expected item after attributes");
3337 attributes_box = Vec::new();
3339 self.bump(); // empty
3342 // fall through and out.
3345 let stmt = self.parse_stmt(attributes_box);
3346 attributes_box = Vec::new();
3348 StmtExpr(e, stmt_id) => {
3349 // expression without semicolon
3350 if classify::stmt_ends_with_semi(&*stmt) {
3351 // Just check for errors and recover; do not eat semicolon yet.
3352 self.commit_stmt(stmt, &[], &[token::SEMI, token::RBRACE]);
3358 let span_with_semi = Span {
3360 hi: self.last_span.hi,
3361 expn_info: stmt.span.expn_info,
3363 stmts.push(box(GC) codemap::Spanned {
3364 node: StmtSemi(e, stmt_id),
3365 span: span_with_semi,
3376 StmtMac(ref m, _) => {
3377 // statement macro; might be an expr
3381 stmts.push(box(GC) codemap::Spanned {
3382 node: StmtMac((*m).clone(), true),
3387 // if a block ends in `m!(arg)` without
3388 // a `;`, it must be an expr
3390 self.mk_mac_expr(stmt.span.lo,
3399 _ => { // all other kinds of statements:
3400 stmts.push(stmt.clone());
3402 if classify::stmt_ends_with_semi(&*stmt) {
3403 self.commit_stmt_expecting(stmt, token::SEMI);
3411 if !attributes_box.is_empty() {
3412 self.span_err(self.last_span, "expected item after attributes");
3415 let hi = self.span.hi;
3418 view_items: view_items,
3421 id: ast::DUMMY_NODE_ID,
3423 span: mk_sp(lo, hi),
3427 fn parse_unboxed_function_type(&mut self) -> UnboxedFnTy {
3428 let inputs = if self.eat(&token::OROR) {
3433 if self.token == token::BINOP(token::AND) &&
3434 self.look_ahead(1, |t| {
3435 token::is_keyword(keywords::Mut, t)
3437 self.look_ahead(2, |t| *t == token::COLON) {
3443 let inputs = self.parse_seq_to_before_or(&token::COMMA,
3445 p.parse_arg_general(false)
3451 let (return_style, output) = self.parse_ret_ty();
3462 // matches bounds = ( boundseq )?
3463 // where boundseq = ( bound + boundseq ) | bound
3464 // and bound = 'static | ty
3465 // Returns "None" if there's no colon (e.g. "T");
3466 // Returns "Some(Empty)" if there's a colon but nothing after (e.g. "T:")
3467 // Returns "Some(stuff)" otherwise (e.g. "T:stuff").
3468 // NB: The None/Some distinction is important for issue #7264.
3470 // Note that the `allow_any_lifetime` argument is a hack for now while the
3471 // AST doesn't support arbitrary lifetimes in bounds on type parameters. In
3472 // the future, this flag should be removed, and the return value of this
3473 // function should be Option<~[TyParamBound]>
3474 fn parse_ty_param_bounds(&mut self, allow_any_lifetime: bool)
3475 -> (Option<ast::Lifetime>,
3476 OwnedSlice<TyParamBound>) {
3477 let mut ret_lifetime = None;
3478 let mut result = vec!();
3481 token::LIFETIME(lifetime) => {
3482 let lifetime_interned_string = token::get_ident(lifetime);
3483 if lifetime_interned_string.equiv(&("'static")) {
3484 result.push(StaticRegionTyParamBound);
3485 if allow_any_lifetime && ret_lifetime.is_none() {
3486 ret_lifetime = Some(ast::Lifetime {
3487 id: ast::DUMMY_NODE_ID,
3492 } else if allow_any_lifetime && ret_lifetime.is_none() {
3493 ret_lifetime = Some(ast::Lifetime {
3494 id: ast::DUMMY_NODE_ID,
3499 result.push(OtherRegionTyParamBound(self.span));
3503 token::MOD_SEP | token::IDENT(..) => {
3504 let tref = self.parse_trait_ref();
3505 result.push(TraitTyParamBound(tref));
3507 token::BINOP(token::OR) | token::OROR => {
3508 let unboxed_function_type =
3509 self.parse_unboxed_function_type();
3510 result.push(UnboxedFnTyParamBound(unboxed_function_type));
3515 if !self.eat(&token::BINOP(token::PLUS)) {
3520 return (ret_lifetime, OwnedSlice::from_vec(result));
3523 // matches typaram = type? IDENT optbounds ( EQ ty )?
3524 fn parse_ty_param(&mut self) -> TyParam {
3525 let sized = self.parse_sized();
3526 let span = self.span;
3527 let ident = self.parse_ident();
3529 if self.eat(&token::COLON) {
3530 let (_, bounds) = self.parse_ty_param_bounds(false);
3536 // For typarams we don't care about the difference b/w "<T>" and "<T:>".
3537 let bounds = opt_bounds.unwrap_or_default();
3539 let default = if self.token == token::EQ {
3541 Some(self.parse_ty(true))
3547 id: ast::DUMMY_NODE_ID,
3555 // parse a set of optional generic type parameter declarations
3556 // matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
3557 // | ( < lifetimes , typaramseq ( , )? > )
3558 // where typaramseq = ( typaram ) | ( typaram , typaramseq )
3559 pub fn parse_generics(&mut self) -> ast::Generics {
3560 if self.eat(&token::LT) {
3561 let lifetimes = self.parse_lifetimes();
3562 let mut seen_default = false;
3563 let ty_params = self.parse_seq_to_gt(Some(token::COMMA), |p| {
3564 p.forbid_lifetime();
3565 let ty_param = p.parse_ty_param();
3566 if ty_param.default.is_some() {
3567 seen_default = true;
3568 } else if seen_default {
3569 p.span_err(p.last_span,
3570 "type parameters with a default must be trailing");
3574 ast::Generics { lifetimes: lifetimes, ty_params: ty_params }
3576 ast_util::empty_generics()
3580 fn parse_generic_values_after_lt(&mut self) -> (Vec<ast::Lifetime>, Vec<P<Ty>> ) {
3581 let lifetimes = self.parse_lifetimes();
3582 let result = self.parse_seq_to_gt(
3585 p.forbid_lifetime();
3589 (lifetimes, result.into_vec())
3592 fn forbid_lifetime(&mut self) {
3593 if Parser::token_is_lifetime(&self.token) {
3594 self.span_fatal(self.span, "lifetime parameters must be declared \
3595 prior to type parameters");
3599 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
3600 -> (Vec<Arg> , bool) {
3602 let mut args: Vec<Option<Arg>> =
3603 self.parse_unspanned_seq(
3606 seq_sep_trailing_allowed(token::COMMA),
3608 if p.token == token::DOTDOTDOT {
3611 if p.token != token::RPAREN {
3612 p.span_fatal(p.span,
3613 "`...` must be last in argument list for variadic function");
3616 p.span_fatal(p.span,
3617 "only foreign functions are allowed to be variadic");
3621 Some(p.parse_arg_general(named_args))
3626 let variadic = match args.pop() {
3629 // Need to put back that last arg
3636 if variadic && args.is_empty() {
3638 "variadic function must be declared with at least one named argument");
3641 let args = args.move_iter().map(|x| x.unwrap()).collect();
3646 // parse the argument list and result type of a function declaration
3647 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> P<FnDecl> {
3649 let (args, variadic) = self.parse_fn_args(true, allow_variadic);
3650 let (ret_style, ret_ty) = self.parse_ret_ty();
3660 fn is_self_ident(&mut self) -> bool {
3662 token::IDENT(id, false) => id.name == special_idents::self_.name,
3667 fn expect_self_ident(&mut self) {
3668 if !self.is_self_ident() {
3669 let token_str = self.this_token_to_str();
3670 self.fatal(format!("expected `self` but found `{}`",
3671 token_str).as_slice())
3676 // parse the argument list and result type of a function
3677 // that may have a self type.
3678 fn parse_fn_decl_with_self(&mut self, parse_arg_fn: |&mut Parser| -> Arg)
3679 -> (ExplicitSelf, P<FnDecl>) {
3680 fn maybe_parse_borrowed_explicit_self(this: &mut Parser)
3681 -> ast::ExplicitSelf_ {
3682 // The following things are possible to see here:
3687 // fn(&'lt mut self)
3689 // We already know that the current token is `&`.
3691 if this.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) {
3693 this.expect_self_ident();
3694 SelfRegion(None, MutImmutable)
3695 } else if this.look_ahead(1, |t| Parser::token_is_mutability(t)) &&
3697 |t| token::is_keyword(keywords::Self,
3700 let mutability = this.parse_mutability();
3701 this.expect_self_ident();
3702 SelfRegion(None, mutability)
3703 } else if this.look_ahead(1, |t| Parser::token_is_lifetime(t)) &&
3705 |t| token::is_keyword(keywords::Self,
3708 let lifetime = this.parse_lifetime();
3709 this.expect_self_ident();
3710 SelfRegion(Some(lifetime), MutImmutable)
3711 } else if this.look_ahead(1, |t| Parser::token_is_lifetime(t)) &&
3712 this.look_ahead(2, |t| {
3713 Parser::token_is_mutability(t)
3715 this.look_ahead(3, |t| token::is_keyword(keywords::Self,
3718 let lifetime = this.parse_lifetime();
3719 let mutability = this.parse_mutability();
3720 this.expect_self_ident();
3721 SelfRegion(Some(lifetime), mutability)
3727 self.expect(&token::LPAREN);
3729 // A bit of complexity and lookahead is needed here in order to be
3730 // backwards compatible.
3731 let lo = self.span.lo;
3732 let mut mutbl_self = MutImmutable;
3733 let explicit_self = match self.token {
3734 token::BINOP(token::AND) => {
3735 maybe_parse_borrowed_explicit_self(self)
3738 // We need to make sure it isn't a type
3739 if self.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) {
3741 self.expect_self_ident();
3747 token::IDENT(..) if self.is_self_ident() => {
3751 token::BINOP(token::STAR) => {
3752 // Possibly "*self" or "*mut self" -- not supported. Try to avoid
3753 // emitting cryptic "unexpected token" errors.
3755 let _mutability = if Parser::token_is_mutability(&self.token) {
3756 self.parse_mutability()
3757 } else { MutImmutable };
3758 if self.is_self_ident() {
3759 self.span_err(self.span, "cannot pass self by unsafe pointer");
3764 _ if Parser::token_is_mutability(&self.token) &&
3765 self.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) => {
3766 mutbl_self = self.parse_mutability();
3767 self.expect_self_ident();
3770 _ if Parser::token_is_mutability(&self.token) &&
3771 self.look_ahead(1, |t| *t == token::TILDE) &&
3772 self.look_ahead(2, |t| token::is_keyword(keywords::Self, t)) => {
3773 mutbl_self = self.parse_mutability();
3775 self.expect_self_ident();
3781 let explicit_self_sp = mk_sp(lo, self.span.hi);
3783 // If we parsed a self type, expect a comma before the argument list.
3784 let fn_inputs = if explicit_self != SelfStatic {
3788 let sep = seq_sep_trailing_disallowed(token::COMMA);
3789 let mut fn_inputs = self.parse_seq_to_before_end(
3794 fn_inputs.unshift(Arg::new_self(explicit_self_sp, mutbl_self));
3798 vec!(Arg::new_self(explicit_self_sp, mutbl_self))
3801 let token_str = self.this_token_to_str();
3802 self.fatal(format!("expected `,` or `)`, found `{}`",
3803 token_str).as_slice())
3807 let sep = seq_sep_trailing_disallowed(token::COMMA);
3808 self.parse_seq_to_before_end(&token::RPAREN, sep, parse_arg_fn)
3811 self.expect(&token::RPAREN);
3813 let hi = self.span.hi;
3815 let (ret_style, ret_ty) = self.parse_ret_ty();
3817 let fn_decl = P(FnDecl {
3824 (spanned(lo, hi, explicit_self), fn_decl)
3827 // parse the |arg, arg| header on a lambda
3828 fn parse_fn_block_decl(&mut self) -> P<FnDecl> {
3829 let inputs_captures = {
3830 if self.eat(&token::OROR) {
3833 self.parse_unspanned_seq(
3834 &token::BINOP(token::OR),
3835 &token::BINOP(token::OR),
3836 seq_sep_trailing_disallowed(token::COMMA),
3837 |p| p.parse_fn_block_arg()
3841 let output = if self.eat(&token::RARROW) {
3845 id: ast::DUMMY_NODE_ID,
3852 inputs: inputs_captures,
3859 // Parses the `(arg, arg) -> return_type` header on a procedure.
3860 fn parse_proc_decl(&mut self) -> P<FnDecl> {
3862 self.parse_unspanned_seq(&token::LPAREN,
3864 seq_sep_trailing_allowed(token::COMMA),
3865 |p| p.parse_fn_block_arg());
3867 let output = if self.eat(&token::RARROW) {
3871 id: ast::DUMMY_NODE_ID,
3885 // parse the name and optional generic types of a function header.
3886 fn parse_fn_header(&mut self) -> (Ident, ast::Generics) {
3887 let id = self.parse_ident();
3888 let generics = self.parse_generics();
3892 fn mk_item(&mut self, lo: BytePos, hi: BytePos, ident: Ident,
3893 node: Item_, vis: Visibility,
3894 attrs: Vec<Attribute>) -> Gc<Item> {
3898 id: ast::DUMMY_NODE_ID,
3905 // parse an item-position function declaration.
3906 fn parse_item_fn(&mut self, fn_style: FnStyle, abi: abi::Abi) -> ItemInfo {
3907 let (ident, generics) = self.parse_fn_header();
3908 let decl = self.parse_fn_decl(false);
3909 let (inner_attrs, body) = self.parse_inner_attrs_and_block();
3910 (ident, ItemFn(decl, fn_style, abi, generics, body), Some(inner_attrs))
3913 // parse a method in a trait impl, starting with `attrs` attributes.
3914 fn parse_method(&mut self,
3915 already_parsed_attrs: Option<Vec<Attribute>>) -> Gc<Method> {
3916 let next_attrs = self.parse_outer_attributes();
3917 let attrs = match already_parsed_attrs {
3918 Some(mut a) => { a.push_all_move(next_attrs); a }
3922 let lo = self.span.lo;
3924 let visa = self.parse_visibility();
3925 let fn_style = self.parse_fn_style();
3926 let ident = self.parse_ident();
3927 let generics = self.parse_generics();
3928 let (explicit_self, decl) = self.parse_fn_decl_with_self(|p| {
3932 let (inner_attrs, body) = self.parse_inner_attrs_and_block();
3933 let hi = body.span.hi;
3934 let attrs = attrs.append(inner_attrs.as_slice());
3935 box(GC) ast::Method {
3939 explicit_self: explicit_self,
3943 id: ast::DUMMY_NODE_ID,
3944 span: mk_sp(lo, hi),
3949 // parse trait Foo { ... }
3950 fn parse_item_trait(&mut self) -> ItemInfo {
3951 let ident = self.parse_ident();
3952 let tps = self.parse_generics();
3953 let sized = self.parse_for_sized();
3955 // Parse traits, if necessary.
3957 if self.token == token::COLON {
3959 traits = self.parse_trait_ref_list(&token::LBRACE);
3961 traits = Vec::new();
3964 let meths = self.parse_trait_methods();
3965 (ident, ItemTrait(tps, sized, traits, meths), None)
3968 // Parses two variants (with the region/type params always optional):
3969 // impl<T> Foo { ... }
3970 // impl<T> ToStr for ~[T] { ... }
3971 fn parse_item_impl(&mut self) -> ItemInfo {
3972 // First, parse type parameters if necessary.
3973 let generics = self.parse_generics();
3975 // Special case: if the next identifier that follows is '(', don't
3976 // allow this to be parsed as a trait.
3977 let could_be_trait = self.token != token::LPAREN;
3980 let mut ty = self.parse_ty(true);
3982 // Parse traits, if necessary.
3983 let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) {
3984 // New-style trait. Reinterpret the type as a trait.
3985 let opt_trait_ref = match ty.node {
3986 TyPath(ref path, None, node_id) => {
3988 path: /* bad */ (*path).clone(),
3993 self.span_err(ty.span,
3994 "bounded traits are only valid in type position");
3998 self.span_err(ty.span, "not a trait");
4003 ty = self.parse_ty(true);
4009 let mut meths = Vec::new();
4010 self.expect(&token::LBRACE);
4011 let (inner_attrs, next) = self.parse_inner_attrs_and_next();
4012 let mut method_attrs = Some(next);
4013 while !self.eat(&token::RBRACE) {
4014 meths.push(self.parse_method(method_attrs));
4015 method_attrs = None;
4018 let ident = ast_util::impl_pretty_name(&opt_trait, &*ty);
4020 (ident, ItemImpl(generics, opt_trait, ty, meths), Some(inner_attrs))
4023 // parse a::B<String,int>
4024 fn parse_trait_ref(&mut self) -> TraitRef {
4026 path: self.parse_path(LifetimeAndTypesWithoutColons).path,
4027 ref_id: ast::DUMMY_NODE_ID,
4031 // parse B + C<String,int> + D
4032 fn parse_trait_ref_list(&mut self, ket: &token::Token) -> Vec<TraitRef> {
4033 self.parse_seq_to_before_end(
4035 seq_sep_trailing_disallowed(token::BINOP(token::PLUS)),
4036 |p| p.parse_trait_ref()
4040 // parse struct Foo { ... }
4041 fn parse_item_struct(&mut self, is_virtual: bool) -> ItemInfo {
4042 let class_name = self.parse_ident();
4043 let generics = self.parse_generics();
4045 let super_struct = if self.eat(&token::COLON) {
4046 let ty = self.parse_ty(true);
4048 TyPath(_, None, _) => {
4052 self.span_err(ty.span, "not a struct");
4060 let mut fields: Vec<StructField>;
4063 if self.eat(&token::LBRACE) {
4064 // It's a record-like struct.
4065 is_tuple_like = false;
4066 fields = Vec::new();
4067 while self.token != token::RBRACE {
4068 fields.push(self.parse_struct_decl_field());
4070 if fields.len() == 0 {
4071 self.fatal(format!("unit-like struct definition should be \
4072 written as `struct {};`",
4073 token::get_ident(class_name)).as_slice());
4076 } else if self.token == token::LPAREN {
4077 // It's a tuple-like struct.
4078 is_tuple_like = true;
4079 fields = self.parse_unspanned_seq(
4082 seq_sep_trailing_allowed(token::COMMA),
4084 let attrs = p.parse_outer_attributes();
4086 let struct_field_ = ast::StructField_ {
4087 kind: UnnamedField(p.parse_visibility()),
4088 id: ast::DUMMY_NODE_ID,
4089 ty: p.parse_ty(true),
4092 spanned(lo, p.span.hi, struct_field_)
4094 self.expect(&token::SEMI);
4095 } else if self.eat(&token::SEMI) {
4096 // It's a unit-like struct.
4097 is_tuple_like = true;
4098 fields = Vec::new();
4100 let token_str = self.this_token_to_str();
4101 self.fatal(format!("expected `{}`, `(`, or `;` after struct \
4102 name but found `{}`", "{",
4103 token_str).as_slice())
4106 let _ = ast::DUMMY_NODE_ID; // FIXME: Workaround for crazy bug.
4107 let new_id = ast::DUMMY_NODE_ID;
4109 ItemStruct(box(GC) ast::StructDef {
4111 ctor_id: if is_tuple_like { Some(new_id) } else { None },
4112 super_struct: super_struct,
4113 is_virtual: is_virtual,
4118 // parse a structure field declaration
4119 pub fn parse_single_struct_field(&mut self,
4121 attrs: Vec<Attribute> )
4123 let a_var = self.parse_name_and_ty(vis, attrs);
4131 let token_str = self.this_token_to_str();
4132 self.span_fatal(self.span,
4133 format!("expected `,`, or `\\}` but found `{}`",
4134 token_str).as_slice())
4138 let token_str = self.this_token_to_str();
4139 self.span_fatal(self.span,
4140 format!("expected `,`, or `}}` but found `{}`",
4141 token_str).as_slice())
4147 // parse an element of a struct definition
4148 fn parse_struct_decl_field(&mut self) -> StructField {
4150 let attrs = self.parse_outer_attributes();
4152 if self.eat_keyword(keywords::Pub) {
4153 return self.parse_single_struct_field(Public, attrs);
4156 return self.parse_single_struct_field(Inherited, attrs);
4159 // parse visiility: PUB, PRIV, or nothing
4160 fn parse_visibility(&mut self) -> Visibility {
4161 if self.eat_keyword(keywords::Pub) { Public }
4165 fn parse_sized(&mut self) -> Sized {
4166 if self.eat_keyword(keywords::Type) { DynSize }
4170 fn parse_for_sized(&mut self) -> Sized {
4171 if self.eat_keyword(keywords::For) {
4172 if !self.eat_keyword(keywords::Type) {
4173 self.span_err(self.last_span,
4174 "expected 'type' after for in trait item");
4182 // given a termination token and a vector of already-parsed
4183 // attributes (of length 0 or 1), parse all of the items in a module
4184 fn parse_mod_items(&mut self,
4186 first_item_attrs: Vec<Attribute>,
4189 // parse all of the items up to closing or an attribute.
4190 // view items are legal here.
4191 let ParsedItemsAndViewItems {
4192 attrs_remaining: attrs_remaining,
4193 view_items: view_items,
4194 items: starting_items,
4196 } = self.parse_items_and_view_items(first_item_attrs, true, true);
4197 let mut items: Vec<Gc<Item>> = starting_items;
4198 let attrs_remaining_len = attrs_remaining.len();
4200 // don't think this other loop is even necessary....
4202 let mut first = true;
4203 while self.token != term {
4204 let mut attrs = self.parse_outer_attributes();
4206 attrs = attrs_remaining.clone().append(attrs.as_slice());
4209 debug!("parse_mod_items: parse_item_or_view_item(attrs={:?})",
4211 match self.parse_item_or_view_item(attrs,
4212 true /* macros allowed */) {
4213 IoviItem(item) => items.push(item),
4214 IoviViewItem(view_item) => {
4215 self.span_fatal(view_item.span,
4216 "view items must be declared at the top of \
4220 let token_str = self.this_token_to_str();
4221 self.fatal(format!("expected item but found `{}`",
4222 token_str).as_slice())
4227 if first && attrs_remaining_len > 0u {
4228 // We parsed attributes for the first item but didn't find it
4229 self.span_err(self.last_span, "expected item after attributes");
4233 inner: mk_sp(inner_lo, self.span.lo),
4234 view_items: view_items,
4239 fn parse_item_const(&mut self) -> ItemInfo {
4240 let m = if self.eat_keyword(keywords::Mut) {MutMutable} else {MutImmutable};
4241 let id = self.parse_ident();
4242 self.expect(&token::COLON);
4243 let ty = self.parse_ty(true);
4244 self.expect(&token::EQ);
4245 let e = self.parse_expr();
4246 self.commit_expr_expecting(e, token::SEMI);
4247 (id, ItemStatic(ty, m, e), None)
4250 // parse a `mod <foo> { ... }` or `mod <foo>;` item
4251 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> ItemInfo {
4252 let id_span = self.span;
4253 let id = self.parse_ident();
4254 if self.token == token::SEMI {
4256 // This mod is in an external file. Let's go get it!
4257 let (m, attrs) = self.eval_src_mod(id, outer_attrs, id_span);
4258 (id, m, Some(attrs))
4260 self.push_mod_path(id, outer_attrs);
4261 self.expect(&token::LBRACE);
4262 let mod_inner_lo = self.span.lo;
4263 let old_owns_directory = self.owns_directory;
4264 self.owns_directory = true;
4265 let (inner, next) = self.parse_inner_attrs_and_next();
4266 let m = self.parse_mod_items(token::RBRACE, next, mod_inner_lo);
4267 self.expect(&token::RBRACE);
4268 self.owns_directory = old_owns_directory;
4269 self.pop_mod_path();
4270 (id, ItemMod(m), Some(inner))
4274 fn push_mod_path(&mut self, id: Ident, attrs: &[Attribute]) {
4275 let default_path = self.id_to_interned_str(id);
4276 let file_path = match ::attr::first_attr_value_str_by_name(attrs,
4279 None => default_path,
4281 self.mod_path_stack.push(file_path)
4284 fn pop_mod_path(&mut self) {
4285 self.mod_path_stack.pop().unwrap();
4288 // read a module from a source file.
4289 fn eval_src_mod(&mut self,
4291 outer_attrs: &[ast::Attribute],
4293 -> (ast::Item_, Vec<ast::Attribute> ) {
4294 let mut prefix = Path::new(self.sess.span_diagnostic.cm.span_to_filename(self.span));
4296 let mod_path = Path::new(".").join_many(self.mod_path_stack.as_slice());
4297 let dir_path = prefix.join(&mod_path);
4298 let mod_string = token::get_ident(id);
4299 let (file_path, owns_directory) = match ::attr::first_attr_value_str_by_name(
4300 outer_attrs, "path") {
4301 Some(d) => (dir_path.join(d), true),
4303 let mod_name = mod_string.get().to_string();
4304 let default_path_str = format!("{}.rs", mod_name);
4305 let secondary_path_str = format!("{}/mod.rs", mod_name);
4306 let default_path = dir_path.join(default_path_str.as_slice());
4307 let secondary_path = dir_path.join(secondary_path_str.as_slice());
4308 let default_exists = default_path.exists();
4309 let secondary_exists = secondary_path.exists();
4311 if !self.owns_directory {
4312 self.span_err(id_sp,
4313 "cannot declare a new module at this location");
4314 let this_module = match self.mod_path_stack.last() {
4315 Some(name) => name.get().to_string(),
4316 None => self.root_module_name.get_ref().clone(),
4318 self.span_note(id_sp,
4319 format!("maybe move this module `{0}` \
4320 to its own directory via \
4322 this_module).as_slice());
4323 if default_exists || secondary_exists {
4324 self.span_note(id_sp,
4325 format!("... or maybe `use` the module \
4326 `{}` instead of possibly \
4328 mod_name).as_slice());
4330 self.abort_if_errors();
4333 match (default_exists, secondary_exists) {
4334 (true, false) => (default_path, false),
4335 (false, true) => (secondary_path, true),
4337 self.span_fatal(id_sp,
4338 format!("file not found for module \
4340 mod_name).as_slice());
4345 format!("file for module `{}` found at both {} \
4349 secondary_path_str).as_slice());
4355 self.eval_src_mod_from_path(file_path, owns_directory,
4356 mod_string.get().to_string(), id_sp)
4359 fn eval_src_mod_from_path(&mut self,
4361 owns_directory: bool,
4363 id_sp: Span) -> (ast::Item_, Vec<ast::Attribute> ) {
4364 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
4365 match included_mod_stack.iter().position(|p| *p == path) {
4367 let mut err = String::from_str("circular modules: ");
4368 let len = included_mod_stack.len();
4369 for p in included_mod_stack.slice(i, len).iter() {
4370 err.push_str(p.display().as_maybe_owned().as_slice());
4371 err.push_str(" -> ");
4373 err.push_str(path.display().as_maybe_owned().as_slice());
4374 self.span_fatal(id_sp, err.as_slice());
4378 included_mod_stack.push(path.clone());
4379 drop(included_mod_stack);
4382 new_sub_parser_from_file(self.sess,
4388 let mod_inner_lo = p0.span.lo;
4389 let (mod_attrs, next) = p0.parse_inner_attrs_and_next();
4390 let first_item_outer_attrs = next;
4391 let m0 = p0.parse_mod_items(token::EOF, first_item_outer_attrs, mod_inner_lo);
4392 self.sess.included_mod_stack.borrow_mut().pop();
4393 return (ast::ItemMod(m0), mod_attrs);
4396 // parse a function declaration from a foreign module
4397 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility,
4398 attrs: Vec<Attribute>) -> Gc<ForeignItem> {
4399 let lo = self.span.lo;
4400 self.expect_keyword(keywords::Fn);
4402 let (ident, generics) = self.parse_fn_header();
4403 let decl = self.parse_fn_decl(true);
4404 let hi = self.span.hi;
4405 self.expect(&token::SEMI);
4406 box(GC) ast::ForeignItem { ident: ident,
4408 node: ForeignItemFn(decl, generics),
4409 id: ast::DUMMY_NODE_ID,
4410 span: mk_sp(lo, hi),
4414 // parse a static item from a foreign module
4415 fn parse_item_foreign_static(&mut self, vis: ast::Visibility,
4416 attrs: Vec<Attribute> ) -> Gc<ForeignItem> {
4417 let lo = self.span.lo;
4419 self.expect_keyword(keywords::Static);
4420 let mutbl = self.eat_keyword(keywords::Mut);
4422 let ident = self.parse_ident();
4423 self.expect(&token::COLON);
4424 let ty = self.parse_ty(true);
4425 let hi = self.span.hi;
4426 self.expect(&token::SEMI);
4427 box(GC) ast::ForeignItem {
4430 node: ForeignItemStatic(ty, mutbl),
4431 id: ast::DUMMY_NODE_ID,
4432 span: mk_sp(lo, hi),
4437 // parse safe/unsafe and fn
4438 fn parse_fn_style(&mut self) -> FnStyle {
4439 if self.eat_keyword(keywords::Fn) { NormalFn }
4440 else if self.eat_keyword(keywords::Unsafe) {
4441 self.expect_keyword(keywords::Fn);
4444 else { self.unexpected(); }
4448 // at this point, this is essentially a wrapper for
4449 // parse_foreign_items.
4450 fn parse_foreign_mod_items(&mut self,
4452 first_item_attrs: Vec<Attribute> )
4454 let ParsedItemsAndViewItems {
4455 attrs_remaining: attrs_remaining,
4456 view_items: view_items,
4458 foreign_items: foreign_items
4459 } = self.parse_foreign_items(first_item_attrs, true);
4460 if ! attrs_remaining.is_empty() {
4461 self.span_err(self.last_span,
4462 "expected item after attributes");
4464 assert!(self.token == token::RBRACE);
4467 view_items: view_items,
4468 items: foreign_items
4472 /// Parse extern crate links
4476 /// extern crate url;
4477 /// extern crate foo = "bar";
4478 fn parse_item_extern_crate(&mut self,
4480 visibility: Visibility,
4481 attrs: Vec<Attribute> )
4484 let (maybe_path, ident) = match self.token {
4485 token::IDENT(..) => {
4486 let the_ident = self.parse_ident();
4487 self.expect_one_of(&[], &[token::EQ, token::SEMI]);
4488 let path = if self.token == token::EQ {
4490 Some(self.parse_str())
4493 self.expect(&token::SEMI);
4497 let token_str = self.this_token_to_str();
4498 self.span_fatal(self.span,
4499 format!("expected extern crate name but \
4501 token_str).as_slice());
4505 IoviViewItem(ast::ViewItem {
4506 node: ViewItemExternCrate(ident, maybe_path, ast::DUMMY_NODE_ID),
4509 span: mk_sp(lo, self.last_span.hi)
4513 /// Parse `extern` for foreign ABIs
4516 /// `extern` is expected to have been
4517 /// consumed before calling this method
4523 fn parse_item_foreign_mod(&mut self,
4525 opt_abi: Option<abi::Abi>,
4526 visibility: Visibility,
4527 attrs: Vec<Attribute> )
4530 self.expect(&token::LBRACE);
4532 let abi = opt_abi.unwrap_or(abi::C);
4534 let (inner, next) = self.parse_inner_attrs_and_next();
4535 let m = self.parse_foreign_mod_items(abi, next);
4536 self.expect(&token::RBRACE);
4538 let item = self.mk_item(lo,
4540 special_idents::invalid,
4543 maybe_append(attrs, Some(inner)));
4544 return IoviItem(item);
4547 // parse type Foo = Bar;
4548 fn parse_item_type(&mut self) -> ItemInfo {
4549 let ident = self.parse_ident();
4550 let tps = self.parse_generics();
4551 self.expect(&token::EQ);
4552 let ty = self.parse_ty(true);
4553 self.expect(&token::SEMI);
4554 (ident, ItemTy(ty, tps), None)
4557 // parse a structure-like enum variant definition
4558 // this should probably be renamed or refactored...
4559 fn parse_struct_def(&mut self) -> Gc<StructDef> {
4560 let mut fields: Vec<StructField> = Vec::new();
4561 while self.token != token::RBRACE {
4562 fields.push(self.parse_struct_decl_field());
4566 return box(GC) ast::StructDef {
4574 // parse the part of an "enum" decl following the '{'
4575 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> EnumDef {
4576 let mut variants = Vec::new();
4577 let mut all_nullary = true;
4578 let mut have_disr = false;
4579 while self.token != token::RBRACE {
4580 let variant_attrs = self.parse_outer_attributes();
4581 let vlo = self.span.lo;
4583 let vis = self.parse_visibility();
4587 let mut args = Vec::new();
4588 let mut disr_expr = None;
4589 ident = self.parse_ident();
4590 if self.eat(&token::LBRACE) {
4591 // Parse a struct variant.
4592 all_nullary = false;
4593 kind = StructVariantKind(self.parse_struct_def());
4594 } else if self.token == token::LPAREN {
4595 all_nullary = false;
4596 let arg_tys = self.parse_enum_variant_seq(
4599 seq_sep_trailing_disallowed(token::COMMA),
4600 |p| p.parse_ty(true)
4602 for ty in arg_tys.move_iter() {
4603 args.push(ast::VariantArg {
4605 id: ast::DUMMY_NODE_ID,
4608 kind = TupleVariantKind(args);
4609 } else if self.eat(&token::EQ) {
4611 disr_expr = Some(self.parse_expr());
4612 kind = TupleVariantKind(args);
4614 kind = TupleVariantKind(Vec::new());
4617 let vr = ast::Variant_ {
4619 attrs: variant_attrs,
4621 id: ast::DUMMY_NODE_ID,
4622 disr_expr: disr_expr,
4625 variants.push(P(spanned(vlo, self.last_span.hi, vr)));
4627 if !self.eat(&token::COMMA) { break; }
4629 self.expect(&token::RBRACE);
4630 if have_disr && !all_nullary {
4631 self.fatal("discriminator values can only be used with a c-like \
4635 ast::EnumDef { variants: variants }
4638 // parse an "enum" declaration
4639 fn parse_item_enum(&mut self) -> ItemInfo {
4640 let id = self.parse_ident();
4641 let generics = self.parse_generics();
4642 self.expect(&token::LBRACE);
4644 let enum_definition = self.parse_enum_def(&generics);
4645 (id, ItemEnum(enum_definition, generics), None)
4648 fn fn_expr_lookahead(tok: &token::Token) -> bool {
4650 token::LPAREN | token::AT | token::TILDE | token::BINOP(_) => true,
4655 // Parses a string as an ABI spec on an extern type or module. Consumes
4656 // the `extern` keyword, if one is found.
4657 fn parse_opt_abi(&mut self) -> Option<abi::Abi> {
4659 token::LIT_STR(s) | token::LIT_STR_RAW(s, _) => {
4661 let identifier_string = token::get_ident(s);
4662 let the_string = identifier_string.get();
4663 match abi::lookup(the_string) {
4664 Some(abi) => Some(abi),
4668 format!("illegal ABI: expected one of [{}], \
4670 abi::all_names().connect(", "),
4671 the_string).as_slice());
4681 // parse one of the items or view items allowed by the
4682 // flags; on failure, return IoviNone.
4683 // NB: this function no longer parses the items inside an
4685 fn parse_item_or_view_item(&mut self,
4686 attrs: Vec<Attribute> ,
4687 macros_allowed: bool)
4690 INTERPOLATED(token::NtItem(item)) => {
4692 let new_attrs = attrs.append(item.attrs.as_slice());
4693 return IoviItem(box(GC) Item {
4701 let lo = self.span.lo;
4703 let visibility = self.parse_visibility();
4705 // must be a view item:
4706 if self.eat_keyword(keywords::Use) {
4707 // USE ITEM (IoviViewItem)
4708 let view_item = self.parse_use();
4709 self.expect(&token::SEMI);
4710 return IoviViewItem(ast::ViewItem {
4714 span: mk_sp(lo, self.last_span.hi)
4717 // either a view item or an item:
4718 if self.eat_keyword(keywords::Extern) {
4719 let next_is_mod = self.eat_keyword(keywords::Mod);
4721 if next_is_mod || self.eat_keyword(keywords::Crate) {
4723 self.span_err(mk_sp(lo, self.last_span.hi),
4724 format!("`extern mod` is obsolete, use \
4725 `extern crate` instead \
4726 to refer to external \
4727 crates.").as_slice())
4729 return self.parse_item_extern_crate(lo, visibility, attrs);
4732 let opt_abi = self.parse_opt_abi();
4734 if self.eat_keyword(keywords::Fn) {
4735 // EXTERN FUNCTION ITEM
4736 let abi = opt_abi.unwrap_or(abi::C);
4737 let (ident, item_, extra_attrs) =
4738 self.parse_item_fn(NormalFn, abi);
4739 let item = self.mk_item(lo,
4744 maybe_append(attrs, extra_attrs));
4745 return IoviItem(item);
4746 } else if self.token == token::LBRACE {
4747 return self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs);
4750 let token_str = self.this_token_to_str();
4751 self.span_fatal(self.span,
4752 format!("expected `{}` or `fn` but found `{}`", "{",
4753 token_str).as_slice());
4756 let is_virtual = self.eat_keyword(keywords::Virtual);
4757 if is_virtual && !self.is_keyword(keywords::Struct) {
4758 self.span_err(self.span,
4759 "`virtual` keyword may only be used with `struct`");
4762 // the rest are all guaranteed to be items:
4763 if self.is_keyword(keywords::Static) {
4766 let (ident, item_, extra_attrs) = self.parse_item_const();
4767 let item = self.mk_item(lo,
4772 maybe_append(attrs, extra_attrs));
4773 return IoviItem(item);
4775 if self.is_keyword(keywords::Fn) &&
4776 self.look_ahead(1, |f| !Parser::fn_expr_lookahead(f)) {
4779 let (ident, item_, extra_attrs) =
4780 self.parse_item_fn(NormalFn, abi::Rust);
4781 let item = self.mk_item(lo,
4786 maybe_append(attrs, extra_attrs));
4787 return IoviItem(item);
4789 if self.is_keyword(keywords::Unsafe)
4790 && self.look_ahead(1u, |t| *t != token::LBRACE) {
4791 // UNSAFE FUNCTION ITEM
4793 let abi = if self.eat_keyword(keywords::Extern) {
4794 self.parse_opt_abi().unwrap_or(abi::C)
4798 self.expect_keyword(keywords::Fn);
4799 let (ident, item_, extra_attrs) =
4800 self.parse_item_fn(UnsafeFn, abi);
4801 let item = self.mk_item(lo,
4806 maybe_append(attrs, extra_attrs));
4807 return IoviItem(item);
4809 if self.eat_keyword(keywords::Mod) {
4811 let (ident, item_, extra_attrs) =
4812 self.parse_item_mod(attrs.as_slice());
4813 let item = self.mk_item(lo,
4818 maybe_append(attrs, extra_attrs));
4819 return IoviItem(item);
4821 if self.eat_keyword(keywords::Type) {
4823 let (ident, item_, extra_attrs) = self.parse_item_type();
4824 let item = self.mk_item(lo,
4829 maybe_append(attrs, extra_attrs));
4830 return IoviItem(item);
4832 if self.eat_keyword(keywords::Enum) {
4834 let (ident, item_, extra_attrs) = self.parse_item_enum();
4835 let item = self.mk_item(lo,
4840 maybe_append(attrs, extra_attrs));
4841 return IoviItem(item);
4843 if self.eat_keyword(keywords::Trait) {
4845 let (ident, item_, extra_attrs) = self.parse_item_trait();
4846 let item = self.mk_item(lo,
4851 maybe_append(attrs, extra_attrs));
4852 return IoviItem(item);
4854 if self.eat_keyword(keywords::Impl) {
4856 let (ident, item_, extra_attrs) = self.parse_item_impl();
4857 let item = self.mk_item(lo,
4862 maybe_append(attrs, extra_attrs));
4863 return IoviItem(item);
4865 if self.eat_keyword(keywords::Struct) {
4867 let (ident, item_, extra_attrs) = self.parse_item_struct(is_virtual);
4868 let item = self.mk_item(lo,
4873 maybe_append(attrs, extra_attrs));
4874 return IoviItem(item);
4876 self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility)
4879 // parse a foreign item; on failure, return IoviNone.
4880 fn parse_foreign_item(&mut self,
4881 attrs: Vec<Attribute> ,
4882 macros_allowed: bool)
4884 maybe_whole!(iovi self, NtItem);
4885 let lo = self.span.lo;
4887 let visibility = self.parse_visibility();
4889 if self.is_keyword(keywords::Static) {
4890 // FOREIGN STATIC ITEM
4891 let item = self.parse_item_foreign_static(visibility, attrs);
4892 return IoviForeignItem(item);
4894 if self.is_keyword(keywords::Fn) || self.is_keyword(keywords::Unsafe) {
4895 // FOREIGN FUNCTION ITEM
4896 let item = self.parse_item_foreign_fn(visibility, attrs);
4897 return IoviForeignItem(item);
4899 self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility)
4902 // this is the fall-through for parsing items.
4903 fn parse_macro_use_or_failure(
4905 attrs: Vec<Attribute> ,
4906 macros_allowed: bool,
4908 visibility: Visibility
4909 ) -> ItemOrViewItem {
4910 if macros_allowed && !token::is_any_keyword(&self.token)
4911 && self.look_ahead(1, |t| *t == token::NOT)
4912 && (self.look_ahead(2, |t| is_plain_ident(t))
4913 || self.look_ahead(2, |t| *t == token::LPAREN)
4914 || self.look_ahead(2, |t| *t == token::LBRACE)) {
4915 // MACRO INVOCATION ITEM
4918 let pth = self.parse_path(NoTypesAllowed).path;
4919 self.expect(&token::NOT);
4921 // a 'special' identifier (like what `macro_rules!` uses)
4922 // is optional. We should eventually unify invoc syntax
4924 let id = if is_plain_ident(&self.token) {
4927 token::special_idents::invalid // no special identifier
4929 // eat a matched-delimiter token tree:
4930 let tts = match token::close_delimiter_for(&self.token) {
4933 self.parse_seq_to_end(&ket,
4935 |p| p.parse_token_tree())
4937 None => self.fatal("expected open delimiter")
4939 // single-variant-enum... :
4940 let m = ast::MacInvocTT(pth, tts, EMPTY_CTXT);
4941 let m: ast::Mac = codemap::Spanned { node: m,
4942 span: mk_sp(self.span.lo,
4944 let item_ = ItemMac(m);
4945 let item = self.mk_item(lo,
4951 return IoviItem(item);
4954 // FAILURE TO PARSE ITEM
4955 if visibility != Inherited {
4956 let mut s = String::from_str("unmatched visibility `");
4957 if visibility == Public {
4963 self.span_fatal(self.last_span, s.as_slice());
4965 return IoviNone(attrs);
4968 pub fn parse_item_with_outer_attributes(&mut self) -> Option<Gc<Item>> {
4969 let attrs = self.parse_outer_attributes();
4970 self.parse_item(attrs)
4973 pub fn parse_item(&mut self, attrs: Vec<Attribute> ) -> Option<Gc<Item>> {
4974 match self.parse_item_or_view_item(attrs, true) {
4975 IoviNone(_) => None,
4977 self.fatal("view items are not allowed here"),
4978 IoviForeignItem(_) =>
4979 self.fatal("foreign items are not allowed here"),
4980 IoviItem(item) => Some(item)
4984 // parse, e.g., "use a::b::{z,y}"
4985 fn parse_use(&mut self) -> ViewItem_ {
4986 return ViewItemUse(self.parse_view_path());
4990 // matches view_path : MOD? IDENT EQ non_global_path
4991 // | MOD? non_global_path MOD_SEP LBRACE RBRACE
4992 // | MOD? non_global_path MOD_SEP LBRACE ident_seq RBRACE
4993 // | MOD? non_global_path MOD_SEP STAR
4994 // | MOD? non_global_path
4995 fn parse_view_path(&mut self) -> Gc<ViewPath> {
4996 let lo = self.span.lo;
4998 if self.token == token::LBRACE {
5000 let idents = self.parse_unspanned_seq(
5001 &token::LBRACE, &token::RBRACE,
5002 seq_sep_trailing_allowed(token::COMMA),
5003 |p| p.parse_path_list_ident());
5004 let path = ast::Path {
5005 span: mk_sp(lo, self.span.hi),
5007 segments: Vec::new()
5009 return box(GC) spanned(lo, self.span.hi,
5010 ViewPathList(path, idents, ast::DUMMY_NODE_ID));
5013 let first_ident = self.parse_ident();
5014 let mut path = vec!(first_ident);
5019 let path_lo = self.span.lo;
5020 path = vec!(self.parse_ident());
5021 while self.token == token::MOD_SEP {
5023 let id = self.parse_ident();
5026 let path = ast::Path {
5027 span: mk_sp(path_lo, self.span.hi),
5029 segments: path.move_iter().map(|identifier| {
5031 identifier: identifier,
5032 lifetimes: Vec::new(),
5033 types: OwnedSlice::empty(),
5037 return box(GC) spanned(lo, self.span.hi,
5038 ViewPathSimple(first_ident, path,
5039 ast::DUMMY_NODE_ID));
5043 // foo::bar or foo::{a,b,c} or foo::*
5044 while self.token == token::MOD_SEP {
5048 token::IDENT(i, _) => {
5053 // foo::bar::{a,b,c}
5055 let idents = self.parse_unspanned_seq(
5058 seq_sep_trailing_allowed(token::COMMA),
5059 |p| p.parse_path_list_ident()
5061 let path = ast::Path {
5062 span: mk_sp(lo, self.span.hi),
5064 segments: path.move_iter().map(|identifier| {
5066 identifier: identifier,
5067 lifetimes: Vec::new(),
5068 types: OwnedSlice::empty(),
5072 return box(GC) spanned(lo, self.span.hi,
5073 ViewPathList(path, idents, ast::DUMMY_NODE_ID));
5077 token::BINOP(token::STAR) => {
5079 let path = ast::Path {
5080 span: mk_sp(lo, self.span.hi),
5082 segments: path.move_iter().map(|identifier| {
5084 identifier: identifier,
5085 lifetimes: Vec::new(),
5086 types: OwnedSlice::empty(),
5090 return box(GC) spanned(lo, self.span.hi,
5091 ViewPathGlob(path, ast::DUMMY_NODE_ID));
5100 let last = *path.get(path.len() - 1u);
5101 let path = ast::Path {
5102 span: mk_sp(lo, self.span.hi),
5104 segments: path.move_iter().map(|identifier| {
5106 identifier: identifier,
5107 lifetimes: Vec::new(),
5108 types: OwnedSlice::empty(),
5112 return box(GC) spanned(lo,
5114 ViewPathSimple(last, path, ast::DUMMY_NODE_ID));
5117 // Parses a sequence of items. Stops when it finds program
5118 // text that can't be parsed as an item
5119 // - mod_items uses extern_mod_allowed = true
5120 // - block_tail_ uses extern_mod_allowed = false
5121 fn parse_items_and_view_items(&mut self,
5122 first_item_attrs: Vec<Attribute> ,
5123 mut extern_mod_allowed: bool,
5124 macros_allowed: bool)
5125 -> ParsedItemsAndViewItems {
5126 let mut attrs = first_item_attrs.append(self.parse_outer_attributes().as_slice());
5127 // First, parse view items.
5128 let mut view_items : Vec<ast::ViewItem> = Vec::new();
5129 let mut items = Vec::new();
5131 // I think this code would probably read better as a single
5132 // loop with a mutable three-state-variable (for extern crates,
5133 // view items, and regular items) ... except that because
5134 // of macros, I'd like to delay that entire check until later.
5136 match self.parse_item_or_view_item(attrs, macros_allowed) {
5137 IoviNone(attrs) => {
5138 return ParsedItemsAndViewItems {
5139 attrs_remaining: attrs,
5140 view_items: view_items,
5142 foreign_items: Vec::new()
5145 IoviViewItem(view_item) => {
5146 match view_item.node {
5147 ViewItemUse(..) => {
5148 // `extern crate` must precede `use`.
5149 extern_mod_allowed = false;
5151 ViewItemExternCrate(..) if !extern_mod_allowed => {
5152 self.span_err(view_item.span,
5153 "\"extern crate\" declarations are \
5156 ViewItemExternCrate(..) => {}
5158 view_items.push(view_item);
5162 attrs = self.parse_outer_attributes();
5165 IoviForeignItem(_) => {
5169 attrs = self.parse_outer_attributes();
5172 // Next, parse items.
5174 match self.parse_item_or_view_item(attrs, macros_allowed) {
5175 IoviNone(returned_attrs) => {
5176 attrs = returned_attrs;
5179 IoviViewItem(view_item) => {
5180 attrs = self.parse_outer_attributes();
5181 self.span_err(view_item.span,
5182 "`use` and `extern crate` declarations must precede items");
5185 attrs = self.parse_outer_attributes();
5188 IoviForeignItem(_) => {
5194 ParsedItemsAndViewItems {
5195 attrs_remaining: attrs,
5196 view_items: view_items,
5198 foreign_items: Vec::new()
5202 // Parses a sequence of foreign items. Stops when it finds program
5203 // text that can't be parsed as an item
5204 fn parse_foreign_items(&mut self, first_item_attrs: Vec<Attribute> ,
5205 macros_allowed: bool)
5206 -> ParsedItemsAndViewItems {
5207 let mut attrs = first_item_attrs.append(self.parse_outer_attributes().as_slice());
5208 let mut foreign_items = Vec::new();
5210 match self.parse_foreign_item(attrs, macros_allowed) {
5211 IoviNone(returned_attrs) => {
5212 if self.token == token::RBRACE {
5213 attrs = returned_attrs;
5218 IoviViewItem(view_item) => {
5219 // I think this can't occur:
5220 self.span_err(view_item.span,
5221 "`use` and `extern crate` declarations must precede items");
5224 // FIXME #5668: this will occur for a macro invocation:
5225 self.span_fatal(item.span, "macros cannot expand to foreign items");
5227 IoviForeignItem(foreign_item) => {
5228 foreign_items.push(foreign_item);
5231 attrs = self.parse_outer_attributes();
5234 ParsedItemsAndViewItems {
5235 attrs_remaining: attrs,
5236 view_items: Vec::new(),
5238 foreign_items: foreign_items
5242 // Parses a source module as a crate. This is the main
5243 // entry point for the parser.
5244 pub fn parse_crate_mod(&mut self) -> Crate {
5245 let lo = self.span.lo;
5246 // parse the crate's inner attrs, maybe (oops) one
5247 // of the attrs of an item:
5248 let (inner, next) = self.parse_inner_attrs_and_next();
5249 let first_item_outer_attrs = next;
5250 // parse the items inside the crate:
5251 let m = self.parse_mod_items(token::EOF, first_item_outer_attrs, lo);
5256 config: self.cfg.clone(),
5257 span: mk_sp(lo, self.span.lo)
5261 pub fn parse_optional_str(&mut self)
5262 -> Option<(InternedString, ast::StrStyle)> {
5263 let (s, style) = match self.token {
5264 token::LIT_STR(s) => (self.id_to_interned_str(s), ast::CookedStr),
5265 token::LIT_STR_RAW(s, n) => {
5266 (self.id_to_interned_str(s), ast::RawStr(n))
5274 pub fn parse_str(&mut self) -> (InternedString, StrStyle) {
5275 match self.parse_optional_str() {
5277 _ => self.fatal("expected string literal")