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, 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);
1018 let (_, bounds) = self.parse_optional_ty_param_bounds(false);
1019 let (ret_style, ret_ty) = self.parse_ret_ty();
1020 let decl = P(FnDecl {
1026 TyProc(box(GC) ClosureTy {
1031 lifetimes: lifetimes,
1035 // parse a TyClosure type
1036 pub fn parse_ty_closure(&mut self) -> Ty_ {
1039 [unsafe] [once] <'lt> |S| [:Bounds] -> T
1040 ^~~~~~~^ ^~~~~^ ^~~~^ ^ ^~~~~~~~^ ^
1042 | | | | | Return type
1043 | | | | Closure bounds
1044 | | | Argument types
1046 | Once-ness (a.k.a., affine)
1051 let fn_style = self.parse_unsafety();
1052 let onceness = if self.eat_keyword(keywords::Once) {Once} else {Many};
1054 let lifetimes = if self.eat(&token::LT) {
1055 let lifetimes = self.parse_lifetimes();
1063 let (is_unboxed, inputs) = if self.eat(&token::OROR) {
1068 let is_unboxed = self.token == token::BINOP(token::AND) &&
1069 self.look_ahead(1, |t| {
1070 token::is_keyword(keywords::Mut, t)
1072 self.look_ahead(2, |t| *t == token::COLON);
1079 let inputs = self.parse_seq_to_before_or(
1081 |p| p.parse_arg_general(false));
1083 (is_unboxed, inputs)
1086 let (region, bounds) = self.parse_optional_ty_param_bounds(true);
1088 let (return_style, output) = self.parse_ret_ty();
1089 let decl = P(FnDecl {
1097 TyUnboxedFn(box(GC) UnboxedFnTy {
1101 TyClosure(box(GC) ClosureTy {
1106 lifetimes: lifetimes,
1111 pub fn parse_unsafety(&mut self) -> FnStyle {
1112 if self.eat_keyword(keywords::Unsafe) {
1119 // parse a function type (following the 'fn')
1120 pub fn parse_ty_fn_decl(&mut self, allow_variadic: bool)
1121 -> (P<FnDecl>, Vec<ast::Lifetime>) {
1132 let lifetimes = if self.eat(&token::LT) {
1133 let lifetimes = self.parse_lifetimes();
1140 let (inputs, variadic) = self.parse_fn_args(false, allow_variadic);
1141 let (ret_style, ret_ty) = self.parse_ret_ty();
1142 let decl = P(FnDecl {
1151 // parse the methods in a trait declaration
1152 pub fn parse_trait_methods(&mut self) -> Vec<TraitMethod> {
1153 self.parse_unspanned_seq(
1158 let attrs = p.parse_outer_attributes();
1161 // NB: at the moment, trait methods are public by default; this
1163 let vis = p.parse_visibility();
1164 let style = p.parse_fn_style();
1165 let ident = p.parse_ident();
1167 let generics = p.parse_generics();
1169 let (explicit_self, d) = p.parse_fn_decl_with_self(|p| {
1170 // This is somewhat dubious; We don't want to allow argument
1171 // names to be left off if there is a definition...
1172 p.parse_arg_general(false)
1175 let hi = p.last_span.hi;
1179 debug!("parse_trait_methods(): parsing required method");
1180 Required(TypeMethod {
1186 explicit_self: explicit_self,
1187 id: ast::DUMMY_NODE_ID,
1188 span: mk_sp(lo, hi),
1193 debug!("parse_trait_methods(): parsing provided method");
1194 let (inner_attrs, body) =
1195 p.parse_inner_attrs_and_block();
1196 let attrs = attrs.append(inner_attrs.as_slice());
1197 Provided(box(GC) ast::Method {
1201 explicit_self: explicit_self,
1205 id: ast::DUMMY_NODE_ID,
1206 span: mk_sp(lo, hi),
1213 let token_str = p.this_token_to_str();
1214 p.fatal((format!("expected `;` or `\\{` but found `{}`",
1215 token_str)).as_slice())
1219 let token_str = p.this_token_to_str();
1220 p.fatal((format!("expected `;` or `{{` but found `{}`",
1221 token_str)).as_slice())
1227 // parse a possibly mutable type
1228 pub fn parse_mt(&mut self) -> MutTy {
1229 let mutbl = self.parse_mutability();
1230 let t = self.parse_ty(false);
1231 MutTy { ty: t, mutbl: mutbl }
1234 // parse [mut/const/imm] ID : TY
1235 // now used only by obsolete record syntax parser...
1236 pub fn parse_ty_field(&mut self) -> TypeField {
1237 let lo = self.span.lo;
1238 let mutbl = self.parse_mutability();
1239 let id = self.parse_ident();
1240 self.expect(&token::COLON);
1241 let ty = self.parse_ty(false);
1242 let hi = ty.span.hi;
1245 mt: MutTy { ty: ty, mutbl: mutbl },
1246 span: mk_sp(lo, hi),
1250 // parse optional return type [ -> TY ] in function decl
1251 pub fn parse_ret_ty(&mut self) -> (RetStyle, P<Ty>) {
1252 return if self.eat(&token::RARROW) {
1253 let lo = self.span.lo;
1254 if self.eat(&token::NOT) {
1258 id: ast::DUMMY_NODE_ID,
1260 span: mk_sp(lo, self.last_span.hi)
1264 (Return, self.parse_ty(false))
1267 let pos = self.span.lo;
1271 id: ast::DUMMY_NODE_ID,
1273 span: mk_sp(pos, pos),
1280 // Useless second parameter for compatibility with quasiquote macros.
1282 pub fn parse_ty(&mut self, _: bool) -> P<Ty> {
1283 maybe_whole!(no_clone self, NtTy);
1285 let lo = self.span.lo;
1287 let t = if self.token == token::LPAREN {
1289 if self.token == token::RPAREN {
1293 // (t) is a parenthesized ty
1294 // (t,) is the type of a tuple with only one field,
1296 let mut ts = vec!(self.parse_ty(false));
1297 let mut one_tuple = false;
1298 while self.token == token::COMMA {
1300 if self.token != token::RPAREN {
1301 ts.push(self.parse_ty(false));
1308 if ts.len() == 1 && !one_tuple {
1309 self.expect(&token::RPAREN);
1314 self.expect(&token::RPAREN);
1317 } else if self.token == token::AT {
1320 TyBox(self.parse_ty(false))
1321 } else if self.token == token::TILDE {
1326 self.obsolete(self.last_span, ObsoleteOwnedVector),
1327 _ => self.obsolete(self.last_span, ObsoleteOwnedType),
1329 TyUniq(self.parse_ty(false))
1330 } else if self.token == token::BINOP(token::STAR) {
1331 // STAR POINTER (bare pointer?)
1333 TyPtr(self.parse_mt())
1334 } else if self.token == token::LBRACKET {
1336 self.expect(&token::LBRACKET);
1337 let t = self.parse_ty(false);
1339 // Parse the `, ..e` in `[ int, ..e ]`
1340 // where `e` is a const expression
1341 let t = match self.maybe_parse_fixed_vstore() {
1343 Some(suffix) => TyFixedLengthVec(t, suffix)
1345 self.expect(&token::RBRACKET);
1347 } else if self.token == token::BINOP(token::AND) ||
1348 self.token == token::ANDAND {
1351 self.parse_borrowed_pointee()
1352 } else if self.is_keyword(keywords::Extern) ||
1353 self.is_keyword(keywords::Unsafe) ||
1354 self.token_is_bare_fn_keyword() {
1356 self.parse_ty_bare_fn()
1357 } else if self.token_is_closure_keyword() ||
1358 self.token == token::BINOP(token::OR) ||
1359 self.token == token::OROR ||
1360 self.token == token::LT {
1363 // FIXME(pcwalton): Eventually `token::LT` will not unambiguously
1364 // introduce a closure, once procs can have lifetime bounds. We
1365 // will need to refactor the grammar a little bit at that point.
1367 self.parse_ty_closure()
1368 } else if self.eat_keyword(keywords::Typeof) {
1370 // In order to not be ambiguous, the type must be surrounded by parens.
1371 self.expect(&token::LPAREN);
1372 let e = self.parse_expr();
1373 self.expect(&token::RPAREN);
1375 } else if self.eat_keyword(keywords::Proc) {
1376 self.parse_proc_type()
1377 } else if self.token == token::MOD_SEP
1378 || is_ident_or_path(&self.token) {
1383 } = self.parse_path(LifetimeAndTypesAndBounds);
1384 TyPath(path, bounds, ast::DUMMY_NODE_ID)
1385 } else if self.eat(&token::UNDERSCORE) {
1386 // TYPE TO BE INFERRED
1389 let msg = format!("expected type, found token {:?}", self.token);
1390 self.fatal(msg.as_slice());
1393 let sp = mk_sp(lo, self.last_span.hi);
1394 P(Ty {id: ast::DUMMY_NODE_ID, node: t, span: sp})
1397 pub fn parse_borrowed_pointee(&mut self) -> Ty_ {
1398 // look for `&'lt` or `&'foo ` and interpret `foo` as the region name:
1399 let opt_lifetime = self.parse_opt_lifetime();
1401 let mt = self.parse_mt();
1402 return TyRptr(opt_lifetime, mt);
1405 pub fn is_named_argument(&mut self) -> bool {
1406 let offset = match self.token {
1407 token::BINOP(token::AND) => 1,
1409 _ if token::is_keyword(keywords::Mut, &self.token) => 1,
1413 debug!("parser is_named_argument offset:{}", offset);
1416 is_plain_ident_or_underscore(&self.token)
1417 && self.look_ahead(1, |t| *t == token::COLON)
1419 self.look_ahead(offset, |t| is_plain_ident_or_underscore(t))
1420 && self.look_ahead(offset + 1, |t| *t == token::COLON)
1424 // This version of parse arg doesn't necessarily require
1425 // identifier names.
1426 pub fn parse_arg_general(&mut self, require_name: bool) -> Arg {
1427 let pat = if require_name || self.is_named_argument() {
1428 debug!("parse_arg_general parse_pat (require_name:{:?})",
1430 let pat = self.parse_pat();
1432 self.expect(&token::COLON);
1435 debug!("parse_arg_general ident_to_pat");
1436 ast_util::ident_to_pat(ast::DUMMY_NODE_ID,
1438 special_idents::invalid)
1441 let t = self.parse_ty(false);
1446 id: ast::DUMMY_NODE_ID,
1450 // parse a single function argument
1451 pub fn parse_arg(&mut self) -> Arg {
1452 self.parse_arg_general(true)
1455 // parse an argument in a lambda header e.g. |arg, arg|
1456 pub fn parse_fn_block_arg(&mut self) -> Arg {
1457 let pat = self.parse_pat();
1458 let t = if self.eat(&token::COLON) {
1459 self.parse_ty(false)
1462 id: ast::DUMMY_NODE_ID,
1464 span: mk_sp(self.span.lo, self.span.hi),
1470 id: ast::DUMMY_NODE_ID
1474 pub fn maybe_parse_fixed_vstore(&mut self) -> Option<Gc<ast::Expr>> {
1475 if self.token == token::COMMA &&
1476 self.look_ahead(1, |t| *t == token::DOTDOT) {
1479 Some(self.parse_expr())
1485 // matches token_lit = LIT_INT | ...
1486 pub fn lit_from_token(&mut self, tok: &token::Token) -> Lit_ {
1488 token::LIT_CHAR(i) => LitChar(i),
1489 token::LIT_INT(i, it) => LitInt(i, it),
1490 token::LIT_UINT(u, ut) => LitUint(u, ut),
1491 token::LIT_INT_UNSUFFIXED(i) => LitIntUnsuffixed(i),
1492 token::LIT_FLOAT(s, ft) => {
1493 LitFloat(self.id_to_interned_str(s), ft)
1495 token::LIT_FLOAT_UNSUFFIXED(s) => {
1496 LitFloatUnsuffixed(self.id_to_interned_str(s))
1498 token::LIT_STR(s) => {
1499 LitStr(self.id_to_interned_str(s), ast::CookedStr)
1501 token::LIT_STR_RAW(s, n) => {
1502 LitStr(self.id_to_interned_str(s), ast::RawStr(n))
1504 token::LPAREN => { self.expect(&token::RPAREN); LitNil },
1505 _ => { self.unexpected_last(tok); }
1509 // matches lit = true | false | token_lit
1510 pub fn parse_lit(&mut self) -> Lit {
1511 let lo = self.span.lo;
1512 let lit = if self.eat_keyword(keywords::True) {
1514 } else if self.eat_keyword(keywords::False) {
1517 let token = self.bump_and_get();
1518 let lit = self.lit_from_token(&token);
1521 codemap::Spanned { node: lit, span: mk_sp(lo, self.last_span.hi) }
1524 // matches '-' lit | lit
1525 pub fn parse_literal_maybe_minus(&mut self) -> Gc<Expr> {
1526 let minus_lo = self.span.lo;
1527 let minus_present = self.eat(&token::BINOP(token::MINUS));
1529 let lo = self.span.lo;
1530 let literal = box(GC) self.parse_lit();
1531 let hi = self.span.hi;
1532 let expr = self.mk_expr(lo, hi, ExprLit(literal));
1535 let minus_hi = self.span.hi;
1536 let unary = self.mk_unary(UnNeg, expr);
1537 self.mk_expr(minus_lo, minus_hi, unary)
1543 /// Parses a path and optional type parameter bounds, depending on the
1544 /// mode. The `mode` parameter determines whether lifetimes, types, and/or
1545 /// bounds are permitted and whether `::` must precede type parameter
1547 pub fn parse_path(&mut self, mode: PathParsingMode) -> PathAndBounds {
1548 // Check for a whole path...
1549 let found = match self.token {
1550 INTERPOLATED(token::NtPath(_)) => Some(self.bump_and_get()),
1554 Some(INTERPOLATED(token::NtPath(box path))) => {
1555 return PathAndBounds {
1563 let lo = self.span.lo;
1564 let is_global = self.eat(&token::MOD_SEP);
1566 // Parse any number of segments and bound sets. A segment is an
1567 // identifier followed by an optional lifetime and a set of types.
1568 // A bound set is a set of type parameter bounds.
1569 let mut segments = Vec::new();
1571 // First, parse an identifier.
1572 let identifier = self.parse_ident();
1574 // Parse the '::' before type parameters if it's required. If
1575 // it is required and wasn't present, then we're done.
1576 if mode == LifetimeAndTypesWithColons &&
1577 !self.eat(&token::MOD_SEP) {
1578 segments.push(ast::PathSegment {
1579 identifier: identifier,
1580 lifetimes: Vec::new(),
1581 types: OwnedSlice::empty(),
1586 // Parse the `<` before the lifetime and types, if applicable.
1587 let (any_lifetime_or_types, lifetimes, types) = {
1588 if mode != NoTypesAllowed && self.eat_lt(false) {
1589 let (lifetimes, types) =
1590 self.parse_generic_values_after_lt();
1591 (true, lifetimes, OwnedSlice::from_vec(types))
1593 (false, Vec::new(), OwnedSlice::empty())
1597 // Assemble and push the result.
1598 segments.push(ast::PathSegment {
1599 identifier: identifier,
1600 lifetimes: lifetimes,
1604 // We're done if we don't see a '::', unless the mode required
1605 // a double colon to get here in the first place.
1606 if !(mode == LifetimeAndTypesWithColons &&
1607 !any_lifetime_or_types) {
1608 if !self.eat(&token::MOD_SEP) {
1614 // Next, parse a colon and bounded type parameters, if applicable.
1615 let bounds = if mode == LifetimeAndTypesAndBounds {
1616 let (_, bounds) = self.parse_optional_ty_param_bounds(false);
1622 // Assemble the span.
1623 let span = mk_sp(lo, self.last_span.hi);
1625 // Assemble the result.
1636 /// parses 0 or 1 lifetime
1637 pub fn parse_opt_lifetime(&mut self) -> Option<ast::Lifetime> {
1639 token::LIFETIME(..) => {
1640 Some(self.parse_lifetime())
1648 /// Parses a single lifetime
1649 // matches lifetime = LIFETIME
1650 pub fn parse_lifetime(&mut self) -> ast::Lifetime {
1652 token::LIFETIME(i) => {
1653 let span = self.span;
1655 return ast::Lifetime {
1656 id: ast::DUMMY_NODE_ID,
1662 self.fatal(format!("expected a lifetime name").as_slice());
1667 // matches lifetimes = ( lifetime ) | ( lifetime , lifetimes )
1668 // actually, it matches the empty one too, but putting that in there
1669 // messes up the grammar....
1670 pub fn parse_lifetimes(&mut self) -> Vec<ast::Lifetime> {
1673 * Parses zero or more comma separated lifetimes.
1674 * Expects each lifetime to be followed by either
1675 * a comma or `>`. Used when parsing type parameter
1676 * lists, where we expect something like `<'a, 'b, T>`.
1679 let mut res = Vec::new();
1682 token::LIFETIME(_) => {
1683 res.push(self.parse_lifetime());
1691 token::COMMA => { self.bump();}
1692 token::GT => { return res; }
1693 token::BINOP(token::SHR) => { return res; }
1695 let msg = format!("expected `,` or `>` after lifetime \
1698 self.fatal(msg.as_slice());
1704 pub fn token_is_mutability(tok: &token::Token) -> bool {
1705 token::is_keyword(keywords::Mut, tok) ||
1706 token::is_keyword(keywords::Const, tok)
1709 // parse mutability declaration (mut/const/imm)
1710 pub fn parse_mutability(&mut self) -> Mutability {
1711 if self.eat_keyword(keywords::Mut) {
1718 // parse ident COLON expr
1719 pub fn parse_field(&mut self) -> Field {
1720 let lo = self.span.lo;
1721 let i = self.parse_ident();
1722 let hi = self.last_span.hi;
1723 self.expect(&token::COLON);
1724 let e = self.parse_expr();
1726 ident: spanned(lo, hi, i),
1728 span: mk_sp(lo, e.span.hi),
1732 pub fn mk_expr(&mut self, lo: BytePos, hi: BytePos, node: Expr_) -> Gc<Expr> {
1734 id: ast::DUMMY_NODE_ID,
1736 span: mk_sp(lo, hi),
1740 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: Gc<Expr>) -> ast::Expr_ {
1741 ExprUnary(unop, expr)
1744 pub fn mk_binary(&mut self, binop: ast::BinOp,
1745 lhs: Gc<Expr>, rhs: Gc<Expr>) -> ast::Expr_ {
1746 ExprBinary(binop, lhs, rhs)
1749 pub fn mk_call(&mut self, f: Gc<Expr>, args: Vec<Gc<Expr>>) -> ast::Expr_ {
1753 fn mk_method_call(&mut self,
1754 ident: ast::SpannedIdent,
1756 args: Vec<Gc<Expr>>)
1758 ExprMethodCall(ident, tps, args)
1761 pub fn mk_index(&mut self, expr: Gc<Expr>, idx: Gc<Expr>) -> ast::Expr_ {
1762 ExprIndex(expr, idx)
1765 pub fn mk_field(&mut self, expr: Gc<Expr>, ident: Ident,
1766 tys: Vec<P<Ty>>) -> ast::Expr_ {
1767 ExprField(expr, ident, tys)
1770 pub fn mk_assign_op(&mut self, binop: ast::BinOp,
1771 lhs: Gc<Expr>, rhs: Gc<Expr>) -> ast::Expr_ {
1772 ExprAssignOp(binop, lhs, rhs)
1775 pub fn mk_mac_expr(&mut self, lo: BytePos, hi: BytePos, m: Mac_) -> Gc<Expr> {
1777 id: ast::DUMMY_NODE_ID,
1778 node: ExprMac(codemap::Spanned {node: m, span: mk_sp(lo, hi)}),
1779 span: mk_sp(lo, hi),
1783 pub fn mk_lit_u32(&mut self, i: u32) -> Gc<Expr> {
1784 let span = &self.span;
1785 let lv_lit = box(GC) codemap::Spanned {
1786 node: LitUint(i as u64, TyU32),
1791 id: ast::DUMMY_NODE_ID,
1792 node: ExprLit(lv_lit),
1797 // at the bottom (top?) of the precedence hierarchy,
1798 // parse things like parenthesized exprs,
1799 // macros, return, etc.
1800 pub fn parse_bottom_expr(&mut self) -> Gc<Expr> {
1801 maybe_whole_expr!(self);
1803 let lo = self.span.lo;
1804 let mut hi = self.span.hi;
1808 if self.token == token::LPAREN {
1810 // (e) is parenthesized e
1811 // (e,) is a tuple with only one field, e
1812 let mut trailing_comma = false;
1813 if self.token == token::RPAREN {
1816 let lit = box(GC) spanned(lo, hi, LitNil);
1817 return self.mk_expr(lo, hi, ExprLit(lit));
1819 let mut es = vec!(self.parse_expr());
1820 self.commit_expr(*es.last().unwrap(), &[], &[token::COMMA, token::RPAREN]);
1821 while self.token == token::COMMA {
1823 if self.token != token::RPAREN {
1824 es.push(self.parse_expr());
1825 self.commit_expr(*es.last().unwrap(), &[], &[token::COMMA, token::RPAREN]);
1828 trailing_comma = true;
1832 self.commit_expr_expecting(*es.last().unwrap(), token::RPAREN);
1834 return if es.len() == 1 && !trailing_comma {
1835 self.mk_expr(lo, hi, ExprParen(*es.get(0)))
1838 self.mk_expr(lo, hi, ExprTup(es))
1840 } else if self.token == token::LBRACE {
1842 let blk = self.parse_block_tail(lo, DefaultBlock);
1843 return self.mk_expr(blk.span.lo, blk.span.hi,
1845 } else if token::is_bar(&self.token) {
1846 return self.parse_lambda_expr();
1847 } else if self.eat_keyword(keywords::Proc) {
1848 let decl = self.parse_proc_decl();
1849 let body = self.parse_expr();
1850 let fakeblock = P(ast::Block {
1851 view_items: Vec::new(),
1854 id: ast::DUMMY_NODE_ID,
1855 rules: DefaultBlock,
1859 return self.mk_expr(lo, body.span.hi, ExprProc(decl, fakeblock));
1860 } else if self.eat_keyword(keywords::Self) {
1861 let path = ast_util::ident_to_path(mk_sp(lo, hi), special_idents::self_);
1862 ex = ExprPath(path);
1863 hi = self.last_span.hi;
1864 } else if self.eat_keyword(keywords::If) {
1865 return self.parse_if_expr();
1866 } else if self.eat_keyword(keywords::For) {
1867 return self.parse_for_expr(None);
1868 } else if self.eat_keyword(keywords::While) {
1869 return self.parse_while_expr();
1870 } else if Parser::token_is_lifetime(&self.token) {
1871 let lifetime = self.get_lifetime();
1873 self.expect(&token::COLON);
1874 if self.eat_keyword(keywords::For) {
1875 return self.parse_for_expr(Some(lifetime))
1876 } else if self.eat_keyword(keywords::Loop) {
1877 return self.parse_loop_expr(Some(lifetime))
1879 self.fatal("expected `for` or `loop` after a label")
1881 } else if self.eat_keyword(keywords::Loop) {
1882 return self.parse_loop_expr(None);
1883 } else if self.eat_keyword(keywords::Continue) {
1884 let lo = self.span.lo;
1885 let ex = if Parser::token_is_lifetime(&self.token) {
1886 let lifetime = self.get_lifetime();
1888 ExprAgain(Some(lifetime))
1892 let hi = self.span.hi;
1893 return self.mk_expr(lo, hi, ex);
1894 } else if self.eat_keyword(keywords::Match) {
1895 return self.parse_match_expr();
1896 } else if self.eat_keyword(keywords::Unsafe) {
1897 return self.parse_block_expr(lo, UnsafeBlock(ast::UserProvided));
1898 } else if self.token == token::LBRACKET {
1901 if self.token == token::RBRACKET {
1904 ex = ExprVec(Vec::new());
1907 let first_expr = self.parse_expr();
1908 if self.token == token::COMMA &&
1909 self.look_ahead(1, |t| *t == token::DOTDOT) {
1910 // Repeating vector syntax: [ 0, ..512 ]
1913 let count = self.parse_expr();
1914 self.expect(&token::RBRACKET);
1915 ex = ExprRepeat(first_expr, count);
1916 } else if self.token == token::COMMA {
1917 // Vector with two or more elements.
1919 let remaining_exprs = self.parse_seq_to_end(
1921 seq_sep_trailing_allowed(token::COMMA),
1924 let mut exprs = vec!(first_expr);
1925 exprs.push_all_move(remaining_exprs);
1926 ex = ExprVec(exprs);
1928 // Vector with one element.
1929 self.expect(&token::RBRACKET);
1930 ex = ExprVec(vec!(first_expr));
1933 hi = self.last_span.hi;
1934 } else if self.eat_keyword(keywords::Return) {
1935 // RETURN expression
1936 if can_begin_expr(&self.token) {
1937 let e = self.parse_expr();
1939 ex = ExprRet(Some(e));
1940 } else { ex = ExprRet(None); }
1941 } else if self.eat_keyword(keywords::Break) {
1943 if Parser::token_is_lifetime(&self.token) {
1944 let lifetime = self.get_lifetime();
1946 ex = ExprBreak(Some(lifetime));
1948 ex = ExprBreak(None);
1951 } else if self.token == token::MOD_SEP ||
1952 is_ident(&self.token) && !self.is_keyword(keywords::True) &&
1953 !self.is_keyword(keywords::False) {
1954 let pth = self.parse_path(LifetimeAndTypesWithColons).path;
1956 // `!`, as an operator, is prefix, so we know this isn't that
1957 if self.token == token::NOT {
1958 // MACRO INVOCATION expression
1961 let ket = token::close_delimiter_for(&self.token)
1962 .unwrap_or_else(|| self.fatal("expected open delimiter"));
1965 let tts = self.parse_seq_to_end(&ket,
1967 |p| p.parse_token_tree());
1968 let hi = self.span.hi;
1970 return self.mk_mac_expr(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT));
1971 } else if self.token == token::LBRACE {
1972 // This might be a struct literal.
1973 if self.looking_at_struct_literal() {
1974 // It's a struct literal.
1976 let mut fields = Vec::new();
1977 let mut base = None;
1979 while self.token != token::RBRACE {
1980 if self.eat(&token::DOTDOT) {
1981 base = Some(self.parse_expr());
1985 fields.push(self.parse_field());
1986 self.commit_expr(fields.last().unwrap().expr,
1987 &[token::COMMA], &[token::RBRACE]);
1991 self.expect(&token::RBRACE);
1992 ex = ExprStruct(pth, fields, base);
1993 return self.mk_expr(lo, hi, ex);
2000 // other literal expression
2001 let lit = self.parse_lit();
2003 ex = ExprLit(box(GC) lit);
2006 return self.mk_expr(lo, hi, ex);
2009 // parse a block or unsafe block
2010 pub fn parse_block_expr(&mut self, lo: BytePos, blk_mode: BlockCheckMode)
2012 self.expect(&token::LBRACE);
2013 let blk = self.parse_block_tail(lo, blk_mode);
2014 return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk));
2017 // parse a.b or a(13) or a[4] or just a
2018 pub fn parse_dot_or_call_expr(&mut self) -> Gc<Expr> {
2019 let b = self.parse_bottom_expr();
2020 self.parse_dot_or_call_expr_with(b)
2023 pub fn parse_dot_or_call_expr_with(&mut self, e0: Gc<Expr>) -> Gc<Expr> {
2029 if self.eat(&token::DOT) {
2031 token::IDENT(i, _) => {
2032 let dot = self.last_span.hi;
2035 let (_, tys) = if self.eat(&token::MOD_SEP) {
2037 self.parse_generic_values_after_lt()
2039 (Vec::new(), Vec::new())
2042 // expr.f() method call
2045 let mut es = self.parse_unspanned_seq(
2048 seq_sep_trailing_disallowed(token::COMMA),
2051 hi = self.last_span.hi;
2054 let id = spanned(dot, hi, i);
2055 let nd = self.mk_method_call(id, tys, es);
2056 e = self.mk_expr(lo, hi, nd);
2059 let field = self.mk_field(e, i, tys);
2060 e = self.mk_expr(lo, hi, field)
2064 _ => self.unexpected()
2068 if self.expr_is_complete(e) { break; }
2072 let es = self.parse_unspanned_seq(
2075 seq_sep_trailing_allowed(token::COMMA),
2078 hi = self.last_span.hi;
2080 let nd = self.mk_call(e, es);
2081 e = self.mk_expr(lo, hi, nd);
2085 token::LBRACKET => {
2087 let ix = self.parse_expr();
2089 self.commit_expr_expecting(ix, token::RBRACKET);
2090 let index = self.mk_index(e, ix);
2091 e = self.mk_expr(lo, hi, index)
2100 // parse an optional separator followed by a kleene-style
2101 // repetition token (+ or *).
2102 pub fn parse_sep_and_zerok(&mut self) -> (Option<token::Token>, bool) {
2103 fn parse_zerok(parser: &mut Parser) -> Option<bool> {
2104 match parser.token {
2105 token::BINOP(token::STAR) | token::BINOP(token::PLUS) => {
2106 let zerok = parser.token == token::BINOP(token::STAR);
2114 match parse_zerok(self) {
2115 Some(zerok) => return (None, zerok),
2119 let separator = self.bump_and_get();
2120 match parse_zerok(self) {
2121 Some(zerok) => (Some(separator), zerok),
2122 None => self.fatal("expected `*` or `+`")
2126 // parse a single token tree from the input.
2127 pub fn parse_token_tree(&mut self) -> TokenTree {
2128 // FIXME #6994: currently, this is too eager. It
2129 // parses token trees but also identifies TTSeq's
2130 // and TTNonterminal's; it's too early to know yet
2131 // whether something will be a nonterminal or a seq
2133 maybe_whole!(deref self, NtTT);
2135 // this is the fall-through for the 'match' below.
2136 // invariants: the current token is not a left-delimiter,
2137 // not an EOF, and not the desired right-delimiter (if
2138 // it were, parse_seq_to_before_end would have prevented
2139 // reaching this point.
2140 fn parse_non_delim_tt_tok(p: &mut Parser) -> TokenTree {
2141 maybe_whole!(deref p, NtTT);
2143 token::RPAREN | token::RBRACE | token::RBRACKET => {
2144 // This is a conservative error: only report the last unclosed delimiter. The
2145 // previous unclosed delimiters could actually be closed! The parser just hasn't
2146 // gotten to them yet.
2147 match p.open_braces.last() {
2149 Some(&sp) => p.span_note(sp, "unclosed delimiter"),
2151 let token_str = p.this_token_to_str();
2152 p.fatal(format!("incorrect close delimiter: `{}`",
2153 token_str).as_slice())
2155 /* we ought to allow different depths of unquotation */
2156 token::DOLLAR if p.quote_depth > 0u => {
2160 if p.token == token::LPAREN {
2161 let seq = p.parse_seq(
2165 |p| p.parse_token_tree()
2167 let (s, z) = p.parse_sep_and_zerok();
2168 let seq = match seq {
2169 Spanned { node, .. } => node,
2171 TTSeq(mk_sp(sp.lo, p.span.hi), Rc::new(seq), s, z)
2173 TTNonterminal(sp, p.parse_ident())
2182 // turn the next token into a TTTok:
2183 fn parse_any_tt_tok(p: &mut Parser) -> TokenTree {
2184 TTTok(p.span, p.bump_and_get())
2187 match (&self.token, token::close_delimiter_for(&self.token)) {
2188 (&token::EOF, _) => {
2189 let open_braces = self.open_braces.clone();
2190 for sp in open_braces.iter() {
2191 self.span_note(*sp, "Did you mean to close this delimiter?");
2193 // There shouldn't really be a span, but it's easier for the test runner
2194 // if we give it one
2195 self.fatal("this file contains an un-closed delimiter ");
2197 (_, Some(close_delim)) => {
2198 // Parse the open delimiter.
2199 self.open_braces.push(self.span);
2200 let mut result = vec!(parse_any_tt_tok(self));
2203 self.parse_seq_to_before_end(&close_delim,
2205 |p| p.parse_token_tree());
2206 result.push_all_move(trees);
2208 // Parse the close delimiter.
2209 result.push(parse_any_tt_tok(self));
2210 self.open_braces.pop().unwrap();
2212 TTDelim(Rc::new(result))
2214 _ => parse_non_delim_tt_tok(self)
2218 // parse a stream of tokens into a list of TokenTree's,
2220 pub fn parse_all_token_trees(&mut self) -> Vec<TokenTree> {
2221 let mut tts = Vec::new();
2222 while self.token != token::EOF {
2223 tts.push(self.parse_token_tree());
2228 pub fn parse_matchers(&mut self) -> Vec<Matcher> {
2229 // unification of Matcher's and TokenTree's would vastly improve
2230 // the interpolation of Matcher's
2231 maybe_whole!(self, NtMatchers);
2232 let mut name_idx = 0u;
2233 match token::close_delimiter_for(&self.token) {
2234 Some(other_delimiter) => {
2236 self.parse_matcher_subseq_upto(&mut name_idx, &other_delimiter)
2238 None => self.fatal("expected open delimiter")
2242 // This goofy function is necessary to correctly match parens in Matcher's.
2243 // Otherwise, `$( ( )` would be a valid Matcher, and `$( () )` would be
2244 // invalid. It's similar to common::parse_seq.
2245 pub fn parse_matcher_subseq_upto(&mut self,
2246 name_idx: &mut uint,
2249 let mut ret_val = Vec::new();
2250 let mut lparens = 0u;
2252 while self.token != *ket || lparens > 0u {
2253 if self.token == token::LPAREN { lparens += 1u; }
2254 if self.token == token::RPAREN { lparens -= 1u; }
2255 ret_val.push(self.parse_matcher(name_idx));
2263 pub fn parse_matcher(&mut self, name_idx: &mut uint) -> Matcher {
2264 let lo = self.span.lo;
2266 let m = if self.token == token::DOLLAR {
2268 if self.token == token::LPAREN {
2269 let name_idx_lo = *name_idx;
2271 let ms = self.parse_matcher_subseq_upto(name_idx,
2274 self.fatal("repetition body must be nonempty");
2276 let (sep, zerok) = self.parse_sep_and_zerok();
2277 MatchSeq(ms, sep, zerok, name_idx_lo, *name_idx)
2279 let bound_to = self.parse_ident();
2280 self.expect(&token::COLON);
2281 let nt_name = self.parse_ident();
2282 let m = MatchNonterminal(bound_to, nt_name, *name_idx);
2287 MatchTok(self.bump_and_get())
2290 return spanned(lo, self.span.hi, m);
2293 // parse a prefix-operator expr
2294 pub fn parse_prefix_expr(&mut self) -> Gc<Expr> {
2295 let lo = self.span.lo;
2302 let e = self.parse_prefix_expr();
2304 ex = self.mk_unary(UnNot, e);
2306 token::BINOP(token::MINUS) => {
2308 let e = self.parse_prefix_expr();
2310 ex = self.mk_unary(UnNeg, e);
2312 token::BINOP(token::STAR) => {
2314 let e = self.parse_prefix_expr();
2316 ex = self.mk_unary(UnDeref, e);
2318 token::BINOP(token::AND) | token::ANDAND => {
2320 let _lt = self.parse_opt_lifetime();
2321 let m = self.parse_mutability();
2322 let e = self.parse_prefix_expr();
2324 // HACK: turn &[...] into a &-vec
2326 ExprVec(..) if m == MutImmutable => {
2327 ExprVstore(e, ExprVstoreSlice)
2329 ExprVec(..) if m == MutMutable => {
2330 ExprVstore(e, ExprVstoreMutSlice)
2332 _ => ExprAddrOf(m, e)
2337 let e = self.parse_prefix_expr();
2339 // HACK: pretending @[] is a (removed) @-vec
2340 ex = self.mk_unary(UnBox, e);
2345 let e = self.parse_prefix_expr();
2347 // HACK: turn ~[...] into a ~-vec
2349 ExprVec(..) | ExprRepeat(..) => {
2350 self.obsolete(self.last_span, ObsoleteOwnedVector);
2351 ExprVstore(e, ExprVstoreUniq)
2353 ExprLit(lit) if lit_is_str(lit) => {
2354 self.obsolete(self.last_span, ObsoleteOwnedExpr);
2355 ExprVstore(e, ExprVstoreUniq)
2358 self.obsolete(self.last_span, ObsoleteOwnedExpr);
2359 self.mk_unary(UnUniq, e)
2363 token::IDENT(_, _) if self.is_keyword(keywords::Box) => {
2366 // Check for a place: `box(PLACE) EXPR`.
2367 if self.eat(&token::LPAREN) {
2368 // Support `box() EXPR` as the default.
2369 if !self.eat(&token::RPAREN) {
2370 let place = self.parse_expr();
2371 self.expect(&token::RPAREN);
2372 let subexpression = self.parse_prefix_expr();
2373 hi = subexpression.span.hi;
2374 ex = ExprBox(place, subexpression);
2375 return self.mk_expr(lo, hi, ex);
2379 // Otherwise, we use the unique pointer default.
2380 let subexpression = self.parse_prefix_expr();
2381 hi = subexpression.span.hi;
2382 // HACK: turn `box [...]` into a boxed-vec
2383 ex = match subexpression.node {
2384 ExprVec(..) | ExprRepeat(..) => {
2385 self.obsolete(self.last_span, ObsoleteOwnedVector);
2386 ExprVstore(subexpression, ExprVstoreUniq)
2388 ExprLit(lit) if lit_is_str(lit) => {
2389 ExprVstore(subexpression, ExprVstoreUniq)
2391 _ => self.mk_unary(UnUniq, subexpression)
2394 _ => return self.parse_dot_or_call_expr()
2396 return self.mk_expr(lo, hi, ex);
2399 // parse an expression of binops
2400 pub fn parse_binops(&mut self) -> Gc<Expr> {
2401 let prefix_expr = self.parse_prefix_expr();
2402 self.parse_more_binops(prefix_expr, 0)
2405 // parse an expression of binops of at least min_prec precedence
2406 pub fn parse_more_binops(&mut self, lhs: Gc<Expr>,
2407 min_prec: uint) -> Gc<Expr> {
2408 if self.expr_is_complete(lhs) { return lhs; }
2410 // Prevent dynamic borrow errors later on by limiting the
2411 // scope of the borrows.
2413 let token: &token::Token = &self.token;
2414 let restriction: &restriction = &self.restriction;
2415 match (token, restriction) {
2416 (&token::BINOP(token::OR), &RESTRICT_NO_BAR_OP) => return lhs,
2417 (&token::BINOP(token::OR),
2418 &RESTRICT_NO_BAR_OR_DOUBLEBAR_OP) => return lhs,
2419 (&token::OROR, &RESTRICT_NO_BAR_OR_DOUBLEBAR_OP) => return lhs,
2424 let cur_opt = token_to_binop(&self.token);
2427 let cur_prec = operator_prec(cur_op);
2428 if cur_prec > min_prec {
2430 let expr = self.parse_prefix_expr();
2431 let rhs = self.parse_more_binops(expr, cur_prec);
2432 let binary = self.mk_binary(cur_op, lhs, rhs);
2433 let bin = self.mk_expr(lhs.span.lo, rhs.span.hi, binary);
2434 self.parse_more_binops(bin, min_prec)
2440 if as_prec > min_prec && self.eat_keyword(keywords::As) {
2441 let rhs = self.parse_ty(true);
2442 let _as = self.mk_expr(lhs.span.lo,
2444 ExprCast(lhs, rhs));
2445 self.parse_more_binops(_as, min_prec)
2453 // parse an assignment expression....
2454 // actually, this seems to be the main entry point for
2455 // parsing an arbitrary expression.
2456 pub fn parse_assign_expr(&mut self) -> Gc<Expr> {
2457 let lo = self.span.lo;
2458 let lhs = self.parse_binops();
2462 let rhs = self.parse_expr();
2463 self.mk_expr(lo, rhs.span.hi, ExprAssign(lhs, rhs))
2465 token::BINOPEQ(op) => {
2467 let rhs = self.parse_expr();
2468 let aop = match op {
2469 token::PLUS => BiAdd,
2470 token::MINUS => BiSub,
2471 token::STAR => BiMul,
2472 token::SLASH => BiDiv,
2473 token::PERCENT => BiRem,
2474 token::CARET => BiBitXor,
2475 token::AND => BiBitAnd,
2476 token::OR => BiBitOr,
2477 token::SHL => BiShl,
2480 let assign_op = self.mk_assign_op(aop, lhs, rhs);
2481 self.mk_expr(lo, rhs.span.hi, assign_op)
2489 // parse an 'if' expression ('if' token already eaten)
2490 pub fn parse_if_expr(&mut self) -> Gc<Expr> {
2491 let lo = self.last_span.lo;
2492 let cond = self.parse_expr();
2493 let thn = self.parse_block();
2494 let mut els: Option<Gc<Expr>> = None;
2495 let mut hi = thn.span.hi;
2496 if self.eat_keyword(keywords::Else) {
2497 let elexpr = self.parse_else_expr();
2499 hi = elexpr.span.hi;
2501 self.mk_expr(lo, hi, ExprIf(cond, thn, els))
2504 // `|args| { ... }` or `{ ...}` like in `do` expressions
2505 pub fn parse_lambda_block_expr(&mut self) -> Gc<Expr> {
2506 self.parse_lambda_expr_(
2509 token::BINOP(token::OR) | token::OROR => {
2510 p.parse_fn_block_decl()
2513 // No argument list - `do foo {`
2517 id: ast::DUMMY_NODE_ID,
2528 let blk = p.parse_block();
2529 p.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk))
2534 pub fn parse_lambda_expr(&mut self) -> Gc<Expr> {
2535 self.parse_lambda_expr_(|p| p.parse_fn_block_decl(),
2539 // parse something of the form |args| expr
2540 // this is used both in parsing a lambda expr
2541 // and in parsing a block expr as e.g. in for...
2542 pub fn parse_lambda_expr_(&mut self,
2543 parse_decl: |&mut Parser| -> P<FnDecl>,
2544 parse_body: |&mut Parser| -> Gc<Expr>)
2546 let lo = self.span.lo;
2547 let decl = parse_decl(self);
2548 let body = parse_body(self);
2549 let fakeblock = P(ast::Block {
2550 view_items: Vec::new(),
2553 id: ast::DUMMY_NODE_ID,
2554 rules: DefaultBlock,
2558 return self.mk_expr(lo, body.span.hi, ExprFnBlock(decl, fakeblock));
2561 pub fn parse_else_expr(&mut self) -> Gc<Expr> {
2562 if self.eat_keyword(keywords::If) {
2563 return self.parse_if_expr();
2565 let blk = self.parse_block();
2566 return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk));
2570 // parse a 'for' .. 'in' expression ('for' token already eaten)
2571 pub fn parse_for_expr(&mut self, opt_ident: Option<ast::Ident>) -> Gc<Expr> {
2572 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
2574 let lo = self.last_span.lo;
2575 let pat = self.parse_pat();
2576 self.expect_keyword(keywords::In);
2577 let expr = self.parse_expr();
2578 let loop_block = self.parse_block();
2579 let hi = self.span.hi;
2581 self.mk_expr(lo, hi, ExprForLoop(pat, expr, loop_block, opt_ident))
2584 pub fn parse_while_expr(&mut self) -> Gc<Expr> {
2585 let lo = self.last_span.lo;
2586 let cond = self.parse_expr();
2587 let body = self.parse_block();
2588 let hi = body.span.hi;
2589 return self.mk_expr(lo, hi, ExprWhile(cond, body));
2592 pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::Ident>) -> Gc<Expr> {
2593 let lo = self.last_span.lo;
2594 let body = self.parse_block();
2595 let hi = body.span.hi;
2596 self.mk_expr(lo, hi, ExprLoop(body, opt_ident))
2599 // For distinguishing between struct literals and blocks
2600 fn looking_at_struct_literal(&mut self) -> bool {
2601 self.token == token::LBRACE &&
2602 ((self.look_ahead(1, |t| token::is_plain_ident(t)) &&
2603 self.look_ahead(2, |t| *t == token::COLON))
2604 || self.look_ahead(1, |t| *t == token::DOTDOT))
2607 fn parse_match_expr(&mut self) -> Gc<Expr> {
2608 let lo = self.last_span.lo;
2609 let discriminant = self.parse_expr();
2610 self.commit_expr_expecting(discriminant, token::LBRACE);
2611 let mut arms: Vec<Arm> = Vec::new();
2612 while self.token != token::RBRACE {
2613 let attrs = self.parse_outer_attributes();
2614 let pats = self.parse_pats();
2615 let mut guard = None;
2616 if self.eat_keyword(keywords::If) {
2617 guard = Some(self.parse_expr());
2619 self.expect(&token::FAT_ARROW);
2620 let expr = self.parse_expr_res(RESTRICT_STMT_EXPR);
2623 !classify::expr_is_simple_block(expr)
2624 && self.token != token::RBRACE;
2627 self.commit_expr(expr, &[token::COMMA], &[token::RBRACE]);
2629 self.eat(&token::COMMA);
2632 arms.push(ast::Arm {
2639 let hi = self.span.hi;
2641 return self.mk_expr(lo, hi, ExprMatch(discriminant, arms));
2644 // parse an expression
2645 pub fn parse_expr(&mut self) -> Gc<Expr> {
2646 return self.parse_expr_res(UNRESTRICTED);
2649 // parse an expression, subject to the given restriction
2650 fn parse_expr_res(&mut self, r: restriction) -> Gc<Expr> {
2651 let old = self.restriction;
2652 self.restriction = r;
2653 let e = self.parse_assign_expr();
2654 self.restriction = old;
2658 // parse the RHS of a local variable declaration (e.g. '= 14;')
2659 fn parse_initializer(&mut self) -> Option<Gc<Expr>> {
2660 if self.token == token::EQ {
2662 Some(self.parse_expr())
2668 // parse patterns, separated by '|' s
2669 fn parse_pats(&mut self) -> Vec<Gc<Pat>> {
2670 let mut pats = Vec::new();
2672 pats.push(self.parse_pat());
2673 if self.token == token::BINOP(token::OR) { self.bump(); }
2674 else { return pats; }
2678 fn parse_pat_vec_elements(
2680 ) -> (Vec<Gc<Pat>> , Option<Gc<Pat>>, Vec<Gc<Pat>> ) {
2681 let mut before = Vec::new();
2682 let mut slice = None;
2683 let mut after = Vec::new();
2684 let mut first = true;
2685 let mut before_slice = true;
2687 while self.token != token::RBRACKET {
2688 if first { first = false; }
2689 else { self.expect(&token::COMMA); }
2691 let mut is_slice = false;
2693 if self.token == token::DOTDOT {
2696 before_slice = false;
2701 if self.token == token::COMMA || self.token == token::RBRACKET {
2702 slice = Some(box(GC) ast::Pat {
2703 id: ast::DUMMY_NODE_ID,
2708 let subpat = self.parse_pat();
2710 ast::Pat { node: PatIdent(_, _, _), .. } => {
2711 slice = Some(subpat);
2713 ast::Pat { span, .. } => self.span_fatal(
2714 span, "expected an identifier or nothing"
2719 let subpat = self.parse_pat();
2721 before.push(subpat);
2728 (before, slice, after)
2731 // parse the fields of a struct-like pattern
2732 fn parse_pat_fields(&mut self) -> (Vec<ast::FieldPat> , bool) {
2733 let mut fields = Vec::new();
2734 let mut etc = false;
2735 let mut first = true;
2736 while self.token != token::RBRACE {
2740 self.expect(&token::COMMA);
2741 // accept trailing commas
2742 if self.token == token::RBRACE { break }
2745 if self.token == token::DOTDOT {
2747 if self.token != token::RBRACE {
2748 let token_str = self.this_token_to_str();
2749 self.fatal(format!("expected `{}`, found `{}`", "}",
2750 token_str).as_slice())
2756 let bind_type = if self.eat_keyword(keywords::Mut) {
2757 BindByValue(MutMutable)
2758 } else if self.eat_keyword(keywords::Ref) {
2759 BindByRef(self.parse_mutability())
2761 BindByValue(MutImmutable)
2764 let fieldname = self.parse_ident();
2766 let subpat = if self.token == token::COLON {
2768 BindByRef(..) | BindByValue(MutMutable) => {
2769 let token_str = self.this_token_to_str();
2770 self.fatal(format!("unexpected `{}`",
2771 token_str).as_slice())
2779 let fieldpath = ast_util::ident_to_path(self.last_span,
2782 id: ast::DUMMY_NODE_ID,
2783 node: PatIdent(bind_type, fieldpath, None),
2784 span: self.last_span
2787 fields.push(ast::FieldPat { ident: fieldname, pat: subpat });
2789 return (fields, etc);
2793 pub fn parse_pat(&mut self) -> Gc<Pat> {
2794 maybe_whole!(self, NtPat);
2796 let lo = self.span.lo;
2801 token::UNDERSCORE => {
2804 hi = self.last_span.hi;
2805 return box(GC) ast::Pat {
2806 id: ast::DUMMY_NODE_ID,
2814 let sub = self.parse_pat();
2816 hi = self.last_span.hi;
2817 self.obsolete(self.last_span, ObsoleteOwnedPattern);
2818 return box(GC) ast::Pat {
2819 id: ast::DUMMY_NODE_ID,
2824 token::BINOP(token::AND) | token::ANDAND => {
2826 let lo = self.span.lo;
2828 let sub = self.parse_pat();
2829 pat = PatRegion(sub);
2830 hi = self.last_span.hi;
2831 return box(GC) ast::Pat {
2832 id: ast::DUMMY_NODE_ID,
2838 // parse (pat,pat,pat,...) as tuple
2840 if self.token == token::RPAREN {
2843 let lit = box(GC) codemap::Spanned {
2845 span: mk_sp(lo, hi)};
2846 let expr = self.mk_expr(lo, hi, ExprLit(lit));
2849 let mut fields = vec!(self.parse_pat());
2850 if self.look_ahead(1, |t| *t != token::RPAREN) {
2851 while self.token == token::COMMA {
2853 if self.token == token::RPAREN { break; }
2854 fields.push(self.parse_pat());
2857 if fields.len() == 1 { self.expect(&token::COMMA); }
2858 self.expect(&token::RPAREN);
2859 pat = PatTup(fields);
2861 hi = self.last_span.hi;
2862 return box(GC) ast::Pat {
2863 id: ast::DUMMY_NODE_ID,
2868 token::LBRACKET => {
2869 // parse [pat,pat,...] as vector pattern
2871 let (before, slice, after) =
2872 self.parse_pat_vec_elements();
2874 self.expect(&token::RBRACKET);
2875 pat = ast::PatVec(before, slice, after);
2876 hi = self.last_span.hi;
2877 return box(GC) ast::Pat {
2878 id: ast::DUMMY_NODE_ID,
2886 if (!is_ident_or_path(&self.token) && self.token != token::MOD_SEP)
2887 || self.is_keyword(keywords::True)
2888 || self.is_keyword(keywords::False) {
2889 // Parse an expression pattern or exp .. exp.
2891 // These expressions are limited to literals (possibly
2892 // preceded by unary-minus) or identifiers.
2893 let val = self.parse_literal_maybe_minus();
2894 if self.eat(&token::DOTDOT) {
2895 let end = if is_ident_or_path(&self.token) {
2896 let path = self.parse_path(LifetimeAndTypesWithColons)
2898 let hi = self.span.hi;
2899 self.mk_expr(lo, hi, ExprPath(path))
2901 self.parse_literal_maybe_minus()
2903 pat = PatRange(val, end);
2907 } else if self.eat_keyword(keywords::Mut) {
2908 pat = self.parse_pat_ident(BindByValue(MutMutable));
2909 } else if self.eat_keyword(keywords::Ref) {
2911 let mutbl = self.parse_mutability();
2912 pat = self.parse_pat_ident(BindByRef(mutbl));
2913 } else if self.eat_keyword(keywords::Box) {
2916 // FIXME(#13910): Rename to `PatBox` and extend to full DST
2918 let sub = self.parse_pat();
2920 hi = self.last_span.hi;
2921 return box(GC) ast::Pat {
2922 id: ast::DUMMY_NODE_ID,
2927 let can_be_enum_or_struct = self.look_ahead(1, |t| {
2929 token::LPAREN | token::LBRACKET | token::LT |
2930 token::LBRACE | token::MOD_SEP => true,
2935 if self.look_ahead(1, |t| *t == token::DOTDOT) {
2936 let start = self.parse_expr_res(RESTRICT_NO_BAR_OP);
2937 self.eat(&token::DOTDOT);
2938 let end = self.parse_expr_res(RESTRICT_NO_BAR_OP);
2939 pat = PatRange(start, end);
2940 } else if is_plain_ident(&self.token) && !can_be_enum_or_struct {
2941 let name = self.parse_path(NoTypesAllowed).path;
2942 if self.eat(&token::NOT) {
2944 let ket = token::close_delimiter_for(&self.token)
2945 .unwrap_or_else(|| self.fatal("expected open delimiter"));
2948 let tts = self.parse_seq_to_end(&ket,
2950 |p| p.parse_token_tree());
2952 let mac = MacInvocTT(name, tts, EMPTY_CTXT);
2953 pat = ast::PatMac(codemap::Spanned {node: mac, span: self.span});
2955 let sub = if self.eat(&token::AT) {
2957 Some(self.parse_pat())
2962 pat = PatIdent(BindByValue(MutImmutable), name, sub);
2965 // parse an enum pat
2966 let enum_path = self.parse_path(LifetimeAndTypesWithColons)
2972 self.parse_pat_fields();
2974 pat = PatStruct(enum_path, fields, etc);
2977 let mut args: Vec<Gc<Pat>> = Vec::new();
2980 let is_dotdot = self.look_ahead(1, |t| {
2982 token::DOTDOT => true,
2987 // This is a "top constructor only" pat
2990 self.expect(&token::RPAREN);
2991 pat = PatEnum(enum_path, None);
2993 args = self.parse_enum_variant_seq(
2996 seq_sep_trailing_disallowed(token::COMMA),
2999 pat = PatEnum(enum_path, Some(args));
3003 if enum_path.segments.len() == 1 {
3004 // it could still be either an enum
3005 // or an identifier pattern, resolve
3006 // will sort it out:
3007 pat = PatIdent(BindByValue(MutImmutable),
3011 pat = PatEnum(enum_path, Some(args));
3019 hi = self.last_span.hi;
3021 id: ast::DUMMY_NODE_ID,
3023 span: mk_sp(lo, hi),
3027 // parse ident or ident @ pat
3028 // used by the copy foo and ref foo patterns to give a good
3029 // error message when parsing mistakes like ref foo(a,b)
3030 fn parse_pat_ident(&mut self,
3031 binding_mode: ast::BindingMode)
3033 if !is_plain_ident(&self.token) {
3034 self.span_fatal(self.last_span,
3035 "expected identifier, found path");
3037 // why a path here, and not just an identifier?
3038 let name = self.parse_path(NoTypesAllowed).path;
3039 let sub = if self.eat(&token::AT) {
3040 Some(self.parse_pat())
3045 // just to be friendly, if they write something like
3047 // we end up here with ( as the current token. This shortly
3048 // leads to a parse error. Note that if there is no explicit
3049 // binding mode then we do not end up here, because the lookahead
3050 // will direct us over to parse_enum_variant()
3051 if self.token == token::LPAREN {
3054 "expected identifier, found enum pattern");
3057 PatIdent(binding_mode, name, sub)
3060 // parse a local variable declaration
3061 fn parse_local(&mut self) -> Gc<Local> {
3062 let lo = self.span.lo;
3063 let pat = self.parse_pat();
3066 id: ast::DUMMY_NODE_ID,
3068 span: mk_sp(lo, lo),
3070 if self.eat(&token::COLON) { ty = self.parse_ty(false); }
3071 let init = self.parse_initializer();
3072 box(GC) ast::Local {
3076 id: ast::DUMMY_NODE_ID,
3077 span: mk_sp(lo, self.last_span.hi),
3082 // parse a "let" stmt
3083 fn parse_let(&mut self) -> Gc<Decl> {
3084 let lo = self.span.lo;
3085 let local = self.parse_local();
3086 box(GC) spanned(lo, self.last_span.hi, DeclLocal(local))
3089 // parse a structure field
3090 fn parse_name_and_ty(&mut self, pr: Visibility,
3091 attrs: Vec<Attribute> ) -> StructField {
3092 let lo = self.span.lo;
3093 if !is_plain_ident(&self.token) {
3094 self.fatal("expected ident");
3096 let name = self.parse_ident();
3097 self.expect(&token::COLON);
3098 let ty = self.parse_ty(false);
3099 spanned(lo, self.last_span.hi, ast::StructField_ {
3100 kind: NamedField(name, pr),
3101 id: ast::DUMMY_NODE_ID,
3107 // parse a statement. may include decl.
3108 // precondition: any attributes are parsed already
3109 pub fn parse_stmt(&mut self, item_attrs: Vec<Attribute>) -> Gc<Stmt> {
3110 maybe_whole!(self, NtStmt);
3112 fn check_expected_item(p: &mut Parser, found_attrs: bool) {
3113 // If we have attributes then we should have an item
3115 p.span_err(p.last_span, "expected item after attributes");
3119 let lo = self.span.lo;
3120 if self.is_keyword(keywords::Let) {
3121 check_expected_item(self, !item_attrs.is_empty());
3122 self.expect_keyword(keywords::Let);
3123 let decl = self.parse_let();
3124 return box(GC) spanned(lo, decl.span.hi, StmtDecl(decl, ast::DUMMY_NODE_ID));
3125 } else if is_ident(&self.token)
3126 && !token::is_any_keyword(&self.token)
3127 && self.look_ahead(1, |t| *t == token::NOT) {
3128 // parse a macro invocation. Looks like there's serious
3129 // overlap here; if this clause doesn't catch it (and it
3130 // won't, for brace-delimited macros) it will fall through
3131 // to the macro clause of parse_item_or_view_item. This
3132 // could use some cleanup, it appears to me.
3134 // whoops! I now have a guess: I'm guessing the "parens-only"
3135 // rule here is deliberate, to allow macro users to use parens
3136 // for things that should be parsed as stmt_mac, and braces
3137 // for things that should expand into items. Tricky, and
3138 // somewhat awkward... and probably undocumented. Of course,
3139 // I could just be wrong.
3141 check_expected_item(self, !item_attrs.is_empty());
3143 // Potential trouble: if we allow macros with paths instead of
3144 // idents, we'd need to look ahead past the whole path here...
3145 let pth = self.parse_path(NoTypesAllowed).path;
3148 let id = if token::close_delimiter_for(&self.token).is_some() {
3149 token::special_idents::invalid // no special identifier
3154 // check that we're pointing at delimiters (need to check
3155 // again after the `if`, because of `parse_ident`
3156 // consuming more tokens).
3157 let (bra, ket) = match token::close_delimiter_for(&self.token) {
3158 Some(ket) => (self.token.clone(), ket),
3161 // we only expect an ident if we didn't parse one
3163 let ident_str = if id == token::special_idents::invalid {
3168 let tok_str = self.this_token_to_str();
3169 self.fatal(format!("expected {}`(` or `\\{`, but found `{}`",
3171 tok_str).as_slice())
3175 // we only expect an ident if we didn't parse one
3177 let ident_str = if id == token::special_idents::invalid {
3182 let tok_str = self.this_token_to_str();
3183 self.fatal(format!("expected {}`(` or `{{`, but found `{}`",
3185 tok_str).as_slice())
3189 let tts = self.parse_unspanned_seq(
3193 |p| p.parse_token_tree()
3195 let hi = self.span.hi;
3197 if id == token::special_idents::invalid {
3198 return box(GC) spanned(lo, hi, StmtMac(
3199 spanned(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT)), false));
3201 // if it has a special ident, it's definitely an item
3202 return box(GC) spanned(lo, hi, StmtDecl(
3203 box(GC) spanned(lo, hi, DeclItem(
3205 lo, hi, id /*id is good here*/,
3206 ItemMac(spanned(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT))),
3207 Inherited, Vec::new(/*no attrs*/)))),
3208 ast::DUMMY_NODE_ID));
3212 let found_attrs = !item_attrs.is_empty();
3213 match self.parse_item_or_view_item(item_attrs, false) {
3216 let decl = box(GC) spanned(lo, hi, DeclItem(i));
3217 return box(GC) spanned(lo, hi, StmtDecl(decl, ast::DUMMY_NODE_ID));
3219 IoviViewItem(vi) => {
3220 self.span_fatal(vi.span,
3221 "view items must be declared at the top of the block");
3223 IoviForeignItem(_) => {
3224 self.fatal("foreign items are not allowed here");
3226 IoviNone(_) => { /* fallthrough */ }
3229 check_expected_item(self, found_attrs);
3231 // Remainder are line-expr stmts.
3232 let e = self.parse_expr_res(RESTRICT_STMT_EXPR);
3233 return box(GC) spanned(lo, e.span.hi, StmtExpr(e, ast::DUMMY_NODE_ID));
3237 // is this expression a successfully-parsed statement?
3238 fn expr_is_complete(&mut self, e: Gc<Expr>) -> bool {
3239 return self.restriction == RESTRICT_STMT_EXPR &&
3240 !classify::expr_requires_semi_to_be_stmt(e);
3243 // parse a block. No inner attrs are allowed.
3244 pub fn parse_block(&mut self) -> P<Block> {
3245 maybe_whole!(no_clone self, NtBlock);
3247 let lo = self.span.lo;
3248 self.expect(&token::LBRACE);
3250 return self.parse_block_tail_(lo, DefaultBlock, Vec::new());
3253 // parse a block. Inner attrs are allowed.
3254 fn parse_inner_attrs_and_block(&mut self)
3255 -> (Vec<Attribute> , P<Block>) {
3257 maybe_whole!(pair_empty self, NtBlock);
3259 let lo = self.span.lo;
3260 self.expect(&token::LBRACE);
3261 let (inner, next) = self.parse_inner_attrs_and_next();
3263 (inner, self.parse_block_tail_(lo, DefaultBlock, next))
3266 // Precondition: already parsed the '{' or '#{'
3267 // I guess that also means "already parsed the 'impure'" if
3268 // necessary, and this should take a qualifier.
3269 // some blocks start with "#{"...
3270 fn parse_block_tail(&mut self, lo: BytePos, s: BlockCheckMode) -> P<Block> {
3271 self.parse_block_tail_(lo, s, Vec::new())
3274 // parse the rest of a block expression or function body
3275 fn parse_block_tail_(&mut self, lo: BytePos, s: BlockCheckMode,
3276 first_item_attrs: Vec<Attribute> ) -> P<Block> {
3277 let mut stmts = Vec::new();
3278 let mut expr = None;
3280 // wouldn't it be more uniform to parse view items only, here?
3281 let ParsedItemsAndViewItems {
3282 attrs_remaining: attrs_remaining,
3283 view_items: view_items,
3286 } = self.parse_items_and_view_items(first_item_attrs,
3289 for item in items.iter() {
3290 let decl = box(GC) spanned(item.span.lo, item.span.hi, DeclItem(*item));
3291 stmts.push(box(GC) spanned(item.span.lo, item.span.hi,
3292 StmtDecl(decl, ast::DUMMY_NODE_ID)));
3295 let mut attributes_box = attrs_remaining;
3297 while self.token != token::RBRACE {
3298 // parsing items even when they're not allowed lets us give
3299 // better error messages and recover more gracefully.
3300 attributes_box.push_all(self.parse_outer_attributes().as_slice());
3303 if !attributes_box.is_empty() {
3304 self.span_err(self.last_span, "expected item after attributes");
3305 attributes_box = Vec::new();
3307 self.bump(); // empty
3310 // fall through and out.
3313 let stmt = self.parse_stmt(attributes_box);
3314 attributes_box = Vec::new();
3316 StmtExpr(e, stmt_id) => {
3317 // expression without semicolon
3318 if classify::stmt_ends_with_semi(&*stmt) {
3319 // Just check for errors and recover; do not eat semicolon yet.
3320 self.commit_stmt(stmt, &[], &[token::SEMI, token::RBRACE]);
3326 let span_with_semi = Span {
3328 hi: self.last_span.hi,
3329 expn_info: stmt.span.expn_info,
3331 stmts.push(box(GC) codemap::Spanned {
3332 node: StmtSemi(e, stmt_id),
3333 span: span_with_semi,
3344 StmtMac(ref m, _) => {
3345 // statement macro; might be an expr
3349 stmts.push(box(GC) codemap::Spanned {
3350 node: StmtMac((*m).clone(), true),
3355 // if a block ends in `m!(arg)` without
3356 // a `;`, it must be an expr
3358 self.mk_mac_expr(stmt.span.lo,
3367 _ => { // all other kinds of statements:
3368 stmts.push(stmt.clone());
3370 if classify::stmt_ends_with_semi(&*stmt) {
3371 self.commit_stmt_expecting(stmt, token::SEMI);
3379 if !attributes_box.is_empty() {
3380 self.span_err(self.last_span, "expected item after attributes");
3383 let hi = self.span.hi;
3386 view_items: view_items,
3389 id: ast::DUMMY_NODE_ID,
3391 span: mk_sp(lo, hi),
3395 fn parse_unboxed_function_type(&mut self) -> UnboxedFnTy {
3396 let inputs = if self.eat(&token::OROR) {
3401 if self.token == token::BINOP(token::AND) &&
3402 self.look_ahead(1, |t| {
3403 token::is_keyword(keywords::Mut, t)
3405 self.look_ahead(2, |t| *t == token::COLON) {
3411 let inputs = self.parse_seq_to_before_or(&token::COMMA,
3413 p.parse_arg_general(false)
3419 let (return_style, output) = self.parse_ret_ty();
3430 // matches optbounds = ( ( : ( boundseq )? )? )
3431 // where boundseq = ( bound + boundseq ) | bound
3432 // and bound = 'static | ty
3433 // Returns "None" if there's no colon (e.g. "T");
3434 // Returns "Some(Empty)" if there's a colon but nothing after (e.g. "T:")
3435 // Returns "Some(stuff)" otherwise (e.g. "T:stuff").
3436 // NB: The None/Some distinction is important for issue #7264.
3438 // Note that the `allow_any_lifetime` argument is a hack for now while the
3439 // AST doesn't support arbitrary lifetimes in bounds on type parameters. In
3440 // the future, this flag should be removed, and the return value of this
3441 // function should be Option<~[TyParamBound]>
3442 fn parse_optional_ty_param_bounds(&mut self, allow_any_lifetime: bool)
3443 -> (Option<ast::Lifetime>, Option<OwnedSlice<TyParamBound>>)
3445 if !self.eat(&token::COLON) {
3446 return (None, None);
3449 let mut ret_lifetime = None;
3450 let mut result = vec!();
3453 token::LIFETIME(lifetime) => {
3454 let lifetime_interned_string = token::get_ident(lifetime);
3455 if lifetime_interned_string.equiv(&("'static")) {
3456 result.push(StaticRegionTyParamBound);
3457 if allow_any_lifetime && ret_lifetime.is_none() {
3458 ret_lifetime = Some(ast::Lifetime {
3459 id: ast::DUMMY_NODE_ID,
3464 } else if allow_any_lifetime && ret_lifetime.is_none() {
3465 ret_lifetime = Some(ast::Lifetime {
3466 id: ast::DUMMY_NODE_ID,
3471 result.push(OtherRegionTyParamBound(self.span));
3475 token::MOD_SEP | token::IDENT(..) => {
3476 let tref = self.parse_trait_ref();
3477 result.push(TraitTyParamBound(tref));
3479 token::BINOP(token::OR) | token::OROR => {
3480 let unboxed_function_type =
3481 self.parse_unboxed_function_type();
3482 result.push(UnboxedFnTyParamBound(unboxed_function_type));
3487 if !self.eat(&token::BINOP(token::PLUS)) {
3492 return (ret_lifetime, Some(OwnedSlice::from_vec(result)));
3495 // matches typaram = type? IDENT optbounds ( EQ ty )?
3496 fn parse_ty_param(&mut self) -> TyParam {
3497 let sized = self.parse_sized();
3498 let span = self.span;
3499 let ident = self.parse_ident();
3500 let (_, opt_bounds) = self.parse_optional_ty_param_bounds(false);
3501 // For typarams we don't care about the difference b/w "<T>" and "<T:>".
3502 let bounds = opt_bounds.unwrap_or_default();
3504 let default = if self.token == token::EQ {
3506 Some(self.parse_ty(false))
3512 id: ast::DUMMY_NODE_ID,
3520 // parse a set of optional generic type parameter declarations
3521 // matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
3522 // | ( < lifetimes , typaramseq ( , )? > )
3523 // where typaramseq = ( typaram ) | ( typaram , typaramseq )
3524 pub fn parse_generics(&mut self) -> ast::Generics {
3525 if self.eat(&token::LT) {
3526 let lifetimes = self.parse_lifetimes();
3527 let mut seen_default = false;
3528 let ty_params = self.parse_seq_to_gt(Some(token::COMMA), |p| {
3529 p.forbid_lifetime();
3530 let ty_param = p.parse_ty_param();
3531 if ty_param.default.is_some() {
3532 seen_default = true;
3533 } else if seen_default {
3534 p.span_err(p.last_span,
3535 "type parameters with a default must be trailing");
3539 ast::Generics { lifetimes: lifetimes, ty_params: ty_params }
3541 ast_util::empty_generics()
3545 fn parse_generic_values_after_lt(&mut self) -> (Vec<ast::Lifetime>, Vec<P<Ty>> ) {
3546 let lifetimes = self.parse_lifetimes();
3547 let result = self.parse_seq_to_gt(
3550 p.forbid_lifetime();
3554 (lifetimes, result.into_vec())
3557 fn forbid_lifetime(&mut self) {
3558 if Parser::token_is_lifetime(&self.token) {
3559 self.span_fatal(self.span, "lifetime parameters must be declared \
3560 prior to type parameters");
3564 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
3565 -> (Vec<Arg> , bool) {
3567 let mut args: Vec<Option<Arg>> =
3568 self.parse_unspanned_seq(
3571 seq_sep_trailing_allowed(token::COMMA),
3573 if p.token == token::DOTDOTDOT {
3576 if p.token != token::RPAREN {
3577 p.span_fatal(p.span,
3578 "`...` must be last in argument list for variadic function");
3581 p.span_fatal(p.span,
3582 "only foreign functions are allowed to be variadic");
3586 Some(p.parse_arg_general(named_args))
3591 let variadic = match args.pop() {
3594 // Need to put back that last arg
3601 if variadic && args.is_empty() {
3603 "variadic function must be declared with at least one named argument");
3606 let args = args.move_iter().map(|x| x.unwrap()).collect();
3611 // parse the argument list and result type of a function declaration
3612 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> P<FnDecl> {
3614 let (args, variadic) = self.parse_fn_args(true, allow_variadic);
3615 let (ret_style, ret_ty) = self.parse_ret_ty();
3625 fn is_self_ident(&mut self) -> bool {
3627 token::IDENT(id, false) => id.name == special_idents::self_.name,
3632 fn expect_self_ident(&mut self) {
3633 if !self.is_self_ident() {
3634 let token_str = self.this_token_to_str();
3635 self.fatal(format!("expected `self` but found `{}`",
3636 token_str).as_slice())
3641 // parse the argument list and result type of a function
3642 // that may have a self type.
3643 fn parse_fn_decl_with_self(&mut self, parse_arg_fn: |&mut Parser| -> Arg)
3644 -> (ExplicitSelf, P<FnDecl>) {
3645 fn maybe_parse_borrowed_explicit_self(this: &mut Parser)
3646 -> ast::ExplicitSelf_ {
3647 // The following things are possible to see here:
3652 // fn(&'lt mut self)
3654 // We already know that the current token is `&`.
3656 if this.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) {
3658 this.expect_self_ident();
3659 SelfRegion(None, MutImmutable)
3660 } else if this.look_ahead(1, |t| Parser::token_is_mutability(t)) &&
3662 |t| token::is_keyword(keywords::Self,
3665 let mutability = this.parse_mutability();
3666 this.expect_self_ident();
3667 SelfRegion(None, mutability)
3668 } else if this.look_ahead(1, |t| Parser::token_is_lifetime(t)) &&
3670 |t| token::is_keyword(keywords::Self,
3673 let lifetime = this.parse_lifetime();
3674 this.expect_self_ident();
3675 SelfRegion(Some(lifetime), MutImmutable)
3676 } else if this.look_ahead(1, |t| Parser::token_is_lifetime(t)) &&
3677 this.look_ahead(2, |t| {
3678 Parser::token_is_mutability(t)
3680 this.look_ahead(3, |t| token::is_keyword(keywords::Self,
3683 let lifetime = this.parse_lifetime();
3684 let mutability = this.parse_mutability();
3685 this.expect_self_ident();
3686 SelfRegion(Some(lifetime), mutability)
3692 self.expect(&token::LPAREN);
3694 // A bit of complexity and lookahead is needed here in order to be
3695 // backwards compatible.
3696 let lo = self.span.lo;
3697 let mut mutbl_self = MutImmutable;
3698 let explicit_self = match self.token {
3699 token::BINOP(token::AND) => {
3700 maybe_parse_borrowed_explicit_self(self)
3703 // We need to make sure it isn't a type
3704 if self.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) {
3706 self.expect_self_ident();
3712 token::IDENT(..) if self.is_self_ident() => {
3716 token::BINOP(token::STAR) => {
3717 // Possibly "*self" or "*mut self" -- not supported. Try to avoid
3718 // emitting cryptic "unexpected token" errors.
3720 let _mutability = if Parser::token_is_mutability(&self.token) {
3721 self.parse_mutability()
3722 } else { MutImmutable };
3723 if self.is_self_ident() {
3724 self.span_err(self.span, "cannot pass self by unsafe pointer");
3729 _ if Parser::token_is_mutability(&self.token) &&
3730 self.look_ahead(1, |t| token::is_keyword(keywords::Self, t)) => {
3731 mutbl_self = self.parse_mutability();
3732 self.expect_self_ident();
3735 _ if Parser::token_is_mutability(&self.token) &&
3736 self.look_ahead(1, |t| *t == token::TILDE) &&
3737 self.look_ahead(2, |t| token::is_keyword(keywords::Self, t)) => {
3738 mutbl_self = self.parse_mutability();
3740 self.expect_self_ident();
3746 let explicit_self_sp = mk_sp(lo, self.span.hi);
3748 // If we parsed a self type, expect a comma before the argument list.
3749 let fn_inputs = if explicit_self != SelfStatic {
3753 let sep = seq_sep_trailing_disallowed(token::COMMA);
3754 let mut fn_inputs = self.parse_seq_to_before_end(
3759 fn_inputs.unshift(Arg::new_self(explicit_self_sp, mutbl_self));
3763 vec!(Arg::new_self(explicit_self_sp, mutbl_self))
3766 let token_str = self.this_token_to_str();
3767 self.fatal(format!("expected `,` or `)`, found `{}`",
3768 token_str).as_slice())
3772 let sep = seq_sep_trailing_disallowed(token::COMMA);
3773 self.parse_seq_to_before_end(&token::RPAREN, sep, parse_arg_fn)
3776 self.expect(&token::RPAREN);
3778 let hi = self.span.hi;
3780 let (ret_style, ret_ty) = self.parse_ret_ty();
3782 let fn_decl = P(FnDecl {
3789 (spanned(lo, hi, explicit_self), fn_decl)
3792 // parse the |arg, arg| header on a lambda
3793 fn parse_fn_block_decl(&mut self) -> P<FnDecl> {
3794 let inputs_captures = {
3795 if self.eat(&token::OROR) {
3798 self.parse_unspanned_seq(
3799 &token::BINOP(token::OR),
3800 &token::BINOP(token::OR),
3801 seq_sep_trailing_disallowed(token::COMMA),
3802 |p| p.parse_fn_block_arg()
3806 let output = if self.eat(&token::RARROW) {
3807 self.parse_ty(false)
3810 id: ast::DUMMY_NODE_ID,
3817 inputs: inputs_captures,
3824 // Parses the `(arg, arg) -> return_type` header on a procedure.
3825 fn parse_proc_decl(&mut self) -> P<FnDecl> {
3827 self.parse_unspanned_seq(&token::LPAREN,
3829 seq_sep_trailing_allowed(token::COMMA),
3830 |p| p.parse_fn_block_arg());
3832 let output = if self.eat(&token::RARROW) {
3833 self.parse_ty(false)
3836 id: ast::DUMMY_NODE_ID,
3850 // parse the name and optional generic types of a function header.
3851 fn parse_fn_header(&mut self) -> (Ident, ast::Generics) {
3852 let id = self.parse_ident();
3853 let generics = self.parse_generics();
3857 fn mk_item(&mut self, lo: BytePos, hi: BytePos, ident: Ident,
3858 node: Item_, vis: Visibility,
3859 attrs: Vec<Attribute>) -> Gc<Item> {
3863 id: ast::DUMMY_NODE_ID,
3870 // parse an item-position function declaration.
3871 fn parse_item_fn(&mut self, fn_style: FnStyle, abi: abi::Abi) -> ItemInfo {
3872 let (ident, generics) = self.parse_fn_header();
3873 let decl = self.parse_fn_decl(false);
3874 let (inner_attrs, body) = self.parse_inner_attrs_and_block();
3875 (ident, ItemFn(decl, fn_style, abi, generics, body), Some(inner_attrs))
3878 // parse a method in a trait impl, starting with `attrs` attributes.
3879 fn parse_method(&mut self,
3880 already_parsed_attrs: Option<Vec<Attribute>>) -> Gc<Method> {
3881 let next_attrs = self.parse_outer_attributes();
3882 let attrs = match already_parsed_attrs {
3883 Some(mut a) => { a.push_all_move(next_attrs); a }
3887 let lo = self.span.lo;
3889 let visa = self.parse_visibility();
3890 let fn_style = self.parse_fn_style();
3891 let ident = self.parse_ident();
3892 let generics = self.parse_generics();
3893 let (explicit_self, decl) = self.parse_fn_decl_with_self(|p| {
3897 let (inner_attrs, body) = self.parse_inner_attrs_and_block();
3898 let hi = body.span.hi;
3899 let attrs = attrs.append(inner_attrs.as_slice());
3900 box(GC) ast::Method {
3904 explicit_self: explicit_self,
3908 id: ast::DUMMY_NODE_ID,
3909 span: mk_sp(lo, hi),
3914 // parse trait Foo { ... }
3915 fn parse_item_trait(&mut self) -> ItemInfo {
3916 let ident = self.parse_ident();
3917 let tps = self.parse_generics();
3918 let sized = self.parse_for_sized();
3920 // Parse traits, if necessary.
3922 if self.token == token::COLON {
3924 traits = self.parse_trait_ref_list(&token::LBRACE);
3926 traits = Vec::new();
3929 let meths = self.parse_trait_methods();
3930 (ident, ItemTrait(tps, sized, traits, meths), None)
3933 // Parses two variants (with the region/type params always optional):
3934 // impl<T> Foo { ... }
3935 // impl<T> ToStr for ~[T] { ... }
3936 fn parse_item_impl(&mut self) -> ItemInfo {
3937 // First, parse type parameters if necessary.
3938 let generics = self.parse_generics();
3940 // Special case: if the next identifier that follows is '(', don't
3941 // allow this to be parsed as a trait.
3942 let could_be_trait = self.token != token::LPAREN;
3945 let mut ty = self.parse_ty(false);
3947 // Parse traits, if necessary.
3948 let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) {
3949 // New-style trait. Reinterpret the type as a trait.
3950 let opt_trait_ref = match ty.node {
3951 TyPath(ref path, None, node_id) => {
3953 path: /* bad */ (*path).clone(),
3958 self.span_err(ty.span,
3959 "bounded traits are only valid in type position");
3963 self.span_err(ty.span, "not a trait");
3968 ty = self.parse_ty(false);
3974 let mut meths = Vec::new();
3975 self.expect(&token::LBRACE);
3976 let (inner_attrs, next) = self.parse_inner_attrs_and_next();
3977 let mut method_attrs = Some(next);
3978 while !self.eat(&token::RBRACE) {
3979 meths.push(self.parse_method(method_attrs));
3980 method_attrs = None;
3983 let ident = ast_util::impl_pretty_name(&opt_trait, &*ty);
3985 (ident, ItemImpl(generics, opt_trait, ty, meths), Some(inner_attrs))
3988 // parse a::B<String,int>
3989 fn parse_trait_ref(&mut self) -> TraitRef {
3991 path: self.parse_path(LifetimeAndTypesWithoutColons).path,
3992 ref_id: ast::DUMMY_NODE_ID,
3996 // parse B + C<String,int> + D
3997 fn parse_trait_ref_list(&mut self, ket: &token::Token) -> Vec<TraitRef> {
3998 self.parse_seq_to_before_end(
4000 seq_sep_trailing_disallowed(token::BINOP(token::PLUS)),
4001 |p| p.parse_trait_ref()
4005 // parse struct Foo { ... }
4006 fn parse_item_struct(&mut self, is_virtual: bool) -> ItemInfo {
4007 let class_name = self.parse_ident();
4008 let generics = self.parse_generics();
4010 let super_struct = if self.eat(&token::COLON) {
4011 let ty = self.parse_ty(false);
4013 TyPath(_, None, _) => {
4017 self.span_err(ty.span, "not a struct");
4025 let mut fields: Vec<StructField>;
4028 if self.eat(&token::LBRACE) {
4029 // It's a record-like struct.
4030 is_tuple_like = false;
4031 fields = Vec::new();
4032 while self.token != token::RBRACE {
4033 fields.push(self.parse_struct_decl_field());
4035 if fields.len() == 0 {
4036 self.fatal(format!("unit-like struct definition should be \
4037 written as `struct {};`",
4038 token::get_ident(class_name)).as_slice());
4041 } else if self.token == token::LPAREN {
4042 // It's a tuple-like struct.
4043 is_tuple_like = true;
4044 fields = self.parse_unspanned_seq(
4047 seq_sep_trailing_allowed(token::COMMA),
4049 let attrs = p.parse_outer_attributes();
4051 let struct_field_ = ast::StructField_ {
4052 kind: UnnamedField(p.parse_visibility()),
4053 id: ast::DUMMY_NODE_ID,
4054 ty: p.parse_ty(false),
4057 spanned(lo, p.span.hi, struct_field_)
4059 self.expect(&token::SEMI);
4060 } else if self.eat(&token::SEMI) {
4061 // It's a unit-like struct.
4062 is_tuple_like = true;
4063 fields = Vec::new();
4065 let token_str = self.this_token_to_str();
4066 self.fatal(format!("expected `{}`, `(`, or `;` after struct \
4067 name but found `{}`", "{",
4068 token_str).as_slice())
4071 let _ = ast::DUMMY_NODE_ID; // FIXME: Workaround for crazy bug.
4072 let new_id = ast::DUMMY_NODE_ID;
4074 ItemStruct(box(GC) ast::StructDef {
4076 ctor_id: if is_tuple_like { Some(new_id) } else { None },
4077 super_struct: super_struct,
4078 is_virtual: is_virtual,
4083 // parse a structure field declaration
4084 pub fn parse_single_struct_field(&mut self,
4086 attrs: Vec<Attribute> )
4088 let a_var = self.parse_name_and_ty(vis, attrs);
4096 let token_str = self.this_token_to_str();
4097 self.span_fatal(self.span,
4098 format!("expected `,`, or `\\}` but found `{}`",
4099 token_str).as_slice())
4103 let token_str = self.this_token_to_str();
4104 self.span_fatal(self.span,
4105 format!("expected `,`, or `}}` but found `{}`",
4106 token_str).as_slice())
4112 // parse an element of a struct definition
4113 fn parse_struct_decl_field(&mut self) -> StructField {
4115 let attrs = self.parse_outer_attributes();
4117 if self.eat_keyword(keywords::Pub) {
4118 return self.parse_single_struct_field(Public, attrs);
4121 return self.parse_single_struct_field(Inherited, attrs);
4124 // parse visiility: PUB, PRIV, or nothing
4125 fn parse_visibility(&mut self) -> Visibility {
4126 if self.eat_keyword(keywords::Pub) { Public }
4130 fn parse_sized(&mut self) -> Sized {
4131 if self.eat_keyword(keywords::Type) { DynSize }
4135 fn parse_for_sized(&mut self) -> Sized {
4136 if self.eat_keyword(keywords::For) {
4137 if !self.eat_keyword(keywords::Type) {
4138 self.span_err(self.last_span,
4139 "expected 'type' after for in trait item");
4147 // given a termination token and a vector of already-parsed
4148 // attributes (of length 0 or 1), parse all of the items in a module
4149 fn parse_mod_items(&mut self,
4151 first_item_attrs: Vec<Attribute>,
4154 // parse all of the items up to closing or an attribute.
4155 // view items are legal here.
4156 let ParsedItemsAndViewItems {
4157 attrs_remaining: attrs_remaining,
4158 view_items: view_items,
4159 items: starting_items,
4161 } = self.parse_items_and_view_items(first_item_attrs, true, true);
4162 let mut items: Vec<Gc<Item>> = starting_items;
4163 let attrs_remaining_len = attrs_remaining.len();
4165 // don't think this other loop is even necessary....
4167 let mut first = true;
4168 while self.token != term {
4169 let mut attrs = self.parse_outer_attributes();
4171 attrs = attrs_remaining.clone().append(attrs.as_slice());
4174 debug!("parse_mod_items: parse_item_or_view_item(attrs={:?})",
4176 match self.parse_item_or_view_item(attrs,
4177 true /* macros allowed */) {
4178 IoviItem(item) => items.push(item),
4179 IoviViewItem(view_item) => {
4180 self.span_fatal(view_item.span,
4181 "view items must be declared at the top of \
4185 let token_str = self.this_token_to_str();
4186 self.fatal(format!("expected item but found `{}`",
4187 token_str).as_slice())
4192 if first && attrs_remaining_len > 0u {
4193 // We parsed attributes for the first item but didn't find it
4194 self.span_err(self.last_span, "expected item after attributes");
4198 inner: mk_sp(inner_lo, self.span.lo),
4199 view_items: view_items,
4204 fn parse_item_const(&mut self) -> ItemInfo {
4205 let m = if self.eat_keyword(keywords::Mut) {MutMutable} else {MutImmutable};
4206 let id = self.parse_ident();
4207 self.expect(&token::COLON);
4208 let ty = self.parse_ty(false);
4209 self.expect(&token::EQ);
4210 let e = self.parse_expr();
4211 self.commit_expr_expecting(e, token::SEMI);
4212 (id, ItemStatic(ty, m, e), None)
4215 // parse a `mod <foo> { ... }` or `mod <foo>;` item
4216 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> ItemInfo {
4217 let id_span = self.span;
4218 let id = self.parse_ident();
4219 if self.token == token::SEMI {
4221 // This mod is in an external file. Let's go get it!
4222 let (m, attrs) = self.eval_src_mod(id, outer_attrs, id_span);
4223 (id, m, Some(attrs))
4225 self.push_mod_path(id, outer_attrs);
4226 self.expect(&token::LBRACE);
4227 let mod_inner_lo = self.span.lo;
4228 let old_owns_directory = self.owns_directory;
4229 self.owns_directory = true;
4230 let (inner, next) = self.parse_inner_attrs_and_next();
4231 let m = self.parse_mod_items(token::RBRACE, next, mod_inner_lo);
4232 self.expect(&token::RBRACE);
4233 self.owns_directory = old_owns_directory;
4234 self.pop_mod_path();
4235 (id, ItemMod(m), Some(inner))
4239 fn push_mod_path(&mut self, id: Ident, attrs: &[Attribute]) {
4240 let default_path = self.id_to_interned_str(id);
4241 let file_path = match ::attr::first_attr_value_str_by_name(attrs,
4244 None => default_path,
4246 self.mod_path_stack.push(file_path)
4249 fn pop_mod_path(&mut self) {
4250 self.mod_path_stack.pop().unwrap();
4253 // read a module from a source file.
4254 fn eval_src_mod(&mut self,
4256 outer_attrs: &[ast::Attribute],
4258 -> (ast::Item_, Vec<ast::Attribute> ) {
4259 let mut prefix = Path::new(self.sess.span_diagnostic.cm.span_to_filename(self.span));
4261 let mod_path = Path::new(".").join_many(self.mod_path_stack.as_slice());
4262 let dir_path = prefix.join(&mod_path);
4263 let mod_string = token::get_ident(id);
4264 let (file_path, owns_directory) = match ::attr::first_attr_value_str_by_name(
4265 outer_attrs, "path") {
4266 Some(d) => (dir_path.join(d), true),
4268 let mod_name = mod_string.get().to_string();
4269 let default_path_str = format!("{}.rs", mod_name);
4270 let secondary_path_str = format!("{}/mod.rs", mod_name);
4271 let default_path = dir_path.join(default_path_str.as_slice());
4272 let secondary_path = dir_path.join(secondary_path_str.as_slice());
4273 let default_exists = default_path.exists();
4274 let secondary_exists = secondary_path.exists();
4276 if !self.owns_directory {
4277 self.span_err(id_sp,
4278 "cannot declare a new module at this location");
4279 let this_module = match self.mod_path_stack.last() {
4280 Some(name) => name.get().to_string(),
4281 None => self.root_module_name.get_ref().clone(),
4283 self.span_note(id_sp,
4284 format!("maybe move this module `{0}` \
4285 to its own directory via \
4287 this_module).as_slice());
4288 if default_exists || secondary_exists {
4289 self.span_note(id_sp,
4290 format!("... or maybe `use` the module \
4291 `{}` instead of possibly \
4293 mod_name).as_slice());
4295 self.abort_if_errors();
4298 match (default_exists, secondary_exists) {
4299 (true, false) => (default_path, false),
4300 (false, true) => (secondary_path, true),
4302 self.span_fatal(id_sp,
4303 format!("file not found for module \
4305 mod_name).as_slice());
4310 format!("file for module `{}` found at both {} \
4314 secondary_path_str).as_slice());
4320 self.eval_src_mod_from_path(file_path, owns_directory,
4321 mod_string.get().to_string(), id_sp)
4324 fn eval_src_mod_from_path(&mut self,
4326 owns_directory: bool,
4328 id_sp: Span) -> (ast::Item_, Vec<ast::Attribute> ) {
4329 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
4330 match included_mod_stack.iter().position(|p| *p == path) {
4332 let mut err = String::from_str("circular modules: ");
4333 let len = included_mod_stack.len();
4334 for p in included_mod_stack.slice(i, len).iter() {
4335 err.push_str(p.display().as_maybe_owned().as_slice());
4336 err.push_str(" -> ");
4338 err.push_str(path.display().as_maybe_owned().as_slice());
4339 self.span_fatal(id_sp, err.as_slice());
4343 included_mod_stack.push(path.clone());
4344 drop(included_mod_stack);
4347 new_sub_parser_from_file(self.sess,
4353 let mod_inner_lo = p0.span.lo;
4354 let (mod_attrs, next) = p0.parse_inner_attrs_and_next();
4355 let first_item_outer_attrs = next;
4356 let m0 = p0.parse_mod_items(token::EOF, first_item_outer_attrs, mod_inner_lo);
4357 self.sess.included_mod_stack.borrow_mut().pop();
4358 return (ast::ItemMod(m0), mod_attrs);
4361 // parse a function declaration from a foreign module
4362 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility,
4363 attrs: Vec<Attribute>) -> Gc<ForeignItem> {
4364 let lo = self.span.lo;
4365 self.expect_keyword(keywords::Fn);
4367 let (ident, generics) = self.parse_fn_header();
4368 let decl = self.parse_fn_decl(true);
4369 let hi = self.span.hi;
4370 self.expect(&token::SEMI);
4371 box(GC) ast::ForeignItem { ident: ident,
4373 node: ForeignItemFn(decl, generics),
4374 id: ast::DUMMY_NODE_ID,
4375 span: mk_sp(lo, hi),
4379 // parse a static item from a foreign module
4380 fn parse_item_foreign_static(&mut self, vis: ast::Visibility,
4381 attrs: Vec<Attribute> ) -> Gc<ForeignItem> {
4382 let lo = self.span.lo;
4384 self.expect_keyword(keywords::Static);
4385 let mutbl = self.eat_keyword(keywords::Mut);
4387 let ident = self.parse_ident();
4388 self.expect(&token::COLON);
4389 let ty = self.parse_ty(false);
4390 let hi = self.span.hi;
4391 self.expect(&token::SEMI);
4392 box(GC) ast::ForeignItem {
4395 node: ForeignItemStatic(ty, mutbl),
4396 id: ast::DUMMY_NODE_ID,
4397 span: mk_sp(lo, hi),
4402 // parse safe/unsafe and fn
4403 fn parse_fn_style(&mut self) -> FnStyle {
4404 if self.eat_keyword(keywords::Fn) { NormalFn }
4405 else if self.eat_keyword(keywords::Unsafe) {
4406 self.expect_keyword(keywords::Fn);
4409 else { self.unexpected(); }
4413 // at this point, this is essentially a wrapper for
4414 // parse_foreign_items.
4415 fn parse_foreign_mod_items(&mut self,
4417 first_item_attrs: Vec<Attribute> )
4419 let ParsedItemsAndViewItems {
4420 attrs_remaining: attrs_remaining,
4421 view_items: view_items,
4423 foreign_items: foreign_items
4424 } = self.parse_foreign_items(first_item_attrs, true);
4425 if ! attrs_remaining.is_empty() {
4426 self.span_err(self.last_span,
4427 "expected item after attributes");
4429 assert!(self.token == token::RBRACE);
4432 view_items: view_items,
4433 items: foreign_items
4437 /// Parse extern crate links
4441 /// extern crate url;
4442 /// extern crate foo = "bar";
4443 fn parse_item_extern_crate(&mut self,
4445 visibility: Visibility,
4446 attrs: Vec<Attribute> )
4449 let (maybe_path, ident) = match self.token {
4450 token::IDENT(..) => {
4451 let the_ident = self.parse_ident();
4452 self.expect_one_of(&[], &[token::EQ, token::SEMI]);
4453 let path = if self.token == token::EQ {
4455 Some(self.parse_str())
4458 self.expect(&token::SEMI);
4462 let token_str = self.this_token_to_str();
4463 self.span_fatal(self.span,
4464 format!("expected extern crate name but \
4466 token_str).as_slice());
4470 IoviViewItem(ast::ViewItem {
4471 node: ViewItemExternCrate(ident, maybe_path, ast::DUMMY_NODE_ID),
4474 span: mk_sp(lo, self.last_span.hi)
4478 /// Parse `extern` for foreign ABIs
4481 /// `extern` is expected to have been
4482 /// consumed before calling this method
4488 fn parse_item_foreign_mod(&mut self,
4490 opt_abi: Option<abi::Abi>,
4491 visibility: Visibility,
4492 attrs: Vec<Attribute> )
4495 self.expect(&token::LBRACE);
4497 let abi = opt_abi.unwrap_or(abi::C);
4499 let (inner, next) = self.parse_inner_attrs_and_next();
4500 let m = self.parse_foreign_mod_items(abi, next);
4501 self.expect(&token::RBRACE);
4503 let item = self.mk_item(lo,
4505 special_idents::invalid,
4508 maybe_append(attrs, Some(inner)));
4509 return IoviItem(item);
4512 // parse type Foo = Bar;
4513 fn parse_item_type(&mut self) -> ItemInfo {
4514 let ident = self.parse_ident();
4515 let tps = self.parse_generics();
4516 self.expect(&token::EQ);
4517 let ty = self.parse_ty(false);
4518 self.expect(&token::SEMI);
4519 (ident, ItemTy(ty, tps), None)
4522 // parse a structure-like enum variant definition
4523 // this should probably be renamed or refactored...
4524 fn parse_struct_def(&mut self) -> Gc<StructDef> {
4525 let mut fields: Vec<StructField> = Vec::new();
4526 while self.token != token::RBRACE {
4527 fields.push(self.parse_struct_decl_field());
4531 return box(GC) ast::StructDef {
4539 // parse the part of an "enum" decl following the '{'
4540 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> EnumDef {
4541 let mut variants = Vec::new();
4542 let mut all_nullary = true;
4543 let mut have_disr = false;
4544 while self.token != token::RBRACE {
4545 let variant_attrs = self.parse_outer_attributes();
4546 let vlo = self.span.lo;
4548 let vis = self.parse_visibility();
4552 let mut args = Vec::new();
4553 let mut disr_expr = None;
4554 ident = self.parse_ident();
4555 if self.eat(&token::LBRACE) {
4556 // Parse a struct variant.
4557 all_nullary = false;
4558 kind = StructVariantKind(self.parse_struct_def());
4559 } else if self.token == token::LPAREN {
4560 all_nullary = false;
4561 let arg_tys = self.parse_enum_variant_seq(
4564 seq_sep_trailing_disallowed(token::COMMA),
4565 |p| p.parse_ty(false)
4567 for ty in arg_tys.move_iter() {
4568 args.push(ast::VariantArg {
4570 id: ast::DUMMY_NODE_ID,
4573 kind = TupleVariantKind(args);
4574 } else if self.eat(&token::EQ) {
4576 disr_expr = Some(self.parse_expr());
4577 kind = TupleVariantKind(args);
4579 kind = TupleVariantKind(Vec::new());
4582 let vr = ast::Variant_ {
4584 attrs: variant_attrs,
4586 id: ast::DUMMY_NODE_ID,
4587 disr_expr: disr_expr,
4590 variants.push(P(spanned(vlo, self.last_span.hi, vr)));
4592 if !self.eat(&token::COMMA) { break; }
4594 self.expect(&token::RBRACE);
4595 if have_disr && !all_nullary {
4596 self.fatal("discriminator values can only be used with a c-like \
4600 ast::EnumDef { variants: variants }
4603 // parse an "enum" declaration
4604 fn parse_item_enum(&mut self) -> ItemInfo {
4605 let id = self.parse_ident();
4606 let generics = self.parse_generics();
4607 self.expect(&token::LBRACE);
4609 let enum_definition = self.parse_enum_def(&generics);
4610 (id, ItemEnum(enum_definition, generics), None)
4613 fn fn_expr_lookahead(tok: &token::Token) -> bool {
4615 token::LPAREN | token::AT | token::TILDE | token::BINOP(_) => true,
4620 // Parses a string as an ABI spec on an extern type or module. Consumes
4621 // the `extern` keyword, if one is found.
4622 fn parse_opt_abi(&mut self) -> Option<abi::Abi> {
4624 token::LIT_STR(s) | token::LIT_STR_RAW(s, _) => {
4626 let identifier_string = token::get_ident(s);
4627 let the_string = identifier_string.get();
4628 match abi::lookup(the_string) {
4629 Some(abi) => Some(abi),
4633 format!("illegal ABI: expected one of [{}], \
4635 abi::all_names().connect(", "),
4636 the_string).as_slice());
4646 // parse one of the items or view items allowed by the
4647 // flags; on failure, return IoviNone.
4648 // NB: this function no longer parses the items inside an
4650 fn parse_item_or_view_item(&mut self,
4651 attrs: Vec<Attribute> ,
4652 macros_allowed: bool)
4655 INTERPOLATED(token::NtItem(item)) => {
4657 let new_attrs = attrs.append(item.attrs.as_slice());
4658 return IoviItem(box(GC) Item {
4666 let lo = self.span.lo;
4668 let visibility = self.parse_visibility();
4670 // must be a view item:
4671 if self.eat_keyword(keywords::Use) {
4672 // USE ITEM (IoviViewItem)
4673 let view_item = self.parse_use();
4674 self.expect(&token::SEMI);
4675 return IoviViewItem(ast::ViewItem {
4679 span: mk_sp(lo, self.last_span.hi)
4682 // either a view item or an item:
4683 if self.eat_keyword(keywords::Extern) {
4684 let next_is_mod = self.eat_keyword(keywords::Mod);
4686 if next_is_mod || self.eat_keyword(keywords::Crate) {
4688 self.span_err(mk_sp(lo, self.last_span.hi),
4689 format!("`extern mod` is obsolete, use \
4690 `extern crate` instead \
4691 to refer to external \
4692 crates.").as_slice())
4694 return self.parse_item_extern_crate(lo, visibility, attrs);
4697 let opt_abi = self.parse_opt_abi();
4699 if self.eat_keyword(keywords::Fn) {
4700 // EXTERN FUNCTION ITEM
4701 let abi = opt_abi.unwrap_or(abi::C);
4702 let (ident, item_, extra_attrs) =
4703 self.parse_item_fn(NormalFn, abi);
4704 let item = self.mk_item(lo,
4709 maybe_append(attrs, extra_attrs));
4710 return IoviItem(item);
4711 } else if self.token == token::LBRACE {
4712 return self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs);
4715 let token_str = self.this_token_to_str();
4716 self.span_fatal(self.span,
4717 format!("expected `{}` or `fn` but found `{}`", "{",
4718 token_str).as_slice());
4721 let is_virtual = self.eat_keyword(keywords::Virtual);
4722 if is_virtual && !self.is_keyword(keywords::Struct) {
4723 self.span_err(self.span,
4724 "`virtual` keyword may only be used with `struct`");
4727 // the rest are all guaranteed to be items:
4728 if self.is_keyword(keywords::Static) {
4731 let (ident, item_, extra_attrs) = self.parse_item_const();
4732 let item = self.mk_item(lo,
4737 maybe_append(attrs, extra_attrs));
4738 return IoviItem(item);
4740 if self.is_keyword(keywords::Fn) &&
4741 self.look_ahead(1, |f| !Parser::fn_expr_lookahead(f)) {
4744 let (ident, item_, extra_attrs) =
4745 self.parse_item_fn(NormalFn, abi::Rust);
4746 let item = self.mk_item(lo,
4751 maybe_append(attrs, extra_attrs));
4752 return IoviItem(item);
4754 if self.is_keyword(keywords::Unsafe)
4755 && self.look_ahead(1u, |t| *t != token::LBRACE) {
4756 // UNSAFE FUNCTION ITEM
4758 let abi = if self.eat_keyword(keywords::Extern) {
4759 self.parse_opt_abi().unwrap_or(abi::C)
4763 self.expect_keyword(keywords::Fn);
4764 let (ident, item_, extra_attrs) =
4765 self.parse_item_fn(UnsafeFn, abi);
4766 let item = self.mk_item(lo,
4771 maybe_append(attrs, extra_attrs));
4772 return IoviItem(item);
4774 if self.eat_keyword(keywords::Mod) {
4776 let (ident, item_, extra_attrs) =
4777 self.parse_item_mod(attrs.as_slice());
4778 let item = self.mk_item(lo,
4783 maybe_append(attrs, extra_attrs));
4784 return IoviItem(item);
4786 if self.eat_keyword(keywords::Type) {
4788 let (ident, item_, extra_attrs) = self.parse_item_type();
4789 let item = self.mk_item(lo,
4794 maybe_append(attrs, extra_attrs));
4795 return IoviItem(item);
4797 if self.eat_keyword(keywords::Enum) {
4799 let (ident, item_, extra_attrs) = self.parse_item_enum();
4800 let item = self.mk_item(lo,
4805 maybe_append(attrs, extra_attrs));
4806 return IoviItem(item);
4808 if self.eat_keyword(keywords::Trait) {
4810 let (ident, item_, extra_attrs) = self.parse_item_trait();
4811 let item = self.mk_item(lo,
4816 maybe_append(attrs, extra_attrs));
4817 return IoviItem(item);
4819 if self.eat_keyword(keywords::Impl) {
4821 let (ident, item_, extra_attrs) = self.parse_item_impl();
4822 let item = self.mk_item(lo,
4827 maybe_append(attrs, extra_attrs));
4828 return IoviItem(item);
4830 if self.eat_keyword(keywords::Struct) {
4832 let (ident, item_, extra_attrs) = self.parse_item_struct(is_virtual);
4833 let item = self.mk_item(lo,
4838 maybe_append(attrs, extra_attrs));
4839 return IoviItem(item);
4841 self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility)
4844 // parse a foreign item; on failure, return IoviNone.
4845 fn parse_foreign_item(&mut self,
4846 attrs: Vec<Attribute> ,
4847 macros_allowed: bool)
4849 maybe_whole!(iovi self, NtItem);
4850 let lo = self.span.lo;
4852 let visibility = self.parse_visibility();
4854 if self.is_keyword(keywords::Static) {
4855 // FOREIGN STATIC ITEM
4856 let item = self.parse_item_foreign_static(visibility, attrs);
4857 return IoviForeignItem(item);
4859 if self.is_keyword(keywords::Fn) || self.is_keyword(keywords::Unsafe) {
4860 // FOREIGN FUNCTION ITEM
4861 let item = self.parse_item_foreign_fn(visibility, attrs);
4862 return IoviForeignItem(item);
4864 self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility)
4867 // this is the fall-through for parsing items.
4868 fn parse_macro_use_or_failure(
4870 attrs: Vec<Attribute> ,
4871 macros_allowed: bool,
4873 visibility: Visibility
4874 ) -> ItemOrViewItem {
4875 if macros_allowed && !token::is_any_keyword(&self.token)
4876 && self.look_ahead(1, |t| *t == token::NOT)
4877 && (self.look_ahead(2, |t| is_plain_ident(t))
4878 || self.look_ahead(2, |t| *t == token::LPAREN)
4879 || self.look_ahead(2, |t| *t == token::LBRACE)) {
4880 // MACRO INVOCATION ITEM
4883 let pth = self.parse_path(NoTypesAllowed).path;
4884 self.expect(&token::NOT);
4886 // a 'special' identifier (like what `macro_rules!` uses)
4887 // is optional. We should eventually unify invoc syntax
4889 let id = if is_plain_ident(&self.token) {
4892 token::special_idents::invalid // no special identifier
4894 // eat a matched-delimiter token tree:
4895 let tts = match token::close_delimiter_for(&self.token) {
4898 self.parse_seq_to_end(&ket,
4900 |p| p.parse_token_tree())
4902 None => self.fatal("expected open delimiter")
4904 // single-variant-enum... :
4905 let m = ast::MacInvocTT(pth, tts, EMPTY_CTXT);
4906 let m: ast::Mac = codemap::Spanned { node: m,
4907 span: mk_sp(self.span.lo,
4909 let item_ = ItemMac(m);
4910 let item = self.mk_item(lo,
4916 return IoviItem(item);
4919 // FAILURE TO PARSE ITEM
4920 if visibility != Inherited {
4921 let mut s = String::from_str("unmatched visibility `");
4922 if visibility == Public {
4928 self.span_fatal(self.last_span, s.as_slice());
4930 return IoviNone(attrs);
4933 pub fn parse_item(&mut self, attrs: Vec<Attribute> ) -> Option<Gc<Item>> {
4934 match self.parse_item_or_view_item(attrs, true) {
4935 IoviNone(_) => None,
4937 self.fatal("view items are not allowed here"),
4938 IoviForeignItem(_) =>
4939 self.fatal("foreign items are not allowed here"),
4940 IoviItem(item) => Some(item)
4944 // parse, e.g., "use a::b::{z,y}"
4945 fn parse_use(&mut self) -> ViewItem_ {
4946 return ViewItemUse(self.parse_view_path());
4950 // matches view_path : MOD? IDENT EQ non_global_path
4951 // | MOD? non_global_path MOD_SEP LBRACE RBRACE
4952 // | MOD? non_global_path MOD_SEP LBRACE ident_seq RBRACE
4953 // | MOD? non_global_path MOD_SEP STAR
4954 // | MOD? non_global_path
4955 fn parse_view_path(&mut self) -> Gc<ViewPath> {
4956 let lo = self.span.lo;
4958 if self.token == token::LBRACE {
4960 let idents = self.parse_unspanned_seq(
4961 &token::LBRACE, &token::RBRACE,
4962 seq_sep_trailing_allowed(token::COMMA),
4963 |p| p.parse_path_list_ident());
4964 let path = ast::Path {
4965 span: mk_sp(lo, self.span.hi),
4967 segments: Vec::new()
4969 return box(GC) spanned(lo, self.span.hi,
4970 ViewPathList(path, idents, ast::DUMMY_NODE_ID));
4973 let first_ident = self.parse_ident();
4974 let mut path = vec!(first_ident);
4979 let path_lo = self.span.lo;
4980 path = vec!(self.parse_ident());
4981 while self.token == token::MOD_SEP {
4983 let id = self.parse_ident();
4986 let path = ast::Path {
4987 span: mk_sp(path_lo, self.span.hi),
4989 segments: path.move_iter().map(|identifier| {
4991 identifier: identifier,
4992 lifetimes: Vec::new(),
4993 types: OwnedSlice::empty(),
4997 return box(GC) spanned(lo, self.span.hi,
4998 ViewPathSimple(first_ident, path,
4999 ast::DUMMY_NODE_ID));
5003 // foo::bar or foo::{a,b,c} or foo::*
5004 while self.token == token::MOD_SEP {
5008 token::IDENT(i, _) => {
5013 // foo::bar::{a,b,c}
5015 let idents = self.parse_unspanned_seq(
5018 seq_sep_trailing_allowed(token::COMMA),
5019 |p| p.parse_path_list_ident()
5021 let path = ast::Path {
5022 span: mk_sp(lo, self.span.hi),
5024 segments: path.move_iter().map(|identifier| {
5026 identifier: identifier,
5027 lifetimes: Vec::new(),
5028 types: OwnedSlice::empty(),
5032 return box(GC) spanned(lo, self.span.hi,
5033 ViewPathList(path, idents, ast::DUMMY_NODE_ID));
5037 token::BINOP(token::STAR) => {
5039 let path = ast::Path {
5040 span: mk_sp(lo, self.span.hi),
5042 segments: path.move_iter().map(|identifier| {
5044 identifier: identifier,
5045 lifetimes: Vec::new(),
5046 types: OwnedSlice::empty(),
5050 return box(GC) spanned(lo, self.span.hi,
5051 ViewPathGlob(path, ast::DUMMY_NODE_ID));
5060 let last = *path.get(path.len() - 1u);
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,
5074 ViewPathSimple(last, path, ast::DUMMY_NODE_ID));
5077 // Parses a sequence of items. Stops when it finds program
5078 // text that can't be parsed as an item
5079 // - mod_items uses extern_mod_allowed = true
5080 // - block_tail_ uses extern_mod_allowed = false
5081 fn parse_items_and_view_items(&mut self,
5082 first_item_attrs: Vec<Attribute> ,
5083 mut extern_mod_allowed: bool,
5084 macros_allowed: bool)
5085 -> ParsedItemsAndViewItems {
5086 let mut attrs = first_item_attrs.append(self.parse_outer_attributes().as_slice());
5087 // First, parse view items.
5088 let mut view_items : Vec<ast::ViewItem> = Vec::new();
5089 let mut items = Vec::new();
5091 // I think this code would probably read better as a single
5092 // loop with a mutable three-state-variable (for extern crates,
5093 // view items, and regular items) ... except that because
5094 // of macros, I'd like to delay that entire check until later.
5096 match self.parse_item_or_view_item(attrs, macros_allowed) {
5097 IoviNone(attrs) => {
5098 return ParsedItemsAndViewItems {
5099 attrs_remaining: attrs,
5100 view_items: view_items,
5102 foreign_items: Vec::new()
5105 IoviViewItem(view_item) => {
5106 match view_item.node {
5107 ViewItemUse(..) => {
5108 // `extern crate` must precede `use`.
5109 extern_mod_allowed = false;
5111 ViewItemExternCrate(..) if !extern_mod_allowed => {
5112 self.span_err(view_item.span,
5113 "\"extern crate\" declarations are \
5116 ViewItemExternCrate(..) => {}
5118 view_items.push(view_item);
5122 attrs = self.parse_outer_attributes();
5125 IoviForeignItem(_) => {
5129 attrs = self.parse_outer_attributes();
5132 // Next, parse items.
5134 match self.parse_item_or_view_item(attrs, macros_allowed) {
5135 IoviNone(returned_attrs) => {
5136 attrs = returned_attrs;
5139 IoviViewItem(view_item) => {
5140 attrs = self.parse_outer_attributes();
5141 self.span_err(view_item.span,
5142 "`use` and `extern crate` declarations must precede items");
5145 attrs = self.parse_outer_attributes();
5148 IoviForeignItem(_) => {
5154 ParsedItemsAndViewItems {
5155 attrs_remaining: attrs,
5156 view_items: view_items,
5158 foreign_items: Vec::new()
5162 // Parses a sequence of foreign items. Stops when it finds program
5163 // text that can't be parsed as an item
5164 fn parse_foreign_items(&mut self, first_item_attrs: Vec<Attribute> ,
5165 macros_allowed: bool)
5166 -> ParsedItemsAndViewItems {
5167 let mut attrs = first_item_attrs.append(self.parse_outer_attributes().as_slice());
5168 let mut foreign_items = Vec::new();
5170 match self.parse_foreign_item(attrs, macros_allowed) {
5171 IoviNone(returned_attrs) => {
5172 if self.token == token::RBRACE {
5173 attrs = returned_attrs;
5178 IoviViewItem(view_item) => {
5179 // I think this can't occur:
5180 self.span_err(view_item.span,
5181 "`use` and `extern crate` declarations must precede items");
5184 // FIXME #5668: this will occur for a macro invocation:
5185 self.span_fatal(item.span, "macros cannot expand to foreign items");
5187 IoviForeignItem(foreign_item) => {
5188 foreign_items.push(foreign_item);
5191 attrs = self.parse_outer_attributes();
5194 ParsedItemsAndViewItems {
5195 attrs_remaining: attrs,
5196 view_items: Vec::new(),
5198 foreign_items: foreign_items
5202 // Parses a source module as a crate. This is the main
5203 // entry point for the parser.
5204 pub fn parse_crate_mod(&mut self) -> Crate {
5205 let lo = self.span.lo;
5206 // parse the crate's inner attrs, maybe (oops) one
5207 // of the attrs of an item:
5208 let (inner, next) = self.parse_inner_attrs_and_next();
5209 let first_item_outer_attrs = next;
5210 // parse the items inside the crate:
5211 let m = self.parse_mod_items(token::EOF, first_item_outer_attrs, lo);
5216 config: self.cfg.clone(),
5217 span: mk_sp(lo, self.span.lo)
5221 pub fn parse_optional_str(&mut self)
5222 -> Option<(InternedString, ast::StrStyle)> {
5223 let (s, style) = match self.token {
5224 token::LIT_STR(s) => (self.id_to_interned_str(s), ast::CookedStr),
5225 token::LIT_STR_RAW(s, n) => {
5226 (self.id_to_interned_str(s), ast::RawStr(n))
5234 pub fn parse_str(&mut self) -> (InternedString, StrStyle) {
5235 match self.parse_optional_str() {
5237 _ => self.fatal("expected string literal")