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.
11 pub use self::PathParsingMode::*;
12 use self::ItemOrViewItem::*;
15 use ast::{AssociatedType, BareFnTy};
16 use ast::{RegionTyParamBound, TraitTyParamBound, TraitBoundModifier};
17 use ast::{ProvidedMethod, Public, Unsafety};
18 use ast::{Mod, BiAdd, Arg, Arm, Attribute, BindByRef, BindByValue};
19 use ast::{BiBitAnd, BiBitOr, BiBitXor, BiRem, BiLt, BiGt, Block};
20 use ast::{BlockCheckMode, CaptureByRef, CaptureByValue, CaptureClause};
21 use ast::{Crate, CrateConfig, Decl, DeclItem};
22 use ast::{DeclLocal, DefaultBlock, DefaultReturn};
23 use ast::{UnDeref, BiDiv, EMPTY_CTXT, EnumDef, ExplicitSelf};
24 use ast::{Expr, Expr_, ExprAddrOf, ExprMatch, ExprAgain};
25 use ast::{ExprAssign, ExprAssignOp, ExprBinary, ExprBlock, ExprBox};
26 use ast::{ExprBreak, ExprCall, ExprCast};
27 use ast::{ExprField, ExprTupField, ExprClosure, ExprIf, ExprIfLet, ExprIndex};
28 use ast::{ExprLit, ExprLoop, ExprMac, ExprRange};
29 use ast::{ExprMethodCall, ExprParen, ExprPath, ExprQPath};
30 use ast::{ExprRepeat, ExprRet, ExprStruct, ExprTup, ExprUnary};
31 use ast::{ExprVec, ExprWhile, ExprWhileLet, ExprForLoop, Field, FnDecl};
32 use ast::{FnUnboxedClosureKind, FnMutUnboxedClosureKind};
33 use ast::{FnOnceUnboxedClosureKind};
34 use ast::{ForeignItem, ForeignItemStatic, ForeignItemFn, ForeignMod, FunctionRetTy};
35 use ast::{Ident, Inherited, ImplItem, Item, Item_, ItemStatic};
36 use ast::{ItemEnum, ItemFn, ItemForeignMod, ItemImpl, ItemConst};
37 use ast::{ItemMac, ItemMod, ItemStruct, ItemTrait, ItemTy};
38 use ast::{LifetimeDef, Lit, Lit_};
39 use ast::{LitBool, LitChar, LitByte, LitBinary};
40 use ast::{LitStr, LitInt, Local, LocalLet};
41 use ast::{MacStmtWithBraces, MacStmtWithSemicolon, MacStmtWithoutBraces};
42 use ast::{MutImmutable, MutMutable, Mac_, MacInvocTT, MatchSource};
43 use ast::{Method, MutTy, BiMul, Mutability};
44 use ast::{MethodImplItem, NamedField, UnNeg, NoReturn, NodeId, UnNot};
45 use ast::{Pat, PatEnum, PatIdent, PatLit, PatRange, PatRegion, PatStruct};
46 use ast::{PatTup, PatBox, PatWild, PatWildMulti, PatWildSingle};
47 use ast::{PolyTraitRef};
48 use ast::{QPath, RequiredMethod};
49 use ast::{Return, BiShl, BiShr, Stmt, StmtDecl};
50 use ast::{StmtExpr, StmtSemi, StmtMac, StructDef, StructField};
51 use ast::{StructVariantKind, BiSub, StrStyle};
52 use ast::{SelfExplicit, SelfRegion, SelfStatic, SelfValue};
53 use ast::{Delimited, SequenceRepetition, TokenTree, TraitItem, TraitRef};
54 use ast::{TtDelimited, TtSequence, TtToken};
55 use ast::{TupleVariantKind, Ty, Ty_, TypeBinding};
56 use ast::{TyFixedLengthVec, TyBareFn};
57 use ast::{TyTypeof, TyInfer, TypeMethod};
58 use ast::{TyParam, TyParamBound, TyParen, TyPath, TyPolyTraitRef, TyPtr, TyQPath};
59 use ast::{TyRptr, TyTup, TyU32, TyVec, UnUniq};
60 use ast::{TypeImplItem, TypeTraitItem, Typedef, UnboxedClosureKind};
61 use ast::{UnnamedField, UnsafeBlock};
62 use ast::{ViewItem, ViewItem_, ViewItemExternCrate, ViewItemUse};
63 use ast::{ViewPath, ViewPathGlob, ViewPathList, ViewPathSimple};
64 use ast::{Visibility, WhereClause};
66 use ast_util::{self, as_prec, ident_to_path, operator_prec};
67 use codemap::{self, Span, BytePos, Spanned, spanned, mk_sp};
69 use ext::tt::macro_parser;
71 use parse::attr::ParserAttr;
73 use parse::common::{SeqSep, seq_sep_none, seq_sep_trailing_allowed};
74 use parse::lexer::{Reader, TokenAndSpan};
75 use parse::obsolete::{ParserObsoleteMethods, ObsoleteSyntax};
76 use parse::token::{self, MatchNt, SubstNt, SpecialVarNt, InternedString};
77 use parse::token::{keywords, special_idents, SpecialMacroVar};
78 use parse::{new_sub_parser_from_file, ParseSess};
81 use owned_slice::OwnedSlice;
83 use std::collections::HashSet;
84 use std::io::fs::PathExtensions;
92 flags Restrictions: u8 {
93 const UNRESTRICTED = 0b0000,
94 const RESTRICTION_STMT_EXPR = 0b0001,
95 const RESTRICTION_NO_BAR_OP = 0b0010,
96 const RESTRICTION_NO_STRUCT_LITERAL = 0b0100,
97 const RESTRICTION_NO_DOTS = 0b1000,
102 type ItemInfo = (Ident, Item_, Option<Vec<Attribute> >);
104 /// How to parse a path. There are four different kinds of paths, all of which
105 /// are parsed somewhat differently.
106 #[derive(Copy, PartialEq)]
107 pub enum PathParsingMode {
108 /// A path with no type parameters; e.g. `foo::bar::Baz`
110 /// A path with a lifetime and type parameters, with no double colons
111 /// before the type parameters; e.g. `foo::bar<'a>::Baz<T>`
112 LifetimeAndTypesWithoutColons,
113 /// A path with a lifetime and type parameters with double colons before
114 /// the type parameters; e.g. `foo::bar::<'a>::Baz::<T>`
115 LifetimeAndTypesWithColons,
118 /// How to parse a bound, whether to allow bound modifiers such as `?`.
119 #[derive(Copy, PartialEq)]
120 pub enum BoundParsingMode {
125 enum ItemOrViewItem {
126 /// Indicates a failure to parse any kind of item. The attributes are
128 IoviNone(Vec<Attribute>),
130 IoviForeignItem(P<ForeignItem>),
131 IoviViewItem(ViewItem)
135 /// Possibly accept an `token::Interpolated` expression (a pre-parsed expression
136 /// dropped into the token stream, which happens while parsing the result of
137 /// macro expansion). Placement of these is not as complex as I feared it would
138 /// be. The important thing is to make sure that lookahead doesn't balk at
139 /// `token::Interpolated` tokens.
140 macro_rules! maybe_whole_expr {
143 let found = match $p.token {
144 token::Interpolated(token::NtExpr(ref e)) => {
147 token::Interpolated(token::NtPath(_)) => {
148 // FIXME: The following avoids an issue with lexical borrowck scopes,
149 // but the clone is unfortunate.
150 let pt = match $p.token {
151 token::Interpolated(token::NtPath(ref pt)) => (**pt).clone(),
155 Some($p.mk_expr(span.lo, span.hi, ExprPath(pt)))
157 token::Interpolated(token::NtBlock(_)) => {
158 // FIXME: The following avoids an issue with lexical borrowck scopes,
159 // but the clone is unfortunate.
160 let b = match $p.token {
161 token::Interpolated(token::NtBlock(ref b)) => (*b).clone(),
165 Some($p.mk_expr(span.lo, span.hi, ExprBlock(b)))
180 /// As maybe_whole_expr, but for things other than expressions
181 macro_rules! maybe_whole {
182 ($p:expr, $constructor:ident) => (
184 let found = match ($p).token {
185 token::Interpolated(token::$constructor(_)) => {
186 Some(($p).bump_and_get())
190 if let Some(token::Interpolated(token::$constructor(x))) = found {
195 (no_clone $p:expr, $constructor:ident) => (
197 let found = match ($p).token {
198 token::Interpolated(token::$constructor(_)) => {
199 Some(($p).bump_and_get())
203 if let Some(token::Interpolated(token::$constructor(x))) = found {
208 (deref $p:expr, $constructor:ident) => (
210 let found = match ($p).token {
211 token::Interpolated(token::$constructor(_)) => {
212 Some(($p).bump_and_get())
216 if let Some(token::Interpolated(token::$constructor(x))) = found {
221 (Some $p:expr, $constructor:ident) => (
223 let found = match ($p).token {
224 token::Interpolated(token::$constructor(_)) => {
225 Some(($p).bump_and_get())
229 if let Some(token::Interpolated(token::$constructor(x))) = found {
230 return Some(x.clone());
234 (iovi $p:expr, $constructor:ident) => (
236 let found = match ($p).token {
237 token::Interpolated(token::$constructor(_)) => {
238 Some(($p).bump_and_get())
242 if let Some(token::Interpolated(token::$constructor(x))) = found {
243 return IoviItem(x.clone());
247 (pair_empty $p:expr, $constructor:ident) => (
249 let found = match ($p).token {
250 token::Interpolated(token::$constructor(_)) => {
251 Some(($p).bump_and_get())
255 if let Some(token::Interpolated(token::$constructor(x))) = found {
256 return (Vec::new(), x);
263 fn maybe_append(mut lhs: Vec<Attribute>, rhs: Option<Vec<Attribute>>)
266 Some(ref attrs) => lhs.extend(attrs.iter().map(|a| a.clone())),
273 struct ParsedItemsAndViewItems {
274 attrs_remaining: Vec<Attribute>,
275 view_items: Vec<ViewItem>,
276 items: Vec<P<Item>> ,
277 foreign_items: Vec<P<ForeignItem>>
280 /* ident is handled by common.rs */
282 pub struct Parser<'a> {
283 pub sess: &'a ParseSess,
284 /// the current token:
285 pub token: token::Token,
286 /// the span of the current token:
288 /// the span of the prior token:
290 pub cfg: CrateConfig,
291 /// the previous token or None (only stashed sometimes).
292 pub last_token: Option<Box<token::Token>>,
293 pub buffer: [TokenAndSpan; 4],
294 pub buffer_start: int,
296 pub tokens_consumed: uint,
297 pub restrictions: Restrictions,
298 pub quote_depth: uint, // not (yet) related to the quasiquoter
299 pub reader: Box<Reader+'a>,
300 pub interner: Rc<token::IdentInterner>,
301 /// The set of seen errors about obsolete syntax. Used to suppress
302 /// extra detail when the same error is seen twice
303 pub obsolete_set: HashSet<ObsoleteSyntax>,
304 /// Used to determine the path to externally loaded source files
305 pub mod_path_stack: Vec<InternedString>,
306 /// Stack of spans of open delimiters. Used for error message.
307 pub open_braces: Vec<Span>,
308 /// Flag if this parser "owns" the directory that it is currently parsing
309 /// in. This will affect how nested files are looked up.
310 pub owns_directory: bool,
311 /// Name of the root module this parser originated from. If `None`, then the
312 /// name is not known. This does not change while the parser is descending
313 /// into modules, and sub-parsers have new values for this name.
314 pub root_module_name: Option<String>,
315 pub expected_tokens: Vec<TokenType>,
318 #[derive(PartialEq, Eq, Clone)]
325 fn to_string(&self) -> String {
327 TokenType::Token(ref t) => format!("`{}`", Parser::token_to_string(t)),
328 TokenType::Operator => "an operator".to_string(),
333 fn is_plain_ident_or_underscore(t: &token::Token) -> bool {
334 t.is_plain_ident() || *t == token::Underscore
337 impl<'a> Parser<'a> {
338 pub fn new(sess: &'a ParseSess,
339 cfg: ast::CrateConfig,
340 mut rdr: Box<Reader+'a>)
343 let tok0 = rdr.real_token();
345 let placeholder = TokenAndSpan {
346 tok: token::Underscore,
352 interner: token::get_ident_interner(),
368 restrictions: UNRESTRICTED,
370 obsolete_set: HashSet::new(),
371 mod_path_stack: Vec::new(),
372 open_braces: Vec::new(),
373 owns_directory: true,
374 root_module_name: None,
375 expected_tokens: Vec::new(),
379 /// Convert a token to a string using self's reader
380 pub fn token_to_string(token: &token::Token) -> String {
381 pprust::token_to_string(token)
384 /// Convert the current token to a string using self's reader
385 pub fn this_token_to_string(&mut self) -> String {
386 Parser::token_to_string(&self.token)
389 pub fn unexpected_last(&mut self, t: &token::Token) -> ! {
390 let token_str = Parser::token_to_string(t);
391 let last_span = self.last_span;
392 self.span_fatal(last_span, &format!("unexpected token: `{}`",
396 pub fn unexpected(&mut self) -> ! {
397 let this_token = self.this_token_to_string();
398 self.fatal(&format!("unexpected token: `{}`", this_token)[]);
401 /// Expect and consume the token t. Signal an error if
402 /// the next token is not t.
403 pub fn expect(&mut self, t: &token::Token) {
404 if self.expected_tokens.is_empty() {
405 if self.token == *t {
408 let token_str = Parser::token_to_string(t);
409 let this_token_str = self.this_token_to_string();
410 self.fatal(&format!("expected `{}`, found `{}`",
415 self.expect_one_of(slice::ref_slice(t), &[]);
419 /// Expect next token to be edible or inedible token. If edible,
420 /// then consume it; if inedible, then return without consuming
421 /// anything. Signal a fatal error if next token is unexpected.
422 pub fn expect_one_of(&mut self,
423 edible: &[token::Token],
424 inedible: &[token::Token]) {
425 fn tokens_to_string(tokens: &[TokenType]) -> String {
426 let mut i = tokens.iter();
427 // This might be a sign we need a connect method on Iterator.
429 .map_or("".to_string(), |t| t.to_string());
430 i.enumerate().fold(b, |mut b, (i, ref a)| {
431 if tokens.len() > 2 && i == tokens.len() - 2 {
433 } else if tokens.len() == 2 && i == tokens.len() - 2 {
438 b.push_str(&*a.to_string());
442 if edible.contains(&self.token) {
444 } else if inedible.contains(&self.token) {
445 // leave it in the input
447 let mut expected = edible.iter().map(|x| TokenType::Token(x.clone()))
448 .collect::<Vec<_>>();
449 expected.extend(inedible.iter().map(|x| TokenType::Token(x.clone())));
450 expected.push_all(&*self.expected_tokens);
451 expected.sort_by(|a, b| a.to_string().cmp(&b.to_string()));
453 let expect = tokens_to_string(&expected[]);
454 let actual = self.this_token_to_string();
456 &(if expected.len() != 1 {
457 (format!("expected one of {}, found `{}`",
461 (format!("expected {}, found `{}`",
469 /// Check for erroneous `ident { }`; if matches, signal error and
470 /// recover (without consuming any expected input token). Returns
471 /// true if and only if input was consumed for recovery.
472 pub fn check_for_erroneous_unit_struct_expecting(&mut self, expected: &[token::Token]) -> bool {
473 if self.token == token::OpenDelim(token::Brace)
474 && expected.iter().all(|t| *t != token::OpenDelim(token::Brace))
475 && self.look_ahead(1, |t| *t == token::CloseDelim(token::Brace)) {
476 // matched; signal non-fatal error and recover.
477 let span = self.span;
479 "unit-like struct construction is written with no trailing `{ }`");
480 self.eat(&token::OpenDelim(token::Brace));
481 self.eat(&token::CloseDelim(token::Brace));
488 /// Commit to parsing a complete expression `e` expected to be
489 /// followed by some token from the set edible + inedible. Recover
490 /// from anticipated input errors, discarding erroneous characters.
491 pub fn commit_expr(&mut self, e: &Expr, edible: &[token::Token], inedible: &[token::Token]) {
492 debug!("commit_expr {:?}", e);
493 if let ExprPath(..) = e.node {
494 // might be unit-struct construction; check for recoverableinput error.
495 let mut expected = edible.iter().map(|x| x.clone()).collect::<Vec<_>>();
496 expected.push_all(inedible);
497 self.check_for_erroneous_unit_struct_expecting(&expected[]);
499 self.expect_one_of(edible, inedible)
502 pub fn commit_expr_expecting(&mut self, e: &Expr, edible: token::Token) {
503 self.commit_expr(e, &[edible], &[])
506 /// Commit to parsing a complete statement `s`, which expects to be
507 /// followed by some token from the set edible + inedible. Check
508 /// for recoverable input errors, discarding erroneous characters.
509 pub fn commit_stmt(&mut self, edible: &[token::Token], inedible: &[token::Token]) {
512 .map_or(false, |t| t.is_ident() || t.is_path()) {
513 let mut expected = edible.iter().map(|x| x.clone()).collect::<Vec<_>>();
514 expected.push_all(&inedible[]);
515 self.check_for_erroneous_unit_struct_expecting(
518 self.expect_one_of(edible, inedible)
521 pub fn commit_stmt_expecting(&mut self, edible: token::Token) {
522 self.commit_stmt(&[edible], &[])
525 pub fn parse_ident(&mut self) -> ast::Ident {
526 self.check_strict_keywords();
527 self.check_reserved_keywords();
529 token::Ident(i, _) => {
533 token::Interpolated(token::NtIdent(..)) => {
534 self.bug("ident interpolation not converted to real token");
537 let token_str = self.this_token_to_string();
538 self.fatal(&format!("expected ident, found `{}`",
544 pub fn parse_path_list_item(&mut self) -> ast::PathListItem {
545 let lo = self.span.lo;
546 let node = if self.eat_keyword(keywords::Mod) {
547 let span = self.last_span;
548 self.span_warn(span, "deprecated syntax; use the `self` keyword now");
549 ast::PathListMod { id: ast::DUMMY_NODE_ID }
550 } else if self.eat_keyword(keywords::Self) {
551 ast::PathListMod { id: ast::DUMMY_NODE_ID }
553 let ident = self.parse_ident();
554 ast::PathListIdent { name: ident, id: ast::DUMMY_NODE_ID }
556 let hi = self.last_span.hi;
557 spanned(lo, hi, node)
560 /// Check if the next token is `tok`, and return `true` if so.
562 /// This method is will automatically add `tok` to `expected_tokens` if `tok` is not
564 pub fn check(&mut self, tok: &token::Token) -> bool {
565 let is_present = self.token == *tok;
566 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
570 /// Consume token 'tok' if it exists. Returns true if the given
571 /// token was present, false otherwise.
572 pub fn eat(&mut self, tok: &token::Token) -> bool {
573 let is_present = self.check(tok);
574 if is_present { self.bump() }
578 /// If the next token is the given keyword, eat it and return
579 /// true. Otherwise, return false.
580 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
581 if self.token.is_keyword(kw) {
589 /// If the given word is not a keyword, signal an error.
590 /// If the next token is not the given word, signal an error.
591 /// Otherwise, eat it.
592 pub fn expect_keyword(&mut self, kw: keywords::Keyword) {
593 if !self.eat_keyword(kw) {
594 let id_interned_str = token::get_name(kw.to_name());
595 let token_str = self.this_token_to_string();
596 self.fatal(&format!("expected `{}`, found `{}`",
597 id_interned_str, token_str)[])
601 /// Signal an error if the given string is a strict keyword
602 pub fn check_strict_keywords(&mut self) {
603 if self.token.is_strict_keyword() {
604 let token_str = self.this_token_to_string();
605 let span = self.span;
607 &format!("expected identifier, found keyword `{}`",
612 /// Signal an error if the current token is a reserved keyword
613 pub fn check_reserved_keywords(&mut self) {
614 if self.token.is_reserved_keyword() {
615 let token_str = self.this_token_to_string();
616 self.fatal(&format!("`{}` is a reserved keyword",
621 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
622 /// `&` and continue. If an `&` is not seen, signal an error.
623 fn expect_and(&mut self) {
625 token::BinOp(token::And) => self.bump(),
627 let span = self.span;
628 let lo = span.lo + BytePos(1);
629 self.replace_token(token::BinOp(token::And), lo, span.hi)
632 let token_str = self.this_token_to_string();
634 Parser::token_to_string(&token::BinOp(token::And));
635 self.fatal(&format!("expected `{}`, found `{}`",
642 /// Expect and consume a `|`. If `||` is seen, replace it with a single
643 /// `|` and continue. If a `|` is not seen, signal an error.
644 fn expect_or(&mut self) {
646 token::BinOp(token::Or) => self.bump(),
648 let span = self.span;
649 let lo = span.lo + BytePos(1);
650 self.replace_token(token::BinOp(token::Or), lo, span.hi)
653 let found_token = self.this_token_to_string();
655 Parser::token_to_string(&token::BinOp(token::Or));
656 self.fatal(&format!("expected `{}`, found `{}`",
663 pub fn expect_no_suffix(&mut self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
665 None => {/* everything ok */}
667 let text = suf.as_str();
669 self.span_bug(sp, "found empty literal suffix in Some")
671 self.span_err(sp, &*format!("{} with a suffix is illegal", kind));
677 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
678 /// `<` and continue. If a `<` is not seen, return false.
680 /// This is meant to be used when parsing generics on a path to get the
682 fn eat_lt(&mut self) -> bool {
684 token::Lt => { self.bump(); true }
685 token::BinOp(token::Shl) => {
686 let span = self.span;
687 let lo = span.lo + BytePos(1);
688 self.replace_token(token::Lt, lo, span.hi);
695 fn expect_lt(&mut self) {
697 let found_token = self.this_token_to_string();
698 let token_str = Parser::token_to_string(&token::Lt);
699 self.fatal(&format!("expected `{}`, found `{}`",
705 /// Parse a sequence bracketed by `|` and `|`, stopping before the `|`.
706 fn parse_seq_to_before_or<T, F>(&mut self,
710 F: FnMut(&mut Parser) -> T,
712 let mut first = true;
713 let mut vector = Vec::new();
714 while self.token != token::BinOp(token::Or) &&
715 self.token != token::OrOr {
727 /// Expect and consume a GT. if a >> is seen, replace it
728 /// with a single > and continue. If a GT is not seen,
730 pub fn expect_gt(&mut self) {
732 token::Gt => self.bump(),
733 token::BinOp(token::Shr) => {
734 let span = self.span;
735 let lo = span.lo + BytePos(1);
736 self.replace_token(token::Gt, lo, span.hi)
738 token::BinOpEq(token::Shr) => {
739 let span = self.span;
740 let lo = span.lo + BytePos(1);
741 self.replace_token(token::Ge, lo, span.hi)
744 let span = self.span;
745 let lo = span.lo + BytePos(1);
746 self.replace_token(token::Eq, lo, span.hi)
749 let gt_str = Parser::token_to_string(&token::Gt);
750 let this_token_str = self.this_token_to_string();
751 self.fatal(&format!("expected `{}`, found `{}`",
758 pub fn parse_seq_to_before_gt_or_return<T, F>(&mut self,
759 sep: Option<token::Token>,
761 -> (OwnedSlice<T>, bool) where
762 F: FnMut(&mut Parser) -> Option<T>,
764 let mut v = Vec::new();
765 // This loop works by alternating back and forth between parsing types
766 // and commas. For example, given a string `A, B,>`, the parser would
767 // first parse `A`, then a comma, then `B`, then a comma. After that it
768 // would encounter a `>` and stop. This lets the parser handle trailing
769 // commas in generic parameters, because it can stop either after
770 // parsing a type or after parsing a comma.
771 for i in iter::count(0u, 1) {
772 if self.check(&token::Gt)
773 || self.token == token::BinOp(token::Shr)
774 || self.token == token::Ge
775 || self.token == token::BinOpEq(token::Shr) {
781 Some(result) => v.push(result),
782 None => return (OwnedSlice::from_vec(v), true)
785 sep.as_ref().map(|t| self.expect(t));
788 return (OwnedSlice::from_vec(v), false);
791 /// Parse a sequence bracketed by '<' and '>', stopping
793 pub fn parse_seq_to_before_gt<T, F>(&mut self,
794 sep: Option<token::Token>,
796 -> OwnedSlice<T> where
797 F: FnMut(&mut Parser) -> T,
799 let (result, returned) = self.parse_seq_to_before_gt_or_return(sep, |p| Some(f(p)));
804 pub fn parse_seq_to_gt<T, F>(&mut self,
805 sep: Option<token::Token>,
807 -> OwnedSlice<T> where
808 F: FnMut(&mut Parser) -> T,
810 let v = self.parse_seq_to_before_gt(sep, f);
815 pub fn parse_seq_to_gt_or_return<T, F>(&mut self,
816 sep: Option<token::Token>,
818 -> (OwnedSlice<T>, bool) where
819 F: FnMut(&mut Parser) -> Option<T>,
821 let (v, returned) = self.parse_seq_to_before_gt_or_return(sep, f);
825 return (v, returned);
828 /// Parse a sequence, including the closing delimiter. The function
829 /// f must consume tokens until reaching the next separator or
831 pub fn parse_seq_to_end<T, F>(&mut self,
836 F: FnMut(&mut Parser) -> T,
838 let val = self.parse_seq_to_before_end(ket, sep, f);
843 /// Parse a sequence, not including the closing delimiter. The function
844 /// f must consume tokens until reaching the next separator or
846 pub fn parse_seq_to_before_end<T, F>(&mut self,
851 F: FnMut(&mut Parser) -> T,
853 let mut first: bool = true;
855 while self.token != *ket {
858 if first { first = false; }
859 else { self.expect(t); }
863 if sep.trailing_sep_allowed && self.check(ket) { break; }
869 /// Parse a sequence, including the closing delimiter. The function
870 /// f must consume tokens until reaching the next separator or
872 pub fn parse_unspanned_seq<T, F>(&mut self,
878 F: FnMut(&mut Parser) -> T,
881 let result = self.parse_seq_to_before_end(ket, sep, f);
886 /// Parse a sequence parameter of enum variant. For consistency purposes,
887 /// these should not be empty.
888 pub fn parse_enum_variant_seq<T, F>(&mut self,
894 F: FnMut(&mut Parser) -> T,
896 let result = self.parse_unspanned_seq(bra, ket, sep, f);
897 if result.is_empty() {
898 let last_span = self.last_span;
899 self.span_err(last_span,
900 "nullary enum variants are written with no trailing `( )`");
905 // NB: Do not use this function unless you actually plan to place the
906 // spanned list in the AST.
907 pub fn parse_seq<T, F>(&mut self,
912 -> Spanned<Vec<T>> where
913 F: FnMut(&mut Parser) -> T,
915 let lo = self.span.lo;
917 let result = self.parse_seq_to_before_end(ket, sep, f);
918 let hi = self.span.hi;
920 spanned(lo, hi, result)
923 /// Advance the parser by one token
924 pub fn bump(&mut self) {
925 self.last_span = self.span;
926 // Stash token for error recovery (sometimes; clone is not necessarily cheap).
927 self.last_token = if self.token.is_ident() || self.token.is_path() {
928 Some(box self.token.clone())
932 let next = if self.buffer_start == self.buffer_end {
933 self.reader.real_token()
935 // Avoid token copies with `replace`.
936 let buffer_start = self.buffer_start as uint;
937 let next_index = (buffer_start + 1) & 3 as uint;
938 self.buffer_start = next_index as int;
940 let placeholder = TokenAndSpan {
941 tok: token::Underscore,
944 mem::replace(&mut self.buffer[buffer_start], placeholder)
947 self.token = next.tok;
948 self.tokens_consumed += 1u;
949 self.expected_tokens.clear();
950 // check after each token
951 self.check_unknown_macro_variable();
954 /// Advance the parser by one token and return the bumped token.
955 pub fn bump_and_get(&mut self) -> token::Token {
956 let old_token = mem::replace(&mut self.token, token::Underscore);
961 /// EFFECT: replace the current token and span with the given one
962 pub fn replace_token(&mut self,
966 self.last_span = mk_sp(self.span.lo, lo);
968 self.span = mk_sp(lo, hi);
970 pub fn buffer_length(&mut self) -> int {
971 if self.buffer_start <= self.buffer_end {
972 return self.buffer_end - self.buffer_start;
974 return (4 - self.buffer_start) + self.buffer_end;
976 pub fn look_ahead<R, F>(&mut self, distance: uint, f: F) -> R where
977 F: FnOnce(&token::Token) -> R,
979 let dist = distance as int;
980 while self.buffer_length() < dist {
981 self.buffer[self.buffer_end as uint] = self.reader.real_token();
982 self.buffer_end = (self.buffer_end + 1) & 3;
984 f(&self.buffer[((self.buffer_start + dist - 1) & 3) as uint].tok)
986 pub fn fatal(&mut self, m: &str) -> ! {
987 self.sess.span_diagnostic.span_fatal(self.span, m)
989 pub fn span_fatal(&mut self, sp: Span, m: &str) -> ! {
990 self.sess.span_diagnostic.span_fatal(sp, m)
992 pub fn span_fatal_help(&mut self, sp: Span, m: &str, help: &str) -> ! {
993 self.span_err(sp, m);
994 self.span_help(sp, help);
995 panic!(diagnostic::FatalError);
997 pub fn span_note(&mut self, sp: Span, m: &str) {
998 self.sess.span_diagnostic.span_note(sp, m)
1000 pub fn span_help(&mut self, sp: Span, m: &str) {
1001 self.sess.span_diagnostic.span_help(sp, m)
1003 pub fn bug(&mut self, m: &str) -> ! {
1004 self.sess.span_diagnostic.span_bug(self.span, m)
1006 pub fn warn(&mut self, m: &str) {
1007 self.sess.span_diagnostic.span_warn(self.span, m)
1009 pub fn span_warn(&mut self, sp: Span, m: &str) {
1010 self.sess.span_diagnostic.span_warn(sp, m)
1012 pub fn span_err(&mut self, sp: Span, m: &str) {
1013 self.sess.span_diagnostic.span_err(sp, m)
1015 pub fn span_bug(&mut self, sp: Span, m: &str) -> ! {
1016 self.sess.span_diagnostic.span_bug(sp, m)
1018 pub fn abort_if_errors(&mut self) {
1019 self.sess.span_diagnostic.handler().abort_if_errors();
1022 pub fn id_to_interned_str(&mut self, id: Ident) -> InternedString {
1023 token::get_ident(id)
1026 /// Is the current token one of the keywords that signals a bare function
1028 pub fn token_is_bare_fn_keyword(&mut self) -> bool {
1029 self.token.is_keyword(keywords::Fn) ||
1030 self.token.is_keyword(keywords::Unsafe) ||
1031 self.token.is_keyword(keywords::Extern)
1034 /// Is the current token one of the keywords that signals a closure type?
1035 pub fn token_is_closure_keyword(&mut self) -> bool {
1036 self.token.is_keyword(keywords::Unsafe)
1039 pub fn get_lifetime(&mut self) -> ast::Ident {
1041 token::Lifetime(ref ident) => *ident,
1042 _ => self.bug("not a lifetime"),
1046 pub fn parse_for_in_type(&mut self) -> Ty_ {
1048 Parses whatever can come after a `for` keyword in a type.
1049 The `for` has already been consumed.
1053 - for <'lt> |S| -> T
1057 - for <'lt> [unsafe] [extern "ABI"] fn (S) -> T
1058 - for <'lt> path::foo(a, b)
1063 let lifetime_defs = self.parse_late_bound_lifetime_defs();
1065 // examine next token to decide to do
1066 if self.eat_keyword(keywords::Proc) {
1067 self.parse_proc_type(lifetime_defs)
1068 } else if self.token_is_bare_fn_keyword() || self.token_is_closure_keyword() {
1069 self.parse_ty_bare_fn_or_ty_closure(lifetime_defs)
1070 } else if self.check(&token::ModSep) ||
1071 self.token.is_ident() ||
1072 self.token.is_path()
1074 let trait_ref = self.parse_trait_ref();
1075 let poly_trait_ref = ast::PolyTraitRef { bound_lifetimes: lifetime_defs,
1076 trait_ref: trait_ref };
1077 let other_bounds = if self.eat(&token::BinOp(token::Plus)) {
1078 self.parse_ty_param_bounds(BoundParsingMode::Bare)
1083 Some(TraitTyParamBound(poly_trait_ref, TraitBoundModifier::None)).into_iter()
1084 .chain(other_bounds.into_vec().into_iter())
1086 ast::TyPolyTraitRef(all_bounds)
1088 self.parse_ty_closure(lifetime_defs)
1092 pub fn parse_ty_path(&mut self) -> Ty_ {
1093 let path = self.parse_path(LifetimeAndTypesWithoutColons);
1094 TyPath(path, ast::DUMMY_NODE_ID)
1097 /// parse a TyBareFn type:
1098 pub fn parse_ty_bare_fn(&mut self, lifetime_defs: Vec<ast::LifetimeDef>) -> Ty_ {
1101 [unsafe] [extern "ABI"] fn <'lt> (S) -> T
1102 ^~~~^ ^~~~^ ^~~~^ ^~^ ^
1105 | | | Argument types
1111 let unsafety = self.parse_unsafety();
1112 let abi = if self.eat_keyword(keywords::Extern) {
1113 self.parse_opt_abi().unwrap_or(abi::C)
1118 self.expect_keyword(keywords::Fn);
1119 let lifetime_defs = self.parse_legacy_lifetime_defs(lifetime_defs);
1120 let (inputs, variadic) = self.parse_fn_args(false, true);
1121 let ret_ty = self.parse_ret_ty();
1122 let decl = P(FnDecl {
1127 TyBareFn(P(BareFnTy {
1130 lifetimes: lifetime_defs,
1135 /// Parses a procedure type (`proc`). The initial `proc` keyword must
1136 /// already have been parsed.
1137 pub fn parse_proc_type(&mut self, lifetime_defs: Vec<ast::LifetimeDef>) -> Ty_ {
1140 proc <'lt> (S) [:Bounds] -> T
1141 ^~~^ ^~~~^ ^ ^~~~~~~~^ ^
1147 the `proc` keyword (already consumed)
1151 let proc_span = self.last_span;
1153 // To be helpful, parse the proc as ever
1154 let _ = self.parse_legacy_lifetime_defs(lifetime_defs);
1155 let _ = self.parse_fn_args(false, false);
1156 let _ = self.parse_colon_then_ty_param_bounds(BoundParsingMode::Bare);
1157 let _ = self.parse_ret_ty();
1159 self.obsolete(proc_span, ObsoleteSyntax::ProcType);
1164 /// Parses an optional unboxed closure kind (`&:`, `&mut:`, or `:`).
1165 pub fn parse_optional_unboxed_closure_kind(&mut self)
1166 -> Option<UnboxedClosureKind> {
1167 if self.check(&token::BinOp(token::And)) &&
1168 self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
1169 self.look_ahead(2, |t| *t == token::Colon) {
1173 return Some(FnMutUnboxedClosureKind)
1176 if self.token == token::BinOp(token::And) &&
1177 self.look_ahead(1, |t| *t == token::Colon) {
1180 return Some(FnUnboxedClosureKind)
1183 if self.eat(&token::Colon) {
1184 return Some(FnOnceUnboxedClosureKind)
1190 pub fn parse_ty_bare_fn_or_ty_closure(&mut self, lifetime_defs: Vec<LifetimeDef>) -> Ty_ {
1191 // Both bare fns and closures can begin with stuff like unsafe
1192 // and extern. So we just scan ahead a few tokens to see if we see
1195 // Closure: [unsafe] <'lt> |S| [:Bounds] -> T
1196 // Fn: [unsafe] [extern "ABI"] fn <'lt> (S) -> T
1198 if self.token.is_keyword(keywords::Fn) {
1199 self.parse_ty_bare_fn(lifetime_defs)
1200 } else if self.token.is_keyword(keywords::Extern) {
1201 self.parse_ty_bare_fn(lifetime_defs)
1202 } else if self.token.is_keyword(keywords::Unsafe) {
1203 if self.look_ahead(1, |t| t.is_keyword(keywords::Fn) ||
1204 t.is_keyword(keywords::Extern)) {
1205 self.parse_ty_bare_fn(lifetime_defs)
1207 self.parse_ty_closure(lifetime_defs)
1210 self.parse_ty_closure(lifetime_defs)
1214 /// Parse a TyClosure type
1215 pub fn parse_ty_closure(&mut self, lifetime_defs: Vec<ast::LifetimeDef>) -> Ty_ {
1218 [unsafe] <'lt> |S| [:Bounds] -> T
1219 ^~~~~~~^ ^~~~^ ^ ^~~~~~~~^ ^
1222 | | | Closure bounds
1224 | Deprecated lifetime defs
1230 let ty_closure_span = self.last_span;
1232 // To be helpful, parse the closure type as ever
1233 let _ = self.parse_unsafety();
1235 let _ = self.parse_legacy_lifetime_defs(lifetime_defs);
1237 if !self.eat(&token::OrOr) {
1240 let _ = self.parse_seq_to_before_or(
1242 |p| p.parse_arg_general(false));
1246 let _ = self.parse_colon_then_ty_param_bounds(BoundParsingMode::Bare);
1248 let _ = self.parse_ret_ty();
1250 self.obsolete(ty_closure_span, ObsoleteSyntax::ClosureType);
1255 pub fn parse_unsafety(&mut self) -> Unsafety {
1256 if self.eat_keyword(keywords::Unsafe) {
1257 return Unsafety::Unsafe;
1259 return Unsafety::Normal;
1263 /// Parses `[ 'for' '<' lifetime_defs '>' ]'
1264 fn parse_legacy_lifetime_defs(&mut self,
1265 lifetime_defs: Vec<ast::LifetimeDef>)
1266 -> Vec<ast::LifetimeDef>
1268 if self.token == token::Lt {
1270 if lifetime_defs.is_empty() {
1271 self.warn("deprecated syntax; use the `for` keyword now \
1272 (e.g. change `fn<'a>` to `for<'a> fn`)");
1273 let lifetime_defs = self.parse_lifetime_defs();
1277 self.fatal("cannot use new `for` keyword and older syntax together");
1284 /// Parses `type Foo;` in a trait declaration only. The `type` keyword has
1285 /// already been parsed.
1286 fn parse_associated_type(&mut self, attrs: Vec<Attribute>)
1289 let ty_param = self.parse_ty_param();
1290 self.expect(&token::Semi);
1297 /// Parses `type Foo = TYPE;` in an implementation declaration only. The
1298 /// `type` keyword has already been parsed.
1299 fn parse_typedef(&mut self, attrs: Vec<Attribute>, vis: Visibility)
1301 let lo = self.span.lo;
1302 let ident = self.parse_ident();
1303 self.expect(&token::Eq);
1304 let typ = self.parse_ty_sum();
1305 let hi = self.span.hi;
1306 self.expect(&token::Semi);
1308 id: ast::DUMMY_NODE_ID,
1309 span: mk_sp(lo, hi),
1317 /// Parse the items in a trait declaration
1318 pub fn parse_trait_items(&mut self) -> Vec<TraitItem> {
1319 self.parse_unspanned_seq(
1320 &token::OpenDelim(token::Brace),
1321 &token::CloseDelim(token::Brace),
1324 let attrs = p.parse_outer_attributes();
1326 if p.eat_keyword(keywords::Type) {
1327 TypeTraitItem(P(p.parse_associated_type(attrs)))
1331 let vis = p.parse_visibility();
1332 let style = p.parse_unsafety();
1333 let abi = if p.eat_keyword(keywords::Extern) {
1334 p.parse_opt_abi().unwrap_or(abi::C)
1338 p.expect_keyword(keywords::Fn);
1340 let ident = p.parse_ident();
1341 let mut generics = p.parse_generics();
1343 let (explicit_self, d) = p.parse_fn_decl_with_self(|p| {
1344 // This is somewhat dubious; We don't want to allow
1345 // argument names to be left off if there is a
1347 p.parse_arg_general(false)
1350 p.parse_where_clause(&mut generics);
1352 let hi = p.last_span.hi;
1356 debug!("parse_trait_methods(): parsing required method");
1357 RequiredMethod(TypeMethod {
1364 explicit_self: explicit_self,
1365 id: ast::DUMMY_NODE_ID,
1366 span: mk_sp(lo, hi),
1370 token::OpenDelim(token::Brace) => {
1371 debug!("parse_trait_methods(): parsing provided method");
1372 let (inner_attrs, body) =
1373 p.parse_inner_attrs_and_block();
1374 let mut attrs = attrs;
1375 attrs.push_all(&inner_attrs[]);
1376 ProvidedMethod(P(ast::Method {
1378 id: ast::DUMMY_NODE_ID,
1379 span: mk_sp(lo, hi),
1380 node: ast::MethDecl(ident,
1392 let token_str = p.this_token_to_string();
1393 p.fatal(&format!("expected `;` or `{{`, found `{}`",
1401 /// Parse a possibly mutable type
1402 pub fn parse_mt(&mut self) -> MutTy {
1403 let mutbl = self.parse_mutability();
1404 let t = self.parse_ty();
1405 MutTy { ty: t, mutbl: mutbl }
1408 /// Parse optional return type [ -> TY ] in function decl
1409 pub fn parse_ret_ty(&mut self) -> FunctionRetTy {
1410 if self.eat(&token::RArrow) {
1411 if self.eat(&token::Not) {
1414 let t = self.parse_ty();
1416 // We used to allow `fn foo() -> &T + U`, but don't
1417 // anymore. If we see it, report a useful error. This
1418 // only makes sense because `parse_ret_ty` is only
1419 // used in fn *declarations*, not fn types or where
1420 // clauses (i.e., not when parsing something like
1421 // `FnMut() -> T + Send`, where the `+` is legal).
1422 if self.token == token::BinOp(token::Plus) {
1423 self.warn("deprecated syntax: `()` are required, see RFC 438 for details");
1429 let pos = self.span.lo;
1430 DefaultReturn(mk_sp(pos, pos))
1434 /// Parse a type in a context where `T1+T2` is allowed.
1435 pub fn parse_ty_sum(&mut self) -> P<Ty> {
1436 let lo = self.span.lo;
1437 let lhs = self.parse_ty();
1439 if !self.eat(&token::BinOp(token::Plus)) {
1443 let bounds = self.parse_ty_param_bounds(BoundParsingMode::Bare);
1445 // In type grammar, `+` is treated like a binary operator,
1446 // and hence both L and R side are required.
1447 if bounds.len() == 0 {
1448 let last_span = self.last_span;
1449 self.span_err(last_span,
1450 "at least one type parameter bound \
1451 must be specified");
1454 let sp = mk_sp(lo, self.last_span.hi);
1455 let sum = ast::TyObjectSum(lhs, bounds);
1456 P(Ty {id: ast::DUMMY_NODE_ID, node: sum, span: sp})
1460 pub fn parse_ty(&mut self) -> P<Ty> {
1461 maybe_whole!(no_clone self, NtTy);
1463 let lo = self.span.lo;
1465 let t = if self.check(&token::OpenDelim(token::Paren)) {
1468 // (t) is a parenthesized ty
1469 // (t,) is the type of a tuple with only one field,
1471 let mut ts = vec![];
1472 let mut last_comma = false;
1473 while self.token != token::CloseDelim(token::Paren) {
1474 ts.push(self.parse_ty_sum());
1475 if self.check(&token::Comma) {
1484 self.expect(&token::CloseDelim(token::Paren));
1485 if ts.len() == 1 && !last_comma {
1486 TyParen(ts.into_iter().nth(0).unwrap())
1490 } else if self.check(&token::BinOp(token::Star)) {
1491 // STAR POINTER (bare pointer?)
1493 TyPtr(self.parse_ptr())
1494 } else if self.check(&token::OpenDelim(token::Bracket)) {
1496 self.expect(&token::OpenDelim(token::Bracket));
1497 let t = self.parse_ty_sum();
1499 // Parse the `; e` in `[ int; e ]`
1500 // where `e` is a const expression
1501 let t = match self.maybe_parse_fixed_length_of_vec() {
1503 Some(suffix) => TyFixedLengthVec(t, suffix)
1505 self.expect(&token::CloseDelim(token::Bracket));
1507 } else if self.check(&token::BinOp(token::And)) ||
1508 self.token == token::AndAnd {
1511 self.parse_borrowed_pointee()
1512 } else if self.token.is_keyword(keywords::For) {
1513 self.parse_for_in_type()
1514 } else if self.token_is_bare_fn_keyword() ||
1515 self.token_is_closure_keyword() {
1516 // BARE FUNCTION OR CLOSURE
1517 self.parse_ty_bare_fn_or_ty_closure(Vec::new())
1518 } else if self.check(&token::BinOp(token::Or)) ||
1519 self.token == token::OrOr ||
1520 (self.token == token::Lt &&
1521 self.look_ahead(1, |t| {
1522 *t == token::Gt || t.is_lifetime()
1525 self.parse_ty_closure(Vec::new())
1526 } else if self.eat_keyword(keywords::Typeof) {
1528 // In order to not be ambiguous, the type must be surrounded by parens.
1529 self.expect(&token::OpenDelim(token::Paren));
1530 let e = self.parse_expr();
1531 self.expect(&token::CloseDelim(token::Paren));
1533 } else if self.eat_keyword(keywords::Proc) {
1534 self.parse_proc_type(Vec::new())
1535 } else if self.eat_lt() {
1536 // QUALIFIED PATH `<TYPE as TRAIT_REF>::item`
1537 let self_type = self.parse_ty_sum();
1538 self.expect_keyword(keywords::As);
1539 let trait_ref = self.parse_trait_ref();
1540 self.expect(&token::Gt);
1541 self.expect(&token::ModSep);
1542 let item_name = self.parse_ident();
1544 self_type: self_type,
1545 trait_ref: P(trait_ref),
1546 item_path: ast::PathSegment {
1547 identifier: item_name,
1548 parameters: ast::PathParameters::none()
1551 } else if self.check(&token::ModSep) ||
1552 self.token.is_ident() ||
1553 self.token.is_path() {
1555 self.parse_ty_path()
1556 } else if self.eat(&token::Underscore) {
1557 // TYPE TO BE INFERRED
1560 let this_token_str = self.this_token_to_string();
1561 let msg = format!("expected type, found `{}`", this_token_str);
1565 let sp = mk_sp(lo, self.last_span.hi);
1566 P(Ty {id: ast::DUMMY_NODE_ID, node: t, span: sp})
1569 pub fn parse_borrowed_pointee(&mut self) -> Ty_ {
1570 // look for `&'lt` or `&'foo ` and interpret `foo` as the region name:
1571 let opt_lifetime = self.parse_opt_lifetime();
1573 let mt = self.parse_mt();
1574 return TyRptr(opt_lifetime, mt);
1577 pub fn parse_ptr(&mut self) -> MutTy {
1578 let mutbl = if self.eat_keyword(keywords::Mut) {
1580 } else if self.eat_keyword(keywords::Const) {
1583 let span = self.last_span;
1585 "bare raw pointers are no longer allowed, you should \
1586 likely use `*mut T`, but otherwise `*T` is now \
1587 known as `*const T`");
1590 let t = self.parse_ty();
1591 MutTy { ty: t, mutbl: mutbl }
1594 pub fn is_named_argument(&mut self) -> bool {
1595 let offset = match self.token {
1596 token::BinOp(token::And) => 1,
1598 _ if self.token.is_keyword(keywords::Mut) => 1,
1602 debug!("parser is_named_argument offset:{}", offset);
1605 is_plain_ident_or_underscore(&self.token)
1606 && self.look_ahead(1, |t| *t == token::Colon)
1608 self.look_ahead(offset, |t| is_plain_ident_or_underscore(t))
1609 && self.look_ahead(offset + 1, |t| *t == token::Colon)
1613 /// This version of parse arg doesn't necessarily require
1614 /// identifier names.
1615 pub fn parse_arg_general(&mut self, require_name: bool) -> Arg {
1616 let pat = if require_name || self.is_named_argument() {
1617 debug!("parse_arg_general parse_pat (require_name:{})",
1619 let pat = self.parse_pat();
1621 self.expect(&token::Colon);
1624 debug!("parse_arg_general ident_to_pat");
1625 ast_util::ident_to_pat(ast::DUMMY_NODE_ID,
1627 special_idents::invalid)
1630 let t = self.parse_ty_sum();
1635 id: ast::DUMMY_NODE_ID,
1639 /// Parse a single function argument
1640 pub fn parse_arg(&mut self) -> Arg {
1641 self.parse_arg_general(true)
1644 /// Parse an argument in a lambda header e.g. |arg, arg|
1645 pub fn parse_fn_block_arg(&mut self) -> Arg {
1646 let pat = self.parse_pat();
1647 let t = if self.eat(&token::Colon) {
1651 id: ast::DUMMY_NODE_ID,
1653 span: mk_sp(self.span.lo, self.span.hi),
1659 id: ast::DUMMY_NODE_ID
1663 pub fn maybe_parse_fixed_length_of_vec(&mut self) -> Option<P<ast::Expr>> {
1664 if self.check(&token::Semi) {
1666 Some(self.parse_expr())
1672 /// Matches token_lit = LIT_INTEGER | ...
1673 pub fn lit_from_token(&mut self, tok: &token::Token) -> Lit_ {
1675 token::Interpolated(token::NtExpr(ref v)) => {
1677 ExprLit(ref lit) => { lit.node.clone() }
1678 _ => { self.unexpected_last(tok); }
1681 token::Literal(lit, suf) => {
1682 let (suffix_illegal, out) = match lit {
1683 token::Byte(i) => (true, LitByte(parse::byte_lit(i.as_str()).0)),
1684 token::Char(i) => (true, LitChar(parse::char_lit(i.as_str()).0)),
1686 // there are some valid suffixes for integer and
1687 // float literals, so all the handling is done
1689 token::Integer(s) => {
1690 (false, parse::integer_lit(s.as_str(),
1691 suf.as_ref().map(|s| s.as_str()),
1692 &self.sess.span_diagnostic,
1695 token::Float(s) => {
1696 (false, parse::float_lit(s.as_str(),
1697 suf.as_ref().map(|s| s.as_str()),
1698 &self.sess.span_diagnostic,
1704 LitStr(token::intern_and_get_ident(parse::str_lit(s.as_str()).as_slice()),
1707 token::StrRaw(s, n) => {
1710 token::intern_and_get_ident(&parse::raw_str_lit(s.as_str())[]),
1714 (true, LitBinary(parse::binary_lit(i.as_str()))),
1715 token::BinaryRaw(i, _) =>
1717 LitBinary(Rc::new(i.as_str().as_bytes().iter().map(|&x| x).collect()))),
1721 let sp = self.last_span;
1722 self.expect_no_suffix(sp, &*format!("{} literal", lit.short_name()), suf)
1727 _ => { self.unexpected_last(tok); }
1731 /// Matches lit = true | false | token_lit
1732 pub fn parse_lit(&mut self) -> Lit {
1733 let lo = self.span.lo;
1734 let lit = if self.eat_keyword(keywords::True) {
1736 } else if self.eat_keyword(keywords::False) {
1739 let token = self.bump_and_get();
1740 let lit = self.lit_from_token(&token);
1743 codemap::Spanned { node: lit, span: mk_sp(lo, self.last_span.hi) }
1746 /// matches '-' lit | lit
1747 pub fn parse_literal_maybe_minus(&mut self) -> P<Expr> {
1748 let minus_lo = self.span.lo;
1749 let minus_present = self.eat(&token::BinOp(token::Minus));
1751 let lo = self.span.lo;
1752 let literal = P(self.parse_lit());
1753 let hi = self.span.hi;
1754 let expr = self.mk_expr(lo, hi, ExprLit(literal));
1757 let minus_hi = self.span.hi;
1758 let unary = self.mk_unary(UnNeg, expr);
1759 self.mk_expr(minus_lo, minus_hi, unary)
1765 /// Parses a path and optional type parameter bounds, depending on the
1766 /// mode. The `mode` parameter determines whether lifetimes, types, and/or
1767 /// bounds are permitted and whether `::` must precede type parameter
1769 pub fn parse_path(&mut self, mode: PathParsingMode) -> ast::Path {
1770 // Check for a whole path...
1771 let found = match self.token {
1772 token::Interpolated(token::NtPath(_)) => Some(self.bump_and_get()),
1775 if let Some(token::Interpolated(token::NtPath(box path))) = found {
1779 let lo = self.span.lo;
1780 let is_global = self.eat(&token::ModSep);
1782 // Parse any number of segments and bound sets. A segment is an
1783 // identifier followed by an optional lifetime and a set of types.
1784 // A bound set is a set of type parameter bounds.
1785 let segments = match mode {
1786 LifetimeAndTypesWithoutColons => {
1787 self.parse_path_segments_without_colons()
1789 LifetimeAndTypesWithColons => {
1790 self.parse_path_segments_with_colons()
1793 self.parse_path_segments_without_types()
1797 // Assemble the span.
1798 let span = mk_sp(lo, self.last_span.hi);
1800 // Assemble the result.
1809 /// - `a::b<T,U>::c<V,W>`
1810 /// - `a::b<T,U>::c(V) -> W`
1811 /// - `a::b<T,U>::c(V)`
1812 pub fn parse_path_segments_without_colons(&mut self) -> Vec<ast::PathSegment> {
1813 let mut segments = Vec::new();
1815 // First, parse an identifier.
1816 let identifier = self.parse_ident();
1818 // Parse types, optionally.
1819 let parameters = if self.eat_lt() {
1820 let (lifetimes, types, bindings) = self.parse_generic_values_after_lt();
1822 ast::AngleBracketedParameters(ast::AngleBracketedParameterData {
1823 lifetimes: lifetimes,
1824 types: OwnedSlice::from_vec(types),
1825 bindings: OwnedSlice::from_vec(bindings),
1827 } else if self.eat(&token::OpenDelim(token::Paren)) {
1828 let inputs = self.parse_seq_to_end(
1829 &token::CloseDelim(token::Paren),
1830 seq_sep_trailing_allowed(token::Comma),
1831 |p| p.parse_ty_sum());
1833 let output_ty = if self.eat(&token::RArrow) {
1834 Some(self.parse_ty())
1839 ast::ParenthesizedParameters(ast::ParenthesizedParameterData {
1844 ast::PathParameters::none()
1847 // Assemble and push the result.
1848 segments.push(ast::PathSegment { identifier: identifier,
1849 parameters: parameters });
1851 // Continue only if we see a `::`
1852 if !self.eat(&token::ModSep) {
1859 /// - `a::b::<T,U>::c`
1860 pub fn parse_path_segments_with_colons(&mut self) -> Vec<ast::PathSegment> {
1861 let mut segments = Vec::new();
1863 // First, parse an identifier.
1864 let identifier = self.parse_ident();
1866 // If we do not see a `::`, stop.
1867 if !self.eat(&token::ModSep) {
1868 segments.push(ast::PathSegment {
1869 identifier: identifier,
1870 parameters: ast::PathParameters::none()
1875 // Check for a type segment.
1877 // Consumed `a::b::<`, go look for types
1878 let (lifetimes, types, bindings) = self.parse_generic_values_after_lt();
1879 segments.push(ast::PathSegment {
1880 identifier: identifier,
1881 parameters: ast::AngleBracketedParameters(ast::AngleBracketedParameterData {
1882 lifetimes: lifetimes,
1883 types: OwnedSlice::from_vec(types),
1884 bindings: OwnedSlice::from_vec(bindings),
1888 // Consumed `a::b::<T,U>`, check for `::` before proceeding
1889 if !self.eat(&token::ModSep) {
1893 // Consumed `a::`, go look for `b`
1894 segments.push(ast::PathSegment {
1895 identifier: identifier,
1896 parameters: ast::PathParameters::none(),
1905 pub fn parse_path_segments_without_types(&mut self) -> Vec<ast::PathSegment> {
1906 let mut segments = Vec::new();
1908 // First, parse an identifier.
1909 let identifier = self.parse_ident();
1911 // Assemble and push the result.
1912 segments.push(ast::PathSegment {
1913 identifier: identifier,
1914 parameters: ast::PathParameters::none()
1917 // If we do not see a `::`, stop.
1918 if !self.eat(&token::ModSep) {
1924 /// parses 0 or 1 lifetime
1925 pub fn parse_opt_lifetime(&mut self) -> Option<ast::Lifetime> {
1927 token::Lifetime(..) => {
1928 Some(self.parse_lifetime())
1936 /// Parses a single lifetime
1937 /// Matches lifetime = LIFETIME
1938 pub fn parse_lifetime(&mut self) -> ast::Lifetime {
1940 token::Lifetime(i) => {
1941 let span = self.span;
1943 return ast::Lifetime {
1944 id: ast::DUMMY_NODE_ID,
1950 self.fatal(&format!("expected a lifetime name")[]);
1955 /// Parses `lifetime_defs = [ lifetime_defs { ',' lifetime_defs } ]` where `lifetime_def =
1956 /// lifetime [':' lifetimes]`
1957 pub fn parse_lifetime_defs(&mut self) -> Vec<ast::LifetimeDef> {
1959 let mut res = Vec::new();
1962 token::Lifetime(_) => {
1963 let lifetime = self.parse_lifetime();
1965 if self.eat(&token::Colon) {
1966 self.parse_lifetimes(token::BinOp(token::Plus))
1970 res.push(ast::LifetimeDef { lifetime: lifetime,
1980 token::Comma => { self.bump(); }
1981 token::Gt => { return res; }
1982 token::BinOp(token::Shr) => { return res; }
1984 let this_token_str = self.this_token_to_string();
1985 let msg = format!("expected `,` or `>` after lifetime \
1994 /// matches lifetimes = ( lifetime ) | ( lifetime , lifetimes ) actually, it matches the empty
1995 /// one too, but putting that in there messes up the grammar....
1997 /// Parses zero or more comma separated lifetimes. Expects each lifetime to be followed by
1998 /// either a comma or `>`. Used when parsing type parameter lists, where we expect something
1999 /// like `<'a, 'b, T>`.
2000 pub fn parse_lifetimes(&mut self, sep: token::Token) -> Vec<ast::Lifetime> {
2002 let mut res = Vec::new();
2005 token::Lifetime(_) => {
2006 res.push(self.parse_lifetime());
2013 if self.token != sep {
2021 /// Parse mutability declaration (mut/const/imm)
2022 pub fn parse_mutability(&mut self) -> Mutability {
2023 if self.eat_keyword(keywords::Mut) {
2030 /// Parse ident COLON expr
2031 pub fn parse_field(&mut self) -> Field {
2032 let lo = self.span.lo;
2033 let i = self.parse_ident();
2034 let hi = self.last_span.hi;
2035 self.expect(&token::Colon);
2036 let e = self.parse_expr();
2038 ident: spanned(lo, hi, i),
2039 span: mk_sp(lo, e.span.hi),
2044 pub fn mk_expr(&mut self, lo: BytePos, hi: BytePos, node: Expr_) -> P<Expr> {
2046 id: ast::DUMMY_NODE_ID,
2048 span: mk_sp(lo, hi),
2052 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::Expr_ {
2053 ExprUnary(unop, expr)
2056 pub fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::Expr_ {
2057 ExprBinary(binop, lhs, rhs)
2060 pub fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::Expr_ {
2064 fn mk_method_call(&mut self,
2065 ident: ast::SpannedIdent,
2069 ExprMethodCall(ident, tps, args)
2072 pub fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::Expr_ {
2073 ExprIndex(expr, idx)
2076 pub fn mk_range(&mut self,
2077 start: Option<P<Expr>>,
2078 end: Option<P<Expr>>)
2080 ExprRange(start, end)
2083 pub fn mk_field(&mut self, expr: P<Expr>, ident: ast::SpannedIdent) -> ast::Expr_ {
2084 ExprField(expr, ident)
2087 pub fn mk_tup_field(&mut self, expr: P<Expr>, idx: codemap::Spanned<uint>) -> ast::Expr_ {
2088 ExprTupField(expr, idx)
2091 pub fn mk_assign_op(&mut self, binop: ast::BinOp,
2092 lhs: P<Expr>, rhs: P<Expr>) -> ast::Expr_ {
2093 ExprAssignOp(binop, lhs, rhs)
2096 pub fn mk_mac_expr(&mut self, lo: BytePos, hi: BytePos, m: Mac_) -> P<Expr> {
2098 id: ast::DUMMY_NODE_ID,
2099 node: ExprMac(codemap::Spanned {node: m, span: mk_sp(lo, hi)}),
2100 span: mk_sp(lo, hi),
2104 pub fn mk_lit_u32(&mut self, i: u32) -> P<Expr> {
2105 let span = &self.span;
2106 let lv_lit = P(codemap::Spanned {
2107 node: LitInt(i as u64, ast::UnsignedIntLit(TyU32)),
2112 id: ast::DUMMY_NODE_ID,
2113 node: ExprLit(lv_lit),
2118 fn expect_open_delim(&mut self) -> token::DelimToken {
2120 token::OpenDelim(delim) => {
2124 _ => self.fatal("expected open delimiter"),
2128 /// At the bottom (top?) of the precedence hierarchy,
2129 /// parse things like parenthesized exprs,
2130 /// macros, return, etc.
2131 pub fn parse_bottom_expr(&mut self) -> P<Expr> {
2132 maybe_whole_expr!(self);
2134 let lo = self.span.lo;
2135 let mut hi = self.span.hi;
2139 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2141 token::OpenDelim(token::Paren) => {
2144 // (e) is parenthesized e
2145 // (e,) is a tuple with only one field, e
2146 let mut es = vec![];
2147 let mut trailing_comma = false;
2148 while self.token != token::CloseDelim(token::Paren) {
2149 es.push(self.parse_expr());
2150 self.commit_expr(&**es.last().unwrap(), &[],
2151 &[token::Comma, token::CloseDelim(token::Paren)]);
2152 if self.check(&token::Comma) {
2153 trailing_comma = true;
2157 trailing_comma = false;
2164 return if es.len() == 1 && !trailing_comma {
2165 self.mk_expr(lo, hi, ExprParen(es.into_iter().nth(0).unwrap()))
2167 self.mk_expr(lo, hi, ExprTup(es))
2170 token::OpenDelim(token::Brace) => {
2172 let blk = self.parse_block_tail(lo, DefaultBlock);
2173 return self.mk_expr(blk.span.lo, blk.span.hi,
2176 token::BinOp(token::Or) | token::OrOr => {
2177 return self.parse_lambda_expr(CaptureByRef);
2179 // FIXME #13626: Should be able to stick in
2180 // token::SELF_KEYWORD_NAME
2181 token::Ident(id @ ast::Ident {
2182 name: ast::Name(token::SELF_KEYWORD_NAME_NUM),
2184 }, token::Plain) => {
2186 let path = ast_util::ident_to_path(mk_sp(lo, hi), id);
2187 ex = ExprPath(path);
2188 hi = self.last_span.hi;
2190 token::OpenDelim(token::Bracket) => {
2193 if self.check(&token::CloseDelim(token::Bracket)) {
2196 ex = ExprVec(Vec::new());
2199 let first_expr = self.parse_expr();
2200 if self.check(&token::Semi) {
2201 // Repeating vector syntax: [ 0; 512 ]
2203 let count = self.parse_expr();
2204 self.expect(&token::CloseDelim(token::Bracket));
2205 ex = ExprRepeat(first_expr, count);
2206 } else if self.check(&token::Comma) {
2207 // Vector with two or more elements.
2209 let remaining_exprs = self.parse_seq_to_end(
2210 &token::CloseDelim(token::Bracket),
2211 seq_sep_trailing_allowed(token::Comma),
2214 let mut exprs = vec!(first_expr);
2215 exprs.extend(remaining_exprs.into_iter());
2216 ex = ExprVec(exprs);
2218 // Vector with one element.
2219 self.expect(&token::CloseDelim(token::Bracket));
2220 ex = ExprVec(vec!(first_expr));
2223 hi = self.last_span.hi;
2227 // QUALIFIED PATH `<TYPE as TRAIT_REF>::item::<'a, T>`
2228 let self_type = self.parse_ty_sum();
2229 self.expect_keyword(keywords::As);
2230 let trait_ref = self.parse_trait_ref();
2231 self.expect(&token::Gt);
2232 self.expect(&token::ModSep);
2233 let item_name = self.parse_ident();
2234 let parameters = if self.eat(&token::ModSep) {
2236 // Consumed `item::<`, go look for types
2237 let (lifetimes, types, bindings) =
2238 self.parse_generic_values_after_lt();
2239 ast::AngleBracketedParameters(ast::AngleBracketedParameterData {
2240 lifetimes: lifetimes,
2241 types: OwnedSlice::from_vec(types),
2242 bindings: OwnedSlice::from_vec(bindings),
2245 ast::PathParameters::none()
2247 let hi = self.span.hi;
2248 return self.mk_expr(lo, hi, ExprQPath(P(QPath {
2249 self_type: self_type,
2250 trait_ref: P(trait_ref),
2251 item_path: ast::PathSegment {
2252 identifier: item_name,
2253 parameters: parameters
2257 if self.eat_keyword(keywords::Move) {
2258 return self.parse_lambda_expr(CaptureByValue);
2260 if self.eat_keyword(keywords::Proc) {
2261 let span = self.last_span;
2262 let _ = self.parse_proc_decl();
2263 let _ = self.parse_expr();
2264 return self.obsolete_expr(span, ObsoleteSyntax::ProcExpr);
2266 if self.eat_keyword(keywords::If) {
2267 return self.parse_if_expr();
2269 if self.eat_keyword(keywords::For) {
2270 return self.parse_for_expr(None);
2272 if self.eat_keyword(keywords::While) {
2273 return self.parse_while_expr(None);
2275 if self.token.is_lifetime() {
2276 let lifetime = self.get_lifetime();
2278 self.expect(&token::Colon);
2279 if self.eat_keyword(keywords::While) {
2280 return self.parse_while_expr(Some(lifetime))
2282 if self.eat_keyword(keywords::For) {
2283 return self.parse_for_expr(Some(lifetime))
2285 if self.eat_keyword(keywords::Loop) {
2286 return self.parse_loop_expr(Some(lifetime))
2288 self.fatal("expected `while`, `for`, or `loop` after a label")
2290 if self.eat_keyword(keywords::Loop) {
2291 return self.parse_loop_expr(None);
2293 if self.eat_keyword(keywords::Continue) {
2294 let lo = self.span.lo;
2295 let ex = if self.token.is_lifetime() {
2296 let lifetime = self.get_lifetime();
2298 ExprAgain(Some(lifetime))
2302 let hi = self.span.hi;
2303 return self.mk_expr(lo, hi, ex);
2305 if self.eat_keyword(keywords::Match) {
2306 return self.parse_match_expr();
2308 if self.eat_keyword(keywords::Unsafe) {
2309 return self.parse_block_expr(
2311 UnsafeBlock(ast::UserProvided));
2313 if self.eat_keyword(keywords::Return) {
2314 // RETURN expression
2315 if self.token.can_begin_expr() {
2316 let e = self.parse_expr();
2318 ex = ExprRet(Some(e));
2322 } else if self.eat_keyword(keywords::Break) {
2324 if self.token.is_lifetime() {
2325 let lifetime = self.get_lifetime();
2327 ex = ExprBreak(Some(lifetime));
2329 ex = ExprBreak(None);
2332 } else if self.check(&token::ModSep) ||
2333 self.token.is_ident() &&
2334 !self.token.is_keyword(keywords::True) &&
2335 !self.token.is_keyword(keywords::False) {
2337 self.parse_path(LifetimeAndTypesWithColons);
2339 // `!`, as an operator, is prefix, so we know this isn't that
2340 if self.check(&token::Not) {
2341 // MACRO INVOCATION expression
2344 let delim = self.expect_open_delim();
2345 let tts = self.parse_seq_to_end(
2346 &token::CloseDelim(delim),
2348 |p| p.parse_token_tree());
2349 let hi = self.span.hi;
2351 return self.mk_mac_expr(lo,
2357 if self.check(&token::OpenDelim(token::Brace)) {
2358 // This is a struct literal, unless we're prohibited
2359 // from parsing struct literals here.
2360 if !self.restrictions.contains(RESTRICTION_NO_STRUCT_LITERAL) {
2361 // It's a struct literal.
2363 let mut fields = Vec::new();
2364 let mut base = None;
2366 while self.token != token::CloseDelim(token::Brace) {
2367 if self.eat(&token::DotDot) {
2368 base = Some(self.parse_expr());
2372 fields.push(self.parse_field());
2373 self.commit_expr(&*fields.last().unwrap().expr,
2375 &[token::CloseDelim(token::Brace)]);
2378 if fields.len() == 0 && base.is_none() {
2379 let last_span = self.last_span;
2380 self.span_err(last_span,
2381 "structure literal must either \
2382 have at least one field or use \
2383 functional structure update \
2388 self.expect(&token::CloseDelim(token::Brace));
2389 ex = ExprStruct(pth, fields, base);
2390 return self.mk_expr(lo, hi, ex);
2397 // other literal expression
2398 let lit = self.parse_lit();
2400 ex = ExprLit(P(lit));
2405 return self.mk_expr(lo, hi, ex);
2408 /// Parse a block or unsafe block
2409 pub fn parse_block_expr(&mut self, lo: BytePos, blk_mode: BlockCheckMode)
2411 self.expect(&token::OpenDelim(token::Brace));
2412 let blk = self.parse_block_tail(lo, blk_mode);
2413 return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk));
2416 /// parse a.b or a(13) or a[4] or just a
2417 pub fn parse_dot_or_call_expr(&mut self) -> P<Expr> {
2418 let b = self.parse_bottom_expr();
2419 self.parse_dot_or_call_expr_with(b)
2422 pub fn parse_dot_or_call_expr_with(&mut self, e0: P<Expr>) -> P<Expr> {
2428 if self.eat(&token::Dot) {
2430 token::Ident(i, _) => {
2431 let dot = self.last_span.hi;
2434 let (_, tys, bindings) = if self.eat(&token::ModSep) {
2436 self.parse_generic_values_after_lt()
2438 (Vec::new(), Vec::new(), Vec::new())
2441 if bindings.len() > 0 {
2442 let last_span = self.last_span;
2443 self.span_err(last_span, "type bindings are only permitted on trait paths");
2446 // expr.f() method call
2448 token::OpenDelim(token::Paren) => {
2449 let mut es = self.parse_unspanned_seq(
2450 &token::OpenDelim(token::Paren),
2451 &token::CloseDelim(token::Paren),
2452 seq_sep_trailing_allowed(token::Comma),
2455 hi = self.last_span.hi;
2458 let id = spanned(dot, hi, i);
2459 let nd = self.mk_method_call(id, tys, es);
2460 e = self.mk_expr(lo, hi, nd);
2463 if !tys.is_empty() {
2464 let last_span = self.last_span;
2465 self.span_err(last_span,
2466 "field expressions may not \
2467 have type parameters");
2470 let id = spanned(dot, hi, i);
2471 let field = self.mk_field(e, id);
2472 e = self.mk_expr(lo, hi, field);
2476 token::Literal(token::Integer(n), suf) => {
2479 // A tuple index may not have a suffix
2480 self.expect_no_suffix(sp, "tuple index", suf);
2482 let dot = self.last_span.hi;
2486 let index = n.as_str().parse::<uint>();
2489 let id = spanned(dot, hi, n);
2490 let field = self.mk_tup_field(e, id);
2491 e = self.mk_expr(lo, hi, field);
2494 let last_span = self.last_span;
2495 self.span_err(last_span, "invalid tuple or tuple struct index");
2499 token::Literal(token::Float(n), _suf) => {
2501 let last_span = self.last_span;
2502 let fstr = n.as_str();
2503 self.span_err(last_span,
2504 &format!("unexpected token: `{}`", n.as_str())[]);
2505 if fstr.chars().all(|x| "0123456789.".contains_char(x)) {
2506 let float = match fstr.parse::<f64>() {
2510 self.span_help(last_span,
2511 &format!("try parenthesizing the first index; e.g., `(foo.{}){}`",
2512 float.trunc() as uint,
2513 &float.fract().to_string()[1..])[]);
2515 self.abort_if_errors();
2518 _ => self.unexpected()
2522 if self.expr_is_complete(&*e) { break; }
2525 token::OpenDelim(token::Paren) => {
2526 let es = self.parse_unspanned_seq(
2527 &token::OpenDelim(token::Paren),
2528 &token::CloseDelim(token::Paren),
2529 seq_sep_trailing_allowed(token::Comma),
2532 hi = self.last_span.hi;
2534 let nd = self.mk_call(e, es);
2535 e = self.mk_expr(lo, hi, nd);
2539 // Could be either an index expression or a slicing expression.
2540 token::OpenDelim(token::Bracket) => {
2541 let bracket_pos = self.span.lo;
2544 let mut found_dotdot = false;
2545 if self.token == token::DotDot &&
2546 self.look_ahead(1, |t| t == &token::CloseDelim(token::Bracket)) {
2547 // Using expr[..], which is a mistake, should be expr[]
2550 found_dotdot = true;
2553 if found_dotdot || self.eat(&token::CloseDelim(token::Bracket)) {
2554 // No expression, expand to a FullRange
2555 // FIXME(#20516) It would be better to use a lang item or
2556 // something for FullRange.
2557 hi = self.last_span.hi;
2558 let range = ExprStruct(ident_to_path(mk_sp(lo, hi),
2559 token::special_idents::FullRange),
2562 let ix = self.mk_expr(bracket_pos, hi, range);
2563 let index = self.mk_index(e, ix);
2564 e = self.mk_expr(lo, hi, index)
2566 let ix = self.parse_expr();
2568 self.commit_expr_expecting(&*ix, token::CloseDelim(token::Bracket));
2569 let index = self.mk_index(e, ix);
2570 e = self.mk_expr(lo, hi, index)
2574 self.span_err(e.span, "incorrect slicing expression: `[..]`");
2575 self.span_note(e.span,
2576 "use `&expr[]` to construct a slice of the whole of expr");
2585 // Parse unquoted tokens after a `$` in a token tree
2586 fn parse_unquoted(&mut self) -> TokenTree {
2587 let mut sp = self.span;
2588 let (name, namep) = match self.token {
2592 if self.token == token::OpenDelim(token::Paren) {
2593 let Spanned { node: seq, span: seq_span } = self.parse_seq(
2594 &token::OpenDelim(token::Paren),
2595 &token::CloseDelim(token::Paren),
2597 |p| p.parse_token_tree()
2599 let (sep, repeat) = self.parse_sep_and_kleene_op();
2600 let name_num = macro_parser::count_names(seq.as_slice());
2601 return TtSequence(mk_sp(sp.lo, seq_span.hi),
2602 Rc::new(SequenceRepetition {
2606 num_captures: name_num
2608 } else if self.token.is_keyword_allow_following_colon(keywords::Crate) {
2610 return TtToken(sp, SpecialVarNt(SpecialMacroVar::CrateMacroVar));
2612 sp = mk_sp(sp.lo, self.span.hi);
2613 let namep = match self.token { token::Ident(_, p) => p, _ => token::Plain };
2614 let name = self.parse_ident();
2618 token::SubstNt(name, namep) => {
2624 // continue by trying to parse the `:ident` after `$name`
2625 if self.token == token::Colon && self.look_ahead(1, |t| t.is_ident() &&
2626 !t.is_strict_keyword() &&
2627 !t.is_reserved_keyword()) {
2629 sp = mk_sp(sp.lo, self.span.hi);
2630 let kindp = match self.token { token::Ident(_, p) => p, _ => token::Plain };
2631 let nt_kind = self.parse_ident();
2632 TtToken(sp, MatchNt(name, nt_kind, namep, kindp))
2634 TtToken(sp, SubstNt(name, namep))
2638 pub fn check_unknown_macro_variable(&mut self) {
2639 if self.quote_depth == 0u {
2641 token::SubstNt(name, _) =>
2642 self.fatal(&format!("unknown macro variable `{}`",
2643 token::get_ident(name))[]),
2649 /// Parse an optional separator followed by a Kleene-style
2650 /// repetition token (+ or *).
2651 pub fn parse_sep_and_kleene_op(&mut self) -> (Option<token::Token>, ast::KleeneOp) {
2652 fn parse_kleene_op(parser: &mut Parser) -> Option<ast::KleeneOp> {
2653 match parser.token {
2654 token::BinOp(token::Star) => {
2656 Some(ast::ZeroOrMore)
2658 token::BinOp(token::Plus) => {
2660 Some(ast::OneOrMore)
2666 match parse_kleene_op(self) {
2667 Some(kleene_op) => return (None, kleene_op),
2671 let separator = self.bump_and_get();
2672 match parse_kleene_op(self) {
2673 Some(zerok) => (Some(separator), zerok),
2674 None => self.fatal("expected `*` or `+`")
2678 /// parse a single token tree from the input.
2679 pub fn parse_token_tree(&mut self) -> TokenTree {
2680 // FIXME #6994: currently, this is too eager. It
2681 // parses token trees but also identifies TtSequence's
2682 // and token::SubstNt's; it's too early to know yet
2683 // whether something will be a nonterminal or a seq
2685 maybe_whole!(deref self, NtTT);
2687 // this is the fall-through for the 'match' below.
2688 // invariants: the current token is not a left-delimiter,
2689 // not an EOF, and not the desired right-delimiter (if
2690 // it were, parse_seq_to_before_end would have prevented
2691 // reaching this point.
2692 fn parse_non_delim_tt_tok(p: &mut Parser) -> TokenTree {
2693 maybe_whole!(deref p, NtTT);
2695 token::CloseDelim(_) => {
2696 // This is a conservative error: only report the last unclosed delimiter. The
2697 // previous unclosed delimiters could actually be closed! The parser just hasn't
2698 // gotten to them yet.
2699 match p.open_braces.last() {
2701 Some(&sp) => p.span_note(sp, "unclosed delimiter"),
2703 let token_str = p.this_token_to_string();
2704 p.fatal(&format!("incorrect close delimiter: `{}`",
2707 /* we ought to allow different depths of unquotation */
2708 token::Dollar | token::SubstNt(..) if p.quote_depth > 0u => {
2712 TtToken(p.span, p.bump_and_get())
2719 let open_braces = self.open_braces.clone();
2720 for sp in open_braces.iter() {
2721 self.span_help(*sp, "did you mean to close this delimiter?");
2723 // There shouldn't really be a span, but it's easier for the test runner
2724 // if we give it one
2725 self.fatal("this file contains an un-closed delimiter ");
2727 token::OpenDelim(delim) => {
2728 // The span for beginning of the delimited section
2729 let pre_span = self.span;
2731 // Parse the open delimiter.
2732 self.open_braces.push(self.span);
2733 let open_span = self.span;
2736 // Parse the token trees within the delimiters
2737 let tts = self.parse_seq_to_before_end(
2738 &token::CloseDelim(delim),
2740 |p| p.parse_token_tree()
2743 // Parse the close delimiter.
2744 let close_span = self.span;
2746 self.open_braces.pop().unwrap();
2748 // Expand to cover the entire delimited token tree
2749 let span = Span { hi: self.span.hi, ..pre_span };
2751 TtDelimited(span, Rc::new(Delimited {
2753 open_span: open_span,
2755 close_span: close_span,
2758 _ => parse_non_delim_tt_tok(self),
2762 // parse a stream of tokens into a list of TokenTree's,
2764 pub fn parse_all_token_trees(&mut self) -> Vec<TokenTree> {
2765 let mut tts = Vec::new();
2766 while self.token != token::Eof {
2767 tts.push(self.parse_token_tree());
2772 /// Parse a prefix-operator expr
2773 pub fn parse_prefix_expr(&mut self) -> P<Expr> {
2774 let lo = self.span.lo;
2777 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2782 let e = self.parse_prefix_expr();
2784 ex = self.mk_unary(UnNot, e);
2786 token::BinOp(token::Minus) => {
2788 let e = self.parse_prefix_expr();
2790 ex = self.mk_unary(UnNeg, e);
2792 token::BinOp(token::Star) => {
2794 let e = self.parse_prefix_expr();
2796 ex = self.mk_unary(UnDeref, e);
2798 token::BinOp(token::And) | token::AndAnd => {
2800 let m = self.parse_mutability();
2801 let e = self.parse_prefix_expr();
2803 ex = ExprAddrOf(m, e);
2805 token::DotDot if !self.restrictions.contains(RESTRICTION_NO_DOTS) => {
2806 // A range, closed above: `..expr`.
2808 let e = self.parse_expr();
2810 ex = self.mk_range(None, Some(e));
2812 token::Ident(_, _) => {
2813 if !self.token.is_keyword(keywords::Box) {
2814 return self.parse_dot_or_call_expr();
2817 let lo = self.span.lo;
2821 // Check for a place: `box(PLACE) EXPR`.
2822 if self.eat(&token::OpenDelim(token::Paren)) {
2823 // Support `box() EXPR` as the default.
2824 if !self.eat(&token::CloseDelim(token::Paren)) {
2825 let place = self.parse_expr();
2826 self.expect(&token::CloseDelim(token::Paren));
2827 // Give a suggestion to use `box()` when a parenthesised expression is used
2828 if !self.token.can_begin_expr() {
2829 let span = self.span;
2830 let this_token_to_string = self.this_token_to_string();
2832 &format!("expected expression, found `{}`",
2833 this_token_to_string)[]);
2834 let box_span = mk_sp(lo, self.last_span.hi);
2835 self.span_help(box_span,
2836 "perhaps you meant `box() (foo)` instead?");
2837 self.abort_if_errors();
2839 let subexpression = self.parse_prefix_expr();
2840 hi = subexpression.span.hi;
2841 ex = ExprBox(Some(place), subexpression);
2842 return self.mk_expr(lo, hi, ex);
2846 // Otherwise, we use the unique pointer default.
2847 let subexpression = self.parse_prefix_expr();
2848 hi = subexpression.span.hi;
2849 // FIXME (pnkfelix): After working out kinks with box
2850 // desugaring, should be `ExprBox(None, subexpression)`
2852 ex = self.mk_unary(UnUniq, subexpression);
2854 _ => return self.parse_dot_or_call_expr()
2856 return self.mk_expr(lo, hi, ex);
2859 /// Parse an expression of binops
2860 pub fn parse_binops(&mut self) -> P<Expr> {
2861 let prefix_expr = self.parse_prefix_expr();
2862 self.parse_more_binops(prefix_expr, 0)
2865 /// Parse an expression of binops of at least min_prec precedence
2866 pub fn parse_more_binops(&mut self, lhs: P<Expr>, min_prec: uint) -> P<Expr> {
2867 if self.expr_is_complete(&*lhs) { return lhs; }
2869 // Prevent dynamic borrow errors later on by limiting the
2870 // scope of the borrows.
2871 if self.token == token::BinOp(token::Or) &&
2872 self.restrictions.contains(RESTRICTION_NO_BAR_OP) {
2876 self.expected_tokens.push(TokenType::Operator);
2878 let cur_opt = self.token.to_binop();
2881 if ast_util::is_comparison_binop(cur_op) {
2882 self.check_no_chained_comparison(&*lhs, cur_op)
2884 let cur_prec = operator_prec(cur_op);
2885 if cur_prec > min_prec {
2887 let expr = self.parse_prefix_expr();
2888 let rhs = self.parse_more_binops(expr, cur_prec);
2889 let lhs_span = lhs.span;
2890 let rhs_span = rhs.span;
2891 let binary = self.mk_binary(cur_op, lhs, rhs);
2892 let bin = self.mk_expr(lhs_span.lo, rhs_span.hi, binary);
2893 self.parse_more_binops(bin, min_prec)
2899 if as_prec > min_prec && self.eat_keyword(keywords::As) {
2900 let rhs = self.parse_ty();
2901 let _as = self.mk_expr(lhs.span.lo,
2903 ExprCast(lhs, rhs));
2904 self.parse_more_binops(_as, min_prec)
2912 /// Produce an error if comparison operators are chained (RFC #558).
2913 /// We only need to check lhs, not rhs, because all comparison ops
2914 /// have same precedence and are left-associative
2915 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: ast::BinOp) {
2916 debug_assert!(ast_util::is_comparison_binop(outer_op));
2918 ExprBinary(op, _, _) if ast_util::is_comparison_binop(op) => {
2919 let op_span = self.span;
2920 self.span_err(op_span,
2921 "Chained comparison operators require parentheses");
2922 if op == BiLt && outer_op == BiGt {
2923 self.span_help(op_span,
2924 "Use ::< instead of < if you meant to specify type arguments.");
2931 /// Parse an assignment expression....
2932 /// actually, this seems to be the main entry point for
2933 /// parsing an arbitrary expression.
2934 pub fn parse_assign_expr(&mut self) -> P<Expr> {
2935 let lhs = self.parse_binops();
2936 self.parse_assign_expr_with(lhs)
2939 pub fn parse_assign_expr_with(&mut self, lhs: P<Expr>) -> P<Expr> {
2940 let restrictions = self.restrictions & RESTRICTION_NO_STRUCT_LITERAL;
2944 let rhs = self.parse_expr_res(restrictions);
2945 self.mk_expr(lhs.span.lo, rhs.span.hi, ExprAssign(lhs, rhs))
2947 token::BinOpEq(op) => {
2949 let rhs = self.parse_expr_res(restrictions);
2950 let aop = match op {
2951 token::Plus => BiAdd,
2952 token::Minus => BiSub,
2953 token::Star => BiMul,
2954 token::Slash => BiDiv,
2955 token::Percent => BiRem,
2956 token::Caret => BiBitXor,
2957 token::And => BiBitAnd,
2958 token::Or => BiBitOr,
2959 token::Shl => BiShl,
2962 let rhs_span = rhs.span;
2963 let span = lhs.span;
2964 let assign_op = self.mk_assign_op(aop, lhs, rhs);
2965 self.mk_expr(span.lo, rhs_span.hi, assign_op)
2967 // A range expression, either `expr..expr` or `expr..`.
2968 token::DotDot if !self.restrictions.contains(RESTRICTION_NO_DOTS) => {
2971 let opt_end = if self.token.can_begin_expr() {
2972 let end = self.parse_expr_res(RESTRICTION_NO_DOTS);
2978 let lo = lhs.span.lo;
2979 let hi = self.span.hi;
2980 let range = self.mk_range(Some(lhs), opt_end);
2981 return self.mk_expr(lo, hi, range);
2990 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
2991 pub fn parse_if_expr(&mut self) -> P<Expr> {
2992 if self.token.is_keyword(keywords::Let) {
2993 return self.parse_if_let_expr();
2995 let lo = self.last_span.lo;
2996 let cond = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
2997 let thn = self.parse_block();
2998 let mut els: Option<P<Expr>> = None;
2999 let mut hi = thn.span.hi;
3000 if self.eat_keyword(keywords::Else) {
3001 let elexpr = self.parse_else_expr();
3002 hi = elexpr.span.hi;
3005 self.mk_expr(lo, hi, ExprIf(cond, thn, els))
3008 /// Parse an 'if let' expression ('if' token already eaten)
3009 pub fn parse_if_let_expr(&mut self) -> P<Expr> {
3010 let lo = self.last_span.lo;
3011 self.expect_keyword(keywords::Let);
3012 let pat = self.parse_pat();
3013 self.expect(&token::Eq);
3014 let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
3015 let thn = self.parse_block();
3016 let (hi, els) = if self.eat_keyword(keywords::Else) {
3017 let expr = self.parse_else_expr();
3018 (expr.span.hi, Some(expr))
3022 self.mk_expr(lo, hi, ExprIfLet(pat, expr, thn, els))
3026 pub fn parse_lambda_expr(&mut self, capture_clause: CaptureClause)
3029 let lo = self.span.lo;
3030 let (decl, optional_unboxed_closure_kind) =
3031 self.parse_fn_block_decl();
3032 let body = self.parse_expr();
3033 let fakeblock = P(ast::Block {
3034 id: ast::DUMMY_NODE_ID,
3035 view_items: Vec::new(),
3039 rules: DefaultBlock,
3045 ExprClosure(capture_clause, optional_unboxed_closure_kind, decl, fakeblock))
3048 pub fn parse_else_expr(&mut self) -> P<Expr> {
3049 if self.eat_keyword(keywords::If) {
3050 return self.parse_if_expr();
3052 let blk = self.parse_block();
3053 return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk));
3057 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3058 pub fn parse_for_expr(&mut self, opt_ident: Option<ast::Ident>) -> P<Expr> {
3059 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3061 let lo = self.last_span.lo;
3062 let pat = self.parse_pat();
3063 self.expect_keyword(keywords::In);
3064 let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
3065 let loop_block = self.parse_block();
3066 let hi = self.span.hi;
3068 self.mk_expr(lo, hi, ExprForLoop(pat, expr, loop_block, opt_ident))
3071 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3072 pub fn parse_while_expr(&mut self, opt_ident: Option<ast::Ident>) -> P<Expr> {
3073 if self.token.is_keyword(keywords::Let) {
3074 return self.parse_while_let_expr(opt_ident);
3076 let lo = self.last_span.lo;
3077 let cond = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
3078 let body = self.parse_block();
3079 let hi = body.span.hi;
3080 return self.mk_expr(lo, hi, ExprWhile(cond, body, opt_ident));
3083 /// Parse a 'while let' expression ('while' token already eaten)
3084 pub fn parse_while_let_expr(&mut self, opt_ident: Option<ast::Ident>) -> P<Expr> {
3085 let lo = self.last_span.lo;
3086 self.expect_keyword(keywords::Let);
3087 let pat = self.parse_pat();
3088 self.expect(&token::Eq);
3089 let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
3090 let body = self.parse_block();
3091 let hi = body.span.hi;
3092 return self.mk_expr(lo, hi, ExprWhileLet(pat, expr, body, opt_ident));
3095 pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::Ident>) -> P<Expr> {
3096 let lo = self.last_span.lo;
3097 let body = self.parse_block();
3098 let hi = body.span.hi;
3099 self.mk_expr(lo, hi, ExprLoop(body, opt_ident))
3102 fn parse_match_expr(&mut self) -> P<Expr> {
3103 let lo = self.last_span.lo;
3104 let discriminant = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
3105 self.commit_expr_expecting(&*discriminant, token::OpenDelim(token::Brace));
3106 let mut arms: Vec<Arm> = Vec::new();
3107 while self.token != token::CloseDelim(token::Brace) {
3108 arms.push(self.parse_arm());
3110 let hi = self.span.hi;
3112 return self.mk_expr(lo, hi, ExprMatch(discriminant, arms, MatchSource::Normal));
3115 pub fn parse_arm(&mut self) -> Arm {
3116 let attrs = self.parse_outer_attributes();
3117 let pats = self.parse_pats();
3118 let mut guard = None;
3119 if self.eat_keyword(keywords::If) {
3120 guard = Some(self.parse_expr());
3122 self.expect(&token::FatArrow);
3123 let expr = self.parse_expr_res(RESTRICTION_STMT_EXPR);
3126 !classify::expr_is_simple_block(&*expr)
3127 && self.token != token::CloseDelim(token::Brace);
3130 self.commit_expr(&*expr, &[token::Comma], &[token::CloseDelim(token::Brace)]);
3132 self.eat(&token::Comma);
3143 /// Parse an expression
3144 pub fn parse_expr(&mut self) -> P<Expr> {
3145 return self.parse_expr_res(UNRESTRICTED);
3148 /// Parse an expression, subject to the given restrictions
3149 pub fn parse_expr_res(&mut self, r: Restrictions) -> P<Expr> {
3150 let old = self.restrictions;
3151 self.restrictions = r;
3152 let e = self.parse_assign_expr();
3153 self.restrictions = old;
3157 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3158 fn parse_initializer(&mut self) -> Option<P<Expr>> {
3159 if self.check(&token::Eq) {
3161 Some(self.parse_expr())
3167 /// Parse patterns, separated by '|' s
3168 fn parse_pats(&mut self) -> Vec<P<Pat>> {
3169 let mut pats = Vec::new();
3171 pats.push(self.parse_pat());
3172 if self.check(&token::BinOp(token::Or)) { self.bump(); }
3173 else { return pats; }
3177 fn parse_pat_vec_elements(
3179 ) -> (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>) {
3180 let mut before = Vec::new();
3181 let mut slice = None;
3182 let mut after = Vec::new();
3183 let mut first = true;
3184 let mut before_slice = true;
3186 while self.token != token::CloseDelim(token::Bracket) {
3190 self.expect(&token::Comma);
3192 if self.token == token::CloseDelim(token::Bracket)
3193 && (before_slice || after.len() != 0) {
3199 if self.check(&token::DotDot) {
3202 if self.check(&token::Comma) ||
3203 self.check(&token::CloseDelim(token::Bracket)) {
3204 slice = Some(P(ast::Pat {
3205 id: ast::DUMMY_NODE_ID,
3206 node: PatWild(PatWildMulti),
3209 before_slice = false;
3215 let subpat = self.parse_pat();
3216 if before_slice && self.check(&token::DotDot) {
3218 slice = Some(subpat);
3219 before_slice = false;
3220 } else if before_slice {
3221 before.push(subpat);
3227 (before, slice, after)
3230 /// Parse the fields of a struct-like pattern
3231 fn parse_pat_fields(&mut self) -> (Vec<codemap::Spanned<ast::FieldPat>> , bool) {
3232 let mut fields = Vec::new();
3233 let mut etc = false;
3234 let mut first = true;
3235 while self.token != token::CloseDelim(token::Brace) {
3239 self.expect(&token::Comma);
3240 // accept trailing commas
3241 if self.check(&token::CloseDelim(token::Brace)) { break }
3244 let lo = self.span.lo;
3247 if self.check(&token::DotDot) {
3249 if self.token != token::CloseDelim(token::Brace) {
3250 let token_str = self.this_token_to_string();
3251 self.fatal(&format!("expected `{}`, found `{}`", "}",
3258 let bind_type = if self.eat_keyword(keywords::Mut) {
3259 BindByValue(MutMutable)
3260 } else if self.eat_keyword(keywords::Ref) {
3261 BindByRef(self.parse_mutability())
3263 BindByValue(MutImmutable)
3266 let fieldname = self.parse_ident();
3268 let (subpat, is_shorthand) = if self.check(&token::Colon) {
3270 BindByRef(..) | BindByValue(MutMutable) => {
3271 let token_str = self.this_token_to_string();
3272 self.fatal(&format!("unexpected `{}`",
3279 let pat = self.parse_pat();
3283 hi = self.last_span.hi;
3284 let fieldpath = codemap::Spanned{span:self.last_span, node: fieldname};
3286 id: ast::DUMMY_NODE_ID,
3287 node: PatIdent(bind_type, fieldpath, None),
3288 span: self.last_span
3291 fields.push(codemap::Spanned { span: mk_sp(lo, hi),
3292 node: ast::FieldPat { ident: fieldname,
3294 is_shorthand: is_shorthand }});
3296 return (fields, etc);
3299 /// Parse a pattern.
3300 pub fn parse_pat(&mut self) -> P<Pat> {
3301 maybe_whole!(self, NtPat);
3303 let lo = self.span.lo;
3308 token::Underscore => {
3310 pat = PatWild(PatWildSingle);
3311 hi = self.last_span.hi;
3313 id: ast::DUMMY_NODE_ID,
3318 token::BinOp(token::And) | token::AndAnd => {
3319 // parse &pat and &mut pat
3320 let lo = self.span.lo;
3322 let mutability = if self.eat_keyword(keywords::Mut) {
3327 let sub = self.parse_pat();
3328 pat = PatRegion(sub, mutability);
3329 hi = self.last_span.hi;
3331 id: ast::DUMMY_NODE_ID,
3336 token::OpenDelim(token::Paren) => {
3337 // parse (pat,pat,pat,...) as tuple
3339 if self.check(&token::CloseDelim(token::Paren)) {
3341 pat = PatTup(vec![]);
3343 let mut fields = vec!(self.parse_pat());
3344 if self.look_ahead(1, |t| *t != token::CloseDelim(token::Paren)) {
3345 while self.check(&token::Comma) {
3347 if self.check(&token::CloseDelim(token::Paren)) { break; }
3348 fields.push(self.parse_pat());
3351 if fields.len() == 1 { self.expect(&token::Comma); }
3352 self.expect(&token::CloseDelim(token::Paren));
3353 pat = PatTup(fields);
3355 hi = self.last_span.hi;
3357 id: ast::DUMMY_NODE_ID,
3362 token::OpenDelim(token::Bracket) => {
3363 // parse [pat,pat,...] as vector pattern
3365 let (before, slice, after) =
3366 self.parse_pat_vec_elements();
3368 self.expect(&token::CloseDelim(token::Bracket));
3369 pat = ast::PatVec(before, slice, after);
3370 hi = self.last_span.hi;
3372 id: ast::DUMMY_NODE_ID,
3379 // at this point, token != _, ~, &, &&, (, [
3381 if (!(self.token.is_ident() || self.token.is_path())
3382 && self.token != token::ModSep)
3383 || self.token.is_keyword(keywords::True)
3384 || self.token.is_keyword(keywords::False) {
3385 // Parse an expression pattern or exp .. exp.
3387 // These expressions are limited to literals (possibly
3388 // preceded by unary-minus) or identifiers.
3389 let val = self.parse_literal_maybe_minus();
3390 if (self.check(&token::DotDotDot)) &&
3391 self.look_ahead(1, |t| {
3392 *t != token::Comma && *t != token::CloseDelim(token::Bracket)
3395 let end = if self.token.is_ident() || self.token.is_path() {
3396 let path = self.parse_path(LifetimeAndTypesWithColons);
3397 let hi = self.span.hi;
3398 self.mk_expr(lo, hi, ExprPath(path))
3400 self.parse_literal_maybe_minus()
3402 pat = PatRange(val, end);
3406 } else if self.eat_keyword(keywords::Mut) {
3407 pat = self.parse_pat_ident(BindByValue(MutMutable));
3408 } else if self.eat_keyword(keywords::Ref) {
3410 let mutbl = self.parse_mutability();
3411 pat = self.parse_pat_ident(BindByRef(mutbl));
3412 } else if self.eat_keyword(keywords::Box) {
3415 // FIXME(#13910): Rename to `PatBox` and extend to full DST
3417 let sub = self.parse_pat();
3419 hi = self.last_span.hi;
3421 id: ast::DUMMY_NODE_ID,
3426 let can_be_enum_or_struct = self.look_ahead(1, |t| {
3428 token::OpenDelim(_) | token::Lt | token::ModSep => true,
3433 if self.look_ahead(1, |t| *t == token::DotDotDot) &&
3434 self.look_ahead(2, |t| {
3435 *t != token::Comma && *t != token::CloseDelim(token::Bracket)
3437 let start = self.parse_expr_res(RESTRICTION_NO_BAR_OP);
3438 self.eat(&token::DotDotDot);
3439 let end = self.parse_expr_res(RESTRICTION_NO_BAR_OP);
3440 pat = PatRange(start, end);
3441 } else if self.token.is_plain_ident() && !can_be_enum_or_struct {
3442 let id = self.parse_ident();
3443 let id_span = self.last_span;
3444 let pth1 = codemap::Spanned{span:id_span, node: id};
3445 if self.eat(&token::Not) {
3447 let delim = self.expect_open_delim();
3448 let tts = self.parse_seq_to_end(&token::CloseDelim(delim),
3450 |p| p.parse_token_tree());
3452 let mac = MacInvocTT(ident_to_path(id_span,id), tts, EMPTY_CTXT);
3453 pat = ast::PatMac(codemap::Spanned {node: mac, span: self.span});
3455 let sub = if self.eat(&token::At) {
3457 Some(self.parse_pat())
3462 pat = PatIdent(BindByValue(MutImmutable), pth1, sub);
3465 // parse an enum pat
3466 let enum_path = self.parse_path(LifetimeAndTypesWithColons);
3468 token::OpenDelim(token::Brace) => {
3471 self.parse_pat_fields();
3473 pat = PatStruct(enum_path, fields, etc);
3476 let mut args: Vec<P<Pat>> = Vec::new();
3478 token::OpenDelim(token::Paren) => {
3479 let is_dotdot = self.look_ahead(1, |t| {
3481 token::DotDot => true,
3486 // This is a "top constructor only" pat
3489 self.expect(&token::CloseDelim(token::Paren));
3490 pat = PatEnum(enum_path, None);
3492 args = self.parse_enum_variant_seq(
3493 &token::OpenDelim(token::Paren),
3494 &token::CloseDelim(token::Paren),
3495 seq_sep_trailing_allowed(token::Comma),
3498 pat = PatEnum(enum_path, Some(args));
3502 if !enum_path.global &&
3503 enum_path.segments.len() == 1 &&
3504 enum_path.segments[0].parameters.is_empty()
3506 // it could still be either an enum
3507 // or an identifier pattern, resolve
3508 // will sort it out:
3509 pat = PatIdent(BindByValue(MutImmutable),
3511 span: enum_path.span,
3512 node: enum_path.segments[0]
3516 pat = PatEnum(enum_path, Some(args));
3524 hi = self.last_span.hi;
3526 id: ast::DUMMY_NODE_ID,
3528 span: mk_sp(lo, hi),
3532 /// Parse ident or ident @ pat
3533 /// used by the copy foo and ref foo patterns to give a good
3534 /// error message when parsing mistakes like ref foo(a,b)
3535 fn parse_pat_ident(&mut self,
3536 binding_mode: ast::BindingMode)
3538 if !self.token.is_plain_ident() {
3539 let span = self.span;
3540 let tok_str = self.this_token_to_string();
3541 self.span_fatal(span,
3542 &format!("expected identifier, found `{}`", tok_str)[]);
3544 let ident = self.parse_ident();
3545 let last_span = self.last_span;
3546 let name = codemap::Spanned{span: last_span, node: ident};
3547 let sub = if self.eat(&token::At) {
3548 Some(self.parse_pat())
3553 // just to be friendly, if they write something like
3555 // we end up here with ( as the current token. This shortly
3556 // leads to a parse error. Note that if there is no explicit
3557 // binding mode then we do not end up here, because the lookahead
3558 // will direct us over to parse_enum_variant()
3559 if self.token == token::OpenDelim(token::Paren) {
3560 let last_span = self.last_span;
3563 "expected identifier, found enum pattern");
3566 PatIdent(binding_mode, name, sub)
3569 /// Parse a local variable declaration
3570 fn parse_local(&mut self) -> P<Local> {
3571 let lo = self.span.lo;
3572 let pat = self.parse_pat();
3575 if self.eat(&token::Colon) {
3576 ty = Some(self.parse_ty_sum());
3578 let init = self.parse_initializer();
3583 id: ast::DUMMY_NODE_ID,
3584 span: mk_sp(lo, self.last_span.hi),
3589 /// Parse a "let" stmt
3590 fn parse_let(&mut self) -> P<Decl> {
3591 let lo = self.span.lo;
3592 let local = self.parse_local();
3593 P(spanned(lo, self.last_span.hi, DeclLocal(local)))
3596 /// Parse a structure field
3597 fn parse_name_and_ty(&mut self, pr: Visibility,
3598 attrs: Vec<Attribute> ) -> StructField {
3599 let lo = self.span.lo;
3600 if !self.token.is_plain_ident() {
3601 self.fatal("expected ident");
3603 let name = self.parse_ident();
3604 self.expect(&token::Colon);
3605 let ty = self.parse_ty_sum();
3606 spanned(lo, self.last_span.hi, ast::StructField_ {
3607 kind: NamedField(name, pr),
3608 id: ast::DUMMY_NODE_ID,
3614 /// Get an expected item after attributes error message.
3615 fn expected_item_err(attrs: &[Attribute]) -> &'static str {
3616 match attrs.last() {
3617 Some(&Attribute { node: ast::Attribute_ { is_sugared_doc: true, .. }, .. }) => {
3618 "expected item after doc comment"
3620 _ => "expected item after attributes",
3624 /// Parse a statement. may include decl.
3625 /// Precondition: any attributes are parsed already
3626 pub fn parse_stmt(&mut self, item_attrs: Vec<Attribute>) -> P<Stmt> {
3627 maybe_whole!(self, NtStmt);
3629 fn check_expected_item(p: &mut Parser, attrs: &[Attribute]) {
3630 // If we have attributes then we should have an item
3631 if !attrs.is_empty() {
3632 let last_span = p.last_span;
3633 p.span_err(last_span, Parser::expected_item_err(attrs));
3637 let lo = self.span.lo;
3638 if self.token.is_keyword(keywords::Let) {
3639 check_expected_item(self, &item_attrs[]);
3640 self.expect_keyword(keywords::Let);
3641 let decl = self.parse_let();
3642 P(spanned(lo, decl.span.hi, StmtDecl(decl, ast::DUMMY_NODE_ID)))
3643 } else if self.token.is_ident()
3644 && !self.token.is_any_keyword()
3645 && self.look_ahead(1, |t| *t == token::Not) {
3646 // it's a macro invocation:
3648 check_expected_item(self, &item_attrs[]);
3650 // Potential trouble: if we allow macros with paths instead of
3651 // idents, we'd need to look ahead past the whole path here...
3652 let pth = self.parse_path(NoTypesAllowed);
3655 let id = match self.token {
3656 token::OpenDelim(_) => token::special_idents::invalid, // no special identifier
3657 _ => self.parse_ident(),
3660 // check that we're pointing at delimiters (need to check
3661 // again after the `if`, because of `parse_ident`
3662 // consuming more tokens).
3663 let delim = match self.token {
3664 token::OpenDelim(delim) => delim,
3666 // we only expect an ident if we didn't parse one
3668 let ident_str = if id.name == token::special_idents::invalid.name {
3673 let tok_str = self.this_token_to_string();
3674 self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
3680 let tts = self.parse_unspanned_seq(
3681 &token::OpenDelim(delim),
3682 &token::CloseDelim(delim),
3684 |p| p.parse_token_tree()
3686 let hi = self.span.hi;
3688 let style = if delim == token::Brace {
3691 MacStmtWithoutBraces
3694 if id.name == token::special_idents::invalid.name {
3697 StmtMac(P(spanned(lo,
3699 MacInvocTT(pth, tts, EMPTY_CTXT))),
3702 // if it has a special ident, it's definitely an item
3704 // Require a semicolon or braces.
3705 if style != MacStmtWithBraces {
3706 if !self.eat(&token::Semi) {
3707 let last_span = self.last_span;
3708 self.span_err(last_span,
3709 "macros that expand to items must \
3710 either be surrounded with braces or \
3711 followed by a semicolon");
3714 P(spanned(lo, hi, StmtDecl(
3715 P(spanned(lo, hi, DeclItem(
3717 lo, hi, id /*id is good here*/,
3718 ItemMac(spanned(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT))),
3719 Inherited, Vec::new(/*no attrs*/))))),
3720 ast::DUMMY_NODE_ID)))
3723 let found_attrs = !item_attrs.is_empty();
3724 let item_err = Parser::expected_item_err(&item_attrs[]);
3725 match self.parse_item_or_view_item(item_attrs, false) {
3728 let decl = P(spanned(lo, hi, DeclItem(i)));
3729 P(spanned(lo, hi, StmtDecl(decl, ast::DUMMY_NODE_ID)))
3731 IoviViewItem(vi) => {
3732 self.span_fatal(vi.span,
3733 "view items must be declared at the top of the block");
3735 IoviForeignItem(_) => {
3736 self.fatal("foreign items are not allowed here");
3740 let last_span = self.last_span;
3741 self.span_err(last_span, item_err);
3744 // Remainder are line-expr stmts.
3745 let e = self.parse_expr_res(RESTRICTION_STMT_EXPR);
3746 P(spanned(lo, e.span.hi, StmtExpr(e, ast::DUMMY_NODE_ID)))
3752 /// Is this expression a successfully-parsed statement?
3753 fn expr_is_complete(&mut self, e: &Expr) -> bool {
3754 self.restrictions.contains(RESTRICTION_STMT_EXPR) &&
3755 !classify::expr_requires_semi_to_be_stmt(e)
3758 /// Parse a block. No inner attrs are allowed.
3759 pub fn parse_block(&mut self) -> P<Block> {
3760 maybe_whole!(no_clone self, NtBlock);
3762 let lo = self.span.lo;
3764 if !self.eat(&token::OpenDelim(token::Brace)) {
3766 let tok = self.this_token_to_string();
3767 self.span_fatal_help(sp,
3768 &format!("expected `{{`, found `{}`", tok)[],
3769 "place this code inside a block");
3772 return self.parse_block_tail_(lo, DefaultBlock, Vec::new());
3775 /// Parse a block. Inner attrs are allowed.
3776 fn parse_inner_attrs_and_block(&mut self)
3777 -> (Vec<Attribute> , P<Block>) {
3779 maybe_whole!(pair_empty self, NtBlock);
3781 let lo = self.span.lo;
3782 self.expect(&token::OpenDelim(token::Brace));
3783 let (inner, next) = self.parse_inner_attrs_and_next();
3785 (inner, self.parse_block_tail_(lo, DefaultBlock, next))
3788 /// Precondition: already parsed the '{' or '#{'
3789 /// I guess that also means "already parsed the 'impure'" if
3790 /// necessary, and this should take a qualifier.
3791 /// Some blocks start with "#{"...
3792 fn parse_block_tail(&mut self, lo: BytePos, s: BlockCheckMode) -> P<Block> {
3793 self.parse_block_tail_(lo, s, Vec::new())
3796 /// Parse the rest of a block expression or function body
3797 fn parse_block_tail_(&mut self, lo: BytePos, s: BlockCheckMode,
3798 first_item_attrs: Vec<Attribute> ) -> P<Block> {
3799 let mut stmts = Vec::new();
3800 let mut expr = None;
3802 // wouldn't it be more uniform to parse view items only, here?
3803 let ParsedItemsAndViewItems {
3808 } = self.parse_items_and_view_items(first_item_attrs,
3811 for item in items.into_iter() {
3812 let span = item.span;
3813 let decl = P(spanned(span.lo, span.hi, DeclItem(item)));
3814 stmts.push(P(spanned(span.lo, span.hi, StmtDecl(decl, ast::DUMMY_NODE_ID))));
3817 let mut attributes_box = attrs_remaining;
3819 while self.token != token::CloseDelim(token::Brace) {
3820 // parsing items even when they're not allowed lets us give
3821 // better error messages and recover more gracefully.
3822 attributes_box.push_all(&self.parse_outer_attributes()[]);
3825 if !attributes_box.is_empty() {
3826 let last_span = self.last_span;
3827 self.span_err(last_span,
3828 Parser::expected_item_err(&attributes_box[]));
3829 attributes_box = Vec::new();
3831 self.bump(); // empty
3833 token::CloseDelim(token::Brace) => {
3834 // fall through and out.
3837 let stmt = self.parse_stmt(attributes_box);
3838 attributes_box = Vec::new();
3839 stmt.and_then(|Spanned {node, span}| match node {
3840 StmtExpr(e, stmt_id) => {
3841 self.handle_expression_like_statement(e,
3847 StmtMac(mac, MacStmtWithoutBraces) => {
3848 // statement macro without braces; might be an
3849 // expr depending on whether a semicolon follows
3852 stmts.push(P(Spanned {
3854 MacStmtWithSemicolon),
3860 let e = self.mk_mac_expr(span.lo,
3862 mac.and_then(|m| m.node));
3863 let e = self.parse_dot_or_call_expr_with(e);
3864 let e = self.parse_more_binops(e, 0);
3865 let e = self.parse_assign_expr_with(e);
3866 self.handle_expression_like_statement(
3875 StmtMac(m, style) => {
3876 // statement macro; might be an expr
3879 stmts.push(P(Spanned {
3881 MacStmtWithSemicolon),
3886 token::CloseDelim(token::Brace) => {
3887 // if a block ends in `m!(arg)` without
3888 // a `;`, it must be an expr
3890 self.mk_mac_expr(span.lo,
3892 m.and_then(|x| x.node)));
3895 stmts.push(P(Spanned {
3896 node: StmtMac(m, style),
3902 _ => { // all other kinds of statements:
3903 if classify::stmt_ends_with_semi(&node) {
3904 self.commit_stmt_expecting(token::Semi);
3907 stmts.push(P(Spanned {
3917 if !attributes_box.is_empty() {
3918 let last_span = self.last_span;
3919 self.span_err(last_span,
3920 Parser::expected_item_err(&attributes_box[]));
3923 let hi = self.span.hi;
3926 view_items: view_items,
3929 id: ast::DUMMY_NODE_ID,
3931 span: mk_sp(lo, hi),
3935 fn handle_expression_like_statement(
3940 stmts: &mut Vec<P<Stmt>>,
3941 last_block_expr: &mut Option<P<Expr>>) {
3942 // expression without semicolon
3943 if classify::expr_requires_semi_to_be_stmt(&*e) {
3944 // Just check for errors and recover; do not eat semicolon yet.
3945 self.commit_stmt(&[],
3946 &[token::Semi, token::CloseDelim(token::Brace)]);
3952 let span_with_semi = Span {
3954 hi: self.last_span.hi,
3955 expn_id: span.expn_id,
3957 stmts.push(P(Spanned {
3958 node: StmtSemi(e, stmt_id),
3959 span: span_with_semi,
3962 token::CloseDelim(token::Brace) => *last_block_expr = Some(e),
3964 stmts.push(P(Spanned {
3965 node: StmtExpr(e, stmt_id),
3972 // Parses a sequence of bounds if a `:` is found,
3973 // otherwise returns empty list.
3974 fn parse_colon_then_ty_param_bounds(&mut self,
3975 mode: BoundParsingMode)
3976 -> OwnedSlice<TyParamBound>
3978 if !self.eat(&token::Colon) {
3981 self.parse_ty_param_bounds(mode)
3985 // matches bounds = ( boundseq )?
3986 // where boundseq = ( polybound + boundseq ) | polybound
3987 // and polybound = ( 'for' '<' 'region '>' )? bound
3988 // and bound = 'region | trait_ref
3989 fn parse_ty_param_bounds(&mut self,
3990 mode: BoundParsingMode)
3991 -> OwnedSlice<TyParamBound>
3993 let mut result = vec!();
3995 let question_span = self.span;
3996 let ate_question = self.eat(&token::Question);
3998 token::Lifetime(lifetime) => {
4000 self.span_err(question_span,
4001 "`?` may only modify trait bounds, not lifetime bounds");
4003 result.push(RegionTyParamBound(ast::Lifetime {
4004 id: ast::DUMMY_NODE_ID,
4010 token::ModSep | token::Ident(..) => {
4011 let poly_trait_ref = self.parse_poly_trait_ref();
4012 let modifier = if ate_question {
4013 if mode == BoundParsingMode::Modified {
4014 TraitBoundModifier::Maybe
4016 self.span_err(question_span,
4018 TraitBoundModifier::None
4021 TraitBoundModifier::None
4023 result.push(TraitTyParamBound(poly_trait_ref, modifier))
4028 if !self.eat(&token::BinOp(token::Plus)) {
4033 return OwnedSlice::from_vec(result);
4036 fn trait_ref_from_ident(ident: Ident, span: Span) -> TraitRef {
4037 let segment = ast::PathSegment {
4039 parameters: ast::PathParameters::none()
4041 let path = ast::Path {
4044 segments: vec![segment],
4048 ref_id: ast::DUMMY_NODE_ID,
4052 /// Matches typaram = (unbound `?`)? IDENT (`?` unbound)? optbounds ( EQ ty )?
4053 fn parse_ty_param(&mut self) -> TyParam {
4054 // This is a bit hacky. Currently we are only interested in a single
4055 // unbound, and it may only be `Sized`. To avoid backtracking and other
4056 // complications, we parse an ident, then check for `?`. If we find it,
4057 // we use the ident as the unbound, otherwise, we use it as the name of
4058 // type param. Even worse, we need to check for `?` before or after the
4060 let mut span = self.span;
4061 let mut ident = self.parse_ident();
4062 let mut unbound = None;
4063 if self.eat(&token::Question) {
4064 let tref = Parser::trait_ref_from_ident(ident, span);
4065 unbound = Some(tref);
4067 ident = self.parse_ident();
4068 self.obsolete(span, ObsoleteSyntax::Sized);
4071 let mut bounds = self.parse_colon_then_ty_param_bounds(BoundParsingMode::Modified);
4072 if let Some(unbound) = unbound {
4073 let mut bounds_as_vec = bounds.into_vec();
4074 bounds_as_vec.push(TraitTyParamBound(PolyTraitRef { bound_lifetimes: vec![],
4075 trait_ref: unbound },
4076 TraitBoundModifier::Maybe));
4077 bounds = OwnedSlice::from_vec(bounds_as_vec);
4080 let default = if self.check(&token::Eq) {
4082 Some(self.parse_ty_sum())
4088 id: ast::DUMMY_NODE_ID,
4095 /// Parse a set of optional generic type parameter declarations. Where
4096 /// clauses are not parsed here, and must be added later via
4097 /// `parse_where_clause()`.
4099 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
4100 /// | ( < lifetimes , typaramseq ( , )? > )
4101 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
4102 pub fn parse_generics(&mut self) -> ast::Generics {
4103 if self.eat(&token::Lt) {
4104 let lifetime_defs = self.parse_lifetime_defs();
4105 let mut seen_default = false;
4106 let ty_params = self.parse_seq_to_gt(Some(token::Comma), |p| {
4107 p.forbid_lifetime();
4108 let ty_param = p.parse_ty_param();
4109 if ty_param.default.is_some() {
4110 seen_default = true;
4111 } else if seen_default {
4112 let last_span = p.last_span;
4113 p.span_err(last_span,
4114 "type parameters with a default must be trailing");
4119 lifetimes: lifetime_defs,
4120 ty_params: ty_params,
4121 where_clause: WhereClause {
4122 id: ast::DUMMY_NODE_ID,
4123 predicates: Vec::new(),
4127 ast_util::empty_generics()
4131 fn parse_generic_values_after_lt(&mut self)
4132 -> (Vec<ast::Lifetime>, Vec<P<Ty>>, Vec<P<TypeBinding>>) {
4133 let lifetimes = self.parse_lifetimes(token::Comma);
4135 // First parse types.
4136 let (types, returned) = self.parse_seq_to_gt_or_return(
4139 p.forbid_lifetime();
4140 if p.look_ahead(1, |t| t == &token::Eq) {
4143 Some(p.parse_ty_sum())
4148 // If we found the `>`, don't continue.
4150 return (lifetimes, types.into_vec(), Vec::new());
4153 // Then parse type bindings.
4154 let bindings = self.parse_seq_to_gt(
4157 p.forbid_lifetime();
4159 let ident = p.parse_ident();
4160 let found_eq = p.eat(&token::Eq);
4163 p.span_warn(span, "whoops, no =?");
4165 let ty = p.parse_ty();
4167 let span = mk_sp(lo, hi);
4168 return P(TypeBinding{id: ast::DUMMY_NODE_ID,
4175 (lifetimes, types.into_vec(), bindings.into_vec())
4178 fn forbid_lifetime(&mut self) {
4179 if self.token.is_lifetime() {
4180 let span = self.span;
4181 self.span_fatal(span, "lifetime parameters must be declared \
4182 prior to type parameters");
4186 /// Parses an optional `where` clause and places it in `generics`.
4189 /// where T : Trait<U, V> + 'b, 'a : 'b
4191 fn parse_where_clause(&mut self, generics: &mut ast::Generics) {
4192 if !self.eat_keyword(keywords::Where) {
4196 let mut parsed_something = false;
4198 let lo = self.span.lo;
4200 token::OpenDelim(token::Brace) => {
4204 token::Lifetime(..) => {
4205 let bounded_lifetime =
4206 self.parse_lifetime();
4208 self.eat(&token::Colon);
4211 self.parse_lifetimes(token::BinOp(token::Plus));
4213 let hi = self.span.hi;
4214 let span = mk_sp(lo, hi);
4216 generics.where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
4217 ast::WhereRegionPredicate {
4219 lifetime: bounded_lifetime,
4224 parsed_something = true;
4228 let bounded_ty = self.parse_ty();
4230 if self.eat(&token::Colon) {
4231 let bounds = self.parse_ty_param_bounds(BoundParsingMode::Bare);
4232 let hi = self.span.hi;
4233 let span = mk_sp(lo, hi);
4235 if bounds.len() == 0 {
4237 "each predicate in a `where` clause must have \
4238 at least one bound in it");
4241 generics.where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
4242 ast::WhereBoundPredicate {
4244 bounded_ty: bounded_ty,
4248 parsed_something = true;
4249 } else if self.eat(&token::Eq) {
4250 // let ty = self.parse_ty();
4251 let hi = self.span.hi;
4252 let span = mk_sp(lo, hi);
4253 // generics.where_clause.predicates.push(
4254 // ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
4255 // id: ast::DUMMY_NODE_ID,
4257 // path: panic!("NYI"), //bounded_ty,
4260 // parsed_something = true;
4263 "equality constraints are not yet supported \
4264 in where clauses (#20041)");
4266 let last_span = self.last_span;
4267 self.span_err(last_span,
4268 "unexpected token in `where` clause");
4273 if !self.eat(&token::Comma) {
4278 if !parsed_something {
4279 let last_span = self.last_span;
4280 self.span_err(last_span,
4281 "a `where` clause must have at least one predicate \
4286 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
4287 -> (Vec<Arg> , bool) {
4289 let mut args: Vec<Option<Arg>> =
4290 self.parse_unspanned_seq(
4291 &token::OpenDelim(token::Paren),
4292 &token::CloseDelim(token::Paren),
4293 seq_sep_trailing_allowed(token::Comma),
4295 if p.token == token::DotDotDot {
4298 if p.token != token::CloseDelim(token::Paren) {
4301 "`...` must be last in argument list for variadic function");
4306 "only foreign functions are allowed to be variadic");
4310 Some(p.parse_arg_general(named_args))
4315 let variadic = match args.pop() {
4318 // Need to put back that last arg
4325 if variadic && args.is_empty() {
4327 "variadic function must be declared with at least one named argument");
4330 let args = args.into_iter().map(|x| x.unwrap()).collect();
4335 /// Parse the argument list and result type of a function declaration
4336 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> P<FnDecl> {
4338 let (args, variadic) = self.parse_fn_args(true, allow_variadic);
4339 let ret_ty = self.parse_ret_ty();
4348 fn is_self_ident(&mut self) -> bool {
4350 token::Ident(id, token::Plain) => id.name == special_idents::self_.name,
4355 fn expect_self_ident(&mut self) -> ast::Ident {
4357 token::Ident(id, token::Plain) if id.name == special_idents::self_.name => {
4362 let token_str = self.this_token_to_string();
4363 self.fatal(&format!("expected `self`, found `{}`",
4369 /// Parse the argument list and result type of a function
4370 /// that may have a self type.
4371 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> (ExplicitSelf, P<FnDecl>) where
4372 F: FnMut(&mut Parser) -> Arg,
4374 fn maybe_parse_borrowed_explicit_self(this: &mut Parser)
4375 -> ast::ExplicitSelf_ {
4376 // The following things are possible to see here:
4381 // fn(&'lt mut self)
4383 // We already know that the current token is `&`.
4385 if this.look_ahead(1, |t| t.is_keyword(keywords::Self)) {
4387 SelfRegion(None, MutImmutable, this.expect_self_ident())
4388 } else if this.look_ahead(1, |t| t.is_mutability()) &&
4389 this.look_ahead(2, |t| t.is_keyword(keywords::Self)) {
4391 let mutability = this.parse_mutability();
4392 SelfRegion(None, mutability, this.expect_self_ident())
4393 } else if this.look_ahead(1, |t| t.is_lifetime()) &&
4394 this.look_ahead(2, |t| t.is_keyword(keywords::Self)) {
4396 let lifetime = this.parse_lifetime();
4397 SelfRegion(Some(lifetime), MutImmutable, this.expect_self_ident())
4398 } else if this.look_ahead(1, |t| t.is_lifetime()) &&
4399 this.look_ahead(2, |t| t.is_mutability()) &&
4400 this.look_ahead(3, |t| t.is_keyword(keywords::Self)) {
4402 let lifetime = this.parse_lifetime();
4403 let mutability = this.parse_mutability();
4404 SelfRegion(Some(lifetime), mutability, this.expect_self_ident())
4410 self.expect(&token::OpenDelim(token::Paren));
4412 // A bit of complexity and lookahead is needed here in order to be
4413 // backwards compatible.
4414 let lo = self.span.lo;
4415 let mut self_ident_lo = self.span.lo;
4416 let mut self_ident_hi = self.span.hi;
4418 let mut mutbl_self = MutImmutable;
4419 let explicit_self = match self.token {
4420 token::BinOp(token::And) => {
4421 let eself = maybe_parse_borrowed_explicit_self(self);
4422 self_ident_lo = self.last_span.lo;
4423 self_ident_hi = self.last_span.hi;
4426 token::BinOp(token::Star) => {
4427 // Possibly "*self" or "*mut self" -- not supported. Try to avoid
4428 // emitting cryptic "unexpected token" errors.
4430 let _mutability = if self.token.is_mutability() {
4431 self.parse_mutability()
4435 if self.is_self_ident() {
4436 let span = self.span;
4437 self.span_err(span, "cannot pass self by unsafe pointer");
4440 // error case, making bogus self ident:
4441 SelfValue(special_idents::self_)
4443 token::Ident(..) => {
4444 if self.is_self_ident() {
4445 let self_ident = self.expect_self_ident();
4447 // Determine whether this is the fully explicit form, `self:
4449 if self.eat(&token::Colon) {
4450 SelfExplicit(self.parse_ty_sum(), self_ident)
4452 SelfValue(self_ident)
4454 } else if self.token.is_mutability() &&
4455 self.look_ahead(1, |t| t.is_keyword(keywords::Self)) {
4456 mutbl_self = self.parse_mutability();
4457 let self_ident = self.expect_self_ident();
4459 // Determine whether this is the fully explicit form,
4461 if self.eat(&token::Colon) {
4462 SelfExplicit(self.parse_ty_sum(), self_ident)
4464 SelfValue(self_ident)
4473 let explicit_self_sp = mk_sp(self_ident_lo, self_ident_hi);
4475 // shared fall-through for the three cases below. borrowing prevents simply
4476 // writing this as a closure
4477 macro_rules! parse_remaining_arguments {
4480 // If we parsed a self type, expect a comma before the argument list.
4484 let sep = seq_sep_trailing_allowed(token::Comma);
4485 let mut fn_inputs = self.parse_seq_to_before_end(
4486 &token::CloseDelim(token::Paren),
4490 fn_inputs.insert(0, Arg::new_self(explicit_self_sp, mutbl_self, $self_id));
4493 token::CloseDelim(token::Paren) => {
4494 vec!(Arg::new_self(explicit_self_sp, mutbl_self, $self_id))
4497 let token_str = self.this_token_to_string();
4498 self.fatal(&format!("expected `,` or `)`, found `{}`",
4505 let fn_inputs = match explicit_self {
4507 let sep = seq_sep_trailing_allowed(token::Comma);
4508 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)
4510 SelfValue(id) => parse_remaining_arguments!(id),
4511 SelfRegion(_,_,id) => parse_remaining_arguments!(id),
4512 SelfExplicit(_,id) => parse_remaining_arguments!(id),
4516 self.expect(&token::CloseDelim(token::Paren));
4518 let hi = self.span.hi;
4520 let ret_ty = self.parse_ret_ty();
4522 let fn_decl = P(FnDecl {
4528 (spanned(lo, hi, explicit_self), fn_decl)
4531 // parse the |arg, arg| header on a lambda
4532 fn parse_fn_block_decl(&mut self)
4533 -> (P<FnDecl>, Option<UnboxedClosureKind>) {
4534 let (optional_unboxed_closure_kind, inputs_captures) = {
4535 if self.eat(&token::OrOr) {
4538 self.expect(&token::BinOp(token::Or));
4539 let optional_unboxed_closure_kind =
4540 self.parse_optional_unboxed_closure_kind();
4541 let args = self.parse_seq_to_before_end(
4542 &token::BinOp(token::Or),
4543 seq_sep_trailing_allowed(token::Comma),
4544 |p| p.parse_fn_block_arg()
4547 (optional_unboxed_closure_kind, args)
4550 let output = self.parse_ret_ty();
4553 inputs: inputs_captures,
4556 }), optional_unboxed_closure_kind)
4559 /// Parses the `(arg, arg) -> return_type` header on a procedure.
4560 fn parse_proc_decl(&mut self) -> P<FnDecl> {
4562 self.parse_unspanned_seq(&token::OpenDelim(token::Paren),
4563 &token::CloseDelim(token::Paren),
4564 seq_sep_trailing_allowed(token::Comma),
4565 |p| p.parse_fn_block_arg());
4567 let output = self.parse_ret_ty();
4576 /// Parse the name and optional generic types of a function header.
4577 fn parse_fn_header(&mut self) -> (Ident, ast::Generics) {
4578 let id = self.parse_ident();
4579 let generics = self.parse_generics();
4583 fn mk_item(&mut self, lo: BytePos, hi: BytePos, ident: Ident,
4584 node: Item_, vis: Visibility,
4585 attrs: Vec<Attribute>) -> P<Item> {
4589 id: ast::DUMMY_NODE_ID,
4596 /// Parse an item-position function declaration.
4597 fn parse_item_fn(&mut self, unsafety: Unsafety, abi: abi::Abi) -> ItemInfo {
4598 let (ident, mut generics) = self.parse_fn_header();
4599 let decl = self.parse_fn_decl(false);
4600 self.parse_where_clause(&mut generics);
4601 let (inner_attrs, body) = self.parse_inner_attrs_and_block();
4602 (ident, ItemFn(decl, unsafety, abi, generics, body), Some(inner_attrs))
4605 /// Parse a method in a trait impl
4606 pub fn parse_method_with_outer_attributes(&mut self) -> P<Method> {
4607 let attrs = self.parse_outer_attributes();
4608 let visa = self.parse_visibility();
4609 self.parse_method(attrs, visa)
4612 /// Parse a method in a trait impl, starting with `attrs` attributes.
4613 pub fn parse_method(&mut self,
4614 attrs: Vec<Attribute>,
4617 let lo = self.span.lo;
4619 // code copied from parse_macro_use_or_failure... abstraction!
4620 let (method_, hi, new_attrs) = {
4621 if !self.token.is_any_keyword()
4622 && self.look_ahead(1, |t| *t == token::Not)
4623 && (self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren))
4624 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) {
4626 let pth = self.parse_path(NoTypesAllowed);
4627 self.expect(&token::Not);
4629 // eat a matched-delimiter token tree:
4630 let delim = self.expect_open_delim();
4631 let tts = self.parse_seq_to_end(&token::CloseDelim(delim),
4633 |p| p.parse_token_tree());
4634 let m_ = ast::MacInvocTT(pth, tts, EMPTY_CTXT);
4635 let m: ast::Mac = codemap::Spanned { node: m_,
4636 span: mk_sp(self.span.lo,
4638 if delim != token::Brace {
4639 self.expect(&token::Semi)
4641 (ast::MethMac(m), self.span.hi, attrs)
4643 let unsafety = self.parse_unsafety();
4644 let abi = if self.eat_keyword(keywords::Extern) {
4645 self.parse_opt_abi().unwrap_or(abi::C)
4649 self.expect_keyword(keywords::Fn);
4650 let ident = self.parse_ident();
4651 let mut generics = self.parse_generics();
4652 let (explicit_self, decl) = self.parse_fn_decl_with_self(|p| {
4655 self.parse_where_clause(&mut generics);
4656 let (inner_attrs, body) = self.parse_inner_attrs_and_block();
4657 let body_span = body.span;
4658 let mut new_attrs = attrs;
4659 new_attrs.push_all(&inner_attrs[]);
4660 (ast::MethDecl(ident,
4668 body_span.hi, new_attrs)
4673 id: ast::DUMMY_NODE_ID,
4674 span: mk_sp(lo, hi),
4679 /// Parse trait Foo { ... }
4680 fn parse_item_trait(&mut self, unsafety: Unsafety) -> ItemInfo {
4681 let ident = self.parse_ident();
4682 let mut tps = self.parse_generics();
4683 let unbound = self.parse_for_sized();
4685 // Parse supertrait bounds.
4686 let mut bounds = self.parse_colon_then_ty_param_bounds(BoundParsingMode::Bare);
4688 if let Some(unbound) = unbound {
4689 let mut bounds_as_vec = bounds.into_vec();
4690 bounds_as_vec.push(TraitTyParamBound(PolyTraitRef { bound_lifetimes: vec![],
4691 trait_ref: unbound },
4692 TraitBoundModifier::Maybe));
4693 bounds = OwnedSlice::from_vec(bounds_as_vec);
4696 self.parse_where_clause(&mut tps);
4698 let meths = self.parse_trait_items();
4699 (ident, ItemTrait(unsafety, tps, bounds, meths), None)
4702 fn parse_impl_items(&mut self) -> (Vec<ImplItem>, Vec<Attribute>) {
4703 let mut impl_items = Vec::new();
4704 self.expect(&token::OpenDelim(token::Brace));
4705 let (inner_attrs, mut method_attrs) =
4706 self.parse_inner_attrs_and_next();
4708 method_attrs.extend(self.parse_outer_attributes().into_iter());
4709 if method_attrs.is_empty() && self.eat(&token::CloseDelim(token::Brace)) {
4713 let vis = self.parse_visibility();
4714 if self.eat_keyword(keywords::Type) {
4715 impl_items.push(TypeImplItem(P(self.parse_typedef(
4719 impl_items.push(MethodImplItem(self.parse_method(
4723 method_attrs = vec![];
4725 (impl_items, inner_attrs)
4728 /// Parses two variants (with the region/type params always optional):
4729 /// impl<T> Foo { ... }
4730 /// impl<T> ToString for ~[T] { ... }
4731 fn parse_item_impl(&mut self, unsafety: ast::Unsafety) -> ItemInfo {
4732 // First, parse type parameters if necessary.
4733 let mut generics = self.parse_generics();
4735 // Special case: if the next identifier that follows is '(', don't
4736 // allow this to be parsed as a trait.
4737 let could_be_trait = self.token != token::OpenDelim(token::Paren);
4739 let neg_span = self.span;
4740 let polarity = if self.eat(&token::Not) {
4741 ast::ImplPolarity::Negative
4743 ast::ImplPolarity::Positive
4747 let mut ty = self.parse_ty_sum();
4749 // Parse traits, if necessary.
4750 let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) {
4751 // New-style trait. Reinterpret the type as a trait.
4752 let opt_trait_ref = match ty.node {
4753 TyPath(ref path, node_id) => {
4755 path: (*path).clone(),
4760 self.span_err(ty.span, "not a trait");
4765 ty = self.parse_ty_sum();
4769 ast::ImplPolarity::Negative => {
4770 // This is a negated type implementation
4771 // `impl !MyType {}`, which is not allowed.
4772 self.span_err(neg_span, "inherent implementation can't be negated");
4779 self.parse_where_clause(&mut generics);
4780 let (impl_items, attrs) = self.parse_impl_items();
4782 let ident = ast_util::impl_pretty_name(&opt_trait, &*ty);
4785 ItemImpl(unsafety, polarity, generics, opt_trait, ty, impl_items),
4789 /// Parse a::B<String,int>
4790 fn parse_trait_ref(&mut self) -> TraitRef {
4792 path: self.parse_path(LifetimeAndTypesWithoutColons),
4793 ref_id: ast::DUMMY_NODE_ID,
4797 fn parse_late_bound_lifetime_defs(&mut self) -> Vec<ast::LifetimeDef> {
4798 if self.eat_keyword(keywords::For) {
4799 self.expect(&token::Lt);
4800 let lifetime_defs = self.parse_lifetime_defs();
4808 /// Parse for<'l> a::B<String,int>
4809 fn parse_poly_trait_ref(&mut self) -> PolyTraitRef {
4810 let lifetime_defs = self.parse_late_bound_lifetime_defs();
4813 bound_lifetimes: lifetime_defs,
4814 trait_ref: self.parse_trait_ref()
4818 /// Parse struct Foo { ... }
4819 fn parse_item_struct(&mut self) -> ItemInfo {
4820 let class_name = self.parse_ident();
4821 let mut generics = self.parse_generics();
4823 if self.eat(&token::Colon) {
4824 let ty = self.parse_ty_sum();
4825 self.span_err(ty.span, "`virtual` structs have been removed from the language");
4828 // There is a special case worth noting here, as reported in issue #17904.
4829 // If we are parsing a tuple struct it is the case that the where clause
4830 // should follow the field list. Like so:
4832 // struct Foo<T>(T) where T: Copy;
4834 // If we are parsing a normal record-style struct it is the case
4835 // that the where clause comes before the body, and after the generics.
4836 // So if we look ahead and see a brace or a where-clause we begin
4837 // parsing a record style struct.
4839 // Otherwise if we look ahead and see a paren we parse a tuple-style
4842 let (fields, ctor_id) = if self.token.is_keyword(keywords::Where) {
4843 self.parse_where_clause(&mut generics);
4844 if self.eat(&token::Semi) {
4845 // If we see a: `struct Foo<T> where T: Copy;` style decl.
4846 (Vec::new(), Some(ast::DUMMY_NODE_ID))
4848 // If we see: `struct Foo<T> where T: Copy { ... }`
4849 (self.parse_record_struct_body(&class_name), None)
4851 // No `where` so: `struct Foo<T>;`
4852 } else if self.eat(&token::Semi) {
4853 (Vec::new(), Some(ast::DUMMY_NODE_ID))
4854 // Record-style struct definition
4855 } else if self.token == token::OpenDelim(token::Brace) {
4856 let fields = self.parse_record_struct_body(&class_name);
4858 // Tuple-style struct definition with optional where-clause.
4860 let fields = self.parse_tuple_struct_body(&class_name, &mut generics);
4861 (fields, Some(ast::DUMMY_NODE_ID))
4865 ItemStruct(P(ast::StructDef {
4872 pub fn parse_record_struct_body(&mut self, class_name: &ast::Ident) -> Vec<StructField> {
4873 let mut fields = Vec::new();
4874 if self.eat(&token::OpenDelim(token::Brace)) {
4875 while self.token != token::CloseDelim(token::Brace) {
4876 fields.push(self.parse_struct_decl_field(true));
4879 if fields.len() == 0 {
4880 self.fatal(&format!("unit-like struct definition should be \
4881 written as `struct {};`",
4882 token::get_ident(class_name.clone()))[]);
4887 let token_str = self.this_token_to_string();
4888 self.fatal(&format!("expected `where`, or `{}` after struct \
4889 name, found `{}`", "{",
4896 pub fn parse_tuple_struct_body(&mut self,
4897 class_name: &ast::Ident,
4898 generics: &mut ast::Generics)
4899 -> Vec<StructField> {
4900 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
4901 if self.check(&token::OpenDelim(token::Paren)) {
4902 let fields = self.parse_unspanned_seq(
4903 &token::OpenDelim(token::Paren),
4904 &token::CloseDelim(token::Paren),
4905 seq_sep_trailing_allowed(token::Comma),
4907 let attrs = p.parse_outer_attributes();
4909 let struct_field_ = ast::StructField_ {
4910 kind: UnnamedField(p.parse_visibility()),
4911 id: ast::DUMMY_NODE_ID,
4912 ty: p.parse_ty_sum(),
4915 spanned(lo, p.span.hi, struct_field_)
4918 if fields.len() == 0 {
4919 self.fatal(&format!("unit-like struct definition should be \
4920 written as `struct {};`",
4921 token::get_ident(class_name.clone()))[]);
4924 self.parse_where_clause(generics);
4925 self.expect(&token::Semi);
4927 // This is the case where we just see struct Foo<T> where T: Copy;
4928 } else if self.token.is_keyword(keywords::Where) {
4929 self.parse_where_clause(generics);
4930 self.expect(&token::Semi);
4932 // This case is where we see: `struct Foo<T>;`
4934 let token_str = self.this_token_to_string();
4935 self.fatal(&format!("expected `where`, `{}`, `(`, or `;` after struct \
4936 name, found `{}`", "{", token_str)[]);
4940 /// Parse a structure field declaration
4941 pub fn parse_single_struct_field(&mut self,
4943 attrs: Vec<Attribute> )
4945 let a_var = self.parse_name_and_ty(vis, attrs);
4950 token::CloseDelim(token::Brace) => {}
4952 let span = self.span;
4953 let token_str = self.this_token_to_string();
4954 self.span_fatal_help(span,
4955 &format!("expected `,`, or `}}`, found `{}`",
4957 "struct fields should be separated by commas")
4963 /// Parse an element of a struct definition
4964 fn parse_struct_decl_field(&mut self, allow_pub: bool) -> StructField {
4966 let attrs = self.parse_outer_attributes();
4968 if self.eat_keyword(keywords::Pub) {
4970 let span = self.last_span;
4971 self.span_err(span, "`pub` is not allowed here");
4973 return self.parse_single_struct_field(Public, attrs);
4976 return self.parse_single_struct_field(Inherited, attrs);
4979 /// Parse visibility: PUB, PRIV, or nothing
4980 fn parse_visibility(&mut self) -> Visibility {
4981 if self.eat_keyword(keywords::Pub) { Public }
4985 fn parse_for_sized(&mut self) -> Option<ast::TraitRef> {
4986 // FIXME, this should really use TraitBoundModifier, but it will get
4987 // re-jigged shortly in any case, so leaving the hacky version for now.
4988 if self.eat_keyword(keywords::For) {
4989 let span = self.span;
4991 let mut ate_question = false;
4992 if self.eat(&token::Question) {
4993 ate_question = true;
4995 let ident = self.parse_ident();
4996 if self.eat(&token::Question) {
5001 ate_question = true;
5005 "expected `?Sized` after `for` in trait item");
5008 let _tref = Parser::trait_ref_from_ident(ident, span);
5010 self.obsolete(span, ObsoleteSyntax::ForSized);
5018 /// Given a termination token and a vector of already-parsed
5019 /// attributes (of length 0 or 1), parse all of the items in a module
5020 fn parse_mod_items(&mut self,
5022 first_item_attrs: Vec<Attribute>,
5025 // parse all of the items up to closing or an attribute.
5026 // view items are legal here.
5027 let ParsedItemsAndViewItems {
5030 items: starting_items,
5032 } = self.parse_items_and_view_items(first_item_attrs, true, true);
5033 let mut items: Vec<P<Item>> = starting_items;
5034 let attrs_remaining_len = attrs_remaining.len();
5036 // don't think this other loop is even necessary....
5038 let mut first = true;
5039 while self.token != term {
5040 let mut attrs = self.parse_outer_attributes();
5042 let mut tmp = attrs_remaining.clone();
5043 tmp.push_all(&attrs[]);
5047 debug!("parse_mod_items: parse_item_or_view_item(attrs={:?})",
5049 match self.parse_item_or_view_item(attrs,
5050 true /* macros allowed */) {
5051 IoviItem(item) => items.push(item),
5052 IoviViewItem(view_item) => {
5053 self.span_fatal(view_item.span,
5054 "view items must be declared at the top of \
5058 let token_str = self.this_token_to_string();
5059 self.fatal(&format!("expected item, found `{}`",
5065 if first && attrs_remaining_len > 0u {
5066 // We parsed attributes for the first item but didn't find it
5067 let last_span = self.last_span;
5068 self.span_err(last_span,
5069 Parser::expected_item_err(&attrs_remaining[]));
5073 inner: mk_sp(inner_lo, self.span.lo),
5074 view_items: view_items,
5079 fn parse_item_const(&mut self, m: Option<Mutability>) -> ItemInfo {
5080 let id = self.parse_ident();
5081 self.expect(&token::Colon);
5082 let ty = self.parse_ty_sum();
5083 self.expect(&token::Eq);
5084 let e = self.parse_expr();
5085 self.commit_expr_expecting(&*e, token::Semi);
5086 let item = match m {
5087 Some(m) => ItemStatic(ty, m, e),
5088 None => ItemConst(ty, e),
5093 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
5094 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> ItemInfo {
5095 let id_span = self.span;
5096 let id = self.parse_ident();
5097 if self.check(&token::Semi) {
5099 // This mod is in an external file. Let's go get it!
5100 let (m, attrs) = self.eval_src_mod(id, outer_attrs, id_span);
5101 (id, m, Some(attrs))
5103 self.push_mod_path(id, outer_attrs);
5104 self.expect(&token::OpenDelim(token::Brace));
5105 let mod_inner_lo = self.span.lo;
5106 let old_owns_directory = self.owns_directory;
5107 self.owns_directory = true;
5108 let (inner, next) = self.parse_inner_attrs_and_next();
5109 let m = self.parse_mod_items(token::CloseDelim(token::Brace), next, mod_inner_lo);
5110 self.expect(&token::CloseDelim(token::Brace));
5111 self.owns_directory = old_owns_directory;
5112 self.pop_mod_path();
5113 (id, ItemMod(m), Some(inner))
5117 fn push_mod_path(&mut self, id: Ident, attrs: &[Attribute]) {
5118 let default_path = self.id_to_interned_str(id);
5119 let file_path = match ::attr::first_attr_value_str_by_name(attrs,
5122 None => default_path,
5124 self.mod_path_stack.push(file_path)
5127 fn pop_mod_path(&mut self) {
5128 self.mod_path_stack.pop().unwrap();
5131 /// Read a module from a source file.
5132 fn eval_src_mod(&mut self,
5134 outer_attrs: &[ast::Attribute],
5136 -> (ast::Item_, Vec<ast::Attribute> ) {
5137 let mut prefix = Path::new(self.sess.span_diagnostic.cm.span_to_filename(self.span));
5139 let mod_path = Path::new(".").join_many(&self.mod_path_stack[]);
5140 let dir_path = prefix.join(&mod_path);
5141 let mod_string = token::get_ident(id);
5142 let (file_path, owns_directory) = match ::attr::first_attr_value_str_by_name(
5143 outer_attrs, "path") {
5144 Some(d) => (dir_path.join(d), true),
5146 let mod_name = mod_string.get().to_string();
5147 let default_path_str = format!("{}.rs", mod_name);
5148 let secondary_path_str = format!("{}/mod.rs", mod_name);
5149 let default_path = dir_path.join(&default_path_str[]);
5150 let secondary_path = dir_path.join(&secondary_path_str[]);
5151 let default_exists = default_path.exists();
5152 let secondary_exists = secondary_path.exists();
5154 if !self.owns_directory {
5155 self.span_err(id_sp,
5156 "cannot declare a new module at this location");
5157 let this_module = match self.mod_path_stack.last() {
5158 Some(name) => name.get().to_string(),
5159 None => self.root_module_name.as_ref().unwrap().clone(),
5161 self.span_note(id_sp,
5162 &format!("maybe move this module `{0}` \
5163 to its own directory via \
5166 if default_exists || secondary_exists {
5167 self.span_note(id_sp,
5168 &format!("... or maybe `use` the module \
5169 `{}` instead of possibly \
5173 self.abort_if_errors();
5176 match (default_exists, secondary_exists) {
5177 (true, false) => (default_path, false),
5178 (false, true) => (secondary_path, true),
5180 self.span_fatal_help(id_sp,
5181 &format!("file not found for module `{}`",
5183 &format!("name the file either {} or {} inside \
5184 the directory {:?}",
5187 dir_path.display())[]);
5190 self.span_fatal_help(
5192 &format!("file for module `{}` found at both {} \
5196 secondary_path_str)[],
5197 "delete or rename one of them to remove the ambiguity");
5203 self.eval_src_mod_from_path(file_path, owns_directory,
5204 mod_string.get().to_string(), id_sp)
5207 fn eval_src_mod_from_path(&mut self,
5209 owns_directory: bool,
5211 id_sp: Span) -> (ast::Item_, Vec<ast::Attribute> ) {
5212 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
5213 match included_mod_stack.iter().position(|p| *p == path) {
5215 let mut err = String::from_str("circular modules: ");
5216 let len = included_mod_stack.len();
5217 for p in included_mod_stack.slice(i, len).iter() {
5218 err.push_str(&p.display().as_cow()[]);
5219 err.push_str(" -> ");
5221 err.push_str(&path.display().as_cow()[]);
5222 self.span_fatal(id_sp, &err[]);
5226 included_mod_stack.push(path.clone());
5227 drop(included_mod_stack);
5230 new_sub_parser_from_file(self.sess,
5236 let mod_inner_lo = p0.span.lo;
5237 let (mod_attrs, next) = p0.parse_inner_attrs_and_next();
5238 let first_item_outer_attrs = next;
5239 let m0 = p0.parse_mod_items(token::Eof, first_item_outer_attrs, mod_inner_lo);
5240 self.sess.included_mod_stack.borrow_mut().pop();
5241 return (ast::ItemMod(m0), mod_attrs);
5244 /// Parse a function declaration from a foreign module
5245 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility,
5246 attrs: Vec<Attribute>) -> P<ForeignItem> {
5247 let lo = self.span.lo;
5248 self.expect_keyword(keywords::Fn);
5250 let (ident, mut generics) = self.parse_fn_header();
5251 let decl = self.parse_fn_decl(true);
5252 self.parse_where_clause(&mut generics);
5253 let hi = self.span.hi;
5254 self.expect(&token::Semi);
5255 P(ast::ForeignItem {
5258 node: ForeignItemFn(decl, generics),
5259 id: ast::DUMMY_NODE_ID,
5260 span: mk_sp(lo, hi),
5265 /// Parse a static item from a foreign module
5266 fn parse_item_foreign_static(&mut self, vis: ast::Visibility,
5267 attrs: Vec<Attribute>) -> P<ForeignItem> {
5268 let lo = self.span.lo;
5270 self.expect_keyword(keywords::Static);
5271 let mutbl = self.eat_keyword(keywords::Mut);
5273 let ident = self.parse_ident();
5274 self.expect(&token::Colon);
5275 let ty = self.parse_ty_sum();
5276 let hi = self.span.hi;
5277 self.expect(&token::Semi);
5281 node: ForeignItemStatic(ty, mutbl),
5282 id: ast::DUMMY_NODE_ID,
5283 span: mk_sp(lo, hi),
5288 /// At this point, this is essentially a wrapper for
5289 /// parse_foreign_items.
5290 fn parse_foreign_mod_items(&mut self,
5292 first_item_attrs: Vec<Attribute> )
5294 let ParsedItemsAndViewItems {
5299 } = self.parse_foreign_items(first_item_attrs, true);
5300 if !attrs_remaining.is_empty() {
5301 let last_span = self.last_span;
5302 self.span_err(last_span,
5303 Parser::expected_item_err(&attrs_remaining[]));
5305 assert!(self.token == token::CloseDelim(token::Brace));
5308 view_items: view_items,
5309 items: foreign_items
5313 /// Parse extern crate links
5317 /// extern crate url;
5318 /// extern crate foo = "bar"; //deprecated
5319 /// extern crate "bar" as foo;
5320 fn parse_item_extern_crate(&mut self,
5322 visibility: Visibility,
5323 attrs: Vec<Attribute> )
5326 let span = self.span;
5327 let (maybe_path, ident) = match self.token {
5328 token::Ident(..) => {
5329 let the_ident = self.parse_ident();
5330 let path = if self.eat_keyword(keywords::As) {
5331 // skip the ident if there is one
5332 if self.token.is_ident() { self.bump(); }
5334 self.span_err(span, "expected `;`, found `as`");
5335 self.span_help(span,
5336 &format!("perhaps you meant to enclose the crate name `{}` in \
5338 the_ident.as_str())[]);
5343 self.expect(&token::Semi);
5346 token::Literal(token::Str_(..), suf) | token::Literal(token::StrRaw(..), suf) => {
5348 self.expect_no_suffix(sp, "extern crate name", suf);
5349 // forgo the internal suffix check of `parse_str` to
5350 // avoid repeats (this unwrap will always succeed due
5351 // to the restriction of the `match`)
5352 let (s, style, _) = self.parse_optional_str().unwrap();
5353 self.expect_keyword(keywords::As);
5354 let the_ident = self.parse_ident();
5355 self.expect(&token::Semi);
5356 (Some((s, style)), the_ident)
5359 let span = self.span;
5360 let token_str = self.this_token_to_string();
5361 self.span_fatal(span,
5362 &format!("expected extern crate name but \
5368 IoviViewItem(ast::ViewItem {
5369 node: ViewItemExternCrate(ident, maybe_path, ast::DUMMY_NODE_ID),
5372 span: mk_sp(lo, self.last_span.hi)
5376 /// Parse `extern` for foreign ABIs
5379 /// `extern` is expected to have been
5380 /// consumed before calling this method
5386 fn parse_item_foreign_mod(&mut self,
5388 opt_abi: Option<abi::Abi>,
5389 visibility: Visibility,
5390 attrs: Vec<Attribute> )
5393 self.expect(&token::OpenDelim(token::Brace));
5395 let abi = opt_abi.unwrap_or(abi::C);
5397 let (inner, next) = self.parse_inner_attrs_and_next();
5398 let m = self.parse_foreign_mod_items(abi, next);
5399 self.expect(&token::CloseDelim(token::Brace));
5401 let last_span = self.last_span;
5402 let item = self.mk_item(lo,
5404 special_idents::invalid,
5407 maybe_append(attrs, Some(inner)));
5408 return IoviItem(item);
5411 /// Parse type Foo = Bar;
5412 fn parse_item_type(&mut self) -> ItemInfo {
5413 let ident = self.parse_ident();
5414 let mut tps = self.parse_generics();
5415 self.parse_where_clause(&mut tps);
5416 self.expect(&token::Eq);
5417 let ty = self.parse_ty_sum();
5418 self.expect(&token::Semi);
5419 (ident, ItemTy(ty, tps), None)
5422 /// Parse a structure-like enum variant definition
5423 /// this should probably be renamed or refactored...
5424 fn parse_struct_def(&mut self) -> P<StructDef> {
5425 let mut fields: Vec<StructField> = Vec::new();
5426 while self.token != token::CloseDelim(token::Brace) {
5427 fields.push(self.parse_struct_decl_field(false));
5437 /// Parse the part of an "enum" decl following the '{'
5438 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> EnumDef {
5439 let mut variants = Vec::new();
5440 let mut all_nullary = true;
5441 let mut any_disr = None;
5442 while self.token != token::CloseDelim(token::Brace) {
5443 let variant_attrs = self.parse_outer_attributes();
5444 let vlo = self.span.lo;
5446 let vis = self.parse_visibility();
5450 let mut args = Vec::new();
5451 let mut disr_expr = None;
5452 ident = self.parse_ident();
5453 if self.eat(&token::OpenDelim(token::Brace)) {
5454 // Parse a struct variant.
5455 all_nullary = false;
5456 let start_span = self.span;
5457 let struct_def = self.parse_struct_def();
5458 if struct_def.fields.len() == 0 {
5459 self.span_err(start_span,
5460 &format!("unit-like struct variant should be written \
5461 without braces, as `{},`",
5462 token::get_ident(ident))[]);
5464 kind = StructVariantKind(struct_def);
5465 } else if self.check(&token::OpenDelim(token::Paren)) {
5466 all_nullary = false;
5467 let arg_tys = self.parse_enum_variant_seq(
5468 &token::OpenDelim(token::Paren),
5469 &token::CloseDelim(token::Paren),
5470 seq_sep_trailing_allowed(token::Comma),
5471 |p| p.parse_ty_sum()
5473 for ty in arg_tys.into_iter() {
5474 args.push(ast::VariantArg {
5476 id: ast::DUMMY_NODE_ID,
5479 kind = TupleVariantKind(args);
5480 } else if self.eat(&token::Eq) {
5481 disr_expr = Some(self.parse_expr());
5482 any_disr = disr_expr.as_ref().map(|expr| expr.span);
5483 kind = TupleVariantKind(args);
5485 kind = TupleVariantKind(Vec::new());
5488 let vr = ast::Variant_ {
5490 attrs: variant_attrs,
5492 id: ast::DUMMY_NODE_ID,
5493 disr_expr: disr_expr,
5496 variants.push(P(spanned(vlo, self.last_span.hi, vr)));
5498 if !self.eat(&token::Comma) { break; }
5500 self.expect(&token::CloseDelim(token::Brace));
5502 Some(disr_span) if !all_nullary =>
5503 self.span_err(disr_span,
5504 "discriminator values can only be used with a c-like enum"),
5508 ast::EnumDef { variants: variants }
5511 /// Parse an "enum" declaration
5512 fn parse_item_enum(&mut self) -> ItemInfo {
5513 let id = self.parse_ident();
5514 let mut generics = self.parse_generics();
5515 self.parse_where_clause(&mut generics);
5516 self.expect(&token::OpenDelim(token::Brace));
5518 let enum_definition = self.parse_enum_def(&generics);
5519 (id, ItemEnum(enum_definition, generics), None)
5522 /// Parses a string as an ABI spec on an extern type or module. Consumes
5523 /// the `extern` keyword, if one is found.
5524 fn parse_opt_abi(&mut self) -> Option<abi::Abi> {
5526 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
5528 self.expect_no_suffix(sp, "ABI spec", suf);
5530 let the_string = s.as_str();
5531 match abi::lookup(the_string) {
5532 Some(abi) => Some(abi),
5534 let last_span = self.last_span;
5537 &format!("illegal ABI: expected one of [{}], \
5539 abi::all_names().connect(", "),
5550 /// Parse one of the items or view items allowed by the
5551 /// flags; on failure, return IoviNone.
5552 /// NB: this function no longer parses the items inside an
5554 fn parse_item_or_view_item(&mut self,
5555 attrs: Vec<Attribute> ,
5556 macros_allowed: bool)
5558 let nt_item = match self.token {
5559 token::Interpolated(token::NtItem(ref item)) => {
5560 Some((**item).clone())
5567 let mut attrs = attrs;
5568 mem::swap(&mut item.attrs, &mut attrs);
5569 item.attrs.extend(attrs.into_iter());
5570 return IoviItem(P(item));
5575 let lo = self.span.lo;
5577 let visibility = self.parse_visibility();
5579 // must be a view item:
5580 if self.eat_keyword(keywords::Use) {
5581 // USE ITEM (IoviViewItem)
5582 let view_item = self.parse_use();
5583 self.expect(&token::Semi);
5584 return IoviViewItem(ast::ViewItem {
5588 span: mk_sp(lo, self.last_span.hi)
5591 // either a view item or an item:
5592 if self.eat_keyword(keywords::Extern) {
5593 if self.eat_keyword(keywords::Crate) {
5594 return self.parse_item_extern_crate(lo, visibility, attrs);
5597 let opt_abi = self.parse_opt_abi();
5599 if self.eat_keyword(keywords::Fn) {
5600 // EXTERN FUNCTION ITEM
5601 let abi = opt_abi.unwrap_or(abi::C);
5602 let (ident, item_, extra_attrs) =
5603 self.parse_item_fn(Unsafety::Normal, abi);
5604 let last_span = self.last_span;
5605 let item = self.mk_item(lo,
5610 maybe_append(attrs, extra_attrs));
5611 return IoviItem(item);
5612 } else if self.check(&token::OpenDelim(token::Brace)) {
5613 return self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs);
5616 let span = self.span;
5617 let token_str = self.this_token_to_string();
5618 self.span_fatal(span,
5619 &format!("expected `{}` or `fn`, found `{}`", "{",
5623 if self.eat_keyword(keywords::Virtual) {
5624 let span = self.span;
5625 self.span_err(span, "`virtual` structs have been removed from the language");
5628 // the rest are all guaranteed to be items:
5629 if self.token.is_keyword(keywords::Static) {
5632 let m = if self.eat_keyword(keywords::Mut) {MutMutable} else {MutImmutable};
5633 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m));
5634 let last_span = self.last_span;
5635 let item = self.mk_item(lo,
5640 maybe_append(attrs, extra_attrs));
5641 return IoviItem(item);
5643 if self.token.is_keyword(keywords::Const) {
5646 if self.eat_keyword(keywords::Mut) {
5647 let last_span = self.last_span;
5648 self.span_err(last_span, "const globals cannot be mutable");
5649 self.span_help(last_span, "did you mean to declare a static?");
5651 let (ident, item_, extra_attrs) = self.parse_item_const(None);
5652 let last_span = self.last_span;
5653 let item = self.mk_item(lo,
5658 maybe_append(attrs, extra_attrs));
5659 return IoviItem(item);
5661 if self.token.is_keyword(keywords::Unsafe) &&
5662 self.look_ahead(1u, |t| t.is_keyword(keywords::Trait))
5664 // UNSAFE TRAIT ITEM
5665 self.expect_keyword(keywords::Unsafe);
5666 self.expect_keyword(keywords::Trait);
5667 let (ident, item_, extra_attrs) =
5668 self.parse_item_trait(ast::Unsafety::Unsafe);
5669 let last_span = self.last_span;
5670 let item = self.mk_item(lo,
5675 maybe_append(attrs, extra_attrs));
5676 return IoviItem(item);
5678 if self.token.is_keyword(keywords::Unsafe) &&
5679 self.look_ahead(1u, |t| t.is_keyword(keywords::Impl))
5682 self.expect_keyword(keywords::Unsafe);
5683 self.expect_keyword(keywords::Impl);
5684 let (ident, item_, extra_attrs) = self.parse_item_impl(ast::Unsafety::Unsafe);
5685 let last_span = self.last_span;
5686 let item = self.mk_item(lo,
5691 maybe_append(attrs, extra_attrs));
5692 return IoviItem(item);
5694 if self.token.is_keyword(keywords::Fn) {
5697 let (ident, item_, extra_attrs) =
5698 self.parse_item_fn(Unsafety::Normal, abi::Rust);
5699 let last_span = self.last_span;
5700 let item = self.mk_item(lo,
5705 maybe_append(attrs, extra_attrs));
5706 return IoviItem(item);
5708 if self.token.is_keyword(keywords::Unsafe)
5709 && self.look_ahead(1u, |t| *t != token::OpenDelim(token::Brace)) {
5710 // UNSAFE FUNCTION ITEM
5712 let abi = if self.eat_keyword(keywords::Extern) {
5713 self.parse_opt_abi().unwrap_or(abi::C)
5717 self.expect_keyword(keywords::Fn);
5718 let (ident, item_, extra_attrs) =
5719 self.parse_item_fn(Unsafety::Unsafe, abi);
5720 let last_span = self.last_span;
5721 let item = self.mk_item(lo,
5726 maybe_append(attrs, extra_attrs));
5727 return IoviItem(item);
5729 if self.eat_keyword(keywords::Mod) {
5731 let (ident, item_, extra_attrs) =
5732 self.parse_item_mod(&attrs[]);
5733 let last_span = self.last_span;
5734 let item = self.mk_item(lo,
5739 maybe_append(attrs, extra_attrs));
5740 return IoviItem(item);
5742 if self.eat_keyword(keywords::Type) {
5744 let (ident, item_, extra_attrs) = self.parse_item_type();
5745 let last_span = self.last_span;
5746 let item = self.mk_item(lo,
5751 maybe_append(attrs, extra_attrs));
5752 return IoviItem(item);
5754 if self.eat_keyword(keywords::Enum) {
5756 let (ident, item_, extra_attrs) = self.parse_item_enum();
5757 let last_span = self.last_span;
5758 let item = self.mk_item(lo,
5763 maybe_append(attrs, extra_attrs));
5764 return IoviItem(item);
5766 if self.eat_keyword(keywords::Trait) {
5768 let (ident, item_, extra_attrs) =
5769 self.parse_item_trait(ast::Unsafety::Normal);
5770 let last_span = self.last_span;
5771 let item = self.mk_item(lo,
5776 maybe_append(attrs, extra_attrs));
5777 return IoviItem(item);
5779 if self.eat_keyword(keywords::Impl) {
5781 let (ident, item_, extra_attrs) = self.parse_item_impl(ast::Unsafety::Normal);
5782 let last_span = self.last_span;
5783 let item = self.mk_item(lo,
5788 maybe_append(attrs, extra_attrs));
5789 return IoviItem(item);
5791 if self.eat_keyword(keywords::Struct) {
5793 let (ident, item_, extra_attrs) = self.parse_item_struct();
5794 let last_span = self.last_span;
5795 let item = self.mk_item(lo,
5800 maybe_append(attrs, extra_attrs));
5801 return IoviItem(item);
5803 self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility)
5806 /// Parse a foreign item; on failure, return IoviNone.
5807 fn parse_foreign_item(&mut self,
5808 attrs: Vec<Attribute> ,
5809 macros_allowed: bool)
5811 maybe_whole!(iovi self, NtItem);
5812 let lo = self.span.lo;
5814 let visibility = self.parse_visibility();
5816 if self.token.is_keyword(keywords::Static) {
5817 // FOREIGN STATIC ITEM
5818 let item = self.parse_item_foreign_static(visibility, attrs);
5819 return IoviForeignItem(item);
5821 if self.token.is_keyword(keywords::Fn) || self.token.is_keyword(keywords::Unsafe) {
5822 // FOREIGN FUNCTION ITEM
5823 let item = self.parse_item_foreign_fn(visibility, attrs);
5824 return IoviForeignItem(item);
5826 self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility)
5829 /// This is the fall-through for parsing items.
5830 fn parse_macro_use_or_failure(
5832 attrs: Vec<Attribute> ,
5833 macros_allowed: bool,
5835 visibility: Visibility
5836 ) -> ItemOrViewItem {
5837 if macros_allowed && !self.token.is_any_keyword()
5838 && self.look_ahead(1, |t| *t == token::Not)
5839 && (self.look_ahead(2, |t| t.is_plain_ident())
5840 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren))
5841 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) {
5842 // MACRO INVOCATION ITEM
5845 let pth = self.parse_path(NoTypesAllowed);
5846 self.expect(&token::Not);
5848 // a 'special' identifier (like what `macro_rules!` uses)
5849 // is optional. We should eventually unify invoc syntax
5851 let id = if self.token.is_plain_ident() {
5854 token::special_idents::invalid // no special identifier
5856 // eat a matched-delimiter token tree:
5857 let delim = self.expect_open_delim();
5858 let tts = self.parse_seq_to_end(&token::CloseDelim(delim),
5860 |p| p.parse_token_tree());
5861 // single-variant-enum... :
5862 let m = ast::MacInvocTT(pth, tts, EMPTY_CTXT);
5863 let m: ast::Mac = codemap::Spanned { node: m,
5864 span: mk_sp(self.span.lo,
5867 if delim != token::Brace {
5868 if !self.eat(&token::Semi) {
5869 let last_span = self.last_span;
5870 self.span_err(last_span,
5871 "macros that expand to items must either \
5872 be surrounded with braces or followed by \
5877 let item_ = ItemMac(m);
5878 let last_span = self.last_span;
5879 let item = self.mk_item(lo,
5885 return IoviItem(item);
5888 // FAILURE TO PARSE ITEM
5892 let last_span = self.last_span;
5893 self.span_fatal(last_span, "unmatched visibility `pub`");
5896 return IoviNone(attrs);
5899 pub fn parse_item_with_outer_attributes(&mut self) -> Option<P<Item>> {
5900 let attrs = self.parse_outer_attributes();
5901 self.parse_item(attrs)
5904 pub fn parse_item(&mut self, attrs: Vec<Attribute>) -> Option<P<Item>> {
5905 match self.parse_item_or_view_item(attrs, true) {
5906 IoviNone(_) => None,
5908 self.fatal("view items are not allowed here"),
5909 IoviForeignItem(_) =>
5910 self.fatal("foreign items are not allowed here"),
5911 IoviItem(item) => Some(item)
5915 /// Parse a ViewItem, e.g. `use foo::bar` or `extern crate foo`
5916 pub fn parse_view_item(&mut self, attrs: Vec<Attribute>) -> ViewItem {
5917 match self.parse_item_or_view_item(attrs, false) {
5918 IoviViewItem(vi) => vi,
5919 _ => self.fatal("expected `use` or `extern crate`"),
5923 /// Parse, e.g., "use a::b::{z,y}"
5924 fn parse_use(&mut self) -> ViewItem_ {
5925 return ViewItemUse(self.parse_view_path());
5929 /// Matches view_path : MOD? non_global_path as IDENT
5930 /// | MOD? non_global_path MOD_SEP LBRACE RBRACE
5931 /// | MOD? non_global_path MOD_SEP LBRACE ident_seq RBRACE
5932 /// | MOD? non_global_path MOD_SEP STAR
5933 /// | MOD? non_global_path
5934 fn parse_view_path(&mut self) -> P<ViewPath> {
5935 let lo = self.span.lo;
5937 // Allow a leading :: because the paths are absolute either way.
5938 // This occurs with "use $crate::..." in macros.
5939 self.eat(&token::ModSep);
5941 if self.check(&token::OpenDelim(token::Brace)) {
5943 let idents = self.parse_unspanned_seq(
5944 &token::OpenDelim(token::Brace),
5945 &token::CloseDelim(token::Brace),
5946 seq_sep_trailing_allowed(token::Comma),
5947 |p| p.parse_path_list_item());
5948 let path = ast::Path {
5949 span: mk_sp(lo, self.span.hi),
5951 segments: Vec::new()
5953 return P(spanned(lo, self.span.hi,
5954 ViewPathList(path, idents, ast::DUMMY_NODE_ID)));
5957 let first_ident = self.parse_ident();
5958 let mut path = vec!(first_ident);
5959 if let token::ModSep = self.token {
5960 // foo::bar or foo::{a,b,c} or foo::*
5961 while self.check(&token::ModSep) {
5965 token::Ident(i, _) => {
5970 // foo::bar::{a,b,c}
5971 token::OpenDelim(token::Brace) => {
5972 let idents = self.parse_unspanned_seq(
5973 &token::OpenDelim(token::Brace),
5974 &token::CloseDelim(token::Brace),
5975 seq_sep_trailing_allowed(token::Comma),
5976 |p| p.parse_path_list_item()
5978 let path = ast::Path {
5979 span: mk_sp(lo, self.span.hi),
5981 segments: path.into_iter().map(|identifier| {
5983 identifier: identifier,
5984 parameters: ast::PathParameters::none(),
5988 return P(spanned(lo, self.span.hi,
5989 ViewPathList(path, idents, ast::DUMMY_NODE_ID)));
5993 token::BinOp(token::Star) => {
5995 let path = ast::Path {
5996 span: mk_sp(lo, self.span.hi),
5998 segments: path.into_iter().map(|identifier| {
6000 identifier: identifier,
6001 parameters: ast::PathParameters::none(),
6005 return P(spanned(lo, self.span.hi,
6006 ViewPathGlob(path, ast::DUMMY_NODE_ID)));
6013 let mut rename_to = path[path.len() - 1u];
6014 let path = ast::Path {
6015 span: mk_sp(lo, self.last_span.hi),
6017 segments: path.into_iter().map(|identifier| {
6019 identifier: identifier,
6020 parameters: ast::PathParameters::none(),
6024 if self.eat_keyword(keywords::As) {
6025 rename_to = self.parse_ident()
6029 ViewPathSimple(rename_to, path, ast::DUMMY_NODE_ID)))
6032 /// Parses a sequence of items. Stops when it finds program
6033 /// text that can't be parsed as an item
6034 /// - mod_items uses extern_mod_allowed = true
6035 /// - block_tail_ uses extern_mod_allowed = false
6036 fn parse_items_and_view_items(&mut self,
6037 first_item_attrs: Vec<Attribute> ,
6038 mut extern_mod_allowed: bool,
6039 macros_allowed: bool)
6040 -> ParsedItemsAndViewItems {
6041 let mut attrs = first_item_attrs;
6042 attrs.push_all(&self.parse_outer_attributes()[]);
6043 // First, parse view items.
6044 let mut view_items : Vec<ast::ViewItem> = Vec::new();
6045 let mut items = Vec::new();
6047 // I think this code would probably read better as a single
6048 // loop with a mutable three-state-variable (for extern crates,
6049 // view items, and regular items) ... except that because
6050 // of macros, I'd like to delay that entire check until later.
6052 match self.parse_item_or_view_item(attrs, macros_allowed) {
6053 IoviNone(attrs) => {
6054 return ParsedItemsAndViewItems {
6055 attrs_remaining: attrs,
6056 view_items: view_items,
6058 foreign_items: Vec::new()
6061 IoviViewItem(view_item) => {
6062 match view_item.node {
6063 ViewItemUse(..) => {
6064 // `extern crate` must precede `use`.
6065 extern_mod_allowed = false;
6067 ViewItemExternCrate(..) if !extern_mod_allowed => {
6068 self.span_err(view_item.span,
6069 "\"extern crate\" declarations are \
6072 ViewItemExternCrate(..) => {}
6074 view_items.push(view_item);
6078 attrs = self.parse_outer_attributes();
6081 IoviForeignItem(_) => {
6085 attrs = self.parse_outer_attributes();
6088 // Next, parse items.
6090 match self.parse_item_or_view_item(attrs, macros_allowed) {
6091 IoviNone(returned_attrs) => {
6092 attrs = returned_attrs;
6095 IoviViewItem(view_item) => {
6096 attrs = self.parse_outer_attributes();
6097 self.span_err(view_item.span,
6098 "`use` and `extern crate` declarations must precede items");
6101 attrs = self.parse_outer_attributes();
6104 IoviForeignItem(_) => {
6110 ParsedItemsAndViewItems {
6111 attrs_remaining: attrs,
6112 view_items: view_items,
6114 foreign_items: Vec::new()
6118 /// Parses a sequence of foreign items. Stops when it finds program
6119 /// text that can't be parsed as an item
6120 fn parse_foreign_items(&mut self, first_item_attrs: Vec<Attribute> ,
6121 macros_allowed: bool)
6122 -> ParsedItemsAndViewItems {
6123 let mut attrs = first_item_attrs;
6124 attrs.push_all(&self.parse_outer_attributes()[]);
6125 let mut foreign_items = Vec::new();
6127 match self.parse_foreign_item(attrs, macros_allowed) {
6128 IoviNone(returned_attrs) => {
6129 if self.check(&token::CloseDelim(token::Brace)) {
6130 attrs = returned_attrs;
6135 IoviViewItem(view_item) => {
6136 // I think this can't occur:
6137 self.span_err(view_item.span,
6138 "`use` and `extern crate` declarations must precede items");
6141 // FIXME #5668: this will occur for a macro invocation:
6142 self.span_fatal(item.span, "macros cannot expand to foreign items");
6144 IoviForeignItem(foreign_item) => {
6145 foreign_items.push(foreign_item);
6148 attrs = self.parse_outer_attributes();
6151 ParsedItemsAndViewItems {
6152 attrs_remaining: attrs,
6153 view_items: Vec::new(),
6155 foreign_items: foreign_items
6159 /// Parses a source module as a crate. This is the main
6160 /// entry point for the parser.
6161 pub fn parse_crate_mod(&mut self) -> Crate {
6162 let lo = self.span.lo;
6163 // parse the crate's inner attrs, maybe (oops) one
6164 // of the attrs of an item:
6165 let (inner, next) = self.parse_inner_attrs_and_next();
6166 let first_item_outer_attrs = next;
6167 // parse the items inside the crate:
6168 let m = self.parse_mod_items(token::Eof, first_item_outer_attrs, lo);
6173 config: self.cfg.clone(),
6174 span: mk_sp(lo, self.span.lo),
6175 exported_macros: Vec::new(),
6179 pub fn parse_optional_str(&mut self)
6180 -> Option<(InternedString, ast::StrStyle, Option<ast::Name>)> {
6181 let ret = match self.token {
6182 token::Literal(token::Str_(s), suf) => {
6183 (self.id_to_interned_str(s.ident()), ast::CookedStr, suf)
6185 token::Literal(token::StrRaw(s, n), suf) => {
6186 (self.id_to_interned_str(s.ident()), ast::RawStr(n), suf)
6194 pub fn parse_str(&mut self) -> (InternedString, StrStyle) {
6195 match self.parse_optional_str() {
6196 Some((s, style, suf)) => {
6197 let sp = self.last_span;
6198 self.expect_no_suffix(sp, "str literal", suf);
6201 _ => self.fatal("expected string literal")