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::*;
14 use ast::{AssociatedType, BareFnTy};
15 use ast::{RegionTyParamBound, TraitTyParamBound, TraitBoundModifier};
16 use ast::{ProvidedMethod, 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, ExprQPath};
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};
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::{Method, MutTy, BiMul, Mutability};
42 use ast::{MethodImplItem, NamedField, UnNeg, NoReturn, NodeId, UnNot};
43 use ast::{Pat, PatEnum, PatIdent, PatLit, PatRange, PatRegion, PatStruct};
44 use ast::{PatTup, PatBox, PatWild, PatWildMulti, PatWildSingle};
45 use ast::{PolyTraitRef};
46 use ast::{QPath, RequiredMethod};
47 use ast::{Return, BiShl, BiShr, Stmt, StmtDecl};
48 use ast::{StmtExpr, StmtSemi, StmtMac, StructDef, StructField};
49 use ast::{StructVariantKind, BiSub, StrStyle};
50 use ast::{SelfExplicit, SelfRegion, SelfStatic, SelfValue};
51 use ast::{Delimited, SequenceRepetition, TokenTree, TraitItem, TraitRef};
52 use ast::{TtDelimited, TtSequence, TtToken};
53 use ast::{TupleVariantKind, Ty, Ty_, TypeBinding};
54 use ast::{TyFixedLengthVec, TyBareFn};
55 use ast::{TyTypeof, TyInfer, TypeMethod};
56 use ast::{TyParam, TyParamBound, TyParen, TyPath, TyPolyTraitRef, TyPtr, TyQPath};
57 use ast::{TyRptr, TyTup, TyU32, TyVec, UnUniq};
58 use ast::{TypeImplItem, TypeTraitItem, Typedef,};
59 use ast::{UnnamedField, UnsafeBlock};
60 use ast::{ViewPath, ViewPathGlob, ViewPathList, ViewPathSimple};
61 use ast::{Visibility, WhereClause};
63 use ast_util::{self, AS_PREC, ident_to_path, operator_prec};
64 use codemap::{self, Span, BytePos, Spanned, spanned, mk_sp};
66 use ext::tt::macro_parser;
68 use parse::attr::ParserAttr;
70 use parse::common::{SeqSep, seq_sep_none, seq_sep_trailing_allowed};
71 use parse::lexer::{Reader, TokenAndSpan};
72 use parse::obsolete::{ParserObsoleteMethods, ObsoleteSyntax};
73 use parse::token::{self, MatchNt, SubstNt, SpecialVarNt, InternedString};
74 use parse::token::{keywords, special_idents, SpecialMacroVar};
75 use parse::{new_sub_parser_from_file, ParseSess};
78 use owned_slice::OwnedSlice;
80 use std::collections::HashSet;
81 use std::old_io::fs::PathExtensions;
89 flags Restrictions: u8 {
90 const UNRESTRICTED = 0b0000,
91 const RESTRICTION_STMT_EXPR = 0b0001,
92 const RESTRICTION_NO_BAR_OP = 0b0010,
93 const RESTRICTION_NO_STRUCT_LITERAL = 0b0100,
98 type ItemInfo = (Ident, Item_, Option<Vec<Attribute> >);
100 /// How to parse a path. There are four different kinds of paths, all of which
101 /// are parsed somewhat differently.
102 #[derive(Copy, PartialEq)]
103 pub enum PathParsingMode {
104 /// A path with no type parameters; e.g. `foo::bar::Baz`
106 /// A path with a lifetime and type parameters, with no double colons
107 /// before the type parameters; e.g. `foo::bar<'a>::Baz<T>`
108 LifetimeAndTypesWithoutColons,
109 /// A path with a lifetime and type parameters with double colons before
110 /// the type parameters; e.g. `foo::bar::<'a>::Baz::<T>`
111 LifetimeAndTypesWithColons,
114 /// How to parse a bound, whether to allow bound modifiers such as `?`.
115 #[derive(Copy, PartialEq)]
116 pub enum BoundParsingMode {
121 /// The `Err` case indicates a failure to parse any kind of item.
122 /// The attributes are returned.
123 type MaybeItem = Result<P<Item>, Vec<Attribute>>;
126 /// Possibly accept an `token::Interpolated` expression (a pre-parsed expression
127 /// dropped into the token stream, which happens while parsing the result of
128 /// macro expansion). Placement of these is not as complex as I feared it would
129 /// be. The important thing is to make sure that lookahead doesn't balk at
130 /// `token::Interpolated` tokens.
131 macro_rules! maybe_whole_expr {
134 let found = match $p.token {
135 token::Interpolated(token::NtExpr(ref e)) => {
138 token::Interpolated(token::NtPath(_)) => {
139 // FIXME: The following avoids an issue with lexical borrowck scopes,
140 // but the clone is unfortunate.
141 let pt = match $p.token {
142 token::Interpolated(token::NtPath(ref pt)) => (**pt).clone(),
146 Some($p.mk_expr(span.lo, span.hi, ExprPath(pt)))
148 token::Interpolated(token::NtBlock(_)) => {
149 // FIXME: The following avoids an issue with lexical borrowck scopes,
150 // but the clone is unfortunate.
151 let b = match $p.token {
152 token::Interpolated(token::NtBlock(ref b)) => (*b).clone(),
156 Some($p.mk_expr(span.lo, span.hi, ExprBlock(b)))
171 /// As maybe_whole_expr, but for things other than expressions
172 macro_rules! maybe_whole {
173 ($p:expr, $constructor:ident) => (
175 let found = match ($p).token {
176 token::Interpolated(token::$constructor(_)) => {
177 Some(($p).bump_and_get())
181 if let Some(token::Interpolated(token::$constructor(x))) = found {
186 (no_clone $p:expr, $constructor:ident) => (
188 let found = match ($p).token {
189 token::Interpolated(token::$constructor(_)) => {
190 Some(($p).bump_and_get())
194 if let Some(token::Interpolated(token::$constructor(x))) = found {
199 (deref $p:expr, $constructor:ident) => (
201 let found = match ($p).token {
202 token::Interpolated(token::$constructor(_)) => {
203 Some(($p).bump_and_get())
207 if let Some(token::Interpolated(token::$constructor(x))) = found {
212 (Some $p:expr, $constructor:ident) => (
214 let found = match ($p).token {
215 token::Interpolated(token::$constructor(_)) => {
216 Some(($p).bump_and_get())
220 if let Some(token::Interpolated(token::$constructor(x))) = found {
221 return Some(x.clone());
225 (pair_empty $p:expr, $constructor:ident) => (
227 let found = match ($p).token {
228 token::Interpolated(token::$constructor(_)) => {
229 Some(($p).bump_and_get())
233 if let Some(token::Interpolated(token::$constructor(x))) = found {
234 return (Vec::new(), x);
241 fn maybe_append(mut lhs: Vec<Attribute>, rhs: Option<Vec<Attribute>>)
244 Some(ref attrs) => lhs.extend(attrs.iter().map(|a| a.clone())),
250 /* ident is handled by common.rs */
252 pub struct Parser<'a> {
253 pub sess: &'a ParseSess,
254 /// the current token:
255 pub token: token::Token,
256 /// the span of the current token:
258 /// the span of the prior token:
260 pub cfg: CrateConfig,
261 /// the previous token or None (only stashed sometimes).
262 pub last_token: Option<Box<token::Token>>,
263 pub buffer: [TokenAndSpan; 4],
264 pub buffer_start: isize,
265 pub buffer_end: isize,
266 pub tokens_consumed: usize,
267 pub restrictions: Restrictions,
268 pub quote_depth: usize, // not (yet) related to the quasiquoter
269 pub reader: Box<Reader+'a>,
270 pub interner: Rc<token::IdentInterner>,
271 /// The set of seen errors about obsolete syntax. Used to suppress
272 /// extra detail when the same error is seen twice
273 pub obsolete_set: HashSet<ObsoleteSyntax>,
274 /// Used to determine the path to externally loaded source files
275 pub mod_path_stack: Vec<InternedString>,
276 /// Stack of spans of open delimiters. Used for error message.
277 pub open_braces: Vec<Span>,
278 /// Flag if this parser "owns" the directory that it is currently parsing
279 /// in. This will affect how nested files are looked up.
280 pub owns_directory: bool,
281 /// Name of the root module this parser originated from. If `None`, then the
282 /// name is not known. This does not change while the parser is descending
283 /// into modules, and sub-parsers have new values for this name.
284 pub root_module_name: Option<String>,
285 pub expected_tokens: Vec<TokenType>,
288 #[derive(PartialEq, Eq, Clone)]
291 Keyword(keywords::Keyword),
296 fn to_string(&self) -> String {
298 TokenType::Token(ref t) => format!("`{}`", Parser::token_to_string(t)),
299 TokenType::Operator => "an operator".to_string(),
300 TokenType::Keyword(kw) => format!("`{}`", token::get_name(kw.to_name())),
305 fn is_plain_ident_or_underscore(t: &token::Token) -> bool {
306 t.is_plain_ident() || *t == token::Underscore
309 impl<'a> Parser<'a> {
310 pub fn new(sess: &'a ParseSess,
311 cfg: ast::CrateConfig,
312 mut rdr: Box<Reader+'a>)
315 let tok0 = rdr.real_token();
317 let placeholder = TokenAndSpan {
318 tok: token::Underscore,
324 interner: token::get_ident_interner(),
340 restrictions: UNRESTRICTED,
342 obsolete_set: HashSet::new(),
343 mod_path_stack: Vec::new(),
344 open_braces: Vec::new(),
345 owns_directory: true,
346 root_module_name: None,
347 expected_tokens: Vec::new(),
351 /// Convert a token to a string using self's reader
352 pub fn token_to_string(token: &token::Token) -> String {
353 pprust::token_to_string(token)
356 /// Convert the current token to a string using self's reader
357 pub fn this_token_to_string(&self) -> String {
358 Parser::token_to_string(&self.token)
361 pub fn unexpected_last(&self, t: &token::Token) -> ! {
362 let token_str = Parser::token_to_string(t);
363 let last_span = self.last_span;
364 self.span_fatal(last_span, &format!("unexpected token: `{}`",
368 pub fn unexpected(&mut self) -> ! {
369 self.expect_one_of(&[], &[]);
373 /// Expect and consume the token t. Signal an error if
374 /// the next token is not t.
375 pub fn expect(&mut self, t: &token::Token) {
376 if self.expected_tokens.is_empty() {
377 if self.token == *t {
380 let token_str = Parser::token_to_string(t);
381 let this_token_str = self.this_token_to_string();
382 self.fatal(&format!("expected `{}`, found `{}`",
387 self.expect_one_of(slice::ref_slice(t), &[]);
391 /// Expect next token to be edible or inedible token. If edible,
392 /// then consume it; if inedible, then return without consuming
393 /// anything. Signal a fatal error if next token is unexpected.
394 pub fn expect_one_of(&mut self,
395 edible: &[token::Token],
396 inedible: &[token::Token]) {
397 fn tokens_to_string(tokens: &[TokenType]) -> String {
398 let mut i = tokens.iter();
399 // This might be a sign we need a connect method on Iterator.
401 .map_or("".to_string(), |t| t.to_string());
402 i.enumerate().fold(b, |mut b, (i, ref a)| {
403 if tokens.len() > 2 && i == tokens.len() - 2 {
405 } else if tokens.len() == 2 && i == tokens.len() - 2 {
410 b.push_str(&*a.to_string());
414 if edible.contains(&self.token) {
416 } else if inedible.contains(&self.token) {
417 // leave it in the input
419 let mut expected = edible.iter().map(|x| TokenType::Token(x.clone()))
420 .collect::<Vec<_>>();
421 expected.extend(inedible.iter().map(|x| TokenType::Token(x.clone())));
422 expected.push_all(&*self.expected_tokens);
423 expected.sort_by(|a, b| a.to_string().cmp(&b.to_string()));
425 let expect = tokens_to_string(&expected[]);
426 let actual = self.this_token_to_string();
428 &(if expected.len() > 1 {
429 (format!("expected one of {}, found `{}`",
432 } else if expected.len() == 0 {
433 (format!("unexpected token: `{}`",
436 (format!("expected {}, found `{}`",
444 /// Check for erroneous `ident { }`; if matches, signal error and
445 /// recover (without consuming any expected input token). Returns
446 /// true if and only if input was consumed for recovery.
447 pub fn check_for_erroneous_unit_struct_expecting(&mut self, expected: &[token::Token]) -> bool {
448 if self.token == token::OpenDelim(token::Brace)
449 && expected.iter().all(|t| *t != token::OpenDelim(token::Brace))
450 && self.look_ahead(1, |t| *t == token::CloseDelim(token::Brace)) {
451 // matched; signal non-fatal error and recover.
452 let span = self.span;
454 "unit-like struct construction is written with no trailing `{ }`");
455 self.eat(&token::OpenDelim(token::Brace));
456 self.eat(&token::CloseDelim(token::Brace));
463 /// Commit to parsing a complete expression `e` expected to be
464 /// followed by some token from the set edible + inedible. Recover
465 /// from anticipated input errors, discarding erroneous characters.
466 pub fn commit_expr(&mut self, e: &Expr, edible: &[token::Token], inedible: &[token::Token]) {
467 debug!("commit_expr {:?}", e);
468 if let ExprPath(..) = e.node {
469 // might be unit-struct construction; check for recoverableinput error.
470 let mut expected = edible.iter().map(|x| x.clone()).collect::<Vec<_>>();
471 expected.push_all(inedible);
472 self.check_for_erroneous_unit_struct_expecting(&expected[]);
474 self.expect_one_of(edible, inedible)
477 pub fn commit_expr_expecting(&mut self, e: &Expr, edible: token::Token) {
478 self.commit_expr(e, &[edible], &[])
481 /// Commit to parsing a complete statement `s`, which expects to be
482 /// followed by some token from the set edible + inedible. Check
483 /// for recoverable input errors, discarding erroneous characters.
484 pub fn commit_stmt(&mut self, edible: &[token::Token], inedible: &[token::Token]) {
487 .map_or(false, |t| t.is_ident() || t.is_path()) {
488 let mut expected = edible.iter().map(|x| x.clone()).collect::<Vec<_>>();
489 expected.push_all(&inedible[]);
490 self.check_for_erroneous_unit_struct_expecting(
493 self.expect_one_of(edible, inedible)
496 pub fn commit_stmt_expecting(&mut self, edible: token::Token) {
497 self.commit_stmt(&[edible], &[])
500 pub fn parse_ident(&mut self) -> ast::Ident {
501 self.check_strict_keywords();
502 self.check_reserved_keywords();
504 token::Ident(i, _) => {
508 token::Interpolated(token::NtIdent(..)) => {
509 self.bug("ident interpolation not converted to real token");
512 let token_str = self.this_token_to_string();
513 self.fatal(&format!("expected ident, found `{}`",
519 pub fn parse_ident_or_self_type(&mut self) -> ast::Ident {
520 if self.is_self_type_ident() {
521 self.expect_self_type_ident()
527 pub fn parse_path_list_item(&mut self) -> ast::PathListItem {
528 let lo = self.span.lo;
529 let node = if self.eat_keyword_noexpect(keywords::Mod) {
530 let span = self.last_span;
531 self.span_warn(span, "deprecated syntax; use the `self` keyword now");
532 ast::PathListMod { id: ast::DUMMY_NODE_ID }
533 } else if self.eat_keyword(keywords::SelfValue) {
534 ast::PathListMod { id: ast::DUMMY_NODE_ID }
536 let ident = self.parse_ident();
537 ast::PathListIdent { name: ident, id: ast::DUMMY_NODE_ID }
539 let hi = self.last_span.hi;
540 spanned(lo, hi, node)
543 /// Check if the next token is `tok`, and return `true` if so.
545 /// This method is will automatically add `tok` to `expected_tokens` if `tok` is not
547 pub fn check(&mut self, tok: &token::Token) -> bool {
548 let is_present = self.token == *tok;
549 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
553 /// Consume token 'tok' if it exists. Returns true if the given
554 /// token was present, false otherwise.
555 pub fn eat(&mut self, tok: &token::Token) -> bool {
556 let is_present = self.check(tok);
557 if is_present { self.bump() }
561 pub fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
562 self.expected_tokens.push(TokenType::Keyword(kw));
563 self.token.is_keyword(kw)
566 /// If the next token is the given keyword, eat it and return
567 /// true. Otherwise, return false.
568 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
569 if self.check_keyword(kw) {
577 pub fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
578 if self.token.is_keyword(kw) {
586 /// If the given word is not a keyword, signal an error.
587 /// If the next token is not the given word, signal an error.
588 /// Otherwise, eat it.
589 pub fn expect_keyword(&mut self, kw: keywords::Keyword) {
590 if !self.eat_keyword(kw) {
591 self.expect_one_of(&[], &[]);
595 /// Signal an error if the given string is a strict keyword
596 pub fn check_strict_keywords(&mut self) {
597 if self.token.is_strict_keyword() {
598 let token_str = self.this_token_to_string();
599 let span = self.span;
601 &format!("expected identifier, found keyword `{}`",
606 /// Signal an error if the current token is a reserved keyword
607 pub fn check_reserved_keywords(&mut self) {
608 if self.token.is_reserved_keyword() {
609 let token_str = self.this_token_to_string();
610 self.fatal(&format!("`{}` is a reserved keyword",
615 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
616 /// `&` and continue. If an `&` is not seen, signal an error.
617 fn expect_and(&mut self) {
618 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
620 token::BinOp(token::And) => self.bump(),
622 let span = self.span;
623 let lo = span.lo + BytePos(1);
624 self.replace_token(token::BinOp(token::And), lo, span.hi)
627 self.expect_one_of(&[], &[]);
632 /// Expect and consume a `|`. If `||` is seen, replace it with a single
633 /// `|` and continue. If a `|` is not seen, signal an error.
634 fn expect_or(&mut self) {
635 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or)));
637 token::BinOp(token::Or) => self.bump(),
639 let span = self.span;
640 let lo = span.lo + BytePos(1);
641 self.replace_token(token::BinOp(token::Or), lo, span.hi)
644 self.expect_one_of(&[], &[]);
649 pub fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
651 None => {/* everything ok */}
653 let text = suf.as_str();
655 self.span_bug(sp, "found empty literal suffix in Some")
657 self.span_err(sp, &*format!("{} with a suffix is illegal", kind));
663 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
664 /// `<` and continue. If a `<` is not seen, return false.
666 /// This is meant to be used when parsing generics on a path to get the
668 fn eat_lt(&mut self) -> bool {
669 self.expected_tokens.push(TokenType::Token(token::Lt));
671 token::Lt => { self.bump(); true }
672 token::BinOp(token::Shl) => {
673 let span = self.span;
674 let lo = span.lo + BytePos(1);
675 self.replace_token(token::Lt, lo, span.hi);
682 fn expect_lt(&mut self) {
684 self.expect_one_of(&[], &[]);
688 /// Parse a sequence bracketed by `|` and `|`, stopping before the `|`.
689 fn parse_seq_to_before_or<T, F>(&mut self,
693 F: FnMut(&mut Parser) -> T,
695 let mut first = true;
696 let mut vector = Vec::new();
697 while self.token != token::BinOp(token::Or) &&
698 self.token != token::OrOr {
710 /// Expect and consume a GT. if a >> is seen, replace it
711 /// with a single > and continue. If a GT is not seen,
713 pub fn expect_gt(&mut self) {
714 self.expected_tokens.push(TokenType::Token(token::Gt));
716 token::Gt => self.bump(),
717 token::BinOp(token::Shr) => {
718 let span = self.span;
719 let lo = span.lo + BytePos(1);
720 self.replace_token(token::Gt, lo, span.hi)
722 token::BinOpEq(token::Shr) => {
723 let span = self.span;
724 let lo = span.lo + BytePos(1);
725 self.replace_token(token::Ge, lo, span.hi)
728 let span = self.span;
729 let lo = span.lo + BytePos(1);
730 self.replace_token(token::Eq, lo, span.hi)
733 let gt_str = Parser::token_to_string(&token::Gt);
734 let this_token_str = self.this_token_to_string();
735 self.fatal(&format!("expected `{}`, found `{}`",
742 pub fn parse_seq_to_before_gt_or_return<T, F>(&mut self,
743 sep: Option<token::Token>,
745 -> (OwnedSlice<T>, bool) where
746 F: FnMut(&mut Parser) -> Option<T>,
748 let mut v = Vec::new();
749 // This loop works by alternating back and forth between parsing types
750 // and commas. For example, given a string `A, B,>`, the parser would
751 // first parse `A`, then a comma, then `B`, then a comma. After that it
752 // would encounter a `>` and stop. This lets the parser handle trailing
753 // commas in generic parameters, because it can stop either after
754 // parsing a type or after parsing a comma.
755 for i in iter::count(0, 1) {
756 if self.check(&token::Gt)
757 || self.token == token::BinOp(token::Shr)
758 || self.token == token::Ge
759 || self.token == token::BinOpEq(token::Shr) {
765 Some(result) => v.push(result),
766 None => return (OwnedSlice::from_vec(v), true)
769 sep.as_ref().map(|t| self.expect(t));
772 return (OwnedSlice::from_vec(v), false);
775 /// Parse a sequence bracketed by '<' and '>', stopping
777 pub fn parse_seq_to_before_gt<T, F>(&mut self,
778 sep: Option<token::Token>,
780 -> OwnedSlice<T> where
781 F: FnMut(&mut Parser) -> T,
783 let (result, returned) = self.parse_seq_to_before_gt_or_return(sep, |p| Some(f(p)));
788 pub fn parse_seq_to_gt<T, F>(&mut self,
789 sep: Option<token::Token>,
791 -> OwnedSlice<T> where
792 F: FnMut(&mut Parser) -> T,
794 let v = self.parse_seq_to_before_gt(sep, f);
799 pub fn parse_seq_to_gt_or_return<T, F>(&mut self,
800 sep: Option<token::Token>,
802 -> (OwnedSlice<T>, bool) where
803 F: FnMut(&mut Parser) -> Option<T>,
805 let (v, returned) = self.parse_seq_to_before_gt_or_return(sep, f);
809 return (v, returned);
812 /// Parse a sequence, including the closing delimiter. The function
813 /// f must consume tokens until reaching the next separator or
815 pub fn parse_seq_to_end<T, F>(&mut self,
820 F: FnMut(&mut Parser) -> T,
822 let val = self.parse_seq_to_before_end(ket, sep, f);
827 /// Parse a sequence, not including the closing delimiter. The function
828 /// f must consume tokens until reaching the next separator or
830 pub fn parse_seq_to_before_end<T, F>(&mut self,
835 F: FnMut(&mut Parser) -> T,
837 let mut first: bool = true;
839 while self.token != *ket {
842 if first { first = false; }
843 else { self.expect(t); }
847 if sep.trailing_sep_allowed && self.check(ket) { break; }
853 /// Parse a sequence, including the closing delimiter. The function
854 /// f must consume tokens until reaching the next separator or
856 pub fn parse_unspanned_seq<T, F>(&mut self,
862 F: FnMut(&mut Parser) -> T,
865 let result = self.parse_seq_to_before_end(ket, sep, f);
870 /// Parse a sequence parameter of enum variant. For consistency purposes,
871 /// these should not be empty.
872 pub fn parse_enum_variant_seq<T, F>(&mut self,
878 F: FnMut(&mut Parser) -> T,
880 let result = self.parse_unspanned_seq(bra, ket, sep, f);
881 if result.is_empty() {
882 let last_span = self.last_span;
883 self.span_err(last_span,
884 "nullary enum variants are written with no trailing `( )`");
889 // NB: Do not use this function unless you actually plan to place the
890 // spanned list in the AST.
891 pub fn parse_seq<T, F>(&mut self,
896 -> Spanned<Vec<T>> where
897 F: FnMut(&mut Parser) -> T,
899 let lo = self.span.lo;
901 let result = self.parse_seq_to_before_end(ket, sep, f);
902 let hi = self.span.hi;
904 spanned(lo, hi, result)
907 /// Advance the parser by one token
908 pub fn bump(&mut self) {
909 self.last_span = self.span;
910 // Stash token for error recovery (sometimes; clone is not necessarily cheap).
911 self.last_token = if self.token.is_ident() || self.token.is_path() {
912 Some(box self.token.clone())
916 let next = if self.buffer_start == self.buffer_end {
917 self.reader.real_token()
919 // Avoid token copies with `replace`.
920 let buffer_start = self.buffer_start as usize;
921 let next_index = (buffer_start + 1) & 3 as usize;
922 self.buffer_start = next_index as isize;
924 let placeholder = TokenAndSpan {
925 tok: token::Underscore,
928 mem::replace(&mut self.buffer[buffer_start], placeholder)
931 self.token = next.tok;
932 self.tokens_consumed += 1;
933 self.expected_tokens.clear();
934 // check after each token
935 self.check_unknown_macro_variable();
938 /// Advance the parser by one token and return the bumped token.
939 pub fn bump_and_get(&mut self) -> token::Token {
940 let old_token = mem::replace(&mut self.token, token::Underscore);
945 /// EFFECT: replace the current token and span with the given one
946 pub fn replace_token(&mut self,
950 self.last_span = mk_sp(self.span.lo, lo);
952 self.span = mk_sp(lo, hi);
954 pub fn buffer_length(&mut self) -> isize {
955 if self.buffer_start <= self.buffer_end {
956 return self.buffer_end - self.buffer_start;
958 return (4 - self.buffer_start) + self.buffer_end;
960 pub fn look_ahead<R, F>(&mut self, distance: usize, f: F) -> R where
961 F: FnOnce(&token::Token) -> R,
963 let dist = distance as isize;
964 while self.buffer_length() < dist {
965 self.buffer[self.buffer_end as usize] = self.reader.real_token();
966 self.buffer_end = (self.buffer_end + 1) & 3;
968 f(&self.buffer[((self.buffer_start + dist - 1) & 3) as usize].tok)
970 pub fn fatal(&self, m: &str) -> ! {
971 self.sess.span_diagnostic.span_fatal(self.span, m)
973 pub fn span_fatal(&self, sp: Span, m: &str) -> ! {
974 self.sess.span_diagnostic.span_fatal(sp, m)
976 pub fn span_fatal_help(&self, sp: Span, m: &str, help: &str) -> ! {
977 self.span_err(sp, m);
978 self.span_help(sp, help);
979 panic!(diagnostic::FatalError);
981 pub fn span_note(&self, sp: Span, m: &str) {
982 self.sess.span_diagnostic.span_note(sp, m)
984 pub fn span_help(&self, sp: Span, m: &str) {
985 self.sess.span_diagnostic.span_help(sp, m)
987 pub fn bug(&self, m: &str) -> ! {
988 self.sess.span_diagnostic.span_bug(self.span, m)
990 pub fn warn(&self, m: &str) {
991 self.sess.span_diagnostic.span_warn(self.span, m)
993 pub fn span_warn(&self, sp: Span, m: &str) {
994 self.sess.span_diagnostic.span_warn(sp, m)
996 pub fn span_err(&self, sp: Span, m: &str) {
997 self.sess.span_diagnostic.span_err(sp, m)
999 pub fn span_bug(&self, sp: Span, m: &str) -> ! {
1000 self.sess.span_diagnostic.span_bug(sp, m)
1002 pub fn abort_if_errors(&self) {
1003 self.sess.span_diagnostic.handler().abort_if_errors();
1006 pub fn id_to_interned_str(&mut self, id: Ident) -> InternedString {
1007 token::get_ident(id)
1010 /// Is the current token one of the keywords that signals a bare function
1012 pub fn token_is_bare_fn_keyword(&mut self) -> bool {
1013 self.check_keyword(keywords::Fn) ||
1014 self.check_keyword(keywords::Unsafe) ||
1015 self.check_keyword(keywords::Extern)
1018 /// Is the current token one of the keywords that signals a closure type?
1019 pub fn token_is_closure_keyword(&mut self) -> bool {
1020 self.check_keyword(keywords::Unsafe)
1023 pub fn get_lifetime(&mut self) -> ast::Ident {
1025 token::Lifetime(ref ident) => *ident,
1026 _ => self.bug("not a lifetime"),
1030 pub fn parse_for_in_type(&mut self) -> Ty_ {
1032 Parses whatever can come after a `for` keyword in a type.
1033 The `for` has already been consumed.
1037 - for <'lt> |S| -> T
1041 - for <'lt> [unsafe] [extern "ABI"] fn (S) -> T
1042 - for <'lt> path::foo(a, b)
1047 let lo = self.span.lo;
1049 let lifetime_defs = self.parse_late_bound_lifetime_defs();
1051 // examine next token to decide to do
1052 if self.eat_keyword_noexpect(keywords::Proc) {
1053 self.parse_proc_type(lifetime_defs)
1054 } else if self.token_is_bare_fn_keyword() || self.token_is_closure_keyword() {
1055 self.parse_ty_bare_fn_or_ty_closure(lifetime_defs)
1056 } else if self.check(&token::ModSep) ||
1057 self.token.is_ident() ||
1058 self.token.is_path()
1060 let hi = self.span.hi;
1061 let trait_ref = self.parse_trait_ref();
1062 let poly_trait_ref = ast::PolyTraitRef { bound_lifetimes: lifetime_defs,
1063 trait_ref: trait_ref,
1064 span: mk_sp(lo, hi)};
1065 let other_bounds = if self.eat(&token::BinOp(token::Plus)) {
1066 self.parse_ty_param_bounds(BoundParsingMode::Bare)
1071 Some(TraitTyParamBound(poly_trait_ref, TraitBoundModifier::None)).into_iter()
1072 .chain(other_bounds.into_vec().into_iter())
1074 ast::TyPolyTraitRef(all_bounds)
1076 self.parse_ty_closure(lifetime_defs)
1080 pub fn parse_ty_path(&mut self) -> Ty_ {
1081 let path = self.parse_path(LifetimeAndTypesWithoutColons);
1082 TyPath(path, ast::DUMMY_NODE_ID)
1085 /// parse a TyBareFn type:
1086 pub fn parse_ty_bare_fn(&mut self, lifetime_defs: Vec<ast::LifetimeDef>) -> Ty_ {
1089 [unsafe] [extern "ABI"] fn <'lt> (S) -> T
1090 ^~~~^ ^~~~^ ^~~~^ ^~^ ^
1093 | | | Argument types
1099 let unsafety = self.parse_unsafety();
1100 let abi = if self.eat_keyword(keywords::Extern) {
1101 self.parse_opt_abi().unwrap_or(abi::C)
1106 self.expect_keyword(keywords::Fn);
1107 let lifetime_defs = self.parse_legacy_lifetime_defs(lifetime_defs);
1108 let (inputs, variadic) = self.parse_fn_args(false, true);
1109 let ret_ty = self.parse_ret_ty();
1110 let decl = P(FnDecl {
1115 TyBareFn(P(BareFnTy {
1118 lifetimes: lifetime_defs,
1123 /// Parses a procedure type (`proc`). The initial `proc` keyword must
1124 /// already have been parsed.
1125 pub fn parse_proc_type(&mut self, lifetime_defs: Vec<ast::LifetimeDef>) -> Ty_ {
1128 proc <'lt> (S) [:Bounds] -> T
1129 ^~~^ ^~~~^ ^ ^~~~~~~~^ ^
1135 the `proc` keyword (already consumed)
1139 let proc_span = self.last_span;
1141 // To be helpful, parse the proc as ever
1142 let _ = self.parse_legacy_lifetime_defs(lifetime_defs);
1143 let _ = self.parse_fn_args(false, false);
1144 let _ = self.parse_colon_then_ty_param_bounds(BoundParsingMode::Bare);
1145 let _ = self.parse_ret_ty();
1147 self.obsolete(proc_span, ObsoleteSyntax::ProcType);
1152 /// Parses an obsolete closure kind (`&:`, `&mut:`, or `:`).
1153 pub fn parse_obsolete_closure_kind(&mut self) {
1154 let lo = self.span.lo;
1156 self.check(&token::BinOp(token::And)) &&
1157 self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
1158 self.look_ahead(2, |t| *t == token::Colon)
1164 self.token == token::BinOp(token::And) &&
1165 self.look_ahead(1, |t| *t == token::Colon)
1171 self.eat(&token::Colon)
1178 let span = mk_sp(lo, self.span.hi);
1179 self.obsolete(span, ObsoleteSyntax::ClosureKind);
1182 pub fn parse_ty_bare_fn_or_ty_closure(&mut self, lifetime_defs: Vec<LifetimeDef>) -> Ty_ {
1183 // Both bare fns and closures can begin with stuff like unsafe
1184 // and extern. So we just scan ahead a few tokens to see if we see
1187 // Closure: [unsafe] <'lt> |S| [:Bounds] -> T
1188 // Fn: [unsafe] [extern "ABI"] fn <'lt> (S) -> T
1190 if self.check_keyword(keywords::Fn) {
1191 self.parse_ty_bare_fn(lifetime_defs)
1192 } else if self.check_keyword(keywords::Extern) {
1193 self.parse_ty_bare_fn(lifetime_defs)
1194 } else if self.check_keyword(keywords::Unsafe) {
1195 if self.look_ahead(1, |t| t.is_keyword(keywords::Fn) ||
1196 t.is_keyword(keywords::Extern)) {
1197 self.parse_ty_bare_fn(lifetime_defs)
1199 self.parse_ty_closure(lifetime_defs)
1202 self.parse_ty_closure(lifetime_defs)
1206 /// Parse a TyClosure type
1207 pub fn parse_ty_closure(&mut self, lifetime_defs: Vec<ast::LifetimeDef>) -> Ty_ {
1210 [unsafe] <'lt> |S| [:Bounds] -> T
1211 ^~~~~~~^ ^~~~^ ^ ^~~~~~~~^ ^
1214 | | | Closure bounds
1216 | Deprecated lifetime defs
1222 let ty_closure_span = self.last_span;
1224 // To be helpful, parse the closure type as ever
1225 let _ = self.parse_unsafety();
1227 let _ = self.parse_legacy_lifetime_defs(lifetime_defs);
1229 if !self.eat(&token::OrOr) {
1232 let _ = self.parse_seq_to_before_or(
1234 |p| p.parse_arg_general(false));
1238 let _ = self.parse_colon_then_ty_param_bounds(BoundParsingMode::Bare);
1240 let _ = self.parse_ret_ty();
1242 self.obsolete(ty_closure_span, ObsoleteSyntax::ClosureType);
1247 pub fn parse_unsafety(&mut self) -> Unsafety {
1248 if self.eat_keyword(keywords::Unsafe) {
1249 return Unsafety::Unsafe;
1251 return Unsafety::Normal;
1255 /// Parses `[ 'for' '<' lifetime_defs '>' ]'
1256 fn parse_legacy_lifetime_defs(&mut self,
1257 lifetime_defs: Vec<ast::LifetimeDef>)
1258 -> Vec<ast::LifetimeDef>
1260 if self.token == token::Lt {
1262 if lifetime_defs.is_empty() {
1263 self.warn("deprecated syntax; use the `for` keyword now \
1264 (e.g. change `fn<'a>` to `for<'a> fn`)");
1265 let lifetime_defs = self.parse_lifetime_defs();
1269 self.fatal("cannot use new `for` keyword and older syntax together");
1276 /// Parses `type Foo;` in a trait declaration only. The `type` keyword has
1277 /// already been parsed.
1278 fn parse_associated_type(&mut self, attrs: Vec<Attribute>)
1281 let ty_param = self.parse_ty_param();
1282 self.expect(&token::Semi);
1289 /// Parses `type Foo = TYPE;` in an implementation declaration only. The
1290 /// `type` keyword has already been parsed.
1291 fn parse_typedef(&mut self, attrs: Vec<Attribute>, vis: Visibility)
1293 let lo = self.span.lo;
1294 let ident = self.parse_ident();
1295 self.expect(&token::Eq);
1296 let typ = self.parse_ty_sum();
1297 let hi = self.span.hi;
1298 self.expect(&token::Semi);
1300 id: ast::DUMMY_NODE_ID,
1301 span: mk_sp(lo, hi),
1309 /// Parse the items in a trait declaration
1310 pub fn parse_trait_items(&mut self) -> Vec<TraitItem> {
1311 self.parse_unspanned_seq(
1312 &token::OpenDelim(token::Brace),
1313 &token::CloseDelim(token::Brace),
1316 let attrs = p.parse_outer_attributes();
1318 if p.eat_keyword(keywords::Type) {
1319 TypeTraitItem(P(p.parse_associated_type(attrs)))
1323 let vis = p.parse_visibility();
1324 let style = p.parse_unsafety();
1325 let abi = if p.eat_keyword(keywords::Extern) {
1326 p.parse_opt_abi().unwrap_or(abi::C)
1330 p.expect_keyword(keywords::Fn);
1332 let ident = p.parse_ident();
1333 let mut generics = p.parse_generics();
1335 let (explicit_self, d) = p.parse_fn_decl_with_self(|p| {
1336 // This is somewhat dubious; We don't want to allow
1337 // argument names to be left off if there is a
1339 p.parse_arg_general(false)
1342 p.parse_where_clause(&mut generics);
1344 let hi = p.last_span.hi;
1348 debug!("parse_trait_methods(): parsing required method");
1349 RequiredMethod(TypeMethod {
1356 explicit_self: explicit_self,
1357 id: ast::DUMMY_NODE_ID,
1358 span: mk_sp(lo, hi),
1362 token::OpenDelim(token::Brace) => {
1363 debug!("parse_trait_methods(): parsing provided method");
1364 let (inner_attrs, body) =
1365 p.parse_inner_attrs_and_block();
1366 let mut attrs = attrs;
1367 attrs.push_all(&inner_attrs[]);
1368 ProvidedMethod(P(ast::Method {
1370 id: ast::DUMMY_NODE_ID,
1371 span: mk_sp(lo, hi),
1372 node: ast::MethDecl(ident,
1384 let token_str = p.this_token_to_string();
1385 p.fatal(&format!("expected `;` or `{{`, found `{}`",
1393 /// Parse a possibly mutable type
1394 pub fn parse_mt(&mut self) -> MutTy {
1395 let mutbl = self.parse_mutability();
1396 let t = self.parse_ty();
1397 MutTy { ty: t, mutbl: mutbl }
1400 /// Parse optional return type [ -> TY ] in function decl
1401 pub fn parse_ret_ty(&mut self) -> FunctionRetTy {
1402 if self.eat(&token::RArrow) {
1403 if self.eat(&token::Not) {
1406 let t = self.parse_ty();
1408 // We used to allow `fn foo() -> &T + U`, but don't
1409 // anymore. If we see it, report a useful error. This
1410 // only makes sense because `parse_ret_ty` is only
1411 // used in fn *declarations*, not fn types or where
1412 // clauses (i.e., not when parsing something like
1413 // `FnMut() -> T + Send`, where the `+` is legal).
1414 if self.token == token::BinOp(token::Plus) {
1415 self.warn("deprecated syntax: `()` are required, see RFC 438 for details");
1421 let pos = self.span.lo;
1422 DefaultReturn(mk_sp(pos, pos))
1426 /// Parse a type in a context where `T1+T2` is allowed.
1427 pub fn parse_ty_sum(&mut self) -> P<Ty> {
1428 let lo = self.span.lo;
1429 let lhs = self.parse_ty();
1431 if !self.eat(&token::BinOp(token::Plus)) {
1435 let bounds = self.parse_ty_param_bounds(BoundParsingMode::Bare);
1437 // In type grammar, `+` is treated like a binary operator,
1438 // and hence both L and R side are required.
1439 if bounds.len() == 0 {
1440 let last_span = self.last_span;
1441 self.span_err(last_span,
1442 "at least one type parameter bound \
1443 must be specified");
1446 let sp = mk_sp(lo, self.last_span.hi);
1447 let sum = ast::TyObjectSum(lhs, bounds);
1448 P(Ty {id: ast::DUMMY_NODE_ID, node: sum, span: sp})
1452 pub fn parse_ty(&mut self) -> P<Ty> {
1453 maybe_whole!(no_clone self, NtTy);
1455 let lo = self.span.lo;
1457 let t = if self.check(&token::OpenDelim(token::Paren)) {
1460 // (t) is a parenthesized ty
1461 // (t,) is the type of a tuple with only one field,
1463 let mut ts = vec![];
1464 let mut last_comma = false;
1465 while self.token != token::CloseDelim(token::Paren) {
1466 ts.push(self.parse_ty_sum());
1467 if self.check(&token::Comma) {
1476 self.expect(&token::CloseDelim(token::Paren));
1477 if ts.len() == 1 && !last_comma {
1478 TyParen(ts.into_iter().nth(0).unwrap())
1482 } else if self.check(&token::BinOp(token::Star)) {
1483 // STAR POINTER (bare pointer?)
1485 TyPtr(self.parse_ptr())
1486 } else if self.check(&token::OpenDelim(token::Bracket)) {
1488 self.expect(&token::OpenDelim(token::Bracket));
1489 let t = self.parse_ty_sum();
1491 // Parse the `; e` in `[ i32; e ]`
1492 // where `e` is a const expression
1493 let t = match self.maybe_parse_fixed_length_of_vec() {
1495 Some(suffix) => TyFixedLengthVec(t, suffix)
1497 self.expect(&token::CloseDelim(token::Bracket));
1499 } else if self.check(&token::BinOp(token::And)) ||
1500 self.token == token::AndAnd {
1503 self.parse_borrowed_pointee()
1504 } else if self.check_keyword(keywords::For) {
1505 self.parse_for_in_type()
1506 } else if self.token_is_bare_fn_keyword() ||
1507 self.token_is_closure_keyword() {
1508 // BARE FUNCTION OR CLOSURE
1509 self.parse_ty_bare_fn_or_ty_closure(Vec::new())
1510 } else if self.check(&token::BinOp(token::Or)) ||
1511 self.token == token::OrOr ||
1512 (self.token == token::Lt &&
1513 self.look_ahead(1, |t| {
1514 *t == token::Gt || t.is_lifetime()
1517 self.parse_ty_closure(Vec::new())
1518 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1520 // In order to not be ambiguous, the type must be surrounded by parens.
1521 self.expect(&token::OpenDelim(token::Paren));
1522 let e = self.parse_expr();
1523 self.expect(&token::CloseDelim(token::Paren));
1525 } else if self.eat_keyword_noexpect(keywords::Proc) {
1526 self.parse_proc_type(Vec::new())
1527 } else if self.eat_lt() {
1528 // QUALIFIED PATH `<TYPE as TRAIT_REF>::item`
1529 let self_type = self.parse_ty_sum();
1530 self.expect_keyword(keywords::As);
1531 let trait_ref = self.parse_trait_ref();
1532 self.expect(&token::Gt);
1533 self.expect(&token::ModSep);
1534 let item_name = self.parse_ident();
1536 self_type: self_type,
1537 trait_ref: P(trait_ref),
1538 item_path: ast::PathSegment {
1539 identifier: item_name,
1540 parameters: ast::PathParameters::none()
1543 } else if self.check(&token::ModSep) ||
1544 self.token.is_ident() ||
1545 self.token.is_path() {
1547 self.parse_ty_path()
1548 } else if self.eat(&token::Underscore) {
1549 // TYPE TO BE INFERRED
1552 let this_token_str = self.this_token_to_string();
1553 let msg = format!("expected type, found `{}`", this_token_str);
1557 let sp = mk_sp(lo, self.last_span.hi);
1558 P(Ty {id: ast::DUMMY_NODE_ID, node: t, span: sp})
1561 pub fn parse_borrowed_pointee(&mut self) -> Ty_ {
1562 // look for `&'lt` or `&'foo ` and interpret `foo` as the region name:
1563 let opt_lifetime = self.parse_opt_lifetime();
1565 let mt = self.parse_mt();
1566 return TyRptr(opt_lifetime, mt);
1569 pub fn parse_ptr(&mut self) -> MutTy {
1570 let mutbl = if self.eat_keyword(keywords::Mut) {
1572 } else if self.eat_keyword(keywords::Const) {
1575 let span = self.last_span;
1577 "bare raw pointers are no longer allowed, you should \
1578 likely use `*mut T`, but otherwise `*T` is now \
1579 known as `*const T`");
1582 let t = self.parse_ty();
1583 MutTy { ty: t, mutbl: mutbl }
1586 pub fn is_named_argument(&mut self) -> bool {
1587 let offset = match self.token {
1588 token::BinOp(token::And) => 1,
1590 _ if self.token.is_keyword(keywords::Mut) => 1,
1594 debug!("parser is_named_argument offset:{}", offset);
1597 is_plain_ident_or_underscore(&self.token)
1598 && self.look_ahead(1, |t| *t == token::Colon)
1600 self.look_ahead(offset, |t| is_plain_ident_or_underscore(t))
1601 && self.look_ahead(offset + 1, |t| *t == token::Colon)
1605 /// This version of parse arg doesn't necessarily require
1606 /// identifier names.
1607 pub fn parse_arg_general(&mut self, require_name: bool) -> Arg {
1608 let pat = if require_name || self.is_named_argument() {
1609 debug!("parse_arg_general parse_pat (require_name:{})",
1611 let pat = self.parse_pat();
1613 self.expect(&token::Colon);
1616 debug!("parse_arg_general ident_to_pat");
1617 ast_util::ident_to_pat(ast::DUMMY_NODE_ID,
1619 special_idents::invalid)
1622 let t = self.parse_ty_sum();
1627 id: ast::DUMMY_NODE_ID,
1631 /// Parse a single function argument
1632 pub fn parse_arg(&mut self) -> Arg {
1633 self.parse_arg_general(true)
1636 /// Parse an argument in a lambda header e.g. |arg, arg|
1637 pub fn parse_fn_block_arg(&mut self) -> Arg {
1638 let pat = self.parse_pat();
1639 let t = if self.eat(&token::Colon) {
1643 id: ast::DUMMY_NODE_ID,
1645 span: mk_sp(self.span.lo, self.span.hi),
1651 id: ast::DUMMY_NODE_ID
1655 pub fn maybe_parse_fixed_length_of_vec(&mut self) -> Option<P<ast::Expr>> {
1656 if self.check(&token::Semi) {
1658 Some(self.parse_expr())
1664 /// Matches token_lit = LIT_INTEGER | ...
1665 pub fn lit_from_token(&self, tok: &token::Token) -> Lit_ {
1667 token::Interpolated(token::NtExpr(ref v)) => {
1669 ExprLit(ref lit) => { lit.node.clone() }
1670 _ => { self.unexpected_last(tok); }
1673 token::Literal(lit, suf) => {
1674 let (suffix_illegal, out) = match lit {
1675 token::Byte(i) => (true, LitByte(parse::byte_lit(i.as_str()).0)),
1676 token::Char(i) => (true, LitChar(parse::char_lit(i.as_str()).0)),
1678 // there are some valid suffixes for integer and
1679 // float literals, so all the handling is done
1681 token::Integer(s) => {
1682 (false, parse::integer_lit(s.as_str(),
1683 suf.as_ref().map(|s| s.as_str()),
1684 &self.sess.span_diagnostic,
1687 token::Float(s) => {
1688 (false, parse::float_lit(s.as_str(),
1689 suf.as_ref().map(|s| s.as_str()),
1690 &self.sess.span_diagnostic,
1696 LitStr(token::intern_and_get_ident(&parse::str_lit(s.as_str())),
1699 token::StrRaw(s, n) => {
1702 token::intern_and_get_ident(&parse::raw_str_lit(s.as_str())[]),
1706 (true, LitBinary(parse::binary_lit(i.as_str()))),
1707 token::BinaryRaw(i, _) =>
1709 LitBinary(Rc::new(i.as_str().as_bytes().iter().map(|&x| x).collect()))),
1713 let sp = self.last_span;
1714 self.expect_no_suffix(sp, &*format!("{} literal", lit.short_name()), suf)
1719 _ => { self.unexpected_last(tok); }
1723 /// Matches lit = true | false | token_lit
1724 pub fn parse_lit(&mut self) -> Lit {
1725 let lo = self.span.lo;
1726 let lit = if self.eat_keyword(keywords::True) {
1728 } else if self.eat_keyword(keywords::False) {
1731 let token = self.bump_and_get();
1732 let lit = self.lit_from_token(&token);
1735 codemap::Spanned { node: lit, span: mk_sp(lo, self.last_span.hi) }
1738 /// matches '-' lit | lit
1739 pub fn parse_literal_maybe_minus(&mut self) -> P<Expr> {
1740 let minus_lo = self.span.lo;
1741 let minus_present = self.eat(&token::BinOp(token::Minus));
1743 let lo = self.span.lo;
1744 let literal = P(self.parse_lit());
1745 let hi = self.span.hi;
1746 let expr = self.mk_expr(lo, hi, ExprLit(literal));
1749 let minus_hi = self.span.hi;
1750 let unary = self.mk_unary(UnNeg, expr);
1751 self.mk_expr(minus_lo, minus_hi, unary)
1757 /// Parses a path and optional type parameter bounds, depending on the
1758 /// mode. The `mode` parameter determines whether lifetimes, types, and/or
1759 /// bounds are permitted and whether `::` must precede type parameter
1761 pub fn parse_path(&mut self, mode: PathParsingMode) -> ast::Path {
1762 // Check for a whole path...
1763 let found = match self.token {
1764 token::Interpolated(token::NtPath(_)) => Some(self.bump_and_get()),
1767 if let Some(token::Interpolated(token::NtPath(box path))) = found {
1771 let lo = self.span.lo;
1772 let is_global = self.eat(&token::ModSep);
1774 // Parse any number of segments and bound sets. A segment is an
1775 // identifier followed by an optional lifetime and a set of types.
1776 // A bound set is a set of type parameter bounds.
1777 let segments = match mode {
1778 LifetimeAndTypesWithoutColons => {
1779 self.parse_path_segments_without_colons()
1781 LifetimeAndTypesWithColons => {
1782 self.parse_path_segments_with_colons()
1785 self.parse_path_segments_without_types()
1789 // Assemble the span.
1790 let span = mk_sp(lo, self.last_span.hi);
1792 // Assemble the result.
1801 /// - `a::b<T,U>::c<V,W>`
1802 /// - `a::b<T,U>::c(V) -> W`
1803 /// - `a::b<T,U>::c(V)`
1804 pub fn parse_path_segments_without_colons(&mut self) -> Vec<ast::PathSegment> {
1805 let mut segments = Vec::new();
1807 // First, parse an identifier.
1808 let identifier = self.parse_ident_or_self_type();
1810 // Parse types, optionally.
1811 let parameters = if self.eat_lt() {
1812 let (lifetimes, types, bindings) = self.parse_generic_values_after_lt();
1814 ast::AngleBracketedParameters(ast::AngleBracketedParameterData {
1815 lifetimes: lifetimes,
1816 types: OwnedSlice::from_vec(types),
1817 bindings: OwnedSlice::from_vec(bindings),
1819 } else if self.eat(&token::OpenDelim(token::Paren)) {
1820 let lo = self.last_span.lo;
1822 let inputs = self.parse_seq_to_end(
1823 &token::CloseDelim(token::Paren),
1824 seq_sep_trailing_allowed(token::Comma),
1825 |p| p.parse_ty_sum());
1827 let output_ty = if self.eat(&token::RArrow) {
1828 Some(self.parse_ty())
1833 let hi = self.last_span.hi;
1835 ast::ParenthesizedParameters(ast::ParenthesizedParameterData {
1836 span: mk_sp(lo, hi),
1841 ast::PathParameters::none()
1844 // Assemble and push the result.
1845 segments.push(ast::PathSegment { identifier: identifier,
1846 parameters: parameters });
1848 // Continue only if we see a `::`
1849 if !self.eat(&token::ModSep) {
1856 /// - `a::b::<T,U>::c`
1857 pub fn parse_path_segments_with_colons(&mut self) -> Vec<ast::PathSegment> {
1858 let mut segments = Vec::new();
1860 // First, parse an identifier.
1861 let identifier = self.parse_ident_or_self_type();
1863 // If we do not see a `::`, stop.
1864 if !self.eat(&token::ModSep) {
1865 segments.push(ast::PathSegment {
1866 identifier: identifier,
1867 parameters: ast::PathParameters::none()
1872 // Check for a type segment.
1874 // Consumed `a::b::<`, go look for types
1875 let (lifetimes, types, bindings) = self.parse_generic_values_after_lt();
1876 segments.push(ast::PathSegment {
1877 identifier: identifier,
1878 parameters: ast::AngleBracketedParameters(ast::AngleBracketedParameterData {
1879 lifetimes: lifetimes,
1880 types: OwnedSlice::from_vec(types),
1881 bindings: OwnedSlice::from_vec(bindings),
1885 // Consumed `a::b::<T,U>`, check for `::` before proceeding
1886 if !self.eat(&token::ModSep) {
1890 // Consumed `a::`, go look for `b`
1891 segments.push(ast::PathSegment {
1892 identifier: identifier,
1893 parameters: ast::PathParameters::none(),
1902 pub fn parse_path_segments_without_types(&mut self) -> Vec<ast::PathSegment> {
1903 let mut segments = Vec::new();
1905 // First, parse an identifier.
1906 let identifier = self.parse_ident_or_self_type();
1908 // Assemble and push the result.
1909 segments.push(ast::PathSegment {
1910 identifier: identifier,
1911 parameters: ast::PathParameters::none()
1914 // If we do not see a `::`, stop.
1915 if !self.eat(&token::ModSep) {
1921 /// parses 0 or 1 lifetime
1922 pub fn parse_opt_lifetime(&mut self) -> Option<ast::Lifetime> {
1924 token::Lifetime(..) => {
1925 Some(self.parse_lifetime())
1933 /// Parses a single lifetime
1934 /// Matches lifetime = LIFETIME
1935 pub fn parse_lifetime(&mut self) -> ast::Lifetime {
1937 token::Lifetime(i) => {
1938 let span = self.span;
1940 return ast::Lifetime {
1941 id: ast::DUMMY_NODE_ID,
1947 self.fatal(&format!("expected a lifetime name")[]);
1952 /// Parses `lifetime_defs = [ lifetime_defs { ',' lifetime_defs } ]` where `lifetime_def =
1953 /// lifetime [':' lifetimes]`
1954 pub fn parse_lifetime_defs(&mut self) -> Vec<ast::LifetimeDef> {
1956 let mut res = Vec::new();
1959 token::Lifetime(_) => {
1960 let lifetime = self.parse_lifetime();
1962 if self.eat(&token::Colon) {
1963 self.parse_lifetimes(token::BinOp(token::Plus))
1967 res.push(ast::LifetimeDef { lifetime: lifetime,
1977 token::Comma => { self.bump(); }
1978 token::Gt => { return res; }
1979 token::BinOp(token::Shr) => { return res; }
1981 let this_token_str = self.this_token_to_string();
1982 let msg = format!("expected `,` or `>` after lifetime \
1991 /// matches lifetimes = ( lifetime ) | ( lifetime , lifetimes ) actually, it matches the empty
1992 /// one too, but putting that in there messes up the grammar....
1994 /// Parses zero or more comma separated lifetimes. Expects each lifetime to be followed by
1995 /// either a comma or `>`. Used when parsing type parameter lists, where we expect something
1996 /// like `<'a, 'b, T>`.
1997 pub fn parse_lifetimes(&mut self, sep: token::Token) -> Vec<ast::Lifetime> {
1999 let mut res = Vec::new();
2002 token::Lifetime(_) => {
2003 res.push(self.parse_lifetime());
2010 if self.token != sep {
2018 /// Parse mutability declaration (mut/const/imm)
2019 pub fn parse_mutability(&mut self) -> Mutability {
2020 if self.eat_keyword(keywords::Mut) {
2027 /// Parse ident COLON expr
2028 pub fn parse_field(&mut self) -> Field {
2029 let lo = self.span.lo;
2030 let i = self.parse_ident();
2031 let hi = self.last_span.hi;
2032 self.expect(&token::Colon);
2033 let e = self.parse_expr();
2035 ident: spanned(lo, hi, i),
2036 span: mk_sp(lo, e.span.hi),
2041 pub fn mk_expr(&mut self, lo: BytePos, hi: BytePos, node: Expr_) -> P<Expr> {
2043 id: ast::DUMMY_NODE_ID,
2045 span: mk_sp(lo, hi),
2049 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::Expr_ {
2050 ExprUnary(unop, expr)
2053 pub fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::Expr_ {
2054 ExprBinary(binop, lhs, rhs)
2057 pub fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::Expr_ {
2061 fn mk_method_call(&mut self,
2062 ident: ast::SpannedIdent,
2066 ExprMethodCall(ident, tps, args)
2069 pub fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::Expr_ {
2070 ExprIndex(expr, idx)
2073 pub fn mk_range(&mut self,
2074 start: Option<P<Expr>>,
2075 end: Option<P<Expr>>)
2077 ExprRange(start, end)
2080 pub fn mk_field(&mut self, expr: P<Expr>, ident: ast::SpannedIdent) -> ast::Expr_ {
2081 ExprField(expr, ident)
2084 pub fn mk_tup_field(&mut self, expr: P<Expr>, idx: codemap::Spanned<usize>) -> ast::Expr_ {
2085 ExprTupField(expr, idx)
2088 pub fn mk_assign_op(&mut self, binop: ast::BinOp,
2089 lhs: P<Expr>, rhs: P<Expr>) -> ast::Expr_ {
2090 ExprAssignOp(binop, lhs, rhs)
2093 pub fn mk_mac_expr(&mut self, lo: BytePos, hi: BytePos, m: Mac_) -> P<Expr> {
2095 id: ast::DUMMY_NODE_ID,
2096 node: ExprMac(codemap::Spanned {node: m, span: mk_sp(lo, hi)}),
2097 span: mk_sp(lo, hi),
2101 pub fn mk_lit_u32(&mut self, i: u32) -> P<Expr> {
2102 let span = &self.span;
2103 let lv_lit = P(codemap::Spanned {
2104 node: LitInt(i as u64, ast::UnsignedIntLit(TyU32)),
2109 id: ast::DUMMY_NODE_ID,
2110 node: ExprLit(lv_lit),
2115 fn expect_open_delim(&mut self) -> token::DelimToken {
2116 self.expected_tokens.push(TokenType::Token(token::Gt));
2118 token::OpenDelim(delim) => {
2122 _ => self.fatal("expected open delimiter"),
2126 /// At the bottom (top?) of the precedence hierarchy,
2127 /// parse things like parenthesized exprs,
2128 /// macros, return, etc.
2129 pub fn parse_bottom_expr(&mut self) -> P<Expr> {
2130 maybe_whole_expr!(self);
2132 let lo = self.span.lo;
2133 let mut hi = self.span.hi;
2137 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2139 token::OpenDelim(token::Paren) => {
2142 // (e) is parenthesized e
2143 // (e,) is a tuple with only one field, e
2144 let mut es = vec![];
2145 let mut trailing_comma = false;
2146 while self.token != token::CloseDelim(token::Paren) {
2147 es.push(self.parse_expr());
2148 self.commit_expr(&**es.last().unwrap(), &[],
2149 &[token::Comma, token::CloseDelim(token::Paren)]);
2150 if self.check(&token::Comma) {
2151 trailing_comma = true;
2155 trailing_comma = false;
2162 return if es.len() == 1 && !trailing_comma {
2163 self.mk_expr(lo, hi, ExprParen(es.into_iter().nth(0).unwrap()))
2165 self.mk_expr(lo, hi, ExprTup(es))
2168 token::OpenDelim(token::Brace) => {
2170 let blk = self.parse_block_tail(lo, DefaultBlock);
2171 return self.mk_expr(blk.span.lo, blk.span.hi,
2174 token::BinOp(token::Or) | token::OrOr => {
2175 return self.parse_lambda_expr(CaptureByRef);
2177 token::Ident(id @ ast::Ident {
2178 name: token::SELF_KEYWORD_NAME,
2180 }, token::Plain) => {
2182 let path = ast_util::ident_to_path(mk_sp(lo, hi), id);
2183 ex = ExprPath(path);
2184 hi = self.last_span.hi;
2186 token::OpenDelim(token::Bracket) => {
2189 if self.check(&token::CloseDelim(token::Bracket)) {
2192 ex = ExprVec(Vec::new());
2195 let first_expr = self.parse_expr();
2196 if self.check(&token::Semi) {
2197 // Repeating vector syntax: [ 0; 512 ]
2199 let count = self.parse_expr();
2200 self.expect(&token::CloseDelim(token::Bracket));
2201 ex = ExprRepeat(first_expr, count);
2202 } else if self.check(&token::Comma) {
2203 // Vector with two or more elements.
2205 let remaining_exprs = self.parse_seq_to_end(
2206 &token::CloseDelim(token::Bracket),
2207 seq_sep_trailing_allowed(token::Comma),
2210 let mut exprs = vec!(first_expr);
2211 exprs.extend(remaining_exprs.into_iter());
2212 ex = ExprVec(exprs);
2214 // Vector with one element.
2215 self.expect(&token::CloseDelim(token::Bracket));
2216 ex = ExprVec(vec!(first_expr));
2219 hi = self.last_span.hi;
2223 // QUALIFIED PATH `<TYPE as TRAIT_REF>::item::<'a, T>`
2224 let self_type = self.parse_ty_sum();
2225 self.expect_keyword(keywords::As);
2226 let trait_ref = self.parse_trait_ref();
2227 self.expect(&token::Gt);
2228 self.expect(&token::ModSep);
2229 let item_name = self.parse_ident();
2230 let parameters = if self.eat(&token::ModSep) {
2232 // Consumed `item::<`, go look for types
2233 let (lifetimes, types, bindings) =
2234 self.parse_generic_values_after_lt();
2235 ast::AngleBracketedParameters(ast::AngleBracketedParameterData {
2236 lifetimes: lifetimes,
2237 types: OwnedSlice::from_vec(types),
2238 bindings: OwnedSlice::from_vec(bindings),
2241 ast::PathParameters::none()
2243 let hi = self.span.hi;
2244 return self.mk_expr(lo, hi, ExprQPath(P(QPath {
2245 self_type: self_type,
2246 trait_ref: P(trait_ref),
2247 item_path: ast::PathSegment {
2248 identifier: item_name,
2249 parameters: parameters
2253 if self.eat_keyword(keywords::Move) {
2254 return self.parse_lambda_expr(CaptureByValue);
2256 if self.eat_keyword_noexpect(keywords::Proc) {
2257 let span = self.last_span;
2258 let _ = self.parse_proc_decl();
2259 let _ = self.parse_expr();
2260 return self.obsolete_expr(span, ObsoleteSyntax::ProcExpr);
2262 if self.eat_keyword(keywords::If) {
2263 return self.parse_if_expr();
2265 if self.eat_keyword(keywords::For) {
2266 return self.parse_for_expr(None);
2268 if self.eat_keyword(keywords::While) {
2269 return self.parse_while_expr(None);
2271 if self.token.is_lifetime() {
2272 let lifetime = self.get_lifetime();
2274 self.expect(&token::Colon);
2275 if self.eat_keyword(keywords::While) {
2276 return self.parse_while_expr(Some(lifetime))
2278 if self.eat_keyword(keywords::For) {
2279 return self.parse_for_expr(Some(lifetime))
2281 if self.eat_keyword(keywords::Loop) {
2282 return self.parse_loop_expr(Some(lifetime))
2284 self.fatal("expected `while`, `for`, or `loop` after a label")
2286 if self.eat_keyword(keywords::Loop) {
2287 return self.parse_loop_expr(None);
2289 if self.eat_keyword(keywords::Continue) {
2290 let lo = self.span.lo;
2291 let ex = if self.token.is_lifetime() {
2292 let lifetime = self.get_lifetime();
2294 ExprAgain(Some(lifetime))
2298 let hi = self.span.hi;
2299 return self.mk_expr(lo, hi, ex);
2301 if self.eat_keyword(keywords::Match) {
2302 return self.parse_match_expr();
2304 if self.eat_keyword(keywords::Unsafe) {
2305 return self.parse_block_expr(
2307 UnsafeBlock(ast::UserProvided));
2309 if self.eat_keyword(keywords::Return) {
2310 // RETURN expression
2311 if self.token.can_begin_expr() {
2312 let e = self.parse_expr();
2314 ex = ExprRet(Some(e));
2318 } else if self.eat_keyword(keywords::Break) {
2320 if self.token.is_lifetime() {
2321 let lifetime = self.get_lifetime();
2323 ex = ExprBreak(Some(lifetime));
2325 ex = ExprBreak(None);
2328 } else if self.check(&token::ModSep) ||
2329 self.token.is_ident() &&
2330 !self.check_keyword(keywords::True) &&
2331 !self.check_keyword(keywords::False) {
2333 self.parse_path(LifetimeAndTypesWithColons);
2335 // `!`, as an operator, is prefix, so we know this isn't that
2336 if self.check(&token::Not) {
2337 // MACRO INVOCATION expression
2340 let delim = self.expect_open_delim();
2341 let tts = self.parse_seq_to_end(
2342 &token::CloseDelim(delim),
2344 |p| p.parse_token_tree());
2345 let hi = self.span.hi;
2347 return self.mk_mac_expr(lo,
2353 if self.check(&token::OpenDelim(token::Brace)) {
2354 // This is a struct literal, unless we're prohibited
2355 // from parsing struct literals here.
2356 if !self.restrictions.contains(RESTRICTION_NO_STRUCT_LITERAL) {
2357 // It's a struct literal.
2359 let mut fields = Vec::new();
2360 let mut base = None;
2362 while self.token != token::CloseDelim(token::Brace) {
2363 if self.eat(&token::DotDot) {
2364 base = Some(self.parse_expr());
2368 fields.push(self.parse_field());
2369 self.commit_expr(&*fields.last().unwrap().expr,
2371 &[token::CloseDelim(token::Brace)]);
2374 if fields.len() == 0 && base.is_none() {
2375 let last_span = self.last_span;
2376 self.span_err(last_span,
2377 "structure literal must either \
2378 have at least one field or use \
2379 functional structure update \
2384 self.expect(&token::CloseDelim(token::Brace));
2385 ex = ExprStruct(pth, fields, base);
2386 return self.mk_expr(lo, hi, ex);
2393 // other literal expression
2394 let lit = self.parse_lit();
2396 ex = ExprLit(P(lit));
2401 return self.mk_expr(lo, hi, ex);
2404 /// Parse a block or unsafe block
2405 pub fn parse_block_expr(&mut self, lo: BytePos, blk_mode: BlockCheckMode)
2407 self.expect(&token::OpenDelim(token::Brace));
2408 let blk = self.parse_block_tail(lo, blk_mode);
2409 return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk));
2412 /// parse a.b or a(13) or a[4] or just a
2413 pub fn parse_dot_or_call_expr(&mut self) -> P<Expr> {
2414 let b = self.parse_bottom_expr();
2415 self.parse_dot_or_call_expr_with(b)
2418 pub fn parse_dot_or_call_expr_with(&mut self, e0: P<Expr>) -> P<Expr> {
2424 if self.eat(&token::Dot) {
2426 token::Ident(i, _) => {
2427 let dot = self.last_span.hi;
2430 let (_, tys, bindings) = if self.eat(&token::ModSep) {
2432 self.parse_generic_values_after_lt()
2434 (Vec::new(), Vec::new(), Vec::new())
2437 if bindings.len() > 0 {
2438 let last_span = self.last_span;
2439 self.span_err(last_span, "type bindings are only permitted on trait paths");
2442 // expr.f() method call
2444 token::OpenDelim(token::Paren) => {
2445 let mut es = self.parse_unspanned_seq(
2446 &token::OpenDelim(token::Paren),
2447 &token::CloseDelim(token::Paren),
2448 seq_sep_trailing_allowed(token::Comma),
2451 hi = self.last_span.hi;
2454 let id = spanned(dot, hi, i);
2455 let nd = self.mk_method_call(id, tys, es);
2456 e = self.mk_expr(lo, hi, nd);
2459 if !tys.is_empty() {
2460 let last_span = self.last_span;
2461 self.span_err(last_span,
2462 "field expressions may not \
2463 have type parameters");
2466 let id = spanned(dot, hi, i);
2467 let field = self.mk_field(e, id);
2468 e = self.mk_expr(lo, hi, field);
2472 token::Literal(token::Integer(n), suf) => {
2475 // A tuple index may not have a suffix
2476 self.expect_no_suffix(sp, "tuple index", suf);
2478 let dot = self.last_span.hi;
2482 let index = n.as_str().parse::<usize>().ok();
2485 let id = spanned(dot, hi, n);
2486 let field = self.mk_tup_field(e, id);
2487 e = self.mk_expr(lo, hi, field);
2490 let last_span = self.last_span;
2491 self.span_err(last_span, "invalid tuple or tuple struct index");
2495 token::Literal(token::Float(n), _suf) => {
2497 let last_span = self.last_span;
2498 let fstr = n.as_str();
2499 self.span_err(last_span,
2500 &format!("unexpected token: `{}`", n.as_str())[]);
2501 if fstr.chars().all(|x| "0123456789.".contains_char(x)) {
2502 let float = match fstr.parse::<f64>().ok() {
2506 self.span_help(last_span,
2507 &format!("try parenthesizing the first index; e.g., `(foo.{}){}`",
2508 float.trunc() as usize,
2509 &float.fract().to_string()[1..])[]);
2511 self.abort_if_errors();
2514 _ => self.unexpected()
2518 if self.expr_is_complete(&*e) { break; }
2521 token::OpenDelim(token::Paren) => {
2522 let es = self.parse_unspanned_seq(
2523 &token::OpenDelim(token::Paren),
2524 &token::CloseDelim(token::Paren),
2525 seq_sep_trailing_allowed(token::Comma),
2528 hi = self.last_span.hi;
2530 let nd = self.mk_call(e, es);
2531 e = self.mk_expr(lo, hi, nd);
2535 // Could be either an index expression or a slicing expression.
2536 token::OpenDelim(token::Bracket) => {
2537 let bracket_pos = self.span.lo;
2540 if self.eat(&token::CloseDelim(token::Bracket)) {
2541 // No expression, expand to a RangeFull
2542 // FIXME(#20516) It would be better to use a lang item or
2543 // something for RangeFull.
2544 hi = self.last_span.hi;
2546 let idents = vec![token::str_to_ident("std"),
2547 token::str_to_ident("ops"),
2548 token::str_to_ident("RangeFull")];
2549 let segments = idents.into_iter().map(|ident| {
2552 parameters: ast::PathParameters::none(),
2555 let path = ast::Path {
2556 span: mk_sp(lo, hi),
2561 let range = ExprStruct(path, vec![], None);
2562 let ix = self.mk_expr(bracket_pos, hi, range);
2563 let index = self.mk_index(e, ix);
2564 e = self.mk_expr(lo, hi, index);
2565 // Enable after snapshot.
2566 // self.span_warn(e.span, "deprecated slicing syntax: `[]`");
2567 // self.span_note(e.span,
2568 // "use `&expr[..]` to construct a slice of the whole of expr");
2570 let ix = self.parse_expr();
2572 self.commit_expr_expecting(&*ix, token::CloseDelim(token::Bracket));
2573 let index = self.mk_index(e, ix);
2574 e = self.mk_expr(lo, hi, index)
2584 // Parse unquoted tokens after a `$` in a token tree
2585 fn parse_unquoted(&mut self) -> TokenTree {
2586 let mut sp = self.span;
2587 let (name, namep) = match self.token {
2591 if self.token == token::OpenDelim(token::Paren) {
2592 let Spanned { node: seq, span: seq_span } = self.parse_seq(
2593 &token::OpenDelim(token::Paren),
2594 &token::CloseDelim(token::Paren),
2596 |p| p.parse_token_tree()
2598 let (sep, repeat) = self.parse_sep_and_kleene_op();
2599 let name_num = macro_parser::count_names(&seq);
2600 return TtSequence(mk_sp(sp.lo, seq_span.hi),
2601 Rc::new(SequenceRepetition {
2605 num_captures: name_num
2607 } else if self.token.is_keyword_allow_following_colon(keywords::Crate) {
2609 return TtToken(sp, SpecialVarNt(SpecialMacroVar::CrateMacroVar));
2611 sp = mk_sp(sp.lo, self.span.hi);
2612 let namep = match self.token { token::Ident(_, p) => p, _ => token::Plain };
2613 let name = self.parse_ident();
2617 token::SubstNt(name, namep) => {
2623 // continue by trying to parse the `:ident` after `$name`
2624 if self.token == token::Colon && self.look_ahead(1, |t| t.is_ident() &&
2625 !t.is_strict_keyword() &&
2626 !t.is_reserved_keyword()) {
2628 sp = mk_sp(sp.lo, self.span.hi);
2629 let kindp = match self.token { token::Ident(_, p) => p, _ => token::Plain };
2630 let nt_kind = self.parse_ident();
2631 TtToken(sp, MatchNt(name, nt_kind, namep, kindp))
2633 TtToken(sp, SubstNt(name, namep))
2637 pub fn check_unknown_macro_variable(&mut self) {
2638 if self.quote_depth == 0 {
2640 token::SubstNt(name, _) =>
2641 self.fatal(&format!("unknown macro variable `{}`",
2642 token::get_ident(name))[]),
2648 /// Parse an optional separator followed by a Kleene-style
2649 /// repetition token (+ or *).
2650 pub fn parse_sep_and_kleene_op(&mut self) -> (Option<token::Token>, ast::KleeneOp) {
2651 fn parse_kleene_op(parser: &mut Parser) -> Option<ast::KleeneOp> {
2652 match parser.token {
2653 token::BinOp(token::Star) => {
2655 Some(ast::ZeroOrMore)
2657 token::BinOp(token::Plus) => {
2659 Some(ast::OneOrMore)
2665 match parse_kleene_op(self) {
2666 Some(kleene_op) => return (None, kleene_op),
2670 let separator = self.bump_and_get();
2671 match parse_kleene_op(self) {
2672 Some(zerok) => (Some(separator), zerok),
2673 None => self.fatal("expected `*` or `+`")
2677 /// parse a single token tree from the input.
2678 pub fn parse_token_tree(&mut self) -> TokenTree {
2679 // FIXME #6994: currently, this is too eager. It
2680 // parses token trees but also identifies TtSequence's
2681 // and token::SubstNt's; it's too early to know yet
2682 // whether something will be a nonterminal or a seq
2684 maybe_whole!(deref self, NtTT);
2686 // this is the fall-through for the 'match' below.
2687 // invariants: the current token is not a left-delimiter,
2688 // not an EOF, and not the desired right-delimiter (if
2689 // it were, parse_seq_to_before_end would have prevented
2690 // reaching this point.
2691 fn parse_non_delim_tt_tok(p: &mut Parser) -> TokenTree {
2692 maybe_whole!(deref p, NtTT);
2694 token::CloseDelim(_) => {
2695 // This is a conservative error: only report the last unclosed delimiter. The
2696 // previous unclosed delimiters could actually be closed! The parser just hasn't
2697 // gotten to them yet.
2698 match p.open_braces.last() {
2700 Some(&sp) => p.span_note(sp, "unclosed delimiter"),
2702 let token_str = p.this_token_to_string();
2703 p.fatal(&format!("incorrect close delimiter: `{}`",
2706 /* we ought to allow different depths of unquotation */
2707 token::Dollar | token::SubstNt(..) if p.quote_depth > 0 => {
2711 TtToken(p.span, p.bump_and_get())
2718 let open_braces = self.open_braces.clone();
2719 for sp in &open_braces {
2720 self.span_help(*sp, "did you mean to close this delimiter?");
2722 // There shouldn't really be a span, but it's easier for the test runner
2723 // if we give it one
2724 self.fatal("this file contains an un-closed delimiter ");
2726 token::OpenDelim(delim) => {
2727 // The span for beginning of the delimited section
2728 let pre_span = self.span;
2730 // Parse the open delimiter.
2731 self.open_braces.push(self.span);
2732 let open_span = self.span;
2735 // Parse the token trees within the delimiters
2736 let tts = self.parse_seq_to_before_end(
2737 &token::CloseDelim(delim),
2739 |p| p.parse_token_tree()
2742 // Parse the close delimiter.
2743 let close_span = self.span;
2745 self.open_braces.pop().unwrap();
2747 // Expand to cover the entire delimited token tree
2748 let span = Span { hi: close_span.hi, ..pre_span };
2750 TtDelimited(span, Rc::new(Delimited {
2752 open_span: open_span,
2754 close_span: close_span,
2757 _ => parse_non_delim_tt_tok(self),
2761 // parse a stream of tokens into a list of TokenTree's,
2763 pub fn parse_all_token_trees(&mut self) -> Vec<TokenTree> {
2764 let mut tts = Vec::new();
2765 while self.token != token::Eof {
2766 tts.push(self.parse_token_tree());
2771 /// Parse a prefix-operator expr
2772 pub fn parse_prefix_expr(&mut self) -> P<Expr> {
2773 let lo = self.span.lo;
2776 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2781 let e = self.parse_prefix_expr();
2783 ex = self.mk_unary(UnNot, e);
2785 token::BinOp(token::Minus) => {
2787 let e = self.parse_prefix_expr();
2789 ex = self.mk_unary(UnNeg, e);
2791 token::BinOp(token::Star) => {
2793 let e = self.parse_prefix_expr();
2795 ex = self.mk_unary(UnDeref, e);
2797 token::BinOp(token::And) | token::AndAnd => {
2799 let m = self.parse_mutability();
2800 let e = self.parse_prefix_expr();
2802 ex = ExprAddrOf(m, e);
2804 token::Ident(_, _) => {
2805 if !self.check_keyword(keywords::Box) {
2806 return self.parse_dot_or_call_expr();
2809 let lo = self.span.lo;
2813 // Check for a place: `box(PLACE) EXPR`.
2814 if self.eat(&token::OpenDelim(token::Paren)) {
2815 // Support `box() EXPR` as the default.
2816 if !self.eat(&token::CloseDelim(token::Paren)) {
2817 let place = self.parse_expr();
2818 self.expect(&token::CloseDelim(token::Paren));
2819 // Give a suggestion to use `box()` when a parenthesised expression is used
2820 if !self.token.can_begin_expr() {
2821 let span = self.span;
2822 let this_token_to_string = self.this_token_to_string();
2824 &format!("expected expression, found `{}`",
2825 this_token_to_string)[]);
2826 let box_span = mk_sp(lo, self.last_span.hi);
2827 self.span_help(box_span,
2828 "perhaps you meant `box() (foo)` instead?");
2829 self.abort_if_errors();
2831 let subexpression = self.parse_prefix_expr();
2832 hi = subexpression.span.hi;
2833 ex = ExprBox(Some(place), subexpression);
2834 return self.mk_expr(lo, hi, ex);
2838 // Otherwise, we use the unique pointer default.
2839 let subexpression = self.parse_prefix_expr();
2840 hi = subexpression.span.hi;
2841 // FIXME (pnkfelix): After working out kinks with box
2842 // desugaring, should be `ExprBox(None, subexpression)`
2844 ex = self.mk_unary(UnUniq, subexpression);
2846 _ => return self.parse_dot_or_call_expr()
2848 return self.mk_expr(lo, hi, ex);
2851 /// Parse an expression of binops
2852 pub fn parse_binops(&mut self) -> P<Expr> {
2853 let prefix_expr = self.parse_prefix_expr();
2854 self.parse_more_binops(prefix_expr, 0)
2857 /// Parse an expression of binops of at least min_prec precedence
2858 pub fn parse_more_binops(&mut self, lhs: P<Expr>, min_prec: usize) -> P<Expr> {
2859 if self.expr_is_complete(&*lhs) { return lhs; }
2861 // Prevent dynamic borrow errors later on by limiting the
2862 // scope of the borrows.
2863 if self.token == token::BinOp(token::Or) &&
2864 self.restrictions.contains(RESTRICTION_NO_BAR_OP) {
2868 self.expected_tokens.push(TokenType::Operator);
2870 let cur_op_span = self.span;
2871 let cur_opt = self.token.to_binop();
2874 if ast_util::is_comparison_binop(cur_op) {
2875 self.check_no_chained_comparison(&*lhs, cur_op)
2877 let cur_prec = operator_prec(cur_op);
2878 if cur_prec >= min_prec {
2880 let expr = self.parse_prefix_expr();
2881 let rhs = self.parse_more_binops(expr, cur_prec + 1);
2882 let lhs_span = lhs.span;
2883 let rhs_span = rhs.span;
2884 let binary = self.mk_binary(codemap::respan(cur_op_span, cur_op), lhs, rhs);
2885 let bin = self.mk_expr(lhs_span.lo, rhs_span.hi, binary);
2886 self.parse_more_binops(bin, min_prec)
2892 if AS_PREC >= min_prec && self.eat_keyword_noexpect(keywords::As) {
2893 let rhs = self.parse_ty();
2894 let _as = self.mk_expr(lhs.span.lo,
2896 ExprCast(lhs, rhs));
2897 self.parse_more_binops(_as, min_prec)
2905 /// Produce an error if comparison operators are chained (RFC #558).
2906 /// We only need to check lhs, not rhs, because all comparison ops
2907 /// have same precedence and are left-associative
2908 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: ast::BinOp_) {
2909 debug_assert!(ast_util::is_comparison_binop(outer_op));
2911 ExprBinary(op, _, _) if ast_util::is_comparison_binop(op.node) => {
2912 // respan to include both operators
2913 let op_span = mk_sp(op.span.lo, self.span.hi);
2914 self.span_err(op_span,
2915 "chained comparison operators require parentheses");
2916 if op.node == BiLt && outer_op == BiGt {
2917 self.span_help(op_span,
2918 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
2925 /// Parse an assignment expression....
2926 /// actually, this seems to be the main entry point for
2927 /// parsing an arbitrary expression.
2928 pub fn parse_assign_expr(&mut self) -> P<Expr> {
2931 // prefix-form of range notation '..expr'
2932 // This has the same precedence as assignment expressions
2933 // (much lower than other prefix expressions) to be consistent
2934 // with the postfix-form 'expr..'
2935 let lo = self.span.lo;
2937 let opt_end = if self.is_at_start_of_range_notation_rhs() {
2938 let end = self.parse_binops();
2943 let hi = self.span.hi;
2944 let ex = self.mk_range(None, opt_end);
2945 self.mk_expr(lo, hi, ex)
2948 let lhs = self.parse_binops();
2949 self.parse_assign_expr_with(lhs)
2954 pub fn parse_assign_expr_with(&mut self, lhs: P<Expr>) -> P<Expr> {
2955 let restrictions = self.restrictions & RESTRICTION_NO_STRUCT_LITERAL;
2956 let op_span = self.span;
2960 let rhs = self.parse_expr_res(restrictions);
2961 self.mk_expr(lhs.span.lo, rhs.span.hi, ExprAssign(lhs, rhs))
2963 token::BinOpEq(op) => {
2965 let rhs = self.parse_expr_res(restrictions);
2966 let aop = match op {
2967 token::Plus => BiAdd,
2968 token::Minus => BiSub,
2969 token::Star => BiMul,
2970 token::Slash => BiDiv,
2971 token::Percent => BiRem,
2972 token::Caret => BiBitXor,
2973 token::And => BiBitAnd,
2974 token::Or => BiBitOr,
2975 token::Shl => BiShl,
2978 let rhs_span = rhs.span;
2979 let span = lhs.span;
2980 let assign_op = self.mk_assign_op(codemap::respan(op_span, aop), lhs, rhs);
2981 self.mk_expr(span.lo, rhs_span.hi, assign_op)
2983 // A range expression, either `expr..expr` or `expr..`.
2987 let opt_end = if self.is_at_start_of_range_notation_rhs() {
2988 let end = self.parse_binops();
2994 let lo = lhs.span.lo;
2995 let hi = self.span.hi;
2996 let range = self.mk_range(Some(lhs), opt_end);
2997 return self.mk_expr(lo, hi, range);
3006 fn is_at_start_of_range_notation_rhs(&self) -> bool {
3007 if self.token.can_begin_expr() {
3008 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
3009 if self.token == token::OpenDelim(token::Brace) {
3010 return !self.restrictions.contains(RESTRICTION_NO_STRUCT_LITERAL);
3018 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
3019 pub fn parse_if_expr(&mut self) -> P<Expr> {
3020 if self.check_keyword(keywords::Let) {
3021 return self.parse_if_let_expr();
3023 let lo = self.last_span.lo;
3024 let cond = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
3025 let thn = self.parse_block();
3026 let mut els: Option<P<Expr>> = None;
3027 let mut hi = thn.span.hi;
3028 if self.eat_keyword(keywords::Else) {
3029 let elexpr = self.parse_else_expr();
3030 hi = elexpr.span.hi;
3033 self.mk_expr(lo, hi, ExprIf(cond, thn, els))
3036 /// Parse an 'if let' expression ('if' token already eaten)
3037 pub fn parse_if_let_expr(&mut self) -> P<Expr> {
3038 let lo = self.last_span.lo;
3039 self.expect_keyword(keywords::Let);
3040 let pat = self.parse_pat();
3041 self.expect(&token::Eq);
3042 let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
3043 let thn = self.parse_block();
3044 let (hi, els) = if self.eat_keyword(keywords::Else) {
3045 let expr = self.parse_else_expr();
3046 (expr.span.hi, Some(expr))
3050 self.mk_expr(lo, hi, ExprIfLet(pat, expr, thn, els))
3054 pub fn parse_lambda_expr(&mut self, capture_clause: CaptureClause)
3057 let lo = self.span.lo;
3058 let decl = self.parse_fn_block_decl();
3059 let body = self.parse_expr();
3060 let fakeblock = P(ast::Block {
3061 id: ast::DUMMY_NODE_ID,
3065 rules: DefaultBlock,
3071 ExprClosure(capture_clause, decl, fakeblock))
3074 pub fn parse_else_expr(&mut self) -> P<Expr> {
3075 if self.eat_keyword(keywords::If) {
3076 return self.parse_if_expr();
3078 let blk = self.parse_block();
3079 return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk));
3083 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3084 pub fn parse_for_expr(&mut self, opt_ident: Option<ast::Ident>) -> P<Expr> {
3085 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3087 let lo = self.last_span.lo;
3088 let pat = self.parse_pat();
3089 self.expect_keyword(keywords::In);
3090 let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
3091 let loop_block = self.parse_block();
3092 let hi = self.span.hi;
3094 self.mk_expr(lo, hi, ExprForLoop(pat, expr, loop_block, opt_ident))
3097 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3098 pub fn parse_while_expr(&mut self, opt_ident: Option<ast::Ident>) -> P<Expr> {
3099 if self.token.is_keyword(keywords::Let) {
3100 return self.parse_while_let_expr(opt_ident);
3102 let lo = self.last_span.lo;
3103 let cond = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
3104 let body = self.parse_block();
3105 let hi = body.span.hi;
3106 return self.mk_expr(lo, hi, ExprWhile(cond, body, opt_ident));
3109 /// Parse a 'while let' expression ('while' token already eaten)
3110 pub fn parse_while_let_expr(&mut self, opt_ident: Option<ast::Ident>) -> P<Expr> {
3111 let lo = self.last_span.lo;
3112 self.expect_keyword(keywords::Let);
3113 let pat = self.parse_pat();
3114 self.expect(&token::Eq);
3115 let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
3116 let body = self.parse_block();
3117 let hi = body.span.hi;
3118 return self.mk_expr(lo, hi, ExprWhileLet(pat, expr, body, opt_ident));
3121 pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::Ident>) -> P<Expr> {
3122 let lo = self.last_span.lo;
3123 let body = self.parse_block();
3124 let hi = body.span.hi;
3125 self.mk_expr(lo, hi, ExprLoop(body, opt_ident))
3128 fn parse_match_expr(&mut self) -> P<Expr> {
3129 let lo = self.last_span.lo;
3130 let discriminant = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
3131 self.commit_expr_expecting(&*discriminant, token::OpenDelim(token::Brace));
3132 let mut arms: Vec<Arm> = Vec::new();
3133 while self.token != token::CloseDelim(token::Brace) {
3134 arms.push(self.parse_arm());
3136 let hi = self.span.hi;
3138 return self.mk_expr(lo, hi, ExprMatch(discriminant, arms, MatchSource::Normal));
3141 pub fn parse_arm(&mut self) -> Arm {
3142 let attrs = self.parse_outer_attributes();
3143 let pats = self.parse_pats();
3144 let mut guard = None;
3145 if self.eat_keyword(keywords::If) {
3146 guard = Some(self.parse_expr());
3148 self.expect(&token::FatArrow);
3149 let expr = self.parse_expr_res(RESTRICTION_STMT_EXPR);
3152 !classify::expr_is_simple_block(&*expr)
3153 && self.token != token::CloseDelim(token::Brace);
3156 self.commit_expr(&*expr, &[token::Comma], &[token::CloseDelim(token::Brace)]);
3158 self.eat(&token::Comma);
3169 /// Parse an expression
3170 pub fn parse_expr(&mut self) -> P<Expr> {
3171 return self.parse_expr_res(UNRESTRICTED);
3174 /// Parse an expression, subject to the given restrictions
3175 pub fn parse_expr_res(&mut self, r: Restrictions) -> P<Expr> {
3176 let old = self.restrictions;
3177 self.restrictions = r;
3178 let e = self.parse_assign_expr();
3179 self.restrictions = old;
3183 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3184 fn parse_initializer(&mut self) -> Option<P<Expr>> {
3185 if self.check(&token::Eq) {
3187 Some(self.parse_expr())
3193 /// Parse patterns, separated by '|' s
3194 fn parse_pats(&mut self) -> Vec<P<Pat>> {
3195 let mut pats = Vec::new();
3197 pats.push(self.parse_pat());
3198 if self.check(&token::BinOp(token::Or)) { self.bump(); }
3199 else { return pats; }
3203 fn parse_pat_vec_elements(
3205 ) -> (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>) {
3206 let mut before = Vec::new();
3207 let mut slice = None;
3208 let mut after = Vec::new();
3209 let mut first = true;
3210 let mut before_slice = true;
3212 while self.token != token::CloseDelim(token::Bracket) {
3216 self.expect(&token::Comma);
3218 if self.token == token::CloseDelim(token::Bracket)
3219 && (before_slice || after.len() != 0) {
3225 if self.check(&token::DotDot) {
3228 if self.check(&token::Comma) ||
3229 self.check(&token::CloseDelim(token::Bracket)) {
3230 slice = Some(P(ast::Pat {
3231 id: ast::DUMMY_NODE_ID,
3232 node: PatWild(PatWildMulti),
3235 before_slice = false;
3241 let subpat = self.parse_pat();
3242 if before_slice && self.check(&token::DotDot) {
3244 slice = Some(subpat);
3245 before_slice = false;
3246 } else if before_slice {
3247 before.push(subpat);
3253 (before, slice, after)
3256 /// Parse the fields of a struct-like pattern
3257 fn parse_pat_fields(&mut self) -> (Vec<codemap::Spanned<ast::FieldPat>> , bool) {
3258 let mut fields = Vec::new();
3259 let mut etc = false;
3260 let mut first = true;
3261 while self.token != token::CloseDelim(token::Brace) {
3265 self.expect(&token::Comma);
3266 // accept trailing commas
3267 if self.check(&token::CloseDelim(token::Brace)) { break }
3270 let lo = self.span.lo;
3273 if self.check(&token::DotDot) {
3275 if self.token != token::CloseDelim(token::Brace) {
3276 let token_str = self.this_token_to_string();
3277 self.fatal(&format!("expected `{}`, found `{}`", "}",
3284 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3285 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3286 // Parsing a pattern of the form "fieldname: pat"
3287 let fieldname = self.parse_ident();
3289 let pat = self.parse_pat();
3291 (pat, fieldname, false)
3293 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3294 let is_box = self.eat_keyword(keywords::Box);
3295 let boxed_span_lo = self.span.lo;
3296 let is_ref = self.eat_keyword(keywords::Ref);
3297 let is_mut = self.eat_keyword(keywords::Mut);
3298 let fieldname = self.parse_ident();
3299 hi = self.last_span.hi;
3301 let bind_type = match (is_ref, is_mut) {
3302 (true, true) => BindByRef(MutMutable),
3303 (true, false) => BindByRef(MutImmutable),
3304 (false, true) => BindByValue(MutMutable),
3305 (false, false) => BindByValue(MutImmutable),
3307 let fieldpath = codemap::Spanned{span:self.last_span, node:fieldname};
3308 let fieldpat = P(ast::Pat{
3309 id: ast::DUMMY_NODE_ID,
3310 node: PatIdent(bind_type, fieldpath, None),
3311 span: mk_sp(boxed_span_lo, hi),
3314 let subpat = if is_box {
3316 id: ast::DUMMY_NODE_ID,
3317 node: PatBox(fieldpat),
3318 span: mk_sp(lo, hi),
3323 (subpat, fieldname, true)
3326 fields.push(codemap::Spanned { span: mk_sp(lo, hi),
3327 node: ast::FieldPat { ident: fieldname,
3329 is_shorthand: is_shorthand }});
3331 return (fields, etc);
3334 /// Parse a pattern.
3335 pub fn parse_pat(&mut self) -> P<Pat> {
3336 maybe_whole!(self, NtPat);
3338 let lo = self.span.lo;
3343 token::Underscore => {
3345 pat = PatWild(PatWildSingle);
3346 hi = self.last_span.hi;
3348 id: ast::DUMMY_NODE_ID,
3353 token::BinOp(token::And) | token::AndAnd => {
3354 // parse &pat and &mut pat
3355 let lo = self.span.lo;
3357 let mutability = if self.eat_keyword(keywords::Mut) {
3362 let sub = self.parse_pat();
3363 pat = PatRegion(sub, mutability);
3364 hi = self.last_span.hi;
3366 id: ast::DUMMY_NODE_ID,
3371 token::OpenDelim(token::Paren) => {
3372 // parse (pat,pat,pat,...) as tuple
3374 if self.check(&token::CloseDelim(token::Paren)) {
3376 pat = PatTup(vec![]);
3378 let mut fields = vec!(self.parse_pat());
3379 if self.look_ahead(1, |t| *t != token::CloseDelim(token::Paren)) {
3380 while self.check(&token::Comma) {
3382 if self.check(&token::CloseDelim(token::Paren)) { break; }
3383 fields.push(self.parse_pat());
3386 if fields.len() == 1 { self.expect(&token::Comma); }
3387 self.expect(&token::CloseDelim(token::Paren));
3388 pat = PatTup(fields);
3390 hi = self.last_span.hi;
3392 id: ast::DUMMY_NODE_ID,
3397 token::OpenDelim(token::Bracket) => {
3398 // parse [pat,pat,...] as vector pattern
3400 let (before, slice, after) =
3401 self.parse_pat_vec_elements();
3403 self.expect(&token::CloseDelim(token::Bracket));
3404 pat = ast::PatVec(before, slice, after);
3405 hi = self.last_span.hi;
3407 id: ast::DUMMY_NODE_ID,
3414 // at this point, token != _, ~, &, &&, (, [
3416 if (!(self.token.is_ident() || self.token.is_path())
3417 && self.token != token::ModSep)
3418 || self.token.is_keyword(keywords::True)
3419 || self.token.is_keyword(keywords::False) {
3420 // Parse an expression pattern or exp ... exp.
3422 // These expressions are limited to literals (possibly
3423 // preceded by unary-minus) or identifiers.
3424 let val = self.parse_literal_maybe_minus();
3425 if (self.check(&token::DotDotDot)) &&
3426 self.look_ahead(1, |t| {
3427 *t != token::Comma && *t != token::CloseDelim(token::Bracket)
3430 let end = if self.token.is_ident() || self.token.is_path() {
3431 let path = self.parse_path(LifetimeAndTypesWithColons);
3432 let hi = self.span.hi;
3433 self.mk_expr(lo, hi, ExprPath(path))
3435 self.parse_literal_maybe_minus()
3437 pat = PatRange(val, end);
3441 } else if self.eat_keyword(keywords::Mut) {
3442 pat = self.parse_pat_ident(BindByValue(MutMutable));
3443 } else if self.eat_keyword(keywords::Ref) {
3445 let mutbl = self.parse_mutability();
3446 pat = self.parse_pat_ident(BindByRef(mutbl));
3447 } else if self.eat_keyword(keywords::Box) {
3450 // FIXME(#13910): Rename to `PatBox` and extend to full DST
3452 let sub = self.parse_pat();
3454 hi = self.last_span.hi;
3456 id: ast::DUMMY_NODE_ID,
3461 let can_be_enum_or_struct = self.look_ahead(1, |t| {
3463 token::OpenDelim(_) | token::Lt | token::ModSep => true,
3468 if self.look_ahead(1, |t| *t == token::DotDotDot) &&
3469 self.look_ahead(2, |t| {
3470 *t != token::Comma && *t != token::CloseDelim(token::Bracket)
3472 let start = self.parse_expr_res(RESTRICTION_NO_BAR_OP);
3473 self.eat(&token::DotDotDot);
3474 let end = self.parse_expr_res(RESTRICTION_NO_BAR_OP);
3475 pat = PatRange(start, end);
3476 } else if self.token.is_plain_ident() && !can_be_enum_or_struct {
3477 let id = self.parse_ident();
3478 let id_span = self.last_span;
3479 let pth1 = codemap::Spanned{span:id_span, node: id};
3480 if self.eat(&token::Not) {
3482 let delim = self.expect_open_delim();
3483 let tts = self.parse_seq_to_end(&token::CloseDelim(delim),
3485 |p| p.parse_token_tree());
3487 let mac = MacInvocTT(ident_to_path(id_span,id), tts, EMPTY_CTXT);
3488 pat = ast::PatMac(codemap::Spanned {node: mac, span: self.span});
3490 let sub = if self.eat(&token::At) {
3492 Some(self.parse_pat())
3497 pat = PatIdent(BindByValue(MutImmutable), pth1, sub);
3500 // parse an enum pat
3501 let enum_path = self.parse_path(LifetimeAndTypesWithColons);
3503 token::OpenDelim(token::Brace) => {
3506 self.parse_pat_fields();
3508 pat = PatStruct(enum_path, fields, etc);
3511 let mut args: Vec<P<Pat>> = Vec::new();
3513 token::OpenDelim(token::Paren) => {
3514 let is_dotdot = self.look_ahead(1, |t| {
3516 token::DotDot => true,
3521 // This is a "top constructor only" pat
3524 self.expect(&token::CloseDelim(token::Paren));
3525 pat = PatEnum(enum_path, None);
3527 args = self.parse_enum_variant_seq(
3528 &token::OpenDelim(token::Paren),
3529 &token::CloseDelim(token::Paren),
3530 seq_sep_trailing_allowed(token::Comma),
3533 pat = PatEnum(enum_path, Some(args));
3537 if !enum_path.global &&
3538 enum_path.segments.len() == 1 &&
3539 enum_path.segments[0].parameters.is_empty()
3541 // NB: If enum_path is a single identifier,
3542 // this should not be reachable due to special
3543 // handling further above.
3545 // However, previously a PatIdent got emitted
3546 // here, so we preserve the branch just in case.
3548 // A rewrite of the logic in this function
3549 // would probably make this obvious.
3550 self.span_bug(enum_path.span,
3551 "ident only path should have been covered already");
3553 pat = PatEnum(enum_path, Some(args));
3561 hi = self.last_span.hi;
3563 id: ast::DUMMY_NODE_ID,
3565 span: mk_sp(lo, hi),
3569 /// Parse ident or ident @ pat
3570 /// used by the copy foo and ref foo patterns to give a good
3571 /// error message when parsing mistakes like ref foo(a,b)
3572 fn parse_pat_ident(&mut self,
3573 binding_mode: ast::BindingMode)
3575 if !self.token.is_plain_ident() {
3576 let span = self.span;
3577 let tok_str = self.this_token_to_string();
3578 self.span_fatal(span,
3579 &format!("expected identifier, found `{}`", tok_str)[]);
3581 let ident = self.parse_ident();
3582 let last_span = self.last_span;
3583 let name = codemap::Spanned{span: last_span, node: ident};
3584 let sub = if self.eat(&token::At) {
3585 Some(self.parse_pat())
3590 // just to be friendly, if they write something like
3592 // we end up here with ( as the current token. This shortly
3593 // leads to a parse error. Note that if there is no explicit
3594 // binding mode then we do not end up here, because the lookahead
3595 // will direct us over to parse_enum_variant()
3596 if self.token == token::OpenDelim(token::Paren) {
3597 let last_span = self.last_span;
3600 "expected identifier, found enum pattern");
3603 PatIdent(binding_mode, name, sub)
3606 /// Parse a local variable declaration
3607 fn parse_local(&mut self) -> P<Local> {
3608 let lo = self.span.lo;
3609 let pat = self.parse_pat();
3612 if self.eat(&token::Colon) {
3613 ty = Some(self.parse_ty_sum());
3615 let init = self.parse_initializer();
3620 id: ast::DUMMY_NODE_ID,
3621 span: mk_sp(lo, self.last_span.hi),
3626 /// Parse a "let" stmt
3627 fn parse_let(&mut self) -> P<Decl> {
3628 let lo = self.span.lo;
3629 let local = self.parse_local();
3630 P(spanned(lo, self.last_span.hi, DeclLocal(local)))
3633 /// Parse a structure field
3634 fn parse_name_and_ty(&mut self, pr: Visibility,
3635 attrs: Vec<Attribute> ) -> StructField {
3636 let lo = self.span.lo;
3637 if !self.token.is_plain_ident() {
3638 self.fatal("expected ident");
3640 let name = self.parse_ident();
3641 self.expect(&token::Colon);
3642 let ty = self.parse_ty_sum();
3643 spanned(lo, self.last_span.hi, ast::StructField_ {
3644 kind: NamedField(name, pr),
3645 id: ast::DUMMY_NODE_ID,
3651 /// Get an expected item after attributes error message.
3652 fn expected_item_err(attrs: &[Attribute]) -> &'static str {
3653 match attrs.last() {
3654 Some(&Attribute { node: ast::Attribute_ { is_sugared_doc: true, .. }, .. }) => {
3655 "expected item after doc comment"
3657 _ => "expected item after attributes",
3661 /// Parse a statement. may include decl.
3662 /// Precondition: any attributes are parsed already
3663 pub fn parse_stmt(&mut self, item_attrs: Vec<Attribute>) -> P<Stmt> {
3664 maybe_whole!(self, NtStmt);
3666 fn check_expected_item(p: &mut Parser, attrs: &[Attribute]) {
3667 // If we have attributes then we should have an item
3668 if !attrs.is_empty() {
3669 let last_span = p.last_span;
3670 p.span_err(last_span, Parser::expected_item_err(attrs));
3674 let lo = self.span.lo;
3675 if self.check_keyword(keywords::Let) {
3676 check_expected_item(self, &item_attrs[]);
3677 self.expect_keyword(keywords::Let);
3678 let decl = self.parse_let();
3679 P(spanned(lo, decl.span.hi, StmtDecl(decl, ast::DUMMY_NODE_ID)))
3680 } else if self.token.is_ident()
3681 && !self.token.is_any_keyword()
3682 && self.look_ahead(1, |t| *t == token::Not) {
3683 // it's a macro invocation:
3685 check_expected_item(self, &item_attrs[]);
3687 // Potential trouble: if we allow macros with paths instead of
3688 // idents, we'd need to look ahead past the whole path here...
3689 let pth = self.parse_path(NoTypesAllowed);
3692 let id = match self.token {
3693 token::OpenDelim(_) => token::special_idents::invalid, // no special identifier
3694 _ => self.parse_ident(),
3697 // check that we're pointing at delimiters (need to check
3698 // again after the `if`, because of `parse_ident`
3699 // consuming more tokens).
3700 let delim = match self.token {
3701 token::OpenDelim(delim) => delim,
3703 // we only expect an ident if we didn't parse one
3705 let ident_str = if id.name == token::special_idents::invalid.name {
3710 let tok_str = self.this_token_to_string();
3711 self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
3717 let tts = self.parse_unspanned_seq(
3718 &token::OpenDelim(delim),
3719 &token::CloseDelim(delim),
3721 |p| p.parse_token_tree()
3723 let hi = self.span.hi;
3725 let style = if delim == token::Brace {
3728 MacStmtWithoutBraces
3731 if id.name == token::special_idents::invalid.name {
3734 StmtMac(P(spanned(lo,
3736 MacInvocTT(pth, tts, EMPTY_CTXT))),
3739 // if it has a special ident, it's definitely an item
3741 // Require a semicolon or braces.
3742 if style != MacStmtWithBraces {
3743 if !self.eat(&token::Semi) {
3744 let last_span = self.last_span;
3745 self.span_err(last_span,
3746 "macros that expand to items must \
3747 either be surrounded with braces or \
3748 followed by a semicolon");
3751 P(spanned(lo, hi, StmtDecl(
3752 P(spanned(lo, hi, DeclItem(
3754 lo, hi, id /*id is good here*/,
3755 ItemMac(spanned(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT))),
3756 Inherited, Vec::new(/*no attrs*/))))),
3757 ast::DUMMY_NODE_ID)))
3760 let found_attrs = !item_attrs.is_empty();
3761 let item_err = Parser::expected_item_err(&item_attrs[]);
3762 match self.parse_item_(item_attrs, false) {
3765 let decl = P(spanned(lo, hi, DeclItem(i)));
3766 P(spanned(lo, hi, StmtDecl(decl, ast::DUMMY_NODE_ID)))
3770 let last_span = self.last_span;
3771 self.span_err(last_span, item_err);
3774 // Remainder are line-expr stmts.
3775 let e = self.parse_expr_res(RESTRICTION_STMT_EXPR);
3776 P(spanned(lo, e.span.hi, StmtExpr(e, ast::DUMMY_NODE_ID)))
3782 /// Is this expression a successfully-parsed statement?
3783 fn expr_is_complete(&mut self, e: &Expr) -> bool {
3784 self.restrictions.contains(RESTRICTION_STMT_EXPR) &&
3785 !classify::expr_requires_semi_to_be_stmt(e)
3788 /// Parse a block. No inner attrs are allowed.
3789 pub fn parse_block(&mut self) -> P<Block> {
3790 maybe_whole!(no_clone self, NtBlock);
3792 let lo = self.span.lo;
3794 if !self.eat(&token::OpenDelim(token::Brace)) {
3796 let tok = self.this_token_to_string();
3797 self.span_fatal_help(sp,
3798 &format!("expected `{{`, found `{}`", tok)[],
3799 "place this code inside a block");
3802 return self.parse_block_tail_(lo, DefaultBlock, Vec::new());
3805 /// Parse a block. Inner attrs are allowed.
3806 fn parse_inner_attrs_and_block(&mut self)
3807 -> (Vec<Attribute> , P<Block>) {
3809 maybe_whole!(pair_empty self, NtBlock);
3811 let lo = self.span.lo;
3812 self.expect(&token::OpenDelim(token::Brace));
3813 let (inner, next) = self.parse_inner_attrs_and_next();
3815 (inner, self.parse_block_tail_(lo, DefaultBlock, next))
3818 /// Precondition: already parsed the '{'.
3819 fn parse_block_tail(&mut self, lo: BytePos, s: BlockCheckMode) -> P<Block> {
3820 self.parse_block_tail_(lo, s, Vec::new())
3823 /// Parse the rest of a block expression or function body
3824 fn parse_block_tail_(&mut self, lo: BytePos, s: BlockCheckMode,
3825 first_item_attrs: Vec<Attribute>) -> P<Block> {
3826 let mut stmts = vec![];
3827 let mut expr = None;
3828 let mut attributes_box = first_item_attrs;
3830 while self.token != token::CloseDelim(token::Brace) {
3831 // parsing items even when they're not allowed lets us give
3832 // better error messages and recover more gracefully.
3833 attributes_box.push_all(&self.parse_outer_attributes()[]);
3836 if !attributes_box.is_empty() {
3837 let last_span = self.last_span;
3838 self.span_err(last_span,
3839 Parser::expected_item_err(&attributes_box[]));
3840 attributes_box = Vec::new();
3842 self.bump(); // empty
3844 token::CloseDelim(token::Brace) => {
3845 // fall through and out.
3848 let stmt = self.parse_stmt(attributes_box);
3849 attributes_box = Vec::new();
3850 stmt.and_then(|Spanned {node, span}| match node {
3851 StmtExpr(e, stmt_id) => {
3852 self.handle_expression_like_statement(e,
3858 StmtMac(mac, MacStmtWithoutBraces) => {
3859 // statement macro without braces; might be an
3860 // expr depending on whether a semicolon follows
3863 stmts.push(P(Spanned {
3865 MacStmtWithSemicolon),
3871 let e = self.mk_mac_expr(span.lo,
3873 mac.and_then(|m| m.node));
3874 let e = self.parse_dot_or_call_expr_with(e);
3875 let e = self.parse_more_binops(e, 0);
3876 let e = self.parse_assign_expr_with(e);
3877 self.handle_expression_like_statement(
3886 StmtMac(m, style) => {
3887 // statement macro; might be an expr
3890 stmts.push(P(Spanned {
3892 MacStmtWithSemicolon),
3897 token::CloseDelim(token::Brace) => {
3898 // if a block ends in `m!(arg)` without
3899 // a `;`, it must be an expr
3901 self.mk_mac_expr(span.lo,
3903 m.and_then(|x| x.node)));
3906 stmts.push(P(Spanned {
3907 node: StmtMac(m, style),
3913 _ => { // all other kinds of statements:
3914 if classify::stmt_ends_with_semi(&node) {
3915 self.commit_stmt_expecting(token::Semi);
3918 stmts.push(P(Spanned {
3928 if !attributes_box.is_empty() {
3929 let last_span = self.last_span;
3930 self.span_err(last_span,
3931 Parser::expected_item_err(&attributes_box[]));
3934 let hi = self.span.hi;
3939 id: ast::DUMMY_NODE_ID,
3941 span: mk_sp(lo, hi),
3945 fn handle_expression_like_statement(
3950 stmts: &mut Vec<P<Stmt>>,
3951 last_block_expr: &mut Option<P<Expr>>) {
3952 // expression without semicolon
3953 if classify::expr_requires_semi_to_be_stmt(&*e) {
3954 // Just check for errors and recover; do not eat semicolon yet.
3955 self.commit_stmt(&[],
3956 &[token::Semi, token::CloseDelim(token::Brace)]);
3962 let span_with_semi = Span {
3964 hi: self.last_span.hi,
3965 expn_id: span.expn_id,
3967 stmts.push(P(Spanned {
3968 node: StmtSemi(e, stmt_id),
3969 span: span_with_semi,
3972 token::CloseDelim(token::Brace) => *last_block_expr = Some(e),
3974 stmts.push(P(Spanned {
3975 node: StmtExpr(e, stmt_id),
3982 // Parses a sequence of bounds if a `:` is found,
3983 // otherwise returns empty list.
3984 fn parse_colon_then_ty_param_bounds(&mut self,
3985 mode: BoundParsingMode)
3986 -> OwnedSlice<TyParamBound>
3988 if !self.eat(&token::Colon) {
3991 self.parse_ty_param_bounds(mode)
3995 // matches bounds = ( boundseq )?
3996 // where boundseq = ( polybound + boundseq ) | polybound
3997 // and polybound = ( 'for' '<' 'region '>' )? bound
3998 // and bound = 'region | trait_ref
3999 fn parse_ty_param_bounds(&mut self,
4000 mode: BoundParsingMode)
4001 -> OwnedSlice<TyParamBound>
4003 let mut result = vec!();
4005 let question_span = self.span;
4006 let ate_question = self.eat(&token::Question);
4008 token::Lifetime(lifetime) => {
4010 self.span_err(question_span,
4011 "`?` may only modify trait bounds, not lifetime bounds");
4013 result.push(RegionTyParamBound(ast::Lifetime {
4014 id: ast::DUMMY_NODE_ID,
4020 token::ModSep | token::Ident(..) => {
4021 let poly_trait_ref = self.parse_poly_trait_ref();
4022 let modifier = if ate_question {
4023 if mode == BoundParsingMode::Modified {
4024 TraitBoundModifier::Maybe
4026 self.span_err(question_span,
4028 TraitBoundModifier::None
4031 TraitBoundModifier::None
4033 result.push(TraitTyParamBound(poly_trait_ref, modifier))
4038 if !self.eat(&token::BinOp(token::Plus)) {
4043 return OwnedSlice::from_vec(result);
4046 fn trait_ref_from_ident(ident: Ident, span: Span) -> TraitRef {
4047 let segment = ast::PathSegment {
4049 parameters: ast::PathParameters::none()
4051 let path = ast::Path {
4054 segments: vec![segment],
4058 ref_id: ast::DUMMY_NODE_ID,
4062 /// Matches typaram = (unbound `?`)? IDENT (`?` unbound)? optbounds ( EQ ty )?
4063 fn parse_ty_param(&mut self) -> TyParam {
4064 // This is a bit hacky. Currently we are only interested in a single
4065 // unbound, and it may only be `Sized`. To avoid backtracking and other
4066 // complications, we parse an ident, then check for `?`. If we find it,
4067 // we use the ident as the unbound, otherwise, we use it as the name of
4068 // type param. Even worse, we need to check for `?` before or after the
4070 let mut span = self.span;
4071 let mut ident = self.parse_ident();
4072 let mut unbound = None;
4073 if self.eat(&token::Question) {
4074 let tref = Parser::trait_ref_from_ident(ident, span);
4075 unbound = Some(tref);
4077 ident = self.parse_ident();
4078 self.obsolete(span, ObsoleteSyntax::Sized);
4081 let mut bounds = self.parse_colon_then_ty_param_bounds(BoundParsingMode::Modified);
4082 if let Some(unbound) = unbound {
4083 let mut bounds_as_vec = bounds.into_vec();
4084 bounds_as_vec.push(TraitTyParamBound(PolyTraitRef { bound_lifetimes: vec![],
4087 TraitBoundModifier::Maybe));
4088 bounds = OwnedSlice::from_vec(bounds_as_vec);
4091 let default = if self.check(&token::Eq) {
4093 Some(self.parse_ty_sum())
4099 id: ast::DUMMY_NODE_ID,
4106 /// Parse a set of optional generic type parameter declarations. Where
4107 /// clauses are not parsed here, and must be added later via
4108 /// `parse_where_clause()`.
4110 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
4111 /// | ( < lifetimes , typaramseq ( , )? > )
4112 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
4113 pub fn parse_generics(&mut self) -> ast::Generics {
4114 if self.eat(&token::Lt) {
4115 let lifetime_defs = self.parse_lifetime_defs();
4116 let mut seen_default = false;
4117 let ty_params = self.parse_seq_to_gt(Some(token::Comma), |p| {
4118 p.forbid_lifetime();
4119 let ty_param = p.parse_ty_param();
4120 if ty_param.default.is_some() {
4121 seen_default = true;
4122 } else if seen_default {
4123 let last_span = p.last_span;
4124 p.span_err(last_span,
4125 "type parameters with a default must be trailing");
4130 lifetimes: lifetime_defs,
4131 ty_params: ty_params,
4132 where_clause: WhereClause {
4133 id: ast::DUMMY_NODE_ID,
4134 predicates: Vec::new(),
4138 ast_util::empty_generics()
4142 fn parse_generic_values_after_lt(&mut self)
4143 -> (Vec<ast::Lifetime>, Vec<P<Ty>>, Vec<P<TypeBinding>>) {
4144 let lifetimes = self.parse_lifetimes(token::Comma);
4146 // First parse types.
4147 let (types, returned) = self.parse_seq_to_gt_or_return(
4150 p.forbid_lifetime();
4151 if p.look_ahead(1, |t| t == &token::Eq) {
4154 Some(p.parse_ty_sum())
4159 // If we found the `>`, don't continue.
4161 return (lifetimes, types.into_vec(), Vec::new());
4164 // Then parse type bindings.
4165 let bindings = self.parse_seq_to_gt(
4168 p.forbid_lifetime();
4170 let ident = p.parse_ident();
4171 let found_eq = p.eat(&token::Eq);
4174 p.span_warn(span, "whoops, no =?");
4176 let ty = p.parse_ty();
4178 let span = mk_sp(lo, hi);
4179 return P(TypeBinding{id: ast::DUMMY_NODE_ID,
4186 (lifetimes, types.into_vec(), bindings.into_vec())
4189 fn forbid_lifetime(&mut self) {
4190 if self.token.is_lifetime() {
4191 let span = self.span;
4192 self.span_fatal(span, "lifetime parameters must be declared \
4193 prior to type parameters");
4197 /// Parses an optional `where` clause and places it in `generics`.
4200 /// where T : Trait<U, V> + 'b, 'a : 'b
4202 fn parse_where_clause(&mut self, generics: &mut ast::Generics) {
4203 if !self.eat_keyword(keywords::Where) {
4207 let mut parsed_something = false;
4209 let lo = self.span.lo;
4211 token::OpenDelim(token::Brace) => {
4215 token::Lifetime(..) => {
4216 let bounded_lifetime =
4217 self.parse_lifetime();
4219 self.eat(&token::Colon);
4222 self.parse_lifetimes(token::BinOp(token::Plus));
4224 let hi = self.span.hi;
4225 let span = mk_sp(lo, hi);
4227 generics.where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
4228 ast::WhereRegionPredicate {
4230 lifetime: bounded_lifetime,
4235 parsed_something = true;
4239 let bound_lifetimes = if self.eat_keyword(keywords::For) {
4240 // Higher ranked constraint.
4241 self.expect(&token::Lt);
4242 let lifetime_defs = self.parse_lifetime_defs();
4249 let bounded_ty = self.parse_ty();
4251 if self.eat(&token::Colon) {
4252 let bounds = self.parse_ty_param_bounds(BoundParsingMode::Bare);
4253 let hi = self.span.hi;
4254 let span = mk_sp(lo, hi);
4256 if bounds.len() == 0 {
4258 "each predicate in a `where` clause must have \
4259 at least one bound in it");
4262 generics.where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
4263 ast::WhereBoundPredicate {
4265 bound_lifetimes: bound_lifetimes,
4266 bounded_ty: bounded_ty,
4270 parsed_something = true;
4271 } else if self.eat(&token::Eq) {
4272 // let ty = self.parse_ty();
4273 let hi = self.span.hi;
4274 let span = mk_sp(lo, hi);
4275 // generics.where_clause.predicates.push(
4276 // ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
4277 // id: ast::DUMMY_NODE_ID,
4279 // path: panic!("NYI"), //bounded_ty,
4282 // parsed_something = true;
4285 "equality constraints are not yet supported \
4286 in where clauses (#20041)");
4288 let last_span = self.last_span;
4289 self.span_err(last_span,
4290 "unexpected token in `where` clause");
4295 if !self.eat(&token::Comma) {
4300 if !parsed_something {
4301 let last_span = self.last_span;
4302 self.span_err(last_span,
4303 "a `where` clause must have at least one predicate \
4308 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
4309 -> (Vec<Arg> , bool) {
4311 let mut args: Vec<Option<Arg>> =
4312 self.parse_unspanned_seq(
4313 &token::OpenDelim(token::Paren),
4314 &token::CloseDelim(token::Paren),
4315 seq_sep_trailing_allowed(token::Comma),
4317 if p.token == token::DotDotDot {
4320 if p.token != token::CloseDelim(token::Paren) {
4323 "`...` must be last in argument list for variadic function");
4328 "only foreign functions are allowed to be variadic");
4332 Some(p.parse_arg_general(named_args))
4337 let variadic = match args.pop() {
4340 // Need to put back that last arg
4347 if variadic && args.is_empty() {
4349 "variadic function must be declared with at least one named argument");
4352 let args = args.into_iter().map(|x| x.unwrap()).collect();
4357 /// Parse the argument list and result type of a function declaration
4358 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> P<FnDecl> {
4360 let (args, variadic) = self.parse_fn_args(true, allow_variadic);
4361 let ret_ty = self.parse_ret_ty();
4370 fn is_self_ident(&mut self) -> bool {
4372 token::Ident(id, token::Plain) => id.name == special_idents::self_.name,
4377 fn expect_self_ident(&mut self) -> ast::Ident {
4379 token::Ident(id, token::Plain) if id.name == special_idents::self_.name => {
4384 let token_str = self.this_token_to_string();
4385 self.fatal(&format!("expected `self`, found `{}`",
4391 fn is_self_type_ident(&mut self) -> bool {
4393 token::Ident(id, token::Plain) => id.name == special_idents::type_self.name,
4398 fn expect_self_type_ident(&mut self) -> ast::Ident {
4400 token::Ident(id, token::Plain) if id.name == special_idents::type_self.name => {
4405 let token_str = self.this_token_to_string();
4406 self.fatal(&format!("expected `Self`, found `{}`",
4412 /// Parse the argument list and result type of a function
4413 /// that may have a self type.
4414 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> (ExplicitSelf, P<FnDecl>) where
4415 F: FnMut(&mut Parser) -> Arg,
4417 fn maybe_parse_borrowed_explicit_self(this: &mut Parser)
4418 -> ast::ExplicitSelf_ {
4419 // The following things are possible to see here:
4424 // fn(&'lt mut self)
4426 // We already know that the current token is `&`.
4428 if this.look_ahead(1, |t| t.is_keyword(keywords::SelfValue)) {
4430 SelfRegion(None, MutImmutable, this.expect_self_ident())
4431 } else if this.look_ahead(1, |t| t.is_mutability()) &&
4432 this.look_ahead(2, |t| t.is_keyword(keywords::SelfValue)) {
4434 let mutability = this.parse_mutability();
4435 SelfRegion(None, mutability, this.expect_self_ident())
4436 } else if this.look_ahead(1, |t| t.is_lifetime()) &&
4437 this.look_ahead(2, |t| t.is_keyword(keywords::SelfValue)) {
4439 let lifetime = this.parse_lifetime();
4440 SelfRegion(Some(lifetime), MutImmutable, this.expect_self_ident())
4441 } else if this.look_ahead(1, |t| t.is_lifetime()) &&
4442 this.look_ahead(2, |t| t.is_mutability()) &&
4443 this.look_ahead(3, |t| t.is_keyword(keywords::SelfValue)) {
4445 let lifetime = this.parse_lifetime();
4446 let mutability = this.parse_mutability();
4447 SelfRegion(Some(lifetime), mutability, this.expect_self_ident())
4453 self.expect(&token::OpenDelim(token::Paren));
4455 // A bit of complexity and lookahead is needed here in order to be
4456 // backwards compatible.
4457 let lo = self.span.lo;
4458 let mut self_ident_lo = self.span.lo;
4459 let mut self_ident_hi = self.span.hi;
4461 let mut mutbl_self = MutImmutable;
4462 let explicit_self = match self.token {
4463 token::BinOp(token::And) => {
4464 let eself = maybe_parse_borrowed_explicit_self(self);
4465 self_ident_lo = self.last_span.lo;
4466 self_ident_hi = self.last_span.hi;
4469 token::BinOp(token::Star) => {
4470 // Possibly "*self" or "*mut self" -- not supported. Try to avoid
4471 // emitting cryptic "unexpected token" errors.
4473 let _mutability = if self.token.is_mutability() {
4474 self.parse_mutability()
4478 if self.is_self_ident() {
4479 let span = self.span;
4480 self.span_err(span, "cannot pass self by unsafe pointer");
4483 // error case, making bogus self ident:
4484 SelfValue(special_idents::self_)
4486 token::Ident(..) => {
4487 if self.is_self_ident() {
4488 let self_ident = self.expect_self_ident();
4490 // Determine whether this is the fully explicit form, `self:
4492 if self.eat(&token::Colon) {
4493 SelfExplicit(self.parse_ty_sum(), self_ident)
4495 SelfValue(self_ident)
4497 } else if self.token.is_mutability() &&
4498 self.look_ahead(1, |t| t.is_keyword(keywords::SelfValue)) {
4499 mutbl_self = self.parse_mutability();
4500 let self_ident = self.expect_self_ident();
4502 // Determine whether this is the fully explicit form,
4504 if self.eat(&token::Colon) {
4505 SelfExplicit(self.parse_ty_sum(), self_ident)
4507 SelfValue(self_ident)
4516 let explicit_self_sp = mk_sp(self_ident_lo, self_ident_hi);
4518 // shared fall-through for the three cases below. borrowing prevents simply
4519 // writing this as a closure
4520 macro_rules! parse_remaining_arguments {
4523 // If we parsed a self type, expect a comma before the argument list.
4527 let sep = seq_sep_trailing_allowed(token::Comma);
4528 let mut fn_inputs = self.parse_seq_to_before_end(
4529 &token::CloseDelim(token::Paren),
4533 fn_inputs.insert(0, Arg::new_self(explicit_self_sp, mutbl_self, $self_id));
4536 token::CloseDelim(token::Paren) => {
4537 vec!(Arg::new_self(explicit_self_sp, mutbl_self, $self_id))
4540 let token_str = self.this_token_to_string();
4541 self.fatal(&format!("expected `,` or `)`, found `{}`",
4548 let fn_inputs = match explicit_self {
4550 let sep = seq_sep_trailing_allowed(token::Comma);
4551 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)
4553 SelfValue(id) => parse_remaining_arguments!(id),
4554 SelfRegion(_,_,id) => parse_remaining_arguments!(id),
4555 SelfExplicit(_,id) => parse_remaining_arguments!(id),
4559 self.expect(&token::CloseDelim(token::Paren));
4561 let hi = self.span.hi;
4563 let ret_ty = self.parse_ret_ty();
4565 let fn_decl = P(FnDecl {
4571 (spanned(lo, hi, explicit_self), fn_decl)
4574 // parse the |arg, arg| header on a lambda
4575 fn parse_fn_block_decl(&mut self) -> P<FnDecl> {
4576 let inputs_captures = {
4577 if self.eat(&token::OrOr) {
4580 self.expect(&token::BinOp(token::Or));
4581 self.parse_obsolete_closure_kind();
4582 let args = self.parse_seq_to_before_end(
4583 &token::BinOp(token::Or),
4584 seq_sep_trailing_allowed(token::Comma),
4585 |p| p.parse_fn_block_arg()
4591 let output = self.parse_ret_ty();
4594 inputs: inputs_captures,
4600 /// Parses the `(arg, arg) -> return_type` header on a procedure.
4601 fn parse_proc_decl(&mut self) -> P<FnDecl> {
4603 self.parse_unspanned_seq(&token::OpenDelim(token::Paren),
4604 &token::CloseDelim(token::Paren),
4605 seq_sep_trailing_allowed(token::Comma),
4606 |p| p.parse_fn_block_arg());
4608 let output = self.parse_ret_ty();
4617 /// Parse the name and optional generic types of a function header.
4618 fn parse_fn_header(&mut self) -> (Ident, ast::Generics) {
4619 let id = self.parse_ident();
4620 let generics = self.parse_generics();
4624 fn mk_item(&mut self, lo: BytePos, hi: BytePos, ident: Ident,
4625 node: Item_, vis: Visibility,
4626 attrs: Vec<Attribute>) -> P<Item> {
4630 id: ast::DUMMY_NODE_ID,
4637 /// Parse an item-position function declaration.
4638 fn parse_item_fn(&mut self, unsafety: Unsafety, abi: abi::Abi) -> ItemInfo {
4639 let (ident, mut generics) = self.parse_fn_header();
4640 let decl = self.parse_fn_decl(false);
4641 self.parse_where_clause(&mut generics);
4642 let (inner_attrs, body) = self.parse_inner_attrs_and_block();
4643 (ident, ItemFn(decl, unsafety, abi, generics, body), Some(inner_attrs))
4646 /// Parse a method in a trait impl
4647 pub fn parse_method_with_outer_attributes(&mut self) -> P<Method> {
4648 let attrs = self.parse_outer_attributes();
4649 let visa = self.parse_visibility();
4650 self.parse_method(attrs, visa)
4653 fn complain_if_pub_macro(&mut self, visa: Visibility, span: Span) {
4656 self.span_err(span, "can't qualify macro invocation with `pub`");
4657 self.span_help(span, "try adjusting the macro to put `pub` inside \
4664 /// Parse a method in a trait impl, starting with `attrs` attributes.
4665 pub fn parse_method(&mut self,
4666 attrs: Vec<Attribute>,
4669 let lo = self.span.lo;
4671 // code copied from parse_macro_use_or_failure... abstraction!
4672 let (method_, hi, new_attrs) = {
4673 if !self.token.is_any_keyword()
4674 && self.look_ahead(1, |t| *t == token::Not)
4675 && (self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren))
4676 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) {
4679 let last_span = self.last_span;
4680 self.complain_if_pub_macro(visa, last_span);
4682 let pth = self.parse_path(NoTypesAllowed);
4683 self.expect(&token::Not);
4685 // eat a matched-delimiter token tree:
4686 let delim = self.expect_open_delim();
4687 let tts = self.parse_seq_to_end(&token::CloseDelim(delim),
4689 |p| p.parse_token_tree());
4690 let m_ = ast::MacInvocTT(pth, tts, EMPTY_CTXT);
4691 let m: ast::Mac = codemap::Spanned { node: m_,
4692 span: mk_sp(self.span.lo,
4694 if delim != token::Brace {
4695 self.expect(&token::Semi)
4697 (ast::MethMac(m), self.span.hi, attrs)
4699 let unsafety = self.parse_unsafety();
4700 let abi = if self.eat_keyword(keywords::Extern) {
4701 self.parse_opt_abi().unwrap_or(abi::C)
4705 self.expect_keyword(keywords::Fn);
4706 let ident = self.parse_ident();
4707 let mut generics = self.parse_generics();
4708 let (explicit_self, decl) = self.parse_fn_decl_with_self(|p| {
4711 self.parse_where_clause(&mut generics);
4712 let (inner_attrs, body) = self.parse_inner_attrs_and_block();
4713 let body_span = body.span;
4714 let mut new_attrs = attrs;
4715 new_attrs.push_all(&inner_attrs[]);
4716 (ast::MethDecl(ident,
4724 body_span.hi, new_attrs)
4729 id: ast::DUMMY_NODE_ID,
4730 span: mk_sp(lo, hi),
4735 /// Parse trait Foo { ... }
4736 fn parse_item_trait(&mut self, unsafety: Unsafety) -> ItemInfo {
4738 let ident = self.parse_ident();
4739 let mut tps = self.parse_generics();
4740 // This is not very accurate, but since unbound only exists to catch
4741 // obsolete syntax, the span is unlikely to ever be used.
4742 let unbound_span = self.span;
4743 let unbound = self.parse_for_sized();
4745 // Parse supertrait bounds.
4746 let mut bounds = self.parse_colon_then_ty_param_bounds(BoundParsingMode::Bare);
4748 if let Some(unbound) = unbound {
4749 let mut bounds_as_vec = bounds.into_vec();
4750 bounds_as_vec.push(TraitTyParamBound(PolyTraitRef { bound_lifetimes: vec![],
4752 span: unbound_span },
4753 TraitBoundModifier::Maybe));
4754 bounds = OwnedSlice::from_vec(bounds_as_vec);
4757 self.parse_where_clause(&mut tps);
4759 let meths = self.parse_trait_items();
4760 (ident, ItemTrait(unsafety, tps, bounds, meths), None)
4763 fn parse_impl_items(&mut self) -> (Vec<ImplItem>, Vec<Attribute>) {
4764 let mut impl_items = Vec::new();
4765 self.expect(&token::OpenDelim(token::Brace));
4766 let (inner_attrs, mut method_attrs) =
4767 self.parse_inner_attrs_and_next();
4769 method_attrs.extend(self.parse_outer_attributes().into_iter());
4770 if method_attrs.is_empty() && self.eat(&token::CloseDelim(token::Brace)) {
4774 let vis = self.parse_visibility();
4775 if self.eat_keyword(keywords::Type) {
4776 impl_items.push(TypeImplItem(P(self.parse_typedef(
4780 impl_items.push(MethodImplItem(self.parse_method(
4784 method_attrs = vec![];
4786 (impl_items, inner_attrs)
4789 /// Parses two variants (with the region/type params always optional):
4790 /// impl<T> Foo { ... }
4791 /// impl<T> ToString for ~[T] { ... }
4792 fn parse_item_impl(&mut self, unsafety: ast::Unsafety) -> ItemInfo {
4793 // First, parse type parameters if necessary.
4794 let mut generics = self.parse_generics();
4796 // Special case: if the next identifier that follows is '(', don't
4797 // allow this to be parsed as a trait.
4798 let could_be_trait = self.token != token::OpenDelim(token::Paren);
4800 let neg_span = self.span;
4801 let polarity = if self.eat(&token::Not) {
4802 ast::ImplPolarity::Negative
4804 ast::ImplPolarity::Positive
4808 let mut ty = self.parse_ty_sum();
4810 // Parse traits, if necessary.
4811 let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) {
4812 // New-style trait. Reinterpret the type as a trait.
4813 let opt_trait_ref = match ty.node {
4814 TyPath(ref path, node_id) => {
4816 path: (*path).clone(),
4821 self.span_err(ty.span, "not a trait");
4826 ty = self.parse_ty_sum();
4830 ast::ImplPolarity::Negative => {
4831 // This is a negated type implementation
4832 // `impl !MyType {}`, which is not allowed.
4833 self.span_err(neg_span, "inherent implementation can't be negated");
4840 self.parse_where_clause(&mut generics);
4841 let (impl_items, attrs) = self.parse_impl_items();
4843 let ident = ast_util::impl_pretty_name(&opt_trait, &*ty);
4846 ItemImpl(unsafety, polarity, generics, opt_trait, ty, impl_items),
4850 /// Parse a::B<String,i32>
4851 fn parse_trait_ref(&mut self) -> TraitRef {
4853 path: self.parse_path(LifetimeAndTypesWithoutColons),
4854 ref_id: ast::DUMMY_NODE_ID,
4858 fn parse_late_bound_lifetime_defs(&mut self) -> Vec<ast::LifetimeDef> {
4859 if self.eat_keyword(keywords::For) {
4860 self.expect(&token::Lt);
4861 let lifetime_defs = self.parse_lifetime_defs();
4869 /// Parse for<'l> a::B<String,i32>
4870 fn parse_poly_trait_ref(&mut self) -> PolyTraitRef {
4871 let lo = self.span.lo;
4872 let lifetime_defs = self.parse_late_bound_lifetime_defs();
4875 bound_lifetimes: lifetime_defs,
4876 trait_ref: self.parse_trait_ref(),
4877 span: mk_sp(lo, self.last_span.hi),
4881 /// Parse struct Foo { ... }
4882 fn parse_item_struct(&mut self) -> ItemInfo {
4883 let class_name = self.parse_ident();
4884 let mut generics = self.parse_generics();
4886 if self.eat(&token::Colon) {
4887 let ty = self.parse_ty_sum();
4888 self.span_err(ty.span, "`virtual` structs have been removed from the language");
4891 // There is a special case worth noting here, as reported in issue #17904.
4892 // If we are parsing a tuple struct it is the case that the where clause
4893 // should follow the field list. Like so:
4895 // struct Foo<T>(T) where T: Copy;
4897 // If we are parsing a normal record-style struct it is the case
4898 // that the where clause comes before the body, and after the generics.
4899 // So if we look ahead and see a brace or a where-clause we begin
4900 // parsing a record style struct.
4902 // Otherwise if we look ahead and see a paren we parse a tuple-style
4905 let (fields, ctor_id) = if self.token.is_keyword(keywords::Where) {
4906 self.parse_where_clause(&mut generics);
4907 if self.eat(&token::Semi) {
4908 // If we see a: `struct Foo<T> where T: Copy;` style decl.
4909 (Vec::new(), Some(ast::DUMMY_NODE_ID))
4911 // If we see: `struct Foo<T> where T: Copy { ... }`
4912 (self.parse_record_struct_body(&class_name), None)
4914 // No `where` so: `struct Foo<T>;`
4915 } else if self.eat(&token::Semi) {
4916 (Vec::new(), Some(ast::DUMMY_NODE_ID))
4917 // Record-style struct definition
4918 } else if self.token == token::OpenDelim(token::Brace) {
4919 let fields = self.parse_record_struct_body(&class_name);
4921 // Tuple-style struct definition with optional where-clause.
4923 let fields = self.parse_tuple_struct_body(&class_name, &mut generics);
4924 (fields, Some(ast::DUMMY_NODE_ID))
4928 ItemStruct(P(ast::StructDef {
4935 pub fn parse_record_struct_body(&mut self, class_name: &ast::Ident) -> Vec<StructField> {
4936 let mut fields = Vec::new();
4937 if self.eat(&token::OpenDelim(token::Brace)) {
4938 while self.token != token::CloseDelim(token::Brace) {
4939 fields.push(self.parse_struct_decl_field(true));
4942 if fields.len() == 0 {
4943 self.fatal(&format!("unit-like struct definition should be \
4944 written as `struct {};`",
4945 token::get_ident(class_name.clone()))[]);
4950 let token_str = self.this_token_to_string();
4951 self.fatal(&format!("expected `where`, or `{}` after struct \
4952 name, found `{}`", "{",
4959 pub fn parse_tuple_struct_body(&mut self,
4960 class_name: &ast::Ident,
4961 generics: &mut ast::Generics)
4962 -> Vec<StructField> {
4963 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
4964 if self.check(&token::OpenDelim(token::Paren)) {
4965 let fields = self.parse_unspanned_seq(
4966 &token::OpenDelim(token::Paren),
4967 &token::CloseDelim(token::Paren),
4968 seq_sep_trailing_allowed(token::Comma),
4970 let attrs = p.parse_outer_attributes();
4972 let struct_field_ = ast::StructField_ {
4973 kind: UnnamedField(p.parse_visibility()),
4974 id: ast::DUMMY_NODE_ID,
4975 ty: p.parse_ty_sum(),
4978 spanned(lo, p.span.hi, struct_field_)
4981 if fields.len() == 0 {
4982 self.fatal(&format!("unit-like struct definition should be \
4983 written as `struct {};`",
4984 token::get_ident(class_name.clone()))[]);
4987 self.parse_where_clause(generics);
4988 self.expect(&token::Semi);
4990 // This is the case where we just see struct Foo<T> where T: Copy;
4991 } else if self.token.is_keyword(keywords::Where) {
4992 self.parse_where_clause(generics);
4993 self.expect(&token::Semi);
4995 // This case is where we see: `struct Foo<T>;`
4997 let token_str = self.this_token_to_string();
4998 self.fatal(&format!("expected `where`, `{}`, `(`, or `;` after struct \
4999 name, found `{}`", "{", token_str)[]);
5003 /// Parse a structure field declaration
5004 pub fn parse_single_struct_field(&mut self,
5006 attrs: Vec<Attribute> )
5008 let a_var = self.parse_name_and_ty(vis, attrs);
5013 token::CloseDelim(token::Brace) => {}
5015 let span = self.span;
5016 let token_str = self.this_token_to_string();
5017 self.span_fatal_help(span,
5018 &format!("expected `,`, or `}}`, found `{}`",
5020 "struct fields should be separated by commas")
5026 /// Parse an element of a struct definition
5027 fn parse_struct_decl_field(&mut self, allow_pub: bool) -> StructField {
5029 let attrs = self.parse_outer_attributes();
5031 if self.eat_keyword(keywords::Pub) {
5033 let span = self.last_span;
5034 self.span_err(span, "`pub` is not allowed here");
5036 return self.parse_single_struct_field(Public, attrs);
5039 return self.parse_single_struct_field(Inherited, attrs);
5042 /// Parse visibility: PUB, PRIV, or nothing
5043 fn parse_visibility(&mut self) -> Visibility {
5044 if self.eat_keyword(keywords::Pub) { Public }
5048 fn parse_for_sized(&mut self) -> Option<ast::TraitRef> {
5049 // FIXME, this should really use TraitBoundModifier, but it will get
5050 // re-jigged shortly in any case, so leaving the hacky version for now.
5051 if self.eat_keyword(keywords::For) {
5052 let span = self.span;
5054 let mut ate_question = false;
5055 if self.eat(&token::Question) {
5056 ate_question = true;
5058 let ident = self.parse_ident();
5059 if self.eat(&token::Question) {
5064 ate_question = true;
5068 "expected `?Sized` after `for` in trait item");
5071 let _tref = Parser::trait_ref_from_ident(ident, span);
5073 self.obsolete(span, ObsoleteSyntax::ForSized);
5081 /// Given a termination token and a vector of already-parsed
5082 /// attributes (of length 0 or 1), parse all of the items in a module
5083 fn parse_mod_items(&mut self,
5085 first_item_attrs: Vec<Attribute>,
5088 // Parse all of the items up to closing or an attribute.
5090 let mut attrs = first_item_attrs;
5091 attrs.push_all(&self.parse_outer_attributes()[]);
5092 let mut items = vec![];
5095 match self.parse_item_(attrs, true) {
5096 Err(returned_attrs) => {
5097 attrs = returned_attrs;
5101 attrs = self.parse_outer_attributes();
5107 // don't think this other loop is even necessary....
5109 while self.token != term {
5110 let mut attrs = mem::replace(&mut attrs, vec![]);
5111 attrs.push_all(&self.parse_outer_attributes()[]);
5112 debug!("parse_mod_items: parse_item_(attrs={:?})", attrs);
5113 match self.parse_item_(attrs, true /* macros allowed */) {
5114 Ok(item) => items.push(item),
5116 let token_str = self.this_token_to_string();
5117 self.fatal(&format!("expected item, found `{}`",
5123 if !attrs.is_empty() {
5124 // We parsed attributes for the first item but didn't find it
5125 let last_span = self.last_span;
5126 self.span_err(last_span,
5127 Parser::expected_item_err(&attrs[]));
5131 inner: mk_sp(inner_lo, self.span.lo),
5136 fn parse_item_const(&mut self, m: Option<Mutability>) -> ItemInfo {
5137 let id = self.parse_ident();
5138 self.expect(&token::Colon);
5139 let ty = self.parse_ty_sum();
5140 self.expect(&token::Eq);
5141 let e = self.parse_expr();
5142 self.commit_expr_expecting(&*e, token::Semi);
5143 let item = match m {
5144 Some(m) => ItemStatic(ty, m, e),
5145 None => ItemConst(ty, e),
5150 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
5151 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> ItemInfo {
5152 let id_span = self.span;
5153 let id = self.parse_ident();
5154 if self.check(&token::Semi) {
5156 // This mod is in an external file. Let's go get it!
5157 let (m, attrs) = self.eval_src_mod(id, outer_attrs, id_span);
5158 (id, m, Some(attrs))
5160 self.push_mod_path(id, outer_attrs);
5161 self.expect(&token::OpenDelim(token::Brace));
5162 let mod_inner_lo = self.span.lo;
5163 let old_owns_directory = self.owns_directory;
5164 self.owns_directory = true;
5165 let (inner, next) = self.parse_inner_attrs_and_next();
5166 let m = self.parse_mod_items(token::CloseDelim(token::Brace), next, mod_inner_lo);
5167 self.expect(&token::CloseDelim(token::Brace));
5168 self.owns_directory = old_owns_directory;
5169 self.pop_mod_path();
5170 (id, ItemMod(m), Some(inner))
5174 fn push_mod_path(&mut self, id: Ident, attrs: &[Attribute]) {
5175 let default_path = self.id_to_interned_str(id);
5176 let file_path = match ::attr::first_attr_value_str_by_name(attrs,
5179 None => default_path,
5181 self.mod_path_stack.push(file_path)
5184 fn pop_mod_path(&mut self) {
5185 self.mod_path_stack.pop().unwrap();
5188 /// Read a module from a source file.
5189 fn eval_src_mod(&mut self,
5191 outer_attrs: &[ast::Attribute],
5193 -> (ast::Item_, Vec<ast::Attribute> ) {
5194 let mut prefix = Path::new(self.sess.span_diagnostic.cm.span_to_filename(self.span));
5196 let mod_path = Path::new(".").join_many(&self.mod_path_stack[]);
5197 let dir_path = prefix.join(&mod_path);
5198 let mod_string = token::get_ident(id);
5199 let (file_path, owns_directory) = match ::attr::first_attr_value_str_by_name(
5200 outer_attrs, "path") {
5201 Some(d) => (dir_path.join(d), true),
5203 let mod_name = mod_string.to_string();
5204 let default_path_str = format!("{}.rs", mod_name);
5205 let secondary_path_str = format!("{}/mod.rs", mod_name);
5206 let default_path = dir_path.join(&default_path_str[]);
5207 let secondary_path = dir_path.join(&secondary_path_str[]);
5208 let default_exists = default_path.exists();
5209 let secondary_exists = secondary_path.exists();
5211 if !self.owns_directory {
5212 self.span_err(id_sp,
5213 "cannot declare a new module at this location");
5214 let this_module = match self.mod_path_stack.last() {
5215 Some(name) => name.to_string(),
5216 None => self.root_module_name.as_ref().unwrap().clone(),
5218 self.span_note(id_sp,
5219 &format!("maybe move this module `{0}` \
5220 to its own directory via \
5223 if default_exists || secondary_exists {
5224 self.span_note(id_sp,
5225 &format!("... or maybe `use` the module \
5226 `{}` instead of possibly \
5230 self.abort_if_errors();
5233 match (default_exists, secondary_exists) {
5234 (true, false) => (default_path, false),
5235 (false, true) => (secondary_path, true),
5237 self.span_fatal_help(id_sp,
5238 &format!("file not found for module `{}`",
5240 &format!("name the file either {} or {} inside \
5241 the directory {:?}",
5244 dir_path.display())[]);
5247 self.span_fatal_help(
5249 &format!("file for module `{}` found at both {} \
5253 secondary_path_str)[],
5254 "delete or rename one of them to remove the ambiguity");
5260 self.eval_src_mod_from_path(file_path, owns_directory,
5261 mod_string.to_string(), id_sp)
5264 fn eval_src_mod_from_path(&mut self,
5266 owns_directory: bool,
5268 id_sp: Span) -> (ast::Item_, Vec<ast::Attribute> ) {
5269 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
5270 match included_mod_stack.iter().position(|p| *p == path) {
5272 let mut err = String::from_str("circular modules: ");
5273 let len = included_mod_stack.len();
5274 for p in &included_mod_stack[i.. len] {
5275 err.push_str(&p.display().as_cow()[]);
5276 err.push_str(" -> ");
5278 err.push_str(&path.display().as_cow()[]);
5279 self.span_fatal(id_sp, &err[]);
5283 included_mod_stack.push(path.clone());
5284 drop(included_mod_stack);
5287 new_sub_parser_from_file(self.sess,
5293 let mod_inner_lo = p0.span.lo;
5294 let (mod_attrs, next) = p0.parse_inner_attrs_and_next();
5295 let first_item_outer_attrs = next;
5296 let m0 = p0.parse_mod_items(token::Eof, first_item_outer_attrs, mod_inner_lo);
5297 self.sess.included_mod_stack.borrow_mut().pop();
5298 return (ast::ItemMod(m0), mod_attrs);
5301 /// Parse a function declaration from a foreign module
5302 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility,
5303 attrs: Vec<Attribute>) -> P<ForeignItem> {
5304 let lo = self.span.lo;
5305 self.expect_keyword(keywords::Fn);
5307 let (ident, mut generics) = self.parse_fn_header();
5308 let decl = self.parse_fn_decl(true);
5309 self.parse_where_clause(&mut generics);
5310 let hi = self.span.hi;
5311 self.expect(&token::Semi);
5312 P(ast::ForeignItem {
5315 node: ForeignItemFn(decl, generics),
5316 id: ast::DUMMY_NODE_ID,
5317 span: mk_sp(lo, hi),
5322 /// Parse a static item from a foreign module
5323 fn parse_item_foreign_static(&mut self, vis: ast::Visibility,
5324 attrs: Vec<Attribute>) -> P<ForeignItem> {
5325 let lo = self.span.lo;
5327 self.expect_keyword(keywords::Static);
5328 let mutbl = self.eat_keyword(keywords::Mut);
5330 let ident = self.parse_ident();
5331 self.expect(&token::Colon);
5332 let ty = self.parse_ty_sum();
5333 let hi = self.span.hi;
5334 self.expect(&token::Semi);
5338 node: ForeignItemStatic(ty, mutbl),
5339 id: ast::DUMMY_NODE_ID,
5340 span: mk_sp(lo, hi),
5345 /// At this point, this is essentially a wrapper for
5346 /// parse_foreign_items.
5347 fn parse_foreign_mod_items(&mut self,
5349 first_item_attrs: Vec<Attribute>)
5351 let foreign_items = self.parse_foreign_items(first_item_attrs);
5352 assert!(self.token == token::CloseDelim(token::Brace));
5355 items: foreign_items
5359 /// Parse extern crate links
5363 /// extern crate url;
5364 /// extern crate foo = "bar"; //deprecated
5365 /// extern crate "bar" as foo;
5366 fn parse_item_extern_crate(&mut self,
5368 visibility: Visibility,
5369 attrs: Vec<Attribute>)
5372 let span = self.span;
5373 let (maybe_path, ident) = match self.token {
5374 token::Ident(..) => {
5375 let the_ident = self.parse_ident();
5376 let path = if self.eat_keyword_noexpect(keywords::As) {
5377 // skip the ident if there is one
5378 if self.token.is_ident() { self.bump(); }
5380 self.span_err(span, "expected `;`, found `as`");
5381 self.span_help(span,
5382 &format!("perhaps you meant to enclose the crate name `{}` in \
5384 the_ident.as_str())[]);
5389 self.expect(&token::Semi);
5392 token::Literal(token::Str_(..), suf) | token::Literal(token::StrRaw(..), suf) => {
5394 self.expect_no_suffix(sp, "extern crate name", suf);
5395 // forgo the internal suffix check of `parse_str` to
5396 // avoid repeats (this unwrap will always succeed due
5397 // to the restriction of the `match`)
5398 let (s, style, _) = self.parse_optional_str().unwrap();
5399 self.expect_keyword(keywords::As);
5400 let the_ident = self.parse_ident();
5401 self.expect(&token::Semi);
5402 (Some((s, style)), the_ident)
5405 let span = self.span;
5406 let token_str = self.this_token_to_string();
5407 self.span_fatal(span,
5408 &format!("expected extern crate name but \
5414 let last_span = self.last_span;
5418 ItemExternCrate(maybe_path),
5423 /// Parse `extern` for foreign ABIs
5426 /// `extern` is expected to have been
5427 /// consumed before calling this method
5433 fn parse_item_foreign_mod(&mut self,
5435 opt_abi: Option<abi::Abi>,
5436 visibility: Visibility,
5437 attrs: Vec<Attribute>)
5440 self.expect(&token::OpenDelim(token::Brace));
5442 let abi = opt_abi.unwrap_or(abi::C);
5444 let (inner, next) = self.parse_inner_attrs_and_next();
5445 let m = self.parse_foreign_mod_items(abi, next);
5446 self.expect(&token::CloseDelim(token::Brace));
5448 let last_span = self.last_span;
5451 special_idents::invalid,
5454 maybe_append(attrs, Some(inner)))
5457 /// Parse type Foo = Bar;
5458 fn parse_item_type(&mut self) -> ItemInfo {
5459 let ident = self.parse_ident();
5460 let mut tps = self.parse_generics();
5461 self.parse_where_clause(&mut tps);
5462 self.expect(&token::Eq);
5463 let ty = self.parse_ty_sum();
5464 self.expect(&token::Semi);
5465 (ident, ItemTy(ty, tps), None)
5468 /// Parse a structure-like enum variant definition
5469 /// this should probably be renamed or refactored...
5470 fn parse_struct_def(&mut self) -> P<StructDef> {
5471 let mut fields: Vec<StructField> = Vec::new();
5472 while self.token != token::CloseDelim(token::Brace) {
5473 fields.push(self.parse_struct_decl_field(false));
5483 /// Parse the part of an "enum" decl following the '{'
5484 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> EnumDef {
5485 let mut variants = Vec::new();
5486 let mut all_nullary = true;
5487 let mut any_disr = None;
5488 while self.token != token::CloseDelim(token::Brace) {
5489 let variant_attrs = self.parse_outer_attributes();
5490 let vlo = self.span.lo;
5492 let vis = self.parse_visibility();
5496 let mut args = Vec::new();
5497 let mut disr_expr = None;
5498 ident = self.parse_ident();
5499 if self.eat(&token::OpenDelim(token::Brace)) {
5500 // Parse a struct variant.
5501 all_nullary = false;
5502 let start_span = self.span;
5503 let struct_def = self.parse_struct_def();
5504 if struct_def.fields.len() == 0 {
5505 self.span_err(start_span,
5506 &format!("unit-like struct variant should be written \
5507 without braces, as `{},`",
5508 token::get_ident(ident))[]);
5510 kind = StructVariantKind(struct_def);
5511 } else if self.check(&token::OpenDelim(token::Paren)) {
5512 all_nullary = false;
5513 let arg_tys = self.parse_enum_variant_seq(
5514 &token::OpenDelim(token::Paren),
5515 &token::CloseDelim(token::Paren),
5516 seq_sep_trailing_allowed(token::Comma),
5517 |p| p.parse_ty_sum()
5520 args.push(ast::VariantArg {
5522 id: ast::DUMMY_NODE_ID,
5525 kind = TupleVariantKind(args);
5526 } else if self.eat(&token::Eq) {
5527 disr_expr = Some(self.parse_expr());
5528 any_disr = disr_expr.as_ref().map(|expr| expr.span);
5529 kind = TupleVariantKind(args);
5531 kind = TupleVariantKind(Vec::new());
5534 let vr = ast::Variant_ {
5536 attrs: variant_attrs,
5538 id: ast::DUMMY_NODE_ID,
5539 disr_expr: disr_expr,
5542 variants.push(P(spanned(vlo, self.last_span.hi, vr)));
5544 if !self.eat(&token::Comma) { break; }
5546 self.expect(&token::CloseDelim(token::Brace));
5548 Some(disr_span) if !all_nullary =>
5549 self.span_err(disr_span,
5550 "discriminator values can only be used with a c-like enum"),
5554 ast::EnumDef { variants: variants }
5557 /// Parse an "enum" declaration
5558 fn parse_item_enum(&mut self) -> ItemInfo {
5559 let id = self.parse_ident();
5560 let mut generics = self.parse_generics();
5561 self.parse_where_clause(&mut generics);
5562 self.expect(&token::OpenDelim(token::Brace));
5564 let enum_definition = self.parse_enum_def(&generics);
5565 (id, ItemEnum(enum_definition, generics), None)
5568 /// Parses a string as an ABI spec on an extern type or module. Consumes
5569 /// the `extern` keyword, if one is found.
5570 fn parse_opt_abi(&mut self) -> Option<abi::Abi> {
5572 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
5574 self.expect_no_suffix(sp, "ABI spec", suf);
5576 let the_string = s.as_str();
5577 match abi::lookup(the_string) {
5578 Some(abi) => Some(abi),
5580 let last_span = self.last_span;
5583 &format!("illegal ABI: expected one of [{}], \
5585 abi::all_names().connect(", "),
5596 /// Parse one of the items allowed by the flags; on failure,
5597 /// return `Err(remaining_attrs)`.
5598 /// NB: this function no longer parses the items inside an
5600 fn parse_item_(&mut self, attrs: Vec<Attribute>,
5601 macros_allowed: bool) -> MaybeItem {
5602 let nt_item = match self.token {
5603 token::Interpolated(token::NtItem(ref item)) => {
5604 Some((**item).clone())
5611 let mut attrs = attrs;
5612 mem::swap(&mut item.attrs, &mut attrs);
5613 item.attrs.extend(attrs.into_iter());
5619 let lo = self.span.lo;
5621 let visibility = self.parse_visibility();
5623 if self.eat_keyword(keywords::Use) {
5625 let item_ = ItemUse(self.parse_view_path());
5626 self.expect(&token::Semi);
5628 let last_span = self.last_span;
5629 let item = self.mk_item(lo,
5631 token::special_idents::invalid,
5638 if self.eat_keyword(keywords::Extern) {
5639 if self.eat_keyword(keywords::Crate) {
5640 return Ok(self.parse_item_extern_crate(lo, visibility, attrs));
5643 let opt_abi = self.parse_opt_abi();
5645 if self.eat_keyword(keywords::Fn) {
5646 // EXTERN FUNCTION ITEM
5647 let abi = opt_abi.unwrap_or(abi::C);
5648 let (ident, item_, extra_attrs) =
5649 self.parse_item_fn(Unsafety::Normal, abi);
5650 let last_span = self.last_span;
5651 let item = self.mk_item(lo,
5656 maybe_append(attrs, extra_attrs));
5658 } else if self.check(&token::OpenDelim(token::Brace)) {
5659 return Ok(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs));
5662 let span = self.span;
5663 let token_str = self.this_token_to_string();
5664 self.span_fatal(span,
5665 &format!("expected `{}` or `fn`, found `{}`", "{",
5669 if self.eat_keyword_noexpect(keywords::Virtual) {
5670 let span = self.span;
5671 self.span_err(span, "`virtual` structs have been removed from the language");
5674 if self.eat_keyword(keywords::Static) {
5676 let m = if self.eat_keyword(keywords::Mut) {MutMutable} else {MutImmutable};
5677 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m));
5678 let last_span = self.last_span;
5679 let item = self.mk_item(lo,
5684 maybe_append(attrs, extra_attrs));
5687 if self.eat_keyword(keywords::Const) {
5689 if self.eat_keyword(keywords::Mut) {
5690 let last_span = self.last_span;
5691 self.span_err(last_span, "const globals cannot be mutable");
5692 self.span_help(last_span, "did you mean to declare a static?");
5694 let (ident, item_, extra_attrs) = self.parse_item_const(None);
5695 let last_span = self.last_span;
5696 let item = self.mk_item(lo,
5701 maybe_append(attrs, extra_attrs));
5704 if self.check_keyword(keywords::Unsafe) &&
5705 self.look_ahead(1, |t| t.is_keyword(keywords::Trait))
5707 // UNSAFE TRAIT ITEM
5708 self.expect_keyword(keywords::Unsafe);
5709 self.expect_keyword(keywords::Trait);
5710 let (ident, item_, extra_attrs) =
5711 self.parse_item_trait(ast::Unsafety::Unsafe);
5712 let last_span = self.last_span;
5713 let item = self.mk_item(lo,
5718 maybe_append(attrs, extra_attrs));
5721 if self.check_keyword(keywords::Unsafe) &&
5722 self.look_ahead(1, |t| t.is_keyword(keywords::Impl))
5725 self.expect_keyword(keywords::Unsafe);
5726 self.expect_keyword(keywords::Impl);
5727 let (ident, item_, extra_attrs) = self.parse_item_impl(ast::Unsafety::Unsafe);
5728 let last_span = self.last_span;
5729 let item = self.mk_item(lo,
5734 maybe_append(attrs, extra_attrs));
5737 if self.check_keyword(keywords::Fn) {
5740 let (ident, item_, extra_attrs) =
5741 self.parse_item_fn(Unsafety::Normal, abi::Rust);
5742 let last_span = self.last_span;
5743 let item = self.mk_item(lo,
5748 maybe_append(attrs, extra_attrs));
5751 if self.check_keyword(keywords::Unsafe)
5752 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
5753 // UNSAFE FUNCTION ITEM
5755 let abi = if self.eat_keyword(keywords::Extern) {
5756 self.parse_opt_abi().unwrap_or(abi::C)
5760 self.expect_keyword(keywords::Fn);
5761 let (ident, item_, extra_attrs) =
5762 self.parse_item_fn(Unsafety::Unsafe, abi);
5763 let last_span = self.last_span;
5764 let item = self.mk_item(lo,
5769 maybe_append(attrs, extra_attrs));
5772 if self.eat_keyword(keywords::Mod) {
5774 let (ident, item_, extra_attrs) =
5775 self.parse_item_mod(&attrs[]);
5776 let last_span = self.last_span;
5777 let item = self.mk_item(lo,
5782 maybe_append(attrs, extra_attrs));
5785 if self.eat_keyword(keywords::Type) {
5787 let (ident, item_, extra_attrs) = self.parse_item_type();
5788 let last_span = self.last_span;
5789 let item = self.mk_item(lo,
5794 maybe_append(attrs, extra_attrs));
5797 if self.eat_keyword(keywords::Enum) {
5799 let (ident, item_, extra_attrs) = self.parse_item_enum();
5800 let last_span = self.last_span;
5801 let item = self.mk_item(lo,
5806 maybe_append(attrs, extra_attrs));
5809 if self.eat_keyword(keywords::Trait) {
5811 let (ident, item_, extra_attrs) =
5812 self.parse_item_trait(ast::Unsafety::Normal);
5813 let last_span = self.last_span;
5814 let item = self.mk_item(lo,
5819 maybe_append(attrs, extra_attrs));
5822 if self.eat_keyword(keywords::Impl) {
5824 let (ident, item_, extra_attrs) = self.parse_item_impl(ast::Unsafety::Normal);
5825 let last_span = self.last_span;
5826 let item = self.mk_item(lo,
5831 maybe_append(attrs, extra_attrs));
5834 if self.eat_keyword(keywords::Struct) {
5836 let (ident, item_, extra_attrs) = self.parse_item_struct();
5837 let last_span = self.last_span;
5838 let item = self.mk_item(lo,
5843 maybe_append(attrs, extra_attrs));
5846 self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility)
5849 /// Parse a foreign item; on failure, return `Err(remaining_attrs)`.
5850 fn parse_foreign_item(&mut self, attrs: Vec<Attribute>)
5851 -> Result<P<ForeignItem>, Vec<Attribute>> {
5852 let lo = self.span.lo;
5854 let visibility = self.parse_visibility();
5856 if self.check_keyword(keywords::Static) {
5857 // FOREIGN STATIC ITEM
5858 return Ok(self.parse_item_foreign_static(visibility, attrs));
5860 if self.check_keyword(keywords::Fn) || self.check_keyword(keywords::Unsafe) {
5861 // FOREIGN FUNCTION ITEM
5862 return Ok(self.parse_item_foreign_fn(visibility, attrs));
5865 // FIXME #5668: this will occur for a macro invocation:
5866 let item = try!(self.parse_macro_use_or_failure(attrs, true, lo, visibility));
5867 self.span_fatal(item.span, "macros cannot expand to foreign items");
5870 /// This is the fall-through for parsing items.
5871 fn parse_macro_use_or_failure(
5873 attrs: Vec<Attribute> ,
5874 macros_allowed: bool,
5876 visibility: Visibility
5878 if macros_allowed && !self.token.is_any_keyword()
5879 && self.look_ahead(1, |t| *t == token::Not)
5880 && (self.look_ahead(2, |t| t.is_plain_ident())
5881 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren))
5882 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) {
5883 // MACRO INVOCATION ITEM
5885 let last_span = self.last_span;
5886 self.complain_if_pub_macro(visibility, last_span);
5889 let pth = self.parse_path(NoTypesAllowed);
5890 self.expect(&token::Not);
5892 // a 'special' identifier (like what `macro_rules!` uses)
5893 // is optional. We should eventually unify invoc syntax
5895 let id = if self.token.is_plain_ident() {
5898 token::special_idents::invalid // no special identifier
5900 // eat a matched-delimiter token tree:
5901 let delim = self.expect_open_delim();
5902 let tts = self.parse_seq_to_end(&token::CloseDelim(delim),
5904 |p| p.parse_token_tree());
5905 // single-variant-enum... :
5906 let m = ast::MacInvocTT(pth, tts, EMPTY_CTXT);
5907 let m: ast::Mac = codemap::Spanned { node: m,
5908 span: mk_sp(self.span.lo,
5911 if delim != token::Brace {
5912 if !self.eat(&token::Semi) {
5913 let last_span = self.last_span;
5914 self.span_err(last_span,
5915 "macros that expand to items must either \
5916 be surrounded with braces or followed by \
5921 let item_ = ItemMac(m);
5922 let last_span = self.last_span;
5923 let item = self.mk_item(lo,
5932 // FAILURE TO PARSE ITEM
5936 let last_span = self.last_span;
5937 self.span_fatal(last_span, "unmatched visibility `pub`");
5943 pub fn parse_item_with_outer_attributes(&mut self) -> Option<P<Item>> {
5944 let attrs = self.parse_outer_attributes();
5945 self.parse_item(attrs)
5948 pub fn parse_item(&mut self, attrs: Vec<Attribute>) -> Option<P<Item>> {
5949 self.parse_item_(attrs, true).ok()
5952 /// Matches view_path : MOD? non_global_path as IDENT
5953 /// | MOD? non_global_path MOD_SEP LBRACE RBRACE
5954 /// | MOD? non_global_path MOD_SEP LBRACE ident_seq RBRACE
5955 /// | MOD? non_global_path MOD_SEP STAR
5956 /// | MOD? non_global_path
5957 fn parse_view_path(&mut self) -> P<ViewPath> {
5958 let lo = self.span.lo;
5960 // Allow a leading :: because the paths are absolute either way.
5961 // This occurs with "use $crate::..." in macros.
5962 self.eat(&token::ModSep);
5964 if self.check(&token::OpenDelim(token::Brace)) {
5966 let idents = self.parse_unspanned_seq(
5967 &token::OpenDelim(token::Brace),
5968 &token::CloseDelim(token::Brace),
5969 seq_sep_trailing_allowed(token::Comma),
5970 |p| p.parse_path_list_item());
5971 let path = ast::Path {
5972 span: mk_sp(lo, self.span.hi),
5974 segments: Vec::new()
5976 return P(spanned(lo, self.span.hi, ViewPathList(path, idents)));
5979 let first_ident = self.parse_ident();
5980 let mut path = vec!(first_ident);
5981 if let token::ModSep = self.token {
5982 // foo::bar or foo::{a,b,c} or foo::*
5983 while self.check(&token::ModSep) {
5987 token::Ident(..) => {
5988 let ident = self.parse_ident();
5992 // foo::bar::{a,b,c}
5993 token::OpenDelim(token::Brace) => {
5994 let idents = self.parse_unspanned_seq(
5995 &token::OpenDelim(token::Brace),
5996 &token::CloseDelim(token::Brace),
5997 seq_sep_trailing_allowed(token::Comma),
5998 |p| p.parse_path_list_item()
6000 let path = ast::Path {
6001 span: mk_sp(lo, self.span.hi),
6003 segments: path.into_iter().map(|identifier| {
6005 identifier: identifier,
6006 parameters: ast::PathParameters::none(),
6010 return P(spanned(lo, self.span.hi, ViewPathList(path, idents)));
6014 token::BinOp(token::Star) => {
6016 let path = ast::Path {
6017 span: mk_sp(lo, self.span.hi),
6019 segments: path.into_iter().map(|identifier| {
6021 identifier: identifier,
6022 parameters: ast::PathParameters::none(),
6026 return P(spanned(lo, self.span.hi, ViewPathGlob(path)));
6029 // fall-through for case foo::bar::;
6031 self.span_err(self.span, "expected identifier or `{` or `*`, found `;`");
6038 let mut rename_to = path[path.len() - 1];
6039 let path = ast::Path {
6040 span: mk_sp(lo, self.last_span.hi),
6042 segments: path.into_iter().map(|identifier| {
6044 identifier: identifier,
6045 parameters: ast::PathParameters::none(),
6049 if self.eat_keyword(keywords::As) {
6050 rename_to = self.parse_ident()
6052 P(spanned(lo, self.last_span.hi, ViewPathSimple(rename_to, path)))
6055 /// Parses a sequence of foreign items. Stops when it finds program
6056 /// text that can't be parsed as an item
6057 fn parse_foreign_items(&mut self, first_item_attrs: Vec<Attribute>)
6058 -> Vec<P<ForeignItem>> {
6059 let mut attrs = first_item_attrs;
6060 attrs.push_all(&self.parse_outer_attributes()[]);
6061 let mut foreign_items = Vec::new();
6063 match self.parse_foreign_item(attrs) {
6064 Ok(foreign_item) => {
6065 foreign_items.push(foreign_item);
6067 Err(returned_attrs) => {
6068 if self.check(&token::CloseDelim(token::Brace)) {
6069 attrs = returned_attrs;
6075 attrs = self.parse_outer_attributes();
6078 if !attrs.is_empty() {
6079 let last_span = self.last_span;
6080 self.span_err(last_span,
6081 Parser::expected_item_err(&attrs[]));
6087 /// Parses a source module as a crate. This is the main
6088 /// entry point for the parser.
6089 pub fn parse_crate_mod(&mut self) -> Crate {
6090 let lo = self.span.lo;
6091 // parse the crate's inner attrs, maybe (oops) one
6092 // of the attrs of an item:
6093 let (inner, next) = self.parse_inner_attrs_and_next();
6094 let first_item_outer_attrs = next;
6095 // parse the items inside the crate:
6096 let m = self.parse_mod_items(token::Eof, first_item_outer_attrs, lo);
6101 config: self.cfg.clone(),
6102 span: mk_sp(lo, self.span.lo),
6103 exported_macros: Vec::new(),
6107 pub fn parse_optional_str(&mut self)
6108 -> Option<(InternedString, ast::StrStyle, Option<ast::Name>)> {
6109 let ret = match self.token {
6110 token::Literal(token::Str_(s), suf) => {
6111 (self.id_to_interned_str(s.ident()), ast::CookedStr, suf)
6113 token::Literal(token::StrRaw(s, n), suf) => {
6114 (self.id_to_interned_str(s.ident()), ast::RawStr(n), suf)
6122 pub fn parse_str(&mut self) -> (InternedString, StrStyle) {
6123 match self.parse_optional_str() {
6124 Some((s, style, suf)) => {
6125 let sp = self.last_span;
6126 self.expect_no_suffix(sp, "str literal", suf);
6129 _ => self.fatal("expected string literal")