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::{FnUnboxedClosureKind, FnMutUnboxedClosureKind};
32 use ast::{FnOnceUnboxedClosureKind};
33 use ast::{ForeignItem, ForeignItemStatic, ForeignItemFn, ForeignMod, FunctionRetTy};
34 use ast::{Ident, Inherited, ImplItem, Item, Item_, ItemStatic};
35 use ast::{ItemEnum, ItemFn, ItemForeignMod, ItemImpl, ItemConst};
36 use ast::{ItemMac, ItemMod, ItemStruct, ItemTrait, ItemTy};
37 use ast::{ItemExternCrate, ItemUse};
38 use ast::{LifetimeDef, Lit, Lit_};
39 use ast::{LitBool, LitChar, LitByte, LitBinary};
40 use ast::{LitStr, LitInt, Local, LocalLet};
41 use ast::{MacStmtWithBraces, MacStmtWithSemicolon, MacStmtWithoutBraces};
42 use ast::{MutImmutable, MutMutable, Mac_, MacInvocTT, MatchSource};
43 use ast::{Method, MutTy, BiMul, Mutability};
44 use ast::{MethodImplItem, NamedField, UnNeg, NoReturn, NodeId, UnNot};
45 use ast::{Pat, PatEnum, PatIdent, PatLit, PatRange, PatRegion, PatStruct};
46 use ast::{PatTup, PatBox, PatWild, PatWildMulti, PatWildSingle};
47 use ast::{PolyTraitRef};
48 use ast::{QPath, RequiredMethod};
49 use ast::{Return, BiShl, BiShr, Stmt, StmtDecl};
50 use ast::{StmtExpr, StmtSemi, StmtMac, StructDef, StructField};
51 use ast::{StructVariantKind, BiSub, StrStyle};
52 use ast::{SelfExplicit, SelfRegion, SelfStatic, SelfValue};
53 use ast::{Delimited, SequenceRepetition, TokenTree, TraitItem, TraitRef};
54 use ast::{TtDelimited, TtSequence, TtToken};
55 use ast::{TupleVariantKind, Ty, Ty_, TypeBinding};
56 use ast::{TyFixedLengthVec, TyBareFn};
57 use ast::{TyTypeof, TyInfer, TypeMethod};
58 use ast::{TyParam, TyParamBound, TyParen, TyPath, TyPolyTraitRef, TyPtr, TyQPath};
59 use ast::{TyRptr, TyTup, TyU32, TyVec, UnUniq};
60 use ast::{TypeImplItem, TypeTraitItem, Typedef, UnboxedClosureKind};
61 use ast::{UnnamedField, UnsafeBlock};
62 use ast::{ViewPath, ViewPathGlob, ViewPathList, ViewPathSimple};
63 use ast::{Visibility, WhereClause};
65 use ast_util::{self, AS_PREC, ident_to_path, operator_prec};
66 use codemap::{self, Span, BytePos, Spanned, spanned, mk_sp};
68 use ext::tt::macro_parser;
70 use parse::attr::ParserAttr;
72 use parse::common::{SeqSep, seq_sep_none, seq_sep_trailing_allowed};
73 use parse::lexer::{Reader, TokenAndSpan};
74 use parse::obsolete::{ParserObsoleteMethods, ObsoleteSyntax};
75 use parse::token::{self, MatchNt, SubstNt, SpecialVarNt, InternedString};
76 use parse::token::{keywords, special_idents, SpecialMacroVar};
77 use parse::{new_sub_parser_from_file, ParseSess};
80 use owned_slice::OwnedSlice;
82 use std::collections::HashSet;
83 use std::io::fs::PathExtensions;
91 flags Restrictions: u8 {
92 const UNRESTRICTED = 0b0000,
93 const RESTRICTION_STMT_EXPR = 0b0001,
94 const RESTRICTION_NO_BAR_OP = 0b0010,
95 const RESTRICTION_NO_STRUCT_LITERAL = 0b0100,
100 type ItemInfo = (Ident, Item_, Option<Vec<Attribute> >);
102 /// How to parse a path. There are four different kinds of paths, all of which
103 /// are parsed somewhat differently.
104 #[derive(Copy, PartialEq)]
105 pub enum PathParsingMode {
106 /// A path with no type parameters; e.g. `foo::bar::Baz`
108 /// A path with a lifetime and type parameters, with no double colons
109 /// before the type parameters; e.g. `foo::bar<'a>::Baz<T>`
110 LifetimeAndTypesWithoutColons,
111 /// A path with a lifetime and type parameters with double colons before
112 /// the type parameters; e.g. `foo::bar::<'a>::Baz::<T>`
113 LifetimeAndTypesWithColons,
116 /// How to parse a bound, whether to allow bound modifiers such as `?`.
117 #[derive(Copy, PartialEq)]
118 pub enum BoundParsingMode {
123 /// The `Err` case indicates a failure to parse any kind of item.
124 /// The attributes are returned.
125 type MaybeItem = Result<P<Item>, Vec<Attribute>>;
128 /// Possibly accept an `token::Interpolated` expression (a pre-parsed expression
129 /// dropped into the token stream, which happens while parsing the result of
130 /// macro expansion). Placement of these is not as complex as I feared it would
131 /// be. The important thing is to make sure that lookahead doesn't balk at
132 /// `token::Interpolated` tokens.
133 macro_rules! maybe_whole_expr {
136 let found = match $p.token {
137 token::Interpolated(token::NtExpr(ref e)) => {
140 token::Interpolated(token::NtPath(_)) => {
141 // FIXME: The following avoids an issue with lexical borrowck scopes,
142 // but the clone is unfortunate.
143 let pt = match $p.token {
144 token::Interpolated(token::NtPath(ref pt)) => (**pt).clone(),
148 Some($p.mk_expr(span.lo, span.hi, ExprPath(pt)))
150 token::Interpolated(token::NtBlock(_)) => {
151 // FIXME: The following avoids an issue with lexical borrowck scopes,
152 // but the clone is unfortunate.
153 let b = match $p.token {
154 token::Interpolated(token::NtBlock(ref b)) => (*b).clone(),
158 Some($p.mk_expr(span.lo, span.hi, ExprBlock(b)))
173 /// As maybe_whole_expr, but for things other than expressions
174 macro_rules! maybe_whole {
175 ($p:expr, $constructor:ident) => (
177 let found = match ($p).token {
178 token::Interpolated(token::$constructor(_)) => {
179 Some(($p).bump_and_get())
183 if let Some(token::Interpolated(token::$constructor(x))) = found {
188 (no_clone $p:expr, $constructor:ident) => (
190 let found = match ($p).token {
191 token::Interpolated(token::$constructor(_)) => {
192 Some(($p).bump_and_get())
196 if let Some(token::Interpolated(token::$constructor(x))) = found {
201 (deref $p:expr, $constructor:ident) => (
203 let found = match ($p).token {
204 token::Interpolated(token::$constructor(_)) => {
205 Some(($p).bump_and_get())
209 if let Some(token::Interpolated(token::$constructor(x))) = found {
214 (Some $p:expr, $constructor:ident) => (
216 let found = match ($p).token {
217 token::Interpolated(token::$constructor(_)) => {
218 Some(($p).bump_and_get())
222 if let Some(token::Interpolated(token::$constructor(x))) = found {
223 return Some(x.clone());
227 (pair_empty $p:expr, $constructor:ident) => (
229 let found = match ($p).token {
230 token::Interpolated(token::$constructor(_)) => {
231 Some(($p).bump_and_get())
235 if let Some(token::Interpolated(token::$constructor(x))) = found {
236 return (Vec::new(), x);
243 fn maybe_append(mut lhs: Vec<Attribute>, rhs: Option<Vec<Attribute>>)
246 Some(ref attrs) => lhs.extend(attrs.iter().map(|a| a.clone())),
252 /* ident is handled by common.rs */
254 pub struct Parser<'a> {
255 pub sess: &'a ParseSess,
256 /// the current token:
257 pub token: token::Token,
258 /// the span of the current token:
260 /// the span of the prior token:
262 pub cfg: CrateConfig,
263 /// the previous token or None (only stashed sometimes).
264 pub last_token: Option<Box<token::Token>>,
265 pub buffer: [TokenAndSpan; 4],
266 pub buffer_start: isize,
267 pub buffer_end: isize,
268 pub tokens_consumed: usize,
269 pub restrictions: Restrictions,
270 pub quote_depth: usize, // not (yet) related to the quasiquoter
271 pub reader: Box<Reader+'a>,
272 pub interner: Rc<token::IdentInterner>,
273 /// The set of seen errors about obsolete syntax. Used to suppress
274 /// extra detail when the same error is seen twice
275 pub obsolete_set: HashSet<ObsoleteSyntax>,
276 /// Used to determine the path to externally loaded source files
277 pub mod_path_stack: Vec<InternedString>,
278 /// Stack of spans of open delimiters. Used for error message.
279 pub open_braces: Vec<Span>,
280 /// Flag if this parser "owns" the directory that it is currently parsing
281 /// in. This will affect how nested files are looked up.
282 pub owns_directory: bool,
283 /// Name of the root module this parser originated from. If `None`, then the
284 /// name is not known. This does not change while the parser is descending
285 /// into modules, and sub-parsers have new values for this name.
286 pub root_module_name: Option<String>,
287 pub expected_tokens: Vec<TokenType>,
290 #[derive(PartialEq, Eq, Clone)]
297 fn to_string(&self) -> String {
299 TokenType::Token(ref t) => format!("`{}`", Parser::token_to_string(t)),
300 TokenType::Operator => "an operator".to_string(),
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(&self) -> ! {
369 let this_token = self.this_token_to_string();
370 self.fatal(&format!("unexpected token: `{}`", this_token)[]);
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 `{}`",
433 (format!("expected {}, found `{}`",
441 /// Check for erroneous `ident { }`; if matches, signal error and
442 /// recover (without consuming any expected input token). Returns
443 /// true if and only if input was consumed for recovery.
444 pub fn check_for_erroneous_unit_struct_expecting(&mut self, expected: &[token::Token]) -> bool {
445 if self.token == token::OpenDelim(token::Brace)
446 && expected.iter().all(|t| *t != token::OpenDelim(token::Brace))
447 && self.look_ahead(1, |t| *t == token::CloseDelim(token::Brace)) {
448 // matched; signal non-fatal error and recover.
449 let span = self.span;
451 "unit-like struct construction is written with no trailing `{ }`");
452 self.eat(&token::OpenDelim(token::Brace));
453 self.eat(&token::CloseDelim(token::Brace));
460 /// Commit to parsing a complete expression `e` expected to be
461 /// followed by some token from the set edible + inedible. Recover
462 /// from anticipated input errors, discarding erroneous characters.
463 pub fn commit_expr(&mut self, e: &Expr, edible: &[token::Token], inedible: &[token::Token]) {
464 debug!("commit_expr {:?}", e);
465 if let ExprPath(..) = e.node {
466 // might be unit-struct construction; check for recoverableinput error.
467 let mut expected = edible.iter().map(|x| x.clone()).collect::<Vec<_>>();
468 expected.push_all(inedible);
469 self.check_for_erroneous_unit_struct_expecting(&expected[]);
471 self.expect_one_of(edible, inedible)
474 pub fn commit_expr_expecting(&mut self, e: &Expr, edible: token::Token) {
475 self.commit_expr(e, &[edible], &[])
478 /// Commit to parsing a complete statement `s`, which expects to be
479 /// followed by some token from the set edible + inedible. Check
480 /// for recoverable input errors, discarding erroneous characters.
481 pub fn commit_stmt(&mut self, edible: &[token::Token], inedible: &[token::Token]) {
484 .map_or(false, |t| t.is_ident() || t.is_path()) {
485 let mut expected = edible.iter().map(|x| x.clone()).collect::<Vec<_>>();
486 expected.push_all(&inedible[]);
487 self.check_for_erroneous_unit_struct_expecting(
490 self.expect_one_of(edible, inedible)
493 pub fn commit_stmt_expecting(&mut self, edible: token::Token) {
494 self.commit_stmt(&[edible], &[])
497 pub fn parse_ident(&mut self) -> ast::Ident {
498 self.check_strict_keywords();
499 self.check_reserved_keywords();
501 token::Ident(i, _) => {
505 token::Interpolated(token::NtIdent(..)) => {
506 self.bug("ident interpolation not converted to real token");
509 let token_str = self.this_token_to_string();
510 self.fatal(&format!("expected ident, found `{}`",
516 pub fn parse_path_list_item(&mut self) -> ast::PathListItem {
517 let lo = self.span.lo;
518 let node = if self.eat_keyword(keywords::Mod) {
519 let span = self.last_span;
520 self.span_warn(span, "deprecated syntax; use the `self` keyword now");
521 ast::PathListMod { id: ast::DUMMY_NODE_ID }
522 } else if self.eat_keyword(keywords::Self) {
523 ast::PathListMod { id: ast::DUMMY_NODE_ID }
525 let ident = self.parse_ident();
526 ast::PathListIdent { name: ident, id: ast::DUMMY_NODE_ID }
528 let hi = self.last_span.hi;
529 spanned(lo, hi, node)
532 /// Check if the next token is `tok`, and return `true` if so.
534 /// This method is will automatically add `tok` to `expected_tokens` if `tok` is not
536 pub fn check(&mut self, tok: &token::Token) -> bool {
537 let is_present = self.token == *tok;
538 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
542 /// Consume token 'tok' if it exists. Returns true if the given
543 /// token was present, false otherwise.
544 pub fn eat(&mut self, tok: &token::Token) -> bool {
545 let is_present = self.check(tok);
546 if is_present { self.bump() }
550 /// If the next token is the given keyword, eat it and return
551 /// true. Otherwise, return false.
552 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
553 if self.token.is_keyword(kw) {
561 /// If the given word is not a keyword, signal an error.
562 /// If the next token is not the given word, signal an error.
563 /// Otherwise, eat it.
564 pub fn expect_keyword(&mut self, kw: keywords::Keyword) {
565 if !self.eat_keyword(kw) {
566 let id_interned_str = token::get_name(kw.to_name());
567 let token_str = self.this_token_to_string();
568 self.fatal(&format!("expected `{}`, found `{}`",
569 id_interned_str, token_str)[])
573 /// Signal an error if the given string is a strict keyword
574 pub fn check_strict_keywords(&mut self) {
575 if self.token.is_strict_keyword() {
576 let token_str = self.this_token_to_string();
577 let span = self.span;
579 &format!("expected identifier, found keyword `{}`",
584 /// Signal an error if the current token is a reserved keyword
585 pub fn check_reserved_keywords(&mut self) {
586 if self.token.is_reserved_keyword() {
587 let token_str = self.this_token_to_string();
588 self.fatal(&format!("`{}` is a reserved keyword",
593 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
594 /// `&` and continue. If an `&` is not seen, signal an error.
595 fn expect_and(&mut self) {
597 token::BinOp(token::And) => self.bump(),
599 let span = self.span;
600 let lo = span.lo + BytePos(1);
601 self.replace_token(token::BinOp(token::And), lo, span.hi)
604 let token_str = self.this_token_to_string();
606 Parser::token_to_string(&token::BinOp(token::And));
607 self.fatal(&format!("expected `{}`, found `{}`",
614 /// Expect and consume a `|`. If `||` is seen, replace it with a single
615 /// `|` and continue. If a `|` is not seen, signal an error.
616 fn expect_or(&mut self) {
618 token::BinOp(token::Or) => self.bump(),
620 let span = self.span;
621 let lo = span.lo + BytePos(1);
622 self.replace_token(token::BinOp(token::Or), lo, span.hi)
625 let found_token = self.this_token_to_string();
627 Parser::token_to_string(&token::BinOp(token::Or));
628 self.fatal(&format!("expected `{}`, found `{}`",
635 pub fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
637 None => {/* everything ok */}
639 let text = suf.as_str();
641 self.span_bug(sp, "found empty literal suffix in Some")
643 self.span_err(sp, &*format!("{} with a suffix is illegal", kind));
649 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
650 /// `<` and continue. If a `<` is not seen, return false.
652 /// This is meant to be used when parsing generics on a path to get the
654 fn eat_lt(&mut self) -> bool {
656 token::Lt => { self.bump(); true }
657 token::BinOp(token::Shl) => {
658 let span = self.span;
659 let lo = span.lo + BytePos(1);
660 self.replace_token(token::Lt, lo, span.hi);
667 fn expect_lt(&mut self) {
669 let found_token = self.this_token_to_string();
670 let token_str = Parser::token_to_string(&token::Lt);
671 self.fatal(&format!("expected `{}`, found `{}`",
677 /// Parse a sequence bracketed by `|` and `|`, stopping before the `|`.
678 fn parse_seq_to_before_or<T, F>(&mut self,
682 F: FnMut(&mut Parser) -> T,
684 let mut first = true;
685 let mut vector = Vec::new();
686 while self.token != token::BinOp(token::Or) &&
687 self.token != token::OrOr {
699 /// Expect and consume a GT. if a >> is seen, replace it
700 /// with a single > and continue. If a GT is not seen,
702 pub fn expect_gt(&mut self) {
704 token::Gt => self.bump(),
705 token::BinOp(token::Shr) => {
706 let span = self.span;
707 let lo = span.lo + BytePos(1);
708 self.replace_token(token::Gt, lo, span.hi)
710 token::BinOpEq(token::Shr) => {
711 let span = self.span;
712 let lo = span.lo + BytePos(1);
713 self.replace_token(token::Ge, lo, span.hi)
716 let span = self.span;
717 let lo = span.lo + BytePos(1);
718 self.replace_token(token::Eq, lo, span.hi)
721 let gt_str = Parser::token_to_string(&token::Gt);
722 let this_token_str = self.this_token_to_string();
723 self.fatal(&format!("expected `{}`, found `{}`",
730 pub fn parse_seq_to_before_gt_or_return<T, F>(&mut self,
731 sep: Option<token::Token>,
733 -> (OwnedSlice<T>, bool) where
734 F: FnMut(&mut Parser) -> Option<T>,
736 let mut v = Vec::new();
737 // This loop works by alternating back and forth between parsing types
738 // and commas. For example, given a string `A, B,>`, the parser would
739 // first parse `A`, then a comma, then `B`, then a comma. After that it
740 // would encounter a `>` and stop. This lets the parser handle trailing
741 // commas in generic parameters, because it can stop either after
742 // parsing a type or after parsing a comma.
743 for i in iter::count(0us, 1) {
744 if self.check(&token::Gt)
745 || self.token == token::BinOp(token::Shr)
746 || self.token == token::Ge
747 || self.token == token::BinOpEq(token::Shr) {
753 Some(result) => v.push(result),
754 None => return (OwnedSlice::from_vec(v), true)
757 sep.as_ref().map(|t| self.expect(t));
760 return (OwnedSlice::from_vec(v), false);
763 /// Parse a sequence bracketed by '<' and '>', stopping
765 pub fn parse_seq_to_before_gt<T, F>(&mut self,
766 sep: Option<token::Token>,
768 -> OwnedSlice<T> where
769 F: FnMut(&mut Parser) -> T,
771 let (result, returned) = self.parse_seq_to_before_gt_or_return(sep, |p| Some(f(p)));
776 pub fn parse_seq_to_gt<T, F>(&mut self,
777 sep: Option<token::Token>,
779 -> OwnedSlice<T> where
780 F: FnMut(&mut Parser) -> T,
782 let v = self.parse_seq_to_before_gt(sep, f);
787 pub fn parse_seq_to_gt_or_return<T, F>(&mut self,
788 sep: Option<token::Token>,
790 -> (OwnedSlice<T>, bool) where
791 F: FnMut(&mut Parser) -> Option<T>,
793 let (v, returned) = self.parse_seq_to_before_gt_or_return(sep, f);
797 return (v, returned);
800 /// Parse a sequence, including the closing delimiter. The function
801 /// f must consume tokens until reaching the next separator or
803 pub fn parse_seq_to_end<T, F>(&mut self,
808 F: FnMut(&mut Parser) -> T,
810 let val = self.parse_seq_to_before_end(ket, sep, f);
815 /// Parse a sequence, not including the closing delimiter. The function
816 /// f must consume tokens until reaching the next separator or
818 pub fn parse_seq_to_before_end<T, F>(&mut self,
823 F: FnMut(&mut Parser) -> T,
825 let mut first: bool = true;
827 while self.token != *ket {
830 if first { first = false; }
831 else { self.expect(t); }
835 if sep.trailing_sep_allowed && self.check(ket) { break; }
841 /// Parse a sequence, including the closing delimiter. The function
842 /// f must consume tokens until reaching the next separator or
844 pub fn parse_unspanned_seq<T, F>(&mut self,
850 F: FnMut(&mut Parser) -> T,
853 let result = self.parse_seq_to_before_end(ket, sep, f);
858 /// Parse a sequence parameter of enum variant. For consistency purposes,
859 /// these should not be empty.
860 pub fn parse_enum_variant_seq<T, F>(&mut self,
866 F: FnMut(&mut Parser) -> T,
868 let result = self.parse_unspanned_seq(bra, ket, sep, f);
869 if result.is_empty() {
870 let last_span = self.last_span;
871 self.span_err(last_span,
872 "nullary enum variants are written with no trailing `( )`");
877 // NB: Do not use this function unless you actually plan to place the
878 // spanned list in the AST.
879 pub fn parse_seq<T, F>(&mut self,
884 -> Spanned<Vec<T>> where
885 F: FnMut(&mut Parser) -> T,
887 let lo = self.span.lo;
889 let result = self.parse_seq_to_before_end(ket, sep, f);
890 let hi = self.span.hi;
892 spanned(lo, hi, result)
895 /// Advance the parser by one token
896 pub fn bump(&mut self) {
897 self.last_span = self.span;
898 // Stash token for error recovery (sometimes; clone is not necessarily cheap).
899 self.last_token = if self.token.is_ident() || self.token.is_path() {
900 Some(box self.token.clone())
904 let next = if self.buffer_start == self.buffer_end {
905 self.reader.real_token()
907 // Avoid token copies with `replace`.
908 let buffer_start = self.buffer_start as usize;
909 let next_index = (buffer_start + 1) & 3 as usize;
910 self.buffer_start = next_index as isize;
912 let placeholder = TokenAndSpan {
913 tok: token::Underscore,
916 mem::replace(&mut self.buffer[buffer_start], placeholder)
919 self.token = next.tok;
920 self.tokens_consumed += 1us;
921 self.expected_tokens.clear();
922 // check after each token
923 self.check_unknown_macro_variable();
926 /// Advance the parser by one token and return the bumped token.
927 pub fn bump_and_get(&mut self) -> token::Token {
928 let old_token = mem::replace(&mut self.token, token::Underscore);
933 /// EFFECT: replace the current token and span with the given one
934 pub fn replace_token(&mut self,
938 self.last_span = mk_sp(self.span.lo, lo);
940 self.span = mk_sp(lo, hi);
942 pub fn buffer_length(&mut self) -> isize {
943 if self.buffer_start <= self.buffer_end {
944 return self.buffer_end - self.buffer_start;
946 return (4 - self.buffer_start) + self.buffer_end;
948 pub fn look_ahead<R, F>(&mut self, distance: usize, f: F) -> R where
949 F: FnOnce(&token::Token) -> R,
951 let dist = distance as isize;
952 while self.buffer_length() < dist {
953 self.buffer[self.buffer_end as usize] = self.reader.real_token();
954 self.buffer_end = (self.buffer_end + 1) & 3;
956 f(&self.buffer[((self.buffer_start + dist - 1) & 3) as usize].tok)
958 pub fn fatal(&self, m: &str) -> ! {
959 self.sess.span_diagnostic.span_fatal(self.span, m)
961 pub fn span_fatal(&self, sp: Span, m: &str) -> ! {
962 self.sess.span_diagnostic.span_fatal(sp, m)
964 pub fn span_fatal_help(&self, sp: Span, m: &str, help: &str) -> ! {
965 self.span_err(sp, m);
966 self.span_help(sp, help);
967 panic!(diagnostic::FatalError);
969 pub fn span_note(&self, sp: Span, m: &str) {
970 self.sess.span_diagnostic.span_note(sp, m)
972 pub fn span_help(&self, sp: Span, m: &str) {
973 self.sess.span_diagnostic.span_help(sp, m)
975 pub fn bug(&self, m: &str) -> ! {
976 self.sess.span_diagnostic.span_bug(self.span, m)
978 pub fn warn(&self, m: &str) {
979 self.sess.span_diagnostic.span_warn(self.span, m)
981 pub fn span_warn(&self, sp: Span, m: &str) {
982 self.sess.span_diagnostic.span_warn(sp, m)
984 pub fn span_err(&self, sp: Span, m: &str) {
985 self.sess.span_diagnostic.span_err(sp, m)
987 pub fn span_bug(&self, sp: Span, m: &str) -> ! {
988 self.sess.span_diagnostic.span_bug(sp, m)
990 pub fn abort_if_errors(&self) {
991 self.sess.span_diagnostic.handler().abort_if_errors();
994 pub fn id_to_interned_str(&mut self, id: Ident) -> InternedString {
998 /// Is the current token one of the keywords that signals a bare function
1000 pub fn token_is_bare_fn_keyword(&mut self) -> bool {
1001 self.token.is_keyword(keywords::Fn) ||
1002 self.token.is_keyword(keywords::Unsafe) ||
1003 self.token.is_keyword(keywords::Extern)
1006 /// Is the current token one of the keywords that signals a closure type?
1007 pub fn token_is_closure_keyword(&mut self) -> bool {
1008 self.token.is_keyword(keywords::Unsafe)
1011 pub fn get_lifetime(&mut self) -> ast::Ident {
1013 token::Lifetime(ref ident) => *ident,
1014 _ => self.bug("not a lifetime"),
1018 pub fn parse_for_in_type(&mut self) -> Ty_ {
1020 Parses whatever can come after a `for` keyword in a type.
1021 The `for` has already been consumed.
1025 - for <'lt> |S| -> T
1029 - for <'lt> [unsafe] [extern "ABI"] fn (S) -> T
1030 - for <'lt> path::foo(a, b)
1035 let lifetime_defs = self.parse_late_bound_lifetime_defs();
1037 // examine next token to decide to do
1038 if self.eat_keyword(keywords::Proc) {
1039 self.parse_proc_type(lifetime_defs)
1040 } else if self.token_is_bare_fn_keyword() || self.token_is_closure_keyword() {
1041 self.parse_ty_bare_fn_or_ty_closure(lifetime_defs)
1042 } else if self.check(&token::ModSep) ||
1043 self.token.is_ident() ||
1044 self.token.is_path()
1046 let trait_ref = self.parse_trait_ref();
1047 let poly_trait_ref = ast::PolyTraitRef { bound_lifetimes: lifetime_defs,
1048 trait_ref: trait_ref };
1049 let other_bounds = if self.eat(&token::BinOp(token::Plus)) {
1050 self.parse_ty_param_bounds(BoundParsingMode::Bare)
1055 Some(TraitTyParamBound(poly_trait_ref, TraitBoundModifier::None)).into_iter()
1056 .chain(other_bounds.into_vec().into_iter())
1058 ast::TyPolyTraitRef(all_bounds)
1060 self.parse_ty_closure(lifetime_defs)
1064 pub fn parse_ty_path(&mut self) -> Ty_ {
1065 let path = self.parse_path(LifetimeAndTypesWithoutColons);
1066 TyPath(path, ast::DUMMY_NODE_ID)
1069 /// parse a TyBareFn type:
1070 pub fn parse_ty_bare_fn(&mut self, lifetime_defs: Vec<ast::LifetimeDef>) -> Ty_ {
1073 [unsafe] [extern "ABI"] fn <'lt> (S) -> T
1074 ^~~~^ ^~~~^ ^~~~^ ^~^ ^
1077 | | | Argument types
1083 let unsafety = self.parse_unsafety();
1084 let abi = if self.eat_keyword(keywords::Extern) {
1085 self.parse_opt_abi().unwrap_or(abi::C)
1090 self.expect_keyword(keywords::Fn);
1091 let lifetime_defs = self.parse_legacy_lifetime_defs(lifetime_defs);
1092 let (inputs, variadic) = self.parse_fn_args(false, true);
1093 let ret_ty = self.parse_ret_ty();
1094 let decl = P(FnDecl {
1099 TyBareFn(P(BareFnTy {
1102 lifetimes: lifetime_defs,
1107 /// Parses a procedure type (`proc`). The initial `proc` keyword must
1108 /// already have been parsed.
1109 pub fn parse_proc_type(&mut self, lifetime_defs: Vec<ast::LifetimeDef>) -> Ty_ {
1112 proc <'lt> (S) [:Bounds] -> T
1113 ^~~^ ^~~~^ ^ ^~~~~~~~^ ^
1119 the `proc` keyword (already consumed)
1123 let proc_span = self.last_span;
1125 // To be helpful, parse the proc as ever
1126 let _ = self.parse_legacy_lifetime_defs(lifetime_defs);
1127 let _ = self.parse_fn_args(false, false);
1128 let _ = self.parse_colon_then_ty_param_bounds(BoundParsingMode::Bare);
1129 let _ = self.parse_ret_ty();
1131 self.obsolete(proc_span, ObsoleteSyntax::ProcType);
1136 /// Parses an optional unboxed closure kind (`&:`, `&mut:`, or `:`).
1137 pub fn parse_optional_unboxed_closure_kind(&mut self)
1138 -> Option<UnboxedClosureKind> {
1139 if self.check(&token::BinOp(token::And)) &&
1140 self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
1141 self.look_ahead(2, |t| *t == token::Colon) {
1145 return Some(FnMutUnboxedClosureKind)
1148 if self.token == token::BinOp(token::And) &&
1149 self.look_ahead(1, |t| *t == token::Colon) {
1152 return Some(FnUnboxedClosureKind)
1155 if self.eat(&token::Colon) {
1156 return Some(FnOnceUnboxedClosureKind)
1162 pub fn parse_ty_bare_fn_or_ty_closure(&mut self, lifetime_defs: Vec<LifetimeDef>) -> Ty_ {
1163 // Both bare fns and closures can begin with stuff like unsafe
1164 // and extern. So we just scan ahead a few tokens to see if we see
1167 // Closure: [unsafe] <'lt> |S| [:Bounds] -> T
1168 // Fn: [unsafe] [extern "ABI"] fn <'lt> (S) -> T
1170 if self.token.is_keyword(keywords::Fn) {
1171 self.parse_ty_bare_fn(lifetime_defs)
1172 } else if self.token.is_keyword(keywords::Extern) {
1173 self.parse_ty_bare_fn(lifetime_defs)
1174 } else if self.token.is_keyword(keywords::Unsafe) {
1175 if self.look_ahead(1, |t| t.is_keyword(keywords::Fn) ||
1176 t.is_keyword(keywords::Extern)) {
1177 self.parse_ty_bare_fn(lifetime_defs)
1179 self.parse_ty_closure(lifetime_defs)
1182 self.parse_ty_closure(lifetime_defs)
1186 /// Parse a TyClosure type
1187 pub fn parse_ty_closure(&mut self, lifetime_defs: Vec<ast::LifetimeDef>) -> Ty_ {
1190 [unsafe] <'lt> |S| [:Bounds] -> T
1191 ^~~~~~~^ ^~~~^ ^ ^~~~~~~~^ ^
1194 | | | Closure bounds
1196 | Deprecated lifetime defs
1202 let ty_closure_span = self.last_span;
1204 // To be helpful, parse the closure type as ever
1205 let _ = self.parse_unsafety();
1207 let _ = self.parse_legacy_lifetime_defs(lifetime_defs);
1209 if !self.eat(&token::OrOr) {
1212 let _ = self.parse_seq_to_before_or(
1214 |p| p.parse_arg_general(false));
1218 let _ = self.parse_colon_then_ty_param_bounds(BoundParsingMode::Bare);
1220 let _ = self.parse_ret_ty();
1222 self.obsolete(ty_closure_span, ObsoleteSyntax::ClosureType);
1227 pub fn parse_unsafety(&mut self) -> Unsafety {
1228 if self.eat_keyword(keywords::Unsafe) {
1229 return Unsafety::Unsafe;
1231 return Unsafety::Normal;
1235 /// Parses `[ 'for' '<' lifetime_defs '>' ]'
1236 fn parse_legacy_lifetime_defs(&mut self,
1237 lifetime_defs: Vec<ast::LifetimeDef>)
1238 -> Vec<ast::LifetimeDef>
1240 if self.token == token::Lt {
1242 if lifetime_defs.is_empty() {
1243 self.warn("deprecated syntax; use the `for` keyword now \
1244 (e.g. change `fn<'a>` to `for<'a> fn`)");
1245 let lifetime_defs = self.parse_lifetime_defs();
1249 self.fatal("cannot use new `for` keyword and older syntax together");
1256 /// Parses `type Foo;` in a trait declaration only. The `type` keyword has
1257 /// already been parsed.
1258 fn parse_associated_type(&mut self, attrs: Vec<Attribute>)
1261 let ty_param = self.parse_ty_param();
1262 self.expect(&token::Semi);
1269 /// Parses `type Foo = TYPE;` in an implementation declaration only. The
1270 /// `type` keyword has already been parsed.
1271 fn parse_typedef(&mut self, attrs: Vec<Attribute>, vis: Visibility)
1273 let lo = self.span.lo;
1274 let ident = self.parse_ident();
1275 self.expect(&token::Eq);
1276 let typ = self.parse_ty_sum();
1277 let hi = self.span.hi;
1278 self.expect(&token::Semi);
1280 id: ast::DUMMY_NODE_ID,
1281 span: mk_sp(lo, hi),
1289 /// Parse the items in a trait declaration
1290 pub fn parse_trait_items(&mut self) -> Vec<TraitItem> {
1291 self.parse_unspanned_seq(
1292 &token::OpenDelim(token::Brace),
1293 &token::CloseDelim(token::Brace),
1296 let attrs = p.parse_outer_attributes();
1298 if p.eat_keyword(keywords::Type) {
1299 TypeTraitItem(P(p.parse_associated_type(attrs)))
1303 let vis = p.parse_visibility();
1304 let style = p.parse_unsafety();
1305 let abi = if p.eat_keyword(keywords::Extern) {
1306 p.parse_opt_abi().unwrap_or(abi::C)
1310 p.expect_keyword(keywords::Fn);
1312 let ident = p.parse_ident();
1313 let mut generics = p.parse_generics();
1315 let (explicit_self, d) = p.parse_fn_decl_with_self(|p| {
1316 // This is somewhat dubious; We don't want to allow
1317 // argument names to be left off if there is a
1319 p.parse_arg_general(false)
1322 p.parse_where_clause(&mut generics);
1324 let hi = p.last_span.hi;
1328 debug!("parse_trait_methods(): parsing required method");
1329 RequiredMethod(TypeMethod {
1336 explicit_self: explicit_self,
1337 id: ast::DUMMY_NODE_ID,
1338 span: mk_sp(lo, hi),
1342 token::OpenDelim(token::Brace) => {
1343 debug!("parse_trait_methods(): parsing provided method");
1344 let (inner_attrs, body) =
1345 p.parse_inner_attrs_and_block();
1346 let mut attrs = attrs;
1347 attrs.push_all(&inner_attrs[]);
1348 ProvidedMethod(P(ast::Method {
1350 id: ast::DUMMY_NODE_ID,
1351 span: mk_sp(lo, hi),
1352 node: ast::MethDecl(ident,
1364 let token_str = p.this_token_to_string();
1365 p.fatal(&format!("expected `;` or `{{`, found `{}`",
1373 /// Parse a possibly mutable type
1374 pub fn parse_mt(&mut self) -> MutTy {
1375 let mutbl = self.parse_mutability();
1376 let t = self.parse_ty();
1377 MutTy { ty: t, mutbl: mutbl }
1380 /// Parse optional return type [ -> TY ] in function decl
1381 pub fn parse_ret_ty(&mut self) -> FunctionRetTy {
1382 if self.eat(&token::RArrow) {
1383 if self.eat(&token::Not) {
1386 let t = self.parse_ty();
1388 // We used to allow `fn foo() -> &T + U`, but don't
1389 // anymore. If we see it, report a useful error. This
1390 // only makes sense because `parse_ret_ty` is only
1391 // used in fn *declarations*, not fn types or where
1392 // clauses (i.e., not when parsing something like
1393 // `FnMut() -> T + Send`, where the `+` is legal).
1394 if self.token == token::BinOp(token::Plus) {
1395 self.warn("deprecated syntax: `()` are required, see RFC 438 for details");
1401 let pos = self.span.lo;
1402 DefaultReturn(mk_sp(pos, pos))
1406 /// Parse a type in a context where `T1+T2` is allowed.
1407 pub fn parse_ty_sum(&mut self) -> P<Ty> {
1408 let lo = self.span.lo;
1409 let lhs = self.parse_ty();
1411 if !self.eat(&token::BinOp(token::Plus)) {
1415 let bounds = self.parse_ty_param_bounds(BoundParsingMode::Bare);
1417 // In type grammar, `+` is treated like a binary operator,
1418 // and hence both L and R side are required.
1419 if bounds.len() == 0 {
1420 let last_span = self.last_span;
1421 self.span_err(last_span,
1422 "at least one type parameter bound \
1423 must be specified");
1426 let sp = mk_sp(lo, self.last_span.hi);
1427 let sum = ast::TyObjectSum(lhs, bounds);
1428 P(Ty {id: ast::DUMMY_NODE_ID, node: sum, span: sp})
1432 pub fn parse_ty(&mut self) -> P<Ty> {
1433 maybe_whole!(no_clone self, NtTy);
1435 let lo = self.span.lo;
1437 let t = if self.check(&token::OpenDelim(token::Paren)) {
1440 // (t) is a parenthesized ty
1441 // (t,) is the type of a tuple with only one field,
1443 let mut ts = vec![];
1444 let mut last_comma = false;
1445 while self.token != token::CloseDelim(token::Paren) {
1446 ts.push(self.parse_ty_sum());
1447 if self.check(&token::Comma) {
1456 self.expect(&token::CloseDelim(token::Paren));
1457 if ts.len() == 1 && !last_comma {
1458 TyParen(ts.into_iter().nth(0).unwrap())
1462 } else if self.check(&token::BinOp(token::Star)) {
1463 // STAR POINTER (bare pointer?)
1465 TyPtr(self.parse_ptr())
1466 } else if self.check(&token::OpenDelim(token::Bracket)) {
1468 self.expect(&token::OpenDelim(token::Bracket));
1469 let t = self.parse_ty_sum();
1471 // Parse the `; e` in `[ i32; e ]`
1472 // where `e` is a const expression
1473 let t = match self.maybe_parse_fixed_length_of_vec() {
1475 Some(suffix) => TyFixedLengthVec(t, suffix)
1477 self.expect(&token::CloseDelim(token::Bracket));
1479 } else if self.check(&token::BinOp(token::And)) ||
1480 self.token == token::AndAnd {
1483 self.parse_borrowed_pointee()
1484 } else if self.token.is_keyword(keywords::For) {
1485 self.parse_for_in_type()
1486 } else if self.token_is_bare_fn_keyword() ||
1487 self.token_is_closure_keyword() {
1488 // BARE FUNCTION OR CLOSURE
1489 self.parse_ty_bare_fn_or_ty_closure(Vec::new())
1490 } else if self.check(&token::BinOp(token::Or)) ||
1491 self.token == token::OrOr ||
1492 (self.token == token::Lt &&
1493 self.look_ahead(1, |t| {
1494 *t == token::Gt || t.is_lifetime()
1497 self.parse_ty_closure(Vec::new())
1498 } else if self.eat_keyword(keywords::Typeof) {
1500 // In order to not be ambiguous, the type must be surrounded by parens.
1501 self.expect(&token::OpenDelim(token::Paren));
1502 let e = self.parse_expr();
1503 self.expect(&token::CloseDelim(token::Paren));
1505 } else if self.eat_keyword(keywords::Proc) {
1506 self.parse_proc_type(Vec::new())
1507 } else if self.eat_lt() {
1508 // QUALIFIED PATH `<TYPE as TRAIT_REF>::item`
1509 let self_type = self.parse_ty_sum();
1510 self.expect_keyword(keywords::As);
1511 let trait_ref = self.parse_trait_ref();
1512 self.expect(&token::Gt);
1513 self.expect(&token::ModSep);
1514 let item_name = self.parse_ident();
1516 self_type: self_type,
1517 trait_ref: P(trait_ref),
1518 item_path: ast::PathSegment {
1519 identifier: item_name,
1520 parameters: ast::PathParameters::none()
1523 } else if self.check(&token::ModSep) ||
1524 self.token.is_ident() ||
1525 self.token.is_path() {
1527 self.parse_ty_path()
1528 } else if self.eat(&token::Underscore) {
1529 // TYPE TO BE INFERRED
1532 let this_token_str = self.this_token_to_string();
1533 let msg = format!("expected type, found `{}`", this_token_str);
1537 let sp = mk_sp(lo, self.last_span.hi);
1538 P(Ty {id: ast::DUMMY_NODE_ID, node: t, span: sp})
1541 pub fn parse_borrowed_pointee(&mut self) -> Ty_ {
1542 // look for `&'lt` or `&'foo ` and interpret `foo` as the region name:
1543 let opt_lifetime = self.parse_opt_lifetime();
1545 let mt = self.parse_mt();
1546 return TyRptr(opt_lifetime, mt);
1549 pub fn parse_ptr(&mut self) -> MutTy {
1550 let mutbl = if self.eat_keyword(keywords::Mut) {
1552 } else if self.eat_keyword(keywords::Const) {
1555 let span = self.last_span;
1557 "bare raw pointers are no longer allowed, you should \
1558 likely use `*mut T`, but otherwise `*T` is now \
1559 known as `*const T`");
1562 let t = self.parse_ty();
1563 MutTy { ty: t, mutbl: mutbl }
1566 pub fn is_named_argument(&mut self) -> bool {
1567 let offset = match self.token {
1568 token::BinOp(token::And) => 1,
1570 _ if self.token.is_keyword(keywords::Mut) => 1,
1574 debug!("parser is_named_argument offset:{}", offset);
1577 is_plain_ident_or_underscore(&self.token)
1578 && self.look_ahead(1, |t| *t == token::Colon)
1580 self.look_ahead(offset, |t| is_plain_ident_or_underscore(t))
1581 && self.look_ahead(offset + 1, |t| *t == token::Colon)
1585 /// This version of parse arg doesn't necessarily require
1586 /// identifier names.
1587 pub fn parse_arg_general(&mut self, require_name: bool) -> Arg {
1588 let pat = if require_name || self.is_named_argument() {
1589 debug!("parse_arg_general parse_pat (require_name:{})",
1591 let pat = self.parse_pat();
1593 self.expect(&token::Colon);
1596 debug!("parse_arg_general ident_to_pat");
1597 ast_util::ident_to_pat(ast::DUMMY_NODE_ID,
1599 special_idents::invalid)
1602 let t = self.parse_ty_sum();
1607 id: ast::DUMMY_NODE_ID,
1611 /// Parse a single function argument
1612 pub fn parse_arg(&mut self) -> Arg {
1613 self.parse_arg_general(true)
1616 /// Parse an argument in a lambda header e.g. |arg, arg|
1617 pub fn parse_fn_block_arg(&mut self) -> Arg {
1618 let pat = self.parse_pat();
1619 let t = if self.eat(&token::Colon) {
1623 id: ast::DUMMY_NODE_ID,
1625 span: mk_sp(self.span.lo, self.span.hi),
1631 id: ast::DUMMY_NODE_ID
1635 pub fn maybe_parse_fixed_length_of_vec(&mut self) -> Option<P<ast::Expr>> {
1636 if self.check(&token::Semi) {
1638 Some(self.parse_expr())
1644 /// Matches token_lit = LIT_INTEGER | ...
1645 pub fn lit_from_token(&self, tok: &token::Token) -> Lit_ {
1647 token::Interpolated(token::NtExpr(ref v)) => {
1649 ExprLit(ref lit) => { lit.node.clone() }
1650 _ => { self.unexpected_last(tok); }
1653 token::Literal(lit, suf) => {
1654 let (suffix_illegal, out) = match lit {
1655 token::Byte(i) => (true, LitByte(parse::byte_lit(i.as_str()).0)),
1656 token::Char(i) => (true, LitChar(parse::char_lit(i.as_str()).0)),
1658 // there are some valid suffixes for integer and
1659 // float literals, so all the handling is done
1661 token::Integer(s) => {
1662 (false, parse::integer_lit(s.as_str(),
1663 suf.as_ref().map(|s| s.as_str()),
1664 &self.sess.span_diagnostic,
1667 token::Float(s) => {
1668 (false, parse::float_lit(s.as_str(),
1669 suf.as_ref().map(|s| s.as_str()),
1670 &self.sess.span_diagnostic,
1676 LitStr(token::intern_and_get_ident(parse::str_lit(s.as_str()).as_slice()),
1679 token::StrRaw(s, n) => {
1682 token::intern_and_get_ident(&parse::raw_str_lit(s.as_str())[]),
1686 (true, LitBinary(parse::binary_lit(i.as_str()))),
1687 token::BinaryRaw(i, _) =>
1689 LitBinary(Rc::new(i.as_str().as_bytes().iter().map(|&x| x).collect()))),
1693 let sp = self.last_span;
1694 self.expect_no_suffix(sp, &*format!("{} literal", lit.short_name()), suf)
1699 _ => { self.unexpected_last(tok); }
1703 /// Matches lit = true | false | token_lit
1704 pub fn parse_lit(&mut self) -> Lit {
1705 let lo = self.span.lo;
1706 let lit = if self.eat_keyword(keywords::True) {
1708 } else if self.eat_keyword(keywords::False) {
1711 let token = self.bump_and_get();
1712 let lit = self.lit_from_token(&token);
1715 codemap::Spanned { node: lit, span: mk_sp(lo, self.last_span.hi) }
1718 /// matches '-' lit | lit
1719 pub fn parse_literal_maybe_minus(&mut self) -> P<Expr> {
1720 let minus_lo = self.span.lo;
1721 let minus_present = self.eat(&token::BinOp(token::Minus));
1723 let lo = self.span.lo;
1724 let literal = P(self.parse_lit());
1725 let hi = self.span.hi;
1726 let expr = self.mk_expr(lo, hi, ExprLit(literal));
1729 let minus_hi = self.span.hi;
1730 let unary = self.mk_unary(UnNeg, expr);
1731 self.mk_expr(minus_lo, minus_hi, unary)
1737 /// Parses a path and optional type parameter bounds, depending on the
1738 /// mode. The `mode` parameter determines whether lifetimes, types, and/or
1739 /// bounds are permitted and whether `::` must precede type parameter
1741 pub fn parse_path(&mut self, mode: PathParsingMode) -> ast::Path {
1742 // Check for a whole path...
1743 let found = match self.token {
1744 token::Interpolated(token::NtPath(_)) => Some(self.bump_and_get()),
1747 if let Some(token::Interpolated(token::NtPath(box path))) = found {
1751 let lo = self.span.lo;
1752 let is_global = self.eat(&token::ModSep);
1754 // Parse any number of segments and bound sets. A segment is an
1755 // identifier followed by an optional lifetime and a set of types.
1756 // A bound set is a set of type parameter bounds.
1757 let segments = match mode {
1758 LifetimeAndTypesWithoutColons => {
1759 self.parse_path_segments_without_colons()
1761 LifetimeAndTypesWithColons => {
1762 self.parse_path_segments_with_colons()
1765 self.parse_path_segments_without_types()
1769 // Assemble the span.
1770 let span = mk_sp(lo, self.last_span.hi);
1772 // Assemble the result.
1781 /// - `a::b<T,U>::c<V,W>`
1782 /// - `a::b<T,U>::c(V) -> W`
1783 /// - `a::b<T,U>::c(V)`
1784 pub fn parse_path_segments_without_colons(&mut self) -> Vec<ast::PathSegment> {
1785 let mut segments = Vec::new();
1787 // First, parse an identifier.
1788 let identifier = self.parse_ident();
1790 // Parse types, optionally.
1791 let parameters = if self.eat_lt() {
1792 let (lifetimes, types, bindings) = self.parse_generic_values_after_lt();
1794 ast::AngleBracketedParameters(ast::AngleBracketedParameterData {
1795 lifetimes: lifetimes,
1796 types: OwnedSlice::from_vec(types),
1797 bindings: OwnedSlice::from_vec(bindings),
1799 } else if self.eat(&token::OpenDelim(token::Paren)) {
1800 let inputs = self.parse_seq_to_end(
1801 &token::CloseDelim(token::Paren),
1802 seq_sep_trailing_allowed(token::Comma),
1803 |p| p.parse_ty_sum());
1805 let output_ty = if self.eat(&token::RArrow) {
1806 Some(self.parse_ty())
1811 ast::ParenthesizedParameters(ast::ParenthesizedParameterData {
1816 ast::PathParameters::none()
1819 // Assemble and push the result.
1820 segments.push(ast::PathSegment { identifier: identifier,
1821 parameters: parameters });
1823 // Continue only if we see a `::`
1824 if !self.eat(&token::ModSep) {
1831 /// - `a::b::<T,U>::c`
1832 pub fn parse_path_segments_with_colons(&mut self) -> Vec<ast::PathSegment> {
1833 let mut segments = Vec::new();
1835 // First, parse an identifier.
1836 let identifier = self.parse_ident();
1838 // If we do not see a `::`, stop.
1839 if !self.eat(&token::ModSep) {
1840 segments.push(ast::PathSegment {
1841 identifier: identifier,
1842 parameters: ast::PathParameters::none()
1847 // Check for a type segment.
1849 // Consumed `a::b::<`, go look for types
1850 let (lifetimes, types, bindings) = self.parse_generic_values_after_lt();
1851 segments.push(ast::PathSegment {
1852 identifier: identifier,
1853 parameters: ast::AngleBracketedParameters(ast::AngleBracketedParameterData {
1854 lifetimes: lifetimes,
1855 types: OwnedSlice::from_vec(types),
1856 bindings: OwnedSlice::from_vec(bindings),
1860 // Consumed `a::b::<T,U>`, check for `::` before proceeding
1861 if !self.eat(&token::ModSep) {
1865 // Consumed `a::`, go look for `b`
1866 segments.push(ast::PathSegment {
1867 identifier: identifier,
1868 parameters: ast::PathParameters::none(),
1877 pub fn parse_path_segments_without_types(&mut self) -> Vec<ast::PathSegment> {
1878 let mut segments = Vec::new();
1880 // First, parse an identifier.
1881 let identifier = self.parse_ident();
1883 // Assemble and push the result.
1884 segments.push(ast::PathSegment {
1885 identifier: identifier,
1886 parameters: ast::PathParameters::none()
1889 // If we do not see a `::`, stop.
1890 if !self.eat(&token::ModSep) {
1896 /// parses 0 or 1 lifetime
1897 pub fn parse_opt_lifetime(&mut self) -> Option<ast::Lifetime> {
1899 token::Lifetime(..) => {
1900 Some(self.parse_lifetime())
1908 /// Parses a single lifetime
1909 /// Matches lifetime = LIFETIME
1910 pub fn parse_lifetime(&mut self) -> ast::Lifetime {
1912 token::Lifetime(i) => {
1913 let span = self.span;
1915 return ast::Lifetime {
1916 id: ast::DUMMY_NODE_ID,
1922 self.fatal(&format!("expected a lifetime name")[]);
1927 /// Parses `lifetime_defs = [ lifetime_defs { ',' lifetime_defs } ]` where `lifetime_def =
1928 /// lifetime [':' lifetimes]`
1929 pub fn parse_lifetime_defs(&mut self) -> Vec<ast::LifetimeDef> {
1931 let mut res = Vec::new();
1934 token::Lifetime(_) => {
1935 let lifetime = self.parse_lifetime();
1937 if self.eat(&token::Colon) {
1938 self.parse_lifetimes(token::BinOp(token::Plus))
1942 res.push(ast::LifetimeDef { lifetime: lifetime,
1952 token::Comma => { self.bump(); }
1953 token::Gt => { return res; }
1954 token::BinOp(token::Shr) => { return res; }
1956 let this_token_str = self.this_token_to_string();
1957 let msg = format!("expected `,` or `>` after lifetime \
1966 /// matches lifetimes = ( lifetime ) | ( lifetime , lifetimes ) actually, it matches the empty
1967 /// one too, but putting that in there messes up the grammar....
1969 /// Parses zero or more comma separated lifetimes. Expects each lifetime to be followed by
1970 /// either a comma or `>`. Used when parsing type parameter lists, where we expect something
1971 /// like `<'a, 'b, T>`.
1972 pub fn parse_lifetimes(&mut self, sep: token::Token) -> Vec<ast::Lifetime> {
1974 let mut res = Vec::new();
1977 token::Lifetime(_) => {
1978 res.push(self.parse_lifetime());
1985 if self.token != sep {
1993 /// Parse mutability declaration (mut/const/imm)
1994 pub fn parse_mutability(&mut self) -> Mutability {
1995 if self.eat_keyword(keywords::Mut) {
2002 /// Parse ident COLON expr
2003 pub fn parse_field(&mut self) -> Field {
2004 let lo = self.span.lo;
2005 let i = self.parse_ident();
2006 let hi = self.last_span.hi;
2007 self.expect(&token::Colon);
2008 let e = self.parse_expr();
2010 ident: spanned(lo, hi, i),
2011 span: mk_sp(lo, e.span.hi),
2016 pub fn mk_expr(&mut self, lo: BytePos, hi: BytePos, node: Expr_) -> P<Expr> {
2018 id: ast::DUMMY_NODE_ID,
2020 span: mk_sp(lo, hi),
2024 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::Expr_ {
2025 ExprUnary(unop, expr)
2028 pub fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::Expr_ {
2029 ExprBinary(binop, lhs, rhs)
2032 pub fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::Expr_ {
2036 fn mk_method_call(&mut self,
2037 ident: ast::SpannedIdent,
2041 ExprMethodCall(ident, tps, args)
2044 pub fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::Expr_ {
2045 ExprIndex(expr, idx)
2048 pub fn mk_range(&mut self,
2049 start: Option<P<Expr>>,
2050 end: Option<P<Expr>>)
2052 ExprRange(start, end)
2055 pub fn mk_field(&mut self, expr: P<Expr>, ident: ast::SpannedIdent) -> ast::Expr_ {
2056 ExprField(expr, ident)
2059 pub fn mk_tup_field(&mut self, expr: P<Expr>, idx: codemap::Spanned<usize>) -> ast::Expr_ {
2060 ExprTupField(expr, idx)
2063 pub fn mk_assign_op(&mut self, binop: ast::BinOp,
2064 lhs: P<Expr>, rhs: P<Expr>) -> ast::Expr_ {
2065 ExprAssignOp(binop, lhs, rhs)
2068 pub fn mk_mac_expr(&mut self, lo: BytePos, hi: BytePos, m: Mac_) -> P<Expr> {
2070 id: ast::DUMMY_NODE_ID,
2071 node: ExprMac(codemap::Spanned {node: m, span: mk_sp(lo, hi)}),
2072 span: mk_sp(lo, hi),
2076 pub fn mk_lit_u32(&mut self, i: u32) -> P<Expr> {
2077 let span = &self.span;
2078 let lv_lit = P(codemap::Spanned {
2079 node: LitInt(i as u64, ast::UnsignedIntLit(TyU32)),
2084 id: ast::DUMMY_NODE_ID,
2085 node: ExprLit(lv_lit),
2090 fn expect_open_delim(&mut self) -> token::DelimToken {
2092 token::OpenDelim(delim) => {
2096 _ => self.fatal("expected open delimiter"),
2100 /// At the bottom (top?) of the precedence hierarchy,
2101 /// parse things like parenthesized exprs,
2102 /// macros, return, etc.
2103 pub fn parse_bottom_expr(&mut self) -> P<Expr> {
2104 maybe_whole_expr!(self);
2106 let lo = self.span.lo;
2107 let mut hi = self.span.hi;
2111 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2113 token::OpenDelim(token::Paren) => {
2116 // (e) is parenthesized e
2117 // (e,) is a tuple with only one field, e
2118 let mut es = vec![];
2119 let mut trailing_comma = false;
2120 while self.token != token::CloseDelim(token::Paren) {
2121 es.push(self.parse_expr());
2122 self.commit_expr(&**es.last().unwrap(), &[],
2123 &[token::Comma, token::CloseDelim(token::Paren)]);
2124 if self.check(&token::Comma) {
2125 trailing_comma = true;
2129 trailing_comma = false;
2136 return if es.len() == 1 && !trailing_comma {
2137 self.mk_expr(lo, hi, ExprParen(es.into_iter().nth(0).unwrap()))
2139 self.mk_expr(lo, hi, ExprTup(es))
2142 token::OpenDelim(token::Brace) => {
2144 let blk = self.parse_block_tail(lo, DefaultBlock);
2145 return self.mk_expr(blk.span.lo, blk.span.hi,
2148 token::BinOp(token::Or) | token::OrOr => {
2149 return self.parse_lambda_expr(CaptureByRef);
2151 // FIXME #13626: Should be able to stick in
2152 // token::SELF_KEYWORD_NAME
2153 token::Ident(id @ ast::Ident {
2154 name: ast::Name(token::SELF_KEYWORD_NAME_NUM),
2156 }, token::Plain) => {
2158 let path = ast_util::ident_to_path(mk_sp(lo, hi), id);
2159 ex = ExprPath(path);
2160 hi = self.last_span.hi;
2162 token::OpenDelim(token::Bracket) => {
2165 if self.check(&token::CloseDelim(token::Bracket)) {
2168 ex = ExprVec(Vec::new());
2171 let first_expr = self.parse_expr();
2172 if self.check(&token::Semi) {
2173 // Repeating vector syntax: [ 0; 512 ]
2175 let count = self.parse_expr();
2176 self.expect(&token::CloseDelim(token::Bracket));
2177 ex = ExprRepeat(first_expr, count);
2178 } else if self.check(&token::Comma) {
2179 // Vector with two or more elements.
2181 let remaining_exprs = self.parse_seq_to_end(
2182 &token::CloseDelim(token::Bracket),
2183 seq_sep_trailing_allowed(token::Comma),
2186 let mut exprs = vec!(first_expr);
2187 exprs.extend(remaining_exprs.into_iter());
2188 ex = ExprVec(exprs);
2190 // Vector with one element.
2191 self.expect(&token::CloseDelim(token::Bracket));
2192 ex = ExprVec(vec!(first_expr));
2195 hi = self.last_span.hi;
2199 // QUALIFIED PATH `<TYPE as TRAIT_REF>::item::<'a, T>`
2200 let self_type = self.parse_ty_sum();
2201 self.expect_keyword(keywords::As);
2202 let trait_ref = self.parse_trait_ref();
2203 self.expect(&token::Gt);
2204 self.expect(&token::ModSep);
2205 let item_name = self.parse_ident();
2206 let parameters = if self.eat(&token::ModSep) {
2208 // Consumed `item::<`, go look for types
2209 let (lifetimes, types, bindings) =
2210 self.parse_generic_values_after_lt();
2211 ast::AngleBracketedParameters(ast::AngleBracketedParameterData {
2212 lifetimes: lifetimes,
2213 types: OwnedSlice::from_vec(types),
2214 bindings: OwnedSlice::from_vec(bindings),
2217 ast::PathParameters::none()
2219 let hi = self.span.hi;
2220 return self.mk_expr(lo, hi, ExprQPath(P(QPath {
2221 self_type: self_type,
2222 trait_ref: P(trait_ref),
2223 item_path: ast::PathSegment {
2224 identifier: item_name,
2225 parameters: parameters
2229 if self.eat_keyword(keywords::Move) {
2230 return self.parse_lambda_expr(CaptureByValue);
2232 if self.eat_keyword(keywords::Proc) {
2233 let span = self.last_span;
2234 let _ = self.parse_proc_decl();
2235 let _ = self.parse_expr();
2236 return self.obsolete_expr(span, ObsoleteSyntax::ProcExpr);
2238 if self.eat_keyword(keywords::If) {
2239 return self.parse_if_expr();
2241 if self.eat_keyword(keywords::For) {
2242 return self.parse_for_expr(None);
2244 if self.eat_keyword(keywords::While) {
2245 return self.parse_while_expr(None);
2247 if self.token.is_lifetime() {
2248 let lifetime = self.get_lifetime();
2250 self.expect(&token::Colon);
2251 if self.eat_keyword(keywords::While) {
2252 return self.parse_while_expr(Some(lifetime))
2254 if self.eat_keyword(keywords::For) {
2255 return self.parse_for_expr(Some(lifetime))
2257 if self.eat_keyword(keywords::Loop) {
2258 return self.parse_loop_expr(Some(lifetime))
2260 self.fatal("expected `while`, `for`, or `loop` after a label")
2262 if self.eat_keyword(keywords::Loop) {
2263 return self.parse_loop_expr(None);
2265 if self.eat_keyword(keywords::Continue) {
2266 let lo = self.span.lo;
2267 let ex = if self.token.is_lifetime() {
2268 let lifetime = self.get_lifetime();
2270 ExprAgain(Some(lifetime))
2274 let hi = self.span.hi;
2275 return self.mk_expr(lo, hi, ex);
2277 if self.eat_keyword(keywords::Match) {
2278 return self.parse_match_expr();
2280 if self.eat_keyword(keywords::Unsafe) {
2281 return self.parse_block_expr(
2283 UnsafeBlock(ast::UserProvided));
2285 if self.eat_keyword(keywords::Return) {
2286 // RETURN expression
2287 if self.token.can_begin_expr() {
2288 let e = self.parse_expr();
2290 ex = ExprRet(Some(e));
2294 } else if self.eat_keyword(keywords::Break) {
2296 if self.token.is_lifetime() {
2297 let lifetime = self.get_lifetime();
2299 ex = ExprBreak(Some(lifetime));
2301 ex = ExprBreak(None);
2304 } else if self.check(&token::ModSep) ||
2305 self.token.is_ident() &&
2306 !self.token.is_keyword(keywords::True) &&
2307 !self.token.is_keyword(keywords::False) {
2309 self.parse_path(LifetimeAndTypesWithColons);
2311 // `!`, as an operator, is prefix, so we know this isn't that
2312 if self.check(&token::Not) {
2313 // MACRO INVOCATION expression
2316 let delim = self.expect_open_delim();
2317 let tts = self.parse_seq_to_end(
2318 &token::CloseDelim(delim),
2320 |p| p.parse_token_tree());
2321 let hi = self.span.hi;
2323 return self.mk_mac_expr(lo,
2329 if self.check(&token::OpenDelim(token::Brace)) {
2330 // This is a struct literal, unless we're prohibited
2331 // from parsing struct literals here.
2332 if !self.restrictions.contains(RESTRICTION_NO_STRUCT_LITERAL) {
2333 // It's a struct literal.
2335 let mut fields = Vec::new();
2336 let mut base = None;
2338 while self.token != token::CloseDelim(token::Brace) {
2339 if self.eat(&token::DotDot) {
2340 base = Some(self.parse_expr());
2344 fields.push(self.parse_field());
2345 self.commit_expr(&*fields.last().unwrap().expr,
2347 &[token::CloseDelim(token::Brace)]);
2350 if fields.len() == 0 && base.is_none() {
2351 let last_span = self.last_span;
2352 self.span_err(last_span,
2353 "structure literal must either \
2354 have at least one field or use \
2355 functional structure update \
2360 self.expect(&token::CloseDelim(token::Brace));
2361 ex = ExprStruct(pth, fields, base);
2362 return self.mk_expr(lo, hi, ex);
2369 // other literal expression
2370 let lit = self.parse_lit();
2372 ex = ExprLit(P(lit));
2377 return self.mk_expr(lo, hi, ex);
2380 /// Parse a block or unsafe block
2381 pub fn parse_block_expr(&mut self, lo: BytePos, blk_mode: BlockCheckMode)
2383 self.expect(&token::OpenDelim(token::Brace));
2384 let blk = self.parse_block_tail(lo, blk_mode);
2385 return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk));
2388 /// parse a.b or a(13) or a[4] or just a
2389 pub fn parse_dot_or_call_expr(&mut self) -> P<Expr> {
2390 let b = self.parse_bottom_expr();
2391 self.parse_dot_or_call_expr_with(b)
2394 pub fn parse_dot_or_call_expr_with(&mut self, e0: P<Expr>) -> P<Expr> {
2400 if self.eat(&token::Dot) {
2402 token::Ident(i, _) => {
2403 let dot = self.last_span.hi;
2406 let (_, tys, bindings) = if self.eat(&token::ModSep) {
2408 self.parse_generic_values_after_lt()
2410 (Vec::new(), Vec::new(), Vec::new())
2413 if bindings.len() > 0 {
2414 let last_span = self.last_span;
2415 self.span_err(last_span, "type bindings are only permitted on trait paths");
2418 // expr.f() method call
2420 token::OpenDelim(token::Paren) => {
2421 let mut es = self.parse_unspanned_seq(
2422 &token::OpenDelim(token::Paren),
2423 &token::CloseDelim(token::Paren),
2424 seq_sep_trailing_allowed(token::Comma),
2427 hi = self.last_span.hi;
2430 let id = spanned(dot, hi, i);
2431 let nd = self.mk_method_call(id, tys, es);
2432 e = self.mk_expr(lo, hi, nd);
2435 if !tys.is_empty() {
2436 let last_span = self.last_span;
2437 self.span_err(last_span,
2438 "field expressions may not \
2439 have type parameters");
2442 let id = spanned(dot, hi, i);
2443 let field = self.mk_field(e, id);
2444 e = self.mk_expr(lo, hi, field);
2448 token::Literal(token::Integer(n), suf) => {
2451 // A tuple index may not have a suffix
2452 self.expect_no_suffix(sp, "tuple index", suf);
2454 let dot = self.last_span.hi;
2458 let index = n.as_str().parse::<usize>();
2461 let id = spanned(dot, hi, n);
2462 let field = self.mk_tup_field(e, id);
2463 e = self.mk_expr(lo, hi, field);
2466 let last_span = self.last_span;
2467 self.span_err(last_span, "invalid tuple or tuple struct index");
2471 token::Literal(token::Float(n), _suf) => {
2473 let last_span = self.last_span;
2474 let fstr = n.as_str();
2475 self.span_err(last_span,
2476 &format!("unexpected token: `{}`", n.as_str())[]);
2477 if fstr.chars().all(|x| "0123456789.".contains_char(x)) {
2478 let float = match fstr.parse::<f64>() {
2482 self.span_help(last_span,
2483 &format!("try parenthesizing the first index; e.g., `(foo.{}){}`",
2484 float.trunc() as usize,
2485 &float.fract().to_string()[1..])[]);
2487 self.abort_if_errors();
2490 _ => self.unexpected()
2494 if self.expr_is_complete(&*e) { break; }
2497 token::OpenDelim(token::Paren) => {
2498 let es = self.parse_unspanned_seq(
2499 &token::OpenDelim(token::Paren),
2500 &token::CloseDelim(token::Paren),
2501 seq_sep_trailing_allowed(token::Comma),
2504 hi = self.last_span.hi;
2506 let nd = self.mk_call(e, es);
2507 e = self.mk_expr(lo, hi, nd);
2511 // Could be either an index expression or a slicing expression.
2512 token::OpenDelim(token::Bracket) => {
2513 let bracket_pos = self.span.lo;
2516 let mut found_dotdot = false;
2517 if self.token == token::DotDot &&
2518 self.look_ahead(1, |t| t == &token::CloseDelim(token::Bracket)) {
2519 // Using expr[..], which is a mistake, should be expr[]
2522 found_dotdot = true;
2525 if found_dotdot || self.eat(&token::CloseDelim(token::Bracket)) {
2526 // No expression, expand to a FullRange
2527 // FIXME(#20516) It would be better to use a lang item or
2528 // something for FullRange.
2529 hi = self.last_span.hi;
2530 let range = ExprStruct(ident_to_path(mk_sp(lo, hi),
2531 token::special_idents::FullRange),
2534 let ix = self.mk_expr(bracket_pos, hi, range);
2535 let index = self.mk_index(e, ix);
2536 e = self.mk_expr(lo, hi, index)
2538 let ix = self.parse_expr();
2540 self.commit_expr_expecting(&*ix, token::CloseDelim(token::Bracket));
2541 let index = self.mk_index(e, ix);
2542 e = self.mk_expr(lo, hi, index)
2546 self.span_err(e.span, "incorrect slicing expression: `[..]`");
2547 self.span_note(e.span,
2548 "use `&expr[]` to construct a slice of the whole of expr");
2557 // Parse unquoted tokens after a `$` in a token tree
2558 fn parse_unquoted(&mut self) -> TokenTree {
2559 let mut sp = self.span;
2560 let (name, namep) = match self.token {
2564 if self.token == token::OpenDelim(token::Paren) {
2565 let Spanned { node: seq, span: seq_span } = self.parse_seq(
2566 &token::OpenDelim(token::Paren),
2567 &token::CloseDelim(token::Paren),
2569 |p| p.parse_token_tree()
2571 let (sep, repeat) = self.parse_sep_and_kleene_op();
2572 let name_num = macro_parser::count_names(seq.as_slice());
2573 return TtSequence(mk_sp(sp.lo, seq_span.hi),
2574 Rc::new(SequenceRepetition {
2578 num_captures: name_num
2580 } else if self.token.is_keyword_allow_following_colon(keywords::Crate) {
2582 return TtToken(sp, SpecialVarNt(SpecialMacroVar::CrateMacroVar));
2584 sp = mk_sp(sp.lo, self.span.hi);
2585 let namep = match self.token { token::Ident(_, p) => p, _ => token::Plain };
2586 let name = self.parse_ident();
2590 token::SubstNt(name, namep) => {
2596 // continue by trying to parse the `:ident` after `$name`
2597 if self.token == token::Colon && self.look_ahead(1, |t| t.is_ident() &&
2598 !t.is_strict_keyword() &&
2599 !t.is_reserved_keyword()) {
2601 sp = mk_sp(sp.lo, self.span.hi);
2602 let kindp = match self.token { token::Ident(_, p) => p, _ => token::Plain };
2603 let nt_kind = self.parse_ident();
2604 TtToken(sp, MatchNt(name, nt_kind, namep, kindp))
2606 TtToken(sp, SubstNt(name, namep))
2610 pub fn check_unknown_macro_variable(&mut self) {
2611 if self.quote_depth == 0us {
2613 token::SubstNt(name, _) =>
2614 self.fatal(&format!("unknown macro variable `{}`",
2615 token::get_ident(name))[]),
2621 /// Parse an optional separator followed by a Kleene-style
2622 /// repetition token (+ or *).
2623 pub fn parse_sep_and_kleene_op(&mut self) -> (Option<token::Token>, ast::KleeneOp) {
2624 fn parse_kleene_op(parser: &mut Parser) -> Option<ast::KleeneOp> {
2625 match parser.token {
2626 token::BinOp(token::Star) => {
2628 Some(ast::ZeroOrMore)
2630 token::BinOp(token::Plus) => {
2632 Some(ast::OneOrMore)
2638 match parse_kleene_op(self) {
2639 Some(kleene_op) => return (None, kleene_op),
2643 let separator = self.bump_and_get();
2644 match parse_kleene_op(self) {
2645 Some(zerok) => (Some(separator), zerok),
2646 None => self.fatal("expected `*` or `+`")
2650 /// parse a single token tree from the input.
2651 pub fn parse_token_tree(&mut self) -> TokenTree {
2652 // FIXME #6994: currently, this is too eager. It
2653 // parses token trees but also identifies TtSequence's
2654 // and token::SubstNt's; it's too early to know yet
2655 // whether something will be a nonterminal or a seq
2657 maybe_whole!(deref self, NtTT);
2659 // this is the fall-through for the 'match' below.
2660 // invariants: the current token is not a left-delimiter,
2661 // not an EOF, and not the desired right-delimiter (if
2662 // it were, parse_seq_to_before_end would have prevented
2663 // reaching this point.
2664 fn parse_non_delim_tt_tok(p: &mut Parser) -> TokenTree {
2665 maybe_whole!(deref p, NtTT);
2667 token::CloseDelim(_) => {
2668 // This is a conservative error: only report the last unclosed delimiter. The
2669 // previous unclosed delimiters could actually be closed! The parser just hasn't
2670 // gotten to them yet.
2671 match p.open_braces.last() {
2673 Some(&sp) => p.span_note(sp, "unclosed delimiter"),
2675 let token_str = p.this_token_to_string();
2676 p.fatal(&format!("incorrect close delimiter: `{}`",
2679 /* we ought to allow different depths of unquotation */
2680 token::Dollar | token::SubstNt(..) if p.quote_depth > 0us => {
2684 TtToken(p.span, p.bump_and_get())
2691 let open_braces = self.open_braces.clone();
2692 for sp in open_braces.iter() {
2693 self.span_help(*sp, "did you mean to close this delimiter?");
2695 // There shouldn't really be a span, but it's easier for the test runner
2696 // if we give it one
2697 self.fatal("this file contains an un-closed delimiter ");
2699 token::OpenDelim(delim) => {
2700 // The span for beginning of the delimited section
2701 let pre_span = self.span;
2703 // Parse the open delimiter.
2704 self.open_braces.push(self.span);
2705 let open_span = self.span;
2708 // Parse the token trees within the delimiters
2709 let tts = self.parse_seq_to_before_end(
2710 &token::CloseDelim(delim),
2712 |p| p.parse_token_tree()
2715 // Parse the close delimiter.
2716 let close_span = self.span;
2718 self.open_braces.pop().unwrap();
2720 // Expand to cover the entire delimited token tree
2721 let span = Span { hi: self.span.hi, ..pre_span };
2723 TtDelimited(span, Rc::new(Delimited {
2725 open_span: open_span,
2727 close_span: close_span,
2730 _ => parse_non_delim_tt_tok(self),
2734 // parse a stream of tokens into a list of TokenTree's,
2736 pub fn parse_all_token_trees(&mut self) -> Vec<TokenTree> {
2737 let mut tts = Vec::new();
2738 while self.token != token::Eof {
2739 tts.push(self.parse_token_tree());
2744 /// Parse a prefix-operator expr
2745 pub fn parse_prefix_expr(&mut self) -> P<Expr> {
2746 let lo = self.span.lo;
2749 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2754 let e = self.parse_prefix_expr();
2756 ex = self.mk_unary(UnNot, e);
2758 token::BinOp(token::Minus) => {
2760 let e = self.parse_prefix_expr();
2762 ex = self.mk_unary(UnNeg, e);
2764 token::BinOp(token::Star) => {
2766 let e = self.parse_prefix_expr();
2768 ex = self.mk_unary(UnDeref, e);
2770 token::BinOp(token::And) | token::AndAnd => {
2772 let m = self.parse_mutability();
2773 let e = self.parse_prefix_expr();
2775 ex = ExprAddrOf(m, e);
2777 token::Ident(_, _) => {
2778 if !self.token.is_keyword(keywords::Box) {
2779 return self.parse_dot_or_call_expr();
2782 let lo = self.span.lo;
2786 // Check for a place: `box(PLACE) EXPR`.
2787 if self.eat(&token::OpenDelim(token::Paren)) {
2788 // Support `box() EXPR` as the default.
2789 if !self.eat(&token::CloseDelim(token::Paren)) {
2790 let place = self.parse_expr();
2791 self.expect(&token::CloseDelim(token::Paren));
2792 // Give a suggestion to use `box()` when a parenthesised expression is used
2793 if !self.token.can_begin_expr() {
2794 let span = self.span;
2795 let this_token_to_string = self.this_token_to_string();
2797 &format!("expected expression, found `{}`",
2798 this_token_to_string)[]);
2799 let box_span = mk_sp(lo, self.last_span.hi);
2800 self.span_help(box_span,
2801 "perhaps you meant `box() (foo)` instead?");
2802 self.abort_if_errors();
2804 let subexpression = self.parse_prefix_expr();
2805 hi = subexpression.span.hi;
2806 ex = ExprBox(Some(place), subexpression);
2807 return self.mk_expr(lo, hi, ex);
2811 // Otherwise, we use the unique pointer default.
2812 let subexpression = self.parse_prefix_expr();
2813 hi = subexpression.span.hi;
2814 // FIXME (pnkfelix): After working out kinks with box
2815 // desugaring, should be `ExprBox(None, subexpression)`
2817 ex = self.mk_unary(UnUniq, subexpression);
2819 _ => return self.parse_dot_or_call_expr()
2821 return self.mk_expr(lo, hi, ex);
2824 /// Parse an expression of binops
2825 pub fn parse_binops(&mut self) -> P<Expr> {
2826 let prefix_expr = self.parse_prefix_expr();
2827 self.parse_more_binops(prefix_expr, 0)
2830 /// Parse an expression of binops of at least min_prec precedence
2831 pub fn parse_more_binops(&mut self, lhs: P<Expr>, min_prec: usize) -> P<Expr> {
2832 if self.expr_is_complete(&*lhs) { return lhs; }
2834 // Prevent dynamic borrow errors later on by limiting the
2835 // scope of the borrows.
2836 if self.token == token::BinOp(token::Or) &&
2837 self.restrictions.contains(RESTRICTION_NO_BAR_OP) {
2841 self.expected_tokens.push(TokenType::Operator);
2843 let cur_op_span = self.span;
2844 let cur_opt = self.token.to_binop();
2847 if ast_util::is_comparison_binop(cur_op) {
2848 self.check_no_chained_comparison(&*lhs, cur_op)
2850 let cur_prec = operator_prec(cur_op);
2851 if cur_prec >= min_prec {
2853 let expr = self.parse_prefix_expr();
2854 let rhs = self.parse_more_binops(expr, cur_prec + 1);
2855 let lhs_span = lhs.span;
2856 let rhs_span = rhs.span;
2857 let binary = self.mk_binary(codemap::respan(cur_op_span, cur_op), lhs, rhs);
2858 let bin = self.mk_expr(lhs_span.lo, rhs_span.hi, binary);
2859 self.parse_more_binops(bin, min_prec)
2865 if AS_PREC >= min_prec && self.eat_keyword(keywords::As) {
2866 let rhs = self.parse_ty();
2867 let _as = self.mk_expr(lhs.span.lo,
2869 ExprCast(lhs, rhs));
2870 self.parse_more_binops(_as, min_prec)
2878 /// Produce an error if comparison operators are chained (RFC #558).
2879 /// We only need to check lhs, not rhs, because all comparison ops
2880 /// have same precedence and are left-associative
2881 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: ast::BinOp_) {
2882 debug_assert!(ast_util::is_comparison_binop(outer_op));
2884 ExprBinary(op, _, _) if ast_util::is_comparison_binop(op.node) => {
2885 // respan to include both operators
2886 let op_span = mk_sp(op.span.lo, self.span.hi);
2887 self.span_err(op_span,
2888 "chained comparison operators require parentheses");
2889 if op.node == BiLt && outer_op == BiGt {
2890 self.span_help(op_span,
2891 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
2898 /// Parse an assignment expression....
2899 /// actually, this seems to be the main entry point for
2900 /// parsing an arbitrary expression.
2901 pub fn parse_assign_expr(&mut self) -> P<Expr> {
2904 // prefix-form of range notation '..expr'
2905 // This has the same precedence as assignment expressions
2906 // (much lower than other prefix expressions) to be consistent
2907 // with the postfix-form 'expr..'
2908 let lo = self.span.lo;
2910 let rhs = self.parse_binops();
2911 let hi = rhs.span.hi;
2912 let ex = self.mk_range(None, Some(rhs));
2913 self.mk_expr(lo, hi, ex)
2916 let lhs = self.parse_binops();
2917 self.parse_assign_expr_with(lhs)
2922 pub fn parse_assign_expr_with(&mut self, lhs: P<Expr>) -> P<Expr> {
2923 let restrictions = self.restrictions & RESTRICTION_NO_STRUCT_LITERAL;
2924 let op_span = self.span;
2928 let rhs = self.parse_expr_res(restrictions);
2929 self.mk_expr(lhs.span.lo, rhs.span.hi, ExprAssign(lhs, rhs))
2931 token::BinOpEq(op) => {
2933 let rhs = self.parse_expr_res(restrictions);
2934 let aop = match op {
2935 token::Plus => BiAdd,
2936 token::Minus => BiSub,
2937 token::Star => BiMul,
2938 token::Slash => BiDiv,
2939 token::Percent => BiRem,
2940 token::Caret => BiBitXor,
2941 token::And => BiBitAnd,
2942 token::Or => BiBitOr,
2943 token::Shl => BiShl,
2946 let rhs_span = rhs.span;
2947 let span = lhs.span;
2948 let assign_op = self.mk_assign_op(codemap::respan(op_span, aop), lhs, rhs);
2949 self.mk_expr(span.lo, rhs_span.hi, assign_op)
2951 // A range expression, either `expr..expr` or `expr..`.
2955 let opt_end = if self.is_at_start_of_range_notation_rhs() {
2956 let end = self.parse_binops();
2962 let lo = lhs.span.lo;
2963 let hi = self.span.hi;
2964 let range = self.mk_range(Some(lhs), opt_end);
2965 return self.mk_expr(lo, hi, range);
2974 fn is_at_start_of_range_notation_rhs(&self) -> bool {
2975 if self.token.can_begin_expr() {
2976 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
2977 if self.token == token::OpenDelim(token::Brace) {
2978 return !self.restrictions.contains(RESTRICTION_NO_STRUCT_LITERAL);
2986 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
2987 pub fn parse_if_expr(&mut self) -> P<Expr> {
2988 if self.token.is_keyword(keywords::Let) {
2989 return self.parse_if_let_expr();
2991 let lo = self.last_span.lo;
2992 let cond = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
2993 let thn = self.parse_block();
2994 let mut els: Option<P<Expr>> = None;
2995 let mut hi = thn.span.hi;
2996 if self.eat_keyword(keywords::Else) {
2997 let elexpr = self.parse_else_expr();
2998 hi = elexpr.span.hi;
3001 self.mk_expr(lo, hi, ExprIf(cond, thn, els))
3004 /// Parse an 'if let' expression ('if' token already eaten)
3005 pub fn parse_if_let_expr(&mut self) -> P<Expr> {
3006 let lo = self.last_span.lo;
3007 self.expect_keyword(keywords::Let);
3008 let pat = self.parse_pat();
3009 self.expect(&token::Eq);
3010 let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
3011 let thn = self.parse_block();
3012 let (hi, els) = if self.eat_keyword(keywords::Else) {
3013 let expr = self.parse_else_expr();
3014 (expr.span.hi, Some(expr))
3018 self.mk_expr(lo, hi, ExprIfLet(pat, expr, thn, els))
3022 pub fn parse_lambda_expr(&mut self, capture_clause: CaptureClause)
3025 let lo = self.span.lo;
3026 let (decl, optional_unboxed_closure_kind) =
3027 self.parse_fn_block_decl();
3028 let body = self.parse_expr();
3029 let fakeblock = P(ast::Block {
3030 id: ast::DUMMY_NODE_ID,
3034 rules: DefaultBlock,
3040 ExprClosure(capture_clause, optional_unboxed_closure_kind, decl, fakeblock))
3043 pub fn parse_else_expr(&mut self) -> P<Expr> {
3044 if self.eat_keyword(keywords::If) {
3045 return self.parse_if_expr();
3047 let blk = self.parse_block();
3048 return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk));
3052 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3053 pub fn parse_for_expr(&mut self, opt_ident: Option<ast::Ident>) -> P<Expr> {
3054 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3056 let lo = self.last_span.lo;
3057 let pat = self.parse_pat();
3058 self.expect_keyword(keywords::In);
3059 let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
3060 let loop_block = self.parse_block();
3061 let hi = self.span.hi;
3063 self.mk_expr(lo, hi, ExprForLoop(pat, expr, loop_block, opt_ident))
3066 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3067 pub fn parse_while_expr(&mut self, opt_ident: Option<ast::Ident>) -> P<Expr> {
3068 if self.token.is_keyword(keywords::Let) {
3069 return self.parse_while_let_expr(opt_ident);
3071 let lo = self.last_span.lo;
3072 let cond = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
3073 let body = self.parse_block();
3074 let hi = body.span.hi;
3075 return self.mk_expr(lo, hi, ExprWhile(cond, body, opt_ident));
3078 /// Parse a 'while let' expression ('while' token already eaten)
3079 pub fn parse_while_let_expr(&mut self, opt_ident: Option<ast::Ident>) -> P<Expr> {
3080 let lo = self.last_span.lo;
3081 self.expect_keyword(keywords::Let);
3082 let pat = self.parse_pat();
3083 self.expect(&token::Eq);
3084 let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
3085 let body = self.parse_block();
3086 let hi = body.span.hi;
3087 return self.mk_expr(lo, hi, ExprWhileLet(pat, expr, body, opt_ident));
3090 pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::Ident>) -> P<Expr> {
3091 let lo = self.last_span.lo;
3092 let body = self.parse_block();
3093 let hi = body.span.hi;
3094 self.mk_expr(lo, hi, ExprLoop(body, opt_ident))
3097 fn parse_match_expr(&mut self) -> P<Expr> {
3098 let lo = self.last_span.lo;
3099 let discriminant = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
3100 self.commit_expr_expecting(&*discriminant, token::OpenDelim(token::Brace));
3101 let mut arms: Vec<Arm> = Vec::new();
3102 while self.token != token::CloseDelim(token::Brace) {
3103 arms.push(self.parse_arm());
3105 let hi = self.span.hi;
3107 return self.mk_expr(lo, hi, ExprMatch(discriminant, arms, MatchSource::Normal));
3110 pub fn parse_arm(&mut self) -> Arm {
3111 let attrs = self.parse_outer_attributes();
3112 let pats = self.parse_pats();
3113 let mut guard = None;
3114 if self.eat_keyword(keywords::If) {
3115 guard = Some(self.parse_expr());
3117 self.expect(&token::FatArrow);
3118 let expr = self.parse_expr_res(RESTRICTION_STMT_EXPR);
3121 !classify::expr_is_simple_block(&*expr)
3122 && self.token != token::CloseDelim(token::Brace);
3125 self.commit_expr(&*expr, &[token::Comma], &[token::CloseDelim(token::Brace)]);
3127 self.eat(&token::Comma);
3138 /// Parse an expression
3139 pub fn parse_expr(&mut self) -> P<Expr> {
3140 return self.parse_expr_res(UNRESTRICTED);
3143 /// Parse an expression, subject to the given restrictions
3144 pub fn parse_expr_res(&mut self, r: Restrictions) -> P<Expr> {
3145 let old = self.restrictions;
3146 self.restrictions = r;
3147 let e = self.parse_assign_expr();
3148 self.restrictions = old;
3152 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3153 fn parse_initializer(&mut self) -> Option<P<Expr>> {
3154 if self.check(&token::Eq) {
3156 Some(self.parse_expr())
3162 /// Parse patterns, separated by '|' s
3163 fn parse_pats(&mut self) -> Vec<P<Pat>> {
3164 let mut pats = Vec::new();
3166 pats.push(self.parse_pat());
3167 if self.check(&token::BinOp(token::Or)) { self.bump(); }
3168 else { return pats; }
3172 fn parse_pat_vec_elements(
3174 ) -> (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>) {
3175 let mut before = Vec::new();
3176 let mut slice = None;
3177 let mut after = Vec::new();
3178 let mut first = true;
3179 let mut before_slice = true;
3181 while self.token != token::CloseDelim(token::Bracket) {
3185 self.expect(&token::Comma);
3187 if self.token == token::CloseDelim(token::Bracket)
3188 && (before_slice || after.len() != 0) {
3194 if self.check(&token::DotDot) {
3197 if self.check(&token::Comma) ||
3198 self.check(&token::CloseDelim(token::Bracket)) {
3199 slice = Some(P(ast::Pat {
3200 id: ast::DUMMY_NODE_ID,
3201 node: PatWild(PatWildMulti),
3204 before_slice = false;
3210 let subpat = self.parse_pat();
3211 if before_slice && self.check(&token::DotDot) {
3213 slice = Some(subpat);
3214 before_slice = false;
3215 } else if before_slice {
3216 before.push(subpat);
3222 (before, slice, after)
3225 /// Parse the fields of a struct-like pattern
3226 fn parse_pat_fields(&mut self) -> (Vec<codemap::Spanned<ast::FieldPat>> , bool) {
3227 let mut fields = Vec::new();
3228 let mut etc = false;
3229 let mut first = true;
3230 while self.token != token::CloseDelim(token::Brace) {
3234 self.expect(&token::Comma);
3235 // accept trailing commas
3236 if self.check(&token::CloseDelim(token::Brace)) { break }
3239 let lo = self.span.lo;
3242 if self.check(&token::DotDot) {
3244 if self.token != token::CloseDelim(token::Brace) {
3245 let token_str = self.this_token_to_string();
3246 self.fatal(&format!("expected `{}`, found `{}`", "}",
3253 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3254 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3255 // Parsing a pattern of the form "fieldname: pat"
3256 let fieldname = self.parse_ident();
3258 let pat = self.parse_pat();
3260 (pat, fieldname, false)
3262 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3263 let is_box = self.eat_keyword(keywords::Box);
3264 let boxed_span_lo = self.span.lo;
3265 let is_ref = self.eat_keyword(keywords::Ref);
3266 let is_mut = self.eat_keyword(keywords::Mut);
3267 let fieldname = self.parse_ident();
3268 hi = self.last_span.hi;
3270 let bind_type = match (is_ref, is_mut) {
3271 (true, true) => BindByRef(MutMutable),
3272 (true, false) => BindByRef(MutImmutable),
3273 (false, true) => BindByValue(MutMutable),
3274 (false, false) => BindByValue(MutImmutable),
3276 let fieldpath = codemap::Spanned{span:self.last_span, node:fieldname};
3277 let fieldpat = P(ast::Pat{
3278 id: ast::DUMMY_NODE_ID,
3279 node: PatIdent(bind_type, fieldpath, None),
3280 span: mk_sp(boxed_span_lo, hi),
3283 let subpat = if is_box {
3285 id: ast::DUMMY_NODE_ID,
3286 node: PatBox(fieldpat),
3287 span: mk_sp(lo, hi),
3292 (subpat, fieldname, true)
3295 fields.push(codemap::Spanned { span: mk_sp(lo, hi),
3296 node: ast::FieldPat { ident: fieldname,
3298 is_shorthand: is_shorthand }});
3300 return (fields, etc);
3303 /// Parse a pattern.
3304 pub fn parse_pat(&mut self) -> P<Pat> {
3305 maybe_whole!(self, NtPat);
3307 let lo = self.span.lo;
3312 token::Underscore => {
3314 pat = PatWild(PatWildSingle);
3315 hi = self.last_span.hi;
3317 id: ast::DUMMY_NODE_ID,
3322 token::BinOp(token::And) | token::AndAnd => {
3323 // parse &pat and &mut pat
3324 let lo = self.span.lo;
3326 let mutability = if self.eat_keyword(keywords::Mut) {
3331 let sub = self.parse_pat();
3332 pat = PatRegion(sub, mutability);
3333 hi = self.last_span.hi;
3335 id: ast::DUMMY_NODE_ID,
3340 token::OpenDelim(token::Paren) => {
3341 // parse (pat,pat,pat,...) as tuple
3343 if self.check(&token::CloseDelim(token::Paren)) {
3345 pat = PatTup(vec![]);
3347 let mut fields = vec!(self.parse_pat());
3348 if self.look_ahead(1, |t| *t != token::CloseDelim(token::Paren)) {
3349 while self.check(&token::Comma) {
3351 if self.check(&token::CloseDelim(token::Paren)) { break; }
3352 fields.push(self.parse_pat());
3355 if fields.len() == 1 { self.expect(&token::Comma); }
3356 self.expect(&token::CloseDelim(token::Paren));
3357 pat = PatTup(fields);
3359 hi = self.last_span.hi;
3361 id: ast::DUMMY_NODE_ID,
3366 token::OpenDelim(token::Bracket) => {
3367 // parse [pat,pat,...] as vector pattern
3369 let (before, slice, after) =
3370 self.parse_pat_vec_elements();
3372 self.expect(&token::CloseDelim(token::Bracket));
3373 pat = ast::PatVec(before, slice, after);
3374 hi = self.last_span.hi;
3376 id: ast::DUMMY_NODE_ID,
3383 // at this point, token != _, ~, &, &&, (, [
3385 if (!(self.token.is_ident() || self.token.is_path())
3386 && self.token != token::ModSep)
3387 || self.token.is_keyword(keywords::True)
3388 || self.token.is_keyword(keywords::False) {
3389 // Parse an expression pattern or exp .. exp.
3391 // These expressions are limited to literals (possibly
3392 // preceded by unary-minus) or identifiers.
3393 let val = self.parse_literal_maybe_minus();
3394 if (self.check(&token::DotDotDot)) &&
3395 self.look_ahead(1, |t| {
3396 *t != token::Comma && *t != token::CloseDelim(token::Bracket)
3399 let end = if self.token.is_ident() || self.token.is_path() {
3400 let path = self.parse_path(LifetimeAndTypesWithColons);
3401 let hi = self.span.hi;
3402 self.mk_expr(lo, hi, ExprPath(path))
3404 self.parse_literal_maybe_minus()
3406 pat = PatRange(val, end);
3410 } else if self.eat_keyword(keywords::Mut) {
3411 pat = self.parse_pat_ident(BindByValue(MutMutable));
3412 } else if self.eat_keyword(keywords::Ref) {
3414 let mutbl = self.parse_mutability();
3415 pat = self.parse_pat_ident(BindByRef(mutbl));
3416 } else if self.eat_keyword(keywords::Box) {
3419 // FIXME(#13910): Rename to `PatBox` and extend to full DST
3421 let sub = self.parse_pat();
3423 hi = self.last_span.hi;
3425 id: ast::DUMMY_NODE_ID,
3430 let can_be_enum_or_struct = self.look_ahead(1, |t| {
3432 token::OpenDelim(_) | token::Lt | token::ModSep => true,
3437 if self.look_ahead(1, |t| *t == token::DotDotDot) &&
3438 self.look_ahead(2, |t| {
3439 *t != token::Comma && *t != token::CloseDelim(token::Bracket)
3441 let start = self.parse_expr_res(RESTRICTION_NO_BAR_OP);
3442 self.eat(&token::DotDotDot);
3443 let end = self.parse_expr_res(RESTRICTION_NO_BAR_OP);
3444 pat = PatRange(start, end);
3445 } else if self.token.is_plain_ident() && !can_be_enum_or_struct {
3446 let id = self.parse_ident();
3447 let id_span = self.last_span;
3448 let pth1 = codemap::Spanned{span:id_span, node: id};
3449 if self.eat(&token::Not) {
3451 let delim = self.expect_open_delim();
3452 let tts = self.parse_seq_to_end(&token::CloseDelim(delim),
3454 |p| p.parse_token_tree());
3456 let mac = MacInvocTT(ident_to_path(id_span,id), tts, EMPTY_CTXT);
3457 pat = ast::PatMac(codemap::Spanned {node: mac, span: self.span});
3459 let sub = if self.eat(&token::At) {
3461 Some(self.parse_pat())
3466 pat = PatIdent(BindByValue(MutImmutable), pth1, sub);
3469 // parse an enum pat
3470 let enum_path = self.parse_path(LifetimeAndTypesWithColons);
3472 token::OpenDelim(token::Brace) => {
3475 self.parse_pat_fields();
3477 pat = PatStruct(enum_path, fields, etc);
3480 let mut args: Vec<P<Pat>> = Vec::new();
3482 token::OpenDelim(token::Paren) => {
3483 let is_dotdot = self.look_ahead(1, |t| {
3485 token::DotDot => true,
3490 // This is a "top constructor only" pat
3493 self.expect(&token::CloseDelim(token::Paren));
3494 pat = PatEnum(enum_path, None);
3496 args = self.parse_enum_variant_seq(
3497 &token::OpenDelim(token::Paren),
3498 &token::CloseDelim(token::Paren),
3499 seq_sep_trailing_allowed(token::Comma),
3502 pat = PatEnum(enum_path, Some(args));
3506 if !enum_path.global &&
3507 enum_path.segments.len() == 1 &&
3508 enum_path.segments[0].parameters.is_empty()
3510 // it could still be either an enum
3511 // or an identifier pattern, resolve
3512 // will sort it out:
3513 pat = PatIdent(BindByValue(MutImmutable),
3515 span: enum_path.span,
3516 node: enum_path.segments[0]
3520 pat = PatEnum(enum_path, Some(args));
3528 hi = self.last_span.hi;
3530 id: ast::DUMMY_NODE_ID,
3532 span: mk_sp(lo, hi),
3536 /// Parse ident or ident @ pat
3537 /// used by the copy foo and ref foo patterns to give a good
3538 /// error message when parsing mistakes like ref foo(a,b)
3539 fn parse_pat_ident(&mut self,
3540 binding_mode: ast::BindingMode)
3542 if !self.token.is_plain_ident() {
3543 let span = self.span;
3544 let tok_str = self.this_token_to_string();
3545 self.span_fatal(span,
3546 &format!("expected identifier, found `{}`", tok_str)[]);
3548 let ident = self.parse_ident();
3549 let last_span = self.last_span;
3550 let name = codemap::Spanned{span: last_span, node: ident};
3551 let sub = if self.eat(&token::At) {
3552 Some(self.parse_pat())
3557 // just to be friendly, if they write something like
3559 // we end up here with ( as the current token. This shortly
3560 // leads to a parse error. Note that if there is no explicit
3561 // binding mode then we do not end up here, because the lookahead
3562 // will direct us over to parse_enum_variant()
3563 if self.token == token::OpenDelim(token::Paren) {
3564 let last_span = self.last_span;
3567 "expected identifier, found enum pattern");
3570 PatIdent(binding_mode, name, sub)
3573 /// Parse a local variable declaration
3574 fn parse_local(&mut self) -> P<Local> {
3575 let lo = self.span.lo;
3576 let pat = self.parse_pat();
3579 if self.eat(&token::Colon) {
3580 ty = Some(self.parse_ty_sum());
3582 let init = self.parse_initializer();
3587 id: ast::DUMMY_NODE_ID,
3588 span: mk_sp(lo, self.last_span.hi),
3593 /// Parse a "let" stmt
3594 fn parse_let(&mut self) -> P<Decl> {
3595 let lo = self.span.lo;
3596 let local = self.parse_local();
3597 P(spanned(lo, self.last_span.hi, DeclLocal(local)))
3600 /// Parse a structure field
3601 fn parse_name_and_ty(&mut self, pr: Visibility,
3602 attrs: Vec<Attribute> ) -> StructField {
3603 let lo = self.span.lo;
3604 if !self.token.is_plain_ident() {
3605 self.fatal("expected ident");
3607 let name = self.parse_ident();
3608 self.expect(&token::Colon);
3609 let ty = self.parse_ty_sum();
3610 spanned(lo, self.last_span.hi, ast::StructField_ {
3611 kind: NamedField(name, pr),
3612 id: ast::DUMMY_NODE_ID,
3618 /// Get an expected item after attributes error message.
3619 fn expected_item_err(attrs: &[Attribute]) -> &'static str {
3620 match attrs.last() {
3621 Some(&Attribute { node: ast::Attribute_ { is_sugared_doc: true, .. }, .. }) => {
3622 "expected item after doc comment"
3624 _ => "expected item after attributes",
3628 /// Parse a statement. may include decl.
3629 /// Precondition: any attributes are parsed already
3630 pub fn parse_stmt(&mut self, item_attrs: Vec<Attribute>) -> P<Stmt> {
3631 maybe_whole!(self, NtStmt);
3633 fn check_expected_item(p: &mut Parser, attrs: &[Attribute]) {
3634 // If we have attributes then we should have an item
3635 if !attrs.is_empty() {
3636 let last_span = p.last_span;
3637 p.span_err(last_span, Parser::expected_item_err(attrs));
3641 let lo = self.span.lo;
3642 if self.token.is_keyword(keywords::Let) {
3643 check_expected_item(self, &item_attrs[]);
3644 self.expect_keyword(keywords::Let);
3645 let decl = self.parse_let();
3646 P(spanned(lo, decl.span.hi, StmtDecl(decl, ast::DUMMY_NODE_ID)))
3647 } else if self.token.is_ident()
3648 && !self.token.is_any_keyword()
3649 && self.look_ahead(1, |t| *t == token::Not) {
3650 // it's a macro invocation:
3652 check_expected_item(self, &item_attrs[]);
3654 // Potential trouble: if we allow macros with paths instead of
3655 // idents, we'd need to look ahead past the whole path here...
3656 let pth = self.parse_path(NoTypesAllowed);
3659 let id = match self.token {
3660 token::OpenDelim(_) => token::special_idents::invalid, // no special identifier
3661 _ => self.parse_ident(),
3664 // check that we're pointing at delimiters (need to check
3665 // again after the `if`, because of `parse_ident`
3666 // consuming more tokens).
3667 let delim = match self.token {
3668 token::OpenDelim(delim) => delim,
3670 // we only expect an ident if we didn't parse one
3672 let ident_str = if id.name == token::special_idents::invalid.name {
3677 let tok_str = self.this_token_to_string();
3678 self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
3684 let tts = self.parse_unspanned_seq(
3685 &token::OpenDelim(delim),
3686 &token::CloseDelim(delim),
3688 |p| p.parse_token_tree()
3690 let hi = self.span.hi;
3692 let style = if delim == token::Brace {
3695 MacStmtWithoutBraces
3698 if id.name == token::special_idents::invalid.name {
3701 StmtMac(P(spanned(lo,
3703 MacInvocTT(pth, tts, EMPTY_CTXT))),
3706 // if it has a special ident, it's definitely an item
3708 // Require a semicolon or braces.
3709 if style != MacStmtWithBraces {
3710 if !self.eat(&token::Semi) {
3711 let last_span = self.last_span;
3712 self.span_err(last_span,
3713 "macros that expand to items must \
3714 either be surrounded with braces or \
3715 followed by a semicolon");
3718 P(spanned(lo, hi, StmtDecl(
3719 P(spanned(lo, hi, DeclItem(
3721 lo, hi, id /*id is good here*/,
3722 ItemMac(spanned(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT))),
3723 Inherited, Vec::new(/*no attrs*/))))),
3724 ast::DUMMY_NODE_ID)))
3727 let found_attrs = !item_attrs.is_empty();
3728 let item_err = Parser::expected_item_err(&item_attrs[]);
3729 match self.parse_item_(item_attrs, false) {
3732 let decl = P(spanned(lo, hi, DeclItem(i)));
3733 P(spanned(lo, hi, StmtDecl(decl, ast::DUMMY_NODE_ID)))
3737 let last_span = self.last_span;
3738 self.span_err(last_span, item_err);
3741 // Remainder are line-expr stmts.
3742 let e = self.parse_expr_res(RESTRICTION_STMT_EXPR);
3743 P(spanned(lo, e.span.hi, StmtExpr(e, ast::DUMMY_NODE_ID)))
3749 /// Is this expression a successfully-parsed statement?
3750 fn expr_is_complete(&mut self, e: &Expr) -> bool {
3751 self.restrictions.contains(RESTRICTION_STMT_EXPR) &&
3752 !classify::expr_requires_semi_to_be_stmt(e)
3755 /// Parse a block. No inner attrs are allowed.
3756 pub fn parse_block(&mut self) -> P<Block> {
3757 maybe_whole!(no_clone self, NtBlock);
3759 let lo = self.span.lo;
3761 if !self.eat(&token::OpenDelim(token::Brace)) {
3763 let tok = self.this_token_to_string();
3764 self.span_fatal_help(sp,
3765 &format!("expected `{{`, found `{}`", tok)[],
3766 "place this code inside a block");
3769 return self.parse_block_tail_(lo, DefaultBlock, Vec::new());
3772 /// Parse a block. Inner attrs are allowed.
3773 fn parse_inner_attrs_and_block(&mut self)
3774 -> (Vec<Attribute> , P<Block>) {
3776 maybe_whole!(pair_empty self, NtBlock);
3778 let lo = self.span.lo;
3779 self.expect(&token::OpenDelim(token::Brace));
3780 let (inner, next) = self.parse_inner_attrs_and_next();
3782 (inner, self.parse_block_tail_(lo, DefaultBlock, next))
3785 /// Precondition: already parsed the '{'.
3786 fn parse_block_tail(&mut self, lo: BytePos, s: BlockCheckMode) -> P<Block> {
3787 self.parse_block_tail_(lo, s, Vec::new())
3790 /// Parse the rest of a block expression or function body
3791 fn parse_block_tail_(&mut self, lo: BytePos, s: BlockCheckMode,
3792 first_item_attrs: Vec<Attribute>) -> P<Block> {
3793 let mut stmts = vec![];
3794 let mut expr = None;
3795 let mut attributes_box = first_item_attrs;
3797 while self.token != token::CloseDelim(token::Brace) {
3798 // parsing items even when they're not allowed lets us give
3799 // better error messages and recover more gracefully.
3800 attributes_box.push_all(&self.parse_outer_attributes()[]);
3803 if !attributes_box.is_empty() {
3804 let last_span = self.last_span;
3805 self.span_err(last_span,
3806 Parser::expected_item_err(&attributes_box[]));
3807 attributes_box = Vec::new();
3809 self.bump(); // empty
3811 token::CloseDelim(token::Brace) => {
3812 // fall through and out.
3815 let stmt = self.parse_stmt(attributes_box);
3816 attributes_box = Vec::new();
3817 stmt.and_then(|Spanned {node, span}| match node {
3818 StmtExpr(e, stmt_id) => {
3819 self.handle_expression_like_statement(e,
3825 StmtMac(mac, MacStmtWithoutBraces) => {
3826 // statement macro without braces; might be an
3827 // expr depending on whether a semicolon follows
3830 stmts.push(P(Spanned {
3832 MacStmtWithSemicolon),
3838 let e = self.mk_mac_expr(span.lo,
3840 mac.and_then(|m| m.node));
3841 let e = self.parse_dot_or_call_expr_with(e);
3842 let e = self.parse_more_binops(e, 0);
3843 let e = self.parse_assign_expr_with(e);
3844 self.handle_expression_like_statement(
3853 StmtMac(m, style) => {
3854 // statement macro; might be an expr
3857 stmts.push(P(Spanned {
3859 MacStmtWithSemicolon),
3864 token::CloseDelim(token::Brace) => {
3865 // if a block ends in `m!(arg)` without
3866 // a `;`, it must be an expr
3868 self.mk_mac_expr(span.lo,
3870 m.and_then(|x| x.node)));
3873 stmts.push(P(Spanned {
3874 node: StmtMac(m, style),
3880 _ => { // all other kinds of statements:
3881 if classify::stmt_ends_with_semi(&node) {
3882 self.commit_stmt_expecting(token::Semi);
3885 stmts.push(P(Spanned {
3895 if !attributes_box.is_empty() {
3896 let last_span = self.last_span;
3897 self.span_err(last_span,
3898 Parser::expected_item_err(&attributes_box[]));
3901 let hi = self.span.hi;
3906 id: ast::DUMMY_NODE_ID,
3908 span: mk_sp(lo, hi),
3912 fn handle_expression_like_statement(
3917 stmts: &mut Vec<P<Stmt>>,
3918 last_block_expr: &mut Option<P<Expr>>) {
3919 // expression without semicolon
3920 if classify::expr_requires_semi_to_be_stmt(&*e) {
3921 // Just check for errors and recover; do not eat semicolon yet.
3922 self.commit_stmt(&[],
3923 &[token::Semi, token::CloseDelim(token::Brace)]);
3929 let span_with_semi = Span {
3931 hi: self.last_span.hi,
3932 expn_id: span.expn_id,
3934 stmts.push(P(Spanned {
3935 node: StmtSemi(e, stmt_id),
3936 span: span_with_semi,
3939 token::CloseDelim(token::Brace) => *last_block_expr = Some(e),
3941 stmts.push(P(Spanned {
3942 node: StmtExpr(e, stmt_id),
3949 // Parses a sequence of bounds if a `:` is found,
3950 // otherwise returns empty list.
3951 fn parse_colon_then_ty_param_bounds(&mut self,
3952 mode: BoundParsingMode)
3953 -> OwnedSlice<TyParamBound>
3955 if !self.eat(&token::Colon) {
3958 self.parse_ty_param_bounds(mode)
3962 // matches bounds = ( boundseq )?
3963 // where boundseq = ( polybound + boundseq ) | polybound
3964 // and polybound = ( 'for' '<' 'region '>' )? bound
3965 // and bound = 'region | trait_ref
3966 fn parse_ty_param_bounds(&mut self,
3967 mode: BoundParsingMode)
3968 -> OwnedSlice<TyParamBound>
3970 let mut result = vec!();
3972 let question_span = self.span;
3973 let ate_question = self.eat(&token::Question);
3975 token::Lifetime(lifetime) => {
3977 self.span_err(question_span,
3978 "`?` may only modify trait bounds, not lifetime bounds");
3980 result.push(RegionTyParamBound(ast::Lifetime {
3981 id: ast::DUMMY_NODE_ID,
3987 token::ModSep | token::Ident(..) => {
3988 let poly_trait_ref = self.parse_poly_trait_ref();
3989 let modifier = if ate_question {
3990 if mode == BoundParsingMode::Modified {
3991 TraitBoundModifier::Maybe
3993 self.span_err(question_span,
3995 TraitBoundModifier::None
3998 TraitBoundModifier::None
4000 result.push(TraitTyParamBound(poly_trait_ref, modifier))
4005 if !self.eat(&token::BinOp(token::Plus)) {
4010 return OwnedSlice::from_vec(result);
4013 fn trait_ref_from_ident(ident: Ident, span: Span) -> TraitRef {
4014 let segment = ast::PathSegment {
4016 parameters: ast::PathParameters::none()
4018 let path = ast::Path {
4021 segments: vec![segment],
4025 ref_id: ast::DUMMY_NODE_ID,
4029 /// Matches typaram = (unbound `?`)? IDENT (`?` unbound)? optbounds ( EQ ty )?
4030 fn parse_ty_param(&mut self) -> TyParam {
4031 // This is a bit hacky. Currently we are only interested in a single
4032 // unbound, and it may only be `Sized`. To avoid backtracking and other
4033 // complications, we parse an ident, then check for `?`. If we find it,
4034 // we use the ident as the unbound, otherwise, we use it as the name of
4035 // type param. Even worse, we need to check for `?` before or after the
4037 let mut span = self.span;
4038 let mut ident = self.parse_ident();
4039 let mut unbound = None;
4040 if self.eat(&token::Question) {
4041 let tref = Parser::trait_ref_from_ident(ident, span);
4042 unbound = Some(tref);
4044 ident = self.parse_ident();
4045 self.obsolete(span, ObsoleteSyntax::Sized);
4048 let mut bounds = self.parse_colon_then_ty_param_bounds(BoundParsingMode::Modified);
4049 if let Some(unbound) = unbound {
4050 let mut bounds_as_vec = bounds.into_vec();
4051 bounds_as_vec.push(TraitTyParamBound(PolyTraitRef { bound_lifetimes: vec![],
4052 trait_ref: unbound },
4053 TraitBoundModifier::Maybe));
4054 bounds = OwnedSlice::from_vec(bounds_as_vec);
4057 let default = if self.check(&token::Eq) {
4059 Some(self.parse_ty_sum())
4065 id: ast::DUMMY_NODE_ID,
4072 /// Parse a set of optional generic type parameter declarations. Where
4073 /// clauses are not parsed here, and must be added later via
4074 /// `parse_where_clause()`.
4076 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
4077 /// | ( < lifetimes , typaramseq ( , )? > )
4078 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
4079 pub fn parse_generics(&mut self) -> ast::Generics {
4080 if self.eat(&token::Lt) {
4081 let lifetime_defs = self.parse_lifetime_defs();
4082 let mut seen_default = false;
4083 let ty_params = self.parse_seq_to_gt(Some(token::Comma), |p| {
4084 p.forbid_lifetime();
4085 let ty_param = p.parse_ty_param();
4086 if ty_param.default.is_some() {
4087 seen_default = true;
4088 } else if seen_default {
4089 let last_span = p.last_span;
4090 p.span_err(last_span,
4091 "type parameters with a default must be trailing");
4096 lifetimes: lifetime_defs,
4097 ty_params: ty_params,
4098 where_clause: WhereClause {
4099 id: ast::DUMMY_NODE_ID,
4100 predicates: Vec::new(),
4104 ast_util::empty_generics()
4108 fn parse_generic_values_after_lt(&mut self)
4109 -> (Vec<ast::Lifetime>, Vec<P<Ty>>, Vec<P<TypeBinding>>) {
4110 let lifetimes = self.parse_lifetimes(token::Comma);
4112 // First parse types.
4113 let (types, returned) = self.parse_seq_to_gt_or_return(
4116 p.forbid_lifetime();
4117 if p.look_ahead(1, |t| t == &token::Eq) {
4120 Some(p.parse_ty_sum())
4125 // If we found the `>`, don't continue.
4127 return (lifetimes, types.into_vec(), Vec::new());
4130 // Then parse type bindings.
4131 let bindings = self.parse_seq_to_gt(
4134 p.forbid_lifetime();
4136 let ident = p.parse_ident();
4137 let found_eq = p.eat(&token::Eq);
4140 p.span_warn(span, "whoops, no =?");
4142 let ty = p.parse_ty();
4144 let span = mk_sp(lo, hi);
4145 return P(TypeBinding{id: ast::DUMMY_NODE_ID,
4152 (lifetimes, types.into_vec(), bindings.into_vec())
4155 fn forbid_lifetime(&mut self) {
4156 if self.token.is_lifetime() {
4157 let span = self.span;
4158 self.span_fatal(span, "lifetime parameters must be declared \
4159 prior to type parameters");
4163 /// Parses an optional `where` clause and places it in `generics`.
4166 /// where T : Trait<U, V> + 'b, 'a : 'b
4168 fn parse_where_clause(&mut self, generics: &mut ast::Generics) {
4169 if !self.eat_keyword(keywords::Where) {
4173 let mut parsed_something = false;
4175 let lo = self.span.lo;
4177 token::OpenDelim(token::Brace) => {
4181 token::Lifetime(..) => {
4182 let bounded_lifetime =
4183 self.parse_lifetime();
4185 self.eat(&token::Colon);
4188 self.parse_lifetimes(token::BinOp(token::Plus));
4190 let hi = self.span.hi;
4191 let span = mk_sp(lo, hi);
4193 generics.where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
4194 ast::WhereRegionPredicate {
4196 lifetime: bounded_lifetime,
4201 parsed_something = true;
4205 let bounded_ty = self.parse_ty();
4207 if self.eat(&token::Colon) {
4208 let bounds = self.parse_ty_param_bounds(BoundParsingMode::Bare);
4209 let hi = self.span.hi;
4210 let span = mk_sp(lo, hi);
4212 if bounds.len() == 0 {
4214 "each predicate in a `where` clause must have \
4215 at least one bound in it");
4218 generics.where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
4219 ast::WhereBoundPredicate {
4221 bounded_ty: bounded_ty,
4225 parsed_something = true;
4226 } else if self.eat(&token::Eq) {
4227 // let ty = self.parse_ty();
4228 let hi = self.span.hi;
4229 let span = mk_sp(lo, hi);
4230 // generics.where_clause.predicates.push(
4231 // ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
4232 // id: ast::DUMMY_NODE_ID,
4234 // path: panic!("NYI"), //bounded_ty,
4237 // parsed_something = true;
4240 "equality constraints are not yet supported \
4241 in where clauses (#20041)");
4243 let last_span = self.last_span;
4244 self.span_err(last_span,
4245 "unexpected token in `where` clause");
4250 if !self.eat(&token::Comma) {
4255 if !parsed_something {
4256 let last_span = self.last_span;
4257 self.span_err(last_span,
4258 "a `where` clause must have at least one predicate \
4263 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
4264 -> (Vec<Arg> , bool) {
4266 let mut args: Vec<Option<Arg>> =
4267 self.parse_unspanned_seq(
4268 &token::OpenDelim(token::Paren),
4269 &token::CloseDelim(token::Paren),
4270 seq_sep_trailing_allowed(token::Comma),
4272 if p.token == token::DotDotDot {
4275 if p.token != token::CloseDelim(token::Paren) {
4278 "`...` must be last in argument list for variadic function");
4283 "only foreign functions are allowed to be variadic");
4287 Some(p.parse_arg_general(named_args))
4292 let variadic = match args.pop() {
4295 // Need to put back that last arg
4302 if variadic && args.is_empty() {
4304 "variadic function must be declared with at least one named argument");
4307 let args = args.into_iter().map(|x| x.unwrap()).collect();
4312 /// Parse the argument list and result type of a function declaration
4313 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> P<FnDecl> {
4315 let (args, variadic) = self.parse_fn_args(true, allow_variadic);
4316 let ret_ty = self.parse_ret_ty();
4325 fn is_self_ident(&mut self) -> bool {
4327 token::Ident(id, token::Plain) => id.name == special_idents::self_.name,
4332 fn expect_self_ident(&mut self) -> ast::Ident {
4334 token::Ident(id, token::Plain) if id.name == special_idents::self_.name => {
4339 let token_str = self.this_token_to_string();
4340 self.fatal(&format!("expected `self`, found `{}`",
4346 /// Parse the argument list and result type of a function
4347 /// that may have a self type.
4348 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> (ExplicitSelf, P<FnDecl>) where
4349 F: FnMut(&mut Parser) -> Arg,
4351 fn maybe_parse_borrowed_explicit_self(this: &mut Parser)
4352 -> ast::ExplicitSelf_ {
4353 // The following things are possible to see here:
4358 // fn(&'lt mut self)
4360 // We already know that the current token is `&`.
4362 if this.look_ahead(1, |t| t.is_keyword(keywords::Self)) {
4364 SelfRegion(None, MutImmutable, this.expect_self_ident())
4365 } else if this.look_ahead(1, |t| t.is_mutability()) &&
4366 this.look_ahead(2, |t| t.is_keyword(keywords::Self)) {
4368 let mutability = this.parse_mutability();
4369 SelfRegion(None, mutability, this.expect_self_ident())
4370 } else if this.look_ahead(1, |t| t.is_lifetime()) &&
4371 this.look_ahead(2, |t| t.is_keyword(keywords::Self)) {
4373 let lifetime = this.parse_lifetime();
4374 SelfRegion(Some(lifetime), MutImmutable, this.expect_self_ident())
4375 } else if this.look_ahead(1, |t| t.is_lifetime()) &&
4376 this.look_ahead(2, |t| t.is_mutability()) &&
4377 this.look_ahead(3, |t| t.is_keyword(keywords::Self)) {
4379 let lifetime = this.parse_lifetime();
4380 let mutability = this.parse_mutability();
4381 SelfRegion(Some(lifetime), mutability, this.expect_self_ident())
4387 self.expect(&token::OpenDelim(token::Paren));
4389 // A bit of complexity and lookahead is needed here in order to be
4390 // backwards compatible.
4391 let lo = self.span.lo;
4392 let mut self_ident_lo = self.span.lo;
4393 let mut self_ident_hi = self.span.hi;
4395 let mut mutbl_self = MutImmutable;
4396 let explicit_self = match self.token {
4397 token::BinOp(token::And) => {
4398 let eself = maybe_parse_borrowed_explicit_self(self);
4399 self_ident_lo = self.last_span.lo;
4400 self_ident_hi = self.last_span.hi;
4403 token::BinOp(token::Star) => {
4404 // Possibly "*self" or "*mut self" -- not supported. Try to avoid
4405 // emitting cryptic "unexpected token" errors.
4407 let _mutability = if self.token.is_mutability() {
4408 self.parse_mutability()
4412 if self.is_self_ident() {
4413 let span = self.span;
4414 self.span_err(span, "cannot pass self by unsafe pointer");
4417 // error case, making bogus self ident:
4418 SelfValue(special_idents::self_)
4420 token::Ident(..) => {
4421 if self.is_self_ident() {
4422 let self_ident = self.expect_self_ident();
4424 // Determine whether this is the fully explicit form, `self:
4426 if self.eat(&token::Colon) {
4427 SelfExplicit(self.parse_ty_sum(), self_ident)
4429 SelfValue(self_ident)
4431 } else if self.token.is_mutability() &&
4432 self.look_ahead(1, |t| t.is_keyword(keywords::Self)) {
4433 mutbl_self = self.parse_mutability();
4434 let self_ident = self.expect_self_ident();
4436 // Determine whether this is the fully explicit form,
4438 if self.eat(&token::Colon) {
4439 SelfExplicit(self.parse_ty_sum(), self_ident)
4441 SelfValue(self_ident)
4450 let explicit_self_sp = mk_sp(self_ident_lo, self_ident_hi);
4452 // shared fall-through for the three cases below. borrowing prevents simply
4453 // writing this as a closure
4454 macro_rules! parse_remaining_arguments {
4457 // If we parsed a self type, expect a comma before the argument list.
4461 let sep = seq_sep_trailing_allowed(token::Comma);
4462 let mut fn_inputs = self.parse_seq_to_before_end(
4463 &token::CloseDelim(token::Paren),
4467 fn_inputs.insert(0, Arg::new_self(explicit_self_sp, mutbl_self, $self_id));
4470 token::CloseDelim(token::Paren) => {
4471 vec!(Arg::new_self(explicit_self_sp, mutbl_self, $self_id))
4474 let token_str = self.this_token_to_string();
4475 self.fatal(&format!("expected `,` or `)`, found `{}`",
4482 let fn_inputs = match explicit_self {
4484 let sep = seq_sep_trailing_allowed(token::Comma);
4485 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)
4487 SelfValue(id) => parse_remaining_arguments!(id),
4488 SelfRegion(_,_,id) => parse_remaining_arguments!(id),
4489 SelfExplicit(_,id) => parse_remaining_arguments!(id),
4493 self.expect(&token::CloseDelim(token::Paren));
4495 let hi = self.span.hi;
4497 let ret_ty = self.parse_ret_ty();
4499 let fn_decl = P(FnDecl {
4505 (spanned(lo, hi, explicit_self), fn_decl)
4508 // parse the |arg, arg| header on a lambda
4509 fn parse_fn_block_decl(&mut self)
4510 -> (P<FnDecl>, Option<UnboxedClosureKind>) {
4511 let (optional_unboxed_closure_kind, inputs_captures) = {
4512 if self.eat(&token::OrOr) {
4515 self.expect(&token::BinOp(token::Or));
4516 let optional_unboxed_closure_kind =
4517 self.parse_optional_unboxed_closure_kind();
4518 let args = self.parse_seq_to_before_end(
4519 &token::BinOp(token::Or),
4520 seq_sep_trailing_allowed(token::Comma),
4521 |p| p.parse_fn_block_arg()
4524 (optional_unboxed_closure_kind, args)
4527 let output = self.parse_ret_ty();
4530 inputs: inputs_captures,
4533 }), optional_unboxed_closure_kind)
4536 /// Parses the `(arg, arg) -> return_type` header on a procedure.
4537 fn parse_proc_decl(&mut self) -> P<FnDecl> {
4539 self.parse_unspanned_seq(&token::OpenDelim(token::Paren),
4540 &token::CloseDelim(token::Paren),
4541 seq_sep_trailing_allowed(token::Comma),
4542 |p| p.parse_fn_block_arg());
4544 let output = self.parse_ret_ty();
4553 /// Parse the name and optional generic types of a function header.
4554 fn parse_fn_header(&mut self) -> (Ident, ast::Generics) {
4555 let id = self.parse_ident();
4556 let generics = self.parse_generics();
4560 fn mk_item(&mut self, lo: BytePos, hi: BytePos, ident: Ident,
4561 node: Item_, vis: Visibility,
4562 attrs: Vec<Attribute>) -> P<Item> {
4566 id: ast::DUMMY_NODE_ID,
4573 /// Parse an item-position function declaration.
4574 fn parse_item_fn(&mut self, unsafety: Unsafety, abi: abi::Abi) -> ItemInfo {
4575 let (ident, mut generics) = self.parse_fn_header();
4576 let decl = self.parse_fn_decl(false);
4577 self.parse_where_clause(&mut generics);
4578 let (inner_attrs, body) = self.parse_inner_attrs_and_block();
4579 (ident, ItemFn(decl, unsafety, abi, generics, body), Some(inner_attrs))
4582 /// Parse a method in a trait impl
4583 pub fn parse_method_with_outer_attributes(&mut self) -> P<Method> {
4584 let attrs = self.parse_outer_attributes();
4585 let visa = self.parse_visibility();
4586 self.parse_method(attrs, visa)
4589 /// Parse a method in a trait impl, starting with `attrs` attributes.
4590 pub fn parse_method(&mut self,
4591 attrs: Vec<Attribute>,
4594 let lo = self.span.lo;
4596 // code copied from parse_macro_use_or_failure... abstraction!
4597 let (method_, hi, new_attrs) = {
4598 if !self.token.is_any_keyword()
4599 && self.look_ahead(1, |t| *t == token::Not)
4600 && (self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren))
4601 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) {
4603 let pth = self.parse_path(NoTypesAllowed);
4604 self.expect(&token::Not);
4606 // eat a matched-delimiter token tree:
4607 let delim = self.expect_open_delim();
4608 let tts = self.parse_seq_to_end(&token::CloseDelim(delim),
4610 |p| p.parse_token_tree());
4611 let m_ = ast::MacInvocTT(pth, tts, EMPTY_CTXT);
4612 let m: ast::Mac = codemap::Spanned { node: m_,
4613 span: mk_sp(self.span.lo,
4615 if delim != token::Brace {
4616 self.expect(&token::Semi)
4618 (ast::MethMac(m), self.span.hi, attrs)
4620 let unsafety = self.parse_unsafety();
4621 let abi = if self.eat_keyword(keywords::Extern) {
4622 self.parse_opt_abi().unwrap_or(abi::C)
4626 self.expect_keyword(keywords::Fn);
4627 let ident = self.parse_ident();
4628 let mut generics = self.parse_generics();
4629 let (explicit_self, decl) = self.parse_fn_decl_with_self(|p| {
4632 self.parse_where_clause(&mut generics);
4633 let (inner_attrs, body) = self.parse_inner_attrs_and_block();
4634 let body_span = body.span;
4635 let mut new_attrs = attrs;
4636 new_attrs.push_all(&inner_attrs[]);
4637 (ast::MethDecl(ident,
4645 body_span.hi, new_attrs)
4650 id: ast::DUMMY_NODE_ID,
4651 span: mk_sp(lo, hi),
4656 /// Parse trait Foo { ... }
4657 fn parse_item_trait(&mut self, unsafety: Unsafety) -> ItemInfo {
4658 let ident = self.parse_ident();
4659 let mut tps = self.parse_generics();
4660 let unbound = self.parse_for_sized();
4662 // Parse supertrait bounds.
4663 let mut bounds = self.parse_colon_then_ty_param_bounds(BoundParsingMode::Bare);
4665 if let Some(unbound) = unbound {
4666 let mut bounds_as_vec = bounds.into_vec();
4667 bounds_as_vec.push(TraitTyParamBound(PolyTraitRef { bound_lifetimes: vec![],
4668 trait_ref: unbound },
4669 TraitBoundModifier::Maybe));
4670 bounds = OwnedSlice::from_vec(bounds_as_vec);
4673 self.parse_where_clause(&mut tps);
4675 let meths = self.parse_trait_items();
4676 (ident, ItemTrait(unsafety, tps, bounds, meths), None)
4679 fn parse_impl_items(&mut self) -> (Vec<ImplItem>, Vec<Attribute>) {
4680 let mut impl_items = Vec::new();
4681 self.expect(&token::OpenDelim(token::Brace));
4682 let (inner_attrs, mut method_attrs) =
4683 self.parse_inner_attrs_and_next();
4685 method_attrs.extend(self.parse_outer_attributes().into_iter());
4686 if method_attrs.is_empty() && self.eat(&token::CloseDelim(token::Brace)) {
4690 let vis = self.parse_visibility();
4691 if self.eat_keyword(keywords::Type) {
4692 impl_items.push(TypeImplItem(P(self.parse_typedef(
4696 impl_items.push(MethodImplItem(self.parse_method(
4700 method_attrs = vec![];
4702 (impl_items, inner_attrs)
4705 /// Parses two variants (with the region/type params always optional):
4706 /// impl<T> Foo { ... }
4707 /// impl<T> ToString for ~[T] { ... }
4708 fn parse_item_impl(&mut self, unsafety: ast::Unsafety) -> ItemInfo {
4709 // First, parse type parameters if necessary.
4710 let mut generics = self.parse_generics();
4712 // Special case: if the next identifier that follows is '(', don't
4713 // allow this to be parsed as a trait.
4714 let could_be_trait = self.token != token::OpenDelim(token::Paren);
4716 let neg_span = self.span;
4717 let polarity = if self.eat(&token::Not) {
4718 ast::ImplPolarity::Negative
4720 ast::ImplPolarity::Positive
4724 let mut ty = self.parse_ty_sum();
4726 // Parse traits, if necessary.
4727 let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) {
4728 // New-style trait. Reinterpret the type as a trait.
4729 let opt_trait_ref = match ty.node {
4730 TyPath(ref path, node_id) => {
4732 path: (*path).clone(),
4737 self.span_err(ty.span, "not a trait");
4742 ty = self.parse_ty_sum();
4746 ast::ImplPolarity::Negative => {
4747 // This is a negated type implementation
4748 // `impl !MyType {}`, which is not allowed.
4749 self.span_err(neg_span, "inherent implementation can't be negated");
4756 self.parse_where_clause(&mut generics);
4757 let (impl_items, attrs) = self.parse_impl_items();
4759 let ident = ast_util::impl_pretty_name(&opt_trait, &*ty);
4762 ItemImpl(unsafety, polarity, generics, opt_trait, ty, impl_items),
4766 /// Parse a::B<String,i32>
4767 fn parse_trait_ref(&mut self) -> TraitRef {
4769 path: self.parse_path(LifetimeAndTypesWithoutColons),
4770 ref_id: ast::DUMMY_NODE_ID,
4774 fn parse_late_bound_lifetime_defs(&mut self) -> Vec<ast::LifetimeDef> {
4775 if self.eat_keyword(keywords::For) {
4776 self.expect(&token::Lt);
4777 let lifetime_defs = self.parse_lifetime_defs();
4785 /// Parse for<'l> a::B<String,i32>
4786 fn parse_poly_trait_ref(&mut self) -> PolyTraitRef {
4787 let lifetime_defs = self.parse_late_bound_lifetime_defs();
4790 bound_lifetimes: lifetime_defs,
4791 trait_ref: self.parse_trait_ref()
4795 /// Parse struct Foo { ... }
4796 fn parse_item_struct(&mut self) -> ItemInfo {
4797 let class_name = self.parse_ident();
4798 let mut generics = self.parse_generics();
4800 if self.eat(&token::Colon) {
4801 let ty = self.parse_ty_sum();
4802 self.span_err(ty.span, "`virtual` structs have been removed from the language");
4805 // There is a special case worth noting here, as reported in issue #17904.
4806 // If we are parsing a tuple struct it is the case that the where clause
4807 // should follow the field list. Like so:
4809 // struct Foo<T>(T) where T: Copy;
4811 // If we are parsing a normal record-style struct it is the case
4812 // that the where clause comes before the body, and after the generics.
4813 // So if we look ahead and see a brace or a where-clause we begin
4814 // parsing a record style struct.
4816 // Otherwise if we look ahead and see a paren we parse a tuple-style
4819 let (fields, ctor_id) = if self.token.is_keyword(keywords::Where) {
4820 self.parse_where_clause(&mut generics);
4821 if self.eat(&token::Semi) {
4822 // If we see a: `struct Foo<T> where T: Copy;` style decl.
4823 (Vec::new(), Some(ast::DUMMY_NODE_ID))
4825 // If we see: `struct Foo<T> where T: Copy { ... }`
4826 (self.parse_record_struct_body(&class_name), None)
4828 // No `where` so: `struct Foo<T>;`
4829 } else if self.eat(&token::Semi) {
4830 (Vec::new(), Some(ast::DUMMY_NODE_ID))
4831 // Record-style struct definition
4832 } else if self.token == token::OpenDelim(token::Brace) {
4833 let fields = self.parse_record_struct_body(&class_name);
4835 // Tuple-style struct definition with optional where-clause.
4837 let fields = self.parse_tuple_struct_body(&class_name, &mut generics);
4838 (fields, Some(ast::DUMMY_NODE_ID))
4842 ItemStruct(P(ast::StructDef {
4849 pub fn parse_record_struct_body(&mut self, class_name: &ast::Ident) -> Vec<StructField> {
4850 let mut fields = Vec::new();
4851 if self.eat(&token::OpenDelim(token::Brace)) {
4852 while self.token != token::CloseDelim(token::Brace) {
4853 fields.push(self.parse_struct_decl_field(true));
4856 if fields.len() == 0 {
4857 self.fatal(&format!("unit-like struct definition should be \
4858 written as `struct {};`",
4859 token::get_ident(class_name.clone()))[]);
4864 let token_str = self.this_token_to_string();
4865 self.fatal(&format!("expected `where`, or `{}` after struct \
4866 name, found `{}`", "{",
4873 pub fn parse_tuple_struct_body(&mut self,
4874 class_name: &ast::Ident,
4875 generics: &mut ast::Generics)
4876 -> Vec<StructField> {
4877 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
4878 if self.check(&token::OpenDelim(token::Paren)) {
4879 let fields = self.parse_unspanned_seq(
4880 &token::OpenDelim(token::Paren),
4881 &token::CloseDelim(token::Paren),
4882 seq_sep_trailing_allowed(token::Comma),
4884 let attrs = p.parse_outer_attributes();
4886 let struct_field_ = ast::StructField_ {
4887 kind: UnnamedField(p.parse_visibility()),
4888 id: ast::DUMMY_NODE_ID,
4889 ty: p.parse_ty_sum(),
4892 spanned(lo, p.span.hi, struct_field_)
4895 if fields.len() == 0 {
4896 self.fatal(&format!("unit-like struct definition should be \
4897 written as `struct {};`",
4898 token::get_ident(class_name.clone()))[]);
4901 self.parse_where_clause(generics);
4902 self.expect(&token::Semi);
4904 // This is the case where we just see struct Foo<T> where T: Copy;
4905 } else if self.token.is_keyword(keywords::Where) {
4906 self.parse_where_clause(generics);
4907 self.expect(&token::Semi);
4909 // This case is where we see: `struct Foo<T>;`
4911 let token_str = self.this_token_to_string();
4912 self.fatal(&format!("expected `where`, `{}`, `(`, or `;` after struct \
4913 name, found `{}`", "{", token_str)[]);
4917 /// Parse a structure field declaration
4918 pub fn parse_single_struct_field(&mut self,
4920 attrs: Vec<Attribute> )
4922 let a_var = self.parse_name_and_ty(vis, attrs);
4927 token::CloseDelim(token::Brace) => {}
4929 let span = self.span;
4930 let token_str = self.this_token_to_string();
4931 self.span_fatal_help(span,
4932 &format!("expected `,`, or `}}`, found `{}`",
4934 "struct fields should be separated by commas")
4940 /// Parse an element of a struct definition
4941 fn parse_struct_decl_field(&mut self, allow_pub: bool) -> StructField {
4943 let attrs = self.parse_outer_attributes();
4945 if self.eat_keyword(keywords::Pub) {
4947 let span = self.last_span;
4948 self.span_err(span, "`pub` is not allowed here");
4950 return self.parse_single_struct_field(Public, attrs);
4953 return self.parse_single_struct_field(Inherited, attrs);
4956 /// Parse visibility: PUB, PRIV, or nothing
4957 fn parse_visibility(&mut self) -> Visibility {
4958 if self.eat_keyword(keywords::Pub) { Public }
4962 fn parse_for_sized(&mut self) -> Option<ast::TraitRef> {
4963 // FIXME, this should really use TraitBoundModifier, but it will get
4964 // re-jigged shortly in any case, so leaving the hacky version for now.
4965 if self.eat_keyword(keywords::For) {
4966 let span = self.span;
4968 let mut ate_question = false;
4969 if self.eat(&token::Question) {
4970 ate_question = true;
4972 let ident = self.parse_ident();
4973 if self.eat(&token::Question) {
4978 ate_question = true;
4982 "expected `?Sized` after `for` in trait item");
4985 let _tref = Parser::trait_ref_from_ident(ident, span);
4987 self.obsolete(span, ObsoleteSyntax::ForSized);
4995 /// Given a termination token and a vector of already-parsed
4996 /// attributes (of length 0 or 1), parse all of the items in a module
4997 fn parse_mod_items(&mut self,
4999 first_item_attrs: Vec<Attribute>,
5002 // Parse all of the items up to closing or an attribute.
5004 let mut attrs = first_item_attrs;
5005 attrs.push_all(&self.parse_outer_attributes()[]);
5006 let mut items = vec![];
5009 match self.parse_item_(attrs, true) {
5010 Err(returned_attrs) => {
5011 attrs = returned_attrs;
5015 attrs = self.parse_outer_attributes();
5021 // don't think this other loop is even necessary....
5023 while self.token != term {
5024 let mut attrs = mem::replace(&mut attrs, vec![]);
5025 attrs.push_all(&self.parse_outer_attributes()[]);
5026 debug!("parse_mod_items: parse_item_(attrs={:?})", attrs);
5027 match self.parse_item_(attrs, true /* macros allowed */) {
5028 Ok(item) => items.push(item),
5030 let token_str = self.this_token_to_string();
5031 self.fatal(&format!("expected item, found `{}`",
5037 if !attrs.is_empty() {
5038 // We parsed attributes for the first item but didn't find it
5039 let last_span = self.last_span;
5040 self.span_err(last_span,
5041 Parser::expected_item_err(&attrs[]));
5045 inner: mk_sp(inner_lo, self.span.lo),
5050 fn parse_item_const(&mut self, m: Option<Mutability>) -> ItemInfo {
5051 let id = self.parse_ident();
5052 self.expect(&token::Colon);
5053 let ty = self.parse_ty_sum();
5054 self.expect(&token::Eq);
5055 let e = self.parse_expr();
5056 self.commit_expr_expecting(&*e, token::Semi);
5057 let item = match m {
5058 Some(m) => ItemStatic(ty, m, e),
5059 None => ItemConst(ty, e),
5064 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
5065 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> ItemInfo {
5066 let id_span = self.span;
5067 let id = self.parse_ident();
5068 if self.check(&token::Semi) {
5070 // This mod is in an external file. Let's go get it!
5071 let (m, attrs) = self.eval_src_mod(id, outer_attrs, id_span);
5072 (id, m, Some(attrs))
5074 self.push_mod_path(id, outer_attrs);
5075 self.expect(&token::OpenDelim(token::Brace));
5076 let mod_inner_lo = self.span.lo;
5077 let old_owns_directory = self.owns_directory;
5078 self.owns_directory = true;
5079 let (inner, next) = self.parse_inner_attrs_and_next();
5080 let m = self.parse_mod_items(token::CloseDelim(token::Brace), next, mod_inner_lo);
5081 self.expect(&token::CloseDelim(token::Brace));
5082 self.owns_directory = old_owns_directory;
5083 self.pop_mod_path();
5084 (id, ItemMod(m), Some(inner))
5088 fn push_mod_path(&mut self, id: Ident, attrs: &[Attribute]) {
5089 let default_path = self.id_to_interned_str(id);
5090 let file_path = match ::attr::first_attr_value_str_by_name(attrs,
5093 None => default_path,
5095 self.mod_path_stack.push(file_path)
5098 fn pop_mod_path(&mut self) {
5099 self.mod_path_stack.pop().unwrap();
5102 /// Read a module from a source file.
5103 fn eval_src_mod(&mut self,
5105 outer_attrs: &[ast::Attribute],
5107 -> (ast::Item_, Vec<ast::Attribute> ) {
5108 let mut prefix = Path::new(self.sess.span_diagnostic.cm.span_to_filename(self.span));
5110 let mod_path = Path::new(".").join_many(&self.mod_path_stack[]);
5111 let dir_path = prefix.join(&mod_path);
5112 let mod_string = token::get_ident(id);
5113 let (file_path, owns_directory) = match ::attr::first_attr_value_str_by_name(
5114 outer_attrs, "path") {
5115 Some(d) => (dir_path.join(d), true),
5117 let mod_name = mod_string.get().to_string();
5118 let default_path_str = format!("{}.rs", mod_name);
5119 let secondary_path_str = format!("{}/mod.rs", mod_name);
5120 let default_path = dir_path.join(&default_path_str[]);
5121 let secondary_path = dir_path.join(&secondary_path_str[]);
5122 let default_exists = default_path.exists();
5123 let secondary_exists = secondary_path.exists();
5125 if !self.owns_directory {
5126 self.span_err(id_sp,
5127 "cannot declare a new module at this location");
5128 let this_module = match self.mod_path_stack.last() {
5129 Some(name) => name.get().to_string(),
5130 None => self.root_module_name.as_ref().unwrap().clone(),
5132 self.span_note(id_sp,
5133 &format!("maybe move this module `{0}` \
5134 to its own directory via \
5137 if default_exists || secondary_exists {
5138 self.span_note(id_sp,
5139 &format!("... or maybe `use` the module \
5140 `{}` instead of possibly \
5144 self.abort_if_errors();
5147 match (default_exists, secondary_exists) {
5148 (true, false) => (default_path, false),
5149 (false, true) => (secondary_path, true),
5151 self.span_fatal_help(id_sp,
5152 &format!("file not found for module `{}`",
5154 &format!("name the file either {} or {} inside \
5155 the directory {:?}",
5158 dir_path.display())[]);
5161 self.span_fatal_help(
5163 &format!("file for module `{}` found at both {} \
5167 secondary_path_str)[],
5168 "delete or rename one of them to remove the ambiguity");
5174 self.eval_src_mod_from_path(file_path, owns_directory,
5175 mod_string.get().to_string(), id_sp)
5178 fn eval_src_mod_from_path(&mut self,
5180 owns_directory: bool,
5182 id_sp: Span) -> (ast::Item_, Vec<ast::Attribute> ) {
5183 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
5184 match included_mod_stack.iter().position(|p| *p == path) {
5186 let mut err = String::from_str("circular modules: ");
5187 let len = included_mod_stack.len();
5188 for p in included_mod_stack[i.. len].iter() {
5189 err.push_str(&p.display().as_cow()[]);
5190 err.push_str(" -> ");
5192 err.push_str(&path.display().as_cow()[]);
5193 self.span_fatal(id_sp, &err[]);
5197 included_mod_stack.push(path.clone());
5198 drop(included_mod_stack);
5201 new_sub_parser_from_file(self.sess,
5207 let mod_inner_lo = p0.span.lo;
5208 let (mod_attrs, next) = p0.parse_inner_attrs_and_next();
5209 let first_item_outer_attrs = next;
5210 let m0 = p0.parse_mod_items(token::Eof, first_item_outer_attrs, mod_inner_lo);
5211 self.sess.included_mod_stack.borrow_mut().pop();
5212 return (ast::ItemMod(m0), mod_attrs);
5215 /// Parse a function declaration from a foreign module
5216 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility,
5217 attrs: Vec<Attribute>) -> P<ForeignItem> {
5218 let lo = self.span.lo;
5219 self.expect_keyword(keywords::Fn);
5221 let (ident, mut generics) = self.parse_fn_header();
5222 let decl = self.parse_fn_decl(true);
5223 self.parse_where_clause(&mut generics);
5224 let hi = self.span.hi;
5225 self.expect(&token::Semi);
5226 P(ast::ForeignItem {
5229 node: ForeignItemFn(decl, generics),
5230 id: ast::DUMMY_NODE_ID,
5231 span: mk_sp(lo, hi),
5236 /// Parse a static item from a foreign module
5237 fn parse_item_foreign_static(&mut self, vis: ast::Visibility,
5238 attrs: Vec<Attribute>) -> P<ForeignItem> {
5239 let lo = self.span.lo;
5241 self.expect_keyword(keywords::Static);
5242 let mutbl = self.eat_keyword(keywords::Mut);
5244 let ident = self.parse_ident();
5245 self.expect(&token::Colon);
5246 let ty = self.parse_ty_sum();
5247 let hi = self.span.hi;
5248 self.expect(&token::Semi);
5252 node: ForeignItemStatic(ty, mutbl),
5253 id: ast::DUMMY_NODE_ID,
5254 span: mk_sp(lo, hi),
5259 /// At this point, this is essentially a wrapper for
5260 /// parse_foreign_items.
5261 fn parse_foreign_mod_items(&mut self,
5263 first_item_attrs: Vec<Attribute>)
5265 let foreign_items = self.parse_foreign_items(first_item_attrs);
5266 assert!(self.token == token::CloseDelim(token::Brace));
5269 items: foreign_items
5273 /// Parse extern crate links
5277 /// extern crate url;
5278 /// extern crate foo = "bar"; //deprecated
5279 /// extern crate "bar" as foo;
5280 fn parse_item_extern_crate(&mut self,
5282 visibility: Visibility,
5283 attrs: Vec<Attribute>)
5286 let span = self.span;
5287 let (maybe_path, ident) = match self.token {
5288 token::Ident(..) => {
5289 let the_ident = self.parse_ident();
5290 let path = if self.eat_keyword(keywords::As) {
5291 // skip the ident if there is one
5292 if self.token.is_ident() { self.bump(); }
5294 self.span_err(span, "expected `;`, found `as`");
5295 self.span_help(span,
5296 &format!("perhaps you meant to enclose the crate name `{}` in \
5298 the_ident.as_str())[]);
5303 self.expect(&token::Semi);
5306 token::Literal(token::Str_(..), suf) | token::Literal(token::StrRaw(..), suf) => {
5308 self.expect_no_suffix(sp, "extern crate name", suf);
5309 // forgo the internal suffix check of `parse_str` to
5310 // avoid repeats (this unwrap will always succeed due
5311 // to the restriction of the `match`)
5312 let (s, style, _) = self.parse_optional_str().unwrap();
5313 self.expect_keyword(keywords::As);
5314 let the_ident = self.parse_ident();
5315 self.expect(&token::Semi);
5316 (Some((s, style)), the_ident)
5319 let span = self.span;
5320 let token_str = self.this_token_to_string();
5321 self.span_fatal(span,
5322 &format!("expected extern crate name but \
5328 let last_span = self.last_span;
5332 ItemExternCrate(maybe_path),
5337 /// Parse `extern` for foreign ABIs
5340 /// `extern` is expected to have been
5341 /// consumed before calling this method
5347 fn parse_item_foreign_mod(&mut self,
5349 opt_abi: Option<abi::Abi>,
5350 visibility: Visibility,
5351 attrs: Vec<Attribute>)
5354 self.expect(&token::OpenDelim(token::Brace));
5356 let abi = opt_abi.unwrap_or(abi::C);
5358 let (inner, next) = self.parse_inner_attrs_and_next();
5359 let m = self.parse_foreign_mod_items(abi, next);
5360 self.expect(&token::CloseDelim(token::Brace));
5362 let last_span = self.last_span;
5365 special_idents::invalid,
5368 maybe_append(attrs, Some(inner)))
5371 /// Parse type Foo = Bar;
5372 fn parse_item_type(&mut self) -> ItemInfo {
5373 let ident = self.parse_ident();
5374 let mut tps = self.parse_generics();
5375 self.parse_where_clause(&mut tps);
5376 self.expect(&token::Eq);
5377 let ty = self.parse_ty_sum();
5378 self.expect(&token::Semi);
5379 (ident, ItemTy(ty, tps), None)
5382 /// Parse a structure-like enum variant definition
5383 /// this should probably be renamed or refactored...
5384 fn parse_struct_def(&mut self) -> P<StructDef> {
5385 let mut fields: Vec<StructField> = Vec::new();
5386 while self.token != token::CloseDelim(token::Brace) {
5387 fields.push(self.parse_struct_decl_field(false));
5397 /// Parse the part of an "enum" decl following the '{'
5398 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> EnumDef {
5399 let mut variants = Vec::new();
5400 let mut all_nullary = true;
5401 let mut any_disr = None;
5402 while self.token != token::CloseDelim(token::Brace) {
5403 let variant_attrs = self.parse_outer_attributes();
5404 let vlo = self.span.lo;
5406 let vis = self.parse_visibility();
5410 let mut args = Vec::new();
5411 let mut disr_expr = None;
5412 ident = self.parse_ident();
5413 if self.eat(&token::OpenDelim(token::Brace)) {
5414 // Parse a struct variant.
5415 all_nullary = false;
5416 let start_span = self.span;
5417 let struct_def = self.parse_struct_def();
5418 if struct_def.fields.len() == 0 {
5419 self.span_err(start_span,
5420 &format!("unit-like struct variant should be written \
5421 without braces, as `{},`",
5422 token::get_ident(ident))[]);
5424 kind = StructVariantKind(struct_def);
5425 } else if self.check(&token::OpenDelim(token::Paren)) {
5426 all_nullary = false;
5427 let arg_tys = self.parse_enum_variant_seq(
5428 &token::OpenDelim(token::Paren),
5429 &token::CloseDelim(token::Paren),
5430 seq_sep_trailing_allowed(token::Comma),
5431 |p| p.parse_ty_sum()
5433 for ty in arg_tys.into_iter() {
5434 args.push(ast::VariantArg {
5436 id: ast::DUMMY_NODE_ID,
5439 kind = TupleVariantKind(args);
5440 } else if self.eat(&token::Eq) {
5441 disr_expr = Some(self.parse_expr());
5442 any_disr = disr_expr.as_ref().map(|expr| expr.span);
5443 kind = TupleVariantKind(args);
5445 kind = TupleVariantKind(Vec::new());
5448 let vr = ast::Variant_ {
5450 attrs: variant_attrs,
5452 id: ast::DUMMY_NODE_ID,
5453 disr_expr: disr_expr,
5456 variants.push(P(spanned(vlo, self.last_span.hi, vr)));
5458 if !self.eat(&token::Comma) { break; }
5460 self.expect(&token::CloseDelim(token::Brace));
5462 Some(disr_span) if !all_nullary =>
5463 self.span_err(disr_span,
5464 "discriminator values can only be used with a c-like enum"),
5468 ast::EnumDef { variants: variants }
5471 /// Parse an "enum" declaration
5472 fn parse_item_enum(&mut self) -> ItemInfo {
5473 let id = self.parse_ident();
5474 let mut generics = self.parse_generics();
5475 self.parse_where_clause(&mut generics);
5476 self.expect(&token::OpenDelim(token::Brace));
5478 let enum_definition = self.parse_enum_def(&generics);
5479 (id, ItemEnum(enum_definition, generics), None)
5482 /// Parses a string as an ABI spec on an extern type or module. Consumes
5483 /// the `extern` keyword, if one is found.
5484 fn parse_opt_abi(&mut self) -> Option<abi::Abi> {
5486 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
5488 self.expect_no_suffix(sp, "ABI spec", suf);
5490 let the_string = s.as_str();
5491 match abi::lookup(the_string) {
5492 Some(abi) => Some(abi),
5494 let last_span = self.last_span;
5497 &format!("illegal ABI: expected one of [{}], \
5499 abi::all_names().connect(", "),
5510 /// Parse one of the items allowed by the flags; on failure,
5511 /// return `Err(remaining_attrs)`.
5512 /// NB: this function no longer parses the items inside an
5514 fn parse_item_(&mut self, attrs: Vec<Attribute>,
5515 macros_allowed: bool) -> MaybeItem {
5516 let nt_item = match self.token {
5517 token::Interpolated(token::NtItem(ref item)) => {
5518 Some((**item).clone())
5525 let mut attrs = attrs;
5526 mem::swap(&mut item.attrs, &mut attrs);
5527 item.attrs.extend(attrs.into_iter());
5533 let lo = self.span.lo;
5535 let visibility = self.parse_visibility();
5537 if self.eat_keyword(keywords::Use) {
5539 let item_ = ItemUse(self.parse_view_path());
5540 self.expect(&token::Semi);
5542 let last_span = self.last_span;
5543 let item = self.mk_item(lo,
5545 token::special_idents::invalid,
5552 if self.eat_keyword(keywords::Extern) {
5553 if self.eat_keyword(keywords::Crate) {
5554 return Ok(self.parse_item_extern_crate(lo, visibility, attrs));
5557 let opt_abi = self.parse_opt_abi();
5559 if self.eat_keyword(keywords::Fn) {
5560 // EXTERN FUNCTION ITEM
5561 let abi = opt_abi.unwrap_or(abi::C);
5562 let (ident, item_, extra_attrs) =
5563 self.parse_item_fn(Unsafety::Normal, abi);
5564 let last_span = self.last_span;
5565 let item = self.mk_item(lo,
5570 maybe_append(attrs, extra_attrs));
5572 } else if self.check(&token::OpenDelim(token::Brace)) {
5573 return Ok(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs));
5576 let span = self.span;
5577 let token_str = self.this_token_to_string();
5578 self.span_fatal(span,
5579 &format!("expected `{}` or `fn`, found `{}`", "{",
5583 if self.eat_keyword(keywords::Virtual) {
5584 let span = self.span;
5585 self.span_err(span, "`virtual` structs have been removed from the language");
5588 if self.token.is_keyword(keywords::Static) {
5591 let m = if self.eat_keyword(keywords::Mut) {MutMutable} else {MutImmutable};
5592 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m));
5593 let last_span = self.last_span;
5594 let item = self.mk_item(lo,
5599 maybe_append(attrs, extra_attrs));
5602 if self.token.is_keyword(keywords::Const) {
5605 if self.eat_keyword(keywords::Mut) {
5606 let last_span = self.last_span;
5607 self.span_err(last_span, "const globals cannot be mutable");
5608 self.span_help(last_span, "did you mean to declare a static?");
5610 let (ident, item_, extra_attrs) = self.parse_item_const(None);
5611 let last_span = self.last_span;
5612 let item = self.mk_item(lo,
5617 maybe_append(attrs, extra_attrs));
5620 if self.token.is_keyword(keywords::Unsafe) &&
5621 self.look_ahead(1us, |t| t.is_keyword(keywords::Trait))
5623 // UNSAFE TRAIT ITEM
5624 self.expect_keyword(keywords::Unsafe);
5625 self.expect_keyword(keywords::Trait);
5626 let (ident, item_, extra_attrs) =
5627 self.parse_item_trait(ast::Unsafety::Unsafe);
5628 let last_span = self.last_span;
5629 let item = self.mk_item(lo,
5634 maybe_append(attrs, extra_attrs));
5637 if self.token.is_keyword(keywords::Unsafe) &&
5638 self.look_ahead(1us, |t| t.is_keyword(keywords::Impl))
5641 self.expect_keyword(keywords::Unsafe);
5642 self.expect_keyword(keywords::Impl);
5643 let (ident, item_, extra_attrs) = self.parse_item_impl(ast::Unsafety::Unsafe);
5644 let last_span = self.last_span;
5645 let item = self.mk_item(lo,
5650 maybe_append(attrs, extra_attrs));
5653 if self.token.is_keyword(keywords::Fn) {
5656 let (ident, item_, extra_attrs) =
5657 self.parse_item_fn(Unsafety::Normal, abi::Rust);
5658 let last_span = self.last_span;
5659 let item = self.mk_item(lo,
5664 maybe_append(attrs, extra_attrs));
5667 if self.token.is_keyword(keywords::Unsafe)
5668 && self.look_ahead(1us, |t| *t != token::OpenDelim(token::Brace)) {
5669 // UNSAFE FUNCTION ITEM
5671 let abi = if self.eat_keyword(keywords::Extern) {
5672 self.parse_opt_abi().unwrap_or(abi::C)
5676 self.expect_keyword(keywords::Fn);
5677 let (ident, item_, extra_attrs) =
5678 self.parse_item_fn(Unsafety::Unsafe, abi);
5679 let last_span = self.last_span;
5680 let item = self.mk_item(lo,
5685 maybe_append(attrs, extra_attrs));
5688 if self.eat_keyword(keywords::Mod) {
5690 let (ident, item_, extra_attrs) =
5691 self.parse_item_mod(&attrs[]);
5692 let last_span = self.last_span;
5693 let item = self.mk_item(lo,
5698 maybe_append(attrs, extra_attrs));
5701 if self.eat_keyword(keywords::Type) {
5703 let (ident, item_, extra_attrs) = self.parse_item_type();
5704 let last_span = self.last_span;
5705 let item = self.mk_item(lo,
5710 maybe_append(attrs, extra_attrs));
5713 if self.eat_keyword(keywords::Enum) {
5715 let (ident, item_, extra_attrs) = self.parse_item_enum();
5716 let last_span = self.last_span;
5717 let item = self.mk_item(lo,
5722 maybe_append(attrs, extra_attrs));
5725 if self.eat_keyword(keywords::Trait) {
5727 let (ident, item_, extra_attrs) =
5728 self.parse_item_trait(ast::Unsafety::Normal);
5729 let last_span = self.last_span;
5730 let item = self.mk_item(lo,
5735 maybe_append(attrs, extra_attrs));
5738 if self.eat_keyword(keywords::Impl) {
5740 let (ident, item_, extra_attrs) = self.parse_item_impl(ast::Unsafety::Normal);
5741 let last_span = self.last_span;
5742 let item = self.mk_item(lo,
5747 maybe_append(attrs, extra_attrs));
5750 if self.eat_keyword(keywords::Struct) {
5752 let (ident, item_, extra_attrs) = self.parse_item_struct();
5753 let last_span = self.last_span;
5754 let item = self.mk_item(lo,
5759 maybe_append(attrs, extra_attrs));
5762 self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility)
5765 /// Parse a foreign item; on failure, return `Err(remaining_attrs)`.
5766 fn parse_foreign_item(&mut self, attrs: Vec<Attribute>)
5767 -> Result<P<ForeignItem>, Vec<Attribute>> {
5768 let lo = self.span.lo;
5770 let visibility = self.parse_visibility();
5772 if self.token.is_keyword(keywords::Static) {
5773 // FOREIGN STATIC ITEM
5774 return Ok(self.parse_item_foreign_static(visibility, attrs));
5776 if self.token.is_keyword(keywords::Fn) || self.token.is_keyword(keywords::Unsafe) {
5777 // FOREIGN FUNCTION ITEM
5778 return Ok(self.parse_item_foreign_fn(visibility, attrs));
5781 // FIXME #5668: this will occur for a macro invocation:
5782 let item = try!(self.parse_macro_use_or_failure(attrs, true, lo, visibility));
5783 self.span_fatal(item.span, "macros cannot expand to foreign items");
5786 /// This is the fall-through for parsing items.
5787 fn parse_macro_use_or_failure(
5789 attrs: Vec<Attribute> ,
5790 macros_allowed: bool,
5792 visibility: Visibility
5794 if macros_allowed && !self.token.is_any_keyword()
5795 && self.look_ahead(1, |t| *t == token::Not)
5796 && (self.look_ahead(2, |t| t.is_plain_ident())
5797 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren))
5798 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) {
5799 // MACRO INVOCATION ITEM
5802 let pth = self.parse_path(NoTypesAllowed);
5803 self.expect(&token::Not);
5805 // a 'special' identifier (like what `macro_rules!` uses)
5806 // is optional. We should eventually unify invoc syntax
5808 let id = if self.token.is_plain_ident() {
5811 token::special_idents::invalid // no special identifier
5813 // eat a matched-delimiter token tree:
5814 let delim = self.expect_open_delim();
5815 let tts = self.parse_seq_to_end(&token::CloseDelim(delim),
5817 |p| p.parse_token_tree());
5818 // single-variant-enum... :
5819 let m = ast::MacInvocTT(pth, tts, EMPTY_CTXT);
5820 let m: ast::Mac = codemap::Spanned { node: m,
5821 span: mk_sp(self.span.lo,
5824 if delim != token::Brace {
5825 if !self.eat(&token::Semi) {
5826 let last_span = self.last_span;
5827 self.span_err(last_span,
5828 "macros that expand to items must either \
5829 be surrounded with braces or followed by \
5834 let item_ = ItemMac(m);
5835 let last_span = self.last_span;
5836 let item = self.mk_item(lo,
5845 // FAILURE TO PARSE ITEM
5849 let last_span = self.last_span;
5850 self.span_fatal(last_span, "unmatched visibility `pub`");
5856 pub fn parse_item_with_outer_attributes(&mut self) -> Option<P<Item>> {
5857 let attrs = self.parse_outer_attributes();
5858 self.parse_item(attrs)
5861 pub fn parse_item(&mut self, attrs: Vec<Attribute>) -> Option<P<Item>> {
5862 self.parse_item_(attrs, true).ok()
5865 /// Matches view_path : MOD? non_global_path as IDENT
5866 /// | MOD? non_global_path MOD_SEP LBRACE RBRACE
5867 /// | MOD? non_global_path MOD_SEP LBRACE ident_seq RBRACE
5868 /// | MOD? non_global_path MOD_SEP STAR
5869 /// | MOD? non_global_path
5870 fn parse_view_path(&mut self) -> P<ViewPath> {
5871 let lo = self.span.lo;
5873 // Allow a leading :: because the paths are absolute either way.
5874 // This occurs with "use $crate::..." in macros.
5875 self.eat(&token::ModSep);
5877 if self.check(&token::OpenDelim(token::Brace)) {
5879 let idents = self.parse_unspanned_seq(
5880 &token::OpenDelim(token::Brace),
5881 &token::CloseDelim(token::Brace),
5882 seq_sep_trailing_allowed(token::Comma),
5883 |p| p.parse_path_list_item());
5884 let path = ast::Path {
5885 span: mk_sp(lo, self.span.hi),
5887 segments: Vec::new()
5889 return P(spanned(lo, self.span.hi, ViewPathList(path, idents)));
5892 let first_ident = self.parse_ident();
5893 let mut path = vec!(first_ident);
5894 if let token::ModSep = self.token {
5895 // foo::bar or foo::{a,b,c} or foo::*
5896 while self.check(&token::ModSep) {
5900 token::Ident(i, _) => {
5905 // foo::bar::{a,b,c}
5906 token::OpenDelim(token::Brace) => {
5907 let idents = self.parse_unspanned_seq(
5908 &token::OpenDelim(token::Brace),
5909 &token::CloseDelim(token::Brace),
5910 seq_sep_trailing_allowed(token::Comma),
5911 |p| p.parse_path_list_item()
5913 let path = ast::Path {
5914 span: mk_sp(lo, self.span.hi),
5916 segments: path.into_iter().map(|identifier| {
5918 identifier: identifier,
5919 parameters: ast::PathParameters::none(),
5923 return P(spanned(lo, self.span.hi, ViewPathList(path, idents)));
5927 token::BinOp(token::Star) => {
5929 let path = ast::Path {
5930 span: mk_sp(lo, self.span.hi),
5932 segments: path.into_iter().map(|identifier| {
5934 identifier: identifier,
5935 parameters: ast::PathParameters::none(),
5939 return P(spanned(lo, self.span.hi, ViewPathGlob(path)));
5946 let mut rename_to = path[path.len() - 1us];
5947 let path = ast::Path {
5948 span: mk_sp(lo, self.last_span.hi),
5950 segments: path.into_iter().map(|identifier| {
5952 identifier: identifier,
5953 parameters: ast::PathParameters::none(),
5957 if self.eat_keyword(keywords::As) {
5958 rename_to = self.parse_ident()
5960 P(spanned(lo, self.last_span.hi, ViewPathSimple(rename_to, path)))
5963 /// Parses a sequence of foreign items. Stops when it finds program
5964 /// text that can't be parsed as an item
5965 fn parse_foreign_items(&mut self, first_item_attrs: Vec<Attribute>)
5966 -> Vec<P<ForeignItem>> {
5967 let mut attrs = first_item_attrs;
5968 attrs.push_all(&self.parse_outer_attributes()[]);
5969 let mut foreign_items = Vec::new();
5971 match self.parse_foreign_item(attrs) {
5972 Ok(foreign_item) => {
5973 foreign_items.push(foreign_item);
5975 Err(returned_attrs) => {
5976 if self.check(&token::CloseDelim(token::Brace)) {
5977 attrs = returned_attrs;
5983 attrs = self.parse_outer_attributes();
5986 if !attrs.is_empty() {
5987 let last_span = self.last_span;
5988 self.span_err(last_span,
5989 Parser::expected_item_err(&attrs[]));
5995 /// Parses a source module as a crate. This is the main
5996 /// entry point for the parser.
5997 pub fn parse_crate_mod(&mut self) -> Crate {
5998 let lo = self.span.lo;
5999 // parse the crate's inner attrs, maybe (oops) one
6000 // of the attrs of an item:
6001 let (inner, next) = self.parse_inner_attrs_and_next();
6002 let first_item_outer_attrs = next;
6003 // parse the items inside the crate:
6004 let m = self.parse_mod_items(token::Eof, first_item_outer_attrs, lo);
6009 config: self.cfg.clone(),
6010 span: mk_sp(lo, self.span.lo),
6011 exported_macros: Vec::new(),
6015 pub fn parse_optional_str(&mut self)
6016 -> Option<(InternedString, ast::StrStyle, Option<ast::Name>)> {
6017 let ret = match self.token {
6018 token::Literal(token::Str_(s), suf) => {
6019 (self.id_to_interned_str(s.ident()), ast::CookedStr, suf)
6021 token::Literal(token::StrRaw(s, n), suf) => {
6022 (self.id_to_interned_str(s.ident()), ast::RawStr(n), suf)
6030 pub fn parse_str(&mut self) -> (InternedString, StrStyle) {
6031 match self.parse_optional_str() {
6032 Some((s, style, suf)) => {
6033 let sp = self.last_span;
6034 self.expect_no_suffix(sp, "str literal", suf);
6037 _ => self.fatal("expected string literal")