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 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3259 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3260 // Parsing a pattern of the form "fieldname: pat"
3261 let fieldname = self.parse_ident();
3263 let pat = self.parse_pat();
3265 (pat, fieldname, false)
3267 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3268 let is_box = self.eat_keyword(keywords::Box);
3269 let boxed_span_lo = self.span.lo;
3270 let is_ref = self.eat_keyword(keywords::Ref);
3271 let is_mut = self.eat_keyword(keywords::Mut);
3272 let fieldname = self.parse_ident();
3273 hi = self.last_span.hi;
3275 let bind_type = match (is_ref, is_mut) {
3276 (true, true) => BindByRef(MutMutable),
3277 (true, false) => BindByRef(MutImmutable),
3278 (false, true) => BindByValue(MutMutable),
3279 (false, false) => BindByValue(MutImmutable),
3281 let fieldpath = codemap::Spanned{span:self.last_span, node:fieldname};
3282 let fieldpat = P(ast::Pat{
3283 id: ast::DUMMY_NODE_ID,
3284 node: PatIdent(bind_type, fieldpath, None),
3285 span: mk_sp(boxed_span_lo, hi),
3288 let subpat = if is_box {
3290 id: ast::DUMMY_NODE_ID,
3291 node: PatBox(fieldpat),
3292 span: mk_sp(lo, hi),
3297 (subpat, fieldname, true)
3300 fields.push(codemap::Spanned { span: mk_sp(lo, hi),
3301 node: ast::FieldPat { ident: fieldname,
3303 is_shorthand: is_shorthand }});
3305 return (fields, etc);
3308 /// Parse a pattern.
3309 pub fn parse_pat(&mut self) -> P<Pat> {
3310 maybe_whole!(self, NtPat);
3312 let lo = self.span.lo;
3317 token::Underscore => {
3319 pat = PatWild(PatWildSingle);
3320 hi = self.last_span.hi;
3322 id: ast::DUMMY_NODE_ID,
3327 token::BinOp(token::And) | token::AndAnd => {
3328 // parse &pat and &mut pat
3329 let lo = self.span.lo;
3331 let mutability = if self.eat_keyword(keywords::Mut) {
3336 let sub = self.parse_pat();
3337 pat = PatRegion(sub, mutability);
3338 hi = self.last_span.hi;
3340 id: ast::DUMMY_NODE_ID,
3345 token::OpenDelim(token::Paren) => {
3346 // parse (pat,pat,pat,...) as tuple
3348 if self.check(&token::CloseDelim(token::Paren)) {
3350 pat = PatTup(vec![]);
3352 let mut fields = vec!(self.parse_pat());
3353 if self.look_ahead(1, |t| *t != token::CloseDelim(token::Paren)) {
3354 while self.check(&token::Comma) {
3356 if self.check(&token::CloseDelim(token::Paren)) { break; }
3357 fields.push(self.parse_pat());
3360 if fields.len() == 1 { self.expect(&token::Comma); }
3361 self.expect(&token::CloseDelim(token::Paren));
3362 pat = PatTup(fields);
3364 hi = self.last_span.hi;
3366 id: ast::DUMMY_NODE_ID,
3371 token::OpenDelim(token::Bracket) => {
3372 // parse [pat,pat,...] as vector pattern
3374 let (before, slice, after) =
3375 self.parse_pat_vec_elements();
3377 self.expect(&token::CloseDelim(token::Bracket));
3378 pat = ast::PatVec(before, slice, after);
3379 hi = self.last_span.hi;
3381 id: ast::DUMMY_NODE_ID,
3388 // at this point, token != _, ~, &, &&, (, [
3390 if (!(self.token.is_ident() || self.token.is_path())
3391 && self.token != token::ModSep)
3392 || self.token.is_keyword(keywords::True)
3393 || self.token.is_keyword(keywords::False) {
3394 // Parse an expression pattern or exp .. exp.
3396 // These expressions are limited to literals (possibly
3397 // preceded by unary-minus) or identifiers.
3398 let val = self.parse_literal_maybe_minus();
3399 if (self.check(&token::DotDotDot)) &&
3400 self.look_ahead(1, |t| {
3401 *t != token::Comma && *t != token::CloseDelim(token::Bracket)
3404 let end = if self.token.is_ident() || self.token.is_path() {
3405 let path = self.parse_path(LifetimeAndTypesWithColons);
3406 let hi = self.span.hi;
3407 self.mk_expr(lo, hi, ExprPath(path))
3409 self.parse_literal_maybe_minus()
3411 pat = PatRange(val, end);
3415 } else if self.eat_keyword(keywords::Mut) {
3416 pat = self.parse_pat_ident(BindByValue(MutMutable));
3417 } else if self.eat_keyword(keywords::Ref) {
3419 let mutbl = self.parse_mutability();
3420 pat = self.parse_pat_ident(BindByRef(mutbl));
3421 } else if self.eat_keyword(keywords::Box) {
3424 // FIXME(#13910): Rename to `PatBox` and extend to full DST
3426 let sub = self.parse_pat();
3428 hi = self.last_span.hi;
3430 id: ast::DUMMY_NODE_ID,
3435 let can_be_enum_or_struct = self.look_ahead(1, |t| {
3437 token::OpenDelim(_) | token::Lt | token::ModSep => true,
3442 if self.look_ahead(1, |t| *t == token::DotDotDot) &&
3443 self.look_ahead(2, |t| {
3444 *t != token::Comma && *t != token::CloseDelim(token::Bracket)
3446 let start = self.parse_expr_res(RESTRICTION_NO_BAR_OP);
3447 self.eat(&token::DotDotDot);
3448 let end = self.parse_expr_res(RESTRICTION_NO_BAR_OP);
3449 pat = PatRange(start, end);
3450 } else if self.token.is_plain_ident() && !can_be_enum_or_struct {
3451 let id = self.parse_ident();
3452 let id_span = self.last_span;
3453 let pth1 = codemap::Spanned{span:id_span, node: id};
3454 if self.eat(&token::Not) {
3456 let delim = self.expect_open_delim();
3457 let tts = self.parse_seq_to_end(&token::CloseDelim(delim),
3459 |p| p.parse_token_tree());
3461 let mac = MacInvocTT(ident_to_path(id_span,id), tts, EMPTY_CTXT);
3462 pat = ast::PatMac(codemap::Spanned {node: mac, span: self.span});
3464 let sub = if self.eat(&token::At) {
3466 Some(self.parse_pat())
3471 pat = PatIdent(BindByValue(MutImmutable), pth1, sub);
3474 // parse an enum pat
3475 let enum_path = self.parse_path(LifetimeAndTypesWithColons);
3477 token::OpenDelim(token::Brace) => {
3480 self.parse_pat_fields();
3482 pat = PatStruct(enum_path, fields, etc);
3485 let mut args: Vec<P<Pat>> = Vec::new();
3487 token::OpenDelim(token::Paren) => {
3488 let is_dotdot = self.look_ahead(1, |t| {
3490 token::DotDot => true,
3495 // This is a "top constructor only" pat
3498 self.expect(&token::CloseDelim(token::Paren));
3499 pat = PatEnum(enum_path, None);
3501 args = self.parse_enum_variant_seq(
3502 &token::OpenDelim(token::Paren),
3503 &token::CloseDelim(token::Paren),
3504 seq_sep_trailing_allowed(token::Comma),
3507 pat = PatEnum(enum_path, Some(args));
3511 if !enum_path.global &&
3512 enum_path.segments.len() == 1 &&
3513 enum_path.segments[0].parameters.is_empty()
3515 // it could still be either an enum
3516 // or an identifier pattern, resolve
3517 // will sort it out:
3518 pat = PatIdent(BindByValue(MutImmutable),
3520 span: enum_path.span,
3521 node: enum_path.segments[0]
3525 pat = PatEnum(enum_path, Some(args));
3533 hi = self.last_span.hi;
3535 id: ast::DUMMY_NODE_ID,
3537 span: mk_sp(lo, hi),
3541 /// Parse ident or ident @ pat
3542 /// used by the copy foo and ref foo patterns to give a good
3543 /// error message when parsing mistakes like ref foo(a,b)
3544 fn parse_pat_ident(&mut self,
3545 binding_mode: ast::BindingMode)
3547 if !self.token.is_plain_ident() {
3548 let span = self.span;
3549 let tok_str = self.this_token_to_string();
3550 self.span_fatal(span,
3551 &format!("expected identifier, found `{}`", tok_str)[]);
3553 let ident = self.parse_ident();
3554 let last_span = self.last_span;
3555 let name = codemap::Spanned{span: last_span, node: ident};
3556 let sub = if self.eat(&token::At) {
3557 Some(self.parse_pat())
3562 // just to be friendly, if they write something like
3564 // we end up here with ( as the current token. This shortly
3565 // leads to a parse error. Note that if there is no explicit
3566 // binding mode then we do not end up here, because the lookahead
3567 // will direct us over to parse_enum_variant()
3568 if self.token == token::OpenDelim(token::Paren) {
3569 let last_span = self.last_span;
3572 "expected identifier, found enum pattern");
3575 PatIdent(binding_mode, name, sub)
3578 /// Parse a local variable declaration
3579 fn parse_local(&mut self) -> P<Local> {
3580 let lo = self.span.lo;
3581 let pat = self.parse_pat();
3584 if self.eat(&token::Colon) {
3585 ty = Some(self.parse_ty_sum());
3587 let init = self.parse_initializer();
3592 id: ast::DUMMY_NODE_ID,
3593 span: mk_sp(lo, self.last_span.hi),
3598 /// Parse a "let" stmt
3599 fn parse_let(&mut self) -> P<Decl> {
3600 let lo = self.span.lo;
3601 let local = self.parse_local();
3602 P(spanned(lo, self.last_span.hi, DeclLocal(local)))
3605 /// Parse a structure field
3606 fn parse_name_and_ty(&mut self, pr: Visibility,
3607 attrs: Vec<Attribute> ) -> StructField {
3608 let lo = self.span.lo;
3609 if !self.token.is_plain_ident() {
3610 self.fatal("expected ident");
3612 let name = self.parse_ident();
3613 self.expect(&token::Colon);
3614 let ty = self.parse_ty_sum();
3615 spanned(lo, self.last_span.hi, ast::StructField_ {
3616 kind: NamedField(name, pr),
3617 id: ast::DUMMY_NODE_ID,
3623 /// Get an expected item after attributes error message.
3624 fn expected_item_err(attrs: &[Attribute]) -> &'static str {
3625 match attrs.last() {
3626 Some(&Attribute { node: ast::Attribute_ { is_sugared_doc: true, .. }, .. }) => {
3627 "expected item after doc comment"
3629 _ => "expected item after attributes",
3633 /// Parse a statement. may include decl.
3634 /// Precondition: any attributes are parsed already
3635 pub fn parse_stmt(&mut self, item_attrs: Vec<Attribute>) -> P<Stmt> {
3636 maybe_whole!(self, NtStmt);
3638 fn check_expected_item(p: &mut Parser, attrs: &[Attribute]) {
3639 // If we have attributes then we should have an item
3640 if !attrs.is_empty() {
3641 let last_span = p.last_span;
3642 p.span_err(last_span, Parser::expected_item_err(attrs));
3646 let lo = self.span.lo;
3647 if self.token.is_keyword(keywords::Let) {
3648 check_expected_item(self, &item_attrs[]);
3649 self.expect_keyword(keywords::Let);
3650 let decl = self.parse_let();
3651 P(spanned(lo, decl.span.hi, StmtDecl(decl, ast::DUMMY_NODE_ID)))
3652 } else if self.token.is_ident()
3653 && !self.token.is_any_keyword()
3654 && self.look_ahead(1, |t| *t == token::Not) {
3655 // it's a macro invocation:
3657 check_expected_item(self, &item_attrs[]);
3659 // Potential trouble: if we allow macros with paths instead of
3660 // idents, we'd need to look ahead past the whole path here...
3661 let pth = self.parse_path(NoTypesAllowed);
3664 let id = match self.token {
3665 token::OpenDelim(_) => token::special_idents::invalid, // no special identifier
3666 _ => self.parse_ident(),
3669 // check that we're pointing at delimiters (need to check
3670 // again after the `if`, because of `parse_ident`
3671 // consuming more tokens).
3672 let delim = match self.token {
3673 token::OpenDelim(delim) => delim,
3675 // we only expect an ident if we didn't parse one
3677 let ident_str = if id.name == token::special_idents::invalid.name {
3682 let tok_str = self.this_token_to_string();
3683 self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
3689 let tts = self.parse_unspanned_seq(
3690 &token::OpenDelim(delim),
3691 &token::CloseDelim(delim),
3693 |p| p.parse_token_tree()
3695 let hi = self.span.hi;
3697 let style = if delim == token::Brace {
3700 MacStmtWithoutBraces
3703 if id.name == token::special_idents::invalid.name {
3706 StmtMac(P(spanned(lo,
3708 MacInvocTT(pth, tts, EMPTY_CTXT))),
3711 // if it has a special ident, it's definitely an item
3713 // Require a semicolon or braces.
3714 if style != MacStmtWithBraces {
3715 if !self.eat(&token::Semi) {
3716 let last_span = self.last_span;
3717 self.span_err(last_span,
3718 "macros that expand to items must \
3719 either be surrounded with braces or \
3720 followed by a semicolon");
3723 P(spanned(lo, hi, StmtDecl(
3724 P(spanned(lo, hi, DeclItem(
3726 lo, hi, id /*id is good here*/,
3727 ItemMac(spanned(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT))),
3728 Inherited, Vec::new(/*no attrs*/))))),
3729 ast::DUMMY_NODE_ID)))
3732 let found_attrs = !item_attrs.is_empty();
3733 let item_err = Parser::expected_item_err(&item_attrs[]);
3734 match self.parse_item_or_view_item(item_attrs, false) {
3737 let decl = P(spanned(lo, hi, DeclItem(i)));
3738 P(spanned(lo, hi, StmtDecl(decl, ast::DUMMY_NODE_ID)))
3740 IoviViewItem(vi) => {
3741 self.span_fatal(vi.span,
3742 "view items must be declared at the top of the block");
3744 IoviForeignItem(_) => {
3745 self.fatal("foreign items are not allowed here");
3749 let last_span = self.last_span;
3750 self.span_err(last_span, item_err);
3753 // Remainder are line-expr stmts.
3754 let e = self.parse_expr_res(RESTRICTION_STMT_EXPR);
3755 P(spanned(lo, e.span.hi, StmtExpr(e, ast::DUMMY_NODE_ID)))
3761 /// Is this expression a successfully-parsed statement?
3762 fn expr_is_complete(&mut self, e: &Expr) -> bool {
3763 self.restrictions.contains(RESTRICTION_STMT_EXPR) &&
3764 !classify::expr_requires_semi_to_be_stmt(e)
3767 /// Parse a block. No inner attrs are allowed.
3768 pub fn parse_block(&mut self) -> P<Block> {
3769 maybe_whole!(no_clone self, NtBlock);
3771 let lo = self.span.lo;
3773 if !self.eat(&token::OpenDelim(token::Brace)) {
3775 let tok = self.this_token_to_string();
3776 self.span_fatal_help(sp,
3777 &format!("expected `{{`, found `{}`", tok)[],
3778 "place this code inside a block");
3781 return self.parse_block_tail_(lo, DefaultBlock, Vec::new());
3784 /// Parse a block. Inner attrs are allowed.
3785 fn parse_inner_attrs_and_block(&mut self)
3786 -> (Vec<Attribute> , P<Block>) {
3788 maybe_whole!(pair_empty self, NtBlock);
3790 let lo = self.span.lo;
3791 self.expect(&token::OpenDelim(token::Brace));
3792 let (inner, next) = self.parse_inner_attrs_and_next();
3794 (inner, self.parse_block_tail_(lo, DefaultBlock, next))
3797 /// Precondition: already parsed the '{' or '#{'
3798 /// I guess that also means "already parsed the 'impure'" if
3799 /// necessary, and this should take a qualifier.
3800 /// Some blocks start with "#{"...
3801 fn parse_block_tail(&mut self, lo: BytePos, s: BlockCheckMode) -> P<Block> {
3802 self.parse_block_tail_(lo, s, Vec::new())
3805 /// Parse the rest of a block expression or function body
3806 fn parse_block_tail_(&mut self, lo: BytePos, s: BlockCheckMode,
3807 first_item_attrs: Vec<Attribute> ) -> P<Block> {
3808 let mut stmts = Vec::new();
3809 let mut expr = None;
3811 // wouldn't it be more uniform to parse view items only, here?
3812 let ParsedItemsAndViewItems {
3817 } = self.parse_items_and_view_items(first_item_attrs,
3820 for item in items.into_iter() {
3821 let span = item.span;
3822 let decl = P(spanned(span.lo, span.hi, DeclItem(item)));
3823 stmts.push(P(spanned(span.lo, span.hi, StmtDecl(decl, ast::DUMMY_NODE_ID))));
3826 let mut attributes_box = attrs_remaining;
3828 while self.token != token::CloseDelim(token::Brace) {
3829 // parsing items even when they're not allowed lets us give
3830 // better error messages and recover more gracefully.
3831 attributes_box.push_all(&self.parse_outer_attributes()[]);
3834 if !attributes_box.is_empty() {
3835 let last_span = self.last_span;
3836 self.span_err(last_span,
3837 Parser::expected_item_err(&attributes_box[]));
3838 attributes_box = Vec::new();
3840 self.bump(); // empty
3842 token::CloseDelim(token::Brace) => {
3843 // fall through and out.
3846 let stmt = self.parse_stmt(attributes_box);
3847 attributes_box = Vec::new();
3848 stmt.and_then(|Spanned {node, span}| match node {
3849 StmtExpr(e, stmt_id) => {
3850 self.handle_expression_like_statement(e,
3856 StmtMac(mac, MacStmtWithoutBraces) => {
3857 // statement macro without braces; might be an
3858 // expr depending on whether a semicolon follows
3861 stmts.push(P(Spanned {
3863 MacStmtWithSemicolon),
3869 let e = self.mk_mac_expr(span.lo,
3871 mac.and_then(|m| m.node));
3872 let e = self.parse_dot_or_call_expr_with(e);
3873 let e = self.parse_more_binops(e, 0);
3874 let e = self.parse_assign_expr_with(e);
3875 self.handle_expression_like_statement(
3884 StmtMac(m, style) => {
3885 // statement macro; might be an expr
3888 stmts.push(P(Spanned {
3890 MacStmtWithSemicolon),
3895 token::CloseDelim(token::Brace) => {
3896 // if a block ends in `m!(arg)` without
3897 // a `;`, it must be an expr
3899 self.mk_mac_expr(span.lo,
3901 m.and_then(|x| x.node)));
3904 stmts.push(P(Spanned {
3905 node: StmtMac(m, style),
3911 _ => { // all other kinds of statements:
3912 if classify::stmt_ends_with_semi(&node) {
3913 self.commit_stmt_expecting(token::Semi);
3916 stmts.push(P(Spanned {
3926 if !attributes_box.is_empty() {
3927 let last_span = self.last_span;
3928 self.span_err(last_span,
3929 Parser::expected_item_err(&attributes_box[]));
3932 let hi = self.span.hi;
3935 view_items: view_items,
3938 id: ast::DUMMY_NODE_ID,
3940 span: mk_sp(lo, hi),
3944 fn handle_expression_like_statement(
3949 stmts: &mut Vec<P<Stmt>>,
3950 last_block_expr: &mut Option<P<Expr>>) {
3951 // expression without semicolon
3952 if classify::expr_requires_semi_to_be_stmt(&*e) {
3953 // Just check for errors and recover; do not eat semicolon yet.
3954 self.commit_stmt(&[],
3955 &[token::Semi, token::CloseDelim(token::Brace)]);
3961 let span_with_semi = Span {
3963 hi: self.last_span.hi,
3964 expn_id: span.expn_id,
3966 stmts.push(P(Spanned {
3967 node: StmtSemi(e, stmt_id),
3968 span: span_with_semi,
3971 token::CloseDelim(token::Brace) => *last_block_expr = Some(e),
3973 stmts.push(P(Spanned {
3974 node: StmtExpr(e, stmt_id),
3981 // Parses a sequence of bounds if a `:` is found,
3982 // otherwise returns empty list.
3983 fn parse_colon_then_ty_param_bounds(&mut self,
3984 mode: BoundParsingMode)
3985 -> OwnedSlice<TyParamBound>
3987 if !self.eat(&token::Colon) {
3990 self.parse_ty_param_bounds(mode)
3994 // matches bounds = ( boundseq )?
3995 // where boundseq = ( polybound + boundseq ) | polybound
3996 // and polybound = ( 'for' '<' 'region '>' )? bound
3997 // and bound = 'region | trait_ref
3998 fn parse_ty_param_bounds(&mut self,
3999 mode: BoundParsingMode)
4000 -> OwnedSlice<TyParamBound>
4002 let mut result = vec!();
4004 let question_span = self.span;
4005 let ate_question = self.eat(&token::Question);
4007 token::Lifetime(lifetime) => {
4009 self.span_err(question_span,
4010 "`?` may only modify trait bounds, not lifetime bounds");
4012 result.push(RegionTyParamBound(ast::Lifetime {
4013 id: ast::DUMMY_NODE_ID,
4019 token::ModSep | token::Ident(..) => {
4020 let poly_trait_ref = self.parse_poly_trait_ref();
4021 let modifier = if ate_question {
4022 if mode == BoundParsingMode::Modified {
4023 TraitBoundModifier::Maybe
4025 self.span_err(question_span,
4027 TraitBoundModifier::None
4030 TraitBoundModifier::None
4032 result.push(TraitTyParamBound(poly_trait_ref, modifier))
4037 if !self.eat(&token::BinOp(token::Plus)) {
4042 return OwnedSlice::from_vec(result);
4045 fn trait_ref_from_ident(ident: Ident, span: Span) -> TraitRef {
4046 let segment = ast::PathSegment {
4048 parameters: ast::PathParameters::none()
4050 let path = ast::Path {
4053 segments: vec![segment],
4057 ref_id: ast::DUMMY_NODE_ID,
4061 /// Matches typaram = (unbound `?`)? IDENT (`?` unbound)? optbounds ( EQ ty )?
4062 fn parse_ty_param(&mut self) -> TyParam {
4063 // This is a bit hacky. Currently we are only interested in a single
4064 // unbound, and it may only be `Sized`. To avoid backtracking and other
4065 // complications, we parse an ident, then check for `?`. If we find it,
4066 // we use the ident as the unbound, otherwise, we use it as the name of
4067 // type param. Even worse, we need to check for `?` before or after the
4069 let mut span = self.span;
4070 let mut ident = self.parse_ident();
4071 let mut unbound = None;
4072 if self.eat(&token::Question) {
4073 let tref = Parser::trait_ref_from_ident(ident, span);
4074 unbound = Some(tref);
4076 ident = self.parse_ident();
4077 self.obsolete(span, ObsoleteSyntax::Sized);
4080 let mut bounds = self.parse_colon_then_ty_param_bounds(BoundParsingMode::Modified);
4081 if let Some(unbound) = unbound {
4082 let mut bounds_as_vec = bounds.into_vec();
4083 bounds_as_vec.push(TraitTyParamBound(PolyTraitRef { bound_lifetimes: vec![],
4084 trait_ref: unbound },
4085 TraitBoundModifier::Maybe));
4086 bounds = OwnedSlice::from_vec(bounds_as_vec);
4089 let default = if self.check(&token::Eq) {
4091 Some(self.parse_ty_sum())
4097 id: ast::DUMMY_NODE_ID,
4104 /// Parse a set of optional generic type parameter declarations. Where
4105 /// clauses are not parsed here, and must be added later via
4106 /// `parse_where_clause()`.
4108 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
4109 /// | ( < lifetimes , typaramseq ( , )? > )
4110 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
4111 pub fn parse_generics(&mut self) -> ast::Generics {
4112 if self.eat(&token::Lt) {
4113 let lifetime_defs = self.parse_lifetime_defs();
4114 let mut seen_default = false;
4115 let ty_params = self.parse_seq_to_gt(Some(token::Comma), |p| {
4116 p.forbid_lifetime();
4117 let ty_param = p.parse_ty_param();
4118 if ty_param.default.is_some() {
4119 seen_default = true;
4120 } else if seen_default {
4121 let last_span = p.last_span;
4122 p.span_err(last_span,
4123 "type parameters with a default must be trailing");
4128 lifetimes: lifetime_defs,
4129 ty_params: ty_params,
4130 where_clause: WhereClause {
4131 id: ast::DUMMY_NODE_ID,
4132 predicates: Vec::new(),
4136 ast_util::empty_generics()
4140 fn parse_generic_values_after_lt(&mut self)
4141 -> (Vec<ast::Lifetime>, Vec<P<Ty>>, Vec<P<TypeBinding>>) {
4142 let lifetimes = self.parse_lifetimes(token::Comma);
4144 // First parse types.
4145 let (types, returned) = self.parse_seq_to_gt_or_return(
4148 p.forbid_lifetime();
4149 if p.look_ahead(1, |t| t == &token::Eq) {
4152 Some(p.parse_ty_sum())
4157 // If we found the `>`, don't continue.
4159 return (lifetimes, types.into_vec(), Vec::new());
4162 // Then parse type bindings.
4163 let bindings = self.parse_seq_to_gt(
4166 p.forbid_lifetime();
4168 let ident = p.parse_ident();
4169 let found_eq = p.eat(&token::Eq);
4172 p.span_warn(span, "whoops, no =?");
4174 let ty = p.parse_ty();
4176 let span = mk_sp(lo, hi);
4177 return P(TypeBinding{id: ast::DUMMY_NODE_ID,
4184 (lifetimes, types.into_vec(), bindings.into_vec())
4187 fn forbid_lifetime(&mut self) {
4188 if self.token.is_lifetime() {
4189 let span = self.span;
4190 self.span_fatal(span, "lifetime parameters must be declared \
4191 prior to type parameters");
4195 /// Parses an optional `where` clause and places it in `generics`.
4198 /// where T : Trait<U, V> + 'b, 'a : 'b
4200 fn parse_where_clause(&mut self, generics: &mut ast::Generics) {
4201 if !self.eat_keyword(keywords::Where) {
4205 let mut parsed_something = false;
4207 let lo = self.span.lo;
4209 token::OpenDelim(token::Brace) => {
4213 token::Lifetime(..) => {
4214 let bounded_lifetime =
4215 self.parse_lifetime();
4217 self.eat(&token::Colon);
4220 self.parse_lifetimes(token::BinOp(token::Plus));
4222 let hi = self.span.hi;
4223 let span = mk_sp(lo, hi);
4225 generics.where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
4226 ast::WhereRegionPredicate {
4228 lifetime: bounded_lifetime,
4233 parsed_something = true;
4237 let bounded_ty = self.parse_ty();
4239 if self.eat(&token::Colon) {
4240 let bounds = self.parse_ty_param_bounds(BoundParsingMode::Bare);
4241 let hi = self.span.hi;
4242 let span = mk_sp(lo, hi);
4244 if bounds.len() == 0 {
4246 "each predicate in a `where` clause must have \
4247 at least one bound in it");
4250 generics.where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
4251 ast::WhereBoundPredicate {
4253 bounded_ty: bounded_ty,
4257 parsed_something = true;
4258 } else if self.eat(&token::Eq) {
4259 // let ty = self.parse_ty();
4260 let hi = self.span.hi;
4261 let span = mk_sp(lo, hi);
4262 // generics.where_clause.predicates.push(
4263 // ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
4264 // id: ast::DUMMY_NODE_ID,
4266 // path: panic!("NYI"), //bounded_ty,
4269 // parsed_something = true;
4272 "equality constraints are not yet supported \
4273 in where clauses (#20041)");
4275 let last_span = self.last_span;
4276 self.span_err(last_span,
4277 "unexpected token in `where` clause");
4282 if !self.eat(&token::Comma) {
4287 if !parsed_something {
4288 let last_span = self.last_span;
4289 self.span_err(last_span,
4290 "a `where` clause must have at least one predicate \
4295 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
4296 -> (Vec<Arg> , bool) {
4298 let mut args: Vec<Option<Arg>> =
4299 self.parse_unspanned_seq(
4300 &token::OpenDelim(token::Paren),
4301 &token::CloseDelim(token::Paren),
4302 seq_sep_trailing_allowed(token::Comma),
4304 if p.token == token::DotDotDot {
4307 if p.token != token::CloseDelim(token::Paren) {
4310 "`...` must be last in argument list for variadic function");
4315 "only foreign functions are allowed to be variadic");
4319 Some(p.parse_arg_general(named_args))
4324 let variadic = match args.pop() {
4327 // Need to put back that last arg
4334 if variadic && args.is_empty() {
4336 "variadic function must be declared with at least one named argument");
4339 let args = args.into_iter().map(|x| x.unwrap()).collect();
4344 /// Parse the argument list and result type of a function declaration
4345 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> P<FnDecl> {
4347 let (args, variadic) = self.parse_fn_args(true, allow_variadic);
4348 let ret_ty = self.parse_ret_ty();
4357 fn is_self_ident(&mut self) -> bool {
4359 token::Ident(id, token::Plain) => id.name == special_idents::self_.name,
4364 fn expect_self_ident(&mut self) -> ast::Ident {
4366 token::Ident(id, token::Plain) if id.name == special_idents::self_.name => {
4371 let token_str = self.this_token_to_string();
4372 self.fatal(&format!("expected `self`, found `{}`",
4378 /// Parse the argument list and result type of a function
4379 /// that may have a self type.
4380 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> (ExplicitSelf, P<FnDecl>) where
4381 F: FnMut(&mut Parser) -> Arg,
4383 fn maybe_parse_borrowed_explicit_self(this: &mut Parser)
4384 -> ast::ExplicitSelf_ {
4385 // The following things are possible to see here:
4390 // fn(&'lt mut self)
4392 // We already know that the current token is `&`.
4394 if this.look_ahead(1, |t| t.is_keyword(keywords::Self)) {
4396 SelfRegion(None, MutImmutable, this.expect_self_ident())
4397 } else if this.look_ahead(1, |t| t.is_mutability()) &&
4398 this.look_ahead(2, |t| t.is_keyword(keywords::Self)) {
4400 let mutability = this.parse_mutability();
4401 SelfRegion(None, mutability, this.expect_self_ident())
4402 } else if this.look_ahead(1, |t| t.is_lifetime()) &&
4403 this.look_ahead(2, |t| t.is_keyword(keywords::Self)) {
4405 let lifetime = this.parse_lifetime();
4406 SelfRegion(Some(lifetime), MutImmutable, this.expect_self_ident())
4407 } else if this.look_ahead(1, |t| t.is_lifetime()) &&
4408 this.look_ahead(2, |t| t.is_mutability()) &&
4409 this.look_ahead(3, |t| t.is_keyword(keywords::Self)) {
4411 let lifetime = this.parse_lifetime();
4412 let mutability = this.parse_mutability();
4413 SelfRegion(Some(lifetime), mutability, this.expect_self_ident())
4419 self.expect(&token::OpenDelim(token::Paren));
4421 // A bit of complexity and lookahead is needed here in order to be
4422 // backwards compatible.
4423 let lo = self.span.lo;
4424 let mut self_ident_lo = self.span.lo;
4425 let mut self_ident_hi = self.span.hi;
4427 let mut mutbl_self = MutImmutable;
4428 let explicit_self = match self.token {
4429 token::BinOp(token::And) => {
4430 let eself = maybe_parse_borrowed_explicit_self(self);
4431 self_ident_lo = self.last_span.lo;
4432 self_ident_hi = self.last_span.hi;
4435 token::BinOp(token::Star) => {
4436 // Possibly "*self" or "*mut self" -- not supported. Try to avoid
4437 // emitting cryptic "unexpected token" errors.
4439 let _mutability = if self.token.is_mutability() {
4440 self.parse_mutability()
4444 if self.is_self_ident() {
4445 let span = self.span;
4446 self.span_err(span, "cannot pass self by unsafe pointer");
4449 // error case, making bogus self ident:
4450 SelfValue(special_idents::self_)
4452 token::Ident(..) => {
4453 if self.is_self_ident() {
4454 let self_ident = self.expect_self_ident();
4456 // Determine whether this is the fully explicit form, `self:
4458 if self.eat(&token::Colon) {
4459 SelfExplicit(self.parse_ty_sum(), self_ident)
4461 SelfValue(self_ident)
4463 } else if self.token.is_mutability() &&
4464 self.look_ahead(1, |t| t.is_keyword(keywords::Self)) {
4465 mutbl_self = self.parse_mutability();
4466 let self_ident = self.expect_self_ident();
4468 // Determine whether this is the fully explicit form,
4470 if self.eat(&token::Colon) {
4471 SelfExplicit(self.parse_ty_sum(), self_ident)
4473 SelfValue(self_ident)
4482 let explicit_self_sp = mk_sp(self_ident_lo, self_ident_hi);
4484 // shared fall-through for the three cases below. borrowing prevents simply
4485 // writing this as a closure
4486 macro_rules! parse_remaining_arguments {
4489 // If we parsed a self type, expect a comma before the argument list.
4493 let sep = seq_sep_trailing_allowed(token::Comma);
4494 let mut fn_inputs = self.parse_seq_to_before_end(
4495 &token::CloseDelim(token::Paren),
4499 fn_inputs.insert(0, Arg::new_self(explicit_self_sp, mutbl_self, $self_id));
4502 token::CloseDelim(token::Paren) => {
4503 vec!(Arg::new_self(explicit_self_sp, mutbl_self, $self_id))
4506 let token_str = self.this_token_to_string();
4507 self.fatal(&format!("expected `,` or `)`, found `{}`",
4514 let fn_inputs = match explicit_self {
4516 let sep = seq_sep_trailing_allowed(token::Comma);
4517 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)
4519 SelfValue(id) => parse_remaining_arguments!(id),
4520 SelfRegion(_,_,id) => parse_remaining_arguments!(id),
4521 SelfExplicit(_,id) => parse_remaining_arguments!(id),
4525 self.expect(&token::CloseDelim(token::Paren));
4527 let hi = self.span.hi;
4529 let ret_ty = self.parse_ret_ty();
4531 let fn_decl = P(FnDecl {
4537 (spanned(lo, hi, explicit_self), fn_decl)
4540 // parse the |arg, arg| header on a lambda
4541 fn parse_fn_block_decl(&mut self)
4542 -> (P<FnDecl>, Option<UnboxedClosureKind>) {
4543 let (optional_unboxed_closure_kind, inputs_captures) = {
4544 if self.eat(&token::OrOr) {
4547 self.expect(&token::BinOp(token::Or));
4548 let optional_unboxed_closure_kind =
4549 self.parse_optional_unboxed_closure_kind();
4550 let args = self.parse_seq_to_before_end(
4551 &token::BinOp(token::Or),
4552 seq_sep_trailing_allowed(token::Comma),
4553 |p| p.parse_fn_block_arg()
4556 (optional_unboxed_closure_kind, args)
4559 let output = self.parse_ret_ty();
4562 inputs: inputs_captures,
4565 }), optional_unboxed_closure_kind)
4568 /// Parses the `(arg, arg) -> return_type` header on a procedure.
4569 fn parse_proc_decl(&mut self) -> P<FnDecl> {
4571 self.parse_unspanned_seq(&token::OpenDelim(token::Paren),
4572 &token::CloseDelim(token::Paren),
4573 seq_sep_trailing_allowed(token::Comma),
4574 |p| p.parse_fn_block_arg());
4576 let output = self.parse_ret_ty();
4585 /// Parse the name and optional generic types of a function header.
4586 fn parse_fn_header(&mut self) -> (Ident, ast::Generics) {
4587 let id = self.parse_ident();
4588 let generics = self.parse_generics();
4592 fn mk_item(&mut self, lo: BytePos, hi: BytePos, ident: Ident,
4593 node: Item_, vis: Visibility,
4594 attrs: Vec<Attribute>) -> P<Item> {
4598 id: ast::DUMMY_NODE_ID,
4605 /// Parse an item-position function declaration.
4606 fn parse_item_fn(&mut self, unsafety: Unsafety, abi: abi::Abi) -> ItemInfo {
4607 let (ident, mut generics) = self.parse_fn_header();
4608 let decl = self.parse_fn_decl(false);
4609 self.parse_where_clause(&mut generics);
4610 let (inner_attrs, body) = self.parse_inner_attrs_and_block();
4611 (ident, ItemFn(decl, unsafety, abi, generics, body), Some(inner_attrs))
4614 /// Parse a method in a trait impl
4615 pub fn parse_method_with_outer_attributes(&mut self) -> P<Method> {
4616 let attrs = self.parse_outer_attributes();
4617 let visa = self.parse_visibility();
4618 self.parse_method(attrs, visa)
4621 /// Parse a method in a trait impl, starting with `attrs` attributes.
4622 pub fn parse_method(&mut self,
4623 attrs: Vec<Attribute>,
4626 let lo = self.span.lo;
4628 // code copied from parse_macro_use_or_failure... abstraction!
4629 let (method_, hi, new_attrs) = {
4630 if !self.token.is_any_keyword()
4631 && self.look_ahead(1, |t| *t == token::Not)
4632 && (self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren))
4633 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) {
4635 let pth = self.parse_path(NoTypesAllowed);
4636 self.expect(&token::Not);
4638 // eat a matched-delimiter token tree:
4639 let delim = self.expect_open_delim();
4640 let tts = self.parse_seq_to_end(&token::CloseDelim(delim),
4642 |p| p.parse_token_tree());
4643 let m_ = ast::MacInvocTT(pth, tts, EMPTY_CTXT);
4644 let m: ast::Mac = codemap::Spanned { node: m_,
4645 span: mk_sp(self.span.lo,
4647 if delim != token::Brace {
4648 self.expect(&token::Semi)
4650 (ast::MethMac(m), self.span.hi, attrs)
4652 let unsafety = self.parse_unsafety();
4653 let abi = if self.eat_keyword(keywords::Extern) {
4654 self.parse_opt_abi().unwrap_or(abi::C)
4658 self.expect_keyword(keywords::Fn);
4659 let ident = self.parse_ident();
4660 let mut generics = self.parse_generics();
4661 let (explicit_self, decl) = self.parse_fn_decl_with_self(|p| {
4664 self.parse_where_clause(&mut generics);
4665 let (inner_attrs, body) = self.parse_inner_attrs_and_block();
4666 let body_span = body.span;
4667 let mut new_attrs = attrs;
4668 new_attrs.push_all(&inner_attrs[]);
4669 (ast::MethDecl(ident,
4677 body_span.hi, new_attrs)
4682 id: ast::DUMMY_NODE_ID,
4683 span: mk_sp(lo, hi),
4688 /// Parse trait Foo { ... }
4689 fn parse_item_trait(&mut self, unsafety: Unsafety) -> ItemInfo {
4690 let ident = self.parse_ident();
4691 let mut tps = self.parse_generics();
4692 let unbound = self.parse_for_sized();
4694 // Parse supertrait bounds.
4695 let mut bounds = self.parse_colon_then_ty_param_bounds(BoundParsingMode::Bare);
4697 if let Some(unbound) = unbound {
4698 let mut bounds_as_vec = bounds.into_vec();
4699 bounds_as_vec.push(TraitTyParamBound(PolyTraitRef { bound_lifetimes: vec![],
4700 trait_ref: unbound },
4701 TraitBoundModifier::Maybe));
4702 bounds = OwnedSlice::from_vec(bounds_as_vec);
4705 self.parse_where_clause(&mut tps);
4707 let meths = self.parse_trait_items();
4708 (ident, ItemTrait(unsafety, tps, bounds, meths), None)
4711 fn parse_impl_items(&mut self) -> (Vec<ImplItem>, Vec<Attribute>) {
4712 let mut impl_items = Vec::new();
4713 self.expect(&token::OpenDelim(token::Brace));
4714 let (inner_attrs, mut method_attrs) =
4715 self.parse_inner_attrs_and_next();
4717 method_attrs.extend(self.parse_outer_attributes().into_iter());
4718 if method_attrs.is_empty() && self.eat(&token::CloseDelim(token::Brace)) {
4722 let vis = self.parse_visibility();
4723 if self.eat_keyword(keywords::Type) {
4724 impl_items.push(TypeImplItem(P(self.parse_typedef(
4728 impl_items.push(MethodImplItem(self.parse_method(
4732 method_attrs = vec![];
4734 (impl_items, inner_attrs)
4737 /// Parses two variants (with the region/type params always optional):
4738 /// impl<T> Foo { ... }
4739 /// impl<T> ToString for ~[T] { ... }
4740 fn parse_item_impl(&mut self, unsafety: ast::Unsafety) -> ItemInfo {
4741 // First, parse type parameters if necessary.
4742 let mut generics = self.parse_generics();
4744 // Special case: if the next identifier that follows is '(', don't
4745 // allow this to be parsed as a trait.
4746 let could_be_trait = self.token != token::OpenDelim(token::Paren);
4748 let neg_span = self.span;
4749 let polarity = if self.eat(&token::Not) {
4750 ast::ImplPolarity::Negative
4752 ast::ImplPolarity::Positive
4756 let mut ty = self.parse_ty_sum();
4758 // Parse traits, if necessary.
4759 let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) {
4760 // New-style trait. Reinterpret the type as a trait.
4761 let opt_trait_ref = match ty.node {
4762 TyPath(ref path, node_id) => {
4764 path: (*path).clone(),
4769 self.span_err(ty.span, "not a trait");
4774 ty = self.parse_ty_sum();
4778 ast::ImplPolarity::Negative => {
4779 // This is a negated type implementation
4780 // `impl !MyType {}`, which is not allowed.
4781 self.span_err(neg_span, "inherent implementation can't be negated");
4788 self.parse_where_clause(&mut generics);
4789 let (impl_items, attrs) = self.parse_impl_items();
4791 let ident = ast_util::impl_pretty_name(&opt_trait, &*ty);
4794 ItemImpl(unsafety, polarity, generics, opt_trait, ty, impl_items),
4798 /// Parse a::B<String,int>
4799 fn parse_trait_ref(&mut self) -> TraitRef {
4801 path: self.parse_path(LifetimeAndTypesWithoutColons),
4802 ref_id: ast::DUMMY_NODE_ID,
4806 fn parse_late_bound_lifetime_defs(&mut self) -> Vec<ast::LifetimeDef> {
4807 if self.eat_keyword(keywords::For) {
4808 self.expect(&token::Lt);
4809 let lifetime_defs = self.parse_lifetime_defs();
4817 /// Parse for<'l> a::B<String,int>
4818 fn parse_poly_trait_ref(&mut self) -> PolyTraitRef {
4819 let lifetime_defs = self.parse_late_bound_lifetime_defs();
4822 bound_lifetimes: lifetime_defs,
4823 trait_ref: self.parse_trait_ref()
4827 /// Parse struct Foo { ... }
4828 fn parse_item_struct(&mut self) -> ItemInfo {
4829 let class_name = self.parse_ident();
4830 let mut generics = self.parse_generics();
4832 if self.eat(&token::Colon) {
4833 let ty = self.parse_ty_sum();
4834 self.span_err(ty.span, "`virtual` structs have been removed from the language");
4837 // There is a special case worth noting here, as reported in issue #17904.
4838 // If we are parsing a tuple struct it is the case that the where clause
4839 // should follow the field list. Like so:
4841 // struct Foo<T>(T) where T: Copy;
4843 // If we are parsing a normal record-style struct it is the case
4844 // that the where clause comes before the body, and after the generics.
4845 // So if we look ahead and see a brace or a where-clause we begin
4846 // parsing a record style struct.
4848 // Otherwise if we look ahead and see a paren we parse a tuple-style
4851 let (fields, ctor_id) = if self.token.is_keyword(keywords::Where) {
4852 self.parse_where_clause(&mut generics);
4853 if self.eat(&token::Semi) {
4854 // If we see a: `struct Foo<T> where T: Copy;` style decl.
4855 (Vec::new(), Some(ast::DUMMY_NODE_ID))
4857 // If we see: `struct Foo<T> where T: Copy { ... }`
4858 (self.parse_record_struct_body(&class_name), None)
4860 // No `where` so: `struct Foo<T>;`
4861 } else if self.eat(&token::Semi) {
4862 (Vec::new(), Some(ast::DUMMY_NODE_ID))
4863 // Record-style struct definition
4864 } else if self.token == token::OpenDelim(token::Brace) {
4865 let fields = self.parse_record_struct_body(&class_name);
4867 // Tuple-style struct definition with optional where-clause.
4869 let fields = self.parse_tuple_struct_body(&class_name, &mut generics);
4870 (fields, Some(ast::DUMMY_NODE_ID))
4874 ItemStruct(P(ast::StructDef {
4881 pub fn parse_record_struct_body(&mut self, class_name: &ast::Ident) -> Vec<StructField> {
4882 let mut fields = Vec::new();
4883 if self.eat(&token::OpenDelim(token::Brace)) {
4884 while self.token != token::CloseDelim(token::Brace) {
4885 fields.push(self.parse_struct_decl_field(true));
4888 if fields.len() == 0 {
4889 self.fatal(&format!("unit-like struct definition should be \
4890 written as `struct {};`",
4891 token::get_ident(class_name.clone()))[]);
4896 let token_str = self.this_token_to_string();
4897 self.fatal(&format!("expected `where`, or `{}` after struct \
4898 name, found `{}`", "{",
4905 pub fn parse_tuple_struct_body(&mut self,
4906 class_name: &ast::Ident,
4907 generics: &mut ast::Generics)
4908 -> Vec<StructField> {
4909 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
4910 if self.check(&token::OpenDelim(token::Paren)) {
4911 let fields = self.parse_unspanned_seq(
4912 &token::OpenDelim(token::Paren),
4913 &token::CloseDelim(token::Paren),
4914 seq_sep_trailing_allowed(token::Comma),
4916 let attrs = p.parse_outer_attributes();
4918 let struct_field_ = ast::StructField_ {
4919 kind: UnnamedField(p.parse_visibility()),
4920 id: ast::DUMMY_NODE_ID,
4921 ty: p.parse_ty_sum(),
4924 spanned(lo, p.span.hi, struct_field_)
4927 if fields.len() == 0 {
4928 self.fatal(&format!("unit-like struct definition should be \
4929 written as `struct {};`",
4930 token::get_ident(class_name.clone()))[]);
4933 self.parse_where_clause(generics);
4934 self.expect(&token::Semi);
4936 // This is the case where we just see struct Foo<T> where T: Copy;
4937 } else if self.token.is_keyword(keywords::Where) {
4938 self.parse_where_clause(generics);
4939 self.expect(&token::Semi);
4941 // This case is where we see: `struct Foo<T>;`
4943 let token_str = self.this_token_to_string();
4944 self.fatal(&format!("expected `where`, `{}`, `(`, or `;` after struct \
4945 name, found `{}`", "{", token_str)[]);
4949 /// Parse a structure field declaration
4950 pub fn parse_single_struct_field(&mut self,
4952 attrs: Vec<Attribute> )
4954 let a_var = self.parse_name_and_ty(vis, attrs);
4959 token::CloseDelim(token::Brace) => {}
4961 let span = self.span;
4962 let token_str = self.this_token_to_string();
4963 self.span_fatal_help(span,
4964 &format!("expected `,`, or `}}`, found `{}`",
4966 "struct fields should be separated by commas")
4972 /// Parse an element of a struct definition
4973 fn parse_struct_decl_field(&mut self, allow_pub: bool) -> StructField {
4975 let attrs = self.parse_outer_attributes();
4977 if self.eat_keyword(keywords::Pub) {
4979 let span = self.last_span;
4980 self.span_err(span, "`pub` is not allowed here");
4982 return self.parse_single_struct_field(Public, attrs);
4985 return self.parse_single_struct_field(Inherited, attrs);
4988 /// Parse visibility: PUB, PRIV, or nothing
4989 fn parse_visibility(&mut self) -> Visibility {
4990 if self.eat_keyword(keywords::Pub) { Public }
4994 fn parse_for_sized(&mut self) -> Option<ast::TraitRef> {
4995 // FIXME, this should really use TraitBoundModifier, but it will get
4996 // re-jigged shortly in any case, so leaving the hacky version for now.
4997 if self.eat_keyword(keywords::For) {
4998 let span = self.span;
5000 let mut ate_question = false;
5001 if self.eat(&token::Question) {
5002 ate_question = true;
5004 let ident = self.parse_ident();
5005 if self.eat(&token::Question) {
5010 ate_question = true;
5014 "expected `?Sized` after `for` in trait item");
5017 let _tref = Parser::trait_ref_from_ident(ident, span);
5019 self.obsolete(span, ObsoleteSyntax::ForSized);
5027 /// Given a termination token and a vector of already-parsed
5028 /// attributes (of length 0 or 1), parse all of the items in a module
5029 fn parse_mod_items(&mut self,
5031 first_item_attrs: Vec<Attribute>,
5034 // parse all of the items up to closing or an attribute.
5035 // view items are legal here.
5036 let ParsedItemsAndViewItems {
5039 items: starting_items,
5041 } = self.parse_items_and_view_items(first_item_attrs, true, true);
5042 let mut items: Vec<P<Item>> = starting_items;
5043 let attrs_remaining_len = attrs_remaining.len();
5045 // don't think this other loop is even necessary....
5047 let mut first = true;
5048 while self.token != term {
5049 let mut attrs = self.parse_outer_attributes();
5051 let mut tmp = attrs_remaining.clone();
5052 tmp.push_all(&attrs[]);
5056 debug!("parse_mod_items: parse_item_or_view_item(attrs={:?})",
5058 match self.parse_item_or_view_item(attrs,
5059 true /* macros allowed */) {
5060 IoviItem(item) => items.push(item),
5061 IoviViewItem(view_item) => {
5062 self.span_fatal(view_item.span,
5063 "view items must be declared at the top of \
5067 let token_str = self.this_token_to_string();
5068 self.fatal(&format!("expected item, found `{}`",
5074 if first && attrs_remaining_len > 0u {
5075 // We parsed attributes for the first item but didn't find it
5076 let last_span = self.last_span;
5077 self.span_err(last_span,
5078 Parser::expected_item_err(&attrs_remaining[]));
5082 inner: mk_sp(inner_lo, self.span.lo),
5083 view_items: view_items,
5088 fn parse_item_const(&mut self, m: Option<Mutability>) -> ItemInfo {
5089 let id = self.parse_ident();
5090 self.expect(&token::Colon);
5091 let ty = self.parse_ty_sum();
5092 self.expect(&token::Eq);
5093 let e = self.parse_expr();
5094 self.commit_expr_expecting(&*e, token::Semi);
5095 let item = match m {
5096 Some(m) => ItemStatic(ty, m, e),
5097 None => ItemConst(ty, e),
5102 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
5103 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> ItemInfo {
5104 let id_span = self.span;
5105 let id = self.parse_ident();
5106 if self.check(&token::Semi) {
5108 // This mod is in an external file. Let's go get it!
5109 let (m, attrs) = self.eval_src_mod(id, outer_attrs, id_span);
5110 (id, m, Some(attrs))
5112 self.push_mod_path(id, outer_attrs);
5113 self.expect(&token::OpenDelim(token::Brace));
5114 let mod_inner_lo = self.span.lo;
5115 let old_owns_directory = self.owns_directory;
5116 self.owns_directory = true;
5117 let (inner, next) = self.parse_inner_attrs_and_next();
5118 let m = self.parse_mod_items(token::CloseDelim(token::Brace), next, mod_inner_lo);
5119 self.expect(&token::CloseDelim(token::Brace));
5120 self.owns_directory = old_owns_directory;
5121 self.pop_mod_path();
5122 (id, ItemMod(m), Some(inner))
5126 fn push_mod_path(&mut self, id: Ident, attrs: &[Attribute]) {
5127 let default_path = self.id_to_interned_str(id);
5128 let file_path = match ::attr::first_attr_value_str_by_name(attrs,
5131 None => default_path,
5133 self.mod_path_stack.push(file_path)
5136 fn pop_mod_path(&mut self) {
5137 self.mod_path_stack.pop().unwrap();
5140 /// Read a module from a source file.
5141 fn eval_src_mod(&mut self,
5143 outer_attrs: &[ast::Attribute],
5145 -> (ast::Item_, Vec<ast::Attribute> ) {
5146 let mut prefix = Path::new(self.sess.span_diagnostic.cm.span_to_filename(self.span));
5148 let mod_path = Path::new(".").join_many(&self.mod_path_stack[]);
5149 let dir_path = prefix.join(&mod_path);
5150 let mod_string = token::get_ident(id);
5151 let (file_path, owns_directory) = match ::attr::first_attr_value_str_by_name(
5152 outer_attrs, "path") {
5153 Some(d) => (dir_path.join(d), true),
5155 let mod_name = mod_string.get().to_string();
5156 let default_path_str = format!("{}.rs", mod_name);
5157 let secondary_path_str = format!("{}/mod.rs", mod_name);
5158 let default_path = dir_path.join(&default_path_str[]);
5159 let secondary_path = dir_path.join(&secondary_path_str[]);
5160 let default_exists = default_path.exists();
5161 let secondary_exists = secondary_path.exists();
5163 if !self.owns_directory {
5164 self.span_err(id_sp,
5165 "cannot declare a new module at this location");
5166 let this_module = match self.mod_path_stack.last() {
5167 Some(name) => name.get().to_string(),
5168 None => self.root_module_name.as_ref().unwrap().clone(),
5170 self.span_note(id_sp,
5171 &format!("maybe move this module `{0}` \
5172 to its own directory via \
5175 if default_exists || secondary_exists {
5176 self.span_note(id_sp,
5177 &format!("... or maybe `use` the module \
5178 `{}` instead of possibly \
5182 self.abort_if_errors();
5185 match (default_exists, secondary_exists) {
5186 (true, false) => (default_path, false),
5187 (false, true) => (secondary_path, true),
5189 self.span_fatal_help(id_sp,
5190 &format!("file not found for module `{}`",
5192 &format!("name the file either {} or {} inside \
5193 the directory {:?}",
5196 dir_path.display())[]);
5199 self.span_fatal_help(
5201 &format!("file for module `{}` found at both {} \
5205 secondary_path_str)[],
5206 "delete or rename one of them to remove the ambiguity");
5212 self.eval_src_mod_from_path(file_path, owns_directory,
5213 mod_string.get().to_string(), id_sp)
5216 fn eval_src_mod_from_path(&mut self,
5218 owns_directory: bool,
5220 id_sp: Span) -> (ast::Item_, Vec<ast::Attribute> ) {
5221 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
5222 match included_mod_stack.iter().position(|p| *p == path) {
5224 let mut err = String::from_str("circular modules: ");
5225 let len = included_mod_stack.len();
5226 for p in included_mod_stack.slice(i, len).iter() {
5227 err.push_str(&p.display().as_cow()[]);
5228 err.push_str(" -> ");
5230 err.push_str(&path.display().as_cow()[]);
5231 self.span_fatal(id_sp, &err[]);
5235 included_mod_stack.push(path.clone());
5236 drop(included_mod_stack);
5239 new_sub_parser_from_file(self.sess,
5245 let mod_inner_lo = p0.span.lo;
5246 let (mod_attrs, next) = p0.parse_inner_attrs_and_next();
5247 let first_item_outer_attrs = next;
5248 let m0 = p0.parse_mod_items(token::Eof, first_item_outer_attrs, mod_inner_lo);
5249 self.sess.included_mod_stack.borrow_mut().pop();
5250 return (ast::ItemMod(m0), mod_attrs);
5253 /// Parse a function declaration from a foreign module
5254 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility,
5255 attrs: Vec<Attribute>) -> P<ForeignItem> {
5256 let lo = self.span.lo;
5257 self.expect_keyword(keywords::Fn);
5259 let (ident, mut generics) = self.parse_fn_header();
5260 let decl = self.parse_fn_decl(true);
5261 self.parse_where_clause(&mut generics);
5262 let hi = self.span.hi;
5263 self.expect(&token::Semi);
5264 P(ast::ForeignItem {
5267 node: ForeignItemFn(decl, generics),
5268 id: ast::DUMMY_NODE_ID,
5269 span: mk_sp(lo, hi),
5274 /// Parse a static item from a foreign module
5275 fn parse_item_foreign_static(&mut self, vis: ast::Visibility,
5276 attrs: Vec<Attribute>) -> P<ForeignItem> {
5277 let lo = self.span.lo;
5279 self.expect_keyword(keywords::Static);
5280 let mutbl = self.eat_keyword(keywords::Mut);
5282 let ident = self.parse_ident();
5283 self.expect(&token::Colon);
5284 let ty = self.parse_ty_sum();
5285 let hi = self.span.hi;
5286 self.expect(&token::Semi);
5290 node: ForeignItemStatic(ty, mutbl),
5291 id: ast::DUMMY_NODE_ID,
5292 span: mk_sp(lo, hi),
5297 /// At this point, this is essentially a wrapper for
5298 /// parse_foreign_items.
5299 fn parse_foreign_mod_items(&mut self,
5301 first_item_attrs: Vec<Attribute> )
5303 let ParsedItemsAndViewItems {
5308 } = self.parse_foreign_items(first_item_attrs, true);
5309 if !attrs_remaining.is_empty() {
5310 let last_span = self.last_span;
5311 self.span_err(last_span,
5312 Parser::expected_item_err(&attrs_remaining[]));
5314 assert!(self.token == token::CloseDelim(token::Brace));
5317 view_items: view_items,
5318 items: foreign_items
5322 /// Parse extern crate links
5326 /// extern crate url;
5327 /// extern crate foo = "bar"; //deprecated
5328 /// extern crate "bar" as foo;
5329 fn parse_item_extern_crate(&mut self,
5331 visibility: Visibility,
5332 attrs: Vec<Attribute> )
5335 let span = self.span;
5336 let (maybe_path, ident) = match self.token {
5337 token::Ident(..) => {
5338 let the_ident = self.parse_ident();
5339 let path = if self.eat_keyword(keywords::As) {
5340 // skip the ident if there is one
5341 if self.token.is_ident() { self.bump(); }
5343 self.span_err(span, "expected `;`, found `as`");
5344 self.span_help(span,
5345 &format!("perhaps you meant to enclose the crate name `{}` in \
5347 the_ident.as_str())[]);
5352 self.expect(&token::Semi);
5355 token::Literal(token::Str_(..), suf) | token::Literal(token::StrRaw(..), suf) => {
5357 self.expect_no_suffix(sp, "extern crate name", suf);
5358 // forgo the internal suffix check of `parse_str` to
5359 // avoid repeats (this unwrap will always succeed due
5360 // to the restriction of the `match`)
5361 let (s, style, _) = self.parse_optional_str().unwrap();
5362 self.expect_keyword(keywords::As);
5363 let the_ident = self.parse_ident();
5364 self.expect(&token::Semi);
5365 (Some((s, style)), the_ident)
5368 let span = self.span;
5369 let token_str = self.this_token_to_string();
5370 self.span_fatal(span,
5371 &format!("expected extern crate name but \
5377 IoviViewItem(ast::ViewItem {
5378 node: ViewItemExternCrate(ident, maybe_path, ast::DUMMY_NODE_ID),
5381 span: mk_sp(lo, self.last_span.hi)
5385 /// Parse `extern` for foreign ABIs
5388 /// `extern` is expected to have been
5389 /// consumed before calling this method
5395 fn parse_item_foreign_mod(&mut self,
5397 opt_abi: Option<abi::Abi>,
5398 visibility: Visibility,
5399 attrs: Vec<Attribute> )
5402 self.expect(&token::OpenDelim(token::Brace));
5404 let abi = opt_abi.unwrap_or(abi::C);
5406 let (inner, next) = self.parse_inner_attrs_and_next();
5407 let m = self.parse_foreign_mod_items(abi, next);
5408 self.expect(&token::CloseDelim(token::Brace));
5410 let last_span = self.last_span;
5411 let item = self.mk_item(lo,
5413 special_idents::invalid,
5416 maybe_append(attrs, Some(inner)));
5417 return IoviItem(item);
5420 /// Parse type Foo = Bar;
5421 fn parse_item_type(&mut self) -> ItemInfo {
5422 let ident = self.parse_ident();
5423 let mut tps = self.parse_generics();
5424 self.parse_where_clause(&mut tps);
5425 self.expect(&token::Eq);
5426 let ty = self.parse_ty_sum();
5427 self.expect(&token::Semi);
5428 (ident, ItemTy(ty, tps), None)
5431 /// Parse a structure-like enum variant definition
5432 /// this should probably be renamed or refactored...
5433 fn parse_struct_def(&mut self) -> P<StructDef> {
5434 let mut fields: Vec<StructField> = Vec::new();
5435 while self.token != token::CloseDelim(token::Brace) {
5436 fields.push(self.parse_struct_decl_field(false));
5446 /// Parse the part of an "enum" decl following the '{'
5447 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> EnumDef {
5448 let mut variants = Vec::new();
5449 let mut all_nullary = true;
5450 let mut any_disr = None;
5451 while self.token != token::CloseDelim(token::Brace) {
5452 let variant_attrs = self.parse_outer_attributes();
5453 let vlo = self.span.lo;
5455 let vis = self.parse_visibility();
5459 let mut args = Vec::new();
5460 let mut disr_expr = None;
5461 ident = self.parse_ident();
5462 if self.eat(&token::OpenDelim(token::Brace)) {
5463 // Parse a struct variant.
5464 all_nullary = false;
5465 let start_span = self.span;
5466 let struct_def = self.parse_struct_def();
5467 if struct_def.fields.len() == 0 {
5468 self.span_err(start_span,
5469 &format!("unit-like struct variant should be written \
5470 without braces, as `{},`",
5471 token::get_ident(ident))[]);
5473 kind = StructVariantKind(struct_def);
5474 } else if self.check(&token::OpenDelim(token::Paren)) {
5475 all_nullary = false;
5476 let arg_tys = self.parse_enum_variant_seq(
5477 &token::OpenDelim(token::Paren),
5478 &token::CloseDelim(token::Paren),
5479 seq_sep_trailing_allowed(token::Comma),
5480 |p| p.parse_ty_sum()
5482 for ty in arg_tys.into_iter() {
5483 args.push(ast::VariantArg {
5485 id: ast::DUMMY_NODE_ID,
5488 kind = TupleVariantKind(args);
5489 } else if self.eat(&token::Eq) {
5490 disr_expr = Some(self.parse_expr());
5491 any_disr = disr_expr.as_ref().map(|expr| expr.span);
5492 kind = TupleVariantKind(args);
5494 kind = TupleVariantKind(Vec::new());
5497 let vr = ast::Variant_ {
5499 attrs: variant_attrs,
5501 id: ast::DUMMY_NODE_ID,
5502 disr_expr: disr_expr,
5505 variants.push(P(spanned(vlo, self.last_span.hi, vr)));
5507 if !self.eat(&token::Comma) { break; }
5509 self.expect(&token::CloseDelim(token::Brace));
5511 Some(disr_span) if !all_nullary =>
5512 self.span_err(disr_span,
5513 "discriminator values can only be used with a c-like enum"),
5517 ast::EnumDef { variants: variants }
5520 /// Parse an "enum" declaration
5521 fn parse_item_enum(&mut self) -> ItemInfo {
5522 let id = self.parse_ident();
5523 let mut generics = self.parse_generics();
5524 self.parse_where_clause(&mut generics);
5525 self.expect(&token::OpenDelim(token::Brace));
5527 let enum_definition = self.parse_enum_def(&generics);
5528 (id, ItemEnum(enum_definition, generics), None)
5531 /// Parses a string as an ABI spec on an extern type or module. Consumes
5532 /// the `extern` keyword, if one is found.
5533 fn parse_opt_abi(&mut self) -> Option<abi::Abi> {
5535 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
5537 self.expect_no_suffix(sp, "ABI spec", suf);
5539 let the_string = s.as_str();
5540 match abi::lookup(the_string) {
5541 Some(abi) => Some(abi),
5543 let last_span = self.last_span;
5546 &format!("illegal ABI: expected one of [{}], \
5548 abi::all_names().connect(", "),
5559 /// Parse one of the items or view items allowed by the
5560 /// flags; on failure, return IoviNone.
5561 /// NB: this function no longer parses the items inside an
5563 fn parse_item_or_view_item(&mut self,
5564 attrs: Vec<Attribute> ,
5565 macros_allowed: bool)
5567 let nt_item = match self.token {
5568 token::Interpolated(token::NtItem(ref item)) => {
5569 Some((**item).clone())
5576 let mut attrs = attrs;
5577 mem::swap(&mut item.attrs, &mut attrs);
5578 item.attrs.extend(attrs.into_iter());
5579 return IoviItem(P(item));
5584 let lo = self.span.lo;
5586 let visibility = self.parse_visibility();
5588 // must be a view item:
5589 if self.eat_keyword(keywords::Use) {
5590 // USE ITEM (IoviViewItem)
5591 let view_item = self.parse_use();
5592 self.expect(&token::Semi);
5593 return IoviViewItem(ast::ViewItem {
5597 span: mk_sp(lo, self.last_span.hi)
5600 // either a view item or an item:
5601 if self.eat_keyword(keywords::Extern) {
5602 if self.eat_keyword(keywords::Crate) {
5603 return self.parse_item_extern_crate(lo, visibility, attrs);
5606 let opt_abi = self.parse_opt_abi();
5608 if self.eat_keyword(keywords::Fn) {
5609 // EXTERN FUNCTION ITEM
5610 let abi = opt_abi.unwrap_or(abi::C);
5611 let (ident, item_, extra_attrs) =
5612 self.parse_item_fn(Unsafety::Normal, abi);
5613 let last_span = self.last_span;
5614 let item = self.mk_item(lo,
5619 maybe_append(attrs, extra_attrs));
5620 return IoviItem(item);
5621 } else if self.check(&token::OpenDelim(token::Brace)) {
5622 return self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs);
5625 let span = self.span;
5626 let token_str = self.this_token_to_string();
5627 self.span_fatal(span,
5628 &format!("expected `{}` or `fn`, found `{}`", "{",
5632 if self.eat_keyword(keywords::Virtual) {
5633 let span = self.span;
5634 self.span_err(span, "`virtual` structs have been removed from the language");
5637 // the rest are all guaranteed to be items:
5638 if self.token.is_keyword(keywords::Static) {
5641 let m = if self.eat_keyword(keywords::Mut) {MutMutable} else {MutImmutable};
5642 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m));
5643 let last_span = self.last_span;
5644 let item = self.mk_item(lo,
5649 maybe_append(attrs, extra_attrs));
5650 return IoviItem(item);
5652 if self.token.is_keyword(keywords::Const) {
5655 if self.eat_keyword(keywords::Mut) {
5656 let last_span = self.last_span;
5657 self.span_err(last_span, "const globals cannot be mutable");
5658 self.span_help(last_span, "did you mean to declare a static?");
5660 let (ident, item_, extra_attrs) = self.parse_item_const(None);
5661 let last_span = self.last_span;
5662 let item = self.mk_item(lo,
5667 maybe_append(attrs, extra_attrs));
5668 return IoviItem(item);
5670 if self.token.is_keyword(keywords::Unsafe) &&
5671 self.look_ahead(1u, |t| t.is_keyword(keywords::Trait))
5673 // UNSAFE TRAIT ITEM
5674 self.expect_keyword(keywords::Unsafe);
5675 self.expect_keyword(keywords::Trait);
5676 let (ident, item_, extra_attrs) =
5677 self.parse_item_trait(ast::Unsafety::Unsafe);
5678 let last_span = self.last_span;
5679 let item = self.mk_item(lo,
5684 maybe_append(attrs, extra_attrs));
5685 return IoviItem(item);
5687 if self.token.is_keyword(keywords::Unsafe) &&
5688 self.look_ahead(1u, |t| t.is_keyword(keywords::Impl))
5691 self.expect_keyword(keywords::Unsafe);
5692 self.expect_keyword(keywords::Impl);
5693 let (ident, item_, extra_attrs) = self.parse_item_impl(ast::Unsafety::Unsafe);
5694 let last_span = self.last_span;
5695 let item = self.mk_item(lo,
5700 maybe_append(attrs, extra_attrs));
5701 return IoviItem(item);
5703 if self.token.is_keyword(keywords::Fn) {
5706 let (ident, item_, extra_attrs) =
5707 self.parse_item_fn(Unsafety::Normal, abi::Rust);
5708 let last_span = self.last_span;
5709 let item = self.mk_item(lo,
5714 maybe_append(attrs, extra_attrs));
5715 return IoviItem(item);
5717 if self.token.is_keyword(keywords::Unsafe)
5718 && self.look_ahead(1u, |t| *t != token::OpenDelim(token::Brace)) {
5719 // UNSAFE FUNCTION ITEM
5721 let abi = if self.eat_keyword(keywords::Extern) {
5722 self.parse_opt_abi().unwrap_or(abi::C)
5726 self.expect_keyword(keywords::Fn);
5727 let (ident, item_, extra_attrs) =
5728 self.parse_item_fn(Unsafety::Unsafe, abi);
5729 let last_span = self.last_span;
5730 let item = self.mk_item(lo,
5735 maybe_append(attrs, extra_attrs));
5736 return IoviItem(item);
5738 if self.eat_keyword(keywords::Mod) {
5740 let (ident, item_, extra_attrs) =
5741 self.parse_item_mod(&attrs[]);
5742 let last_span = self.last_span;
5743 let item = self.mk_item(lo,
5748 maybe_append(attrs, extra_attrs));
5749 return IoviItem(item);
5751 if self.eat_keyword(keywords::Type) {
5753 let (ident, item_, extra_attrs) = self.parse_item_type();
5754 let last_span = self.last_span;
5755 let item = self.mk_item(lo,
5760 maybe_append(attrs, extra_attrs));
5761 return IoviItem(item);
5763 if self.eat_keyword(keywords::Enum) {
5765 let (ident, item_, extra_attrs) = self.parse_item_enum();
5766 let last_span = self.last_span;
5767 let item = self.mk_item(lo,
5772 maybe_append(attrs, extra_attrs));
5773 return IoviItem(item);
5775 if self.eat_keyword(keywords::Trait) {
5777 let (ident, item_, extra_attrs) =
5778 self.parse_item_trait(ast::Unsafety::Normal);
5779 let last_span = self.last_span;
5780 let item = self.mk_item(lo,
5785 maybe_append(attrs, extra_attrs));
5786 return IoviItem(item);
5788 if self.eat_keyword(keywords::Impl) {
5790 let (ident, item_, extra_attrs) = self.parse_item_impl(ast::Unsafety::Normal);
5791 let last_span = self.last_span;
5792 let item = self.mk_item(lo,
5797 maybe_append(attrs, extra_attrs));
5798 return IoviItem(item);
5800 if self.eat_keyword(keywords::Struct) {
5802 let (ident, item_, extra_attrs) = self.parse_item_struct();
5803 let last_span = self.last_span;
5804 let item = self.mk_item(lo,
5809 maybe_append(attrs, extra_attrs));
5810 return IoviItem(item);
5812 self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility)
5815 /// Parse a foreign item; on failure, return IoviNone.
5816 fn parse_foreign_item(&mut self,
5817 attrs: Vec<Attribute> ,
5818 macros_allowed: bool)
5820 maybe_whole!(iovi self, NtItem);
5821 let lo = self.span.lo;
5823 let visibility = self.parse_visibility();
5825 if self.token.is_keyword(keywords::Static) {
5826 // FOREIGN STATIC ITEM
5827 let item = self.parse_item_foreign_static(visibility, attrs);
5828 return IoviForeignItem(item);
5830 if self.token.is_keyword(keywords::Fn) || self.token.is_keyword(keywords::Unsafe) {
5831 // FOREIGN FUNCTION ITEM
5832 let item = self.parse_item_foreign_fn(visibility, attrs);
5833 return IoviForeignItem(item);
5835 self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility)
5838 /// This is the fall-through for parsing items.
5839 fn parse_macro_use_or_failure(
5841 attrs: Vec<Attribute> ,
5842 macros_allowed: bool,
5844 visibility: Visibility
5845 ) -> ItemOrViewItem {
5846 if macros_allowed && !self.token.is_any_keyword()
5847 && self.look_ahead(1, |t| *t == token::Not)
5848 && (self.look_ahead(2, |t| t.is_plain_ident())
5849 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren))
5850 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) {
5851 // MACRO INVOCATION ITEM
5854 let pth = self.parse_path(NoTypesAllowed);
5855 self.expect(&token::Not);
5857 // a 'special' identifier (like what `macro_rules!` uses)
5858 // is optional. We should eventually unify invoc syntax
5860 let id = if self.token.is_plain_ident() {
5863 token::special_idents::invalid // no special identifier
5865 // eat a matched-delimiter token tree:
5866 let delim = self.expect_open_delim();
5867 let tts = self.parse_seq_to_end(&token::CloseDelim(delim),
5869 |p| p.parse_token_tree());
5870 // single-variant-enum... :
5871 let m = ast::MacInvocTT(pth, tts, EMPTY_CTXT);
5872 let m: ast::Mac = codemap::Spanned { node: m,
5873 span: mk_sp(self.span.lo,
5876 if delim != token::Brace {
5877 if !self.eat(&token::Semi) {
5878 let last_span = self.last_span;
5879 self.span_err(last_span,
5880 "macros that expand to items must either \
5881 be surrounded with braces or followed by \
5886 let item_ = ItemMac(m);
5887 let last_span = self.last_span;
5888 let item = self.mk_item(lo,
5894 return IoviItem(item);
5897 // FAILURE TO PARSE ITEM
5901 let last_span = self.last_span;
5902 self.span_fatal(last_span, "unmatched visibility `pub`");
5905 return IoviNone(attrs);
5908 pub fn parse_item_with_outer_attributes(&mut self) -> Option<P<Item>> {
5909 let attrs = self.parse_outer_attributes();
5910 self.parse_item(attrs)
5913 pub fn parse_item(&mut self, attrs: Vec<Attribute>) -> Option<P<Item>> {
5914 match self.parse_item_or_view_item(attrs, true) {
5915 IoviNone(_) => None,
5917 self.fatal("view items are not allowed here"),
5918 IoviForeignItem(_) =>
5919 self.fatal("foreign items are not allowed here"),
5920 IoviItem(item) => Some(item)
5924 /// Parse a ViewItem, e.g. `use foo::bar` or `extern crate foo`
5925 pub fn parse_view_item(&mut self, attrs: Vec<Attribute>) -> ViewItem {
5926 match self.parse_item_or_view_item(attrs, false) {
5927 IoviViewItem(vi) => vi,
5928 _ => self.fatal("expected `use` or `extern crate`"),
5932 /// Parse, e.g., "use a::b::{z,y}"
5933 fn parse_use(&mut self) -> ViewItem_ {
5934 return ViewItemUse(self.parse_view_path());
5938 /// Matches view_path : MOD? non_global_path as IDENT
5939 /// | MOD? non_global_path MOD_SEP LBRACE RBRACE
5940 /// | MOD? non_global_path MOD_SEP LBRACE ident_seq RBRACE
5941 /// | MOD? non_global_path MOD_SEP STAR
5942 /// | MOD? non_global_path
5943 fn parse_view_path(&mut self) -> P<ViewPath> {
5944 let lo = self.span.lo;
5946 // Allow a leading :: because the paths are absolute either way.
5947 // This occurs with "use $crate::..." in macros.
5948 self.eat(&token::ModSep);
5950 if self.check(&token::OpenDelim(token::Brace)) {
5952 let idents = self.parse_unspanned_seq(
5953 &token::OpenDelim(token::Brace),
5954 &token::CloseDelim(token::Brace),
5955 seq_sep_trailing_allowed(token::Comma),
5956 |p| p.parse_path_list_item());
5957 let path = ast::Path {
5958 span: mk_sp(lo, self.span.hi),
5960 segments: Vec::new()
5962 return P(spanned(lo, self.span.hi,
5963 ViewPathList(path, idents, ast::DUMMY_NODE_ID)));
5966 let first_ident = self.parse_ident();
5967 let mut path = vec!(first_ident);
5968 if let token::ModSep = self.token {
5969 // foo::bar or foo::{a,b,c} or foo::*
5970 while self.check(&token::ModSep) {
5974 token::Ident(i, _) => {
5979 // foo::bar::{a,b,c}
5980 token::OpenDelim(token::Brace) => {
5981 let idents = self.parse_unspanned_seq(
5982 &token::OpenDelim(token::Brace),
5983 &token::CloseDelim(token::Brace),
5984 seq_sep_trailing_allowed(token::Comma),
5985 |p| p.parse_path_list_item()
5987 let path = ast::Path {
5988 span: mk_sp(lo, self.span.hi),
5990 segments: path.into_iter().map(|identifier| {
5992 identifier: identifier,
5993 parameters: ast::PathParameters::none(),
5997 return P(spanned(lo, self.span.hi,
5998 ViewPathList(path, idents, ast::DUMMY_NODE_ID)));
6002 token::BinOp(token::Star) => {
6004 let path = ast::Path {
6005 span: mk_sp(lo, self.span.hi),
6007 segments: path.into_iter().map(|identifier| {
6009 identifier: identifier,
6010 parameters: ast::PathParameters::none(),
6014 return P(spanned(lo, self.span.hi,
6015 ViewPathGlob(path, ast::DUMMY_NODE_ID)));
6022 let mut rename_to = path[path.len() - 1u];
6023 let path = ast::Path {
6024 span: mk_sp(lo, self.last_span.hi),
6026 segments: path.into_iter().map(|identifier| {
6028 identifier: identifier,
6029 parameters: ast::PathParameters::none(),
6033 if self.eat_keyword(keywords::As) {
6034 rename_to = self.parse_ident()
6038 ViewPathSimple(rename_to, path, ast::DUMMY_NODE_ID)))
6041 /// Parses a sequence of items. Stops when it finds program
6042 /// text that can't be parsed as an item
6043 /// - mod_items uses extern_mod_allowed = true
6044 /// - block_tail_ uses extern_mod_allowed = false
6045 fn parse_items_and_view_items(&mut self,
6046 first_item_attrs: Vec<Attribute> ,
6047 mut extern_mod_allowed: bool,
6048 macros_allowed: bool)
6049 -> ParsedItemsAndViewItems {
6050 let mut attrs = first_item_attrs;
6051 attrs.push_all(&self.parse_outer_attributes()[]);
6052 // First, parse view items.
6053 let mut view_items : Vec<ast::ViewItem> = Vec::new();
6054 let mut items = Vec::new();
6056 // I think this code would probably read better as a single
6057 // loop with a mutable three-state-variable (for extern crates,
6058 // view items, and regular items) ... except that because
6059 // of macros, I'd like to delay that entire check until later.
6061 match self.parse_item_or_view_item(attrs, macros_allowed) {
6062 IoviNone(attrs) => {
6063 return ParsedItemsAndViewItems {
6064 attrs_remaining: attrs,
6065 view_items: view_items,
6067 foreign_items: Vec::new()
6070 IoviViewItem(view_item) => {
6071 match view_item.node {
6072 ViewItemUse(..) => {
6073 // `extern crate` must precede `use`.
6074 extern_mod_allowed = false;
6076 ViewItemExternCrate(..) if !extern_mod_allowed => {
6077 self.span_err(view_item.span,
6078 "\"extern crate\" declarations are \
6081 ViewItemExternCrate(..) => {}
6083 view_items.push(view_item);
6087 attrs = self.parse_outer_attributes();
6090 IoviForeignItem(_) => {
6094 attrs = self.parse_outer_attributes();
6097 // Next, parse items.
6099 match self.parse_item_or_view_item(attrs, macros_allowed) {
6100 IoviNone(returned_attrs) => {
6101 attrs = returned_attrs;
6104 IoviViewItem(view_item) => {
6105 attrs = self.parse_outer_attributes();
6106 self.span_err(view_item.span,
6107 "`use` and `extern crate` declarations must precede items");
6110 attrs = self.parse_outer_attributes();
6113 IoviForeignItem(_) => {
6119 ParsedItemsAndViewItems {
6120 attrs_remaining: attrs,
6121 view_items: view_items,
6123 foreign_items: Vec::new()
6127 /// Parses a sequence of foreign items. Stops when it finds program
6128 /// text that can't be parsed as an item
6129 fn parse_foreign_items(&mut self, first_item_attrs: Vec<Attribute> ,
6130 macros_allowed: bool)
6131 -> ParsedItemsAndViewItems {
6132 let mut attrs = first_item_attrs;
6133 attrs.push_all(&self.parse_outer_attributes()[]);
6134 let mut foreign_items = Vec::new();
6136 match self.parse_foreign_item(attrs, macros_allowed) {
6137 IoviNone(returned_attrs) => {
6138 if self.check(&token::CloseDelim(token::Brace)) {
6139 attrs = returned_attrs;
6144 IoviViewItem(view_item) => {
6145 // I think this can't occur:
6146 self.span_err(view_item.span,
6147 "`use` and `extern crate` declarations must precede items");
6150 // FIXME #5668: this will occur for a macro invocation:
6151 self.span_fatal(item.span, "macros cannot expand to foreign items");
6153 IoviForeignItem(foreign_item) => {
6154 foreign_items.push(foreign_item);
6157 attrs = self.parse_outer_attributes();
6160 ParsedItemsAndViewItems {
6161 attrs_remaining: attrs,
6162 view_items: Vec::new(),
6164 foreign_items: foreign_items
6168 /// Parses a source module as a crate. This is the main
6169 /// entry point for the parser.
6170 pub fn parse_crate_mod(&mut self) -> Crate {
6171 let lo = self.span.lo;
6172 // parse the crate's inner attrs, maybe (oops) one
6173 // of the attrs of an item:
6174 let (inner, next) = self.parse_inner_attrs_and_next();
6175 let first_item_outer_attrs = next;
6176 // parse the items inside the crate:
6177 let m = self.parse_mod_items(token::Eof, first_item_outer_attrs, lo);
6182 config: self.cfg.clone(),
6183 span: mk_sp(lo, self.span.lo),
6184 exported_macros: Vec::new(),
6188 pub fn parse_optional_str(&mut self)
6189 -> Option<(InternedString, ast::StrStyle, Option<ast::Name>)> {
6190 let ret = match self.token {
6191 token::Literal(token::Str_(s), suf) => {
6192 (self.id_to_interned_str(s.ident()), ast::CookedStr, suf)
6194 token::Literal(token::StrRaw(s, n), suf) => {
6195 (self.id_to_interned_str(s.ident()), ast::RawStr(n), suf)
6203 pub fn parse_str(&mut self) -> (InternedString, StrStyle) {
6204 match self.parse_optional_str() {
6205 Some((s, style, suf)) => {
6206 let sp = self.last_span;
6207 self.expect_no_suffix(sp, "str literal", suf);
6210 _ => self.fatal("expected string literal")