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::*;
15 use ast::{RegionTyParamBound, TraitTyParamBound, TraitBoundModifier};
16 use ast::{Public, Unsafety};
17 use ast::{Mod, BiAdd, Arg, Arm, Attribute, BindByRef, BindByValue};
18 use ast::{BiBitAnd, BiBitOr, BiBitXor, BiRem, BiLt, BiGt, Block};
19 use ast::{BlockCheckMode, CaptureByRef, CaptureByValue, CaptureClause};
20 use ast::{Crate, CrateConfig, Decl, DeclItem};
21 use ast::{DeclLocal, DefaultBlock, DefaultReturn};
22 use ast::{UnDeref, BiDiv, EMPTY_CTXT, EnumDef, ExplicitSelf};
23 use ast::{Expr, Expr_, ExprAddrOf, ExprMatch, ExprAgain};
24 use ast::{ExprAssign, ExprAssignOp, ExprBinary, ExprBlock, ExprBox};
25 use ast::{ExprBreak, ExprCall, ExprCast};
26 use ast::{ExprField, ExprTupField, ExprClosure, ExprIf, ExprIfLet, ExprIndex};
27 use ast::{ExprLit, ExprLoop, ExprMac, ExprRange};
28 use ast::{ExprMethodCall, ExprParen, ExprPath};
29 use ast::{ExprRepeat, ExprRet, ExprStruct, ExprTup, ExprUnary};
30 use ast::{ExprVec, ExprWhile, ExprWhileLet, ExprForLoop, Field, FnDecl};
31 use ast::{ForeignItem, ForeignItemStatic, ForeignItemFn, ForeignMod, FunctionRetTy};
32 use ast::{Ident, Inherited, ImplItem, Item, Item_, ItemStatic};
33 use ast::{ItemEnum, ItemFn, ItemForeignMod, ItemImpl, ItemConst};
34 use ast::{ItemMac, ItemMod, ItemStruct, ItemTrait, ItemTy, ItemDefaultImpl};
35 use ast::{ItemExternCrate, ItemUse};
36 use ast::{LifetimeDef, Lit, Lit_};
37 use ast::{LitBool, LitChar, LitByte, LitBinary};
38 use ast::{LitStr, LitInt, Local, LocalLet};
39 use ast::{MacStmtWithBraces, MacStmtWithSemicolon, MacStmtWithoutBraces};
40 use ast::{MutImmutable, MutMutable, Mac_, MacInvocTT, MatchSource};
41 use ast::{MutTy, BiMul, Mutability};
42 use ast::{MethodImplItem, NamedField, UnNeg, NoReturn, UnNot};
43 use ast::{Pat, PatEnum, PatIdent, PatLit, PatRange, PatRegion, PatStruct};
44 use ast::{PatTup, PatBox, PatWild, PatWildMulti, PatWildSingle};
45 use ast::{PolyTraitRef, QSelf};
46 use ast::{Return, BiShl, BiShr, Stmt, StmtDecl};
47 use ast::{StmtExpr, StmtSemi, StmtMac, StructDef, StructField};
48 use ast::{StructVariantKind, BiSub, StrStyle};
49 use ast::{SelfExplicit, SelfRegion, SelfStatic, SelfValue};
50 use ast::{Delimited, SequenceRepetition, TokenTree, TraitItem, TraitRef};
51 use ast::{TtDelimited, TtSequence, TtToken};
52 use ast::{TupleVariantKind, Ty, Ty_, TypeBinding};
53 use ast::{TyFixedLengthVec, TyBareFn, TyTypeof, TyInfer};
54 use ast::{TyParam, TyParamBound, TyParen, TyPath, TyPolyTraitRef, TyPtr};
55 use ast::{TyRptr, TyTup, TyU32, TyVec, UnUniq};
56 use ast::{TypeImplItem, TypeTraitItem};
57 use ast::{UnnamedField, UnsafeBlock};
58 use ast::{ViewPath, ViewPathGlob, ViewPathList, ViewPathSimple};
59 use ast::{Visibility, WhereClause};
61 use ast_util::{self, AS_PREC, ident_to_path, operator_prec};
62 use codemap::{self, Span, BytePos, Spanned, spanned, mk_sp};
64 use ext::tt::macro_parser;
66 use parse::attr::ParserAttr;
68 use parse::common::{SeqSep, seq_sep_none, seq_sep_trailing_allowed};
69 use parse::lexer::{Reader, TokenAndSpan};
70 use parse::obsolete::{ParserObsoleteMethods, ObsoleteSyntax};
71 use parse::token::{self, MatchNt, SubstNt, SpecialVarNt, InternedString};
72 use parse::token::{keywords, special_idents, SpecialMacroVar};
73 use parse::{new_sub_parser_from_file, ParseSess};
76 use owned_slice::OwnedSlice;
78 use std::collections::HashSet;
79 use std::io::prelude::*;
81 use std::path::{Path, PathBuf};
86 flags Restrictions: u8 {
87 const UNRESTRICTED = 0b0000,
88 const RESTRICTION_STMT_EXPR = 0b0001,
89 const RESTRICTION_NO_BAR_OP = 0b0010,
90 const RESTRICTION_NO_STRUCT_LITERAL = 0b0100,
95 type ItemInfo = (Ident, Item_, Option<Vec<Attribute> >);
97 /// How to parse a path. There are four different kinds of paths, all of which
98 /// are parsed somewhat differently.
99 #[derive(Copy, PartialEq)]
100 pub enum PathParsingMode {
101 /// A path with no type parameters; e.g. `foo::bar::Baz`
103 /// A path with a lifetime and type parameters, with no double colons
104 /// before the type parameters; e.g. `foo::bar<'a>::Baz<T>`
105 LifetimeAndTypesWithoutColons,
106 /// A path with a lifetime and type parameters with double colons before
107 /// the type parameters; e.g. `foo::bar::<'a>::Baz::<T>`
108 LifetimeAndTypesWithColons,
111 /// How to parse a bound, whether to allow bound modifiers such as `?`.
112 #[derive(Copy, PartialEq)]
113 pub enum BoundParsingMode {
118 /// Possibly accept an `token::Interpolated` expression (a pre-parsed expression
119 /// dropped into the token stream, which happens while parsing the result of
120 /// macro expansion). Placement of these is not as complex as I feared it would
121 /// be. The important thing is to make sure that lookahead doesn't balk at
122 /// `token::Interpolated` tokens.
123 macro_rules! maybe_whole_expr {
126 let found = match $p.token {
127 token::Interpolated(token::NtExpr(ref e)) => {
130 token::Interpolated(token::NtPath(_)) => {
131 // FIXME: The following avoids an issue with lexical borrowck scopes,
132 // but the clone is unfortunate.
133 let pt = match $p.token {
134 token::Interpolated(token::NtPath(ref pt)) => (**pt).clone(),
138 Some($p.mk_expr(span.lo, span.hi, ExprPath(None, pt)))
140 token::Interpolated(token::NtBlock(_)) => {
141 // FIXME: The following avoids an issue with lexical borrowck scopes,
142 // but the clone is unfortunate.
143 let b = match $p.token {
144 token::Interpolated(token::NtBlock(ref b)) => (*b).clone(),
148 Some($p.mk_expr(span.lo, span.hi, ExprBlock(b)))
163 /// As maybe_whole_expr, but for things other than expressions
164 macro_rules! maybe_whole {
165 ($p:expr, $constructor:ident) => (
167 let found = match ($p).token {
168 token::Interpolated(token::$constructor(_)) => {
169 Some(($p).bump_and_get())
173 if let Some(token::Interpolated(token::$constructor(x))) = found {
178 (no_clone $p:expr, $constructor:ident) => (
180 let found = match ($p).token {
181 token::Interpolated(token::$constructor(_)) => {
182 Some(($p).bump_and_get())
186 if let Some(token::Interpolated(token::$constructor(x))) = found {
191 (deref $p:expr, $constructor:ident) => (
193 let found = match ($p).token {
194 token::Interpolated(token::$constructor(_)) => {
195 Some(($p).bump_and_get())
199 if let Some(token::Interpolated(token::$constructor(x))) = found {
204 (Some deref $p:expr, $constructor:ident) => (
206 let found = match ($p).token {
207 token::Interpolated(token::$constructor(_)) => {
208 Some(($p).bump_and_get())
212 if let Some(token::Interpolated(token::$constructor(x))) = found {
213 return Some((*x).clone());
217 (pair_empty $p:expr, $constructor:ident) => (
219 let found = match ($p).token {
220 token::Interpolated(token::$constructor(_)) => {
221 Some(($p).bump_and_get())
225 if let Some(token::Interpolated(token::$constructor(x))) = found {
226 return (Vec::new(), x);
233 fn maybe_append(mut lhs: Vec<Attribute>, rhs: Option<Vec<Attribute>>)
235 if let Some(ref attrs) = rhs {
236 lhs.extend(attrs.iter().cloned())
241 /* ident is handled by common.rs */
243 pub struct Parser<'a> {
244 pub sess: &'a ParseSess,
245 /// the current token:
246 pub token: token::Token,
247 /// the span of the current token:
249 /// the span of the prior token:
251 pub cfg: CrateConfig,
252 /// the previous token or None (only stashed sometimes).
253 pub last_token: Option<Box<token::Token>>,
254 pub buffer: [TokenAndSpan; 4],
255 pub buffer_start: isize,
256 pub buffer_end: isize,
257 pub tokens_consumed: usize,
258 pub restrictions: Restrictions,
259 pub quote_depth: usize, // not (yet) related to the quasiquoter
260 pub reader: Box<Reader+'a>,
261 pub interner: Rc<token::IdentInterner>,
262 /// The set of seen errors about obsolete syntax. Used to suppress
263 /// extra detail when the same error is seen twice
264 pub obsolete_set: HashSet<ObsoleteSyntax>,
265 /// Used to determine the path to externally loaded source files
266 pub mod_path_stack: Vec<InternedString>,
267 /// Stack of spans of open delimiters. Used for error message.
268 pub open_braces: Vec<Span>,
269 /// Flag if this parser "owns" the directory that it is currently parsing
270 /// in. This will affect how nested files are looked up.
271 pub owns_directory: bool,
272 /// Name of the root module this parser originated from. If `None`, then the
273 /// name is not known. This does not change while the parser is descending
274 /// into modules, and sub-parsers have new values for this name.
275 pub root_module_name: Option<String>,
276 pub expected_tokens: Vec<TokenType>,
279 #[derive(PartialEq, Eq, Clone)]
282 Keyword(keywords::Keyword),
287 fn to_string(&self) -> String {
289 TokenType::Token(ref t) => format!("`{}`", Parser::token_to_string(t)),
290 TokenType::Operator => "an operator".to_string(),
291 TokenType::Keyword(kw) => format!("`{}`", token::get_name(kw.to_name())),
296 fn is_plain_ident_or_underscore(t: &token::Token) -> bool {
297 t.is_plain_ident() || *t == token::Underscore
300 impl<'a> Parser<'a> {
301 pub fn new(sess: &'a ParseSess,
302 cfg: ast::CrateConfig,
303 mut rdr: Box<Reader+'a>)
306 let tok0 = rdr.real_token();
308 let placeholder = TokenAndSpan {
309 tok: token::Underscore,
315 interner: token::get_ident_interner(),
331 restrictions: UNRESTRICTED,
333 obsolete_set: HashSet::new(),
334 mod_path_stack: Vec::new(),
335 open_braces: Vec::new(),
336 owns_directory: true,
337 root_module_name: None,
338 expected_tokens: Vec::new(),
342 /// Convert a token to a string using self's reader
343 pub fn token_to_string(token: &token::Token) -> String {
344 pprust::token_to_string(token)
347 /// Convert the current token to a string using self's reader
348 pub fn this_token_to_string(&self) -> String {
349 Parser::token_to_string(&self.token)
352 pub fn unexpected_last(&self, t: &token::Token) -> ! {
353 let token_str = Parser::token_to_string(t);
354 let last_span = self.last_span;
355 self.span_fatal(last_span, &format!("unexpected token: `{}`",
359 pub fn unexpected(&mut self) -> ! {
360 self.expect_one_of(&[], &[]);
364 /// Expect and consume the token t. Signal an error if
365 /// the next token is not t.
366 pub fn expect(&mut self, t: &token::Token) {
367 if self.expected_tokens.is_empty() {
368 if self.token == *t {
371 let token_str = Parser::token_to_string(t);
372 let this_token_str = self.this_token_to_string();
373 self.fatal(&format!("expected `{}`, found `{}`",
378 self.expect_one_of(slice::ref_slice(t), &[]);
382 /// Expect next token to be edible or inedible token. If edible,
383 /// then consume it; if inedible, then return without consuming
384 /// anything. Signal a fatal error if next token is unexpected.
385 pub fn expect_one_of(&mut self,
386 edible: &[token::Token],
387 inedible: &[token::Token]) {
388 fn tokens_to_string(tokens: &[TokenType]) -> String {
389 let mut i = tokens.iter();
390 // This might be a sign we need a connect method on Iterator.
392 .map_or("".to_string(), |t| t.to_string());
393 i.enumerate().fold(b, |mut b, (i, ref a)| {
394 if tokens.len() > 2 && i == tokens.len() - 2 {
396 } else if tokens.len() == 2 && i == tokens.len() - 2 {
401 b.push_str(&*a.to_string());
405 if edible.contains(&self.token) {
407 } else if inedible.contains(&self.token) {
408 // leave it in the input
410 let mut expected = edible.iter().map(|x| TokenType::Token(x.clone()))
411 .collect::<Vec<_>>();
412 expected.extend(inedible.iter().map(|x| TokenType::Token(x.clone())));
413 expected.push_all(&*self.expected_tokens);
414 expected.sort_by(|a, b| a.to_string().cmp(&b.to_string()));
416 let expect = tokens_to_string(&expected[..]);
417 let actual = self.this_token_to_string();
419 &(if expected.len() > 1 {
420 (format!("expected one of {}, found `{}`",
423 } else if expected.len() == 0 {
424 (format!("unexpected token: `{}`",
427 (format!("expected {}, found `{}`",
435 /// Check for erroneous `ident { }`; if matches, signal error and
436 /// recover (without consuming any expected input token). Returns
437 /// true if and only if input was consumed for recovery.
438 pub fn check_for_erroneous_unit_struct_expecting(&mut self, expected: &[token::Token]) -> bool {
439 if self.token == token::OpenDelim(token::Brace)
440 && expected.iter().all(|t| *t != token::OpenDelim(token::Brace))
441 && self.look_ahead(1, |t| *t == token::CloseDelim(token::Brace)) {
442 // matched; signal non-fatal error and recover.
443 let span = self.span;
445 "unit-like struct construction is written with no trailing `{ }`");
446 self.eat(&token::OpenDelim(token::Brace));
447 self.eat(&token::CloseDelim(token::Brace));
454 /// Commit to parsing a complete expression `e` expected to be
455 /// followed by some token from the set edible + inedible. Recover
456 /// from anticipated input errors, discarding erroneous characters.
457 pub fn commit_expr(&mut self, e: &Expr, edible: &[token::Token], inedible: &[token::Token]) {
458 debug!("commit_expr {:?}", e);
459 if let ExprPath(..) = e.node {
460 // might be unit-struct construction; check for recoverableinput error.
461 let mut expected = edible.iter().cloned().collect::<Vec<_>>();
462 expected.push_all(inedible);
463 self.check_for_erroneous_unit_struct_expecting(&expected[..]);
465 self.expect_one_of(edible, inedible)
468 pub fn commit_expr_expecting(&mut self, e: &Expr, edible: token::Token) {
469 self.commit_expr(e, &[edible], &[])
472 /// Commit to parsing a complete statement `s`, which expects to be
473 /// followed by some token from the set edible + inedible. Check
474 /// for recoverable input errors, discarding erroneous characters.
475 pub fn commit_stmt(&mut self, edible: &[token::Token], inedible: &[token::Token]) {
478 .map_or(false, |t| t.is_ident() || t.is_path()) {
479 let mut expected = edible.iter().cloned().collect::<Vec<_>>();
480 expected.push_all(&inedible);
481 self.check_for_erroneous_unit_struct_expecting(&expected);
483 self.expect_one_of(edible, inedible)
486 pub fn commit_stmt_expecting(&mut self, edible: token::Token) {
487 self.commit_stmt(&[edible], &[])
490 pub fn parse_ident(&mut self) -> ast::Ident {
491 self.check_strict_keywords();
492 self.check_reserved_keywords();
494 token::Ident(i, _) => {
498 token::Interpolated(token::NtIdent(..)) => {
499 self.bug("ident interpolation not converted to real token");
502 let token_str = self.this_token_to_string();
503 self.fatal(&format!("expected ident, found `{}`",
509 pub fn parse_ident_or_self_type(&mut self) -> ast::Ident {
510 if self.is_self_type_ident() {
511 self.expect_self_type_ident()
517 pub fn parse_path_list_item(&mut self) -> ast::PathListItem {
518 let lo = self.span.lo;
519 let node = if self.eat_keyword(keywords::SelfValue) {
520 ast::PathListMod { id: ast::DUMMY_NODE_ID }
522 let ident = self.parse_ident();
523 ast::PathListIdent { name: ident, id: ast::DUMMY_NODE_ID }
525 let hi = self.last_span.hi;
526 spanned(lo, hi, node)
529 /// Check if the next token is `tok`, and return `true` if so.
531 /// This method is will automatically add `tok` to `expected_tokens` if `tok` is not
533 pub fn check(&mut self, tok: &token::Token) -> bool {
534 let is_present = self.token == *tok;
535 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
539 /// Consume token 'tok' if it exists. Returns true if the given
540 /// token was present, false otherwise.
541 pub fn eat(&mut self, tok: &token::Token) -> bool {
542 let is_present = self.check(tok);
543 if is_present { self.bump() }
547 pub fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
548 self.expected_tokens.push(TokenType::Keyword(kw));
549 self.token.is_keyword(kw)
552 /// If the next token is the given keyword, eat it and return
553 /// true. Otherwise, return false.
554 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
555 if self.check_keyword(kw) {
563 pub fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
564 if self.token.is_keyword(kw) {
572 /// If the given word is not a keyword, signal an error.
573 /// If the next token is not the given word, signal an error.
574 /// Otherwise, eat it.
575 pub fn expect_keyword(&mut self, kw: keywords::Keyword) {
576 if !self.eat_keyword(kw) {
577 self.expect_one_of(&[], &[]);
581 /// Signal an error if the given string is a strict keyword
582 pub fn check_strict_keywords(&mut self) {
583 if self.token.is_strict_keyword() {
584 let token_str = self.this_token_to_string();
585 let span = self.span;
587 &format!("expected identifier, found keyword `{}`",
592 /// Signal an error if the current token is a reserved keyword
593 pub fn check_reserved_keywords(&mut self) {
594 if self.token.is_reserved_keyword() {
595 let token_str = self.this_token_to_string();
596 self.fatal(&format!("`{}` is a reserved keyword",
601 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
602 /// `&` and continue. If an `&` is not seen, signal an error.
603 fn expect_and(&mut self) {
604 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
606 token::BinOp(token::And) => self.bump(),
608 let span = self.span;
609 let lo = span.lo + BytePos(1);
610 self.replace_token(token::BinOp(token::And), lo, span.hi)
613 self.expect_one_of(&[], &[]);
618 pub fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
620 None => {/* everything ok */}
622 let text = suf.as_str();
624 self.span_bug(sp, "found empty literal suffix in Some")
626 self.span_err(sp, &*format!("{} with a suffix is illegal", kind));
632 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
633 /// `<` and continue. If a `<` is not seen, return false.
635 /// This is meant to be used when parsing generics on a path to get the
637 fn eat_lt(&mut self) -> bool {
638 self.expected_tokens.push(TokenType::Token(token::Lt));
640 token::Lt => { self.bump(); true }
641 token::BinOp(token::Shl) => {
642 let span = self.span;
643 let lo = span.lo + BytePos(1);
644 self.replace_token(token::Lt, lo, span.hi);
651 fn expect_lt(&mut self) {
653 self.expect_one_of(&[], &[]);
657 /// Expect and consume a GT. if a >> is seen, replace it
658 /// with a single > and continue. If a GT is not seen,
660 pub fn expect_gt(&mut self) {
661 self.expected_tokens.push(TokenType::Token(token::Gt));
663 token::Gt => self.bump(),
664 token::BinOp(token::Shr) => {
665 let span = self.span;
666 let lo = span.lo + BytePos(1);
667 self.replace_token(token::Gt, lo, span.hi)
669 token::BinOpEq(token::Shr) => {
670 let span = self.span;
671 let lo = span.lo + BytePos(1);
672 self.replace_token(token::Ge, lo, span.hi)
675 let span = self.span;
676 let lo = span.lo + BytePos(1);
677 self.replace_token(token::Eq, lo, span.hi)
680 let gt_str = Parser::token_to_string(&token::Gt);
681 let this_token_str = self.this_token_to_string();
682 self.fatal(&format!("expected `{}`, found `{}`",
689 pub fn parse_seq_to_before_gt_or_return<T, F>(&mut self,
690 sep: Option<token::Token>,
692 -> (OwnedSlice<T>, bool) where
693 F: FnMut(&mut Parser) -> Option<T>,
695 let mut v = Vec::new();
696 // This loop works by alternating back and forth between parsing types
697 // and commas. For example, given a string `A, B,>`, the parser would
698 // first parse `A`, then a comma, then `B`, then a comma. After that it
699 // would encounter a `>` and stop. This lets the parser handle trailing
700 // commas in generic parameters, because it can stop either after
701 // parsing a type or after parsing a comma.
703 if self.check(&token::Gt)
704 || self.token == token::BinOp(token::Shr)
705 || self.token == token::Ge
706 || self.token == token::BinOpEq(token::Shr) {
712 Some(result) => v.push(result),
713 None => return (OwnedSlice::from_vec(v), true)
716 sep.as_ref().map(|t| self.expect(t));
719 return (OwnedSlice::from_vec(v), false);
722 /// Parse a sequence bracketed by '<' and '>', stopping
724 pub fn parse_seq_to_before_gt<T, F>(&mut self,
725 sep: Option<token::Token>,
727 -> OwnedSlice<T> where
728 F: FnMut(&mut Parser) -> T,
730 let (result, returned) = self.parse_seq_to_before_gt_or_return(sep, |p| Some(f(p)));
735 pub fn parse_seq_to_gt<T, F>(&mut self,
736 sep: Option<token::Token>,
738 -> OwnedSlice<T> where
739 F: FnMut(&mut Parser) -> T,
741 let v = self.parse_seq_to_before_gt(sep, f);
746 pub fn parse_seq_to_gt_or_return<T, F>(&mut self,
747 sep: Option<token::Token>,
749 -> (OwnedSlice<T>, bool) where
750 F: FnMut(&mut Parser) -> Option<T>,
752 let (v, returned) = self.parse_seq_to_before_gt_or_return(sep, f);
756 return (v, returned);
759 /// Parse a sequence, including the closing delimiter. The function
760 /// f must consume tokens until reaching the next separator or
762 pub fn parse_seq_to_end<T, F>(&mut self,
767 F: FnMut(&mut Parser) -> T,
769 let val = self.parse_seq_to_before_end(ket, sep, f);
774 /// Parse a sequence, not including the closing delimiter. The function
775 /// f must consume tokens until reaching the next separator or
777 pub fn parse_seq_to_before_end<T, F>(&mut self,
782 F: FnMut(&mut Parser) -> T,
784 let mut first: bool = true;
786 while self.token != *ket {
789 if first { first = false; }
790 else { self.expect(t); }
794 if sep.trailing_sep_allowed && self.check(ket) { break; }
800 /// Parse a sequence, including the closing delimiter. The function
801 /// f must consume tokens until reaching the next separator or
803 pub fn parse_unspanned_seq<T, F>(&mut self,
809 F: FnMut(&mut Parser) -> T,
812 let result = self.parse_seq_to_before_end(ket, sep, f);
817 /// Parse a sequence parameter of enum variant. For consistency purposes,
818 /// these should not be empty.
819 pub fn parse_enum_variant_seq<T, F>(&mut self,
825 F: FnMut(&mut Parser) -> T,
827 let result = self.parse_unspanned_seq(bra, ket, sep, f);
828 if result.is_empty() {
829 let last_span = self.last_span;
830 self.span_err(last_span,
831 "nullary enum variants are written with no trailing `( )`");
836 // NB: Do not use this function unless you actually plan to place the
837 // spanned list in the AST.
838 pub fn parse_seq<T, F>(&mut self,
843 -> Spanned<Vec<T>> where
844 F: FnMut(&mut Parser) -> T,
846 let lo = self.span.lo;
848 let result = self.parse_seq_to_before_end(ket, sep, f);
849 let hi = self.span.hi;
851 spanned(lo, hi, result)
854 /// Advance the parser by one token
855 pub fn bump(&mut self) {
856 self.last_span = self.span;
857 // Stash token for error recovery (sometimes; clone is not necessarily cheap).
858 self.last_token = if self.token.is_ident() || self.token.is_path() {
859 Some(box self.token.clone())
863 let next = if self.buffer_start == self.buffer_end {
864 self.reader.real_token()
866 // Avoid token copies with `replace`.
867 let buffer_start = self.buffer_start as usize;
868 let next_index = (buffer_start + 1) & 3;
869 self.buffer_start = next_index as isize;
871 let placeholder = TokenAndSpan {
872 tok: token::Underscore,
875 mem::replace(&mut self.buffer[buffer_start], placeholder)
878 self.token = next.tok;
879 self.tokens_consumed += 1;
880 self.expected_tokens.clear();
881 // check after each token
882 self.check_unknown_macro_variable();
885 /// Advance the parser by one token and return the bumped token.
886 pub fn bump_and_get(&mut self) -> token::Token {
887 let old_token = mem::replace(&mut self.token, token::Underscore);
892 /// EFFECT: replace the current token and span with the given one
893 pub fn replace_token(&mut self,
897 self.last_span = mk_sp(self.span.lo, lo);
899 self.span = mk_sp(lo, hi);
901 pub fn buffer_length(&mut self) -> isize {
902 if self.buffer_start <= self.buffer_end {
903 return self.buffer_end - self.buffer_start;
905 return (4 - self.buffer_start) + self.buffer_end;
907 pub fn look_ahead<R, F>(&mut self, distance: usize, f: F) -> R where
908 F: FnOnce(&token::Token) -> R,
910 let dist = distance as isize;
911 while self.buffer_length() < dist {
912 self.buffer[self.buffer_end as usize] = self.reader.real_token();
913 self.buffer_end = (self.buffer_end + 1) & 3;
915 f(&self.buffer[((self.buffer_start + dist - 1) & 3) as usize].tok)
917 pub fn fatal(&self, m: &str) -> ! {
918 self.sess.span_diagnostic.span_fatal(self.span, m)
920 pub fn span_fatal(&self, sp: Span, m: &str) -> ! {
921 self.sess.span_diagnostic.span_fatal(sp, m)
923 pub fn span_fatal_help(&self, sp: Span, m: &str, help: &str) -> ! {
924 self.span_err(sp, m);
925 self.fileline_help(sp, help);
926 panic!(diagnostic::FatalError);
928 pub fn span_note(&self, sp: Span, m: &str) {
929 self.sess.span_diagnostic.span_note(sp, m)
931 pub fn span_help(&self, sp: Span, m: &str) {
932 self.sess.span_diagnostic.span_help(sp, m)
934 pub fn fileline_help(&self, sp: Span, m: &str) {
935 self.sess.span_diagnostic.fileline_help(sp, m)
937 pub fn bug(&self, m: &str) -> ! {
938 self.sess.span_diagnostic.span_bug(self.span, m)
940 pub fn warn(&self, m: &str) {
941 self.sess.span_diagnostic.span_warn(self.span, m)
943 pub fn span_warn(&self, sp: Span, m: &str) {
944 self.sess.span_diagnostic.span_warn(sp, m)
946 pub fn span_err(&self, sp: Span, m: &str) {
947 self.sess.span_diagnostic.span_err(sp, m)
949 pub fn span_bug(&self, sp: Span, m: &str) -> ! {
950 self.sess.span_diagnostic.span_bug(sp, m)
952 pub fn abort_if_errors(&self) {
953 self.sess.span_diagnostic.handler().abort_if_errors();
956 pub fn id_to_interned_str(&mut self, id: Ident) -> InternedString {
960 /// Is the current token one of the keywords that signals a bare function
962 pub fn token_is_bare_fn_keyword(&mut self) -> bool {
963 self.check_keyword(keywords::Fn) ||
964 self.check_keyword(keywords::Unsafe) ||
965 self.check_keyword(keywords::Extern)
968 pub fn get_lifetime(&mut self) -> ast::Ident {
970 token::Lifetime(ref ident) => *ident,
971 _ => self.bug("not a lifetime"),
975 pub fn parse_for_in_type(&mut self) -> Ty_ {
977 Parses whatever can come after a `for` keyword in a type.
978 The `for` has already been consumed.
986 - for <'lt> [unsafe] [extern "ABI"] fn (S) -> T
987 - for <'lt> path::foo(a, b)
992 let lo = self.span.lo;
994 let lifetime_defs = self.parse_late_bound_lifetime_defs();
996 // examine next token to decide to do
997 if self.token_is_bare_fn_keyword() {
998 self.parse_ty_bare_fn(lifetime_defs)
1000 let hi = self.span.hi;
1001 let trait_ref = self.parse_trait_ref();
1002 let poly_trait_ref = ast::PolyTraitRef { bound_lifetimes: lifetime_defs,
1003 trait_ref: trait_ref,
1004 span: mk_sp(lo, hi)};
1005 let other_bounds = if self.eat(&token::BinOp(token::Plus)) {
1006 self.parse_ty_param_bounds(BoundParsingMode::Bare)
1011 Some(TraitTyParamBound(poly_trait_ref, TraitBoundModifier::None)).into_iter()
1012 .chain(other_bounds.into_vec().into_iter())
1014 ast::TyPolyTraitRef(all_bounds)
1018 pub fn parse_ty_path(&mut self) -> Ty_ {
1019 TyPath(None, self.parse_path(LifetimeAndTypesWithoutColons))
1022 /// parse a TyBareFn type:
1023 pub fn parse_ty_bare_fn(&mut self, lifetime_defs: Vec<ast::LifetimeDef>) -> Ty_ {
1026 [unsafe] [extern "ABI"] fn <'lt> (S) -> T
1027 ^~~~^ ^~~~^ ^~~~^ ^~^ ^
1030 | | | Argument types
1036 let unsafety = self.parse_unsafety();
1037 let abi = if self.eat_keyword(keywords::Extern) {
1038 self.parse_opt_abi().unwrap_or(abi::C)
1043 self.expect_keyword(keywords::Fn);
1044 let (inputs, variadic) = self.parse_fn_args(false, true);
1045 let ret_ty = self.parse_ret_ty();
1046 let decl = P(FnDecl {
1051 TyBareFn(P(BareFnTy {
1054 lifetimes: lifetime_defs,
1059 /// Parses an obsolete closure kind (`&:`, `&mut:`, or `:`).
1060 pub fn parse_obsolete_closure_kind(&mut self) {
1061 let lo = self.span.lo;
1063 self.check(&token::BinOp(token::And)) &&
1064 self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
1065 self.look_ahead(2, |t| *t == token::Colon)
1071 self.token == token::BinOp(token::And) &&
1072 self.look_ahead(1, |t| *t == token::Colon)
1077 self.eat(&token::Colon)
1084 let span = mk_sp(lo, self.span.hi);
1085 self.obsolete(span, ObsoleteSyntax::ClosureKind);
1088 pub fn parse_unsafety(&mut self) -> Unsafety {
1089 if self.eat_keyword(keywords::Unsafe) {
1090 return Unsafety::Unsafe;
1092 return Unsafety::Normal;
1096 /// Parse the items in a trait declaration
1097 pub fn parse_trait_items(&mut self) -> Vec<P<TraitItem>> {
1098 self.parse_unspanned_seq(
1099 &token::OpenDelim(token::Brace),
1100 &token::CloseDelim(token::Brace),
1104 let mut attrs = p.parse_outer_attributes();
1106 let (name, node) = if p.eat_keyword(keywords::Type) {
1107 let TyParam {ident, bounds, default, ..} = p.parse_ty_param();
1108 p.expect(&token::Semi);
1109 (ident, TypeTraitItem(bounds, default))
1111 let style = p.parse_unsafety();
1112 let abi = if p.eat_keyword(keywords::Extern) {
1113 p.parse_opt_abi().unwrap_or(abi::C)
1117 p.expect_keyword(keywords::Fn);
1119 let ident = p.parse_ident();
1120 let mut generics = p.parse_generics();
1122 let (explicit_self, d) = p.parse_fn_decl_with_self(|p| {
1123 // This is somewhat dubious; We don't want to allow
1124 // argument names to be left off if there is a
1126 p.parse_arg_general(false)
1129 generics.where_clause = p.parse_where_clause();
1130 let sig = ast::MethodSig {
1135 explicit_self: explicit_self,
1138 let body = match p.token {
1141 debug!("parse_trait_methods(): parsing required method");
1144 token::OpenDelim(token::Brace) => {
1145 debug!("parse_trait_methods(): parsing provided method");
1146 let (inner_attrs, body) =
1147 p.parse_inner_attrs_and_block();
1148 attrs.push_all(&inner_attrs[..]);
1153 let token_str = p.this_token_to_string();
1154 p.fatal(&format!("expected `;` or `{{`, found `{}`",
1158 (ident, ast::MethodTraitItem(sig, body))
1162 id: ast::DUMMY_NODE_ID,
1166 span: mk_sp(lo, p.last_span.hi),
1171 /// Parse a possibly mutable type
1172 pub fn parse_mt(&mut self) -> MutTy {
1173 let mutbl = self.parse_mutability();
1174 let t = self.parse_ty();
1175 MutTy { ty: t, mutbl: mutbl }
1178 /// Parse optional return type [ -> TY ] in function decl
1179 pub fn parse_ret_ty(&mut self) -> FunctionRetTy {
1180 if self.eat(&token::RArrow) {
1181 if self.eat(&token::Not) {
1184 Return(self.parse_ty())
1187 let pos = self.span.lo;
1188 DefaultReturn(mk_sp(pos, pos))
1192 /// Parse a type in a context where `T1+T2` is allowed.
1193 pub fn parse_ty_sum(&mut self) -> P<Ty> {
1194 let lo = self.span.lo;
1195 let lhs = self.parse_ty();
1197 if !self.eat(&token::BinOp(token::Plus)) {
1201 let bounds = self.parse_ty_param_bounds(BoundParsingMode::Bare);
1203 // In type grammar, `+` is treated like a binary operator,
1204 // and hence both L and R side are required.
1205 if bounds.len() == 0 {
1206 let last_span = self.last_span;
1207 self.span_err(last_span,
1208 "at least one type parameter bound \
1209 must be specified");
1212 let sp = mk_sp(lo, self.last_span.hi);
1213 let sum = ast::TyObjectSum(lhs, bounds);
1214 P(Ty {id: ast::DUMMY_NODE_ID, node: sum, span: sp})
1218 pub fn parse_ty(&mut self) -> P<Ty> {
1219 maybe_whole!(no_clone self, NtTy);
1221 let lo = self.span.lo;
1223 let t = if self.check(&token::OpenDelim(token::Paren)) {
1226 // (t) is a parenthesized ty
1227 // (t,) is the type of a tuple with only one field,
1229 let mut ts = vec![];
1230 let mut last_comma = false;
1231 while self.token != token::CloseDelim(token::Paren) {
1232 ts.push(self.parse_ty_sum());
1233 if self.check(&token::Comma) {
1242 self.expect(&token::CloseDelim(token::Paren));
1243 if ts.len() == 1 && !last_comma {
1244 TyParen(ts.into_iter().nth(0).unwrap())
1248 } else if self.check(&token::BinOp(token::Star)) {
1249 // STAR POINTER (bare pointer?)
1251 TyPtr(self.parse_ptr())
1252 } else if self.check(&token::OpenDelim(token::Bracket)) {
1254 self.expect(&token::OpenDelim(token::Bracket));
1255 let t = self.parse_ty_sum();
1257 // Parse the `; e` in `[ i32; e ]`
1258 // where `e` is a const expression
1259 let t = match self.maybe_parse_fixed_length_of_vec() {
1261 Some(suffix) => TyFixedLengthVec(t, suffix)
1263 self.expect(&token::CloseDelim(token::Bracket));
1265 } else if self.check(&token::BinOp(token::And)) ||
1266 self.token == token::AndAnd {
1269 self.parse_borrowed_pointee()
1270 } else if self.check_keyword(keywords::For) {
1271 self.parse_for_in_type()
1272 } else if self.token_is_bare_fn_keyword() {
1274 self.parse_ty_bare_fn(Vec::new())
1275 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1277 // In order to not be ambiguous, the type must be surrounded by parens.
1278 self.expect(&token::OpenDelim(token::Paren));
1279 let e = self.parse_expr();
1280 self.expect(&token::CloseDelim(token::Paren));
1282 } else if self.eat_lt() {
1283 // QUALIFIED PATH `<TYPE as TRAIT_REF>::item`
1284 let self_type = self.parse_ty_sum();
1286 let mut path = if self.eat_keyword(keywords::As) {
1287 self.parse_path(LifetimeAndTypesWithoutColons)
1298 position: path.segments.len()
1301 self.expect(&token::Gt);
1302 self.expect(&token::ModSep);
1304 path.segments.push(ast::PathSegment {
1305 identifier: self.parse_ident(),
1306 parameters: ast::PathParameters::none()
1309 if path.segments.len() == 1 {
1310 path.span.lo = self.last_span.lo;
1312 path.span.hi = self.last_span.hi;
1314 TyPath(Some(qself), path)
1315 } else if self.check(&token::ModSep) ||
1316 self.token.is_ident() ||
1317 self.token.is_path() {
1319 self.parse_ty_path()
1320 } else if self.eat(&token::Underscore) {
1321 // TYPE TO BE INFERRED
1324 let this_token_str = self.this_token_to_string();
1325 let msg = format!("expected type, found `{}`", this_token_str);
1326 self.fatal(&msg[..]);
1329 let sp = mk_sp(lo, self.last_span.hi);
1330 P(Ty {id: ast::DUMMY_NODE_ID, node: t, span: sp})
1333 pub fn parse_borrowed_pointee(&mut self) -> Ty_ {
1334 // look for `&'lt` or `&'foo ` and interpret `foo` as the region name:
1335 let opt_lifetime = self.parse_opt_lifetime();
1337 let mt = self.parse_mt();
1338 return TyRptr(opt_lifetime, mt);
1341 pub fn parse_ptr(&mut self) -> MutTy {
1342 let mutbl = if self.eat_keyword(keywords::Mut) {
1344 } else if self.eat_keyword(keywords::Const) {
1347 let span = self.last_span;
1349 "bare raw pointers are no longer allowed, you should \
1350 likely use `*mut T`, but otherwise `*T` is now \
1351 known as `*const T`");
1354 let t = self.parse_ty();
1355 MutTy { ty: t, mutbl: mutbl }
1358 pub fn is_named_argument(&mut self) -> bool {
1359 let offset = match self.token {
1360 token::BinOp(token::And) => 1,
1362 _ if self.token.is_keyword(keywords::Mut) => 1,
1366 debug!("parser is_named_argument offset:{}", offset);
1369 is_plain_ident_or_underscore(&self.token)
1370 && self.look_ahead(1, |t| *t == token::Colon)
1372 self.look_ahead(offset, |t| is_plain_ident_or_underscore(t))
1373 && self.look_ahead(offset + 1, |t| *t == token::Colon)
1377 /// This version of parse arg doesn't necessarily require
1378 /// identifier names.
1379 pub fn parse_arg_general(&mut self, require_name: bool) -> Arg {
1380 let pat = if require_name || self.is_named_argument() {
1381 debug!("parse_arg_general parse_pat (require_name:{})",
1383 let pat = self.parse_pat();
1385 self.expect(&token::Colon);
1388 debug!("parse_arg_general ident_to_pat");
1389 ast_util::ident_to_pat(ast::DUMMY_NODE_ID,
1391 special_idents::invalid)
1394 let t = self.parse_ty_sum();
1399 id: ast::DUMMY_NODE_ID,
1403 /// Parse a single function argument
1404 pub fn parse_arg(&mut self) -> Arg {
1405 self.parse_arg_general(true)
1408 /// Parse an argument in a lambda header e.g. |arg, arg|
1409 pub fn parse_fn_block_arg(&mut self) -> Arg {
1410 let pat = self.parse_pat();
1411 let t = if self.eat(&token::Colon) {
1415 id: ast::DUMMY_NODE_ID,
1417 span: mk_sp(self.span.lo, self.span.hi),
1423 id: ast::DUMMY_NODE_ID
1427 pub fn maybe_parse_fixed_length_of_vec(&mut self) -> Option<P<ast::Expr>> {
1428 if self.check(&token::Semi) {
1430 Some(self.parse_expr())
1436 /// Matches token_lit = LIT_INTEGER | ...
1437 pub fn lit_from_token(&self, tok: &token::Token) -> Lit_ {
1439 token::Interpolated(token::NtExpr(ref v)) => {
1441 ExprLit(ref lit) => { lit.node.clone() }
1442 _ => { self.unexpected_last(tok); }
1445 token::Literal(lit, suf) => {
1446 let (suffix_illegal, out) = match lit {
1447 token::Byte(i) => (true, LitByte(parse::byte_lit(i.as_str()).0)),
1448 token::Char(i) => (true, LitChar(parse::char_lit(i.as_str()).0)),
1450 // there are some valid suffixes for integer and
1451 // float literals, so all the handling is done
1453 token::Integer(s) => {
1454 (false, parse::integer_lit(s.as_str(),
1455 suf.as_ref().map(|s| s.as_str()),
1456 &self.sess.span_diagnostic,
1459 token::Float(s) => {
1460 (false, parse::float_lit(s.as_str(),
1461 suf.as_ref().map(|s| s.as_str()),
1462 &self.sess.span_diagnostic,
1468 LitStr(token::intern_and_get_ident(&parse::str_lit(s.as_str())),
1471 token::StrRaw(s, n) => {
1474 token::intern_and_get_ident(&parse::raw_str_lit(s.as_str())),
1478 (true, LitBinary(parse::binary_lit(i.as_str()))),
1479 token::BinaryRaw(i, _) =>
1481 LitBinary(Rc::new(i.as_str().as_bytes().iter().cloned().collect()))),
1485 let sp = self.last_span;
1486 self.expect_no_suffix(sp, &*format!("{} literal", lit.short_name()), suf)
1491 _ => { self.unexpected_last(tok); }
1495 /// Matches lit = true | false | token_lit
1496 pub fn parse_lit(&mut self) -> Lit {
1497 let lo = self.span.lo;
1498 let lit = if self.eat_keyword(keywords::True) {
1500 } else if self.eat_keyword(keywords::False) {
1503 let token = self.bump_and_get();
1504 let lit = self.lit_from_token(&token);
1507 codemap::Spanned { node: lit, span: mk_sp(lo, self.last_span.hi) }
1510 /// matches '-' lit | lit
1511 pub fn parse_literal_maybe_minus(&mut self) -> P<Expr> {
1512 let minus_lo = self.span.lo;
1513 let minus_present = self.eat(&token::BinOp(token::Minus));
1515 let lo = self.span.lo;
1516 let literal = P(self.parse_lit());
1517 let hi = self.span.hi;
1518 let expr = self.mk_expr(lo, hi, ExprLit(literal));
1521 let minus_hi = self.span.hi;
1522 let unary = self.mk_unary(UnNeg, expr);
1523 self.mk_expr(minus_lo, minus_hi, unary)
1529 /// Parses a path and optional type parameter bounds, depending on the
1530 /// mode. The `mode` parameter determines whether lifetimes, types, and/or
1531 /// bounds are permitted and whether `::` must precede type parameter
1533 pub fn parse_path(&mut self, mode: PathParsingMode) -> ast::Path {
1534 // Check for a whole path...
1535 let found = match self.token {
1536 token::Interpolated(token::NtPath(_)) => Some(self.bump_and_get()),
1539 if let Some(token::Interpolated(token::NtPath(box path))) = found {
1543 let lo = self.span.lo;
1544 let is_global = self.eat(&token::ModSep);
1546 // Parse any number of segments and bound sets. A segment is an
1547 // identifier followed by an optional lifetime and a set of types.
1548 // A bound set is a set of type parameter bounds.
1549 let segments = match mode {
1550 LifetimeAndTypesWithoutColons => {
1551 self.parse_path_segments_without_colons()
1553 LifetimeAndTypesWithColons => {
1554 self.parse_path_segments_with_colons()
1557 self.parse_path_segments_without_types()
1561 // Assemble the span.
1562 let span = mk_sp(lo, self.last_span.hi);
1564 // Assemble the result.
1573 /// - `a::b<T,U>::c<V,W>`
1574 /// - `a::b<T,U>::c(V) -> W`
1575 /// - `a::b<T,U>::c(V)`
1576 pub fn parse_path_segments_without_colons(&mut self) -> Vec<ast::PathSegment> {
1577 let mut segments = Vec::new();
1579 // First, parse an identifier.
1580 let identifier = self.parse_ident_or_self_type();
1582 // Parse types, optionally.
1583 let parameters = if self.eat_lt() {
1584 let (lifetimes, types, bindings) = self.parse_generic_values_after_lt();
1586 ast::AngleBracketedParameters(ast::AngleBracketedParameterData {
1587 lifetimes: lifetimes,
1588 types: OwnedSlice::from_vec(types),
1589 bindings: OwnedSlice::from_vec(bindings),
1591 } else if self.eat(&token::OpenDelim(token::Paren)) {
1592 let lo = self.last_span.lo;
1594 let inputs = self.parse_seq_to_end(
1595 &token::CloseDelim(token::Paren),
1596 seq_sep_trailing_allowed(token::Comma),
1597 |p| p.parse_ty_sum());
1599 let output_ty = if self.eat(&token::RArrow) {
1600 Some(self.parse_ty())
1605 let hi = self.last_span.hi;
1607 ast::ParenthesizedParameters(ast::ParenthesizedParameterData {
1608 span: mk_sp(lo, hi),
1613 ast::PathParameters::none()
1616 // Assemble and push the result.
1617 segments.push(ast::PathSegment { identifier: identifier,
1618 parameters: parameters });
1620 // Continue only if we see a `::`
1621 if !self.eat(&token::ModSep) {
1628 /// - `a::b::<T,U>::c`
1629 pub fn parse_path_segments_with_colons(&mut self) -> Vec<ast::PathSegment> {
1630 let mut segments = Vec::new();
1632 // First, parse an identifier.
1633 let identifier = self.parse_ident_or_self_type();
1635 // If we do not see a `::`, stop.
1636 if !self.eat(&token::ModSep) {
1637 segments.push(ast::PathSegment {
1638 identifier: identifier,
1639 parameters: ast::PathParameters::none()
1644 // Check for a type segment.
1646 // Consumed `a::b::<`, go look for types
1647 let (lifetimes, types, bindings) = self.parse_generic_values_after_lt();
1648 segments.push(ast::PathSegment {
1649 identifier: identifier,
1650 parameters: ast::AngleBracketedParameters(ast::AngleBracketedParameterData {
1651 lifetimes: lifetimes,
1652 types: OwnedSlice::from_vec(types),
1653 bindings: OwnedSlice::from_vec(bindings),
1657 // Consumed `a::b::<T,U>`, check for `::` before proceeding
1658 if !self.eat(&token::ModSep) {
1662 // Consumed `a::`, go look for `b`
1663 segments.push(ast::PathSegment {
1664 identifier: identifier,
1665 parameters: ast::PathParameters::none(),
1674 pub fn parse_path_segments_without_types(&mut self) -> Vec<ast::PathSegment> {
1675 let mut segments = Vec::new();
1677 // First, parse an identifier.
1678 let identifier = self.parse_ident_or_self_type();
1680 // Assemble and push the result.
1681 segments.push(ast::PathSegment {
1682 identifier: identifier,
1683 parameters: ast::PathParameters::none()
1686 // If we do not see a `::`, stop.
1687 if !self.eat(&token::ModSep) {
1693 /// parses 0 or 1 lifetime
1694 pub fn parse_opt_lifetime(&mut self) -> Option<ast::Lifetime> {
1696 token::Lifetime(..) => {
1697 Some(self.parse_lifetime())
1705 /// Parses a single lifetime
1706 /// Matches lifetime = LIFETIME
1707 pub fn parse_lifetime(&mut self) -> ast::Lifetime {
1709 token::Lifetime(i) => {
1710 let span = self.span;
1712 return ast::Lifetime {
1713 id: ast::DUMMY_NODE_ID,
1719 self.fatal(&format!("expected a lifetime name"));
1724 /// Parses `lifetime_defs = [ lifetime_defs { ',' lifetime_defs } ]` where `lifetime_def =
1725 /// lifetime [':' lifetimes]`
1726 pub fn parse_lifetime_defs(&mut self) -> Vec<ast::LifetimeDef> {
1728 let mut res = Vec::new();
1731 token::Lifetime(_) => {
1732 let lifetime = self.parse_lifetime();
1734 if self.eat(&token::Colon) {
1735 self.parse_lifetimes(token::BinOp(token::Plus))
1739 res.push(ast::LifetimeDef { lifetime: lifetime,
1749 token::Comma => { self.bump(); }
1750 token::Gt => { return res; }
1751 token::BinOp(token::Shr) => { return res; }
1753 let this_token_str = self.this_token_to_string();
1754 let msg = format!("expected `,` or `>` after lifetime \
1757 self.fatal(&msg[..]);
1763 /// matches lifetimes = ( lifetime ) | ( lifetime , lifetimes ) actually, it matches the empty
1764 /// one too, but putting that in there messes up the grammar....
1766 /// Parses zero or more comma separated lifetimes. Expects each lifetime to be followed by
1767 /// either a comma or `>`. Used when parsing type parameter lists, where we expect something
1768 /// like `<'a, 'b, T>`.
1769 pub fn parse_lifetimes(&mut self, sep: token::Token) -> Vec<ast::Lifetime> {
1771 let mut res = Vec::new();
1774 token::Lifetime(_) => {
1775 res.push(self.parse_lifetime());
1782 if self.token != sep {
1790 /// Parse mutability declaration (mut/const/imm)
1791 pub fn parse_mutability(&mut self) -> Mutability {
1792 if self.eat_keyword(keywords::Mut) {
1799 /// Parse ident COLON expr
1800 pub fn parse_field(&mut self) -> Field {
1801 let lo = self.span.lo;
1802 let i = self.parse_ident();
1803 let hi = self.last_span.hi;
1804 self.expect(&token::Colon);
1805 let e = self.parse_expr();
1807 ident: spanned(lo, hi, i),
1808 span: mk_sp(lo, e.span.hi),
1813 pub fn mk_expr(&mut self, lo: BytePos, hi: BytePos, node: Expr_) -> P<Expr> {
1815 id: ast::DUMMY_NODE_ID,
1817 span: mk_sp(lo, hi),
1821 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::Expr_ {
1822 ExprUnary(unop, expr)
1825 pub fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::Expr_ {
1826 ExprBinary(binop, lhs, rhs)
1829 pub fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::Expr_ {
1833 fn mk_method_call(&mut self,
1834 ident: ast::SpannedIdent,
1838 ExprMethodCall(ident, tps, args)
1841 pub fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::Expr_ {
1842 ExprIndex(expr, idx)
1845 pub fn mk_range(&mut self,
1846 start: Option<P<Expr>>,
1847 end: Option<P<Expr>>)
1849 ExprRange(start, end)
1852 pub fn mk_field(&mut self, expr: P<Expr>, ident: ast::SpannedIdent) -> ast::Expr_ {
1853 ExprField(expr, ident)
1856 pub fn mk_tup_field(&mut self, expr: P<Expr>, idx: codemap::Spanned<usize>) -> ast::Expr_ {
1857 ExprTupField(expr, idx)
1860 pub fn mk_assign_op(&mut self, binop: ast::BinOp,
1861 lhs: P<Expr>, rhs: P<Expr>) -> ast::Expr_ {
1862 ExprAssignOp(binop, lhs, rhs)
1865 pub fn mk_mac_expr(&mut self, lo: BytePos, hi: BytePos, m: Mac_) -> P<Expr> {
1867 id: ast::DUMMY_NODE_ID,
1868 node: ExprMac(codemap::Spanned {node: m, span: mk_sp(lo, hi)}),
1869 span: mk_sp(lo, hi),
1873 pub fn mk_lit_u32(&mut self, i: u32) -> P<Expr> {
1874 let span = &self.span;
1875 let lv_lit = P(codemap::Spanned {
1876 node: LitInt(i as u64, ast::UnsignedIntLit(TyU32)),
1881 id: ast::DUMMY_NODE_ID,
1882 node: ExprLit(lv_lit),
1887 fn expect_open_delim(&mut self) -> token::DelimToken {
1888 self.expected_tokens.push(TokenType::Token(token::Gt));
1890 token::OpenDelim(delim) => {
1894 _ => self.fatal("expected open delimiter"),
1898 /// At the bottom (top?) of the precedence hierarchy,
1899 /// parse things like parenthesized exprs,
1900 /// macros, return, etc.
1901 pub fn parse_bottom_expr(&mut self) -> P<Expr> {
1902 maybe_whole_expr!(self);
1904 let lo = self.span.lo;
1905 let mut hi = self.span.hi;
1909 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
1911 token::OpenDelim(token::Paren) => {
1914 // (e) is parenthesized e
1915 // (e,) is a tuple with only one field, e
1916 let mut es = vec![];
1917 let mut trailing_comma = false;
1918 while self.token != token::CloseDelim(token::Paren) {
1919 es.push(self.parse_expr());
1920 self.commit_expr(&**es.last().unwrap(), &[],
1921 &[token::Comma, token::CloseDelim(token::Paren)]);
1922 if self.check(&token::Comma) {
1923 trailing_comma = true;
1927 trailing_comma = false;
1934 return if es.len() == 1 && !trailing_comma {
1935 self.mk_expr(lo, hi, ExprParen(es.into_iter().nth(0).unwrap()))
1937 self.mk_expr(lo, hi, ExprTup(es))
1940 token::OpenDelim(token::Brace) => {
1941 return self.parse_block_expr(lo, DefaultBlock);
1943 token::BinOp(token::Or) | token::OrOr => {
1944 return self.parse_lambda_expr(CaptureByRef);
1946 token::Ident(id @ ast::Ident {
1947 name: token::SELF_KEYWORD_NAME,
1949 }, token::Plain) => {
1951 let path = ast_util::ident_to_path(mk_sp(lo, hi), id);
1952 ex = ExprPath(None, path);
1953 hi = self.last_span.hi;
1955 token::OpenDelim(token::Bracket) => {
1958 if self.check(&token::CloseDelim(token::Bracket)) {
1961 ex = ExprVec(Vec::new());
1964 let first_expr = self.parse_expr();
1965 if self.check(&token::Semi) {
1966 // Repeating vector syntax: [ 0; 512 ]
1968 let count = self.parse_expr();
1969 self.expect(&token::CloseDelim(token::Bracket));
1970 ex = ExprRepeat(first_expr, count);
1971 } else if self.check(&token::Comma) {
1972 // Vector with two or more elements.
1974 let remaining_exprs = self.parse_seq_to_end(
1975 &token::CloseDelim(token::Bracket),
1976 seq_sep_trailing_allowed(token::Comma),
1979 let mut exprs = vec!(first_expr);
1980 exprs.extend(remaining_exprs.into_iter());
1981 ex = ExprVec(exprs);
1983 // Vector with one element.
1984 self.expect(&token::CloseDelim(token::Bracket));
1985 ex = ExprVec(vec!(first_expr));
1988 hi = self.last_span.hi;
1992 // QUALIFIED PATH `<TYPE as TRAIT_REF>::item::<'a, T>`
1993 let self_type = self.parse_ty_sum();
1994 let mut path = if self.eat_keyword(keywords::As) {
1995 self.parse_path(LifetimeAndTypesWithoutColons)
2005 position: path.segments.len()
2007 self.expect(&token::Gt);
2008 self.expect(&token::ModSep);
2010 let item_name = self.parse_ident();
2011 let parameters = if self.eat(&token::ModSep) {
2013 // Consumed `item::<`, go look for types
2014 let (lifetimes, types, bindings) =
2015 self.parse_generic_values_after_lt();
2016 ast::AngleBracketedParameters(ast::AngleBracketedParameterData {
2017 lifetimes: lifetimes,
2018 types: OwnedSlice::from_vec(types),
2019 bindings: OwnedSlice::from_vec(bindings),
2022 ast::PathParameters::none()
2024 path.segments.push(ast::PathSegment {
2025 identifier: item_name,
2026 parameters: parameters
2029 if path.segments.len() == 1 {
2030 path.span.lo = self.last_span.lo;
2032 path.span.hi = self.last_span.hi;
2034 let hi = self.span.hi;
2035 return self.mk_expr(lo, hi, ExprPath(Some(qself), path));
2037 if self.eat_keyword(keywords::Move) {
2038 return self.parse_lambda_expr(CaptureByValue);
2040 if self.eat_keyword(keywords::If) {
2041 return self.parse_if_expr();
2043 if self.eat_keyword(keywords::For) {
2044 return self.parse_for_expr(None);
2046 if self.eat_keyword(keywords::While) {
2047 return self.parse_while_expr(None);
2049 if self.token.is_lifetime() {
2050 let lifetime = self.get_lifetime();
2052 self.expect(&token::Colon);
2053 if self.eat_keyword(keywords::While) {
2054 return self.parse_while_expr(Some(lifetime))
2056 if self.eat_keyword(keywords::For) {
2057 return self.parse_for_expr(Some(lifetime))
2059 if self.eat_keyword(keywords::Loop) {
2060 return self.parse_loop_expr(Some(lifetime))
2062 self.fatal("expected `while`, `for`, or `loop` after a label")
2064 if self.eat_keyword(keywords::Loop) {
2065 return self.parse_loop_expr(None);
2067 if self.eat_keyword(keywords::Continue) {
2068 let lo = self.span.lo;
2069 let ex = if self.token.is_lifetime() {
2070 let lifetime = self.get_lifetime();
2072 ExprAgain(Some(lifetime))
2076 let hi = self.span.hi;
2077 return self.mk_expr(lo, hi, ex);
2079 if self.eat_keyword(keywords::Match) {
2080 return self.parse_match_expr();
2082 if self.eat_keyword(keywords::Unsafe) {
2083 return self.parse_block_expr(
2085 UnsafeBlock(ast::UserProvided));
2087 if self.eat_keyword(keywords::Return) {
2088 // RETURN expression
2089 if self.token.can_begin_expr() {
2090 let e = self.parse_expr();
2092 ex = ExprRet(Some(e));
2096 } else if self.eat_keyword(keywords::Break) {
2098 if self.token.is_lifetime() {
2099 let lifetime = self.get_lifetime();
2101 ex = ExprBreak(Some(lifetime));
2103 ex = ExprBreak(None);
2106 } else if self.check(&token::ModSep) ||
2107 self.token.is_ident() &&
2108 !self.check_keyword(keywords::True) &&
2109 !self.check_keyword(keywords::False) {
2111 self.parse_path(LifetimeAndTypesWithColons);
2113 // `!`, as an operator, is prefix, so we know this isn't that
2114 if self.check(&token::Not) {
2115 // MACRO INVOCATION expression
2118 let delim = self.expect_open_delim();
2119 let tts = self.parse_seq_to_end(
2120 &token::CloseDelim(delim),
2122 |p| p.parse_token_tree());
2123 let hi = self.span.hi;
2125 return self.mk_mac_expr(lo,
2131 if self.check(&token::OpenDelim(token::Brace)) {
2132 // This is a struct literal, unless we're prohibited
2133 // from parsing struct literals here.
2134 if !self.restrictions.contains(RESTRICTION_NO_STRUCT_LITERAL) {
2135 // It's a struct literal.
2137 let mut fields = Vec::new();
2138 let mut base = None;
2140 while self.token != token::CloseDelim(token::Brace) {
2141 if self.eat(&token::DotDot) {
2142 base = Some(self.parse_expr());
2146 fields.push(self.parse_field());
2147 self.commit_expr(&*fields.last().unwrap().expr,
2149 &[token::CloseDelim(token::Brace)]);
2152 if fields.len() == 0 && base.is_none() {
2153 let last_span = self.last_span;
2154 self.span_err(last_span,
2155 "structure literal must either \
2156 have at least one field or use \
2157 functional structure update \
2162 self.expect(&token::CloseDelim(token::Brace));
2163 ex = ExprStruct(pth, fields, base);
2164 return self.mk_expr(lo, hi, ex);
2169 ex = ExprPath(None, pth);
2171 // other literal expression
2172 let lit = self.parse_lit();
2174 ex = ExprLit(P(lit));
2179 return self.mk_expr(lo, hi, ex);
2182 /// Parse a block or unsafe block
2183 pub fn parse_block_expr(&mut self, lo: BytePos, blk_mode: BlockCheckMode)
2185 self.expect(&token::OpenDelim(token::Brace));
2186 let blk = self.parse_block_tail(lo, blk_mode);
2187 return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk));
2190 /// parse a.b or a(13) or a[4] or just a
2191 pub fn parse_dot_or_call_expr(&mut self) -> P<Expr> {
2192 let b = self.parse_bottom_expr();
2193 self.parse_dot_or_call_expr_with(b)
2196 pub fn parse_dot_or_call_expr_with(&mut self, e0: P<Expr>) -> P<Expr> {
2202 if self.eat(&token::Dot) {
2204 token::Ident(i, _) => {
2205 let dot = self.last_span.hi;
2208 let (_, tys, bindings) = if self.eat(&token::ModSep) {
2210 self.parse_generic_values_after_lt()
2212 (Vec::new(), Vec::new(), Vec::new())
2215 if bindings.len() > 0 {
2216 let last_span = self.last_span;
2217 self.span_err(last_span, "type bindings are only permitted on trait paths");
2220 // expr.f() method call
2222 token::OpenDelim(token::Paren) => {
2223 let mut es = self.parse_unspanned_seq(
2224 &token::OpenDelim(token::Paren),
2225 &token::CloseDelim(token::Paren),
2226 seq_sep_trailing_allowed(token::Comma),
2229 hi = self.last_span.hi;
2232 let id = spanned(dot, hi, i);
2233 let nd = self.mk_method_call(id, tys, es);
2234 e = self.mk_expr(lo, hi, nd);
2237 if !tys.is_empty() {
2238 let last_span = self.last_span;
2239 self.span_err(last_span,
2240 "field expressions may not \
2241 have type parameters");
2244 let id = spanned(dot, hi, i);
2245 let field = self.mk_field(e, id);
2246 e = self.mk_expr(lo, hi, field);
2250 token::Literal(token::Integer(n), suf) => {
2253 // A tuple index may not have a suffix
2254 self.expect_no_suffix(sp, "tuple index", suf);
2256 let dot = self.last_span.hi;
2260 let index = n.as_str().parse::<usize>().ok();
2263 let id = spanned(dot, hi, n);
2264 let field = self.mk_tup_field(e, id);
2265 e = self.mk_expr(lo, hi, field);
2268 let last_span = self.last_span;
2269 self.span_err(last_span, "invalid tuple or tuple struct index");
2273 token::Literal(token::Float(n), _suf) => {
2275 let last_span = self.last_span;
2276 let fstr = n.as_str();
2277 self.span_err(last_span,
2278 &format!("unexpected token: `{}`", n.as_str()));
2279 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2280 let float = match fstr.parse::<f64>().ok() {
2284 self.fileline_help(last_span,
2285 &format!("try parenthesizing the first index; e.g., `(foo.{}){}`",
2286 float.trunc() as usize,
2287 &float.fract().to_string()[1..]));
2289 self.abort_if_errors();
2292 _ => self.unexpected()
2296 if self.expr_is_complete(&*e) { break; }
2299 token::OpenDelim(token::Paren) => {
2300 let es = self.parse_unspanned_seq(
2301 &token::OpenDelim(token::Paren),
2302 &token::CloseDelim(token::Paren),
2303 seq_sep_trailing_allowed(token::Comma),
2306 hi = self.last_span.hi;
2308 let nd = self.mk_call(e, es);
2309 e = self.mk_expr(lo, hi, nd);
2313 // Could be either an index expression or a slicing expression.
2314 token::OpenDelim(token::Bracket) => {
2315 let bracket_pos = self.span.lo;
2318 if self.eat(&token::CloseDelim(token::Bracket)) {
2319 // No expression, expand to a RangeFull
2320 // FIXME(#20516) It would be better to use a lang item or
2321 // something for RangeFull.
2322 hi = self.last_span.hi;
2324 let idents = vec![token::str_to_ident("std"),
2325 token::str_to_ident("ops"),
2326 token::str_to_ident("RangeFull")];
2327 let segments = idents.into_iter().map(|ident| {
2330 parameters: ast::PathParameters::none(),
2333 let span = mk_sp(lo, hi);
2334 let path = ast::Path {
2340 let range = ExprStruct(path, vec![], None);
2341 let ix = self.mk_expr(bracket_pos, hi, range);
2342 let index = self.mk_index(e, ix);
2343 e = self.mk_expr(lo, hi, index);
2345 let obsolete_span = mk_sp(bracket_pos, hi);
2346 self.obsolete(obsolete_span, ObsoleteSyntax::EmptyIndex);
2348 let ix = self.parse_expr();
2350 self.commit_expr_expecting(&*ix, token::CloseDelim(token::Bracket));
2351 let index = self.mk_index(e, ix);
2352 e = self.mk_expr(lo, hi, index)
2362 // Parse unquoted tokens after a `$` in a token tree
2363 fn parse_unquoted(&mut self) -> TokenTree {
2364 let mut sp = self.span;
2365 let (name, namep) = match self.token {
2369 if self.token == token::OpenDelim(token::Paren) {
2370 let Spanned { node: seq, span: seq_span } = self.parse_seq(
2371 &token::OpenDelim(token::Paren),
2372 &token::CloseDelim(token::Paren),
2374 |p| p.parse_token_tree()
2376 let (sep, repeat) = self.parse_sep_and_kleene_op();
2377 let name_num = macro_parser::count_names(&seq);
2378 return TtSequence(mk_sp(sp.lo, seq_span.hi),
2379 Rc::new(SequenceRepetition {
2383 num_captures: name_num
2385 } else if self.token.is_keyword_allow_following_colon(keywords::Crate) {
2387 return TtToken(sp, SpecialVarNt(SpecialMacroVar::CrateMacroVar));
2389 sp = mk_sp(sp.lo, self.span.hi);
2390 let namep = match self.token { token::Ident(_, p) => p, _ => token::Plain };
2391 let name = self.parse_ident();
2395 token::SubstNt(name, namep) => {
2401 // continue by trying to parse the `:ident` after `$name`
2402 if self.token == token::Colon && self.look_ahead(1, |t| t.is_ident() &&
2403 !t.is_strict_keyword() &&
2404 !t.is_reserved_keyword()) {
2406 sp = mk_sp(sp.lo, self.span.hi);
2407 let kindp = match self.token { token::Ident(_, p) => p, _ => token::Plain };
2408 let nt_kind = self.parse_ident();
2409 TtToken(sp, MatchNt(name, nt_kind, namep, kindp))
2411 TtToken(sp, SubstNt(name, namep))
2415 pub fn check_unknown_macro_variable(&mut self) {
2416 if self.quote_depth == 0 {
2418 token::SubstNt(name, _) =>
2419 self.fatal(&format!("unknown macro variable `{}`",
2420 token::get_ident(name))),
2426 /// Parse an optional separator followed by a Kleene-style
2427 /// repetition token (+ or *).
2428 pub fn parse_sep_and_kleene_op(&mut self) -> (Option<token::Token>, ast::KleeneOp) {
2429 fn parse_kleene_op(parser: &mut Parser) -> Option<ast::KleeneOp> {
2430 match parser.token {
2431 token::BinOp(token::Star) => {
2433 Some(ast::ZeroOrMore)
2435 token::BinOp(token::Plus) => {
2437 Some(ast::OneOrMore)
2443 match parse_kleene_op(self) {
2444 Some(kleene_op) => return (None, kleene_op),
2448 let separator = self.bump_and_get();
2449 match parse_kleene_op(self) {
2450 Some(zerok) => (Some(separator), zerok),
2451 None => self.fatal("expected `*` or `+`")
2455 /// parse a single token tree from the input.
2456 pub fn parse_token_tree(&mut self) -> TokenTree {
2457 // FIXME #6994: currently, this is too eager. It
2458 // parses token trees but also identifies TtSequence's
2459 // and token::SubstNt's; it's too early to know yet
2460 // whether something will be a nonterminal or a seq
2462 maybe_whole!(deref self, NtTT);
2464 // this is the fall-through for the 'match' below.
2465 // invariants: the current token is not a left-delimiter,
2466 // not an EOF, and not the desired right-delimiter (if
2467 // it were, parse_seq_to_before_end would have prevented
2468 // reaching this point.
2469 fn parse_non_delim_tt_tok(p: &mut Parser) -> TokenTree {
2470 maybe_whole!(deref p, NtTT);
2472 token::CloseDelim(_) => {
2473 // This is a conservative error: only report the last unclosed delimiter. The
2474 // previous unclosed delimiters could actually be closed! The parser just hasn't
2475 // gotten to them yet.
2476 match p.open_braces.last() {
2478 Some(&sp) => p.span_note(sp, "unclosed delimiter"),
2480 let token_str = p.this_token_to_string();
2481 p.fatal(&format!("incorrect close delimiter: `{}`",
2484 /* we ought to allow different depths of unquotation */
2485 token::Dollar | token::SubstNt(..) if p.quote_depth > 0 => {
2489 TtToken(p.span, p.bump_and_get())
2496 let open_braces = self.open_braces.clone();
2497 for sp in &open_braces {
2498 self.span_help(*sp, "did you mean to close this delimiter?");
2500 // There shouldn't really be a span, but it's easier for the test runner
2501 // if we give it one
2502 self.fatal("this file contains an un-closed delimiter ");
2504 token::OpenDelim(delim) => {
2505 // The span for beginning of the delimited section
2506 let pre_span = self.span;
2508 // Parse the open delimiter.
2509 self.open_braces.push(self.span);
2510 let open_span = self.span;
2513 // Parse the token trees within the delimiters
2514 let tts = self.parse_seq_to_before_end(
2515 &token::CloseDelim(delim),
2517 |p| p.parse_token_tree()
2520 // Parse the close delimiter.
2521 let close_span = self.span;
2523 self.open_braces.pop().unwrap();
2525 // Expand to cover the entire delimited token tree
2526 let span = Span { hi: close_span.hi, ..pre_span };
2528 TtDelimited(span, Rc::new(Delimited {
2530 open_span: open_span,
2532 close_span: close_span,
2535 _ => parse_non_delim_tt_tok(self),
2539 // parse a stream of tokens into a list of TokenTree's,
2541 pub fn parse_all_token_trees(&mut self) -> Vec<TokenTree> {
2542 let mut tts = Vec::new();
2543 while self.token != token::Eof {
2544 tts.push(self.parse_token_tree());
2549 /// Parse a prefix-operator expr
2550 pub fn parse_prefix_expr(&mut self) -> P<Expr> {
2551 let lo = self.span.lo;
2554 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2559 let e = self.parse_prefix_expr();
2561 ex = self.mk_unary(UnNot, e);
2563 token::BinOp(token::Minus) => {
2565 let e = self.parse_prefix_expr();
2567 ex = self.mk_unary(UnNeg, e);
2569 token::BinOp(token::Star) => {
2571 let e = self.parse_prefix_expr();
2573 ex = self.mk_unary(UnDeref, e);
2575 token::BinOp(token::And) | token::AndAnd => {
2577 let m = self.parse_mutability();
2578 let e = self.parse_prefix_expr();
2580 ex = ExprAddrOf(m, e);
2582 token::Ident(_, _) => {
2583 if !self.check_keyword(keywords::Box) {
2584 return self.parse_dot_or_call_expr();
2587 let lo = self.span.lo;
2591 // Check for a place: `box(PLACE) EXPR`.
2592 if self.eat(&token::OpenDelim(token::Paren)) {
2593 // Support `box() EXPR` as the default.
2594 if !self.eat(&token::CloseDelim(token::Paren)) {
2595 let place = self.parse_expr();
2596 self.expect(&token::CloseDelim(token::Paren));
2597 // Give a suggestion to use `box()` when a parenthesised expression is used
2598 if !self.token.can_begin_expr() {
2599 let span = self.span;
2600 let this_token_to_string = self.this_token_to_string();
2602 &format!("expected expression, found `{}`",
2603 this_token_to_string));
2604 let box_span = mk_sp(lo, self.last_span.hi);
2605 self.span_help(box_span,
2606 "perhaps you meant `box() (foo)` instead?");
2607 self.abort_if_errors();
2609 let subexpression = self.parse_prefix_expr();
2610 hi = subexpression.span.hi;
2611 ex = ExprBox(Some(place), subexpression);
2612 return self.mk_expr(lo, hi, ex);
2616 // Otherwise, we use the unique pointer default.
2617 let subexpression = self.parse_prefix_expr();
2618 hi = subexpression.span.hi;
2619 // FIXME (pnkfelix): After working out kinks with box
2620 // desugaring, should be `ExprBox(None, subexpression)`
2622 ex = self.mk_unary(UnUniq, subexpression);
2624 _ => return self.parse_dot_or_call_expr()
2626 return self.mk_expr(lo, hi, ex);
2629 /// Parse an expression of binops
2630 pub fn parse_binops(&mut self) -> P<Expr> {
2631 let prefix_expr = self.parse_prefix_expr();
2632 self.parse_more_binops(prefix_expr, 0)
2635 /// Parse an expression of binops of at least min_prec precedence
2636 pub fn parse_more_binops(&mut self, lhs: P<Expr>, min_prec: usize) -> P<Expr> {
2637 if self.expr_is_complete(&*lhs) { return lhs; }
2639 // Prevent dynamic borrow errors later on by limiting the
2640 // scope of the borrows.
2641 if self.token == token::BinOp(token::Or) &&
2642 self.restrictions.contains(RESTRICTION_NO_BAR_OP) {
2646 self.expected_tokens.push(TokenType::Operator);
2648 let cur_op_span = self.span;
2649 let cur_opt = self.token.to_binop();
2652 if ast_util::is_comparison_binop(cur_op) {
2653 self.check_no_chained_comparison(&*lhs, cur_op)
2655 let cur_prec = operator_prec(cur_op);
2656 if cur_prec >= min_prec {
2658 let expr = self.parse_prefix_expr();
2659 let rhs = self.parse_more_binops(expr, cur_prec + 1);
2660 let lhs_span = lhs.span;
2661 let rhs_span = rhs.span;
2662 let binary = self.mk_binary(codemap::respan(cur_op_span, cur_op), lhs, rhs);
2663 let bin = self.mk_expr(lhs_span.lo, rhs_span.hi, binary);
2664 self.parse_more_binops(bin, min_prec)
2670 if AS_PREC >= min_prec && self.eat_keyword_noexpect(keywords::As) {
2671 let rhs = self.parse_ty();
2672 let _as = self.mk_expr(lhs.span.lo,
2674 ExprCast(lhs, rhs));
2675 self.parse_more_binops(_as, min_prec)
2683 /// Produce an error if comparison operators are chained (RFC #558).
2684 /// We only need to check lhs, not rhs, because all comparison ops
2685 /// have same precedence and are left-associative
2686 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: ast::BinOp_) {
2687 debug_assert!(ast_util::is_comparison_binop(outer_op));
2689 ExprBinary(op, _, _) if ast_util::is_comparison_binop(op.node) => {
2690 // respan to include both operators
2691 let op_span = mk_sp(op.span.lo, self.span.hi);
2692 self.span_err(op_span,
2693 "chained comparison operators require parentheses");
2694 if op.node == BiLt && outer_op == BiGt {
2695 self.fileline_help(op_span,
2696 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
2703 /// Parse an assignment expression....
2704 /// actually, this seems to be the main entry point for
2705 /// parsing an arbitrary expression.
2706 pub fn parse_assign_expr(&mut self) -> P<Expr> {
2709 // prefix-form of range notation '..expr'
2710 // This has the same precedence as assignment expressions
2711 // (much lower than other prefix expressions) to be consistent
2712 // with the postfix-form 'expr..'
2713 let lo = self.span.lo;
2715 let opt_end = if self.is_at_start_of_range_notation_rhs() {
2716 let end = self.parse_binops();
2721 let hi = self.span.hi;
2722 let ex = self.mk_range(None, opt_end);
2723 self.mk_expr(lo, hi, ex)
2726 let lhs = self.parse_binops();
2727 self.parse_assign_expr_with(lhs)
2732 pub fn parse_assign_expr_with(&mut self, lhs: P<Expr>) -> P<Expr> {
2733 let restrictions = self.restrictions & RESTRICTION_NO_STRUCT_LITERAL;
2734 let op_span = self.span;
2738 let rhs = self.parse_expr_res(restrictions);
2739 self.mk_expr(lhs.span.lo, rhs.span.hi, ExprAssign(lhs, rhs))
2741 token::BinOpEq(op) => {
2743 let rhs = self.parse_expr_res(restrictions);
2744 let aop = match op {
2745 token::Plus => BiAdd,
2746 token::Minus => BiSub,
2747 token::Star => BiMul,
2748 token::Slash => BiDiv,
2749 token::Percent => BiRem,
2750 token::Caret => BiBitXor,
2751 token::And => BiBitAnd,
2752 token::Or => BiBitOr,
2753 token::Shl => BiShl,
2756 let rhs_span = rhs.span;
2757 let span = lhs.span;
2758 let assign_op = self.mk_assign_op(codemap::respan(op_span, aop), lhs, rhs);
2759 self.mk_expr(span.lo, rhs_span.hi, assign_op)
2761 // A range expression, either `expr..expr` or `expr..`.
2765 let opt_end = if self.is_at_start_of_range_notation_rhs() {
2766 let end = self.parse_binops();
2772 let lo = lhs.span.lo;
2773 let hi = self.span.hi;
2774 let range = self.mk_range(Some(lhs), opt_end);
2775 return self.mk_expr(lo, hi, range);
2784 fn is_at_start_of_range_notation_rhs(&self) -> bool {
2785 if self.token.can_begin_expr() {
2786 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
2787 if self.token == token::OpenDelim(token::Brace) {
2788 return !self.restrictions.contains(RESTRICTION_NO_STRUCT_LITERAL);
2796 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
2797 pub fn parse_if_expr(&mut self) -> P<Expr> {
2798 if self.check_keyword(keywords::Let) {
2799 return self.parse_if_let_expr();
2801 let lo = self.last_span.lo;
2802 let cond = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
2803 let thn = self.parse_block();
2804 let mut els: Option<P<Expr>> = None;
2805 let mut hi = thn.span.hi;
2806 if self.eat_keyword(keywords::Else) {
2807 let elexpr = self.parse_else_expr();
2808 hi = elexpr.span.hi;
2811 self.mk_expr(lo, hi, ExprIf(cond, thn, els))
2814 /// Parse an 'if let' expression ('if' token already eaten)
2815 pub fn parse_if_let_expr(&mut self) -> P<Expr> {
2816 let lo = self.last_span.lo;
2817 self.expect_keyword(keywords::Let);
2818 let pat = self.parse_pat();
2819 self.expect(&token::Eq);
2820 let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
2821 let thn = self.parse_block();
2822 let (hi, els) = if self.eat_keyword(keywords::Else) {
2823 let expr = self.parse_else_expr();
2824 (expr.span.hi, Some(expr))
2828 self.mk_expr(lo, hi, ExprIfLet(pat, expr, thn, els))
2832 pub fn parse_lambda_expr(&mut self, capture_clause: CaptureClause)
2835 let lo = self.span.lo;
2836 let decl = self.parse_fn_block_decl();
2837 let body = match decl.output {
2838 DefaultReturn(_) => {
2839 // If no explicit return type is given, parse any
2840 // expr and wrap it up in a dummy block:
2841 let body_expr = self.parse_expr();
2843 id: ast::DUMMY_NODE_ID,
2845 span: body_expr.span,
2846 expr: Some(body_expr),
2847 rules: DefaultBlock,
2851 // If an explicit return type is given, require a
2852 // block to appear (RFC 968).
2860 ExprClosure(capture_clause, decl, body))
2863 pub fn parse_else_expr(&mut self) -> P<Expr> {
2864 if self.eat_keyword(keywords::If) {
2865 return self.parse_if_expr();
2867 let blk = self.parse_block();
2868 return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk));
2872 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
2873 pub fn parse_for_expr(&mut self, opt_ident: Option<ast::Ident>) -> P<Expr> {
2874 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
2876 let lo = self.last_span.lo;
2877 let pat = self.parse_pat();
2878 self.expect_keyword(keywords::In);
2879 let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
2880 let loop_block = self.parse_block();
2881 let hi = self.span.hi;
2883 self.mk_expr(lo, hi, ExprForLoop(pat, expr, loop_block, opt_ident))
2886 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
2887 pub fn parse_while_expr(&mut self, opt_ident: Option<ast::Ident>) -> P<Expr> {
2888 if self.token.is_keyword(keywords::Let) {
2889 return self.parse_while_let_expr(opt_ident);
2891 let lo = self.last_span.lo;
2892 let cond = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
2893 let body = self.parse_block();
2894 let hi = body.span.hi;
2895 return self.mk_expr(lo, hi, ExprWhile(cond, body, opt_ident));
2898 /// Parse a 'while let' expression ('while' token already eaten)
2899 pub fn parse_while_let_expr(&mut self, opt_ident: Option<ast::Ident>) -> P<Expr> {
2900 let lo = self.last_span.lo;
2901 self.expect_keyword(keywords::Let);
2902 let pat = self.parse_pat();
2903 self.expect(&token::Eq);
2904 let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
2905 let body = self.parse_block();
2906 let hi = body.span.hi;
2907 return self.mk_expr(lo, hi, ExprWhileLet(pat, expr, body, opt_ident));
2910 pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::Ident>) -> P<Expr> {
2911 let lo = self.last_span.lo;
2912 let body = self.parse_block();
2913 let hi = body.span.hi;
2914 self.mk_expr(lo, hi, ExprLoop(body, opt_ident))
2917 fn parse_match_expr(&mut self) -> P<Expr> {
2918 let lo = self.last_span.lo;
2919 let discriminant = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
2920 self.commit_expr_expecting(&*discriminant, token::OpenDelim(token::Brace));
2921 let mut arms: Vec<Arm> = Vec::new();
2922 while self.token != token::CloseDelim(token::Brace) {
2923 arms.push(self.parse_arm());
2925 let hi = self.span.hi;
2927 return self.mk_expr(lo, hi, ExprMatch(discriminant, arms, MatchSource::Normal));
2930 pub fn parse_arm(&mut self) -> Arm {
2931 let attrs = self.parse_outer_attributes();
2932 let pats = self.parse_pats();
2933 let mut guard = None;
2934 if self.eat_keyword(keywords::If) {
2935 guard = Some(self.parse_expr());
2937 self.expect(&token::FatArrow);
2938 let expr = self.parse_expr_res(RESTRICTION_STMT_EXPR);
2941 !classify::expr_is_simple_block(&*expr)
2942 && self.token != token::CloseDelim(token::Brace);
2945 self.commit_expr(&*expr, &[token::Comma], &[token::CloseDelim(token::Brace)]);
2947 self.eat(&token::Comma);
2958 /// Parse an expression
2959 pub fn parse_expr(&mut self) -> P<Expr> {
2960 return self.parse_expr_res(UNRESTRICTED);
2963 /// Parse an expression, subject to the given restrictions
2964 pub fn parse_expr_res(&mut self, r: Restrictions) -> P<Expr> {
2965 let old = self.restrictions;
2966 self.restrictions = r;
2967 let e = self.parse_assign_expr();
2968 self.restrictions = old;
2972 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
2973 fn parse_initializer(&mut self) -> Option<P<Expr>> {
2974 if self.check(&token::Eq) {
2976 Some(self.parse_expr())
2982 /// Parse patterns, separated by '|' s
2983 fn parse_pats(&mut self) -> Vec<P<Pat>> {
2984 let mut pats = Vec::new();
2986 pats.push(self.parse_pat());
2987 if self.check(&token::BinOp(token::Or)) { self.bump(); }
2988 else { return pats; }
2992 fn parse_pat_vec_elements(
2994 ) -> (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>) {
2995 let mut before = Vec::new();
2996 let mut slice = None;
2997 let mut after = Vec::new();
2998 let mut first = true;
2999 let mut before_slice = true;
3001 while self.token != token::CloseDelim(token::Bracket) {
3005 self.expect(&token::Comma);
3007 if self.token == token::CloseDelim(token::Bracket)
3008 && (before_slice || after.len() != 0) {
3014 if self.check(&token::DotDot) {
3017 if self.check(&token::Comma) ||
3018 self.check(&token::CloseDelim(token::Bracket)) {
3019 slice = Some(P(ast::Pat {
3020 id: ast::DUMMY_NODE_ID,
3021 node: PatWild(PatWildMulti),
3024 before_slice = false;
3030 let subpat = self.parse_pat();
3031 if before_slice && self.check(&token::DotDot) {
3033 slice = Some(subpat);
3034 before_slice = false;
3035 } else if before_slice {
3036 before.push(subpat);
3042 (before, slice, after)
3045 /// Parse the fields of a struct-like pattern
3046 fn parse_pat_fields(&mut self) -> (Vec<codemap::Spanned<ast::FieldPat>> , bool) {
3047 let mut fields = Vec::new();
3048 let mut etc = false;
3049 let mut first = true;
3050 while self.token != token::CloseDelim(token::Brace) {
3054 self.expect(&token::Comma);
3055 // accept trailing commas
3056 if self.check(&token::CloseDelim(token::Brace)) { break }
3059 let lo = self.span.lo;
3062 if self.check(&token::DotDot) {
3064 if self.token != token::CloseDelim(token::Brace) {
3065 let token_str = self.this_token_to_string();
3066 self.fatal(&format!("expected `{}`, found `{}`", "}",
3073 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3074 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3075 // Parsing a pattern of the form "fieldname: pat"
3076 let fieldname = self.parse_ident();
3078 let pat = self.parse_pat();
3080 (pat, fieldname, false)
3082 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3083 let is_box = self.eat_keyword(keywords::Box);
3084 let boxed_span_lo = self.span.lo;
3085 let is_ref = self.eat_keyword(keywords::Ref);
3086 let is_mut = self.eat_keyword(keywords::Mut);
3087 let fieldname = self.parse_ident();
3088 hi = self.last_span.hi;
3090 let bind_type = match (is_ref, is_mut) {
3091 (true, true) => BindByRef(MutMutable),
3092 (true, false) => BindByRef(MutImmutable),
3093 (false, true) => BindByValue(MutMutable),
3094 (false, false) => BindByValue(MutImmutable),
3096 let fieldpath = codemap::Spanned{span:self.last_span, node:fieldname};
3097 let fieldpat = P(ast::Pat{
3098 id: ast::DUMMY_NODE_ID,
3099 node: PatIdent(bind_type, fieldpath, None),
3100 span: mk_sp(boxed_span_lo, hi),
3103 let subpat = if is_box {
3105 id: ast::DUMMY_NODE_ID,
3106 node: PatBox(fieldpat),
3107 span: mk_sp(lo, hi),
3112 (subpat, fieldname, true)
3115 fields.push(codemap::Spanned { span: mk_sp(lo, hi),
3116 node: ast::FieldPat { ident: fieldname,
3118 is_shorthand: is_shorthand }});
3120 return (fields, etc);
3123 /// Parse a pattern.
3124 pub fn parse_pat(&mut self) -> P<Pat> {
3125 maybe_whole!(self, NtPat);
3127 let lo = self.span.lo;
3132 token::Underscore => {
3134 pat = PatWild(PatWildSingle);
3135 hi = self.last_span.hi;
3137 id: ast::DUMMY_NODE_ID,
3142 token::BinOp(token::And) | token::AndAnd => {
3143 // parse &pat and &mut pat
3144 let lo = self.span.lo;
3146 let mutability = if self.eat_keyword(keywords::Mut) {
3151 let sub = self.parse_pat();
3152 pat = PatRegion(sub, mutability);
3153 hi = self.last_span.hi;
3155 id: ast::DUMMY_NODE_ID,
3160 token::OpenDelim(token::Paren) => {
3161 // parse (pat,pat,pat,...) as tuple
3163 if self.check(&token::CloseDelim(token::Paren)) {
3165 pat = PatTup(vec![]);
3167 let mut fields = vec!(self.parse_pat());
3168 if self.look_ahead(1, |t| *t != token::CloseDelim(token::Paren)) {
3169 while self.check(&token::Comma) {
3171 if self.check(&token::CloseDelim(token::Paren)) { break; }
3172 fields.push(self.parse_pat());
3175 if fields.len() == 1 { self.expect(&token::Comma); }
3176 self.expect(&token::CloseDelim(token::Paren));
3177 pat = PatTup(fields);
3179 hi = self.last_span.hi;
3181 id: ast::DUMMY_NODE_ID,
3186 token::OpenDelim(token::Bracket) => {
3187 // parse [pat,pat,...] as vector pattern
3189 let (before, slice, after) =
3190 self.parse_pat_vec_elements();
3192 self.expect(&token::CloseDelim(token::Bracket));
3193 pat = ast::PatVec(before, slice, after);
3194 hi = self.last_span.hi;
3196 id: ast::DUMMY_NODE_ID,
3203 // at this point, token != _, ~, &, &&, (, [
3205 if (!(self.token.is_ident() || self.token.is_path())
3206 && self.token != token::ModSep)
3207 || self.token.is_keyword(keywords::True)
3208 || self.token.is_keyword(keywords::False) {
3209 // Parse an expression pattern or exp ... exp.
3211 // These expressions are limited to literals (possibly
3212 // preceded by unary-minus) or identifiers.
3213 let val = self.parse_literal_maybe_minus();
3214 if (self.check(&token::DotDotDot)) &&
3215 self.look_ahead(1, |t| {
3216 *t != token::Comma && *t != token::CloseDelim(token::Bracket)
3219 let end = if self.token.is_ident() || self.token.is_path() {
3220 let path = self.parse_path(LifetimeAndTypesWithColons);
3221 let hi = self.span.hi;
3222 self.mk_expr(lo, hi, ExprPath(None, path))
3224 self.parse_literal_maybe_minus()
3226 pat = PatRange(val, end);
3230 } else if self.eat_keyword(keywords::Mut) {
3231 pat = self.parse_pat_ident(BindByValue(MutMutable));
3232 } else if self.eat_keyword(keywords::Ref) {
3234 let mutbl = self.parse_mutability();
3235 pat = self.parse_pat_ident(BindByRef(mutbl));
3236 } else if self.eat_keyword(keywords::Box) {
3239 // FIXME(#13910): Rename to `PatBox` and extend to full DST
3241 let sub = self.parse_pat();
3243 hi = self.last_span.hi;
3245 id: ast::DUMMY_NODE_ID,
3250 let can_be_enum_or_struct = self.look_ahead(1, |t| {
3252 token::OpenDelim(_) | token::Lt | token::ModSep => true,
3257 if self.look_ahead(1, |t| *t == token::DotDotDot) &&
3258 self.look_ahead(2, |t| {
3259 *t != token::Comma && *t != token::CloseDelim(token::Bracket)
3261 let start = self.parse_expr_res(RESTRICTION_NO_BAR_OP);
3262 self.eat(&token::DotDotDot);
3263 let end = self.parse_expr_res(RESTRICTION_NO_BAR_OP);
3264 pat = PatRange(start, end);
3265 } else if self.token.is_plain_ident() && !can_be_enum_or_struct {
3266 let id = self.parse_ident();
3267 let id_span = self.last_span;
3268 let pth1 = codemap::Spanned{span:id_span, node: id};
3269 if self.eat(&token::Not) {
3271 let delim = self.expect_open_delim();
3272 let tts = self.parse_seq_to_end(&token::CloseDelim(delim),
3274 |p| p.parse_token_tree());
3276 let mac = MacInvocTT(ident_to_path(id_span,id), tts, EMPTY_CTXT);
3277 pat = ast::PatMac(codemap::Spanned {node: mac, span: self.span});
3279 let sub = if self.eat(&token::At) {
3281 Some(self.parse_pat())
3286 pat = PatIdent(BindByValue(MutImmutable), pth1, sub);
3288 } else if self.look_ahead(1, |t| *t == token::Lt) {
3292 // parse an enum pat
3293 let enum_path = self.parse_path(LifetimeAndTypesWithColons);
3295 token::OpenDelim(token::Brace) => {
3298 self.parse_pat_fields();
3300 pat = PatStruct(enum_path, fields, etc);
3302 token::DotDotDot => {
3303 let hi = self.last_span.hi;
3304 let start = self.mk_expr(lo, hi, ExprPath(None, enum_path));
3305 self.eat(&token::DotDotDot);
3306 let end = if self.token.is_ident() || self.token.is_path() {
3307 let path = self.parse_path(LifetimeAndTypesWithColons);
3308 let hi = self.span.hi;
3309 self.mk_expr(lo, hi, ExprPath(None, path))
3311 self.parse_literal_maybe_minus()
3313 pat = PatRange(start, end);
3316 let mut args: Vec<P<Pat>> = Vec::new();
3318 token::OpenDelim(token::Paren) => {
3319 let is_dotdot = self.look_ahead(1, |t| {
3321 token::DotDot => true,
3326 // This is a "top constructor only" pat
3329 self.expect(&token::CloseDelim(token::Paren));
3330 pat = PatEnum(enum_path, None);
3332 args = self.parse_enum_variant_seq(
3333 &token::OpenDelim(token::Paren),
3334 &token::CloseDelim(token::Paren),
3335 seq_sep_trailing_allowed(token::Comma),
3338 pat = PatEnum(enum_path, Some(args));
3342 if !enum_path.global &&
3343 enum_path.segments.len() == 1 &&
3344 enum_path.segments[0].parameters.is_empty()
3346 // NB: If enum_path is a single identifier,
3347 // this should not be reachable due to special
3348 // handling further above.
3350 // However, previously a PatIdent got emitted
3351 // here, so we preserve the branch just in case.
3353 // A rewrite of the logic in this function
3354 // would probably make this obvious.
3355 self.span_bug(enum_path.span,
3356 "ident only path should have been covered already");
3358 pat = PatEnum(enum_path, Some(args));
3366 hi = self.last_span.hi;
3368 id: ast::DUMMY_NODE_ID,
3370 span: mk_sp(lo, hi),
3374 /// Parse ident or ident @ pat
3375 /// used by the copy foo and ref foo patterns to give a good
3376 /// error message when parsing mistakes like ref foo(a,b)
3377 fn parse_pat_ident(&mut self,
3378 binding_mode: ast::BindingMode)
3380 if !self.token.is_plain_ident() {
3381 let span = self.span;
3382 let tok_str = self.this_token_to_string();
3383 self.span_fatal(span,
3384 &format!("expected identifier, found `{}`", tok_str));
3386 let ident = self.parse_ident();
3387 let last_span = self.last_span;
3388 let name = codemap::Spanned{span: last_span, node: ident};
3389 let sub = if self.eat(&token::At) {
3390 Some(self.parse_pat())
3395 // just to be friendly, if they write something like
3397 // we end up here with ( as the current token. This shortly
3398 // leads to a parse error. Note that if there is no explicit
3399 // binding mode then we do not end up here, because the lookahead
3400 // will direct us over to parse_enum_variant()
3401 if self.token == token::OpenDelim(token::Paren) {
3402 let last_span = self.last_span;
3405 "expected identifier, found enum pattern");
3408 PatIdent(binding_mode, name, sub)
3411 /// Parse a local variable declaration
3412 fn parse_local(&mut self) -> P<Local> {
3413 let lo = self.span.lo;
3414 let pat = self.parse_pat();
3417 if self.eat(&token::Colon) {
3418 ty = Some(self.parse_ty_sum());
3420 let init = self.parse_initializer();
3425 id: ast::DUMMY_NODE_ID,
3426 span: mk_sp(lo, self.last_span.hi),
3431 /// Parse a "let" stmt
3432 fn parse_let(&mut self) -> P<Decl> {
3433 let lo = self.span.lo;
3434 let local = self.parse_local();
3435 P(spanned(lo, self.last_span.hi, DeclLocal(local)))
3438 /// Parse a structure field
3439 fn parse_name_and_ty(&mut self, pr: Visibility,
3440 attrs: Vec<Attribute> ) -> StructField {
3441 let lo = self.span.lo;
3442 if !self.token.is_plain_ident() {
3443 self.fatal("expected ident");
3445 let name = self.parse_ident();
3446 self.expect(&token::Colon);
3447 let ty = self.parse_ty_sum();
3448 spanned(lo, self.last_span.hi, ast::StructField_ {
3449 kind: NamedField(name, pr),
3450 id: ast::DUMMY_NODE_ID,
3456 /// Emit an expected item after attributes error.
3457 fn expected_item_err(&self, attrs: &[Attribute]) {
3458 let message = match attrs.last() {
3459 Some(&Attribute { node: ast::Attribute_ { is_sugared_doc: true, .. }, .. }) => {
3460 "expected item after doc comment"
3462 _ => "expected item after attributes",
3465 self.span_err(self.last_span, message);
3468 /// Parse a statement. may include decl.
3469 pub fn parse_stmt(&mut self) -> Option<P<Stmt>> {
3470 self.parse_stmt_().map(P)
3473 fn parse_stmt_(&mut self) -> Option<Stmt> {
3474 maybe_whole!(Some deref self, NtStmt);
3476 fn check_expected_item(p: &mut Parser, attrs: &[Attribute]) {
3477 // If we have attributes then we should have an item
3478 if !attrs.is_empty() {
3479 p.expected_item_err(attrs);
3483 let lo = self.span.lo;
3484 let attrs = self.parse_outer_attributes();
3486 Some(if self.check_keyword(keywords::Let) {
3487 check_expected_item(self, &attrs);
3488 self.expect_keyword(keywords::Let);
3489 let decl = self.parse_let();
3490 spanned(lo, decl.span.hi, StmtDecl(decl, ast::DUMMY_NODE_ID))
3491 } else if self.token.is_ident()
3492 && !self.token.is_any_keyword()
3493 && self.look_ahead(1, |t| *t == token::Not) {
3494 // it's a macro invocation:
3496 check_expected_item(self, &attrs);
3498 // Potential trouble: if we allow macros with paths instead of
3499 // idents, we'd need to look ahead past the whole path here...
3500 let pth = self.parse_path(NoTypesAllowed);
3503 let id = match self.token {
3504 token::OpenDelim(_) => token::special_idents::invalid, // no special identifier
3505 _ => self.parse_ident(),
3508 // check that we're pointing at delimiters (need to check
3509 // again after the `if`, because of `parse_ident`
3510 // consuming more tokens).
3511 let delim = match self.token {
3512 token::OpenDelim(delim) => delim,
3514 // we only expect an ident if we didn't parse one
3516 let ident_str = if id.name == token::special_idents::invalid.name {
3521 let tok_str = self.this_token_to_string();
3522 self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
3528 let tts = self.parse_unspanned_seq(
3529 &token::OpenDelim(delim),
3530 &token::CloseDelim(delim),
3532 |p| p.parse_token_tree()
3534 let hi = self.span.hi;
3536 let style = if delim == token::Brace {
3539 MacStmtWithoutBraces
3542 if id.name == token::special_idents::invalid.name {
3544 StmtMac(P(spanned(lo,
3546 MacInvocTT(pth, tts, EMPTY_CTXT))),
3549 // if it has a special ident, it's definitely an item
3551 // Require a semicolon or braces.
3552 if style != MacStmtWithBraces {
3553 if !self.eat(&token::Semi) {
3554 let last_span = self.last_span;
3555 self.span_err(last_span,
3556 "macros that expand to items must \
3557 either be surrounded with braces or \
3558 followed by a semicolon");
3561 spanned(lo, hi, StmtDecl(
3562 P(spanned(lo, hi, DeclItem(
3564 lo, hi, id /*id is good here*/,
3565 ItemMac(spanned(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT))),
3566 Inherited, Vec::new(/*no attrs*/))))),
3567 ast::DUMMY_NODE_ID))
3570 match self.parse_item_(attrs, false) {
3573 let decl = P(spanned(lo, hi, DeclItem(i)));
3574 spanned(lo, hi, StmtDecl(decl, ast::DUMMY_NODE_ID))
3577 // Do not attempt to parse an expression if we're done here.
3578 if self.token == token::Semi {
3583 if self.token == token::CloseDelim(token::Brace) {
3587 // Remainder are line-expr stmts.
3588 let e = self.parse_expr_res(RESTRICTION_STMT_EXPR);
3589 spanned(lo, e.span.hi, StmtExpr(e, ast::DUMMY_NODE_ID))
3595 /// Is this expression a successfully-parsed statement?
3596 fn expr_is_complete(&mut self, e: &Expr) -> bool {
3597 self.restrictions.contains(RESTRICTION_STMT_EXPR) &&
3598 !classify::expr_requires_semi_to_be_stmt(e)
3601 /// Parse a block. No inner attrs are allowed.
3602 pub fn parse_block(&mut self) -> P<Block> {
3603 maybe_whole!(no_clone self, NtBlock);
3605 let lo = self.span.lo;
3607 if !self.eat(&token::OpenDelim(token::Brace)) {
3609 let tok = self.this_token_to_string();
3610 self.span_fatal_help(sp,
3611 &format!("expected `{{`, found `{}`", tok),
3612 "place this code inside a block");
3615 self.parse_block_tail(lo, DefaultBlock)
3618 /// Parse a block. Inner attrs are allowed.
3619 fn parse_inner_attrs_and_block(&mut self) -> (Vec<Attribute>, P<Block>) {
3620 maybe_whole!(pair_empty self, NtBlock);
3622 let lo = self.span.lo;
3623 self.expect(&token::OpenDelim(token::Brace));
3624 (self.parse_inner_attributes(),
3625 self.parse_block_tail(lo, DefaultBlock))
3628 /// Parse the rest of a block expression or function body
3629 /// Precondition: already parsed the '{'.
3630 fn parse_block_tail(&mut self, lo: BytePos, s: BlockCheckMode) -> P<Block> {
3631 let mut stmts = vec![];
3632 let mut expr = None;
3634 while !self.eat(&token::CloseDelim(token::Brace)) {
3635 let Spanned {node, span} = if let Some(s) = self.parse_stmt_() {
3638 // Found only `;` or `}`.
3643 self.handle_expression_like_statement(e, span, &mut stmts, &mut expr);
3645 StmtMac(mac, MacStmtWithoutBraces) => {
3646 // statement macro without braces; might be an
3647 // expr depending on whether a semicolon follows
3650 stmts.push(P(Spanned {
3651 node: StmtMac(mac, MacStmtWithSemicolon),
3657 let e = self.mk_mac_expr(span.lo, span.hi,
3658 mac.and_then(|m| m.node));
3659 let e = self.parse_dot_or_call_expr_with(e);
3660 let e = self.parse_more_binops(e, 0);
3661 let e = self.parse_assign_expr_with(e);
3662 self.handle_expression_like_statement(
3670 StmtMac(m, style) => {
3671 // statement macro; might be an expr
3674 stmts.push(P(Spanned {
3675 node: StmtMac(m, MacStmtWithSemicolon),
3680 token::CloseDelim(token::Brace) => {
3681 // if a block ends in `m!(arg)` without
3682 // a `;`, it must be an expr
3683 expr = Some(self.mk_mac_expr(span.lo, span.hi,
3684 m.and_then(|x| x.node)));
3687 stmts.push(P(Spanned {
3688 node: StmtMac(m, style),
3694 _ => { // all other kinds of statements:
3695 if classify::stmt_ends_with_semi(&node) {
3696 self.commit_stmt_expecting(token::Semi);
3699 stmts.push(P(Spanned {
3710 id: ast::DUMMY_NODE_ID,
3712 span: mk_sp(lo, self.last_span.hi),
3716 fn handle_expression_like_statement(
3720 stmts: &mut Vec<P<Stmt>>,
3721 last_block_expr: &mut Option<P<Expr>>) {
3722 // expression without semicolon
3723 if classify::expr_requires_semi_to_be_stmt(&*e) {
3724 // Just check for errors and recover; do not eat semicolon yet.
3725 self.commit_stmt(&[],
3726 &[token::Semi, token::CloseDelim(token::Brace)]);
3732 let span_with_semi = Span {
3734 hi: self.last_span.hi,
3735 expn_id: span.expn_id,
3737 stmts.push(P(Spanned {
3738 node: StmtSemi(e, ast::DUMMY_NODE_ID),
3739 span: span_with_semi,
3742 token::CloseDelim(token::Brace) => *last_block_expr = Some(e),
3744 stmts.push(P(Spanned {
3745 node: StmtExpr(e, ast::DUMMY_NODE_ID),
3752 // Parses a sequence of bounds if a `:` is found,
3753 // otherwise returns empty list.
3754 fn parse_colon_then_ty_param_bounds(&mut self,
3755 mode: BoundParsingMode)
3756 -> OwnedSlice<TyParamBound>
3758 if !self.eat(&token::Colon) {
3761 self.parse_ty_param_bounds(mode)
3765 // matches bounds = ( boundseq )?
3766 // where boundseq = ( polybound + boundseq ) | polybound
3767 // and polybound = ( 'for' '<' 'region '>' )? bound
3768 // and bound = 'region | trait_ref
3769 fn parse_ty_param_bounds(&mut self,
3770 mode: BoundParsingMode)
3771 -> OwnedSlice<TyParamBound>
3773 let mut result = vec!();
3775 let question_span = self.span;
3776 let ate_question = self.eat(&token::Question);
3778 token::Lifetime(lifetime) => {
3780 self.span_err(question_span,
3781 "`?` may only modify trait bounds, not lifetime bounds");
3783 result.push(RegionTyParamBound(ast::Lifetime {
3784 id: ast::DUMMY_NODE_ID,
3790 token::ModSep | token::Ident(..) => {
3791 let poly_trait_ref = self.parse_poly_trait_ref();
3792 let modifier = if ate_question {
3793 if mode == BoundParsingMode::Modified {
3794 TraitBoundModifier::Maybe
3796 self.span_err(question_span,
3798 TraitBoundModifier::None
3801 TraitBoundModifier::None
3803 result.push(TraitTyParamBound(poly_trait_ref, modifier))
3808 if !self.eat(&token::BinOp(token::Plus)) {
3813 return OwnedSlice::from_vec(result);
3816 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
3817 fn parse_ty_param(&mut self) -> TyParam {
3818 let span = self.span;
3819 let ident = self.parse_ident();
3821 let bounds = self.parse_colon_then_ty_param_bounds(BoundParsingMode::Modified);
3823 let default = if self.check(&token::Eq) {
3825 Some(self.parse_ty_sum())
3832 id: ast::DUMMY_NODE_ID,
3839 /// Parse a set of optional generic type parameter declarations. Where
3840 /// clauses are not parsed here, and must be added later via
3841 /// `parse_where_clause()`.
3843 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
3844 /// | ( < lifetimes , typaramseq ( , )? > )
3845 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
3846 pub fn parse_generics(&mut self) -> ast::Generics {
3847 if self.eat(&token::Lt) {
3848 let lifetime_defs = self.parse_lifetime_defs();
3849 let mut seen_default = false;
3850 let ty_params = self.parse_seq_to_gt(Some(token::Comma), |p| {
3851 p.forbid_lifetime();
3852 let ty_param = p.parse_ty_param();
3853 if ty_param.default.is_some() {
3854 seen_default = true;
3855 } else if seen_default {
3856 let last_span = p.last_span;
3857 p.span_err(last_span,
3858 "type parameters with a default must be trailing");
3863 lifetimes: lifetime_defs,
3864 ty_params: ty_params,
3865 where_clause: WhereClause {
3866 id: ast::DUMMY_NODE_ID,
3867 predicates: Vec::new(),
3871 ast_util::empty_generics()
3875 fn parse_generic_values_after_lt(&mut self)
3876 -> (Vec<ast::Lifetime>, Vec<P<Ty>>, Vec<P<TypeBinding>>) {
3877 let lifetimes = self.parse_lifetimes(token::Comma);
3879 // First parse types.
3880 let (types, returned) = self.parse_seq_to_gt_or_return(
3883 p.forbid_lifetime();
3884 if p.look_ahead(1, |t| t == &token::Eq) {
3887 Some(p.parse_ty_sum())
3892 // If we found the `>`, don't continue.
3894 return (lifetimes, types.into_vec(), Vec::new());
3897 // Then parse type bindings.
3898 let bindings = self.parse_seq_to_gt(
3901 p.forbid_lifetime();
3903 let ident = p.parse_ident();
3904 let found_eq = p.eat(&token::Eq);
3907 p.span_warn(span, "whoops, no =?");
3909 let ty = p.parse_ty();
3911 let span = mk_sp(lo, hi);
3912 return P(TypeBinding{id: ast::DUMMY_NODE_ID,
3919 (lifetimes, types.into_vec(), bindings.into_vec())
3922 fn forbid_lifetime(&mut self) {
3923 if self.token.is_lifetime() {
3924 let span = self.span;
3925 self.span_fatal(span, "lifetime parameters must be declared \
3926 prior to type parameters");
3930 /// Parses an optional `where` clause and places it in `generics`.
3933 /// where T : Trait<U, V> + 'b, 'a : 'b
3935 fn parse_where_clause(&mut self) -> ast::WhereClause {
3936 let mut where_clause = WhereClause {
3937 id: ast::DUMMY_NODE_ID,
3938 predicates: Vec::new(),
3941 if !self.eat_keyword(keywords::Where) {
3942 return where_clause;
3945 let mut parsed_something = false;
3947 let lo = self.span.lo;
3949 token::OpenDelim(token::Brace) => {
3953 token::Lifetime(..) => {
3954 let bounded_lifetime =
3955 self.parse_lifetime();
3957 self.eat(&token::Colon);
3960 self.parse_lifetimes(token::BinOp(token::Plus));
3962 let hi = self.span.hi;
3963 let span = mk_sp(lo, hi);
3965 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
3966 ast::WhereRegionPredicate {
3968 lifetime: bounded_lifetime,
3973 parsed_something = true;
3977 let bound_lifetimes = if self.eat_keyword(keywords::For) {
3978 // Higher ranked constraint.
3979 self.expect(&token::Lt);
3980 let lifetime_defs = self.parse_lifetime_defs();
3987 let bounded_ty = self.parse_ty();
3989 if self.eat(&token::Colon) {
3990 let bounds = self.parse_ty_param_bounds(BoundParsingMode::Bare);
3991 let hi = self.span.hi;
3992 let span = mk_sp(lo, hi);
3994 if bounds.len() == 0 {
3996 "each predicate in a `where` clause must have \
3997 at least one bound in it");
4000 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
4001 ast::WhereBoundPredicate {
4003 bound_lifetimes: bound_lifetimes,
4004 bounded_ty: bounded_ty,
4008 parsed_something = true;
4009 } else if self.eat(&token::Eq) {
4010 // let ty = self.parse_ty();
4011 let hi = self.span.hi;
4012 let span = mk_sp(lo, hi);
4013 // where_clause.predicates.push(
4014 // ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
4015 // id: ast::DUMMY_NODE_ID,
4017 // path: panic!("NYI"), //bounded_ty,
4020 // parsed_something = true;
4023 "equality constraints are not yet supported \
4024 in where clauses (#20041)");
4026 let last_span = self.last_span;
4027 self.span_err(last_span,
4028 "unexpected token in `where` clause");
4033 if !self.eat(&token::Comma) {
4038 if !parsed_something {
4039 let last_span = self.last_span;
4040 self.span_err(last_span,
4041 "a `where` clause must have at least one predicate \
4048 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
4049 -> (Vec<Arg> , bool) {
4051 let mut args: Vec<Option<Arg>> =
4052 self.parse_unspanned_seq(
4053 &token::OpenDelim(token::Paren),
4054 &token::CloseDelim(token::Paren),
4055 seq_sep_trailing_allowed(token::Comma),
4057 if p.token == token::DotDotDot {
4060 if p.token != token::CloseDelim(token::Paren) {
4063 "`...` must be last in argument list for variadic function");
4068 "only foreign functions are allowed to be variadic");
4072 Some(p.parse_arg_general(named_args))
4077 let variadic = match args.pop() {
4080 // Need to put back that last arg
4087 if variadic && args.is_empty() {
4089 "variadic function must be declared with at least one named argument");
4092 let args = args.into_iter().map(|x| x.unwrap()).collect();
4097 /// Parse the argument list and result type of a function declaration
4098 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> P<FnDecl> {
4100 let (args, variadic) = self.parse_fn_args(true, allow_variadic);
4101 let ret_ty = self.parse_ret_ty();
4110 fn is_self_ident(&mut self) -> bool {
4112 token::Ident(id, token::Plain) => id.name == special_idents::self_.name,
4117 fn expect_self_ident(&mut self) -> ast::Ident {
4119 token::Ident(id, token::Plain) if id.name == special_idents::self_.name => {
4124 let token_str = self.this_token_to_string();
4125 self.fatal(&format!("expected `self`, found `{}`",
4131 fn is_self_type_ident(&mut self) -> bool {
4133 token::Ident(id, token::Plain) => id.name == special_idents::type_self.name,
4138 fn expect_self_type_ident(&mut self) -> ast::Ident {
4140 token::Ident(id, token::Plain) if id.name == special_idents::type_self.name => {
4145 let token_str = self.this_token_to_string();
4146 self.fatal(&format!("expected `Self`, found `{}`",
4152 /// Parse the argument list and result type of a function
4153 /// that may have a self type.
4154 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> (ExplicitSelf, P<FnDecl>) where
4155 F: FnMut(&mut Parser) -> Arg,
4157 fn maybe_parse_borrowed_explicit_self(this: &mut Parser)
4158 -> ast::ExplicitSelf_ {
4159 // The following things are possible to see here:
4164 // fn(&'lt mut self)
4166 // We already know that the current token is `&`.
4168 if this.look_ahead(1, |t| t.is_keyword(keywords::SelfValue)) {
4170 SelfRegion(None, MutImmutable, this.expect_self_ident())
4171 } else if this.look_ahead(1, |t| t.is_mutability()) &&
4172 this.look_ahead(2, |t| t.is_keyword(keywords::SelfValue)) {
4174 let mutability = this.parse_mutability();
4175 SelfRegion(None, mutability, this.expect_self_ident())
4176 } else if this.look_ahead(1, |t| t.is_lifetime()) &&
4177 this.look_ahead(2, |t| t.is_keyword(keywords::SelfValue)) {
4179 let lifetime = this.parse_lifetime();
4180 SelfRegion(Some(lifetime), MutImmutable, this.expect_self_ident())
4181 } else if this.look_ahead(1, |t| t.is_lifetime()) &&
4182 this.look_ahead(2, |t| t.is_mutability()) &&
4183 this.look_ahead(3, |t| t.is_keyword(keywords::SelfValue)) {
4185 let lifetime = this.parse_lifetime();
4186 let mutability = this.parse_mutability();
4187 SelfRegion(Some(lifetime), mutability, this.expect_self_ident())
4193 self.expect(&token::OpenDelim(token::Paren));
4195 // A bit of complexity and lookahead is needed here in order to be
4196 // backwards compatible.
4197 let lo = self.span.lo;
4198 let mut self_ident_lo = self.span.lo;
4199 let mut self_ident_hi = self.span.hi;
4201 let mut mutbl_self = MutImmutable;
4202 let explicit_self = match self.token {
4203 token::BinOp(token::And) => {
4204 let eself = maybe_parse_borrowed_explicit_self(self);
4205 self_ident_lo = self.last_span.lo;
4206 self_ident_hi = self.last_span.hi;
4209 token::BinOp(token::Star) => {
4210 // Possibly "*self" or "*mut self" -- not supported. Try to avoid
4211 // emitting cryptic "unexpected token" errors.
4213 let _mutability = if self.token.is_mutability() {
4214 self.parse_mutability()
4218 if self.is_self_ident() {
4219 let span = self.span;
4220 self.span_err(span, "cannot pass self by unsafe pointer");
4223 // error case, making bogus self ident:
4224 SelfValue(special_idents::self_)
4226 token::Ident(..) => {
4227 if self.is_self_ident() {
4228 let self_ident = self.expect_self_ident();
4230 // Determine whether this is the fully explicit form, `self:
4232 if self.eat(&token::Colon) {
4233 SelfExplicit(self.parse_ty_sum(), self_ident)
4235 SelfValue(self_ident)
4237 } else if self.token.is_mutability() &&
4238 self.look_ahead(1, |t| t.is_keyword(keywords::SelfValue)) {
4239 mutbl_self = self.parse_mutability();
4240 let self_ident = self.expect_self_ident();
4242 // Determine whether this is the fully explicit form,
4244 if self.eat(&token::Colon) {
4245 SelfExplicit(self.parse_ty_sum(), self_ident)
4247 SelfValue(self_ident)
4256 let explicit_self_sp = mk_sp(self_ident_lo, self_ident_hi);
4258 // shared fall-through for the three cases below. borrowing prevents simply
4259 // writing this as a closure
4260 macro_rules! parse_remaining_arguments {
4263 // If we parsed a self type, expect a comma before the argument list.
4267 let sep = seq_sep_trailing_allowed(token::Comma);
4268 let mut fn_inputs = self.parse_seq_to_before_end(
4269 &token::CloseDelim(token::Paren),
4273 fn_inputs.insert(0, Arg::new_self(explicit_self_sp, mutbl_self, $self_id));
4276 token::CloseDelim(token::Paren) => {
4277 vec!(Arg::new_self(explicit_self_sp, mutbl_self, $self_id))
4280 let token_str = self.this_token_to_string();
4281 self.fatal(&format!("expected `,` or `)`, found `{}`",
4288 let fn_inputs = match explicit_self {
4290 let sep = seq_sep_trailing_allowed(token::Comma);
4291 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)
4293 SelfValue(id) => parse_remaining_arguments!(id),
4294 SelfRegion(_,_,id) => parse_remaining_arguments!(id),
4295 SelfExplicit(_,id) => parse_remaining_arguments!(id),
4299 self.expect(&token::CloseDelim(token::Paren));
4301 let hi = self.span.hi;
4303 let ret_ty = self.parse_ret_ty();
4305 let fn_decl = P(FnDecl {
4311 (spanned(lo, hi, explicit_self), fn_decl)
4314 // parse the |arg, arg| header on a lambda
4315 fn parse_fn_block_decl(&mut self) -> P<FnDecl> {
4316 let inputs_captures = {
4317 if self.eat(&token::OrOr) {
4320 self.expect(&token::BinOp(token::Or));
4321 self.parse_obsolete_closure_kind();
4322 let args = self.parse_seq_to_before_end(
4323 &token::BinOp(token::Or),
4324 seq_sep_trailing_allowed(token::Comma),
4325 |p| p.parse_fn_block_arg()
4331 let output = self.parse_ret_ty();
4334 inputs: inputs_captures,
4340 /// Parse the name and optional generic types of a function header.
4341 fn parse_fn_header(&mut self) -> (Ident, ast::Generics) {
4342 let id = self.parse_ident();
4343 let generics = self.parse_generics();
4347 fn mk_item(&mut self, lo: BytePos, hi: BytePos, ident: Ident,
4348 node: Item_, vis: Visibility,
4349 attrs: Vec<Attribute>) -> P<Item> {
4353 id: ast::DUMMY_NODE_ID,
4360 /// Parse an item-position function declaration.
4361 fn parse_item_fn(&mut self, unsafety: Unsafety, abi: abi::Abi) -> ItemInfo {
4362 let (ident, mut generics) = self.parse_fn_header();
4363 let decl = self.parse_fn_decl(false);
4364 generics.where_clause = self.parse_where_clause();
4365 let (inner_attrs, body) = self.parse_inner_attrs_and_block();
4366 (ident, ItemFn(decl, unsafety, abi, generics, body), Some(inner_attrs))
4369 /// Parse an impl item.
4370 pub fn parse_impl_item(&mut self) -> P<ImplItem> {
4371 let lo = self.span.lo;
4372 let mut attrs = self.parse_outer_attributes();
4373 let vis = self.parse_visibility();
4374 let (name, node) = if self.eat_keyword(keywords::Type) {
4375 let name = self.parse_ident();
4376 self.expect(&token::Eq);
4377 let typ = self.parse_ty_sum();
4378 self.expect(&token::Semi);
4379 (name, TypeImplItem(typ))
4381 let (name, inner_attrs, node) = self.parse_impl_method(vis);
4382 attrs.extend(inner_attrs.into_iter());
4387 id: ast::DUMMY_NODE_ID,
4388 span: mk_sp(lo, self.last_span.hi),
4396 fn complain_if_pub_macro(&mut self, visa: Visibility, span: Span) {
4399 self.span_err(span, "can't qualify macro invocation with `pub`");
4400 self.fileline_help(span, "try adjusting the macro to put `pub` inside \
4407 /// Parse a method or a macro invocation in a trait impl.
4408 fn parse_impl_method(&mut self, vis: Visibility)
4409 -> (Ident, Vec<ast::Attribute>, ast::ImplItem_) {
4410 // code copied from parse_macro_use_or_failure... abstraction!
4411 if !self.token.is_any_keyword()
4412 && self.look_ahead(1, |t| *t == token::Not)
4413 && (self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren))
4414 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) {
4417 let last_span = self.last_span;
4418 self.complain_if_pub_macro(vis, last_span);
4420 let pth = self.parse_path(NoTypesAllowed);
4421 self.expect(&token::Not);
4423 // eat a matched-delimiter token tree:
4424 let delim = self.expect_open_delim();
4425 let tts = self.parse_seq_to_end(&token::CloseDelim(delim),
4427 |p| p.parse_token_tree());
4428 let m_ = ast::MacInvocTT(pth, tts, EMPTY_CTXT);
4429 let m: ast::Mac = codemap::Spanned { node: m_,
4430 span: mk_sp(self.span.lo,
4432 if delim != token::Brace {
4433 self.expect(&token::Semi)
4435 (token::special_idents::invalid, vec![], ast::MacImplItem(m))
4437 let unsafety = self.parse_unsafety();
4438 let abi = if self.eat_keyword(keywords::Extern) {
4439 self.parse_opt_abi().unwrap_or(abi::C)
4443 self.expect_keyword(keywords::Fn);
4444 let ident = self.parse_ident();
4445 let mut generics = self.parse_generics();
4446 let (explicit_self, decl) = self.parse_fn_decl_with_self(|p| {
4449 generics.where_clause = self.parse_where_clause();
4450 let (inner_attrs, body) = self.parse_inner_attrs_and_block();
4451 (ident, inner_attrs, MethodImplItem(ast::MethodSig {
4454 explicit_self: explicit_self,
4461 /// Parse trait Foo { ... }
4462 fn parse_item_trait(&mut self, unsafety: Unsafety) -> ItemInfo {
4464 let ident = self.parse_ident();
4465 let mut tps = self.parse_generics();
4467 // Parse supertrait bounds.
4468 let bounds = self.parse_colon_then_ty_param_bounds(BoundParsingMode::Bare);
4470 tps.where_clause = self.parse_where_clause();
4472 let meths = self.parse_trait_items();
4473 (ident, ItemTrait(unsafety, tps, bounds, meths), None)
4476 /// Parses items implementations variants
4477 /// impl<T> Foo { ... }
4478 /// impl<T> ToString for &'static T { ... }
4479 /// impl Send for .. {}
4480 fn parse_item_impl(&mut self, unsafety: ast::Unsafety) -> ItemInfo {
4481 let impl_span = self.span;
4483 // First, parse type parameters if necessary.
4484 let mut generics = self.parse_generics();
4486 // Special case: if the next identifier that follows is '(', don't
4487 // allow this to be parsed as a trait.
4488 let could_be_trait = self.token != token::OpenDelim(token::Paren);
4490 let neg_span = self.span;
4491 let polarity = if self.eat(&token::Not) {
4492 ast::ImplPolarity::Negative
4494 ast::ImplPolarity::Positive
4498 let mut ty = self.parse_ty_sum();
4500 // Parse traits, if necessary.
4501 let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) {
4502 // New-style trait. Reinterpret the type as a trait.
4504 TyPath(None, ref path) => {
4506 path: (*path).clone(),
4511 self.span_err(ty.span, "not a trait");
4517 ast::ImplPolarity::Negative => {
4518 // This is a negated type implementation
4519 // `impl !MyType {}`, which is not allowed.
4520 self.span_err(neg_span, "inherent implementation can't be negated");
4527 if self.eat(&token::DotDot) {
4528 if generics.is_parameterized() {
4529 self.span_err(impl_span, "default trait implementations are not \
4530 allowed to have genercis");
4533 self.expect(&token::OpenDelim(token::Brace));
4534 self.expect(&token::CloseDelim(token::Brace));
4535 (ast_util::impl_pretty_name(&opt_trait, None),
4536 ItemDefaultImpl(unsafety, opt_trait.unwrap()), None)
4538 if opt_trait.is_some() {
4539 ty = self.parse_ty_sum();
4541 generics.where_clause = self.parse_where_clause();
4543 self.expect(&token::OpenDelim(token::Brace));
4544 let attrs = self.parse_inner_attributes();
4546 let mut impl_items = vec![];
4547 while !self.eat(&token::CloseDelim(token::Brace)) {
4548 impl_items.push(self.parse_impl_item());
4551 (ast_util::impl_pretty_name(&opt_trait, Some(&*ty)),
4552 ItemImpl(unsafety, polarity, generics, opt_trait, ty, impl_items),
4557 /// Parse a::B<String,i32>
4558 fn parse_trait_ref(&mut self) -> TraitRef {
4560 path: self.parse_path(LifetimeAndTypesWithoutColons),
4561 ref_id: ast::DUMMY_NODE_ID,
4565 fn parse_late_bound_lifetime_defs(&mut self) -> Vec<ast::LifetimeDef> {
4566 if self.eat_keyword(keywords::For) {
4567 self.expect(&token::Lt);
4568 let lifetime_defs = self.parse_lifetime_defs();
4576 /// Parse for<'l> a::B<String,i32>
4577 fn parse_poly_trait_ref(&mut self) -> PolyTraitRef {
4578 let lo = self.span.lo;
4579 let lifetime_defs = self.parse_late_bound_lifetime_defs();
4582 bound_lifetimes: lifetime_defs,
4583 trait_ref: self.parse_trait_ref(),
4584 span: mk_sp(lo, self.last_span.hi),
4588 /// Parse struct Foo { ... }
4589 fn parse_item_struct(&mut self) -> ItemInfo {
4590 let class_name = self.parse_ident();
4591 let mut generics = self.parse_generics();
4593 if self.eat(&token::Colon) {
4594 let ty = self.parse_ty_sum();
4595 self.span_err(ty.span, "`virtual` structs have been removed from the language");
4598 // There is a special case worth noting here, as reported in issue #17904.
4599 // If we are parsing a tuple struct it is the case that the where clause
4600 // should follow the field list. Like so:
4602 // struct Foo<T>(T) where T: Copy;
4604 // If we are parsing a normal record-style struct it is the case
4605 // that the where clause comes before the body, and after the generics.
4606 // So if we look ahead and see a brace or a where-clause we begin
4607 // parsing a record style struct.
4609 // Otherwise if we look ahead and see a paren we parse a tuple-style
4612 let (fields, ctor_id) = if self.token.is_keyword(keywords::Where) {
4613 generics.where_clause = self.parse_where_clause();
4614 if self.eat(&token::Semi) {
4615 // If we see a: `struct Foo<T> where T: Copy;` style decl.
4616 (Vec::new(), Some(ast::DUMMY_NODE_ID))
4618 // If we see: `struct Foo<T> where T: Copy { ... }`
4619 (self.parse_record_struct_body(&class_name), None)
4621 // No `where` so: `struct Foo<T>;`
4622 } else if self.eat(&token::Semi) {
4623 (Vec::new(), Some(ast::DUMMY_NODE_ID))
4624 // Record-style struct definition
4625 } else if self.token == token::OpenDelim(token::Brace) {
4626 let fields = self.parse_record_struct_body(&class_name);
4628 // Tuple-style struct definition with optional where-clause.
4630 let fields = self.parse_tuple_struct_body(&class_name, &mut generics);
4631 (fields, Some(ast::DUMMY_NODE_ID))
4635 ItemStruct(P(ast::StructDef {
4642 pub fn parse_record_struct_body(&mut self, class_name: &ast::Ident) -> Vec<StructField> {
4643 let mut fields = Vec::new();
4644 if self.eat(&token::OpenDelim(token::Brace)) {
4645 while self.token != token::CloseDelim(token::Brace) {
4646 fields.push(self.parse_struct_decl_field(true));
4649 if fields.len() == 0 {
4650 self.fatal(&format!("unit-like struct definition should be \
4651 written as `struct {};`",
4652 token::get_ident(class_name.clone())));
4657 let token_str = self.this_token_to_string();
4658 self.fatal(&format!("expected `where`, or `{}` after struct \
4659 name, found `{}`", "{",
4666 pub fn parse_tuple_struct_body(&mut self,
4667 class_name: &ast::Ident,
4668 generics: &mut ast::Generics)
4669 -> Vec<StructField> {
4670 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
4671 if self.check(&token::OpenDelim(token::Paren)) {
4672 let fields = self.parse_unspanned_seq(
4673 &token::OpenDelim(token::Paren),
4674 &token::CloseDelim(token::Paren),
4675 seq_sep_trailing_allowed(token::Comma),
4677 let attrs = p.parse_outer_attributes();
4679 let struct_field_ = ast::StructField_ {
4680 kind: UnnamedField(p.parse_visibility()),
4681 id: ast::DUMMY_NODE_ID,
4682 ty: p.parse_ty_sum(),
4685 spanned(lo, p.span.hi, struct_field_)
4688 if fields.len() == 0 {
4689 self.fatal(&format!("unit-like struct definition should be \
4690 written as `struct {};`",
4691 token::get_ident(class_name.clone())));
4694 generics.where_clause = self.parse_where_clause();
4695 self.expect(&token::Semi);
4697 // This is the case where we just see struct Foo<T> where T: Copy;
4698 } else if self.token.is_keyword(keywords::Where) {
4699 generics.where_clause = self.parse_where_clause();
4700 self.expect(&token::Semi);
4702 // This case is where we see: `struct Foo<T>;`
4704 let token_str = self.this_token_to_string();
4705 self.fatal(&format!("expected `where`, `{}`, `(`, or `;` after struct \
4706 name, found `{}`", "{", token_str));
4710 /// Parse a structure field declaration
4711 pub fn parse_single_struct_field(&mut self,
4713 attrs: Vec<Attribute> )
4715 let a_var = self.parse_name_and_ty(vis, attrs);
4720 token::CloseDelim(token::Brace) => {}
4722 let span = self.span;
4723 let token_str = self.this_token_to_string();
4724 self.span_fatal_help(span,
4725 &format!("expected `,`, or `}}`, found `{}`",
4727 "struct fields should be separated by commas")
4733 /// Parse an element of a struct definition
4734 fn parse_struct_decl_field(&mut self, allow_pub: bool) -> StructField {
4736 let attrs = self.parse_outer_attributes();
4738 if self.eat_keyword(keywords::Pub) {
4740 let span = self.last_span;
4741 self.span_err(span, "`pub` is not allowed here");
4743 return self.parse_single_struct_field(Public, attrs);
4746 return self.parse_single_struct_field(Inherited, attrs);
4749 /// Parse visibility: PUB, PRIV, or nothing
4750 fn parse_visibility(&mut self) -> Visibility {
4751 if self.eat_keyword(keywords::Pub) { Public }
4755 /// Given a termination token, parse all of the items in a module
4756 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: BytePos) -> Mod {
4757 let mut items = vec![];
4758 while let Some(item) = self.parse_item() {
4762 if !self.eat(term) {
4763 let token_str = self.this_token_to_string();
4764 self.fatal(&format!("expected item, found `{}`", token_str))
4768 inner: mk_sp(inner_lo, self.span.lo),
4773 fn parse_item_const(&mut self, m: Option<Mutability>) -> ItemInfo {
4774 let id = self.parse_ident();
4775 self.expect(&token::Colon);
4776 let ty = self.parse_ty_sum();
4777 self.expect(&token::Eq);
4778 let e = self.parse_expr();
4779 self.commit_expr_expecting(&*e, token::Semi);
4780 let item = match m {
4781 Some(m) => ItemStatic(ty, m, e),
4782 None => ItemConst(ty, e),
4787 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
4788 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> ItemInfo {
4789 let id_span = self.span;
4790 let id = self.parse_ident();
4791 if self.check(&token::Semi) {
4793 // This mod is in an external file. Let's go get it!
4794 let (m, attrs) = self.eval_src_mod(id, outer_attrs, id_span);
4795 (id, m, Some(attrs))
4797 self.push_mod_path(id, outer_attrs);
4798 self.expect(&token::OpenDelim(token::Brace));
4799 let mod_inner_lo = self.span.lo;
4800 let old_owns_directory = self.owns_directory;
4801 self.owns_directory = true;
4802 let attrs = self.parse_inner_attributes();
4803 let m = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo);
4804 self.owns_directory = old_owns_directory;
4805 self.pop_mod_path();
4806 (id, ItemMod(m), Some(attrs))
4810 fn push_mod_path(&mut self, id: Ident, attrs: &[Attribute]) {
4811 let default_path = self.id_to_interned_str(id);
4812 let file_path = match ::attr::first_attr_value_str_by_name(attrs,
4815 None => default_path,
4817 self.mod_path_stack.push(file_path)
4820 fn pop_mod_path(&mut self) {
4821 self.mod_path_stack.pop().unwrap();
4824 /// Read a module from a source file.
4825 fn eval_src_mod(&mut self,
4827 outer_attrs: &[ast::Attribute],
4829 -> (ast::Item_, Vec<ast::Attribute> ) {
4830 let mut prefix = PathBuf::from(&self.sess.span_diagnostic.cm
4831 .span_to_filename(self.span));
4833 let mut dir_path = prefix;
4834 for part in &self.mod_path_stack {
4835 dir_path.push(&**part);
4837 let mod_string = token::get_ident(id);
4838 let (file_path, owns_directory) = match ::attr::first_attr_value_str_by_name(
4839 outer_attrs, "path") {
4840 Some(d) => (dir_path.join(&*d), true),
4842 let mod_name = mod_string.to_string();
4843 let default_path_str = format!("{}.rs", mod_name);
4844 let secondary_path_str = format!("{}/mod.rs", mod_name);
4845 let default_path = dir_path.join(&default_path_str[..]);
4846 let secondary_path = dir_path.join(&secondary_path_str[..]);
4847 let default_exists = default_path.exists();
4848 let secondary_exists = secondary_path.exists();
4850 if !self.owns_directory {
4851 self.span_err(id_sp,
4852 "cannot declare a new module at this location");
4853 let this_module = match self.mod_path_stack.last() {
4854 Some(name) => name.to_string(),
4855 None => self.root_module_name.as_ref().unwrap().clone(),
4857 self.span_note(id_sp,
4858 &format!("maybe move this module `{0}` \
4859 to its own directory via \
4862 if default_exists || secondary_exists {
4863 self.span_note(id_sp,
4864 &format!("... or maybe `use` the module \
4865 `{}` instead of possibly \
4869 self.abort_if_errors();
4872 match (default_exists, secondary_exists) {
4873 (true, false) => (default_path, false),
4874 (false, true) => (secondary_path, true),
4876 self.span_fatal_help(id_sp,
4877 &format!("file not found for module `{}`",
4879 &format!("name the file either {} or {} inside \
4880 the directory {:?}",
4883 dir_path.display()));
4886 self.span_fatal_help(
4888 &format!("file for module `{}` found at both {} \
4892 secondary_path_str),
4893 "delete or rename one of them to remove the ambiguity");
4899 self.eval_src_mod_from_path(file_path, owns_directory,
4900 mod_string.to_string(), id_sp)
4903 fn eval_src_mod_from_path(&mut self,
4905 owns_directory: bool,
4907 id_sp: Span) -> (ast::Item_, Vec<ast::Attribute> ) {
4908 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
4909 match included_mod_stack.iter().position(|p| *p == path) {
4911 let mut err = String::from_str("circular modules: ");
4912 let len = included_mod_stack.len();
4913 for p in &included_mod_stack[i.. len] {
4914 err.push_str(&p.to_string_lossy());
4915 err.push_str(" -> ");
4917 err.push_str(&path.to_string_lossy());
4918 self.span_fatal(id_sp, &err[..]);
4922 included_mod_stack.push(path.clone());
4923 drop(included_mod_stack);
4926 new_sub_parser_from_file(self.sess,
4932 let mod_inner_lo = p0.span.lo;
4933 let mod_attrs = p0.parse_inner_attributes();
4934 let m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo);
4935 self.sess.included_mod_stack.borrow_mut().pop();
4936 (ast::ItemMod(m0), mod_attrs)
4939 /// Parse a function declaration from a foreign module
4940 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility,
4941 attrs: Vec<Attribute>) -> P<ForeignItem> {
4942 let lo = self.span.lo;
4943 self.expect_keyword(keywords::Fn);
4945 let (ident, mut generics) = self.parse_fn_header();
4946 let decl = self.parse_fn_decl(true);
4947 generics.where_clause = self.parse_where_clause();
4948 let hi = self.span.hi;
4949 self.expect(&token::Semi);
4950 P(ast::ForeignItem {
4953 node: ForeignItemFn(decl, generics),
4954 id: ast::DUMMY_NODE_ID,
4955 span: mk_sp(lo, hi),
4960 /// Parse a static item from a foreign module
4961 fn parse_item_foreign_static(&mut self, vis: ast::Visibility,
4962 attrs: Vec<Attribute>) -> P<ForeignItem> {
4963 let lo = self.span.lo;
4965 self.expect_keyword(keywords::Static);
4966 let mutbl = self.eat_keyword(keywords::Mut);
4968 let ident = self.parse_ident();
4969 self.expect(&token::Colon);
4970 let ty = self.parse_ty_sum();
4971 let hi = self.span.hi;
4972 self.expect(&token::Semi);
4976 node: ForeignItemStatic(ty, mutbl),
4977 id: ast::DUMMY_NODE_ID,
4978 span: mk_sp(lo, hi),
4983 /// Parse extern crate links
4987 /// extern crate url;
4988 /// extern crate foo = "bar"; //deprecated
4989 /// extern crate "bar" as foo;
4990 fn parse_item_extern_crate(&mut self,
4992 visibility: Visibility,
4993 attrs: Vec<Attribute>)
4996 let (maybe_path, ident) = match self.token {
4997 token::Ident(..) => {
4998 let crate_name = self.parse_ident();
4999 if self.eat_keyword(keywords::As) {
5000 (Some(crate_name.name), self.parse_ident())
5005 token::Literal(token::Str_(..), suf) |
5006 token::Literal(token::StrRaw(..), suf) => {
5008 self.expect_no_suffix(sp, "extern crate name", suf);
5009 // forgo the internal suffix check of `parse_str` to
5010 // avoid repeats (this unwrap will always succeed due
5011 // to the restriction of the `match`)
5012 let (s, _, _) = self.parse_optional_str().unwrap();
5013 self.expect_keyword(keywords::As);
5014 let the_ident = self.parse_ident();
5015 self.obsolete(sp, ObsoleteSyntax::ExternCrateString);
5016 let s = token::intern(&s);
5017 (Some(s), the_ident)
5020 let span = self.span;
5021 let token_str = self.this_token_to_string();
5022 self.span_fatal(span,
5023 &format!("expected extern crate name but \
5028 self.expect(&token::Semi);
5030 let last_span = self.last_span;
5034 ItemExternCrate(maybe_path),
5039 /// Parse `extern` for foreign ABIs
5042 /// `extern` is expected to have been
5043 /// consumed before calling this method
5049 fn parse_item_foreign_mod(&mut self,
5051 opt_abi: Option<abi::Abi>,
5052 visibility: Visibility,
5053 mut attrs: Vec<Attribute>)
5055 self.expect(&token::OpenDelim(token::Brace));
5057 let abi = opt_abi.unwrap_or(abi::C);
5059 attrs.extend(self.parse_inner_attributes().into_iter());
5061 let mut foreign_items = vec![];
5062 while let Some(item) = self.parse_foreign_item() {
5063 foreign_items.push(item);
5065 self.expect(&token::CloseDelim(token::Brace));
5067 let last_span = self.last_span;
5068 let m = ast::ForeignMod {
5070 items: foreign_items
5074 special_idents::invalid,
5080 /// Parse type Foo = Bar;
5081 fn parse_item_type(&mut self) -> ItemInfo {
5082 let ident = self.parse_ident();
5083 let mut tps = self.parse_generics();
5084 tps.where_clause = self.parse_where_clause();
5085 self.expect(&token::Eq);
5086 let ty = self.parse_ty_sum();
5087 self.expect(&token::Semi);
5088 (ident, ItemTy(ty, tps), None)
5091 /// Parse a structure-like enum variant definition
5092 /// this should probably be renamed or refactored...
5093 fn parse_struct_def(&mut self) -> P<StructDef> {
5094 let mut fields: Vec<StructField> = Vec::new();
5095 while self.token != token::CloseDelim(token::Brace) {
5096 fields.push(self.parse_struct_decl_field(false));
5106 /// Parse the part of an "enum" decl following the '{'
5107 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> EnumDef {
5108 let mut variants = Vec::new();
5109 let mut all_nullary = true;
5110 let mut any_disr = None;
5111 while self.token != token::CloseDelim(token::Brace) {
5112 let variant_attrs = self.parse_outer_attributes();
5113 let vlo = self.span.lo;
5115 let vis = self.parse_visibility();
5119 let mut args = Vec::new();
5120 let mut disr_expr = None;
5121 ident = self.parse_ident();
5122 if self.eat(&token::OpenDelim(token::Brace)) {
5123 // Parse a struct variant.
5124 all_nullary = false;
5125 let start_span = self.span;
5126 let struct_def = self.parse_struct_def();
5127 if struct_def.fields.len() == 0 {
5128 self.span_err(start_span,
5129 &format!("unit-like struct variant should be written \
5130 without braces, as `{},`",
5131 token::get_ident(ident)));
5133 kind = StructVariantKind(struct_def);
5134 } else if self.check(&token::OpenDelim(token::Paren)) {
5135 all_nullary = false;
5136 let arg_tys = self.parse_enum_variant_seq(
5137 &token::OpenDelim(token::Paren),
5138 &token::CloseDelim(token::Paren),
5139 seq_sep_trailing_allowed(token::Comma),
5140 |p| p.parse_ty_sum()
5143 args.push(ast::VariantArg {
5145 id: ast::DUMMY_NODE_ID,
5148 kind = TupleVariantKind(args);
5149 } else if self.eat(&token::Eq) {
5150 disr_expr = Some(self.parse_expr());
5151 any_disr = disr_expr.as_ref().map(|expr| expr.span);
5152 kind = TupleVariantKind(args);
5154 kind = TupleVariantKind(Vec::new());
5157 let vr = ast::Variant_ {
5159 attrs: variant_attrs,
5161 id: ast::DUMMY_NODE_ID,
5162 disr_expr: disr_expr,
5165 variants.push(P(spanned(vlo, self.last_span.hi, vr)));
5167 if !self.eat(&token::Comma) { break; }
5169 self.expect(&token::CloseDelim(token::Brace));
5171 Some(disr_span) if !all_nullary =>
5172 self.span_err(disr_span,
5173 "discriminator values can only be used with a c-like enum"),
5177 ast::EnumDef { variants: variants }
5180 /// Parse an "enum" declaration
5181 fn parse_item_enum(&mut self) -> ItemInfo {
5182 let id = self.parse_ident();
5183 let mut generics = self.parse_generics();
5184 generics.where_clause = self.parse_where_clause();
5185 self.expect(&token::OpenDelim(token::Brace));
5187 let enum_definition = self.parse_enum_def(&generics);
5188 (id, ItemEnum(enum_definition, generics), None)
5191 /// Parses a string as an ABI spec on an extern type or module. Consumes
5192 /// the `extern` keyword, if one is found.
5193 fn parse_opt_abi(&mut self) -> Option<abi::Abi> {
5195 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
5197 self.expect_no_suffix(sp, "ABI spec", suf);
5199 let the_string = s.as_str();
5200 match abi::lookup(the_string) {
5201 Some(abi) => Some(abi),
5203 let last_span = self.last_span;
5206 &format!("illegal ABI: expected one of [{}], \
5208 abi::all_names().connect(", "),
5219 /// Parse one of the items allowed by the flags.
5220 /// NB: this function no longer parses the items inside an
5222 fn parse_item_(&mut self, attrs: Vec<Attribute>,
5223 macros_allowed: bool) -> Option<P<Item>> {
5224 let nt_item = match self.token {
5225 token::Interpolated(token::NtItem(ref item)) => {
5226 Some((**item).clone())
5233 let mut attrs = attrs;
5234 mem::swap(&mut item.attrs, &mut attrs);
5235 item.attrs.extend(attrs.into_iter());
5236 return Some(P(item));
5241 let lo = self.span.lo;
5243 let visibility = self.parse_visibility();
5245 if self.eat_keyword(keywords::Use) {
5247 let item_ = ItemUse(self.parse_view_path());
5248 self.expect(&token::Semi);
5250 let last_span = self.last_span;
5251 let item = self.mk_item(lo,
5253 token::special_idents::invalid,
5260 if self.eat_keyword(keywords::Extern) {
5261 if self.eat_keyword(keywords::Crate) {
5262 return Some(self.parse_item_extern_crate(lo, visibility, attrs));
5265 let opt_abi = self.parse_opt_abi();
5267 if self.eat_keyword(keywords::Fn) {
5268 // EXTERN FUNCTION ITEM
5269 let abi = opt_abi.unwrap_or(abi::C);
5270 let (ident, item_, extra_attrs) =
5271 self.parse_item_fn(Unsafety::Normal, abi);
5272 let last_span = self.last_span;
5273 let item = self.mk_item(lo,
5278 maybe_append(attrs, extra_attrs));
5280 } else if self.check(&token::OpenDelim(token::Brace)) {
5281 return Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs));
5284 let span = self.span;
5285 let token_str = self.this_token_to_string();
5286 self.span_fatal(span,
5287 &format!("expected `{}` or `fn`, found `{}`", "{",
5291 if self.eat_keyword_noexpect(keywords::Virtual) {
5292 let span = self.span;
5293 self.span_err(span, "`virtual` structs have been removed from the language");
5296 if self.eat_keyword(keywords::Static) {
5298 let m = if self.eat_keyword(keywords::Mut) {MutMutable} else {MutImmutable};
5299 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m));
5300 let last_span = self.last_span;
5301 let item = self.mk_item(lo,
5306 maybe_append(attrs, extra_attrs));
5309 if self.eat_keyword(keywords::Const) {
5311 if self.eat_keyword(keywords::Mut) {
5312 let last_span = self.last_span;
5313 self.span_err(last_span, "const globals cannot be mutable");
5314 self.fileline_help(last_span, "did you mean to declare a static?");
5316 let (ident, item_, extra_attrs) = self.parse_item_const(None);
5317 let last_span = self.last_span;
5318 let item = self.mk_item(lo,
5323 maybe_append(attrs, extra_attrs));
5326 if self.check_keyword(keywords::Unsafe) &&
5327 self.look_ahead(1, |t| t.is_keyword(keywords::Trait))
5329 // UNSAFE TRAIT ITEM
5330 self.expect_keyword(keywords::Unsafe);
5331 self.expect_keyword(keywords::Trait);
5332 let (ident, item_, extra_attrs) =
5333 self.parse_item_trait(ast::Unsafety::Unsafe);
5334 let last_span = self.last_span;
5335 let item = self.mk_item(lo,
5340 maybe_append(attrs, extra_attrs));
5343 if self.check_keyword(keywords::Unsafe) &&
5344 self.look_ahead(1, |t| t.is_keyword(keywords::Impl))
5347 self.expect_keyword(keywords::Unsafe);
5348 self.expect_keyword(keywords::Impl);
5349 let (ident, item_, extra_attrs) = self.parse_item_impl(ast::Unsafety::Unsafe);
5350 let last_span = self.last_span;
5351 let item = self.mk_item(lo,
5356 maybe_append(attrs, extra_attrs));
5359 if self.check_keyword(keywords::Fn) {
5362 let (ident, item_, extra_attrs) =
5363 self.parse_item_fn(Unsafety::Normal, abi::Rust);
5364 let last_span = self.last_span;
5365 let item = self.mk_item(lo,
5370 maybe_append(attrs, extra_attrs));
5373 if self.check_keyword(keywords::Unsafe)
5374 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
5375 // UNSAFE FUNCTION ITEM
5377 let abi = if self.eat_keyword(keywords::Extern) {
5378 self.parse_opt_abi().unwrap_or(abi::C)
5382 self.expect_keyword(keywords::Fn);
5383 let (ident, item_, extra_attrs) =
5384 self.parse_item_fn(Unsafety::Unsafe, abi);
5385 let last_span = self.last_span;
5386 let item = self.mk_item(lo,
5391 maybe_append(attrs, extra_attrs));
5394 if self.eat_keyword(keywords::Mod) {
5396 let (ident, item_, extra_attrs) =
5397 self.parse_item_mod(&attrs[..]);
5398 let last_span = self.last_span;
5399 let item = self.mk_item(lo,
5404 maybe_append(attrs, extra_attrs));
5407 if self.eat_keyword(keywords::Type) {
5409 let (ident, item_, extra_attrs) = self.parse_item_type();
5410 let last_span = self.last_span;
5411 let item = self.mk_item(lo,
5416 maybe_append(attrs, extra_attrs));
5419 if self.eat_keyword(keywords::Enum) {
5421 let (ident, item_, extra_attrs) = self.parse_item_enum();
5422 let last_span = self.last_span;
5423 let item = self.mk_item(lo,
5428 maybe_append(attrs, extra_attrs));
5431 if self.eat_keyword(keywords::Trait) {
5433 let (ident, item_, extra_attrs) =
5434 self.parse_item_trait(ast::Unsafety::Normal);
5435 let last_span = self.last_span;
5436 let item = self.mk_item(lo,
5441 maybe_append(attrs, extra_attrs));
5444 if self.eat_keyword(keywords::Impl) {
5446 let (ident, item_, extra_attrs) = self.parse_item_impl(ast::Unsafety::Normal);
5447 let last_span = self.last_span;
5448 let item = self.mk_item(lo,
5453 maybe_append(attrs, extra_attrs));
5456 if self.eat_keyword(keywords::Struct) {
5458 let (ident, item_, extra_attrs) = self.parse_item_struct();
5459 let last_span = self.last_span;
5460 let item = self.mk_item(lo,
5465 maybe_append(attrs, extra_attrs));
5468 self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility)
5471 /// Parse a foreign item.
5472 fn parse_foreign_item(&mut self) -> Option<P<ForeignItem>> {
5473 let lo = self.span.lo;
5475 let attrs = self.parse_outer_attributes();
5476 let visibility = self.parse_visibility();
5478 if self.check_keyword(keywords::Static) {
5479 // FOREIGN STATIC ITEM
5480 return Some(self.parse_item_foreign_static(visibility, attrs));
5482 if self.check_keyword(keywords::Fn) || self.check_keyword(keywords::Unsafe) {
5483 // FOREIGN FUNCTION ITEM
5484 return Some(self.parse_item_foreign_fn(visibility, attrs));
5487 // FIXME #5668: this will occur for a macro invocation:
5488 match self.parse_macro_use_or_failure(attrs, true, lo, visibility) {
5490 self.span_fatal(item.span, "macros cannot expand to foreign items");
5496 /// This is the fall-through for parsing items.
5497 fn parse_macro_use_or_failure(
5499 attrs: Vec<Attribute> ,
5500 macros_allowed: bool,
5502 visibility: Visibility
5503 ) -> Option<P<Item>> {
5504 if macros_allowed && !self.token.is_any_keyword()
5505 && self.look_ahead(1, |t| *t == token::Not)
5506 && (self.look_ahead(2, |t| t.is_plain_ident())
5507 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren))
5508 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) {
5509 // MACRO INVOCATION ITEM
5511 let last_span = self.last_span;
5512 self.complain_if_pub_macro(visibility, last_span);
5515 let pth = self.parse_path(NoTypesAllowed);
5516 self.expect(&token::Not);
5518 // a 'special' identifier (like what `macro_rules!` uses)
5519 // is optional. We should eventually unify invoc syntax
5521 let id = if self.token.is_plain_ident() {
5524 token::special_idents::invalid // no special identifier
5526 // eat a matched-delimiter token tree:
5527 let delim = self.expect_open_delim();
5528 let tts = self.parse_seq_to_end(&token::CloseDelim(delim),
5530 |p| p.parse_token_tree());
5531 // single-variant-enum... :
5532 let m = ast::MacInvocTT(pth, tts, EMPTY_CTXT);
5533 let m: ast::Mac = codemap::Spanned { node: m,
5534 span: mk_sp(self.span.lo,
5537 if delim != token::Brace {
5538 if !self.eat(&token::Semi) {
5539 let last_span = self.last_span;
5540 self.span_err(last_span,
5541 "macros that expand to items must either \
5542 be surrounded with braces or followed by \
5547 let item_ = ItemMac(m);
5548 let last_span = self.last_span;
5549 let item = self.mk_item(lo,
5558 // FAILURE TO PARSE ITEM
5562 let last_span = self.last_span;
5563 self.span_fatal(last_span, "unmatched visibility `pub`");
5567 if !attrs.is_empty() {
5568 self.expected_item_err(&attrs);
5573 pub fn parse_item(&mut self) -> Option<P<Item>> {
5574 let attrs = self.parse_outer_attributes();
5575 self.parse_item_(attrs, true)
5578 /// Matches view_path : MOD? non_global_path as IDENT
5579 /// | MOD? non_global_path MOD_SEP LBRACE RBRACE
5580 /// | MOD? non_global_path MOD_SEP LBRACE ident_seq RBRACE
5581 /// | MOD? non_global_path MOD_SEP STAR
5582 /// | MOD? non_global_path
5583 fn parse_view_path(&mut self) -> P<ViewPath> {
5584 let lo = self.span.lo;
5586 // Allow a leading :: because the paths are absolute either way.
5587 // This occurs with "use $crate::..." in macros.
5588 self.eat(&token::ModSep);
5590 if self.check(&token::OpenDelim(token::Brace)) {
5592 let idents = self.parse_unspanned_seq(
5593 &token::OpenDelim(token::Brace),
5594 &token::CloseDelim(token::Brace),
5595 seq_sep_trailing_allowed(token::Comma),
5596 |p| p.parse_path_list_item());
5597 let path = ast::Path {
5598 span: mk_sp(lo, self.span.hi),
5600 segments: Vec::new()
5602 return P(spanned(lo, self.span.hi, ViewPathList(path, idents)));
5605 let first_ident = self.parse_ident();
5606 let mut path = vec!(first_ident);
5607 if let token::ModSep = self.token {
5608 // foo::bar or foo::{a,b,c} or foo::*
5609 while self.check(&token::ModSep) {
5613 token::Ident(..) => {
5614 let ident = self.parse_ident();
5618 // foo::bar::{a,b,c}
5619 token::OpenDelim(token::Brace) => {
5620 let idents = self.parse_unspanned_seq(
5621 &token::OpenDelim(token::Brace),
5622 &token::CloseDelim(token::Brace),
5623 seq_sep_trailing_allowed(token::Comma),
5624 |p| p.parse_path_list_item()
5626 let path = ast::Path {
5627 span: mk_sp(lo, self.span.hi),
5629 segments: path.into_iter().map(|identifier| {
5631 identifier: identifier,
5632 parameters: ast::PathParameters::none(),
5636 return P(spanned(lo, self.span.hi, ViewPathList(path, idents)));
5640 token::BinOp(token::Star) => {
5642 let path = ast::Path {
5643 span: mk_sp(lo, self.span.hi),
5645 segments: path.into_iter().map(|identifier| {
5647 identifier: identifier,
5648 parameters: ast::PathParameters::none(),
5652 return P(spanned(lo, self.span.hi, ViewPathGlob(path)));
5655 // fall-through for case foo::bar::;
5657 self.span_err(self.span, "expected identifier or `{` or `*`, found `;`");
5664 let mut rename_to = path[path.len() - 1];
5665 let path = ast::Path {
5666 span: mk_sp(lo, self.last_span.hi),
5668 segments: path.into_iter().map(|identifier| {
5670 identifier: identifier,
5671 parameters: ast::PathParameters::none(),
5675 if self.eat_keyword(keywords::As) {
5676 rename_to = self.parse_ident()
5678 P(spanned(lo, self.last_span.hi, ViewPathSimple(rename_to, path)))
5681 /// Parses a source module as a crate. This is the main
5682 /// entry point for the parser.
5683 pub fn parse_crate_mod(&mut self) -> Crate {
5684 let lo = self.span.lo;
5686 attrs: self.parse_inner_attributes(),
5687 module: self.parse_mod_items(&token::Eof, lo),
5688 config: self.cfg.clone(),
5689 span: mk_sp(lo, self.span.lo),
5690 exported_macros: Vec::new(),
5694 pub fn parse_optional_str(&mut self)
5695 -> Option<(InternedString, ast::StrStyle, Option<ast::Name>)> {
5696 let ret = match self.token {
5697 token::Literal(token::Str_(s), suf) => {
5698 (self.id_to_interned_str(s.ident()), ast::CookedStr, suf)
5700 token::Literal(token::StrRaw(s, n), suf) => {
5701 (self.id_to_interned_str(s.ident()), ast::RawStr(n), suf)
5709 pub fn parse_str(&mut self) -> (InternedString, StrStyle) {
5710 match self.parse_optional_str() {
5711 Some((s, style, suf)) => {
5712 let sp = self.last_span;
5713 self.expect_no_suffix(sp, "str literal", suf);
5716 _ => self.fatal("expected string literal")