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, Clone, 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, Clone, 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) => {
2317 let ix = self.parse_expr();
2319 self.commit_expr_expecting(&*ix, token::CloseDelim(token::Bracket));
2320 let index = self.mk_index(e, ix);
2321 e = self.mk_expr(lo, hi, index)
2329 // Parse unquoted tokens after a `$` in a token tree
2330 fn parse_unquoted(&mut self) -> TokenTree {
2331 let mut sp = self.span;
2332 let (name, namep) = match self.token {
2336 if self.token == token::OpenDelim(token::Paren) {
2337 let Spanned { node: seq, span: seq_span } = self.parse_seq(
2338 &token::OpenDelim(token::Paren),
2339 &token::CloseDelim(token::Paren),
2341 |p| p.parse_token_tree()
2343 let (sep, repeat) = self.parse_sep_and_kleene_op();
2344 let name_num = macro_parser::count_names(&seq);
2345 return TtSequence(mk_sp(sp.lo, seq_span.hi),
2346 Rc::new(SequenceRepetition {
2350 num_captures: name_num
2352 } else if self.token.is_keyword_allow_following_colon(keywords::Crate) {
2354 return TtToken(sp, SpecialVarNt(SpecialMacroVar::CrateMacroVar));
2356 sp = mk_sp(sp.lo, self.span.hi);
2357 let namep = match self.token { token::Ident(_, p) => p, _ => token::Plain };
2358 let name = self.parse_ident();
2362 token::SubstNt(name, namep) => {
2368 // continue by trying to parse the `:ident` after `$name`
2369 if self.token == token::Colon && self.look_ahead(1, |t| t.is_ident() &&
2370 !t.is_strict_keyword() &&
2371 !t.is_reserved_keyword()) {
2373 sp = mk_sp(sp.lo, self.span.hi);
2374 let kindp = match self.token { token::Ident(_, p) => p, _ => token::Plain };
2375 let nt_kind = self.parse_ident();
2376 TtToken(sp, MatchNt(name, nt_kind, namep, kindp))
2378 TtToken(sp, SubstNt(name, namep))
2382 pub fn check_unknown_macro_variable(&mut self) {
2383 if self.quote_depth == 0 {
2385 token::SubstNt(name, _) =>
2386 self.fatal(&format!("unknown macro variable `{}`",
2387 token::get_ident(name))),
2393 /// Parse an optional separator followed by a Kleene-style
2394 /// repetition token (+ or *).
2395 pub fn parse_sep_and_kleene_op(&mut self) -> (Option<token::Token>, ast::KleeneOp) {
2396 fn parse_kleene_op(parser: &mut Parser) -> Option<ast::KleeneOp> {
2397 match parser.token {
2398 token::BinOp(token::Star) => {
2400 Some(ast::ZeroOrMore)
2402 token::BinOp(token::Plus) => {
2404 Some(ast::OneOrMore)
2410 match parse_kleene_op(self) {
2411 Some(kleene_op) => return (None, kleene_op),
2415 let separator = self.bump_and_get();
2416 match parse_kleene_op(self) {
2417 Some(zerok) => (Some(separator), zerok),
2418 None => self.fatal("expected `*` or `+`")
2422 /// parse a single token tree from the input.
2423 pub fn parse_token_tree(&mut self) -> TokenTree {
2424 // FIXME #6994: currently, this is too eager. It
2425 // parses token trees but also identifies TtSequence's
2426 // and token::SubstNt's; it's too early to know yet
2427 // whether something will be a nonterminal or a seq
2429 maybe_whole!(deref self, NtTT);
2431 // this is the fall-through for the 'match' below.
2432 // invariants: the current token is not a left-delimiter,
2433 // not an EOF, and not the desired right-delimiter (if
2434 // it were, parse_seq_to_before_end would have prevented
2435 // reaching this point.
2436 fn parse_non_delim_tt_tok(p: &mut Parser) -> TokenTree {
2437 maybe_whole!(deref p, NtTT);
2439 token::CloseDelim(_) => {
2440 // This is a conservative error: only report the last unclosed delimiter. The
2441 // previous unclosed delimiters could actually be closed! The parser just hasn't
2442 // gotten to them yet.
2443 match p.open_braces.last() {
2445 Some(&sp) => p.span_note(sp, "unclosed delimiter"),
2447 let token_str = p.this_token_to_string();
2448 p.fatal(&format!("incorrect close delimiter: `{}`",
2451 /* we ought to allow different depths of unquotation */
2452 token::Dollar | token::SubstNt(..) if p.quote_depth > 0 => {
2456 TtToken(p.span, p.bump_and_get())
2463 let open_braces = self.open_braces.clone();
2464 for sp in &open_braces {
2465 self.span_help(*sp, "did you mean to close this delimiter?");
2467 // There shouldn't really be a span, but it's easier for the test runner
2468 // if we give it one
2469 self.fatal("this file contains an un-closed delimiter ");
2471 token::OpenDelim(delim) => {
2472 // The span for beginning of the delimited section
2473 let pre_span = self.span;
2475 // Parse the open delimiter.
2476 self.open_braces.push(self.span);
2477 let open_span = self.span;
2480 // Parse the token trees within the delimiters
2481 let tts = self.parse_seq_to_before_end(
2482 &token::CloseDelim(delim),
2484 |p| p.parse_token_tree()
2487 // Parse the close delimiter.
2488 let close_span = self.span;
2490 self.open_braces.pop().unwrap();
2492 // Expand to cover the entire delimited token tree
2493 let span = Span { hi: close_span.hi, ..pre_span };
2495 TtDelimited(span, Rc::new(Delimited {
2497 open_span: open_span,
2499 close_span: close_span,
2502 _ => parse_non_delim_tt_tok(self),
2506 // parse a stream of tokens into a list of TokenTree's,
2508 pub fn parse_all_token_trees(&mut self) -> Vec<TokenTree> {
2509 let mut tts = Vec::new();
2510 while self.token != token::Eof {
2511 tts.push(self.parse_token_tree());
2516 /// Parse a prefix-operator expr
2517 pub fn parse_prefix_expr(&mut self) -> P<Expr> {
2518 let lo = self.span.lo;
2521 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2526 let e = self.parse_prefix_expr();
2528 ex = self.mk_unary(UnNot, e);
2530 token::BinOp(token::Minus) => {
2532 let e = self.parse_prefix_expr();
2534 ex = self.mk_unary(UnNeg, e);
2536 token::BinOp(token::Star) => {
2538 let e = self.parse_prefix_expr();
2540 ex = self.mk_unary(UnDeref, e);
2542 token::BinOp(token::And) | token::AndAnd => {
2544 let m = self.parse_mutability();
2545 let e = self.parse_prefix_expr();
2547 ex = ExprAddrOf(m, e);
2549 token::Ident(_, _) => {
2550 if !self.check_keyword(keywords::Box) {
2551 return self.parse_dot_or_call_expr();
2554 let lo = self.span.lo;
2558 // Check for a place: `box(PLACE) EXPR`.
2559 if self.eat(&token::OpenDelim(token::Paren)) {
2560 // Support `box() EXPR` as the default.
2561 if !self.eat(&token::CloseDelim(token::Paren)) {
2562 let place = self.parse_expr();
2563 self.expect(&token::CloseDelim(token::Paren));
2564 // Give a suggestion to use `box()` when a parenthesised expression is used
2565 if !self.token.can_begin_expr() {
2566 let span = self.span;
2567 let this_token_to_string = self.this_token_to_string();
2569 &format!("expected expression, found `{}`",
2570 this_token_to_string));
2571 let box_span = mk_sp(lo, self.last_span.hi);
2572 self.span_help(box_span,
2573 "perhaps you meant `box() (foo)` instead?");
2574 self.abort_if_errors();
2576 let subexpression = self.parse_prefix_expr();
2577 hi = subexpression.span.hi;
2578 ex = ExprBox(Some(place), subexpression);
2579 return self.mk_expr(lo, hi, ex);
2583 // Otherwise, we use the unique pointer default.
2584 let subexpression = self.parse_prefix_expr();
2585 hi = subexpression.span.hi;
2586 // FIXME (pnkfelix): After working out kinks with box
2587 // desugaring, should be `ExprBox(None, subexpression)`
2589 ex = self.mk_unary(UnUniq, subexpression);
2591 _ => return self.parse_dot_or_call_expr()
2593 return self.mk_expr(lo, hi, ex);
2596 /// Parse an expression of binops
2597 pub fn parse_binops(&mut self) -> P<Expr> {
2598 let prefix_expr = self.parse_prefix_expr();
2599 self.parse_more_binops(prefix_expr, 0)
2602 /// Parse an expression of binops of at least min_prec precedence
2603 pub fn parse_more_binops(&mut self, lhs: P<Expr>, min_prec: usize) -> P<Expr> {
2604 if self.expr_is_complete(&*lhs) { return lhs; }
2606 // Prevent dynamic borrow errors later on by limiting the
2607 // scope of the borrows.
2608 if self.token == token::BinOp(token::Or) &&
2609 self.restrictions.contains(RESTRICTION_NO_BAR_OP) {
2613 self.expected_tokens.push(TokenType::Operator);
2615 let cur_op_span = self.span;
2616 let cur_opt = self.token.to_binop();
2619 if ast_util::is_comparison_binop(cur_op) {
2620 self.check_no_chained_comparison(&*lhs, cur_op)
2622 let cur_prec = operator_prec(cur_op);
2623 if cur_prec >= min_prec {
2625 let expr = self.parse_prefix_expr();
2626 let rhs = self.parse_more_binops(expr, cur_prec + 1);
2627 let lhs_span = lhs.span;
2628 let rhs_span = rhs.span;
2629 let binary = self.mk_binary(codemap::respan(cur_op_span, cur_op), lhs, rhs);
2630 let bin = self.mk_expr(lhs_span.lo, rhs_span.hi, binary);
2631 self.parse_more_binops(bin, min_prec)
2637 if AS_PREC >= min_prec && self.eat_keyword_noexpect(keywords::As) {
2638 let rhs = self.parse_ty();
2639 let _as = self.mk_expr(lhs.span.lo,
2641 ExprCast(lhs, rhs));
2642 self.parse_more_binops(_as, min_prec)
2650 /// Produce an error if comparison operators are chained (RFC #558).
2651 /// We only need to check lhs, not rhs, because all comparison ops
2652 /// have same precedence and are left-associative
2653 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: ast::BinOp_) {
2654 debug_assert!(ast_util::is_comparison_binop(outer_op));
2656 ExprBinary(op, _, _) if ast_util::is_comparison_binop(op.node) => {
2657 // respan to include both operators
2658 let op_span = mk_sp(op.span.lo, self.span.hi);
2659 self.span_err(op_span,
2660 "chained comparison operators require parentheses");
2661 if op.node == BiLt && outer_op == BiGt {
2662 self.fileline_help(op_span,
2663 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
2670 /// Parse an assignment expression....
2671 /// actually, this seems to be the main entry point for
2672 /// parsing an arbitrary expression.
2673 pub fn parse_assign_expr(&mut self) -> P<Expr> {
2676 // prefix-form of range notation '..expr'
2677 // This has the same precedence as assignment expressions
2678 // (much lower than other prefix expressions) to be consistent
2679 // with the postfix-form 'expr..'
2680 let lo = self.span.lo;
2682 let opt_end = if self.is_at_start_of_range_notation_rhs() {
2683 let end = self.parse_binops();
2688 let hi = self.span.hi;
2689 let ex = self.mk_range(None, opt_end);
2690 self.mk_expr(lo, hi, ex)
2693 let lhs = self.parse_binops();
2694 self.parse_assign_expr_with(lhs)
2699 pub fn parse_assign_expr_with(&mut self, lhs: P<Expr>) -> P<Expr> {
2700 let restrictions = self.restrictions & RESTRICTION_NO_STRUCT_LITERAL;
2701 let op_span = self.span;
2705 let rhs = self.parse_expr_res(restrictions);
2706 self.mk_expr(lhs.span.lo, rhs.span.hi, ExprAssign(lhs, rhs))
2708 token::BinOpEq(op) => {
2710 let rhs = self.parse_expr_res(restrictions);
2711 let aop = match op {
2712 token::Plus => BiAdd,
2713 token::Minus => BiSub,
2714 token::Star => BiMul,
2715 token::Slash => BiDiv,
2716 token::Percent => BiRem,
2717 token::Caret => BiBitXor,
2718 token::And => BiBitAnd,
2719 token::Or => BiBitOr,
2720 token::Shl => BiShl,
2723 let rhs_span = rhs.span;
2724 let span = lhs.span;
2725 let assign_op = self.mk_assign_op(codemap::respan(op_span, aop), lhs, rhs);
2726 self.mk_expr(span.lo, rhs_span.hi, assign_op)
2728 // A range expression, either `expr..expr` or `expr..`.
2732 let opt_end = if self.is_at_start_of_range_notation_rhs() {
2733 let end = self.parse_binops();
2739 let lo = lhs.span.lo;
2740 let hi = self.span.hi;
2741 let range = self.mk_range(Some(lhs), opt_end);
2742 return self.mk_expr(lo, hi, range);
2751 fn is_at_start_of_range_notation_rhs(&self) -> bool {
2752 if self.token.can_begin_expr() {
2753 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
2754 if self.token == token::OpenDelim(token::Brace) {
2755 return !self.restrictions.contains(RESTRICTION_NO_STRUCT_LITERAL);
2763 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
2764 pub fn parse_if_expr(&mut self) -> P<Expr> {
2765 if self.check_keyword(keywords::Let) {
2766 return self.parse_if_let_expr();
2768 let lo = self.last_span.lo;
2769 let cond = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
2770 let thn = self.parse_block();
2771 let mut els: Option<P<Expr>> = None;
2772 let mut hi = thn.span.hi;
2773 if self.eat_keyword(keywords::Else) {
2774 let elexpr = self.parse_else_expr();
2775 hi = elexpr.span.hi;
2778 self.mk_expr(lo, hi, ExprIf(cond, thn, els))
2781 /// Parse an 'if let' expression ('if' token already eaten)
2782 pub fn parse_if_let_expr(&mut self) -> P<Expr> {
2783 let lo = self.last_span.lo;
2784 self.expect_keyword(keywords::Let);
2785 let pat = self.parse_pat();
2786 self.expect(&token::Eq);
2787 let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
2788 let thn = self.parse_block();
2789 let (hi, els) = if self.eat_keyword(keywords::Else) {
2790 let expr = self.parse_else_expr();
2791 (expr.span.hi, Some(expr))
2795 self.mk_expr(lo, hi, ExprIfLet(pat, expr, thn, els))
2799 pub fn parse_lambda_expr(&mut self, capture_clause: CaptureClause)
2802 let lo = self.span.lo;
2803 let decl = self.parse_fn_block_decl();
2804 let body = match decl.output {
2805 DefaultReturn(_) => {
2806 // If no explicit return type is given, parse any
2807 // expr and wrap it up in a dummy block:
2808 let body_expr = self.parse_expr();
2810 id: ast::DUMMY_NODE_ID,
2812 span: body_expr.span,
2813 expr: Some(body_expr),
2814 rules: DefaultBlock,
2818 // If an explicit return type is given, require a
2819 // block to appear (RFC 968).
2827 ExprClosure(capture_clause, decl, body))
2830 pub fn parse_else_expr(&mut self) -> P<Expr> {
2831 if self.eat_keyword(keywords::If) {
2832 return self.parse_if_expr();
2834 let blk = self.parse_block();
2835 return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk));
2839 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
2840 pub fn parse_for_expr(&mut self, opt_ident: Option<ast::Ident>) -> P<Expr> {
2841 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
2843 let lo = self.last_span.lo;
2844 let pat = self.parse_pat();
2845 self.expect_keyword(keywords::In);
2846 let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
2847 let loop_block = self.parse_block();
2848 let hi = self.span.hi;
2850 self.mk_expr(lo, hi, ExprForLoop(pat, expr, loop_block, opt_ident))
2853 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
2854 pub fn parse_while_expr(&mut self, opt_ident: Option<ast::Ident>) -> P<Expr> {
2855 if self.token.is_keyword(keywords::Let) {
2856 return self.parse_while_let_expr(opt_ident);
2858 let lo = self.last_span.lo;
2859 let cond = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
2860 let body = self.parse_block();
2861 let hi = body.span.hi;
2862 return self.mk_expr(lo, hi, ExprWhile(cond, body, opt_ident));
2865 /// Parse a 'while let' expression ('while' token already eaten)
2866 pub fn parse_while_let_expr(&mut self, opt_ident: Option<ast::Ident>) -> P<Expr> {
2867 let lo = self.last_span.lo;
2868 self.expect_keyword(keywords::Let);
2869 let pat = self.parse_pat();
2870 self.expect(&token::Eq);
2871 let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
2872 let body = self.parse_block();
2873 let hi = body.span.hi;
2874 return self.mk_expr(lo, hi, ExprWhileLet(pat, expr, body, opt_ident));
2877 pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::Ident>) -> P<Expr> {
2878 let lo = self.last_span.lo;
2879 let body = self.parse_block();
2880 let hi = body.span.hi;
2881 self.mk_expr(lo, hi, ExprLoop(body, opt_ident))
2884 fn parse_match_expr(&mut self) -> P<Expr> {
2885 let lo = self.last_span.lo;
2886 let discriminant = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
2887 self.commit_expr_expecting(&*discriminant, token::OpenDelim(token::Brace));
2888 let mut arms: Vec<Arm> = Vec::new();
2889 while self.token != token::CloseDelim(token::Brace) {
2890 arms.push(self.parse_arm());
2892 let hi = self.span.hi;
2894 return self.mk_expr(lo, hi, ExprMatch(discriminant, arms, MatchSource::Normal));
2897 pub fn parse_arm(&mut self) -> Arm {
2898 let attrs = self.parse_outer_attributes();
2899 let pats = self.parse_pats();
2900 let mut guard = None;
2901 if self.eat_keyword(keywords::If) {
2902 guard = Some(self.parse_expr());
2904 self.expect(&token::FatArrow);
2905 let expr = self.parse_expr_res(RESTRICTION_STMT_EXPR);
2908 !classify::expr_is_simple_block(&*expr)
2909 && self.token != token::CloseDelim(token::Brace);
2912 self.commit_expr(&*expr, &[token::Comma], &[token::CloseDelim(token::Brace)]);
2914 self.eat(&token::Comma);
2925 /// Parse an expression
2926 pub fn parse_expr(&mut self) -> P<Expr> {
2927 return self.parse_expr_res(UNRESTRICTED);
2930 /// Parse an expression, subject to the given restrictions
2931 pub fn parse_expr_res(&mut self, r: Restrictions) -> P<Expr> {
2932 let old = self.restrictions;
2933 self.restrictions = r;
2934 let e = self.parse_assign_expr();
2935 self.restrictions = old;
2939 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
2940 fn parse_initializer(&mut self) -> Option<P<Expr>> {
2941 if self.check(&token::Eq) {
2943 Some(self.parse_expr())
2949 /// Parse patterns, separated by '|' s
2950 fn parse_pats(&mut self) -> Vec<P<Pat>> {
2951 let mut pats = Vec::new();
2953 pats.push(self.parse_pat());
2954 if self.check(&token::BinOp(token::Or)) { self.bump(); }
2955 else { return pats; }
2959 fn parse_pat_vec_elements(
2961 ) -> (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>) {
2962 let mut before = Vec::new();
2963 let mut slice = None;
2964 let mut after = Vec::new();
2965 let mut first = true;
2966 let mut before_slice = true;
2968 while self.token != token::CloseDelim(token::Bracket) {
2972 self.expect(&token::Comma);
2974 if self.token == token::CloseDelim(token::Bracket)
2975 && (before_slice || after.len() != 0) {
2981 if self.check(&token::DotDot) {
2984 if self.check(&token::Comma) ||
2985 self.check(&token::CloseDelim(token::Bracket)) {
2986 slice = Some(P(ast::Pat {
2987 id: ast::DUMMY_NODE_ID,
2988 node: PatWild(PatWildMulti),
2991 before_slice = false;
2997 let subpat = self.parse_pat();
2998 if before_slice && self.check(&token::DotDot) {
3000 slice = Some(subpat);
3001 before_slice = false;
3002 } else if before_slice {
3003 before.push(subpat);
3009 (before, slice, after)
3012 /// Parse the fields of a struct-like pattern
3013 fn parse_pat_fields(&mut self) -> (Vec<codemap::Spanned<ast::FieldPat>> , bool) {
3014 let mut fields = Vec::new();
3015 let mut etc = false;
3016 let mut first = true;
3017 while self.token != token::CloseDelim(token::Brace) {
3021 self.expect(&token::Comma);
3022 // accept trailing commas
3023 if self.check(&token::CloseDelim(token::Brace)) { break }
3026 let lo = self.span.lo;
3029 if self.check(&token::DotDot) {
3031 if self.token != token::CloseDelim(token::Brace) {
3032 let token_str = self.this_token_to_string();
3033 self.fatal(&format!("expected `{}`, found `{}`", "}",
3040 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3041 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3042 // Parsing a pattern of the form "fieldname: pat"
3043 let fieldname = self.parse_ident();
3045 let pat = self.parse_pat();
3047 (pat, fieldname, false)
3049 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3050 let is_box = self.eat_keyword(keywords::Box);
3051 let boxed_span_lo = self.span.lo;
3052 let is_ref = self.eat_keyword(keywords::Ref);
3053 let is_mut = self.eat_keyword(keywords::Mut);
3054 let fieldname = self.parse_ident();
3055 hi = self.last_span.hi;
3057 let bind_type = match (is_ref, is_mut) {
3058 (true, true) => BindByRef(MutMutable),
3059 (true, false) => BindByRef(MutImmutable),
3060 (false, true) => BindByValue(MutMutable),
3061 (false, false) => BindByValue(MutImmutable),
3063 let fieldpath = codemap::Spanned{span:self.last_span, node:fieldname};
3064 let fieldpat = P(ast::Pat{
3065 id: ast::DUMMY_NODE_ID,
3066 node: PatIdent(bind_type, fieldpath, None),
3067 span: mk_sp(boxed_span_lo, hi),
3070 let subpat = if is_box {
3072 id: ast::DUMMY_NODE_ID,
3073 node: PatBox(fieldpat),
3074 span: mk_sp(lo, hi),
3079 (subpat, fieldname, true)
3082 fields.push(codemap::Spanned { span: mk_sp(lo, hi),
3083 node: ast::FieldPat { ident: fieldname,
3085 is_shorthand: is_shorthand }});
3087 return (fields, etc);
3090 /// Parse a pattern.
3091 pub fn parse_pat(&mut self) -> P<Pat> {
3092 maybe_whole!(self, NtPat);
3094 let lo = self.span.lo;
3099 token::Underscore => {
3101 pat = PatWild(PatWildSingle);
3102 hi = self.last_span.hi;
3104 id: ast::DUMMY_NODE_ID,
3109 token::BinOp(token::And) | token::AndAnd => {
3110 // parse &pat and &mut pat
3111 let lo = self.span.lo;
3113 let mutability = if self.eat_keyword(keywords::Mut) {
3118 let sub = self.parse_pat();
3119 pat = PatRegion(sub, mutability);
3120 hi = self.last_span.hi;
3122 id: ast::DUMMY_NODE_ID,
3127 token::OpenDelim(token::Paren) => {
3128 // parse (pat,pat,pat,...) as tuple
3130 if self.check(&token::CloseDelim(token::Paren)) {
3132 pat = PatTup(vec![]);
3134 let mut fields = vec!(self.parse_pat());
3135 if self.look_ahead(1, |t| *t != token::CloseDelim(token::Paren)) {
3136 while self.check(&token::Comma) {
3138 if self.check(&token::CloseDelim(token::Paren)) { break; }
3139 fields.push(self.parse_pat());
3142 if fields.len() == 1 { self.expect(&token::Comma); }
3143 self.expect(&token::CloseDelim(token::Paren));
3144 pat = PatTup(fields);
3146 hi = self.last_span.hi;
3148 id: ast::DUMMY_NODE_ID,
3153 token::OpenDelim(token::Bracket) => {
3154 // parse [pat,pat,...] as vector pattern
3156 let (before, slice, after) =
3157 self.parse_pat_vec_elements();
3159 self.expect(&token::CloseDelim(token::Bracket));
3160 pat = ast::PatVec(before, slice, after);
3161 hi = self.last_span.hi;
3163 id: ast::DUMMY_NODE_ID,
3170 // at this point, token != _, ~, &, &&, (, [
3172 if (!(self.token.is_ident() || self.token.is_path())
3173 && self.token != token::ModSep)
3174 || self.token.is_keyword(keywords::True)
3175 || self.token.is_keyword(keywords::False) {
3176 // Parse an expression pattern or exp ... exp.
3178 // These expressions are limited to literals (possibly
3179 // preceded by unary-minus) or identifiers.
3180 let val = self.parse_literal_maybe_minus();
3181 if (self.check(&token::DotDotDot)) &&
3182 self.look_ahead(1, |t| {
3183 *t != token::Comma && *t != token::CloseDelim(token::Bracket)
3186 let end = if self.token.is_ident() || self.token.is_path() {
3187 let path = self.parse_path(LifetimeAndTypesWithColons);
3188 let hi = self.span.hi;
3189 self.mk_expr(lo, hi, ExprPath(None, path))
3191 self.parse_literal_maybe_minus()
3193 pat = PatRange(val, end);
3197 } else if self.eat_keyword(keywords::Mut) {
3198 pat = self.parse_pat_ident(BindByValue(MutMutable));
3199 } else if self.eat_keyword(keywords::Ref) {
3201 let mutbl = self.parse_mutability();
3202 pat = self.parse_pat_ident(BindByRef(mutbl));
3203 } else if self.eat_keyword(keywords::Box) {
3206 // FIXME(#13910): Rename to `PatBox` and extend to full DST
3208 let sub = self.parse_pat();
3210 hi = self.last_span.hi;
3212 id: ast::DUMMY_NODE_ID,
3217 let can_be_enum_or_struct = self.look_ahead(1, |t| {
3219 token::OpenDelim(_) | token::Lt | token::ModSep => true,
3224 if self.look_ahead(1, |t| *t == token::DotDotDot) &&
3225 self.look_ahead(2, |t| {
3226 *t != token::Comma && *t != token::CloseDelim(token::Bracket)
3228 let start = self.parse_expr_res(RESTRICTION_NO_BAR_OP);
3229 self.eat(&token::DotDotDot);
3230 let end = self.parse_expr_res(RESTRICTION_NO_BAR_OP);
3231 pat = PatRange(start, end);
3232 } else if self.token.is_plain_ident() && !can_be_enum_or_struct {
3233 let id = self.parse_ident();
3234 let id_span = self.last_span;
3235 let pth1 = codemap::Spanned{span:id_span, node: id};
3236 if self.eat(&token::Not) {
3238 let delim = self.expect_open_delim();
3239 let tts = self.parse_seq_to_end(&token::CloseDelim(delim),
3241 |p| p.parse_token_tree());
3243 let mac = MacInvocTT(ident_to_path(id_span,id), tts, EMPTY_CTXT);
3244 pat = ast::PatMac(codemap::Spanned {node: mac, span: self.span});
3246 let sub = if self.eat(&token::At) {
3248 Some(self.parse_pat())
3253 pat = PatIdent(BindByValue(MutImmutable), pth1, sub);
3255 } else if self.look_ahead(1, |t| *t == token::Lt) {
3259 // parse an enum pat
3260 let enum_path = self.parse_path(LifetimeAndTypesWithColons);
3262 token::OpenDelim(token::Brace) => {
3265 self.parse_pat_fields();
3267 pat = PatStruct(enum_path, fields, etc);
3269 token::DotDotDot => {
3270 let hi = self.last_span.hi;
3271 let start = self.mk_expr(lo, hi, ExprPath(None, enum_path));
3272 self.eat(&token::DotDotDot);
3273 let end = if self.token.is_ident() || self.token.is_path() {
3274 let path = self.parse_path(LifetimeAndTypesWithColons);
3275 let hi = self.span.hi;
3276 self.mk_expr(lo, hi, ExprPath(None, path))
3278 self.parse_literal_maybe_minus()
3280 pat = PatRange(start, end);
3283 let mut args: Vec<P<Pat>> = Vec::new();
3285 token::OpenDelim(token::Paren) => {
3286 let is_dotdot = self.look_ahead(1, |t| {
3288 token::DotDot => true,
3293 // This is a "top constructor only" pat
3296 self.expect(&token::CloseDelim(token::Paren));
3297 pat = PatEnum(enum_path, None);
3299 args = self.parse_enum_variant_seq(
3300 &token::OpenDelim(token::Paren),
3301 &token::CloseDelim(token::Paren),
3302 seq_sep_trailing_allowed(token::Comma),
3305 pat = PatEnum(enum_path, Some(args));
3309 if !enum_path.global &&
3310 enum_path.segments.len() == 1 &&
3311 enum_path.segments[0].parameters.is_empty()
3313 // NB: If enum_path is a single identifier,
3314 // this should not be reachable due to special
3315 // handling further above.
3317 // However, previously a PatIdent got emitted
3318 // here, so we preserve the branch just in case.
3320 // A rewrite of the logic in this function
3321 // would probably make this obvious.
3322 self.span_bug(enum_path.span,
3323 "ident only path should have been covered already");
3325 pat = PatEnum(enum_path, Some(args));
3333 hi = self.last_span.hi;
3335 id: ast::DUMMY_NODE_ID,
3337 span: mk_sp(lo, hi),
3341 /// Parse ident or ident @ pat
3342 /// used by the copy foo and ref foo patterns to give a good
3343 /// error message when parsing mistakes like ref foo(a,b)
3344 fn parse_pat_ident(&mut self,
3345 binding_mode: ast::BindingMode)
3347 if !self.token.is_plain_ident() {
3348 let span = self.span;
3349 let tok_str = self.this_token_to_string();
3350 self.span_fatal(span,
3351 &format!("expected identifier, found `{}`", tok_str));
3353 let ident = self.parse_ident();
3354 let last_span = self.last_span;
3355 let name = codemap::Spanned{span: last_span, node: ident};
3356 let sub = if self.eat(&token::At) {
3357 Some(self.parse_pat())
3362 // just to be friendly, if they write something like
3364 // we end up here with ( as the current token. This shortly
3365 // leads to a parse error. Note that if there is no explicit
3366 // binding mode then we do not end up here, because the lookahead
3367 // will direct us over to parse_enum_variant()
3368 if self.token == token::OpenDelim(token::Paren) {
3369 let last_span = self.last_span;
3372 "expected identifier, found enum pattern");
3375 PatIdent(binding_mode, name, sub)
3378 /// Parse a local variable declaration
3379 fn parse_local(&mut self) -> P<Local> {
3380 let lo = self.span.lo;
3381 let pat = self.parse_pat();
3384 if self.eat(&token::Colon) {
3385 ty = Some(self.parse_ty_sum());
3387 let init = self.parse_initializer();
3392 id: ast::DUMMY_NODE_ID,
3393 span: mk_sp(lo, self.last_span.hi),
3398 /// Parse a "let" stmt
3399 fn parse_let(&mut self) -> P<Decl> {
3400 let lo = self.span.lo;
3401 let local = self.parse_local();
3402 P(spanned(lo, self.last_span.hi, DeclLocal(local)))
3405 /// Parse a structure field
3406 fn parse_name_and_ty(&mut self, pr: Visibility,
3407 attrs: Vec<Attribute> ) -> StructField {
3408 let lo = self.span.lo;
3409 if !self.token.is_plain_ident() {
3410 self.fatal("expected ident");
3412 let name = self.parse_ident();
3413 self.expect(&token::Colon);
3414 let ty = self.parse_ty_sum();
3415 spanned(lo, self.last_span.hi, ast::StructField_ {
3416 kind: NamedField(name, pr),
3417 id: ast::DUMMY_NODE_ID,
3423 /// Emit an expected item after attributes error.
3424 fn expected_item_err(&self, attrs: &[Attribute]) {
3425 let message = match attrs.last() {
3426 Some(&Attribute { node: ast::Attribute_ { is_sugared_doc: true, .. }, .. }) => {
3427 "expected item after doc comment"
3429 _ => "expected item after attributes",
3432 self.span_err(self.last_span, message);
3435 /// Parse a statement. may include decl.
3436 pub fn parse_stmt(&mut self) -> Option<P<Stmt>> {
3437 self.parse_stmt_().map(P)
3440 fn parse_stmt_(&mut self) -> Option<Stmt> {
3441 maybe_whole!(Some deref self, NtStmt);
3443 fn check_expected_item(p: &mut Parser, attrs: &[Attribute]) {
3444 // If we have attributes then we should have an item
3445 if !attrs.is_empty() {
3446 p.expected_item_err(attrs);
3450 let lo = self.span.lo;
3451 let attrs = self.parse_outer_attributes();
3453 Some(if self.check_keyword(keywords::Let) {
3454 check_expected_item(self, &attrs);
3455 self.expect_keyword(keywords::Let);
3456 let decl = self.parse_let();
3457 spanned(lo, decl.span.hi, StmtDecl(decl, ast::DUMMY_NODE_ID))
3458 } else if self.token.is_ident()
3459 && !self.token.is_any_keyword()
3460 && self.look_ahead(1, |t| *t == token::Not) {
3461 // it's a macro invocation:
3463 check_expected_item(self, &attrs);
3465 // Potential trouble: if we allow macros with paths instead of
3466 // idents, we'd need to look ahead past the whole path here...
3467 let pth = self.parse_path(NoTypesAllowed);
3470 let id = match self.token {
3471 token::OpenDelim(_) => token::special_idents::invalid, // no special identifier
3472 _ => self.parse_ident(),
3475 // check that we're pointing at delimiters (need to check
3476 // again after the `if`, because of `parse_ident`
3477 // consuming more tokens).
3478 let delim = match self.token {
3479 token::OpenDelim(delim) => delim,
3481 // we only expect an ident if we didn't parse one
3483 let ident_str = if id.name == token::special_idents::invalid.name {
3488 let tok_str = self.this_token_to_string();
3489 self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
3495 let tts = self.parse_unspanned_seq(
3496 &token::OpenDelim(delim),
3497 &token::CloseDelim(delim),
3499 |p| p.parse_token_tree()
3501 let hi = self.span.hi;
3503 let style = if delim == token::Brace {
3506 MacStmtWithoutBraces
3509 if id.name == token::special_idents::invalid.name {
3511 StmtMac(P(spanned(lo,
3513 MacInvocTT(pth, tts, EMPTY_CTXT))),
3516 // if it has a special ident, it's definitely an item
3518 // Require a semicolon or braces.
3519 if style != MacStmtWithBraces {
3520 if !self.eat(&token::Semi) {
3521 let last_span = self.last_span;
3522 self.span_err(last_span,
3523 "macros that expand to items must \
3524 either be surrounded with braces or \
3525 followed by a semicolon");
3528 spanned(lo, hi, StmtDecl(
3529 P(spanned(lo, hi, DeclItem(
3531 lo, hi, id /*id is good here*/,
3532 ItemMac(spanned(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT))),
3533 Inherited, Vec::new(/*no attrs*/))))),
3534 ast::DUMMY_NODE_ID))
3537 match self.parse_item_(attrs, false) {
3540 let decl = P(spanned(lo, hi, DeclItem(i)));
3541 spanned(lo, hi, StmtDecl(decl, ast::DUMMY_NODE_ID))
3544 // Do not attempt to parse an expression if we're done here.
3545 if self.token == token::Semi {
3550 if self.token == token::CloseDelim(token::Brace) {
3554 // Remainder are line-expr stmts.
3555 let e = self.parse_expr_res(RESTRICTION_STMT_EXPR);
3556 spanned(lo, e.span.hi, StmtExpr(e, ast::DUMMY_NODE_ID))
3562 /// Is this expression a successfully-parsed statement?
3563 fn expr_is_complete(&mut self, e: &Expr) -> bool {
3564 self.restrictions.contains(RESTRICTION_STMT_EXPR) &&
3565 !classify::expr_requires_semi_to_be_stmt(e)
3568 /// Parse a block. No inner attrs are allowed.
3569 pub fn parse_block(&mut self) -> P<Block> {
3570 maybe_whole!(no_clone self, NtBlock);
3572 let lo = self.span.lo;
3574 if !self.eat(&token::OpenDelim(token::Brace)) {
3576 let tok = self.this_token_to_string();
3577 self.span_fatal_help(sp,
3578 &format!("expected `{{`, found `{}`", tok),
3579 "place this code inside a block");
3582 self.parse_block_tail(lo, DefaultBlock)
3585 /// Parse a block. Inner attrs are allowed.
3586 fn parse_inner_attrs_and_block(&mut self) -> (Vec<Attribute>, P<Block>) {
3587 maybe_whole!(pair_empty self, NtBlock);
3589 let lo = self.span.lo;
3590 self.expect(&token::OpenDelim(token::Brace));
3591 (self.parse_inner_attributes(),
3592 self.parse_block_tail(lo, DefaultBlock))
3595 /// Parse the rest of a block expression or function body
3596 /// Precondition: already parsed the '{'.
3597 fn parse_block_tail(&mut self, lo: BytePos, s: BlockCheckMode) -> P<Block> {
3598 let mut stmts = vec![];
3599 let mut expr = None;
3601 while !self.eat(&token::CloseDelim(token::Brace)) {
3602 let Spanned {node, span} = if let Some(s) = self.parse_stmt_() {
3605 // Found only `;` or `}`.
3610 self.handle_expression_like_statement(e, span, &mut stmts, &mut expr);
3612 StmtMac(mac, MacStmtWithoutBraces) => {
3613 // statement macro without braces; might be an
3614 // expr depending on whether a semicolon follows
3617 stmts.push(P(Spanned {
3618 node: StmtMac(mac, MacStmtWithSemicolon),
3624 let e = self.mk_mac_expr(span.lo, span.hi,
3625 mac.and_then(|m| m.node));
3626 let e = self.parse_dot_or_call_expr_with(e);
3627 let e = self.parse_more_binops(e, 0);
3628 let e = self.parse_assign_expr_with(e);
3629 self.handle_expression_like_statement(
3637 StmtMac(m, style) => {
3638 // statement macro; might be an expr
3641 stmts.push(P(Spanned {
3642 node: StmtMac(m, MacStmtWithSemicolon),
3647 token::CloseDelim(token::Brace) => {
3648 // if a block ends in `m!(arg)` without
3649 // a `;`, it must be an expr
3650 expr = Some(self.mk_mac_expr(span.lo, span.hi,
3651 m.and_then(|x| x.node)));
3654 stmts.push(P(Spanned {
3655 node: StmtMac(m, style),
3661 _ => { // all other kinds of statements:
3662 if classify::stmt_ends_with_semi(&node) {
3663 self.commit_stmt_expecting(token::Semi);
3666 stmts.push(P(Spanned {
3677 id: ast::DUMMY_NODE_ID,
3679 span: mk_sp(lo, self.last_span.hi),
3683 fn handle_expression_like_statement(
3687 stmts: &mut Vec<P<Stmt>>,
3688 last_block_expr: &mut Option<P<Expr>>) {
3689 // expression without semicolon
3690 if classify::expr_requires_semi_to_be_stmt(&*e) {
3691 // Just check for errors and recover; do not eat semicolon yet.
3692 self.commit_stmt(&[],
3693 &[token::Semi, token::CloseDelim(token::Brace)]);
3699 let span_with_semi = Span {
3701 hi: self.last_span.hi,
3702 expn_id: span.expn_id,
3704 stmts.push(P(Spanned {
3705 node: StmtSemi(e, ast::DUMMY_NODE_ID),
3706 span: span_with_semi,
3709 token::CloseDelim(token::Brace) => *last_block_expr = Some(e),
3711 stmts.push(P(Spanned {
3712 node: StmtExpr(e, ast::DUMMY_NODE_ID),
3719 // Parses a sequence of bounds if a `:` is found,
3720 // otherwise returns empty list.
3721 fn parse_colon_then_ty_param_bounds(&mut self,
3722 mode: BoundParsingMode)
3723 -> OwnedSlice<TyParamBound>
3725 if !self.eat(&token::Colon) {
3728 self.parse_ty_param_bounds(mode)
3732 // matches bounds = ( boundseq )?
3733 // where boundseq = ( polybound + boundseq ) | polybound
3734 // and polybound = ( 'for' '<' 'region '>' )? bound
3735 // and bound = 'region | trait_ref
3736 fn parse_ty_param_bounds(&mut self,
3737 mode: BoundParsingMode)
3738 -> OwnedSlice<TyParamBound>
3740 let mut result = vec!();
3742 let question_span = self.span;
3743 let ate_question = self.eat(&token::Question);
3745 token::Lifetime(lifetime) => {
3747 self.span_err(question_span,
3748 "`?` may only modify trait bounds, not lifetime bounds");
3750 result.push(RegionTyParamBound(ast::Lifetime {
3751 id: ast::DUMMY_NODE_ID,
3757 token::ModSep | token::Ident(..) => {
3758 let poly_trait_ref = self.parse_poly_trait_ref();
3759 let modifier = if ate_question {
3760 if mode == BoundParsingMode::Modified {
3761 TraitBoundModifier::Maybe
3763 self.span_err(question_span,
3765 TraitBoundModifier::None
3768 TraitBoundModifier::None
3770 result.push(TraitTyParamBound(poly_trait_ref, modifier))
3775 if !self.eat(&token::BinOp(token::Plus)) {
3780 return OwnedSlice::from_vec(result);
3783 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
3784 fn parse_ty_param(&mut self) -> TyParam {
3785 let span = self.span;
3786 let ident = self.parse_ident();
3788 let bounds = self.parse_colon_then_ty_param_bounds(BoundParsingMode::Modified);
3790 let default = if self.check(&token::Eq) {
3792 Some(self.parse_ty_sum())
3799 id: ast::DUMMY_NODE_ID,
3806 /// Parse a set of optional generic type parameter declarations. Where
3807 /// clauses are not parsed here, and must be added later via
3808 /// `parse_where_clause()`.
3810 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
3811 /// | ( < lifetimes , typaramseq ( , )? > )
3812 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
3813 pub fn parse_generics(&mut self) -> ast::Generics {
3814 if self.eat(&token::Lt) {
3815 let lifetime_defs = self.parse_lifetime_defs();
3816 let mut seen_default = false;
3817 let ty_params = self.parse_seq_to_gt(Some(token::Comma), |p| {
3818 p.forbid_lifetime();
3819 let ty_param = p.parse_ty_param();
3820 if ty_param.default.is_some() {
3821 seen_default = true;
3822 } else if seen_default {
3823 let last_span = p.last_span;
3824 p.span_err(last_span,
3825 "type parameters with a default must be trailing");
3830 lifetimes: lifetime_defs,
3831 ty_params: ty_params,
3832 where_clause: WhereClause {
3833 id: ast::DUMMY_NODE_ID,
3834 predicates: Vec::new(),
3838 ast_util::empty_generics()
3842 fn parse_generic_values_after_lt(&mut self)
3843 -> (Vec<ast::Lifetime>, Vec<P<Ty>>, Vec<P<TypeBinding>>) {
3844 let lifetimes = self.parse_lifetimes(token::Comma);
3846 // First parse types.
3847 let (types, returned) = self.parse_seq_to_gt_or_return(
3850 p.forbid_lifetime();
3851 if p.look_ahead(1, |t| t == &token::Eq) {
3854 Some(p.parse_ty_sum())
3859 // If we found the `>`, don't continue.
3861 return (lifetimes, types.into_vec(), Vec::new());
3864 // Then parse type bindings.
3865 let bindings = self.parse_seq_to_gt(
3868 p.forbid_lifetime();
3870 let ident = p.parse_ident();
3871 let found_eq = p.eat(&token::Eq);
3874 p.span_warn(span, "whoops, no =?");
3876 let ty = p.parse_ty();
3878 let span = mk_sp(lo, hi);
3879 return P(TypeBinding{id: ast::DUMMY_NODE_ID,
3886 (lifetimes, types.into_vec(), bindings.into_vec())
3889 fn forbid_lifetime(&mut self) {
3890 if self.token.is_lifetime() {
3891 let span = self.span;
3892 self.span_fatal(span, "lifetime parameters must be declared \
3893 prior to type parameters");
3897 /// Parses an optional `where` clause and places it in `generics`.
3900 /// where T : Trait<U, V> + 'b, 'a : 'b
3902 fn parse_where_clause(&mut self) -> ast::WhereClause {
3903 let mut where_clause = WhereClause {
3904 id: ast::DUMMY_NODE_ID,
3905 predicates: Vec::new(),
3908 if !self.eat_keyword(keywords::Where) {
3909 return where_clause;
3912 let mut parsed_something = false;
3914 let lo = self.span.lo;
3916 token::OpenDelim(token::Brace) => {
3920 token::Lifetime(..) => {
3921 let bounded_lifetime =
3922 self.parse_lifetime();
3924 self.eat(&token::Colon);
3927 self.parse_lifetimes(token::BinOp(token::Plus));
3929 let hi = self.span.hi;
3930 let span = mk_sp(lo, hi);
3932 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
3933 ast::WhereRegionPredicate {
3935 lifetime: bounded_lifetime,
3940 parsed_something = true;
3944 let bound_lifetimes = if self.eat_keyword(keywords::For) {
3945 // Higher ranked constraint.
3946 self.expect(&token::Lt);
3947 let lifetime_defs = self.parse_lifetime_defs();
3954 let bounded_ty = self.parse_ty();
3956 if self.eat(&token::Colon) {
3957 let bounds = self.parse_ty_param_bounds(BoundParsingMode::Bare);
3958 let hi = self.span.hi;
3959 let span = mk_sp(lo, hi);
3961 if bounds.len() == 0 {
3963 "each predicate in a `where` clause must have \
3964 at least one bound in it");
3967 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
3968 ast::WhereBoundPredicate {
3970 bound_lifetimes: bound_lifetimes,
3971 bounded_ty: bounded_ty,
3975 parsed_something = true;
3976 } else if self.eat(&token::Eq) {
3977 // let ty = self.parse_ty();
3978 let hi = self.span.hi;
3979 let span = mk_sp(lo, hi);
3980 // where_clause.predicates.push(
3981 // ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
3982 // id: ast::DUMMY_NODE_ID,
3984 // path: panic!("NYI"), //bounded_ty,
3987 // parsed_something = true;
3990 "equality constraints are not yet supported \
3991 in where clauses (#20041)");
3993 let last_span = self.last_span;
3994 self.span_err(last_span,
3995 "unexpected token in `where` clause");
4000 if !self.eat(&token::Comma) {
4005 if !parsed_something {
4006 let last_span = self.last_span;
4007 self.span_err(last_span,
4008 "a `where` clause must have at least one predicate \
4015 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
4016 -> (Vec<Arg> , bool) {
4018 let mut args: Vec<Option<Arg>> =
4019 self.parse_unspanned_seq(
4020 &token::OpenDelim(token::Paren),
4021 &token::CloseDelim(token::Paren),
4022 seq_sep_trailing_allowed(token::Comma),
4024 if p.token == token::DotDotDot {
4027 if p.token != token::CloseDelim(token::Paren) {
4030 "`...` must be last in argument list for variadic function");
4035 "only foreign functions are allowed to be variadic");
4039 Some(p.parse_arg_general(named_args))
4044 let variadic = match args.pop() {
4047 // Need to put back that last arg
4054 if variadic && args.is_empty() {
4056 "variadic function must be declared with at least one named argument");
4059 let args = args.into_iter().map(|x| x.unwrap()).collect();
4064 /// Parse the argument list and result type of a function declaration
4065 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> P<FnDecl> {
4067 let (args, variadic) = self.parse_fn_args(true, allow_variadic);
4068 let ret_ty = self.parse_ret_ty();
4077 fn is_self_ident(&mut self) -> bool {
4079 token::Ident(id, token::Plain) => id.name == special_idents::self_.name,
4084 fn expect_self_ident(&mut self) -> ast::Ident {
4086 token::Ident(id, token::Plain) if id.name == special_idents::self_.name => {
4091 let token_str = self.this_token_to_string();
4092 self.fatal(&format!("expected `self`, found `{}`",
4098 fn is_self_type_ident(&mut self) -> bool {
4100 token::Ident(id, token::Plain) => id.name == special_idents::type_self.name,
4105 fn expect_self_type_ident(&mut self) -> ast::Ident {
4107 token::Ident(id, token::Plain) if id.name == special_idents::type_self.name => {
4112 let token_str = self.this_token_to_string();
4113 self.fatal(&format!("expected `Self`, found `{}`",
4119 /// Parse the argument list and result type of a function
4120 /// that may have a self type.
4121 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> (ExplicitSelf, P<FnDecl>) where
4122 F: FnMut(&mut Parser) -> Arg,
4124 fn maybe_parse_borrowed_explicit_self(this: &mut Parser)
4125 -> ast::ExplicitSelf_ {
4126 // The following things are possible to see here:
4131 // fn(&'lt mut self)
4133 // We already know that the current token is `&`.
4135 if this.look_ahead(1, |t| t.is_keyword(keywords::SelfValue)) {
4137 SelfRegion(None, MutImmutable, this.expect_self_ident())
4138 } else if this.look_ahead(1, |t| t.is_mutability()) &&
4139 this.look_ahead(2, |t| t.is_keyword(keywords::SelfValue)) {
4141 let mutability = this.parse_mutability();
4142 SelfRegion(None, mutability, this.expect_self_ident())
4143 } else if this.look_ahead(1, |t| t.is_lifetime()) &&
4144 this.look_ahead(2, |t| t.is_keyword(keywords::SelfValue)) {
4146 let lifetime = this.parse_lifetime();
4147 SelfRegion(Some(lifetime), MutImmutable, this.expect_self_ident())
4148 } else if this.look_ahead(1, |t| t.is_lifetime()) &&
4149 this.look_ahead(2, |t| t.is_mutability()) &&
4150 this.look_ahead(3, |t| t.is_keyword(keywords::SelfValue)) {
4152 let lifetime = this.parse_lifetime();
4153 let mutability = this.parse_mutability();
4154 SelfRegion(Some(lifetime), mutability, this.expect_self_ident())
4160 self.expect(&token::OpenDelim(token::Paren));
4162 // A bit of complexity and lookahead is needed here in order to be
4163 // backwards compatible.
4164 let lo = self.span.lo;
4165 let mut self_ident_lo = self.span.lo;
4166 let mut self_ident_hi = self.span.hi;
4168 let mut mutbl_self = MutImmutable;
4169 let explicit_self = match self.token {
4170 token::BinOp(token::And) => {
4171 let eself = maybe_parse_borrowed_explicit_self(self);
4172 self_ident_lo = self.last_span.lo;
4173 self_ident_hi = self.last_span.hi;
4176 token::BinOp(token::Star) => {
4177 // Possibly "*self" or "*mut self" -- not supported. Try to avoid
4178 // emitting cryptic "unexpected token" errors.
4180 let _mutability = if self.token.is_mutability() {
4181 self.parse_mutability()
4185 if self.is_self_ident() {
4186 let span = self.span;
4187 self.span_err(span, "cannot pass self by unsafe pointer");
4190 // error case, making bogus self ident:
4191 SelfValue(special_idents::self_)
4193 token::Ident(..) => {
4194 if self.is_self_ident() {
4195 let self_ident = self.expect_self_ident();
4197 // Determine whether this is the fully explicit form, `self:
4199 if self.eat(&token::Colon) {
4200 SelfExplicit(self.parse_ty_sum(), self_ident)
4202 SelfValue(self_ident)
4204 } else if self.token.is_mutability() &&
4205 self.look_ahead(1, |t| t.is_keyword(keywords::SelfValue)) {
4206 mutbl_self = self.parse_mutability();
4207 let self_ident = self.expect_self_ident();
4209 // Determine whether this is the fully explicit form,
4211 if self.eat(&token::Colon) {
4212 SelfExplicit(self.parse_ty_sum(), self_ident)
4214 SelfValue(self_ident)
4223 let explicit_self_sp = mk_sp(self_ident_lo, self_ident_hi);
4225 // shared fall-through for the three cases below. borrowing prevents simply
4226 // writing this as a closure
4227 macro_rules! parse_remaining_arguments {
4230 // If we parsed a self type, expect a comma before the argument list.
4234 let sep = seq_sep_trailing_allowed(token::Comma);
4235 let mut fn_inputs = self.parse_seq_to_before_end(
4236 &token::CloseDelim(token::Paren),
4240 fn_inputs.insert(0, Arg::new_self(explicit_self_sp, mutbl_self, $self_id));
4243 token::CloseDelim(token::Paren) => {
4244 vec!(Arg::new_self(explicit_self_sp, mutbl_self, $self_id))
4247 let token_str = self.this_token_to_string();
4248 self.fatal(&format!("expected `,` or `)`, found `{}`",
4255 let fn_inputs = match explicit_self {
4257 let sep = seq_sep_trailing_allowed(token::Comma);
4258 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)
4260 SelfValue(id) => parse_remaining_arguments!(id),
4261 SelfRegion(_,_,id) => parse_remaining_arguments!(id),
4262 SelfExplicit(_,id) => parse_remaining_arguments!(id),
4266 self.expect(&token::CloseDelim(token::Paren));
4268 let hi = self.span.hi;
4270 let ret_ty = self.parse_ret_ty();
4272 let fn_decl = P(FnDecl {
4278 (spanned(lo, hi, explicit_self), fn_decl)
4281 // parse the |arg, arg| header on a lambda
4282 fn parse_fn_block_decl(&mut self) -> P<FnDecl> {
4283 let inputs_captures = {
4284 if self.eat(&token::OrOr) {
4287 self.expect(&token::BinOp(token::Or));
4288 self.parse_obsolete_closure_kind();
4289 let args = self.parse_seq_to_before_end(
4290 &token::BinOp(token::Or),
4291 seq_sep_trailing_allowed(token::Comma),
4292 |p| p.parse_fn_block_arg()
4298 let output = self.parse_ret_ty();
4301 inputs: inputs_captures,
4307 /// Parse the name and optional generic types of a function header.
4308 fn parse_fn_header(&mut self) -> (Ident, ast::Generics) {
4309 let id = self.parse_ident();
4310 let generics = self.parse_generics();
4314 fn mk_item(&mut self, lo: BytePos, hi: BytePos, ident: Ident,
4315 node: Item_, vis: Visibility,
4316 attrs: Vec<Attribute>) -> P<Item> {
4320 id: ast::DUMMY_NODE_ID,
4327 /// Parse an item-position function declaration.
4328 fn parse_item_fn(&mut self, unsafety: Unsafety, abi: abi::Abi) -> ItemInfo {
4329 let (ident, mut generics) = self.parse_fn_header();
4330 let decl = self.parse_fn_decl(false);
4331 generics.where_clause = self.parse_where_clause();
4332 let (inner_attrs, body) = self.parse_inner_attrs_and_block();
4333 (ident, ItemFn(decl, unsafety, abi, generics, body), Some(inner_attrs))
4336 /// Parse an impl item.
4337 pub fn parse_impl_item(&mut self) -> P<ImplItem> {
4338 let lo = self.span.lo;
4339 let mut attrs = self.parse_outer_attributes();
4340 let vis = self.parse_visibility();
4341 let (name, node) = if self.eat_keyword(keywords::Type) {
4342 let name = self.parse_ident();
4343 self.expect(&token::Eq);
4344 let typ = self.parse_ty_sum();
4345 self.expect(&token::Semi);
4346 (name, TypeImplItem(typ))
4348 let (name, inner_attrs, node) = self.parse_impl_method(vis);
4349 attrs.extend(inner_attrs.into_iter());
4354 id: ast::DUMMY_NODE_ID,
4355 span: mk_sp(lo, self.last_span.hi),
4363 fn complain_if_pub_macro(&mut self, visa: Visibility, span: Span) {
4366 self.span_err(span, "can't qualify macro invocation with `pub`");
4367 self.fileline_help(span, "try adjusting the macro to put `pub` inside \
4374 /// Parse a method or a macro invocation in a trait impl.
4375 fn parse_impl_method(&mut self, vis: Visibility)
4376 -> (Ident, Vec<ast::Attribute>, ast::ImplItem_) {
4377 // code copied from parse_macro_use_or_failure... abstraction!
4378 if !self.token.is_any_keyword()
4379 && self.look_ahead(1, |t| *t == token::Not)
4380 && (self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren))
4381 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) {
4384 let last_span = self.last_span;
4385 self.complain_if_pub_macro(vis, last_span);
4387 let pth = self.parse_path(NoTypesAllowed);
4388 self.expect(&token::Not);
4390 // eat a matched-delimiter token tree:
4391 let delim = self.expect_open_delim();
4392 let tts = self.parse_seq_to_end(&token::CloseDelim(delim),
4394 |p| p.parse_token_tree());
4395 let m_ = ast::MacInvocTT(pth, tts, EMPTY_CTXT);
4396 let m: ast::Mac = codemap::Spanned { node: m_,
4397 span: mk_sp(self.span.lo,
4399 if delim != token::Brace {
4400 self.expect(&token::Semi)
4402 (token::special_idents::invalid, vec![], ast::MacImplItem(m))
4404 let unsafety = self.parse_unsafety();
4405 let abi = if self.eat_keyword(keywords::Extern) {
4406 self.parse_opt_abi().unwrap_or(abi::C)
4410 self.expect_keyword(keywords::Fn);
4411 let ident = self.parse_ident();
4412 let mut generics = self.parse_generics();
4413 let (explicit_self, decl) = self.parse_fn_decl_with_self(|p| {
4416 generics.where_clause = self.parse_where_clause();
4417 let (inner_attrs, body) = self.parse_inner_attrs_and_block();
4418 (ident, inner_attrs, MethodImplItem(ast::MethodSig {
4421 explicit_self: explicit_self,
4428 /// Parse trait Foo { ... }
4429 fn parse_item_trait(&mut self, unsafety: Unsafety) -> ItemInfo {
4431 let ident = self.parse_ident();
4432 let mut tps = self.parse_generics();
4434 // Parse supertrait bounds.
4435 let bounds = self.parse_colon_then_ty_param_bounds(BoundParsingMode::Bare);
4437 tps.where_clause = self.parse_where_clause();
4439 let meths = self.parse_trait_items();
4440 (ident, ItemTrait(unsafety, tps, bounds, meths), None)
4443 /// Parses items implementations variants
4444 /// impl<T> Foo { ... }
4445 /// impl<T> ToString for &'static T { ... }
4446 /// impl Send for .. {}
4447 fn parse_item_impl(&mut self, unsafety: ast::Unsafety) -> ItemInfo {
4448 let impl_span = self.span;
4450 // First, parse type parameters if necessary.
4451 let mut generics = self.parse_generics();
4453 // Special case: if the next identifier that follows is '(', don't
4454 // allow this to be parsed as a trait.
4455 let could_be_trait = self.token != token::OpenDelim(token::Paren);
4457 let neg_span = self.span;
4458 let polarity = if self.eat(&token::Not) {
4459 ast::ImplPolarity::Negative
4461 ast::ImplPolarity::Positive
4465 let mut ty = self.parse_ty_sum();
4467 // Parse traits, if necessary.
4468 let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) {
4469 // New-style trait. Reinterpret the type as a trait.
4471 TyPath(None, ref path) => {
4473 path: (*path).clone(),
4478 self.span_err(ty.span, "not a trait");
4484 ast::ImplPolarity::Negative => {
4485 // This is a negated type implementation
4486 // `impl !MyType {}`, which is not allowed.
4487 self.span_err(neg_span, "inherent implementation can't be negated");
4494 if self.eat(&token::DotDot) {
4495 if generics.is_parameterized() {
4496 self.span_err(impl_span, "default trait implementations are not \
4497 allowed to have genercis");
4500 self.expect(&token::OpenDelim(token::Brace));
4501 self.expect(&token::CloseDelim(token::Brace));
4502 (ast_util::impl_pretty_name(&opt_trait, None),
4503 ItemDefaultImpl(unsafety, opt_trait.unwrap()), None)
4505 if opt_trait.is_some() {
4506 ty = self.parse_ty_sum();
4508 generics.where_clause = self.parse_where_clause();
4510 self.expect(&token::OpenDelim(token::Brace));
4511 let attrs = self.parse_inner_attributes();
4513 let mut impl_items = vec![];
4514 while !self.eat(&token::CloseDelim(token::Brace)) {
4515 impl_items.push(self.parse_impl_item());
4518 (ast_util::impl_pretty_name(&opt_trait, Some(&*ty)),
4519 ItemImpl(unsafety, polarity, generics, opt_trait, ty, impl_items),
4524 /// Parse a::B<String,i32>
4525 fn parse_trait_ref(&mut self) -> TraitRef {
4527 path: self.parse_path(LifetimeAndTypesWithoutColons),
4528 ref_id: ast::DUMMY_NODE_ID,
4532 fn parse_late_bound_lifetime_defs(&mut self) -> Vec<ast::LifetimeDef> {
4533 if self.eat_keyword(keywords::For) {
4534 self.expect(&token::Lt);
4535 let lifetime_defs = self.parse_lifetime_defs();
4543 /// Parse for<'l> a::B<String,i32>
4544 fn parse_poly_trait_ref(&mut self) -> PolyTraitRef {
4545 let lo = self.span.lo;
4546 let lifetime_defs = self.parse_late_bound_lifetime_defs();
4549 bound_lifetimes: lifetime_defs,
4550 trait_ref: self.parse_trait_ref(),
4551 span: mk_sp(lo, self.last_span.hi),
4555 /// Parse struct Foo { ... }
4556 fn parse_item_struct(&mut self) -> ItemInfo {
4557 let class_name = self.parse_ident();
4558 let mut generics = self.parse_generics();
4560 if self.eat(&token::Colon) {
4561 let ty = self.parse_ty_sum();
4562 self.span_err(ty.span, "`virtual` structs have been removed from the language");
4565 // There is a special case worth noting here, as reported in issue #17904.
4566 // If we are parsing a tuple struct it is the case that the where clause
4567 // should follow the field list. Like so:
4569 // struct Foo<T>(T) where T: Copy;
4571 // If we are parsing a normal record-style struct it is the case
4572 // that the where clause comes before the body, and after the generics.
4573 // So if we look ahead and see a brace or a where-clause we begin
4574 // parsing a record style struct.
4576 // Otherwise if we look ahead and see a paren we parse a tuple-style
4579 let (fields, ctor_id) = if self.token.is_keyword(keywords::Where) {
4580 generics.where_clause = self.parse_where_clause();
4581 if self.eat(&token::Semi) {
4582 // If we see a: `struct Foo<T> where T: Copy;` style decl.
4583 (Vec::new(), Some(ast::DUMMY_NODE_ID))
4585 // If we see: `struct Foo<T> where T: Copy { ... }`
4586 (self.parse_record_struct_body(&class_name), None)
4588 // No `where` so: `struct Foo<T>;`
4589 } else if self.eat(&token::Semi) {
4590 (Vec::new(), Some(ast::DUMMY_NODE_ID))
4591 // Record-style struct definition
4592 } else if self.token == token::OpenDelim(token::Brace) {
4593 let fields = self.parse_record_struct_body(&class_name);
4595 // Tuple-style struct definition with optional where-clause.
4597 let fields = self.parse_tuple_struct_body(&class_name, &mut generics);
4598 (fields, Some(ast::DUMMY_NODE_ID))
4602 ItemStruct(P(ast::StructDef {
4609 pub fn parse_record_struct_body(&mut self, class_name: &ast::Ident) -> Vec<StructField> {
4610 let mut fields = Vec::new();
4611 if self.eat(&token::OpenDelim(token::Brace)) {
4612 while self.token != token::CloseDelim(token::Brace) {
4613 fields.push(self.parse_struct_decl_field(true));
4616 if fields.len() == 0 {
4617 self.fatal(&format!("unit-like struct definition should be \
4618 written as `struct {};`",
4619 token::get_ident(class_name.clone())));
4624 let token_str = self.this_token_to_string();
4625 self.fatal(&format!("expected `where`, or `{}` after struct \
4626 name, found `{}`", "{",
4633 pub fn parse_tuple_struct_body(&mut self,
4634 class_name: &ast::Ident,
4635 generics: &mut ast::Generics)
4636 -> Vec<StructField> {
4637 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
4638 if self.check(&token::OpenDelim(token::Paren)) {
4639 let fields = self.parse_unspanned_seq(
4640 &token::OpenDelim(token::Paren),
4641 &token::CloseDelim(token::Paren),
4642 seq_sep_trailing_allowed(token::Comma),
4644 let attrs = p.parse_outer_attributes();
4646 let struct_field_ = ast::StructField_ {
4647 kind: UnnamedField(p.parse_visibility()),
4648 id: ast::DUMMY_NODE_ID,
4649 ty: p.parse_ty_sum(),
4652 spanned(lo, p.span.hi, struct_field_)
4655 if fields.len() == 0 {
4656 self.fatal(&format!("unit-like struct definition should be \
4657 written as `struct {};`",
4658 token::get_ident(class_name.clone())));
4661 generics.where_clause = self.parse_where_clause();
4662 self.expect(&token::Semi);
4664 // This is the case where we just see struct Foo<T> where T: Copy;
4665 } else if self.token.is_keyword(keywords::Where) {
4666 generics.where_clause = self.parse_where_clause();
4667 self.expect(&token::Semi);
4669 // This case is where we see: `struct Foo<T>;`
4671 let token_str = self.this_token_to_string();
4672 self.fatal(&format!("expected `where`, `{}`, `(`, or `;` after struct \
4673 name, found `{}`", "{", token_str));
4677 /// Parse a structure field declaration
4678 pub fn parse_single_struct_field(&mut self,
4680 attrs: Vec<Attribute> )
4682 let a_var = self.parse_name_and_ty(vis, attrs);
4687 token::CloseDelim(token::Brace) => {}
4689 let span = self.span;
4690 let token_str = self.this_token_to_string();
4691 self.span_fatal_help(span,
4692 &format!("expected `,`, or `}}`, found `{}`",
4694 "struct fields should be separated by commas")
4700 /// Parse an element of a struct definition
4701 fn parse_struct_decl_field(&mut self, allow_pub: bool) -> StructField {
4703 let attrs = self.parse_outer_attributes();
4705 if self.eat_keyword(keywords::Pub) {
4707 let span = self.last_span;
4708 self.span_err(span, "`pub` is not allowed here");
4710 return self.parse_single_struct_field(Public, attrs);
4713 return self.parse_single_struct_field(Inherited, attrs);
4716 /// Parse visibility: PUB, PRIV, or nothing
4717 fn parse_visibility(&mut self) -> Visibility {
4718 if self.eat_keyword(keywords::Pub) { Public }
4722 /// Given a termination token, parse all of the items in a module
4723 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: BytePos) -> Mod {
4724 let mut items = vec![];
4725 while let Some(item) = self.parse_item() {
4729 if !self.eat(term) {
4730 let token_str = self.this_token_to_string();
4731 self.fatal(&format!("expected item, found `{}`", token_str))
4735 inner: mk_sp(inner_lo, self.span.lo),
4740 fn parse_item_const(&mut self, m: Option<Mutability>) -> ItemInfo {
4741 let id = self.parse_ident();
4742 self.expect(&token::Colon);
4743 let ty = self.parse_ty_sum();
4744 self.expect(&token::Eq);
4745 let e = self.parse_expr();
4746 self.commit_expr_expecting(&*e, token::Semi);
4747 let item = match m {
4748 Some(m) => ItemStatic(ty, m, e),
4749 None => ItemConst(ty, e),
4754 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
4755 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> ItemInfo {
4756 let id_span = self.span;
4757 let id = self.parse_ident();
4758 if self.check(&token::Semi) {
4760 // This mod is in an external file. Let's go get it!
4761 let (m, attrs) = self.eval_src_mod(id, outer_attrs, id_span);
4762 (id, m, Some(attrs))
4764 self.push_mod_path(id, outer_attrs);
4765 self.expect(&token::OpenDelim(token::Brace));
4766 let mod_inner_lo = self.span.lo;
4767 let old_owns_directory = self.owns_directory;
4768 self.owns_directory = true;
4769 let attrs = self.parse_inner_attributes();
4770 let m = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo);
4771 self.owns_directory = old_owns_directory;
4772 self.pop_mod_path();
4773 (id, ItemMod(m), Some(attrs))
4777 fn push_mod_path(&mut self, id: Ident, attrs: &[Attribute]) {
4778 let default_path = self.id_to_interned_str(id);
4779 let file_path = match ::attr::first_attr_value_str_by_name(attrs,
4782 None => default_path,
4784 self.mod_path_stack.push(file_path)
4787 fn pop_mod_path(&mut self) {
4788 self.mod_path_stack.pop().unwrap();
4791 /// Read a module from a source file.
4792 fn eval_src_mod(&mut self,
4794 outer_attrs: &[ast::Attribute],
4796 -> (ast::Item_, Vec<ast::Attribute> ) {
4797 let mut prefix = PathBuf::from(&self.sess.span_diagnostic.cm
4798 .span_to_filename(self.span));
4800 let mut dir_path = prefix;
4801 for part in &self.mod_path_stack {
4802 dir_path.push(&**part);
4804 let mod_string = token::get_ident(id);
4805 let (file_path, owns_directory) = match ::attr::first_attr_value_str_by_name(
4806 outer_attrs, "path") {
4807 Some(d) => (dir_path.join(&*d), true),
4809 let mod_name = mod_string.to_string();
4810 let default_path_str = format!("{}.rs", mod_name);
4811 let secondary_path_str = format!("{}/mod.rs", mod_name);
4812 let default_path = dir_path.join(&default_path_str[..]);
4813 let secondary_path = dir_path.join(&secondary_path_str[..]);
4814 let default_exists = default_path.exists();
4815 let secondary_exists = secondary_path.exists();
4817 if !self.owns_directory {
4818 self.span_err(id_sp,
4819 "cannot declare a new module at this location");
4820 let this_module = match self.mod_path_stack.last() {
4821 Some(name) => name.to_string(),
4822 None => self.root_module_name.as_ref().unwrap().clone(),
4824 self.span_note(id_sp,
4825 &format!("maybe move this module `{0}` \
4826 to its own directory via \
4829 if default_exists || secondary_exists {
4830 self.span_note(id_sp,
4831 &format!("... or maybe `use` the module \
4832 `{}` instead of possibly \
4836 self.abort_if_errors();
4839 match (default_exists, secondary_exists) {
4840 (true, false) => (default_path, false),
4841 (false, true) => (secondary_path, true),
4843 self.span_fatal_help(id_sp,
4844 &format!("file not found for module `{}`",
4846 &format!("name the file either {} or {} inside \
4847 the directory {:?}",
4850 dir_path.display()));
4853 self.span_fatal_help(
4855 &format!("file for module `{}` found at both {} \
4859 secondary_path_str),
4860 "delete or rename one of them to remove the ambiguity");
4866 self.eval_src_mod_from_path(file_path, owns_directory,
4867 mod_string.to_string(), id_sp)
4870 fn eval_src_mod_from_path(&mut self,
4872 owns_directory: bool,
4874 id_sp: Span) -> (ast::Item_, Vec<ast::Attribute> ) {
4875 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
4876 match included_mod_stack.iter().position(|p| *p == path) {
4878 let mut err = String::from_str("circular modules: ");
4879 let len = included_mod_stack.len();
4880 for p in &included_mod_stack[i.. len] {
4881 err.push_str(&p.to_string_lossy());
4882 err.push_str(" -> ");
4884 err.push_str(&path.to_string_lossy());
4885 self.span_fatal(id_sp, &err[..]);
4889 included_mod_stack.push(path.clone());
4890 drop(included_mod_stack);
4893 new_sub_parser_from_file(self.sess,
4899 let mod_inner_lo = p0.span.lo;
4900 let mod_attrs = p0.parse_inner_attributes();
4901 let m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo);
4902 self.sess.included_mod_stack.borrow_mut().pop();
4903 (ast::ItemMod(m0), mod_attrs)
4906 /// Parse a function declaration from a foreign module
4907 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility,
4908 attrs: Vec<Attribute>) -> P<ForeignItem> {
4909 let lo = self.span.lo;
4910 self.expect_keyword(keywords::Fn);
4912 let (ident, mut generics) = self.parse_fn_header();
4913 let decl = self.parse_fn_decl(true);
4914 generics.where_clause = self.parse_where_clause();
4915 let hi = self.span.hi;
4916 self.expect(&token::Semi);
4917 P(ast::ForeignItem {
4920 node: ForeignItemFn(decl, generics),
4921 id: ast::DUMMY_NODE_ID,
4922 span: mk_sp(lo, hi),
4927 /// Parse a static item from a foreign module
4928 fn parse_item_foreign_static(&mut self, vis: ast::Visibility,
4929 attrs: Vec<Attribute>) -> P<ForeignItem> {
4930 let lo = self.span.lo;
4932 self.expect_keyword(keywords::Static);
4933 let mutbl = self.eat_keyword(keywords::Mut);
4935 let ident = self.parse_ident();
4936 self.expect(&token::Colon);
4937 let ty = self.parse_ty_sum();
4938 let hi = self.span.hi;
4939 self.expect(&token::Semi);
4943 node: ForeignItemStatic(ty, mutbl),
4944 id: ast::DUMMY_NODE_ID,
4945 span: mk_sp(lo, hi),
4950 /// Parse extern crate links
4954 /// extern crate foo;
4955 /// extern crate bar as foo;
4956 fn parse_item_extern_crate(&mut self,
4958 visibility: Visibility,
4959 attrs: Vec<Attribute>)
4962 let crate_name = self.parse_ident();
4963 let (maybe_path, ident) = if self.eat_keyword(keywords::As) {
4964 (Some(crate_name.name), self.parse_ident())
4968 self.expect(&token::Semi);
4970 let last_span = self.last_span;
4974 ItemExternCrate(maybe_path),
4979 /// Parse `extern` for foreign ABIs
4982 /// `extern` is expected to have been
4983 /// consumed before calling this method
4989 fn parse_item_foreign_mod(&mut self,
4991 opt_abi: Option<abi::Abi>,
4992 visibility: Visibility,
4993 mut attrs: Vec<Attribute>)
4995 self.expect(&token::OpenDelim(token::Brace));
4997 let abi = opt_abi.unwrap_or(abi::C);
4999 attrs.extend(self.parse_inner_attributes().into_iter());
5001 let mut foreign_items = vec![];
5002 while let Some(item) = self.parse_foreign_item() {
5003 foreign_items.push(item);
5005 self.expect(&token::CloseDelim(token::Brace));
5007 let last_span = self.last_span;
5008 let m = ast::ForeignMod {
5010 items: foreign_items
5014 special_idents::invalid,
5020 /// Parse type Foo = Bar;
5021 fn parse_item_type(&mut self) -> ItemInfo {
5022 let ident = self.parse_ident();
5023 let mut tps = self.parse_generics();
5024 tps.where_clause = self.parse_where_clause();
5025 self.expect(&token::Eq);
5026 let ty = self.parse_ty_sum();
5027 self.expect(&token::Semi);
5028 (ident, ItemTy(ty, tps), None)
5031 /// Parse a structure-like enum variant definition
5032 /// this should probably be renamed or refactored...
5033 fn parse_struct_def(&mut self) -> P<StructDef> {
5034 let mut fields: Vec<StructField> = Vec::new();
5035 while self.token != token::CloseDelim(token::Brace) {
5036 fields.push(self.parse_struct_decl_field(false));
5046 /// Parse the part of an "enum" decl following the '{'
5047 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> EnumDef {
5048 let mut variants = Vec::new();
5049 let mut all_nullary = true;
5050 let mut any_disr = None;
5051 while self.token != token::CloseDelim(token::Brace) {
5052 let variant_attrs = self.parse_outer_attributes();
5053 let vlo = self.span.lo;
5055 let vis = self.parse_visibility();
5059 let mut args = Vec::new();
5060 let mut disr_expr = None;
5061 ident = self.parse_ident();
5062 if self.eat(&token::OpenDelim(token::Brace)) {
5063 // Parse a struct variant.
5064 all_nullary = false;
5065 let start_span = self.span;
5066 let struct_def = self.parse_struct_def();
5067 if struct_def.fields.len() == 0 {
5068 self.span_err(start_span,
5069 &format!("unit-like struct variant should be written \
5070 without braces, as `{},`",
5071 token::get_ident(ident)));
5073 kind = StructVariantKind(struct_def);
5074 } else if self.check(&token::OpenDelim(token::Paren)) {
5075 all_nullary = false;
5076 let arg_tys = self.parse_enum_variant_seq(
5077 &token::OpenDelim(token::Paren),
5078 &token::CloseDelim(token::Paren),
5079 seq_sep_trailing_allowed(token::Comma),
5080 |p| p.parse_ty_sum()
5083 args.push(ast::VariantArg {
5085 id: ast::DUMMY_NODE_ID,
5088 kind = TupleVariantKind(args);
5089 } else if self.eat(&token::Eq) {
5090 disr_expr = Some(self.parse_expr());
5091 any_disr = disr_expr.as_ref().map(|expr| expr.span);
5092 kind = TupleVariantKind(args);
5094 kind = TupleVariantKind(Vec::new());
5097 let vr = ast::Variant_ {
5099 attrs: variant_attrs,
5101 id: ast::DUMMY_NODE_ID,
5102 disr_expr: disr_expr,
5105 variants.push(P(spanned(vlo, self.last_span.hi, vr)));
5107 if !self.eat(&token::Comma) { break; }
5109 self.expect(&token::CloseDelim(token::Brace));
5111 Some(disr_span) if !all_nullary =>
5112 self.span_err(disr_span,
5113 "discriminator values can only be used with a c-like enum"),
5117 ast::EnumDef { variants: variants }
5120 /// Parse an "enum" declaration
5121 fn parse_item_enum(&mut self) -> ItemInfo {
5122 let id = self.parse_ident();
5123 let mut generics = self.parse_generics();
5124 generics.where_clause = self.parse_where_clause();
5125 self.expect(&token::OpenDelim(token::Brace));
5127 let enum_definition = self.parse_enum_def(&generics);
5128 (id, ItemEnum(enum_definition, generics), None)
5131 /// Parses a string as an ABI spec on an extern type or module. Consumes
5132 /// the `extern` keyword, if one is found.
5133 fn parse_opt_abi(&mut self) -> Option<abi::Abi> {
5135 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
5137 self.expect_no_suffix(sp, "ABI spec", suf);
5139 let the_string = s.as_str();
5140 match abi::lookup(the_string) {
5141 Some(abi) => Some(abi),
5143 let last_span = self.last_span;
5146 &format!("illegal ABI: expected one of [{}], \
5148 abi::all_names().connect(", "),
5159 /// Parse one of the items allowed by the flags.
5160 /// NB: this function no longer parses the items inside an
5162 fn parse_item_(&mut self, attrs: Vec<Attribute>,
5163 macros_allowed: bool) -> Option<P<Item>> {
5164 let nt_item = match self.token {
5165 token::Interpolated(token::NtItem(ref item)) => {
5166 Some((**item).clone())
5173 let mut attrs = attrs;
5174 mem::swap(&mut item.attrs, &mut attrs);
5175 item.attrs.extend(attrs.into_iter());
5176 return Some(P(item));
5181 let lo = self.span.lo;
5183 let visibility = self.parse_visibility();
5185 if self.eat_keyword(keywords::Use) {
5187 let item_ = ItemUse(self.parse_view_path());
5188 self.expect(&token::Semi);
5190 let last_span = self.last_span;
5191 let item = self.mk_item(lo,
5193 token::special_idents::invalid,
5200 if self.eat_keyword(keywords::Extern) {
5201 if self.eat_keyword(keywords::Crate) {
5202 return Some(self.parse_item_extern_crate(lo, visibility, attrs));
5205 let opt_abi = self.parse_opt_abi();
5207 if self.eat_keyword(keywords::Fn) {
5208 // EXTERN FUNCTION ITEM
5209 let abi = opt_abi.unwrap_or(abi::C);
5210 let (ident, item_, extra_attrs) =
5211 self.parse_item_fn(Unsafety::Normal, abi);
5212 let last_span = self.last_span;
5213 let item = self.mk_item(lo,
5218 maybe_append(attrs, extra_attrs));
5220 } else if self.check(&token::OpenDelim(token::Brace)) {
5221 return Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs));
5224 let span = self.span;
5225 let token_str = self.this_token_to_string();
5226 self.span_fatal(span,
5227 &format!("expected `{}` or `fn`, found `{}`", "{",
5231 if self.eat_keyword_noexpect(keywords::Virtual) {
5232 let span = self.span;
5233 self.span_err(span, "`virtual` structs have been removed from the language");
5236 if self.eat_keyword(keywords::Static) {
5238 let m = if self.eat_keyword(keywords::Mut) {MutMutable} else {MutImmutable};
5239 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m));
5240 let last_span = self.last_span;
5241 let item = self.mk_item(lo,
5246 maybe_append(attrs, extra_attrs));
5249 if self.eat_keyword(keywords::Const) {
5251 if self.eat_keyword(keywords::Mut) {
5252 let last_span = self.last_span;
5253 self.span_err(last_span, "const globals cannot be mutable");
5254 self.fileline_help(last_span, "did you mean to declare a static?");
5256 let (ident, item_, extra_attrs) = self.parse_item_const(None);
5257 let last_span = self.last_span;
5258 let item = self.mk_item(lo,
5263 maybe_append(attrs, extra_attrs));
5266 if self.check_keyword(keywords::Unsafe) &&
5267 self.look_ahead(1, |t| t.is_keyword(keywords::Trait))
5269 // UNSAFE TRAIT ITEM
5270 self.expect_keyword(keywords::Unsafe);
5271 self.expect_keyword(keywords::Trait);
5272 let (ident, item_, extra_attrs) =
5273 self.parse_item_trait(ast::Unsafety::Unsafe);
5274 let last_span = self.last_span;
5275 let item = self.mk_item(lo,
5280 maybe_append(attrs, extra_attrs));
5283 if self.check_keyword(keywords::Unsafe) &&
5284 self.look_ahead(1, |t| t.is_keyword(keywords::Impl))
5287 self.expect_keyword(keywords::Unsafe);
5288 self.expect_keyword(keywords::Impl);
5289 let (ident, item_, extra_attrs) = self.parse_item_impl(ast::Unsafety::Unsafe);
5290 let last_span = self.last_span;
5291 let item = self.mk_item(lo,
5296 maybe_append(attrs, extra_attrs));
5299 if self.check_keyword(keywords::Fn) {
5302 let (ident, item_, extra_attrs) =
5303 self.parse_item_fn(Unsafety::Normal, abi::Rust);
5304 let last_span = self.last_span;
5305 let item = self.mk_item(lo,
5310 maybe_append(attrs, extra_attrs));
5313 if self.check_keyword(keywords::Unsafe)
5314 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
5315 // UNSAFE FUNCTION ITEM
5317 let abi = if self.eat_keyword(keywords::Extern) {
5318 self.parse_opt_abi().unwrap_or(abi::C)
5322 self.expect_keyword(keywords::Fn);
5323 let (ident, item_, extra_attrs) =
5324 self.parse_item_fn(Unsafety::Unsafe, abi);
5325 let last_span = self.last_span;
5326 let item = self.mk_item(lo,
5331 maybe_append(attrs, extra_attrs));
5334 if self.eat_keyword(keywords::Mod) {
5336 let (ident, item_, extra_attrs) =
5337 self.parse_item_mod(&attrs[..]);
5338 let last_span = self.last_span;
5339 let item = self.mk_item(lo,
5344 maybe_append(attrs, extra_attrs));
5347 if self.eat_keyword(keywords::Type) {
5349 let (ident, item_, extra_attrs) = self.parse_item_type();
5350 let last_span = self.last_span;
5351 let item = self.mk_item(lo,
5356 maybe_append(attrs, extra_attrs));
5359 if self.eat_keyword(keywords::Enum) {
5361 let (ident, item_, extra_attrs) = self.parse_item_enum();
5362 let last_span = self.last_span;
5363 let item = self.mk_item(lo,
5368 maybe_append(attrs, extra_attrs));
5371 if self.eat_keyword(keywords::Trait) {
5373 let (ident, item_, extra_attrs) =
5374 self.parse_item_trait(ast::Unsafety::Normal);
5375 let last_span = self.last_span;
5376 let item = self.mk_item(lo,
5381 maybe_append(attrs, extra_attrs));
5384 if self.eat_keyword(keywords::Impl) {
5386 let (ident, item_, extra_attrs) = self.parse_item_impl(ast::Unsafety::Normal);
5387 let last_span = self.last_span;
5388 let item = self.mk_item(lo,
5393 maybe_append(attrs, extra_attrs));
5396 if self.eat_keyword(keywords::Struct) {
5398 let (ident, item_, extra_attrs) = self.parse_item_struct();
5399 let last_span = self.last_span;
5400 let item = self.mk_item(lo,
5405 maybe_append(attrs, extra_attrs));
5408 self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility)
5411 /// Parse a foreign item.
5412 fn parse_foreign_item(&mut self) -> Option<P<ForeignItem>> {
5413 let lo = self.span.lo;
5415 let attrs = self.parse_outer_attributes();
5416 let visibility = self.parse_visibility();
5418 if self.check_keyword(keywords::Static) {
5419 // FOREIGN STATIC ITEM
5420 return Some(self.parse_item_foreign_static(visibility, attrs));
5422 if self.check_keyword(keywords::Fn) || self.check_keyword(keywords::Unsafe) {
5423 // FOREIGN FUNCTION ITEM
5424 return Some(self.parse_item_foreign_fn(visibility, attrs));
5427 // FIXME #5668: this will occur for a macro invocation:
5428 match self.parse_macro_use_or_failure(attrs, true, lo, visibility) {
5430 self.span_fatal(item.span, "macros cannot expand to foreign items");
5436 /// This is the fall-through for parsing items.
5437 fn parse_macro_use_or_failure(
5439 attrs: Vec<Attribute> ,
5440 macros_allowed: bool,
5442 visibility: Visibility
5443 ) -> Option<P<Item>> {
5444 if macros_allowed && !self.token.is_any_keyword()
5445 && self.look_ahead(1, |t| *t == token::Not)
5446 && (self.look_ahead(2, |t| t.is_plain_ident())
5447 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren))
5448 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) {
5449 // MACRO INVOCATION ITEM
5451 let last_span = self.last_span;
5452 self.complain_if_pub_macro(visibility, last_span);
5455 let pth = self.parse_path(NoTypesAllowed);
5456 self.expect(&token::Not);
5458 // a 'special' identifier (like what `macro_rules!` uses)
5459 // is optional. We should eventually unify invoc syntax
5461 let id = if self.token.is_plain_ident() {
5464 token::special_idents::invalid // no special identifier
5466 // eat a matched-delimiter token tree:
5467 let delim = self.expect_open_delim();
5468 let tts = self.parse_seq_to_end(&token::CloseDelim(delim),
5470 |p| p.parse_token_tree());
5471 // single-variant-enum... :
5472 let m = ast::MacInvocTT(pth, tts, EMPTY_CTXT);
5473 let m: ast::Mac = codemap::Spanned { node: m,
5474 span: mk_sp(self.span.lo,
5477 if delim != token::Brace {
5478 if !self.eat(&token::Semi) {
5479 let last_span = self.last_span;
5480 self.span_err(last_span,
5481 "macros that expand to items must either \
5482 be surrounded with braces or followed by \
5487 let item_ = ItemMac(m);
5488 let last_span = self.last_span;
5489 let item = self.mk_item(lo,
5498 // FAILURE TO PARSE ITEM
5502 let last_span = self.last_span;
5503 self.span_fatal(last_span, "unmatched visibility `pub`");
5507 if !attrs.is_empty() {
5508 self.expected_item_err(&attrs);
5513 pub fn parse_item(&mut self) -> Option<P<Item>> {
5514 let attrs = self.parse_outer_attributes();
5515 self.parse_item_(attrs, true)
5518 /// Matches view_path : MOD? non_global_path as IDENT
5519 /// | MOD? non_global_path MOD_SEP LBRACE RBRACE
5520 /// | MOD? non_global_path MOD_SEP LBRACE ident_seq RBRACE
5521 /// | MOD? non_global_path MOD_SEP STAR
5522 /// | MOD? non_global_path
5523 fn parse_view_path(&mut self) -> P<ViewPath> {
5524 let lo = self.span.lo;
5526 // Allow a leading :: because the paths are absolute either way.
5527 // This occurs with "use $crate::..." in macros.
5528 self.eat(&token::ModSep);
5530 if self.check(&token::OpenDelim(token::Brace)) {
5532 let idents = self.parse_unspanned_seq(
5533 &token::OpenDelim(token::Brace),
5534 &token::CloseDelim(token::Brace),
5535 seq_sep_trailing_allowed(token::Comma),
5536 |p| p.parse_path_list_item());
5537 let path = ast::Path {
5538 span: mk_sp(lo, self.span.hi),
5540 segments: Vec::new()
5542 return P(spanned(lo, self.span.hi, ViewPathList(path, idents)));
5545 let first_ident = self.parse_ident();
5546 let mut path = vec!(first_ident);
5547 if let token::ModSep = self.token {
5548 // foo::bar or foo::{a,b,c} or foo::*
5549 while self.check(&token::ModSep) {
5553 token::Ident(..) => {
5554 let ident = self.parse_ident();
5558 // foo::bar::{a,b,c}
5559 token::OpenDelim(token::Brace) => {
5560 let idents = self.parse_unspanned_seq(
5561 &token::OpenDelim(token::Brace),
5562 &token::CloseDelim(token::Brace),
5563 seq_sep_trailing_allowed(token::Comma),
5564 |p| p.parse_path_list_item()
5566 let path = ast::Path {
5567 span: mk_sp(lo, self.span.hi),
5569 segments: path.into_iter().map(|identifier| {
5571 identifier: identifier,
5572 parameters: ast::PathParameters::none(),
5576 return P(spanned(lo, self.span.hi, ViewPathList(path, idents)));
5580 token::BinOp(token::Star) => {
5582 let path = ast::Path {
5583 span: mk_sp(lo, self.span.hi),
5585 segments: path.into_iter().map(|identifier| {
5587 identifier: identifier,
5588 parameters: ast::PathParameters::none(),
5592 return P(spanned(lo, self.span.hi, ViewPathGlob(path)));
5595 // fall-through for case foo::bar::;
5597 self.span_err(self.span, "expected identifier or `{` or `*`, found `;`");
5604 let mut rename_to = path[path.len() - 1];
5605 let path = ast::Path {
5606 span: mk_sp(lo, self.last_span.hi),
5608 segments: path.into_iter().map(|identifier| {
5610 identifier: identifier,
5611 parameters: ast::PathParameters::none(),
5615 if self.eat_keyword(keywords::As) {
5616 rename_to = self.parse_ident()
5618 P(spanned(lo, self.last_span.hi, ViewPathSimple(rename_to, path)))
5621 /// Parses a source module as a crate. This is the main
5622 /// entry point for the parser.
5623 pub fn parse_crate_mod(&mut self) -> Crate {
5624 let lo = self.span.lo;
5626 attrs: self.parse_inner_attributes(),
5627 module: self.parse_mod_items(&token::Eof, lo),
5628 config: self.cfg.clone(),
5629 span: mk_sp(lo, self.span.lo),
5630 exported_macros: Vec::new(),
5634 pub fn parse_optional_str(&mut self)
5635 -> Option<(InternedString, ast::StrStyle, Option<ast::Name>)> {
5636 let ret = match self.token {
5637 token::Literal(token::Str_(s), suf) => {
5638 (self.id_to_interned_str(s.ident()), ast::CookedStr, suf)
5640 token::Literal(token::StrRaw(s, n), suf) => {
5641 (self.id_to_interned_str(s.ident()), ast::RawStr(n), suf)
5649 pub fn parse_str(&mut self) -> (InternedString, StrStyle) {
5650 match self.parse_optional_str() {
5651 Some((s, style, suf)) => {
5652 let sp = self.last_span;
5653 self.expect_no_suffix(sp, "str literal", suf);
5656 _ => self.fatal("expected string literal")