1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 pub use self::PathParsingMode::*;
14 use ast::{AssociatedType, BareFnTy};
15 use ast::{RegionTyParamBound, TraitTyParamBound, TraitBoundModifier};
16 use ast::{ProvidedMethod, Public, Unsafety};
17 use ast::{Mod, BiAdd, Arg, Arm, Attribute, BindByRef, BindByValue};
18 use ast::{BiBitAnd, BiBitOr, BiBitXor, BiRem, BiLt, BiGt, Block};
19 use ast::{BlockCheckMode, CaptureByRef, CaptureByValue, CaptureClause};
20 use ast::{Crate, CrateConfig, Decl, DeclItem};
21 use ast::{DeclLocal, DefaultBlock, DefaultReturn};
22 use ast::{UnDeref, BiDiv, EMPTY_CTXT, EnumDef, ExplicitSelf};
23 use ast::{Expr, Expr_, ExprAddrOf, ExprMatch, ExprAgain};
24 use ast::{ExprAssign, ExprAssignOp, ExprBinary, ExprBlock, ExprBox};
25 use ast::{ExprBreak, ExprCall, ExprCast};
26 use ast::{ExprField, ExprTupField, ExprClosure, ExprIf, ExprIfLet, ExprIndex};
27 use ast::{ExprLit, ExprLoop, ExprMac, ExprRange};
28 use ast::{ExprMethodCall, ExprParen, ExprPath, ExprQPath};
29 use ast::{ExprRepeat, ExprRet, ExprStruct, ExprTup, ExprUnary};
30 use ast::{ExprVec, ExprWhile, ExprWhileLet, ExprForLoop, Field, FnDecl};
31 use ast::{ForeignItem, ForeignItemStatic, ForeignItemFn, ForeignMod, FunctionRetTy};
32 use ast::{Ident, Inherited, ImplItem, Item, Item_, ItemStatic};
33 use ast::{ItemEnum, ItemFn, ItemForeignMod, ItemImpl, ItemConst};
34 use ast::{ItemMac, ItemMod, ItemStruct, ItemTrait, ItemTy};
35 use ast::{ItemExternCrate, ItemUse};
36 use ast::{LifetimeDef, Lit, Lit_};
37 use ast::{LitBool, LitChar, LitByte, LitBinary};
38 use ast::{LitStr, LitInt, Local, LocalLet};
39 use ast::{MacStmtWithBraces, MacStmtWithSemicolon, MacStmtWithoutBraces};
40 use ast::{MutImmutable, MutMutable, Mac_, MacInvocTT, MatchSource};
41 use ast::{Method, MutTy, BiMul, Mutability};
42 use ast::{MethodImplItem, NamedField, UnNeg, NoReturn, NodeId, UnNot};
43 use ast::{Pat, PatEnum, PatIdent, PatLit, PatRange, PatRegion, PatStruct};
44 use ast::{PatTup, PatBox, PatWild, PatWildMulti, PatWildSingle};
45 use ast::{PolyTraitRef};
46 use ast::{QPath, RequiredMethod};
47 use ast::{Return, BiShl, BiShr, Stmt, StmtDecl};
48 use ast::{StmtExpr, StmtSemi, StmtMac, StructDef, StructField};
49 use ast::{StructVariantKind, BiSub, StrStyle};
50 use ast::{SelfExplicit, SelfRegion, SelfStatic, SelfValue};
51 use ast::{Delimited, SequenceRepetition, TokenTree, TraitItem, TraitRef};
52 use ast::{TtDelimited, TtSequence, TtToken};
53 use ast::{TupleVariantKind, Ty, Ty_, TypeBinding};
54 use ast::{TyFixedLengthVec, TyBareFn};
55 use ast::{TyTypeof, TyInfer, TypeMethod};
56 use ast::{TyParam, TyParamBound, TyParen, TyPath, TyPolyTraitRef, TyPtr, TyQPath};
57 use ast::{TyRptr, TyTup, TyU32, TyVec, UnUniq};
58 use ast::{TypeImplItem, TypeTraitItem, Typedef,};
59 use ast::{UnnamedField, UnsafeBlock};
60 use ast::{ViewPath, ViewPathGlob, ViewPathList, ViewPathSimple};
61 use ast::{Visibility, WhereClause};
63 use ast_util::{self, AS_PREC, ident_to_path, operator_prec};
64 use codemap::{self, Span, BytePos, Spanned, spanned, mk_sp};
66 use ext::tt::macro_parser;
68 use parse::attr::ParserAttr;
70 use parse::common::{SeqSep, seq_sep_none, seq_sep_trailing_allowed};
71 use parse::lexer::{Reader, TokenAndSpan};
72 use parse::obsolete::{ParserObsoleteMethods, ObsoleteSyntax};
73 use parse::token::{self, MatchNt, SubstNt, SpecialVarNt, InternedString};
74 use parse::token::{keywords, special_idents, SpecialMacroVar};
75 use parse::{new_sub_parser_from_file, ParseSess};
78 use owned_slice::OwnedSlice;
80 use std::collections::HashSet;
81 use std::old_io::fs::PathExtensions;
89 flags Restrictions: u8 {
90 const UNRESTRICTED = 0b0000,
91 const RESTRICTION_STMT_EXPR = 0b0001,
92 const RESTRICTION_NO_BAR_OP = 0b0010,
93 const RESTRICTION_NO_STRUCT_LITERAL = 0b0100,
98 type ItemInfo = (Ident, Item_, Option<Vec<Attribute> >);
100 /// How to parse a path. There are four different kinds of paths, all of which
101 /// are parsed somewhat differently.
102 #[derive(Copy, PartialEq)]
103 pub enum PathParsingMode {
104 /// A path with no type parameters; e.g. `foo::bar::Baz`
106 /// A path with a lifetime and type parameters, with no double colons
107 /// before the type parameters; e.g. `foo::bar<'a>::Baz<T>`
108 LifetimeAndTypesWithoutColons,
109 /// A path with a lifetime and type parameters with double colons before
110 /// the type parameters; e.g. `foo::bar::<'a>::Baz::<T>`
111 LifetimeAndTypesWithColons,
114 /// How to parse a bound, whether to allow bound modifiers such as `?`.
115 #[derive(Copy, PartialEq)]
116 pub enum BoundParsingMode {
121 /// The `Err` case indicates a failure to parse any kind of item.
122 /// The attributes are returned.
123 type MaybeItem = Result<P<Item>, Vec<Attribute>>;
126 /// Possibly accept an `token::Interpolated` expression (a pre-parsed expression
127 /// dropped into the token stream, which happens while parsing the result of
128 /// macro expansion). Placement of these is not as complex as I feared it would
129 /// be. The important thing is to make sure that lookahead doesn't balk at
130 /// `token::Interpolated` tokens.
131 macro_rules! maybe_whole_expr {
134 let found = match $p.token {
135 token::Interpolated(token::NtExpr(ref e)) => {
138 token::Interpolated(token::NtPath(_)) => {
139 // FIXME: The following avoids an issue with lexical borrowck scopes,
140 // but the clone is unfortunate.
141 let pt = match $p.token {
142 token::Interpolated(token::NtPath(ref pt)) => (**pt).clone(),
146 Some($p.mk_expr(span.lo, span.hi, ExprPath(pt)))
148 token::Interpolated(token::NtBlock(_)) => {
149 // FIXME: The following avoids an issue with lexical borrowck scopes,
150 // but the clone is unfortunate.
151 let b = match $p.token {
152 token::Interpolated(token::NtBlock(ref b)) => (*b).clone(),
156 Some($p.mk_expr(span.lo, span.hi, ExprBlock(b)))
171 /// As maybe_whole_expr, but for things other than expressions
172 macro_rules! maybe_whole {
173 ($p:expr, $constructor:ident) => (
175 let found = match ($p).token {
176 token::Interpolated(token::$constructor(_)) => {
177 Some(($p).bump_and_get())
181 if let Some(token::Interpolated(token::$constructor(x))) = found {
186 (no_clone $p:expr, $constructor:ident) => (
188 let found = match ($p).token {
189 token::Interpolated(token::$constructor(_)) => {
190 Some(($p).bump_and_get())
194 if let Some(token::Interpolated(token::$constructor(x))) = found {
199 (deref $p:expr, $constructor:ident) => (
201 let found = match ($p).token {
202 token::Interpolated(token::$constructor(_)) => {
203 Some(($p).bump_and_get())
207 if let Some(token::Interpolated(token::$constructor(x))) = found {
212 (Some $p:expr, $constructor:ident) => (
214 let found = match ($p).token {
215 token::Interpolated(token::$constructor(_)) => {
216 Some(($p).bump_and_get())
220 if let Some(token::Interpolated(token::$constructor(x))) = found {
221 return Some(x.clone());
225 (pair_empty $p:expr, $constructor:ident) => (
227 let found = match ($p).token {
228 token::Interpolated(token::$constructor(_)) => {
229 Some(($p).bump_and_get())
233 if let Some(token::Interpolated(token::$constructor(x))) = found {
234 return (Vec::new(), x);
241 fn maybe_append(mut lhs: Vec<Attribute>, rhs: Option<Vec<Attribute>>)
243 if let Some(ref attrs) = rhs {
244 lhs.extend(attrs.iter().cloned())
249 /* ident is handled by common.rs */
251 pub struct Parser<'a> {
252 pub sess: &'a ParseSess,
253 /// the current token:
254 pub token: token::Token,
255 /// the span of the current token:
257 /// the span of the prior token:
259 pub cfg: CrateConfig,
260 /// the previous token or None (only stashed sometimes).
261 pub last_token: Option<Box<token::Token>>,
262 pub buffer: [TokenAndSpan; 4],
263 pub buffer_start: isize,
264 pub buffer_end: isize,
265 pub tokens_consumed: usize,
266 pub restrictions: Restrictions,
267 pub quote_depth: usize, // not (yet) related to the quasiquoter
268 pub reader: Box<Reader+'a>,
269 pub interner: Rc<token::IdentInterner>,
270 /// The set of seen errors about obsolete syntax. Used to suppress
271 /// extra detail when the same error is seen twice
272 pub obsolete_set: HashSet<ObsoleteSyntax>,
273 /// Used to determine the path to externally loaded source files
274 pub mod_path_stack: Vec<InternedString>,
275 /// Stack of spans of open delimiters. Used for error message.
276 pub open_braces: Vec<Span>,
277 /// Flag if this parser "owns" the directory that it is currently parsing
278 /// in. This will affect how nested files are looked up.
279 pub owns_directory: bool,
280 /// Name of the root module this parser originated from. If `None`, then the
281 /// name is not known. This does not change while the parser is descending
282 /// into modules, and sub-parsers have new values for this name.
283 pub root_module_name: Option<String>,
284 pub expected_tokens: Vec<TokenType>,
287 #[derive(PartialEq, Eq, Clone)]
290 Keyword(keywords::Keyword),
295 fn to_string(&self) -> String {
297 TokenType::Token(ref t) => format!("`{}`", Parser::token_to_string(t)),
298 TokenType::Operator => "an operator".to_string(),
299 TokenType::Keyword(kw) => format!("`{}`", token::get_name(kw.to_name())),
304 fn is_plain_ident_or_underscore(t: &token::Token) -> bool {
305 t.is_plain_ident() || *t == token::Underscore
308 impl<'a> Parser<'a> {
309 pub fn new(sess: &'a ParseSess,
310 cfg: ast::CrateConfig,
311 mut rdr: Box<Reader+'a>)
314 let tok0 = rdr.real_token();
316 let placeholder = TokenAndSpan {
317 tok: token::Underscore,
323 interner: token::get_ident_interner(),
339 restrictions: UNRESTRICTED,
341 obsolete_set: HashSet::new(),
342 mod_path_stack: Vec::new(),
343 open_braces: Vec::new(),
344 owns_directory: true,
345 root_module_name: None,
346 expected_tokens: Vec::new(),
350 /// Convert a token to a string using self's reader
351 pub fn token_to_string(token: &token::Token) -> String {
352 pprust::token_to_string(token)
355 /// Convert the current token to a string using self's reader
356 pub fn this_token_to_string(&self) -> String {
357 Parser::token_to_string(&self.token)
360 pub fn unexpected_last(&self, t: &token::Token) -> ! {
361 let token_str = Parser::token_to_string(t);
362 let last_span = self.last_span;
363 self.span_fatal(last_span, &format!("unexpected token: `{}`",
367 pub fn unexpected(&mut self) -> ! {
368 self.expect_one_of(&[], &[]);
372 /// Expect and consume the token t. Signal an error if
373 /// the next token is not t.
374 pub fn expect(&mut self, t: &token::Token) {
375 if self.expected_tokens.is_empty() {
376 if self.token == *t {
379 let token_str = Parser::token_to_string(t);
380 let this_token_str = self.this_token_to_string();
381 self.fatal(&format!("expected `{}`, found `{}`",
386 self.expect_one_of(slice::ref_slice(t), &[]);
390 /// Expect next token to be edible or inedible token. If edible,
391 /// then consume it; if inedible, then return without consuming
392 /// anything. Signal a fatal error if next token is unexpected.
393 pub fn expect_one_of(&mut self,
394 edible: &[token::Token],
395 inedible: &[token::Token]) {
396 fn tokens_to_string(tokens: &[TokenType]) -> String {
397 let mut i = tokens.iter();
398 // This might be a sign we need a connect method on Iterator.
400 .map_or("".to_string(), |t| t.to_string());
401 i.enumerate().fold(b, |mut b, (i, ref a)| {
402 if tokens.len() > 2 && i == tokens.len() - 2 {
404 } else if tokens.len() == 2 && i == tokens.len() - 2 {
409 b.push_str(&*a.to_string());
413 if edible.contains(&self.token) {
415 } else if inedible.contains(&self.token) {
416 // leave it in the input
418 let mut expected = edible.iter().map(|x| TokenType::Token(x.clone()))
419 .collect::<Vec<_>>();
420 expected.extend(inedible.iter().map(|x| TokenType::Token(x.clone())));
421 expected.push_all(&*self.expected_tokens);
422 expected.sort_by(|a, b| a.to_string().cmp(&b.to_string()));
424 let expect = tokens_to_string(&expected[..]);
425 let actual = self.this_token_to_string();
427 &(if expected.len() > 1 {
428 (format!("expected one of {}, found `{}`",
431 } else if expected.len() == 0 {
432 (format!("unexpected token: `{}`",
435 (format!("expected {}, found `{}`",
443 /// Check for erroneous `ident { }`; if matches, signal error and
444 /// recover (without consuming any expected input token). Returns
445 /// true if and only if input was consumed for recovery.
446 pub fn check_for_erroneous_unit_struct_expecting(&mut self, expected: &[token::Token]) -> bool {
447 if self.token == token::OpenDelim(token::Brace)
448 && expected.iter().all(|t| *t != token::OpenDelim(token::Brace))
449 && self.look_ahead(1, |t| *t == token::CloseDelim(token::Brace)) {
450 // matched; signal non-fatal error and recover.
451 let span = self.span;
453 "unit-like struct construction is written with no trailing `{ }`");
454 self.eat(&token::OpenDelim(token::Brace));
455 self.eat(&token::CloseDelim(token::Brace));
462 /// Commit to parsing a complete expression `e` expected to be
463 /// followed by some token from the set edible + inedible. Recover
464 /// from anticipated input errors, discarding erroneous characters.
465 pub fn commit_expr(&mut self, e: &Expr, edible: &[token::Token], inedible: &[token::Token]) {
466 debug!("commit_expr {:?}", e);
467 if let ExprPath(..) = e.node {
468 // might be unit-struct construction; check for recoverableinput error.
469 let mut expected = edible.iter().cloned().collect::<Vec<_>>();
470 expected.push_all(inedible);
471 self.check_for_erroneous_unit_struct_expecting(&expected[..]);
473 self.expect_one_of(edible, inedible)
476 pub fn commit_expr_expecting(&mut self, e: &Expr, edible: token::Token) {
477 self.commit_expr(e, &[edible], &[])
480 /// Commit to parsing a complete statement `s`, which expects to be
481 /// followed by some token from the set edible + inedible. Check
482 /// for recoverable input errors, discarding erroneous characters.
483 pub fn commit_stmt(&mut self, edible: &[token::Token], inedible: &[token::Token]) {
486 .map_or(false, |t| t.is_ident() || t.is_path()) {
487 let mut expected = edible.iter().cloned().collect::<Vec<_>>();
488 expected.push_all(&inedible);
489 self.check_for_erroneous_unit_struct_expecting(&expected);
491 self.expect_one_of(edible, inedible)
494 pub fn commit_stmt_expecting(&mut self, edible: token::Token) {
495 self.commit_stmt(&[edible], &[])
498 pub fn parse_ident(&mut self) -> ast::Ident {
499 self.check_strict_keywords();
500 self.check_reserved_keywords();
502 token::Ident(i, _) => {
506 token::Interpolated(token::NtIdent(..)) => {
507 self.bug("ident interpolation not converted to real token");
510 let token_str = self.this_token_to_string();
511 self.fatal(&format!("expected ident, found `{}`",
517 pub fn parse_ident_or_self_type(&mut self) -> ast::Ident {
518 if self.is_self_type_ident() {
519 self.expect_self_type_ident()
525 pub fn parse_path_list_item(&mut self) -> ast::PathListItem {
526 let lo = self.span.lo;
527 let node = if self.eat_keyword_noexpect(keywords::Mod) {
528 let span = self.last_span;
529 self.span_warn(span, "deprecated syntax; use the `self` keyword now");
530 ast::PathListMod { id: ast::DUMMY_NODE_ID }
531 } else if self.eat_keyword(keywords::SelfValue) {
532 ast::PathListMod { id: ast::DUMMY_NODE_ID }
534 let ident = self.parse_ident();
535 ast::PathListIdent { name: ident, id: ast::DUMMY_NODE_ID }
537 let hi = self.last_span.hi;
538 spanned(lo, hi, node)
541 /// Check if the next token is `tok`, and return `true` if so.
543 /// This method is will automatically add `tok` to `expected_tokens` if `tok` is not
545 pub fn check(&mut self, tok: &token::Token) -> bool {
546 let is_present = self.token == *tok;
547 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
551 /// Consume token 'tok' if it exists. Returns true if the given
552 /// token was present, false otherwise.
553 pub fn eat(&mut self, tok: &token::Token) -> bool {
554 let is_present = self.check(tok);
555 if is_present { self.bump() }
559 pub fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
560 self.expected_tokens.push(TokenType::Keyword(kw));
561 self.token.is_keyword(kw)
564 /// If the next token is the given keyword, eat it and return
565 /// true. Otherwise, return false.
566 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
567 if self.check_keyword(kw) {
575 pub fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
576 if self.token.is_keyword(kw) {
584 /// If the given word is not a keyword, signal an error.
585 /// If the next token is not the given word, signal an error.
586 /// Otherwise, eat it.
587 pub fn expect_keyword(&mut self, kw: keywords::Keyword) {
588 if !self.eat_keyword(kw) {
589 self.expect_one_of(&[], &[]);
593 /// Signal an error if the given string is a strict keyword
594 pub fn check_strict_keywords(&mut self) {
595 if self.token.is_strict_keyword() {
596 let token_str = self.this_token_to_string();
597 let span = self.span;
599 &format!("expected identifier, found keyword `{}`",
604 /// Signal an error if the current token is a reserved keyword
605 pub fn check_reserved_keywords(&mut self) {
606 if self.token.is_reserved_keyword() {
607 let token_str = self.this_token_to_string();
608 self.fatal(&format!("`{}` is a reserved keyword",
613 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
614 /// `&` and continue. If an `&` is not seen, signal an error.
615 fn expect_and(&mut self) {
616 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
618 token::BinOp(token::And) => self.bump(),
620 let span = self.span;
621 let lo = span.lo + BytePos(1);
622 self.replace_token(token::BinOp(token::And), lo, span.hi)
625 self.expect_one_of(&[], &[]);
630 /// Expect and consume a `|`. If `||` is seen, replace it with a single
631 /// `|` and continue. If a `|` is not seen, signal an error.
632 fn expect_or(&mut self) {
633 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or)));
635 token::BinOp(token::Or) => self.bump(),
637 let span = self.span;
638 let lo = span.lo + BytePos(1);
639 self.replace_token(token::BinOp(token::Or), lo, span.hi)
642 self.expect_one_of(&[], &[]);
647 pub fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
649 None => {/* everything ok */}
651 let text = suf.as_str();
653 self.span_bug(sp, "found empty literal suffix in Some")
655 self.span_err(sp, &*format!("{} with a suffix is illegal", kind));
661 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
662 /// `<` and continue. If a `<` is not seen, return false.
664 /// This is meant to be used when parsing generics on a path to get the
666 fn eat_lt(&mut self) -> bool {
667 self.expected_tokens.push(TokenType::Token(token::Lt));
669 token::Lt => { self.bump(); true }
670 token::BinOp(token::Shl) => {
671 let span = self.span;
672 let lo = span.lo + BytePos(1);
673 self.replace_token(token::Lt, lo, span.hi);
680 fn expect_lt(&mut self) {
682 self.expect_one_of(&[], &[]);
686 /// Parse a sequence bracketed by `|` and `|`, stopping before the `|`.
687 fn parse_seq_to_before_or<T, F>(&mut self,
691 F: FnMut(&mut Parser) -> T,
693 let mut first = true;
694 let mut vector = Vec::new();
695 while self.token != token::BinOp(token::Or) &&
696 self.token != token::OrOr {
708 /// Expect and consume a GT. if a >> is seen, replace it
709 /// with a single > and continue. If a GT is not seen,
711 pub fn expect_gt(&mut self) {
712 self.expected_tokens.push(TokenType::Token(token::Gt));
714 token::Gt => self.bump(),
715 token::BinOp(token::Shr) => {
716 let span = self.span;
717 let lo = span.lo + BytePos(1);
718 self.replace_token(token::Gt, lo, span.hi)
720 token::BinOpEq(token::Shr) => {
721 let span = self.span;
722 let lo = span.lo + BytePos(1);
723 self.replace_token(token::Ge, lo, span.hi)
726 let span = self.span;
727 let lo = span.lo + BytePos(1);
728 self.replace_token(token::Eq, lo, span.hi)
731 let gt_str = Parser::token_to_string(&token::Gt);
732 let this_token_str = self.this_token_to_string();
733 self.fatal(&format!("expected `{}`, found `{}`",
740 pub fn parse_seq_to_before_gt_or_return<T, F>(&mut self,
741 sep: Option<token::Token>,
743 -> (OwnedSlice<T>, bool) where
744 F: FnMut(&mut Parser) -> Option<T>,
746 let mut v = Vec::new();
747 // This loop works by alternating back and forth between parsing types
748 // and commas. For example, given a string `A, B,>`, the parser would
749 // first parse `A`, then a comma, then `B`, then a comma. After that it
750 // would encounter a `>` and stop. This lets the parser handle trailing
751 // commas in generic parameters, because it can stop either after
752 // parsing a type or after parsing a comma.
753 for i in iter::count(0, 1) {
754 if self.check(&token::Gt)
755 || self.token == token::BinOp(token::Shr)
756 || self.token == token::Ge
757 || self.token == token::BinOpEq(token::Shr) {
763 Some(result) => v.push(result),
764 None => return (OwnedSlice::from_vec(v), true)
767 sep.as_ref().map(|t| self.expect(t));
770 return (OwnedSlice::from_vec(v), false);
773 /// Parse a sequence bracketed by '<' and '>', stopping
775 pub fn parse_seq_to_before_gt<T, F>(&mut self,
776 sep: Option<token::Token>,
778 -> OwnedSlice<T> where
779 F: FnMut(&mut Parser) -> T,
781 let (result, returned) = self.parse_seq_to_before_gt_or_return(sep, |p| Some(f(p)));
786 pub fn parse_seq_to_gt<T, F>(&mut self,
787 sep: Option<token::Token>,
789 -> OwnedSlice<T> where
790 F: FnMut(&mut Parser) -> T,
792 let v = self.parse_seq_to_before_gt(sep, f);
797 pub fn parse_seq_to_gt_or_return<T, F>(&mut self,
798 sep: Option<token::Token>,
800 -> (OwnedSlice<T>, bool) where
801 F: FnMut(&mut Parser) -> Option<T>,
803 let (v, returned) = self.parse_seq_to_before_gt_or_return(sep, f);
807 return (v, returned);
810 /// Parse a sequence, including the closing delimiter. The function
811 /// f must consume tokens until reaching the next separator or
813 pub fn parse_seq_to_end<T, F>(&mut self,
818 F: FnMut(&mut Parser) -> T,
820 let val = self.parse_seq_to_before_end(ket, sep, f);
825 /// Parse a sequence, not including the closing delimiter. The function
826 /// f must consume tokens until reaching the next separator or
828 pub fn parse_seq_to_before_end<T, F>(&mut self,
833 F: FnMut(&mut Parser) -> T,
835 let mut first: bool = true;
837 while self.token != *ket {
840 if first { first = false; }
841 else { self.expect(t); }
845 if sep.trailing_sep_allowed && self.check(ket) { break; }
851 /// Parse a sequence, including the closing delimiter. The function
852 /// f must consume tokens until reaching the next separator or
854 pub fn parse_unspanned_seq<T, F>(&mut self,
860 F: FnMut(&mut Parser) -> T,
863 let result = self.parse_seq_to_before_end(ket, sep, f);
868 /// Parse a sequence parameter of enum variant. For consistency purposes,
869 /// these should not be empty.
870 pub fn parse_enum_variant_seq<T, F>(&mut self,
876 F: FnMut(&mut Parser) -> T,
878 let result = self.parse_unspanned_seq(bra, ket, sep, f);
879 if result.is_empty() {
880 let last_span = self.last_span;
881 self.span_err(last_span,
882 "nullary enum variants are written with no trailing `( )`");
887 // NB: Do not use this function unless you actually plan to place the
888 // spanned list in the AST.
889 pub fn parse_seq<T, F>(&mut self,
894 -> Spanned<Vec<T>> where
895 F: FnMut(&mut Parser) -> T,
897 let lo = self.span.lo;
899 let result = self.parse_seq_to_before_end(ket, sep, f);
900 let hi = self.span.hi;
902 spanned(lo, hi, result)
905 /// Advance the parser by one token
906 pub fn bump(&mut self) {
907 self.last_span = self.span;
908 // Stash token for error recovery (sometimes; clone is not necessarily cheap).
909 self.last_token = if self.token.is_ident() || self.token.is_path() {
910 Some(box self.token.clone())
914 let next = if self.buffer_start == self.buffer_end {
915 self.reader.real_token()
917 // Avoid token copies with `replace`.
918 let buffer_start = self.buffer_start as usize;
919 let next_index = (buffer_start + 1) & 3 as usize;
920 self.buffer_start = next_index as isize;
922 let placeholder = TokenAndSpan {
923 tok: token::Underscore,
926 mem::replace(&mut self.buffer[buffer_start], placeholder)
929 self.token = next.tok;
930 self.tokens_consumed += 1;
931 self.expected_tokens.clear();
932 // check after each token
933 self.check_unknown_macro_variable();
936 /// Advance the parser by one token and return the bumped token.
937 pub fn bump_and_get(&mut self) -> token::Token {
938 let old_token = mem::replace(&mut self.token, token::Underscore);
943 /// EFFECT: replace the current token and span with the given one
944 pub fn replace_token(&mut self,
948 self.last_span = mk_sp(self.span.lo, lo);
950 self.span = mk_sp(lo, hi);
952 pub fn buffer_length(&mut self) -> isize {
953 if self.buffer_start <= self.buffer_end {
954 return self.buffer_end - self.buffer_start;
956 return (4 - self.buffer_start) + self.buffer_end;
958 pub fn look_ahead<R, F>(&mut self, distance: usize, f: F) -> R where
959 F: FnOnce(&token::Token) -> R,
961 let dist = distance as isize;
962 while self.buffer_length() < dist {
963 self.buffer[self.buffer_end as usize] = self.reader.real_token();
964 self.buffer_end = (self.buffer_end + 1) & 3;
966 f(&self.buffer[((self.buffer_start + dist - 1) & 3) as usize].tok)
968 pub fn fatal(&self, m: &str) -> ! {
969 self.sess.span_diagnostic.span_fatal(self.span, m)
971 pub fn span_fatal(&self, sp: Span, m: &str) -> ! {
972 self.sess.span_diagnostic.span_fatal(sp, m)
974 pub fn span_fatal_help(&self, sp: Span, m: &str, help: &str) -> ! {
975 self.span_err(sp, m);
976 self.span_help(sp, help);
977 panic!(diagnostic::FatalError);
979 pub fn span_note(&self, sp: Span, m: &str) {
980 self.sess.span_diagnostic.span_note(sp, m)
982 pub fn span_help(&self, sp: Span, m: &str) {
983 self.sess.span_diagnostic.span_help(sp, m)
985 pub fn bug(&self, m: &str) -> ! {
986 self.sess.span_diagnostic.span_bug(self.span, m)
988 pub fn warn(&self, m: &str) {
989 self.sess.span_diagnostic.span_warn(self.span, m)
991 pub fn span_warn(&self, sp: Span, m: &str) {
992 self.sess.span_diagnostic.span_warn(sp, m)
994 pub fn span_err(&self, sp: Span, m: &str) {
995 self.sess.span_diagnostic.span_err(sp, m)
997 pub fn span_bug(&self, sp: Span, m: &str) -> ! {
998 self.sess.span_diagnostic.span_bug(sp, m)
1000 pub fn abort_if_errors(&self) {
1001 self.sess.span_diagnostic.handler().abort_if_errors();
1004 pub fn id_to_interned_str(&mut self, id: Ident) -> InternedString {
1005 token::get_ident(id)
1008 /// Is the current token one of the keywords that signals a bare function
1010 pub fn token_is_bare_fn_keyword(&mut self) -> bool {
1011 self.check_keyword(keywords::Fn) ||
1012 self.check_keyword(keywords::Unsafe) ||
1013 self.check_keyword(keywords::Extern)
1016 /// Is the current token one of the keywords that signals a closure type?
1017 pub fn token_is_closure_keyword(&mut self) -> bool {
1018 self.check_keyword(keywords::Unsafe)
1021 pub fn get_lifetime(&mut self) -> ast::Ident {
1023 token::Lifetime(ref ident) => *ident,
1024 _ => self.bug("not a lifetime"),
1028 pub fn parse_for_in_type(&mut self) -> Ty_ {
1030 Parses whatever can come after a `for` keyword in a type.
1031 The `for` has already been consumed.
1035 - for <'lt> |S| -> T
1039 - for <'lt> [unsafe] [extern "ABI"] fn (S) -> T
1040 - for <'lt> path::foo(a, b)
1045 let lo = self.span.lo;
1047 let lifetime_defs = self.parse_late_bound_lifetime_defs();
1049 // examine next token to decide to do
1050 if self.eat_keyword_noexpect(keywords::Proc) {
1051 self.parse_proc_type(lifetime_defs)
1052 } else if self.token_is_bare_fn_keyword() || self.token_is_closure_keyword() {
1053 self.parse_ty_bare_fn_or_ty_closure(lifetime_defs)
1054 } else if self.check(&token::ModSep) ||
1055 self.token.is_ident() ||
1056 self.token.is_path()
1058 let hi = self.span.hi;
1059 let trait_ref = self.parse_trait_ref();
1060 let poly_trait_ref = ast::PolyTraitRef { bound_lifetimes: lifetime_defs,
1061 trait_ref: trait_ref,
1062 span: mk_sp(lo, hi)};
1063 let other_bounds = if self.eat(&token::BinOp(token::Plus)) {
1064 self.parse_ty_param_bounds(BoundParsingMode::Bare)
1069 Some(TraitTyParamBound(poly_trait_ref, TraitBoundModifier::None)).into_iter()
1070 .chain(other_bounds.into_vec().into_iter())
1072 ast::TyPolyTraitRef(all_bounds)
1074 self.parse_ty_closure(lifetime_defs)
1078 pub fn parse_ty_path(&mut self) -> Ty_ {
1079 let path = self.parse_path(LifetimeAndTypesWithoutColons);
1080 TyPath(path, ast::DUMMY_NODE_ID)
1083 /// parse a TyBareFn type:
1084 pub fn parse_ty_bare_fn(&mut self, lifetime_defs: Vec<ast::LifetimeDef>) -> Ty_ {
1087 [unsafe] [extern "ABI"] fn <'lt> (S) -> T
1088 ^~~~^ ^~~~^ ^~~~^ ^~^ ^
1091 | | | Argument types
1097 let unsafety = self.parse_unsafety();
1098 let abi = if self.eat_keyword(keywords::Extern) {
1099 self.parse_opt_abi().unwrap_or(abi::C)
1104 self.expect_keyword(keywords::Fn);
1105 let lifetime_defs = self.parse_legacy_lifetime_defs(lifetime_defs);
1106 let (inputs, variadic) = self.parse_fn_args(false, true);
1107 let ret_ty = self.parse_ret_ty();
1108 let decl = P(FnDecl {
1113 TyBareFn(P(BareFnTy {
1116 lifetimes: lifetime_defs,
1121 /// Parses a procedure type (`proc`). The initial `proc` keyword must
1122 /// already have been parsed.
1123 pub fn parse_proc_type(&mut self, lifetime_defs: Vec<ast::LifetimeDef>) -> Ty_ {
1126 proc <'lt> (S) [:Bounds] -> T
1127 ^~~^ ^~~~^ ^ ^~~~~~~~^ ^
1133 the `proc` keyword (already consumed)
1137 let proc_span = self.last_span;
1139 // To be helpful, parse the proc as ever
1140 let _ = self.parse_legacy_lifetime_defs(lifetime_defs);
1141 let _ = self.parse_fn_args(false, false);
1142 let _ = self.parse_colon_then_ty_param_bounds(BoundParsingMode::Bare);
1143 let _ = self.parse_ret_ty();
1145 self.obsolete(proc_span, ObsoleteSyntax::ProcType);
1150 /// Parses an obsolete closure kind (`&:`, `&mut:`, or `:`).
1151 pub fn parse_obsolete_closure_kind(&mut self) {
1152 let lo = self.span.lo;
1154 self.check(&token::BinOp(token::And)) &&
1155 self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
1156 self.look_ahead(2, |t| *t == token::Colon)
1162 self.token == token::BinOp(token::And) &&
1163 self.look_ahead(1, |t| *t == token::Colon)
1169 self.eat(&token::Colon)
1176 let span = mk_sp(lo, self.span.hi);
1177 self.obsolete(span, ObsoleteSyntax::ClosureKind);
1180 pub fn parse_ty_bare_fn_or_ty_closure(&mut self, lifetime_defs: Vec<LifetimeDef>) -> Ty_ {
1181 // Both bare fns and closures can begin with stuff like unsafe
1182 // and extern. So we just scan ahead a few tokens to see if we see
1185 // Closure: [unsafe] <'lt> |S| [:Bounds] -> T
1186 // Fn: [unsafe] [extern "ABI"] fn <'lt> (S) -> T
1188 if self.check_keyword(keywords::Fn) {
1189 self.parse_ty_bare_fn(lifetime_defs)
1190 } else if self.check_keyword(keywords::Extern) {
1191 self.parse_ty_bare_fn(lifetime_defs)
1192 } else if self.check_keyword(keywords::Unsafe) {
1193 if self.look_ahead(1, |t| t.is_keyword(keywords::Fn) ||
1194 t.is_keyword(keywords::Extern)) {
1195 self.parse_ty_bare_fn(lifetime_defs)
1197 self.parse_ty_closure(lifetime_defs)
1200 self.parse_ty_closure(lifetime_defs)
1204 /// Parse a TyClosure type
1205 pub fn parse_ty_closure(&mut self, lifetime_defs: Vec<ast::LifetimeDef>) -> Ty_ {
1208 [unsafe] <'lt> |S| [:Bounds] -> T
1209 ^~~~~~~^ ^~~~^ ^ ^~~~~~~~^ ^
1212 | | | Closure bounds
1214 | Deprecated lifetime defs
1220 let ty_closure_span = self.last_span;
1222 // To be helpful, parse the closure type as ever
1223 let _ = self.parse_unsafety();
1225 let _ = self.parse_legacy_lifetime_defs(lifetime_defs);
1227 if !self.eat(&token::OrOr) {
1230 let _ = self.parse_seq_to_before_or(
1232 |p| p.parse_arg_general(false));
1236 let _ = self.parse_colon_then_ty_param_bounds(BoundParsingMode::Bare);
1238 let _ = self.parse_ret_ty();
1240 self.obsolete(ty_closure_span, ObsoleteSyntax::ClosureType);
1245 pub fn parse_unsafety(&mut self) -> Unsafety {
1246 if self.eat_keyword(keywords::Unsafe) {
1247 return Unsafety::Unsafe;
1249 return Unsafety::Normal;
1253 /// Parses `[ 'for' '<' lifetime_defs '>' ]'
1254 fn parse_legacy_lifetime_defs(&mut self,
1255 lifetime_defs: Vec<ast::LifetimeDef>)
1256 -> Vec<ast::LifetimeDef>
1258 if self.token == token::Lt {
1260 if lifetime_defs.is_empty() {
1261 self.warn("deprecated syntax; use the `for` keyword now \
1262 (e.g. change `fn<'a>` to `for<'a> fn`)");
1263 let lifetime_defs = self.parse_lifetime_defs();
1267 self.fatal("cannot use new `for` keyword and older syntax together");
1274 /// Parses `type Foo;` in a trait declaration only. The `type` keyword has
1275 /// already been parsed.
1276 fn parse_associated_type(&mut self, attrs: Vec<Attribute>)
1279 let ty_param = self.parse_ty_param();
1280 self.expect(&token::Semi);
1287 /// Parses `type Foo = TYPE;` in an implementation declaration only. The
1288 /// `type` keyword has already been parsed.
1289 fn parse_typedef(&mut self, attrs: Vec<Attribute>, vis: Visibility)
1291 let lo = self.span.lo;
1292 let ident = self.parse_ident();
1293 self.expect(&token::Eq);
1294 let typ = self.parse_ty_sum();
1295 let hi = self.span.hi;
1296 self.expect(&token::Semi);
1298 id: ast::DUMMY_NODE_ID,
1299 span: mk_sp(lo, hi),
1307 /// Parse the items in a trait declaration
1308 pub fn parse_trait_items(&mut self) -> Vec<TraitItem> {
1309 self.parse_unspanned_seq(
1310 &token::OpenDelim(token::Brace),
1311 &token::CloseDelim(token::Brace),
1314 let attrs = p.parse_outer_attributes();
1316 if p.eat_keyword(keywords::Type) {
1317 TypeTraitItem(P(p.parse_associated_type(attrs)))
1321 let vis = p.parse_visibility();
1322 let style = p.parse_unsafety();
1323 let abi = if p.eat_keyword(keywords::Extern) {
1324 p.parse_opt_abi().unwrap_or(abi::C)
1328 p.expect_keyword(keywords::Fn);
1330 let ident = p.parse_ident();
1331 let mut generics = p.parse_generics();
1333 let (explicit_self, d) = p.parse_fn_decl_with_self(|p| {
1334 // This is somewhat dubious; We don't want to allow
1335 // argument names to be left off if there is a
1337 p.parse_arg_general(false)
1340 p.parse_where_clause(&mut generics);
1342 let hi = p.last_span.hi;
1346 debug!("parse_trait_methods(): parsing required method");
1347 RequiredMethod(TypeMethod {
1354 explicit_self: explicit_self,
1355 id: ast::DUMMY_NODE_ID,
1356 span: mk_sp(lo, hi),
1360 token::OpenDelim(token::Brace) => {
1361 debug!("parse_trait_methods(): parsing provided method");
1362 let (inner_attrs, body) =
1363 p.parse_inner_attrs_and_block();
1364 let mut attrs = attrs;
1365 attrs.push_all(&inner_attrs[..]);
1366 ProvidedMethod(P(ast::Method {
1368 id: ast::DUMMY_NODE_ID,
1369 span: mk_sp(lo, hi),
1370 node: ast::MethDecl(ident,
1382 let token_str = p.this_token_to_string();
1383 p.fatal(&format!("expected `;` or `{{`, found `{}`",
1391 /// Parse a possibly mutable type
1392 pub fn parse_mt(&mut self) -> MutTy {
1393 let mutbl = self.parse_mutability();
1394 let t = self.parse_ty();
1395 MutTy { ty: t, mutbl: mutbl }
1398 /// Parse optional return type [ -> TY ] in function decl
1399 pub fn parse_ret_ty(&mut self) -> FunctionRetTy {
1400 if self.eat(&token::RArrow) {
1401 if self.eat(&token::Not) {
1404 let t = self.parse_ty();
1406 // We used to allow `fn foo() -> &T + U`, but don't
1407 // anymore. If we see it, report a useful error. This
1408 // only makes sense because `parse_ret_ty` is only
1409 // used in fn *declarations*, not fn types or where
1410 // clauses (i.e., not when parsing something like
1411 // `FnMut() -> T + Send`, where the `+` is legal).
1412 if self.token == token::BinOp(token::Plus) {
1413 self.warn("deprecated syntax: `()` are required, see RFC 438 for details");
1419 let pos = self.span.lo;
1420 DefaultReturn(mk_sp(pos, pos))
1424 /// Parse a type in a context where `T1+T2` is allowed.
1425 pub fn parse_ty_sum(&mut self) -> P<Ty> {
1426 let lo = self.span.lo;
1427 let lhs = self.parse_ty();
1429 if !self.eat(&token::BinOp(token::Plus)) {
1433 let bounds = self.parse_ty_param_bounds(BoundParsingMode::Bare);
1435 // In type grammar, `+` is treated like a binary operator,
1436 // and hence both L and R side are required.
1437 if bounds.len() == 0 {
1438 let last_span = self.last_span;
1439 self.span_err(last_span,
1440 "at least one type parameter bound \
1441 must be specified");
1444 let sp = mk_sp(lo, self.last_span.hi);
1445 let sum = ast::TyObjectSum(lhs, bounds);
1446 P(Ty {id: ast::DUMMY_NODE_ID, node: sum, span: sp})
1450 pub fn parse_ty(&mut self) -> P<Ty> {
1451 maybe_whole!(no_clone self, NtTy);
1453 let lo = self.span.lo;
1455 let t = if self.check(&token::OpenDelim(token::Paren)) {
1458 // (t) is a parenthesized ty
1459 // (t,) is the type of a tuple with only one field,
1461 let mut ts = vec![];
1462 let mut last_comma = false;
1463 while self.token != token::CloseDelim(token::Paren) {
1464 ts.push(self.parse_ty_sum());
1465 if self.check(&token::Comma) {
1474 self.expect(&token::CloseDelim(token::Paren));
1475 if ts.len() == 1 && !last_comma {
1476 TyParen(ts.into_iter().nth(0).unwrap())
1480 } else if self.check(&token::BinOp(token::Star)) {
1481 // STAR POINTER (bare pointer?)
1483 TyPtr(self.parse_ptr())
1484 } else if self.check(&token::OpenDelim(token::Bracket)) {
1486 self.expect(&token::OpenDelim(token::Bracket));
1487 let t = self.parse_ty_sum();
1489 // Parse the `; e` in `[ i32; e ]`
1490 // where `e` is a const expression
1491 let t = match self.maybe_parse_fixed_length_of_vec() {
1493 Some(suffix) => TyFixedLengthVec(t, suffix)
1495 self.expect(&token::CloseDelim(token::Bracket));
1497 } else if self.check(&token::BinOp(token::And)) ||
1498 self.token == token::AndAnd {
1501 self.parse_borrowed_pointee()
1502 } else if self.check_keyword(keywords::For) {
1503 self.parse_for_in_type()
1504 } else if self.token_is_bare_fn_keyword() ||
1505 self.token_is_closure_keyword() {
1506 // BARE FUNCTION OR CLOSURE
1507 self.parse_ty_bare_fn_or_ty_closure(Vec::new())
1508 } else if self.check(&token::BinOp(token::Or)) ||
1509 self.token == token::OrOr ||
1510 (self.token == token::Lt &&
1511 self.look_ahead(1, |t| {
1512 *t == token::Gt || t.is_lifetime()
1515 self.parse_ty_closure(Vec::new())
1516 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1518 // In order to not be ambiguous, the type must be surrounded by parens.
1519 self.expect(&token::OpenDelim(token::Paren));
1520 let e = self.parse_expr();
1521 self.expect(&token::CloseDelim(token::Paren));
1523 } else if self.eat_keyword_noexpect(keywords::Proc) {
1524 self.parse_proc_type(Vec::new())
1525 } else if self.eat_lt() {
1526 // QUALIFIED PATH `<TYPE as TRAIT_REF>::item`
1527 let self_type = self.parse_ty_sum();
1528 self.expect_keyword(keywords::As);
1529 let trait_ref = self.parse_trait_ref();
1530 self.expect(&token::Gt);
1531 self.expect(&token::ModSep);
1532 let item_name = self.parse_ident();
1534 self_type: self_type,
1535 trait_ref: P(trait_ref),
1536 item_path: ast::PathSegment {
1537 identifier: item_name,
1538 parameters: ast::PathParameters::none()
1541 } else if self.check(&token::ModSep) ||
1542 self.token.is_ident() ||
1543 self.token.is_path() {
1545 self.parse_ty_path()
1546 } else if self.eat(&token::Underscore) {
1547 // TYPE TO BE INFERRED
1550 let this_token_str = self.this_token_to_string();
1551 let msg = format!("expected type, found `{}`", this_token_str);
1552 self.fatal(&msg[..]);
1555 let sp = mk_sp(lo, self.last_span.hi);
1556 P(Ty {id: ast::DUMMY_NODE_ID, node: t, span: sp})
1559 pub fn parse_borrowed_pointee(&mut self) -> Ty_ {
1560 // look for `&'lt` or `&'foo ` and interpret `foo` as the region name:
1561 let opt_lifetime = self.parse_opt_lifetime();
1563 let mt = self.parse_mt();
1564 return TyRptr(opt_lifetime, mt);
1567 pub fn parse_ptr(&mut self) -> MutTy {
1568 let mutbl = if self.eat_keyword(keywords::Mut) {
1570 } else if self.eat_keyword(keywords::Const) {
1573 let span = self.last_span;
1575 "bare raw pointers are no longer allowed, you should \
1576 likely use `*mut T`, but otherwise `*T` is now \
1577 known as `*const T`");
1580 let t = self.parse_ty();
1581 MutTy { ty: t, mutbl: mutbl }
1584 pub fn is_named_argument(&mut self) -> bool {
1585 let offset = match self.token {
1586 token::BinOp(token::And) => 1,
1588 _ if self.token.is_keyword(keywords::Mut) => 1,
1592 debug!("parser is_named_argument offset:{}", offset);
1595 is_plain_ident_or_underscore(&self.token)
1596 && self.look_ahead(1, |t| *t == token::Colon)
1598 self.look_ahead(offset, |t| is_plain_ident_or_underscore(t))
1599 && self.look_ahead(offset + 1, |t| *t == token::Colon)
1603 /// This version of parse arg doesn't necessarily require
1604 /// identifier names.
1605 pub fn parse_arg_general(&mut self, require_name: bool) -> Arg {
1606 let pat = if require_name || self.is_named_argument() {
1607 debug!("parse_arg_general parse_pat (require_name:{})",
1609 let pat = self.parse_pat();
1611 self.expect(&token::Colon);
1614 debug!("parse_arg_general ident_to_pat");
1615 ast_util::ident_to_pat(ast::DUMMY_NODE_ID,
1617 special_idents::invalid)
1620 let t = self.parse_ty_sum();
1625 id: ast::DUMMY_NODE_ID,
1629 /// Parse a single function argument
1630 pub fn parse_arg(&mut self) -> Arg {
1631 self.parse_arg_general(true)
1634 /// Parse an argument in a lambda header e.g. |arg, arg|
1635 pub fn parse_fn_block_arg(&mut self) -> Arg {
1636 let pat = self.parse_pat();
1637 let t = if self.eat(&token::Colon) {
1641 id: ast::DUMMY_NODE_ID,
1643 span: mk_sp(self.span.lo, self.span.hi),
1649 id: ast::DUMMY_NODE_ID
1653 pub fn maybe_parse_fixed_length_of_vec(&mut self) -> Option<P<ast::Expr>> {
1654 if self.check(&token::Semi) {
1656 Some(self.parse_expr())
1662 /// Matches token_lit = LIT_INTEGER | ...
1663 pub fn lit_from_token(&self, tok: &token::Token) -> Lit_ {
1665 token::Interpolated(token::NtExpr(ref v)) => {
1667 ExprLit(ref lit) => { lit.node.clone() }
1668 _ => { self.unexpected_last(tok); }
1671 token::Literal(lit, suf) => {
1672 let (suffix_illegal, out) = match lit {
1673 token::Byte(i) => (true, LitByte(parse::byte_lit(i.as_str()).0)),
1674 token::Char(i) => (true, LitChar(parse::char_lit(i.as_str()).0)),
1676 // there are some valid suffixes for integer and
1677 // float literals, so all the handling is done
1679 token::Integer(s) => {
1680 (false, parse::integer_lit(s.as_str(),
1681 suf.as_ref().map(|s| s.as_str()),
1682 &self.sess.span_diagnostic,
1685 token::Float(s) => {
1686 (false, parse::float_lit(s.as_str(),
1687 suf.as_ref().map(|s| s.as_str()),
1688 &self.sess.span_diagnostic,
1694 LitStr(token::intern_and_get_ident(&parse::str_lit(s.as_str())),
1697 token::StrRaw(s, n) => {
1700 token::intern_and_get_ident(&parse::raw_str_lit(s.as_str())),
1704 (true, LitBinary(parse::binary_lit(i.as_str()))),
1705 token::BinaryRaw(i, _) =>
1707 LitBinary(Rc::new(i.as_str().as_bytes().iter().cloned().collect()))),
1711 let sp = self.last_span;
1712 self.expect_no_suffix(sp, &*format!("{} literal", lit.short_name()), suf)
1717 _ => { self.unexpected_last(tok); }
1721 /// Matches lit = true | false | token_lit
1722 pub fn parse_lit(&mut self) -> Lit {
1723 let lo = self.span.lo;
1724 let lit = if self.eat_keyword(keywords::True) {
1726 } else if self.eat_keyword(keywords::False) {
1729 let token = self.bump_and_get();
1730 let lit = self.lit_from_token(&token);
1733 codemap::Spanned { node: lit, span: mk_sp(lo, self.last_span.hi) }
1736 /// matches '-' lit | lit
1737 pub fn parse_literal_maybe_minus(&mut self) -> P<Expr> {
1738 let minus_lo = self.span.lo;
1739 let minus_present = self.eat(&token::BinOp(token::Minus));
1741 let lo = self.span.lo;
1742 let literal = P(self.parse_lit());
1743 let hi = self.span.hi;
1744 let expr = self.mk_expr(lo, hi, ExprLit(literal));
1747 let minus_hi = self.span.hi;
1748 let unary = self.mk_unary(UnNeg, expr);
1749 self.mk_expr(minus_lo, minus_hi, unary)
1755 /// Parses a path and optional type parameter bounds, depending on the
1756 /// mode. The `mode` parameter determines whether lifetimes, types, and/or
1757 /// bounds are permitted and whether `::` must precede type parameter
1759 pub fn parse_path(&mut self, mode: PathParsingMode) -> ast::Path {
1760 // Check for a whole path...
1761 let found = match self.token {
1762 token::Interpolated(token::NtPath(_)) => Some(self.bump_and_get()),
1765 if let Some(token::Interpolated(token::NtPath(box path))) = found {
1769 let lo = self.span.lo;
1770 let is_global = self.eat(&token::ModSep);
1772 // Parse any number of segments and bound sets. A segment is an
1773 // identifier followed by an optional lifetime and a set of types.
1774 // A bound set is a set of type parameter bounds.
1775 let segments = match mode {
1776 LifetimeAndTypesWithoutColons => {
1777 self.parse_path_segments_without_colons()
1779 LifetimeAndTypesWithColons => {
1780 self.parse_path_segments_with_colons()
1783 self.parse_path_segments_without_types()
1787 // Assemble the span.
1788 let span = mk_sp(lo, self.last_span.hi);
1790 // Assemble the result.
1799 /// - `a::b<T,U>::c<V,W>`
1800 /// - `a::b<T,U>::c(V) -> W`
1801 /// - `a::b<T,U>::c(V)`
1802 pub fn parse_path_segments_without_colons(&mut self) -> Vec<ast::PathSegment> {
1803 let mut segments = Vec::new();
1805 // First, parse an identifier.
1806 let identifier = self.parse_ident_or_self_type();
1808 // Parse types, optionally.
1809 let parameters = if self.eat_lt() {
1810 let (lifetimes, types, bindings) = self.parse_generic_values_after_lt();
1812 ast::AngleBracketedParameters(ast::AngleBracketedParameterData {
1813 lifetimes: lifetimes,
1814 types: OwnedSlice::from_vec(types),
1815 bindings: OwnedSlice::from_vec(bindings),
1817 } else if self.eat(&token::OpenDelim(token::Paren)) {
1818 let lo = self.last_span.lo;
1820 let inputs = self.parse_seq_to_end(
1821 &token::CloseDelim(token::Paren),
1822 seq_sep_trailing_allowed(token::Comma),
1823 |p| p.parse_ty_sum());
1825 let output_ty = if self.eat(&token::RArrow) {
1826 Some(self.parse_ty())
1831 let hi = self.last_span.hi;
1833 ast::ParenthesizedParameters(ast::ParenthesizedParameterData {
1834 span: mk_sp(lo, hi),
1839 ast::PathParameters::none()
1842 // Assemble and push the result.
1843 segments.push(ast::PathSegment { identifier: identifier,
1844 parameters: parameters });
1846 // Continue only if we see a `::`
1847 if !self.eat(&token::ModSep) {
1854 /// - `a::b::<T,U>::c`
1855 pub fn parse_path_segments_with_colons(&mut self) -> Vec<ast::PathSegment> {
1856 let mut segments = Vec::new();
1858 // First, parse an identifier.
1859 let identifier = self.parse_ident_or_self_type();
1861 // If we do not see a `::`, stop.
1862 if !self.eat(&token::ModSep) {
1863 segments.push(ast::PathSegment {
1864 identifier: identifier,
1865 parameters: ast::PathParameters::none()
1870 // Check for a type segment.
1872 // Consumed `a::b::<`, go look for types
1873 let (lifetimes, types, bindings) = self.parse_generic_values_after_lt();
1874 segments.push(ast::PathSegment {
1875 identifier: identifier,
1876 parameters: ast::AngleBracketedParameters(ast::AngleBracketedParameterData {
1877 lifetimes: lifetimes,
1878 types: OwnedSlice::from_vec(types),
1879 bindings: OwnedSlice::from_vec(bindings),
1883 // Consumed `a::b::<T,U>`, check for `::` before proceeding
1884 if !self.eat(&token::ModSep) {
1888 // Consumed `a::`, go look for `b`
1889 segments.push(ast::PathSegment {
1890 identifier: identifier,
1891 parameters: ast::PathParameters::none(),
1900 pub fn parse_path_segments_without_types(&mut self) -> Vec<ast::PathSegment> {
1901 let mut segments = Vec::new();
1903 // First, parse an identifier.
1904 let identifier = self.parse_ident_or_self_type();
1906 // Assemble and push the result.
1907 segments.push(ast::PathSegment {
1908 identifier: identifier,
1909 parameters: ast::PathParameters::none()
1912 // If we do not see a `::`, stop.
1913 if !self.eat(&token::ModSep) {
1919 /// parses 0 or 1 lifetime
1920 pub fn parse_opt_lifetime(&mut self) -> Option<ast::Lifetime> {
1922 token::Lifetime(..) => {
1923 Some(self.parse_lifetime())
1931 /// Parses a single lifetime
1932 /// Matches lifetime = LIFETIME
1933 pub fn parse_lifetime(&mut self) -> ast::Lifetime {
1935 token::Lifetime(i) => {
1936 let span = self.span;
1938 return ast::Lifetime {
1939 id: ast::DUMMY_NODE_ID,
1945 self.fatal(&format!("expected a lifetime name"));
1950 /// Parses `lifetime_defs = [ lifetime_defs { ',' lifetime_defs } ]` where `lifetime_def =
1951 /// lifetime [':' lifetimes]`
1952 pub fn parse_lifetime_defs(&mut self) -> Vec<ast::LifetimeDef> {
1954 let mut res = Vec::new();
1957 token::Lifetime(_) => {
1958 let lifetime = self.parse_lifetime();
1960 if self.eat(&token::Colon) {
1961 self.parse_lifetimes(token::BinOp(token::Plus))
1965 res.push(ast::LifetimeDef { lifetime: lifetime,
1975 token::Comma => { self.bump(); }
1976 token::Gt => { return res; }
1977 token::BinOp(token::Shr) => { return res; }
1979 let this_token_str = self.this_token_to_string();
1980 let msg = format!("expected `,` or `>` after lifetime \
1983 self.fatal(&msg[..]);
1989 /// matches lifetimes = ( lifetime ) | ( lifetime , lifetimes ) actually, it matches the empty
1990 /// one too, but putting that in there messes up the grammar....
1992 /// Parses zero or more comma separated lifetimes. Expects each lifetime to be followed by
1993 /// either a comma or `>`. Used when parsing type parameter lists, where we expect something
1994 /// like `<'a, 'b, T>`.
1995 pub fn parse_lifetimes(&mut self, sep: token::Token) -> Vec<ast::Lifetime> {
1997 let mut res = Vec::new();
2000 token::Lifetime(_) => {
2001 res.push(self.parse_lifetime());
2008 if self.token != sep {
2016 /// Parse mutability declaration (mut/const/imm)
2017 pub fn parse_mutability(&mut self) -> Mutability {
2018 if self.eat_keyword(keywords::Mut) {
2025 /// Parse ident COLON expr
2026 pub fn parse_field(&mut self) -> Field {
2027 let lo = self.span.lo;
2028 let i = self.parse_ident();
2029 let hi = self.last_span.hi;
2030 self.expect(&token::Colon);
2031 let e = self.parse_expr();
2033 ident: spanned(lo, hi, i),
2034 span: mk_sp(lo, e.span.hi),
2039 pub fn mk_expr(&mut self, lo: BytePos, hi: BytePos, node: Expr_) -> P<Expr> {
2041 id: ast::DUMMY_NODE_ID,
2043 span: mk_sp(lo, hi),
2047 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::Expr_ {
2048 ExprUnary(unop, expr)
2051 pub fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::Expr_ {
2052 ExprBinary(binop, lhs, rhs)
2055 pub fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::Expr_ {
2059 fn mk_method_call(&mut self,
2060 ident: ast::SpannedIdent,
2064 ExprMethodCall(ident, tps, args)
2067 pub fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::Expr_ {
2068 ExprIndex(expr, idx)
2071 pub fn mk_range(&mut self,
2072 start: Option<P<Expr>>,
2073 end: Option<P<Expr>>)
2075 ExprRange(start, end)
2078 pub fn mk_field(&mut self, expr: P<Expr>, ident: ast::SpannedIdent) -> ast::Expr_ {
2079 ExprField(expr, ident)
2082 pub fn mk_tup_field(&mut self, expr: P<Expr>, idx: codemap::Spanned<usize>) -> ast::Expr_ {
2083 ExprTupField(expr, idx)
2086 pub fn mk_assign_op(&mut self, binop: ast::BinOp,
2087 lhs: P<Expr>, rhs: P<Expr>) -> ast::Expr_ {
2088 ExprAssignOp(binop, lhs, rhs)
2091 pub fn mk_mac_expr(&mut self, lo: BytePos, hi: BytePos, m: Mac_) -> P<Expr> {
2093 id: ast::DUMMY_NODE_ID,
2094 node: ExprMac(codemap::Spanned {node: m, span: mk_sp(lo, hi)}),
2095 span: mk_sp(lo, hi),
2099 pub fn mk_lit_u32(&mut self, i: u32) -> P<Expr> {
2100 let span = &self.span;
2101 let lv_lit = P(codemap::Spanned {
2102 node: LitInt(i as u64, ast::UnsignedIntLit(TyU32)),
2107 id: ast::DUMMY_NODE_ID,
2108 node: ExprLit(lv_lit),
2113 fn expect_open_delim(&mut self) -> token::DelimToken {
2114 self.expected_tokens.push(TokenType::Token(token::Gt));
2116 token::OpenDelim(delim) => {
2120 _ => self.fatal("expected open delimiter"),
2124 /// At the bottom (top?) of the precedence hierarchy,
2125 /// parse things like parenthesized exprs,
2126 /// macros, return, etc.
2127 pub fn parse_bottom_expr(&mut self) -> P<Expr> {
2128 maybe_whole_expr!(self);
2130 let lo = self.span.lo;
2131 let mut hi = self.span.hi;
2135 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2137 token::OpenDelim(token::Paren) => {
2140 // (e) is parenthesized e
2141 // (e,) is a tuple with only one field, e
2142 let mut es = vec![];
2143 let mut trailing_comma = false;
2144 while self.token != token::CloseDelim(token::Paren) {
2145 es.push(self.parse_expr());
2146 self.commit_expr(&**es.last().unwrap(), &[],
2147 &[token::Comma, token::CloseDelim(token::Paren)]);
2148 if self.check(&token::Comma) {
2149 trailing_comma = true;
2153 trailing_comma = false;
2160 return if es.len() == 1 && !trailing_comma {
2161 self.mk_expr(lo, hi, ExprParen(es.into_iter().nth(0).unwrap()))
2163 self.mk_expr(lo, hi, ExprTup(es))
2166 token::OpenDelim(token::Brace) => {
2168 let blk = self.parse_block_tail(lo, DefaultBlock);
2169 return self.mk_expr(blk.span.lo, blk.span.hi,
2172 token::BinOp(token::Or) | token::OrOr => {
2173 return self.parse_lambda_expr(CaptureByRef);
2175 token::Ident(id @ ast::Ident {
2176 name: token::SELF_KEYWORD_NAME,
2178 }, token::Plain) => {
2180 let path = ast_util::ident_to_path(mk_sp(lo, hi), id);
2181 ex = ExprPath(path);
2182 hi = self.last_span.hi;
2184 token::OpenDelim(token::Bracket) => {
2187 if self.check(&token::CloseDelim(token::Bracket)) {
2190 ex = ExprVec(Vec::new());
2193 let first_expr = self.parse_expr();
2194 if self.check(&token::Semi) {
2195 // Repeating vector syntax: [ 0; 512 ]
2197 let count = self.parse_expr();
2198 self.expect(&token::CloseDelim(token::Bracket));
2199 ex = ExprRepeat(first_expr, count);
2200 } else if self.check(&token::Comma) {
2201 // Vector with two or more elements.
2203 let remaining_exprs = self.parse_seq_to_end(
2204 &token::CloseDelim(token::Bracket),
2205 seq_sep_trailing_allowed(token::Comma),
2208 let mut exprs = vec!(first_expr);
2209 exprs.extend(remaining_exprs.into_iter());
2210 ex = ExprVec(exprs);
2212 // Vector with one element.
2213 self.expect(&token::CloseDelim(token::Bracket));
2214 ex = ExprVec(vec!(first_expr));
2217 hi = self.last_span.hi;
2221 // QUALIFIED PATH `<TYPE as TRAIT_REF>::item::<'a, T>`
2222 let self_type = self.parse_ty_sum();
2223 self.expect_keyword(keywords::As);
2224 let trait_ref = self.parse_trait_ref();
2225 self.expect(&token::Gt);
2226 self.expect(&token::ModSep);
2227 let item_name = self.parse_ident();
2228 let parameters = if self.eat(&token::ModSep) {
2230 // Consumed `item::<`, go look for types
2231 let (lifetimes, types, bindings) =
2232 self.parse_generic_values_after_lt();
2233 ast::AngleBracketedParameters(ast::AngleBracketedParameterData {
2234 lifetimes: lifetimes,
2235 types: OwnedSlice::from_vec(types),
2236 bindings: OwnedSlice::from_vec(bindings),
2239 ast::PathParameters::none()
2241 let hi = self.span.hi;
2242 return self.mk_expr(lo, hi, ExprQPath(P(QPath {
2243 self_type: self_type,
2244 trait_ref: P(trait_ref),
2245 item_path: ast::PathSegment {
2246 identifier: item_name,
2247 parameters: parameters
2251 if self.eat_keyword(keywords::Move) {
2252 return self.parse_lambda_expr(CaptureByValue);
2254 if self.eat_keyword_noexpect(keywords::Proc) {
2255 let span = self.last_span;
2256 let _ = self.parse_proc_decl();
2257 let _ = self.parse_expr();
2258 return self.obsolete_expr(span, ObsoleteSyntax::ProcExpr);
2260 if self.eat_keyword(keywords::If) {
2261 return self.parse_if_expr();
2263 if self.eat_keyword(keywords::For) {
2264 return self.parse_for_expr(None);
2266 if self.eat_keyword(keywords::While) {
2267 return self.parse_while_expr(None);
2269 if self.token.is_lifetime() {
2270 let lifetime = self.get_lifetime();
2272 self.expect(&token::Colon);
2273 if self.eat_keyword(keywords::While) {
2274 return self.parse_while_expr(Some(lifetime))
2276 if self.eat_keyword(keywords::For) {
2277 return self.parse_for_expr(Some(lifetime))
2279 if self.eat_keyword(keywords::Loop) {
2280 return self.parse_loop_expr(Some(lifetime))
2282 self.fatal("expected `while`, `for`, or `loop` after a label")
2284 if self.eat_keyword(keywords::Loop) {
2285 return self.parse_loop_expr(None);
2287 if self.eat_keyword(keywords::Continue) {
2288 let lo = self.span.lo;
2289 let ex = if self.token.is_lifetime() {
2290 let lifetime = self.get_lifetime();
2292 ExprAgain(Some(lifetime))
2296 let hi = self.span.hi;
2297 return self.mk_expr(lo, hi, ex);
2299 if self.eat_keyword(keywords::Match) {
2300 return self.parse_match_expr();
2302 if self.eat_keyword(keywords::Unsafe) {
2303 return self.parse_block_expr(
2305 UnsafeBlock(ast::UserProvided));
2307 if self.eat_keyword(keywords::Return) {
2308 // RETURN expression
2309 if self.token.can_begin_expr() {
2310 let e = self.parse_expr();
2312 ex = ExprRet(Some(e));
2316 } else if self.eat_keyword(keywords::Break) {
2318 if self.token.is_lifetime() {
2319 let lifetime = self.get_lifetime();
2321 ex = ExprBreak(Some(lifetime));
2323 ex = ExprBreak(None);
2326 } else if self.check(&token::ModSep) ||
2327 self.token.is_ident() &&
2328 !self.check_keyword(keywords::True) &&
2329 !self.check_keyword(keywords::False) {
2331 self.parse_path(LifetimeAndTypesWithColons);
2333 // `!`, as an operator, is prefix, so we know this isn't that
2334 if self.check(&token::Not) {
2335 // MACRO INVOCATION expression
2338 let delim = self.expect_open_delim();
2339 let tts = self.parse_seq_to_end(
2340 &token::CloseDelim(delim),
2342 |p| p.parse_token_tree());
2343 let hi = self.span.hi;
2345 return self.mk_mac_expr(lo,
2351 if self.check(&token::OpenDelim(token::Brace)) {
2352 // This is a struct literal, unless we're prohibited
2353 // from parsing struct literals here.
2354 if !self.restrictions.contains(RESTRICTION_NO_STRUCT_LITERAL) {
2355 // It's a struct literal.
2357 let mut fields = Vec::new();
2358 let mut base = None;
2360 while self.token != token::CloseDelim(token::Brace) {
2361 if self.eat(&token::DotDot) {
2362 base = Some(self.parse_expr());
2366 fields.push(self.parse_field());
2367 self.commit_expr(&*fields.last().unwrap().expr,
2369 &[token::CloseDelim(token::Brace)]);
2372 if fields.len() == 0 && base.is_none() {
2373 let last_span = self.last_span;
2374 self.span_err(last_span,
2375 "structure literal must either \
2376 have at least one field or use \
2377 functional structure update \
2382 self.expect(&token::CloseDelim(token::Brace));
2383 ex = ExprStruct(pth, fields, base);
2384 return self.mk_expr(lo, hi, ex);
2391 // other literal expression
2392 let lit = self.parse_lit();
2394 ex = ExprLit(P(lit));
2399 return self.mk_expr(lo, hi, ex);
2402 /// Parse a block or unsafe block
2403 pub fn parse_block_expr(&mut self, lo: BytePos, blk_mode: BlockCheckMode)
2405 self.expect(&token::OpenDelim(token::Brace));
2406 let blk = self.parse_block_tail(lo, blk_mode);
2407 return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk));
2410 /// parse a.b or a(13) or a[4] or just a
2411 pub fn parse_dot_or_call_expr(&mut self) -> P<Expr> {
2412 let b = self.parse_bottom_expr();
2413 self.parse_dot_or_call_expr_with(b)
2416 pub fn parse_dot_or_call_expr_with(&mut self, e0: P<Expr>) -> P<Expr> {
2422 if self.eat(&token::Dot) {
2424 token::Ident(i, _) => {
2425 let dot = self.last_span.hi;
2428 let (_, tys, bindings) = if self.eat(&token::ModSep) {
2430 self.parse_generic_values_after_lt()
2432 (Vec::new(), Vec::new(), Vec::new())
2435 if bindings.len() > 0 {
2436 let last_span = self.last_span;
2437 self.span_err(last_span, "type bindings are only permitted on trait paths");
2440 // expr.f() method call
2442 token::OpenDelim(token::Paren) => {
2443 let mut es = self.parse_unspanned_seq(
2444 &token::OpenDelim(token::Paren),
2445 &token::CloseDelim(token::Paren),
2446 seq_sep_trailing_allowed(token::Comma),
2449 hi = self.last_span.hi;
2452 let id = spanned(dot, hi, i);
2453 let nd = self.mk_method_call(id, tys, es);
2454 e = self.mk_expr(lo, hi, nd);
2457 if !tys.is_empty() {
2458 let last_span = self.last_span;
2459 self.span_err(last_span,
2460 "field expressions may not \
2461 have type parameters");
2464 let id = spanned(dot, hi, i);
2465 let field = self.mk_field(e, id);
2466 e = self.mk_expr(lo, hi, field);
2470 token::Literal(token::Integer(n), suf) => {
2473 // A tuple index may not have a suffix
2474 self.expect_no_suffix(sp, "tuple index", suf);
2476 let dot = self.last_span.hi;
2480 let index = n.as_str().parse::<usize>().ok();
2483 let id = spanned(dot, hi, n);
2484 let field = self.mk_tup_field(e, id);
2485 e = self.mk_expr(lo, hi, field);
2488 let last_span = self.last_span;
2489 self.span_err(last_span, "invalid tuple or tuple struct index");
2493 token::Literal(token::Float(n), _suf) => {
2495 let last_span = self.last_span;
2496 let fstr = n.as_str();
2497 self.span_err(last_span,
2498 &format!("unexpected token: `{}`", n.as_str()));
2499 if fstr.chars().all(|x| "0123456789.".contains_char(x)) {
2500 let float = match fstr.parse::<f64>().ok() {
2504 self.span_help(last_span,
2505 &format!("try parenthesizing the first index; e.g., `(foo.{}){}`",
2506 float.trunc() as usize,
2507 &float.fract().to_string()[1..]));
2509 self.abort_if_errors();
2512 _ => self.unexpected()
2516 if self.expr_is_complete(&*e) { break; }
2519 token::OpenDelim(token::Paren) => {
2520 let es = self.parse_unspanned_seq(
2521 &token::OpenDelim(token::Paren),
2522 &token::CloseDelim(token::Paren),
2523 seq_sep_trailing_allowed(token::Comma),
2526 hi = self.last_span.hi;
2528 let nd = self.mk_call(e, es);
2529 e = self.mk_expr(lo, hi, nd);
2533 // Could be either an index expression or a slicing expression.
2534 token::OpenDelim(token::Bracket) => {
2535 let bracket_pos = self.span.lo;
2538 if self.eat(&token::CloseDelim(token::Bracket)) {
2539 // No expression, expand to a RangeFull
2540 // FIXME(#20516) It would be better to use a lang item or
2541 // something for RangeFull.
2542 hi = self.last_span.hi;
2544 let idents = vec![token::str_to_ident("std"),
2545 token::str_to_ident("ops"),
2546 token::str_to_ident("RangeFull")];
2547 let segments = idents.into_iter().map(|ident| {
2550 parameters: ast::PathParameters::none(),
2553 let span = mk_sp(lo, hi);
2554 let path = ast::Path {
2560 let range = ExprStruct(path, vec![], None);
2561 let ix = self.mk_expr(bracket_pos, hi, range);
2562 let index = self.mk_index(e, ix);
2563 e = self.mk_expr(lo, hi, index);
2565 self.obsolete(span, ObsoleteSyntax::EmptyIndex);
2567 let ix = self.parse_expr();
2569 self.commit_expr_expecting(&*ix, token::CloseDelim(token::Bracket));
2570 let index = self.mk_index(e, ix);
2571 e = self.mk_expr(lo, hi, index)
2581 // Parse unquoted tokens after a `$` in a token tree
2582 fn parse_unquoted(&mut self) -> TokenTree {
2583 let mut sp = self.span;
2584 let (name, namep) = match self.token {
2588 if self.token == token::OpenDelim(token::Paren) {
2589 let Spanned { node: seq, span: seq_span } = self.parse_seq(
2590 &token::OpenDelim(token::Paren),
2591 &token::CloseDelim(token::Paren),
2593 |p| p.parse_token_tree()
2595 let (sep, repeat) = self.parse_sep_and_kleene_op();
2596 let name_num = macro_parser::count_names(&seq);
2597 return TtSequence(mk_sp(sp.lo, seq_span.hi),
2598 Rc::new(SequenceRepetition {
2602 num_captures: name_num
2604 } else if self.token.is_keyword_allow_following_colon(keywords::Crate) {
2606 return TtToken(sp, SpecialVarNt(SpecialMacroVar::CrateMacroVar));
2608 sp = mk_sp(sp.lo, self.span.hi);
2609 let namep = match self.token { token::Ident(_, p) => p, _ => token::Plain };
2610 let name = self.parse_ident();
2614 token::SubstNt(name, namep) => {
2620 // continue by trying to parse the `:ident` after `$name`
2621 if self.token == token::Colon && self.look_ahead(1, |t| t.is_ident() &&
2622 !t.is_strict_keyword() &&
2623 !t.is_reserved_keyword()) {
2625 sp = mk_sp(sp.lo, self.span.hi);
2626 let kindp = match self.token { token::Ident(_, p) => p, _ => token::Plain };
2627 let nt_kind = self.parse_ident();
2628 TtToken(sp, MatchNt(name, nt_kind, namep, kindp))
2630 TtToken(sp, SubstNt(name, namep))
2634 pub fn check_unknown_macro_variable(&mut self) {
2635 if self.quote_depth == 0 {
2637 token::SubstNt(name, _) =>
2638 self.fatal(&format!("unknown macro variable `{}`",
2639 token::get_ident(name))),
2645 /// Parse an optional separator followed by a Kleene-style
2646 /// repetition token (+ or *).
2647 pub fn parse_sep_and_kleene_op(&mut self) -> (Option<token::Token>, ast::KleeneOp) {
2648 fn parse_kleene_op(parser: &mut Parser) -> Option<ast::KleeneOp> {
2649 match parser.token {
2650 token::BinOp(token::Star) => {
2652 Some(ast::ZeroOrMore)
2654 token::BinOp(token::Plus) => {
2656 Some(ast::OneOrMore)
2662 match parse_kleene_op(self) {
2663 Some(kleene_op) => return (None, kleene_op),
2667 let separator = self.bump_and_get();
2668 match parse_kleene_op(self) {
2669 Some(zerok) => (Some(separator), zerok),
2670 None => self.fatal("expected `*` or `+`")
2674 /// parse a single token tree from the input.
2675 pub fn parse_token_tree(&mut self) -> TokenTree {
2676 // FIXME #6994: currently, this is too eager. It
2677 // parses token trees but also identifies TtSequence's
2678 // and token::SubstNt's; it's too early to know yet
2679 // whether something will be a nonterminal or a seq
2681 maybe_whole!(deref self, NtTT);
2683 // this is the fall-through for the 'match' below.
2684 // invariants: the current token is not a left-delimiter,
2685 // not an EOF, and not the desired right-delimiter (if
2686 // it were, parse_seq_to_before_end would have prevented
2687 // reaching this point.
2688 fn parse_non_delim_tt_tok(p: &mut Parser) -> TokenTree {
2689 maybe_whole!(deref p, NtTT);
2691 token::CloseDelim(_) => {
2692 // This is a conservative error: only report the last unclosed delimiter. The
2693 // previous unclosed delimiters could actually be closed! The parser just hasn't
2694 // gotten to them yet.
2695 match p.open_braces.last() {
2697 Some(&sp) => p.span_note(sp, "unclosed delimiter"),
2699 let token_str = p.this_token_to_string();
2700 p.fatal(&format!("incorrect close delimiter: `{}`",
2703 /* we ought to allow different depths of unquotation */
2704 token::Dollar | token::SubstNt(..) if p.quote_depth > 0 => {
2708 TtToken(p.span, p.bump_and_get())
2715 let open_braces = self.open_braces.clone();
2716 for sp in &open_braces {
2717 self.span_help(*sp, "did you mean to close this delimiter?");
2719 // There shouldn't really be a span, but it's easier for the test runner
2720 // if we give it one
2721 self.fatal("this file contains an un-closed delimiter ");
2723 token::OpenDelim(delim) => {
2724 // The span for beginning of the delimited section
2725 let pre_span = self.span;
2727 // Parse the open delimiter.
2728 self.open_braces.push(self.span);
2729 let open_span = self.span;
2732 // Parse the token trees within the delimiters
2733 let tts = self.parse_seq_to_before_end(
2734 &token::CloseDelim(delim),
2736 |p| p.parse_token_tree()
2739 // Parse the close delimiter.
2740 let close_span = self.span;
2742 self.open_braces.pop().unwrap();
2744 // Expand to cover the entire delimited token tree
2745 let span = Span { hi: close_span.hi, ..pre_span };
2747 TtDelimited(span, Rc::new(Delimited {
2749 open_span: open_span,
2751 close_span: close_span,
2754 _ => parse_non_delim_tt_tok(self),
2758 // parse a stream of tokens into a list of TokenTree's,
2760 pub fn parse_all_token_trees(&mut self) -> Vec<TokenTree> {
2761 let mut tts = Vec::new();
2762 while self.token != token::Eof {
2763 tts.push(self.parse_token_tree());
2768 /// Parse a prefix-operator expr
2769 pub fn parse_prefix_expr(&mut self) -> P<Expr> {
2770 let lo = self.span.lo;
2773 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2778 let e = self.parse_prefix_expr();
2780 ex = self.mk_unary(UnNot, e);
2782 token::BinOp(token::Minus) => {
2784 let e = self.parse_prefix_expr();
2786 ex = self.mk_unary(UnNeg, e);
2788 token::BinOp(token::Star) => {
2790 let e = self.parse_prefix_expr();
2792 ex = self.mk_unary(UnDeref, e);
2794 token::BinOp(token::And) | token::AndAnd => {
2796 let m = self.parse_mutability();
2797 let e = self.parse_prefix_expr();
2799 ex = ExprAddrOf(m, e);
2801 token::Ident(_, _) => {
2802 if !self.check_keyword(keywords::Box) {
2803 return self.parse_dot_or_call_expr();
2806 let lo = self.span.lo;
2810 // Check for a place: `box(PLACE) EXPR`.
2811 if self.eat(&token::OpenDelim(token::Paren)) {
2812 // Support `box() EXPR` as the default.
2813 if !self.eat(&token::CloseDelim(token::Paren)) {
2814 let place = self.parse_expr();
2815 self.expect(&token::CloseDelim(token::Paren));
2816 // Give a suggestion to use `box()` when a parenthesised expression is used
2817 if !self.token.can_begin_expr() {
2818 let span = self.span;
2819 let this_token_to_string = self.this_token_to_string();
2821 &format!("expected expression, found `{}`",
2822 this_token_to_string));
2823 let box_span = mk_sp(lo, self.last_span.hi);
2824 self.span_help(box_span,
2825 "perhaps you meant `box() (foo)` instead?");
2826 self.abort_if_errors();
2828 let subexpression = self.parse_prefix_expr();
2829 hi = subexpression.span.hi;
2830 ex = ExprBox(Some(place), subexpression);
2831 return self.mk_expr(lo, hi, ex);
2835 // Otherwise, we use the unique pointer default.
2836 let subexpression = self.parse_prefix_expr();
2837 hi = subexpression.span.hi;
2838 // FIXME (pnkfelix): After working out kinks with box
2839 // desugaring, should be `ExprBox(None, subexpression)`
2841 ex = self.mk_unary(UnUniq, subexpression);
2843 _ => return self.parse_dot_or_call_expr()
2845 return self.mk_expr(lo, hi, ex);
2848 /// Parse an expression of binops
2849 pub fn parse_binops(&mut self) -> P<Expr> {
2850 let prefix_expr = self.parse_prefix_expr();
2851 self.parse_more_binops(prefix_expr, 0)
2854 /// Parse an expression of binops of at least min_prec precedence
2855 pub fn parse_more_binops(&mut self, lhs: P<Expr>, min_prec: usize) -> P<Expr> {
2856 if self.expr_is_complete(&*lhs) { return lhs; }
2858 // Prevent dynamic borrow errors later on by limiting the
2859 // scope of the borrows.
2860 if self.token == token::BinOp(token::Or) &&
2861 self.restrictions.contains(RESTRICTION_NO_BAR_OP) {
2865 self.expected_tokens.push(TokenType::Operator);
2867 let cur_op_span = self.span;
2868 let cur_opt = self.token.to_binop();
2871 if ast_util::is_comparison_binop(cur_op) {
2872 self.check_no_chained_comparison(&*lhs, cur_op)
2874 let cur_prec = operator_prec(cur_op);
2875 if cur_prec >= min_prec {
2877 let expr = self.parse_prefix_expr();
2878 let rhs = self.parse_more_binops(expr, cur_prec + 1);
2879 let lhs_span = lhs.span;
2880 let rhs_span = rhs.span;
2881 let binary = self.mk_binary(codemap::respan(cur_op_span, cur_op), lhs, rhs);
2882 let bin = self.mk_expr(lhs_span.lo, rhs_span.hi, binary);
2883 self.parse_more_binops(bin, min_prec)
2889 if AS_PREC >= min_prec && self.eat_keyword_noexpect(keywords::As) {
2890 let rhs = self.parse_ty();
2891 let _as = self.mk_expr(lhs.span.lo,
2893 ExprCast(lhs, rhs));
2894 self.parse_more_binops(_as, min_prec)
2902 /// Produce an error if comparison operators are chained (RFC #558).
2903 /// We only need to check lhs, not rhs, because all comparison ops
2904 /// have same precedence and are left-associative
2905 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: ast::BinOp_) {
2906 debug_assert!(ast_util::is_comparison_binop(outer_op));
2908 ExprBinary(op, _, _) if ast_util::is_comparison_binop(op.node) => {
2909 // respan to include both operators
2910 let op_span = mk_sp(op.span.lo, self.span.hi);
2911 self.span_err(op_span,
2912 "chained comparison operators require parentheses");
2913 if op.node == BiLt && outer_op == BiGt {
2914 self.span_help(op_span,
2915 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
2922 /// Parse an assignment expression....
2923 /// actually, this seems to be the main entry point for
2924 /// parsing an arbitrary expression.
2925 pub fn parse_assign_expr(&mut self) -> P<Expr> {
2928 // prefix-form of range notation '..expr'
2929 // This has the same precedence as assignment expressions
2930 // (much lower than other prefix expressions) to be consistent
2931 // with the postfix-form 'expr..'
2932 let lo = self.span.lo;
2934 let opt_end = if self.is_at_start_of_range_notation_rhs() {
2935 let end = self.parse_binops();
2940 let hi = self.span.hi;
2941 let ex = self.mk_range(None, opt_end);
2942 self.mk_expr(lo, hi, ex)
2945 let lhs = self.parse_binops();
2946 self.parse_assign_expr_with(lhs)
2951 pub fn parse_assign_expr_with(&mut self, lhs: P<Expr>) -> P<Expr> {
2952 let restrictions = self.restrictions & RESTRICTION_NO_STRUCT_LITERAL;
2953 let op_span = self.span;
2957 let rhs = self.parse_expr_res(restrictions);
2958 self.mk_expr(lhs.span.lo, rhs.span.hi, ExprAssign(lhs, rhs))
2960 token::BinOpEq(op) => {
2962 let rhs = self.parse_expr_res(restrictions);
2963 let aop = match op {
2964 token::Plus => BiAdd,
2965 token::Minus => BiSub,
2966 token::Star => BiMul,
2967 token::Slash => BiDiv,
2968 token::Percent => BiRem,
2969 token::Caret => BiBitXor,
2970 token::And => BiBitAnd,
2971 token::Or => BiBitOr,
2972 token::Shl => BiShl,
2975 let rhs_span = rhs.span;
2976 let span = lhs.span;
2977 let assign_op = self.mk_assign_op(codemap::respan(op_span, aop), lhs, rhs);
2978 self.mk_expr(span.lo, rhs_span.hi, assign_op)
2980 // A range expression, either `expr..expr` or `expr..`.
2984 let opt_end = if self.is_at_start_of_range_notation_rhs() {
2985 let end = self.parse_binops();
2991 let lo = lhs.span.lo;
2992 let hi = self.span.hi;
2993 let range = self.mk_range(Some(lhs), opt_end);
2994 return self.mk_expr(lo, hi, range);
3003 fn is_at_start_of_range_notation_rhs(&self) -> bool {
3004 if self.token.can_begin_expr() {
3005 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
3006 if self.token == token::OpenDelim(token::Brace) {
3007 return !self.restrictions.contains(RESTRICTION_NO_STRUCT_LITERAL);
3015 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
3016 pub fn parse_if_expr(&mut self) -> P<Expr> {
3017 if self.check_keyword(keywords::Let) {
3018 return self.parse_if_let_expr();
3020 let lo = self.last_span.lo;
3021 let cond = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
3022 let thn = self.parse_block();
3023 let mut els: Option<P<Expr>> = None;
3024 let mut hi = thn.span.hi;
3025 if self.eat_keyword(keywords::Else) {
3026 let elexpr = self.parse_else_expr();
3027 hi = elexpr.span.hi;
3030 self.mk_expr(lo, hi, ExprIf(cond, thn, els))
3033 /// Parse an 'if let' expression ('if' token already eaten)
3034 pub fn parse_if_let_expr(&mut self) -> P<Expr> {
3035 let lo = self.last_span.lo;
3036 self.expect_keyword(keywords::Let);
3037 let pat = self.parse_pat();
3038 self.expect(&token::Eq);
3039 let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
3040 let thn = self.parse_block();
3041 let (hi, els) = if self.eat_keyword(keywords::Else) {
3042 let expr = self.parse_else_expr();
3043 (expr.span.hi, Some(expr))
3047 self.mk_expr(lo, hi, ExprIfLet(pat, expr, thn, els))
3051 pub fn parse_lambda_expr(&mut self, capture_clause: CaptureClause)
3054 let lo = self.span.lo;
3055 let decl = self.parse_fn_block_decl();
3056 let body = self.parse_expr();
3057 let fakeblock = P(ast::Block {
3058 id: ast::DUMMY_NODE_ID,
3062 rules: DefaultBlock,
3068 ExprClosure(capture_clause, decl, fakeblock))
3071 pub fn parse_else_expr(&mut self) -> P<Expr> {
3072 if self.eat_keyword(keywords::If) {
3073 return self.parse_if_expr();
3075 let blk = self.parse_block();
3076 return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk));
3080 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3081 pub fn parse_for_expr(&mut self, opt_ident: Option<ast::Ident>) -> P<Expr> {
3082 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3084 let lo = self.last_span.lo;
3085 let pat = self.parse_pat();
3086 self.expect_keyword(keywords::In);
3087 let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
3088 let loop_block = self.parse_block();
3089 let hi = self.span.hi;
3091 self.mk_expr(lo, hi, ExprForLoop(pat, expr, loop_block, opt_ident))
3094 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3095 pub fn parse_while_expr(&mut self, opt_ident: Option<ast::Ident>) -> P<Expr> {
3096 if self.token.is_keyword(keywords::Let) {
3097 return self.parse_while_let_expr(opt_ident);
3099 let lo = self.last_span.lo;
3100 let cond = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
3101 let body = self.parse_block();
3102 let hi = body.span.hi;
3103 return self.mk_expr(lo, hi, ExprWhile(cond, body, opt_ident));
3106 /// Parse a 'while let' expression ('while' token already eaten)
3107 pub fn parse_while_let_expr(&mut self, opt_ident: Option<ast::Ident>) -> P<Expr> {
3108 let lo = self.last_span.lo;
3109 self.expect_keyword(keywords::Let);
3110 let pat = self.parse_pat();
3111 self.expect(&token::Eq);
3112 let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
3113 let body = self.parse_block();
3114 let hi = body.span.hi;
3115 return self.mk_expr(lo, hi, ExprWhileLet(pat, expr, body, opt_ident));
3118 pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::Ident>) -> P<Expr> {
3119 let lo = self.last_span.lo;
3120 let body = self.parse_block();
3121 let hi = body.span.hi;
3122 self.mk_expr(lo, hi, ExprLoop(body, opt_ident))
3125 fn parse_match_expr(&mut self) -> P<Expr> {
3126 let lo = self.last_span.lo;
3127 let discriminant = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
3128 self.commit_expr_expecting(&*discriminant, token::OpenDelim(token::Brace));
3129 let mut arms: Vec<Arm> = Vec::new();
3130 while self.token != token::CloseDelim(token::Brace) {
3131 arms.push(self.parse_arm());
3133 let hi = self.span.hi;
3135 return self.mk_expr(lo, hi, ExprMatch(discriminant, arms, MatchSource::Normal));
3138 pub fn parse_arm(&mut self) -> Arm {
3139 let attrs = self.parse_outer_attributes();
3140 let pats = self.parse_pats();
3141 let mut guard = None;
3142 if self.eat_keyword(keywords::If) {
3143 guard = Some(self.parse_expr());
3145 self.expect(&token::FatArrow);
3146 let expr = self.parse_expr_res(RESTRICTION_STMT_EXPR);
3149 !classify::expr_is_simple_block(&*expr)
3150 && self.token != token::CloseDelim(token::Brace);
3153 self.commit_expr(&*expr, &[token::Comma], &[token::CloseDelim(token::Brace)]);
3155 self.eat(&token::Comma);
3166 /// Parse an expression
3167 pub fn parse_expr(&mut self) -> P<Expr> {
3168 return self.parse_expr_res(UNRESTRICTED);
3171 /// Parse an expression, subject to the given restrictions
3172 pub fn parse_expr_res(&mut self, r: Restrictions) -> P<Expr> {
3173 let old = self.restrictions;
3174 self.restrictions = r;
3175 let e = self.parse_assign_expr();
3176 self.restrictions = old;
3180 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3181 fn parse_initializer(&mut self) -> Option<P<Expr>> {
3182 if self.check(&token::Eq) {
3184 Some(self.parse_expr())
3190 /// Parse patterns, separated by '|' s
3191 fn parse_pats(&mut self) -> Vec<P<Pat>> {
3192 let mut pats = Vec::new();
3194 pats.push(self.parse_pat());
3195 if self.check(&token::BinOp(token::Or)) { self.bump(); }
3196 else { return pats; }
3200 fn parse_pat_vec_elements(
3202 ) -> (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>) {
3203 let mut before = Vec::new();
3204 let mut slice = None;
3205 let mut after = Vec::new();
3206 let mut first = true;
3207 let mut before_slice = true;
3209 while self.token != token::CloseDelim(token::Bracket) {
3213 self.expect(&token::Comma);
3215 if self.token == token::CloseDelim(token::Bracket)
3216 && (before_slice || after.len() != 0) {
3222 if self.check(&token::DotDot) {
3225 if self.check(&token::Comma) ||
3226 self.check(&token::CloseDelim(token::Bracket)) {
3227 slice = Some(P(ast::Pat {
3228 id: ast::DUMMY_NODE_ID,
3229 node: PatWild(PatWildMulti),
3232 before_slice = false;
3238 let subpat = self.parse_pat();
3239 if before_slice && self.check(&token::DotDot) {
3241 slice = Some(subpat);
3242 before_slice = false;
3243 } else if before_slice {
3244 before.push(subpat);
3250 (before, slice, after)
3253 /// Parse the fields of a struct-like pattern
3254 fn parse_pat_fields(&mut self) -> (Vec<codemap::Spanned<ast::FieldPat>> , bool) {
3255 let mut fields = Vec::new();
3256 let mut etc = false;
3257 let mut first = true;
3258 while self.token != token::CloseDelim(token::Brace) {
3262 self.expect(&token::Comma);
3263 // accept trailing commas
3264 if self.check(&token::CloseDelim(token::Brace)) { break }
3267 let lo = self.span.lo;
3270 if self.check(&token::DotDot) {
3272 if self.token != token::CloseDelim(token::Brace) {
3273 let token_str = self.this_token_to_string();
3274 self.fatal(&format!("expected `{}`, found `{}`", "}",
3281 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3282 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3283 // Parsing a pattern of the form "fieldname: pat"
3284 let fieldname = self.parse_ident();
3286 let pat = self.parse_pat();
3288 (pat, fieldname, false)
3290 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3291 let is_box = self.eat_keyword(keywords::Box);
3292 let boxed_span_lo = self.span.lo;
3293 let is_ref = self.eat_keyword(keywords::Ref);
3294 let is_mut = self.eat_keyword(keywords::Mut);
3295 let fieldname = self.parse_ident();
3296 hi = self.last_span.hi;
3298 let bind_type = match (is_ref, is_mut) {
3299 (true, true) => BindByRef(MutMutable),
3300 (true, false) => BindByRef(MutImmutable),
3301 (false, true) => BindByValue(MutMutable),
3302 (false, false) => BindByValue(MutImmutable),
3304 let fieldpath = codemap::Spanned{span:self.last_span, node:fieldname};
3305 let fieldpat = P(ast::Pat{
3306 id: ast::DUMMY_NODE_ID,
3307 node: PatIdent(bind_type, fieldpath, None),
3308 span: mk_sp(boxed_span_lo, hi),
3311 let subpat = if is_box {
3313 id: ast::DUMMY_NODE_ID,
3314 node: PatBox(fieldpat),
3315 span: mk_sp(lo, hi),
3320 (subpat, fieldname, true)
3323 fields.push(codemap::Spanned { span: mk_sp(lo, hi),
3324 node: ast::FieldPat { ident: fieldname,
3326 is_shorthand: is_shorthand }});
3328 return (fields, etc);
3331 /// Parse a pattern.
3332 pub fn parse_pat(&mut self) -> P<Pat> {
3333 maybe_whole!(self, NtPat);
3335 let lo = self.span.lo;
3340 token::Underscore => {
3342 pat = PatWild(PatWildSingle);
3343 hi = self.last_span.hi;
3345 id: ast::DUMMY_NODE_ID,
3350 token::BinOp(token::And) | token::AndAnd => {
3351 // parse &pat and &mut pat
3352 let lo = self.span.lo;
3354 let mutability = if self.eat_keyword(keywords::Mut) {
3359 let sub = self.parse_pat();
3360 pat = PatRegion(sub, mutability);
3361 hi = self.last_span.hi;
3363 id: ast::DUMMY_NODE_ID,
3368 token::OpenDelim(token::Paren) => {
3369 // parse (pat,pat,pat,...) as tuple
3371 if self.check(&token::CloseDelim(token::Paren)) {
3373 pat = PatTup(vec![]);
3375 let mut fields = vec!(self.parse_pat());
3376 if self.look_ahead(1, |t| *t != token::CloseDelim(token::Paren)) {
3377 while self.check(&token::Comma) {
3379 if self.check(&token::CloseDelim(token::Paren)) { break; }
3380 fields.push(self.parse_pat());
3383 if fields.len() == 1 { self.expect(&token::Comma); }
3384 self.expect(&token::CloseDelim(token::Paren));
3385 pat = PatTup(fields);
3387 hi = self.last_span.hi;
3389 id: ast::DUMMY_NODE_ID,
3394 token::OpenDelim(token::Bracket) => {
3395 // parse [pat,pat,...] as vector pattern
3397 let (before, slice, after) =
3398 self.parse_pat_vec_elements();
3400 self.expect(&token::CloseDelim(token::Bracket));
3401 pat = ast::PatVec(before, slice, after);
3402 hi = self.last_span.hi;
3404 id: ast::DUMMY_NODE_ID,
3411 // at this point, token != _, ~, &, &&, (, [
3413 if (!(self.token.is_ident() || self.token.is_path())
3414 && self.token != token::ModSep)
3415 || self.token.is_keyword(keywords::True)
3416 || self.token.is_keyword(keywords::False) {
3417 // Parse an expression pattern or exp ... exp.
3419 // These expressions are limited to literals (possibly
3420 // preceded by unary-minus) or identifiers.
3421 let val = self.parse_literal_maybe_minus();
3422 if (self.check(&token::DotDotDot)) &&
3423 self.look_ahead(1, |t| {
3424 *t != token::Comma && *t != token::CloseDelim(token::Bracket)
3427 let end = if self.token.is_ident() || self.token.is_path() {
3428 let path = self.parse_path(LifetimeAndTypesWithColons);
3429 let hi = self.span.hi;
3430 self.mk_expr(lo, hi, ExprPath(path))
3432 self.parse_literal_maybe_minus()
3434 pat = PatRange(val, end);
3438 } else if self.eat_keyword(keywords::Mut) {
3439 pat = self.parse_pat_ident(BindByValue(MutMutable));
3440 } else if self.eat_keyword(keywords::Ref) {
3442 let mutbl = self.parse_mutability();
3443 pat = self.parse_pat_ident(BindByRef(mutbl));
3444 } else if self.eat_keyword(keywords::Box) {
3447 // FIXME(#13910): Rename to `PatBox` and extend to full DST
3449 let sub = self.parse_pat();
3451 hi = self.last_span.hi;
3453 id: ast::DUMMY_NODE_ID,
3458 let can_be_enum_or_struct = self.look_ahead(1, |t| {
3460 token::OpenDelim(_) | token::Lt | token::ModSep => true,
3465 if self.look_ahead(1, |t| *t == token::DotDotDot) &&
3466 self.look_ahead(2, |t| {
3467 *t != token::Comma && *t != token::CloseDelim(token::Bracket)
3469 let start = self.parse_expr_res(RESTRICTION_NO_BAR_OP);
3470 self.eat(&token::DotDotDot);
3471 let end = self.parse_expr_res(RESTRICTION_NO_BAR_OP);
3472 pat = PatRange(start, end);
3473 } else if self.token.is_plain_ident() && !can_be_enum_or_struct {
3474 let id = self.parse_ident();
3475 let id_span = self.last_span;
3476 let pth1 = codemap::Spanned{span:id_span, node: id};
3477 if self.eat(&token::Not) {
3479 let delim = self.expect_open_delim();
3480 let tts = self.parse_seq_to_end(&token::CloseDelim(delim),
3482 |p| p.parse_token_tree());
3484 let mac = MacInvocTT(ident_to_path(id_span,id), tts, EMPTY_CTXT);
3485 pat = ast::PatMac(codemap::Spanned {node: mac, span: self.span});
3487 let sub = if self.eat(&token::At) {
3489 Some(self.parse_pat())
3494 pat = PatIdent(BindByValue(MutImmutable), pth1, sub);
3497 // parse an enum pat
3498 let enum_path = self.parse_path(LifetimeAndTypesWithColons);
3500 token::OpenDelim(token::Brace) => {
3503 self.parse_pat_fields();
3505 pat = PatStruct(enum_path, fields, etc);
3508 let mut args: Vec<P<Pat>> = Vec::new();
3510 token::OpenDelim(token::Paren) => {
3511 let is_dotdot = self.look_ahead(1, |t| {
3513 token::DotDot => true,
3518 // This is a "top constructor only" pat
3521 self.expect(&token::CloseDelim(token::Paren));
3522 pat = PatEnum(enum_path, None);
3524 args = self.parse_enum_variant_seq(
3525 &token::OpenDelim(token::Paren),
3526 &token::CloseDelim(token::Paren),
3527 seq_sep_trailing_allowed(token::Comma),
3530 pat = PatEnum(enum_path, Some(args));
3534 if !enum_path.global &&
3535 enum_path.segments.len() == 1 &&
3536 enum_path.segments[0].parameters.is_empty()
3538 // NB: If enum_path is a single identifier,
3539 // this should not be reachable due to special
3540 // handling further above.
3542 // However, previously a PatIdent got emitted
3543 // here, so we preserve the branch just in case.
3545 // A rewrite of the logic in this function
3546 // would probably make this obvious.
3547 self.span_bug(enum_path.span,
3548 "ident only path should have been covered already");
3550 pat = PatEnum(enum_path, Some(args));
3558 hi = self.last_span.hi;
3560 id: ast::DUMMY_NODE_ID,
3562 span: mk_sp(lo, hi),
3566 /// Parse ident or ident @ pat
3567 /// used by the copy foo and ref foo patterns to give a good
3568 /// error message when parsing mistakes like ref foo(a,b)
3569 fn parse_pat_ident(&mut self,
3570 binding_mode: ast::BindingMode)
3572 if !self.token.is_plain_ident() {
3573 let span = self.span;
3574 let tok_str = self.this_token_to_string();
3575 self.span_fatal(span,
3576 &format!("expected identifier, found `{}`", tok_str));
3578 let ident = self.parse_ident();
3579 let last_span = self.last_span;
3580 let name = codemap::Spanned{span: last_span, node: ident};
3581 let sub = if self.eat(&token::At) {
3582 Some(self.parse_pat())
3587 // just to be friendly, if they write something like
3589 // we end up here with ( as the current token. This shortly
3590 // leads to a parse error. Note that if there is no explicit
3591 // binding mode then we do not end up here, because the lookahead
3592 // will direct us over to parse_enum_variant()
3593 if self.token == token::OpenDelim(token::Paren) {
3594 let last_span = self.last_span;
3597 "expected identifier, found enum pattern");
3600 PatIdent(binding_mode, name, sub)
3603 /// Parse a local variable declaration
3604 fn parse_local(&mut self) -> P<Local> {
3605 let lo = self.span.lo;
3606 let pat = self.parse_pat();
3609 if self.eat(&token::Colon) {
3610 ty = Some(self.parse_ty_sum());
3612 let init = self.parse_initializer();
3617 id: ast::DUMMY_NODE_ID,
3618 span: mk_sp(lo, self.last_span.hi),
3623 /// Parse a "let" stmt
3624 fn parse_let(&mut self) -> P<Decl> {
3625 let lo = self.span.lo;
3626 let local = self.parse_local();
3627 P(spanned(lo, self.last_span.hi, DeclLocal(local)))
3630 /// Parse a structure field
3631 fn parse_name_and_ty(&mut self, pr: Visibility,
3632 attrs: Vec<Attribute> ) -> StructField {
3633 let lo = self.span.lo;
3634 if !self.token.is_plain_ident() {
3635 self.fatal("expected ident");
3637 let name = self.parse_ident();
3638 self.expect(&token::Colon);
3639 let ty = self.parse_ty_sum();
3640 spanned(lo, self.last_span.hi, ast::StructField_ {
3641 kind: NamedField(name, pr),
3642 id: ast::DUMMY_NODE_ID,
3648 /// Get an expected item after attributes error message.
3649 fn expected_item_err(attrs: &[Attribute]) -> &'static str {
3650 match attrs.last() {
3651 Some(&Attribute { node: ast::Attribute_ { is_sugared_doc: true, .. }, .. }) => {
3652 "expected item after doc comment"
3654 _ => "expected item after attributes",
3658 /// Parse a statement. may include decl.
3659 /// Precondition: any attributes are parsed already
3660 pub fn parse_stmt(&mut self, item_attrs: Vec<Attribute>) -> P<Stmt> {
3661 maybe_whole!(self, NtStmt);
3663 fn check_expected_item(p: &mut Parser, attrs: &[Attribute]) {
3664 // If we have attributes then we should have an item
3665 if !attrs.is_empty() {
3666 let last_span = p.last_span;
3667 p.span_err(last_span, Parser::expected_item_err(attrs));
3671 let lo = self.span.lo;
3672 if self.check_keyword(keywords::Let) {
3673 check_expected_item(self, &item_attrs[..]);
3674 self.expect_keyword(keywords::Let);
3675 let decl = self.parse_let();
3676 P(spanned(lo, decl.span.hi, StmtDecl(decl, ast::DUMMY_NODE_ID)))
3677 } else if self.token.is_ident()
3678 && !self.token.is_any_keyword()
3679 && self.look_ahead(1, |t| *t == token::Not) {
3680 // it's a macro invocation:
3682 check_expected_item(self, &item_attrs[..]);
3684 // Potential trouble: if we allow macros with paths instead of
3685 // idents, we'd need to look ahead past the whole path here...
3686 let pth = self.parse_path(NoTypesAllowed);
3689 let id = match self.token {
3690 token::OpenDelim(_) => token::special_idents::invalid, // no special identifier
3691 _ => self.parse_ident(),
3694 // check that we're pointing at delimiters (need to check
3695 // again after the `if`, because of `parse_ident`
3696 // consuming more tokens).
3697 let delim = match self.token {
3698 token::OpenDelim(delim) => delim,
3700 // we only expect an ident if we didn't parse one
3702 let ident_str = if id.name == token::special_idents::invalid.name {
3707 let tok_str = self.this_token_to_string();
3708 self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
3714 let tts = self.parse_unspanned_seq(
3715 &token::OpenDelim(delim),
3716 &token::CloseDelim(delim),
3718 |p| p.parse_token_tree()
3720 let hi = self.span.hi;
3722 let style = if delim == token::Brace {
3725 MacStmtWithoutBraces
3728 if id.name == token::special_idents::invalid.name {
3731 StmtMac(P(spanned(lo,
3733 MacInvocTT(pth, tts, EMPTY_CTXT))),
3736 // if it has a special ident, it's definitely an item
3738 // Require a semicolon or braces.
3739 if style != MacStmtWithBraces {
3740 if !self.eat(&token::Semi) {
3741 let last_span = self.last_span;
3742 self.span_err(last_span,
3743 "macros that expand to items must \
3744 either be surrounded with braces or \
3745 followed by a semicolon");
3748 P(spanned(lo, hi, StmtDecl(
3749 P(spanned(lo, hi, DeclItem(
3751 lo, hi, id /*id is good here*/,
3752 ItemMac(spanned(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT))),
3753 Inherited, Vec::new(/*no attrs*/))))),
3754 ast::DUMMY_NODE_ID)))
3757 let found_attrs = !item_attrs.is_empty();
3758 let item_err = Parser::expected_item_err(&item_attrs[..]);
3759 match self.parse_item_(item_attrs, false) {
3762 let decl = P(spanned(lo, hi, DeclItem(i)));
3763 P(spanned(lo, hi, StmtDecl(decl, ast::DUMMY_NODE_ID)))
3767 let last_span = self.last_span;
3768 self.span_err(last_span, item_err);
3771 // Remainder are line-expr stmts.
3772 let e = self.parse_expr_res(RESTRICTION_STMT_EXPR);
3773 P(spanned(lo, e.span.hi, StmtExpr(e, ast::DUMMY_NODE_ID)))
3779 /// Is this expression a successfully-parsed statement?
3780 fn expr_is_complete(&mut self, e: &Expr) -> bool {
3781 self.restrictions.contains(RESTRICTION_STMT_EXPR) &&
3782 !classify::expr_requires_semi_to_be_stmt(e)
3785 /// Parse a block. No inner attrs are allowed.
3786 pub fn parse_block(&mut self) -> P<Block> {
3787 maybe_whole!(no_clone self, NtBlock);
3789 let lo = self.span.lo;
3791 if !self.eat(&token::OpenDelim(token::Brace)) {
3793 let tok = self.this_token_to_string();
3794 self.span_fatal_help(sp,
3795 &format!("expected `{{`, found `{}`", tok),
3796 "place this code inside a block");
3799 return self.parse_block_tail_(lo, DefaultBlock, Vec::new());
3802 /// Parse a block. Inner attrs are allowed.
3803 fn parse_inner_attrs_and_block(&mut self)
3804 -> (Vec<Attribute> , P<Block>) {
3806 maybe_whole!(pair_empty self, NtBlock);
3808 let lo = self.span.lo;
3809 self.expect(&token::OpenDelim(token::Brace));
3810 let (inner, next) = self.parse_inner_attrs_and_next();
3812 (inner, self.parse_block_tail_(lo, DefaultBlock, next))
3815 /// Precondition: already parsed the '{'.
3816 fn parse_block_tail(&mut self, lo: BytePos, s: BlockCheckMode) -> P<Block> {
3817 self.parse_block_tail_(lo, s, Vec::new())
3820 /// Parse the rest of a block expression or function body
3821 fn parse_block_tail_(&mut self, lo: BytePos, s: BlockCheckMode,
3822 first_item_attrs: Vec<Attribute>) -> P<Block> {
3823 let mut stmts = vec![];
3824 let mut expr = None;
3825 let mut attributes_box = first_item_attrs;
3827 while self.token != token::CloseDelim(token::Brace) {
3828 // parsing items even when they're not allowed lets us give
3829 // better error messages and recover more gracefully.
3830 attributes_box.push_all(&self.parse_outer_attributes());
3833 if !attributes_box.is_empty() {
3834 let last_span = self.last_span;
3835 self.span_err(last_span,
3836 Parser::expected_item_err(&attributes_box[..]));
3837 attributes_box = Vec::new();
3839 self.bump(); // empty
3841 token::CloseDelim(token::Brace) => {
3842 // fall through and out.
3845 let stmt = self.parse_stmt(attributes_box);
3846 attributes_box = Vec::new();
3847 stmt.and_then(|Spanned {node, span}| match node {
3848 StmtExpr(e, stmt_id) => {
3849 self.handle_expression_like_statement(e,
3855 StmtMac(mac, MacStmtWithoutBraces) => {
3856 // statement macro without braces; might be an
3857 // expr depending on whether a semicolon follows
3860 stmts.push(P(Spanned {
3862 MacStmtWithSemicolon),
3868 let e = self.mk_mac_expr(span.lo,
3870 mac.and_then(|m| m.node));
3871 let e = self.parse_dot_or_call_expr_with(e);
3872 let e = self.parse_more_binops(e, 0);
3873 let e = self.parse_assign_expr_with(e);
3874 self.handle_expression_like_statement(
3883 StmtMac(m, style) => {
3884 // statement macro; might be an expr
3887 stmts.push(P(Spanned {
3889 MacStmtWithSemicolon),
3894 token::CloseDelim(token::Brace) => {
3895 // if a block ends in `m!(arg)` without
3896 // a `;`, it must be an expr
3898 self.mk_mac_expr(span.lo,
3900 m.and_then(|x| x.node)));
3903 stmts.push(P(Spanned {
3904 node: StmtMac(m, style),
3910 _ => { // all other kinds of statements:
3911 if classify::stmt_ends_with_semi(&node) {
3912 self.commit_stmt_expecting(token::Semi);
3915 stmts.push(P(Spanned {
3925 if !attributes_box.is_empty() {
3926 let last_span = self.last_span;
3927 self.span_err(last_span,
3928 Parser::expected_item_err(&attributes_box[..]));
3931 let hi = self.span.hi;
3936 id: ast::DUMMY_NODE_ID,
3938 span: mk_sp(lo, hi),
3942 fn handle_expression_like_statement(
3947 stmts: &mut Vec<P<Stmt>>,
3948 last_block_expr: &mut Option<P<Expr>>) {
3949 // expression without semicolon
3950 if classify::expr_requires_semi_to_be_stmt(&*e) {
3951 // Just check for errors and recover; do not eat semicolon yet.
3952 self.commit_stmt(&[],
3953 &[token::Semi, token::CloseDelim(token::Brace)]);
3959 let span_with_semi = Span {
3961 hi: self.last_span.hi,
3962 expn_id: span.expn_id,
3964 stmts.push(P(Spanned {
3965 node: StmtSemi(e, stmt_id),
3966 span: span_with_semi,
3969 token::CloseDelim(token::Brace) => *last_block_expr = Some(e),
3971 stmts.push(P(Spanned {
3972 node: StmtExpr(e, stmt_id),
3979 // Parses a sequence of bounds if a `:` is found,
3980 // otherwise returns empty list.
3981 fn parse_colon_then_ty_param_bounds(&mut self,
3982 mode: BoundParsingMode)
3983 -> OwnedSlice<TyParamBound>
3985 if !self.eat(&token::Colon) {
3988 self.parse_ty_param_bounds(mode)
3992 // matches bounds = ( boundseq )?
3993 // where boundseq = ( polybound + boundseq ) | polybound
3994 // and polybound = ( 'for' '<' 'region '>' )? bound
3995 // and bound = 'region | trait_ref
3996 fn parse_ty_param_bounds(&mut self,
3997 mode: BoundParsingMode)
3998 -> OwnedSlice<TyParamBound>
4000 let mut result = vec!();
4002 let question_span = self.span;
4003 let ate_question = self.eat(&token::Question);
4005 token::Lifetime(lifetime) => {
4007 self.span_err(question_span,
4008 "`?` may only modify trait bounds, not lifetime bounds");
4010 result.push(RegionTyParamBound(ast::Lifetime {
4011 id: ast::DUMMY_NODE_ID,
4017 token::ModSep | token::Ident(..) => {
4018 let poly_trait_ref = self.parse_poly_trait_ref();
4019 let modifier = if ate_question {
4020 if mode == BoundParsingMode::Modified {
4021 TraitBoundModifier::Maybe
4023 self.span_err(question_span,
4025 TraitBoundModifier::None
4028 TraitBoundModifier::None
4030 result.push(TraitTyParamBound(poly_trait_ref, modifier))
4035 if !self.eat(&token::BinOp(token::Plus)) {
4040 return OwnedSlice::from_vec(result);
4043 fn trait_ref_from_ident(ident: Ident, span: Span) -> TraitRef {
4044 let segment = ast::PathSegment {
4046 parameters: ast::PathParameters::none()
4048 let path = ast::Path {
4051 segments: vec![segment],
4055 ref_id: ast::DUMMY_NODE_ID,
4059 /// Matches typaram = (unbound `?`)? IDENT (`?` unbound)? optbounds ( EQ ty )?
4060 fn parse_ty_param(&mut self) -> TyParam {
4061 // This is a bit hacky. Currently we are only interested in a single
4062 // unbound, and it may only be `Sized`. To avoid backtracking and other
4063 // complications, we parse an ident, then check for `?`. If we find it,
4064 // we use the ident as the unbound, otherwise, we use it as the name of
4065 // type param. Even worse, we need to check for `?` before or after the
4067 let mut span = self.span;
4068 let mut ident = self.parse_ident();
4069 let mut unbound = None;
4070 if self.eat(&token::Question) {
4071 let tref = Parser::trait_ref_from_ident(ident, span);
4072 unbound = Some(tref);
4074 ident = self.parse_ident();
4075 self.obsolete(span, ObsoleteSyntax::Sized);
4078 let mut bounds = self.parse_colon_then_ty_param_bounds(BoundParsingMode::Modified);
4079 if let Some(unbound) = unbound {
4080 let mut bounds_as_vec = bounds.into_vec();
4081 bounds_as_vec.push(TraitTyParamBound(PolyTraitRef { bound_lifetimes: vec![],
4084 TraitBoundModifier::Maybe));
4085 bounds = OwnedSlice::from_vec(bounds_as_vec);
4088 let default = if self.check(&token::Eq) {
4090 Some(self.parse_ty_sum())
4096 id: ast::DUMMY_NODE_ID,
4103 /// Parse a set of optional generic type parameter declarations. Where
4104 /// clauses are not parsed here, and must be added later via
4105 /// `parse_where_clause()`.
4107 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
4108 /// | ( < lifetimes , typaramseq ( , )? > )
4109 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
4110 pub fn parse_generics(&mut self) -> ast::Generics {
4111 if self.eat(&token::Lt) {
4112 let lifetime_defs = self.parse_lifetime_defs();
4113 let mut seen_default = false;
4114 let ty_params = self.parse_seq_to_gt(Some(token::Comma), |p| {
4115 p.forbid_lifetime();
4116 let ty_param = p.parse_ty_param();
4117 if ty_param.default.is_some() {
4118 seen_default = true;
4119 } else if seen_default {
4120 let last_span = p.last_span;
4121 p.span_err(last_span,
4122 "type parameters with a default must be trailing");
4127 lifetimes: lifetime_defs,
4128 ty_params: ty_params,
4129 where_clause: WhereClause {
4130 id: ast::DUMMY_NODE_ID,
4131 predicates: Vec::new(),
4135 ast_util::empty_generics()
4139 fn parse_generic_values_after_lt(&mut self)
4140 -> (Vec<ast::Lifetime>, Vec<P<Ty>>, Vec<P<TypeBinding>>) {
4141 let lifetimes = self.parse_lifetimes(token::Comma);
4143 // First parse types.
4144 let (types, returned) = self.parse_seq_to_gt_or_return(
4147 p.forbid_lifetime();
4148 if p.look_ahead(1, |t| t == &token::Eq) {
4151 Some(p.parse_ty_sum())
4156 // If we found the `>`, don't continue.
4158 return (lifetimes, types.into_vec(), Vec::new());
4161 // Then parse type bindings.
4162 let bindings = self.parse_seq_to_gt(
4165 p.forbid_lifetime();
4167 let ident = p.parse_ident();
4168 let found_eq = p.eat(&token::Eq);
4171 p.span_warn(span, "whoops, no =?");
4173 let ty = p.parse_ty();
4175 let span = mk_sp(lo, hi);
4176 return P(TypeBinding{id: ast::DUMMY_NODE_ID,
4183 (lifetimes, types.into_vec(), bindings.into_vec())
4186 fn forbid_lifetime(&mut self) {
4187 if self.token.is_lifetime() {
4188 let span = self.span;
4189 self.span_fatal(span, "lifetime parameters must be declared \
4190 prior to type parameters");
4194 /// Parses an optional `where` clause and places it in `generics`.
4197 /// where T : Trait<U, V> + 'b, 'a : 'b
4199 fn parse_where_clause(&mut self, generics: &mut ast::Generics) {
4200 if !self.eat_keyword(keywords::Where) {
4204 let mut parsed_something = false;
4206 let lo = self.span.lo;
4208 token::OpenDelim(token::Brace) => {
4212 token::Lifetime(..) => {
4213 let bounded_lifetime =
4214 self.parse_lifetime();
4216 self.eat(&token::Colon);
4219 self.parse_lifetimes(token::BinOp(token::Plus));
4221 let hi = self.span.hi;
4222 let span = mk_sp(lo, hi);
4224 generics.where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
4225 ast::WhereRegionPredicate {
4227 lifetime: bounded_lifetime,
4232 parsed_something = true;
4236 let bound_lifetimes = if self.eat_keyword(keywords::For) {
4237 // Higher ranked constraint.
4238 self.expect(&token::Lt);
4239 let lifetime_defs = self.parse_lifetime_defs();
4246 let bounded_ty = self.parse_ty();
4248 if self.eat(&token::Colon) {
4249 let bounds = self.parse_ty_param_bounds(BoundParsingMode::Bare);
4250 let hi = self.span.hi;
4251 let span = mk_sp(lo, hi);
4253 if bounds.len() == 0 {
4255 "each predicate in a `where` clause must have \
4256 at least one bound in it");
4259 generics.where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
4260 ast::WhereBoundPredicate {
4262 bound_lifetimes: bound_lifetimes,
4263 bounded_ty: bounded_ty,
4267 parsed_something = true;
4268 } else if self.eat(&token::Eq) {
4269 // let ty = self.parse_ty();
4270 let hi = self.span.hi;
4271 let span = mk_sp(lo, hi);
4272 // generics.where_clause.predicates.push(
4273 // ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
4274 // id: ast::DUMMY_NODE_ID,
4276 // path: panic!("NYI"), //bounded_ty,
4279 // parsed_something = true;
4282 "equality constraints are not yet supported \
4283 in where clauses (#20041)");
4285 let last_span = self.last_span;
4286 self.span_err(last_span,
4287 "unexpected token in `where` clause");
4292 if !self.eat(&token::Comma) {
4297 if !parsed_something {
4298 let last_span = self.last_span;
4299 self.span_err(last_span,
4300 "a `where` clause must have at least one predicate \
4305 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
4306 -> (Vec<Arg> , bool) {
4308 let mut args: Vec<Option<Arg>> =
4309 self.parse_unspanned_seq(
4310 &token::OpenDelim(token::Paren),
4311 &token::CloseDelim(token::Paren),
4312 seq_sep_trailing_allowed(token::Comma),
4314 if p.token == token::DotDotDot {
4317 if p.token != token::CloseDelim(token::Paren) {
4320 "`...` must be last in argument list for variadic function");
4325 "only foreign functions are allowed to be variadic");
4329 Some(p.parse_arg_general(named_args))
4334 let variadic = match args.pop() {
4337 // Need to put back that last arg
4344 if variadic && args.is_empty() {
4346 "variadic function must be declared with at least one named argument");
4349 let args = args.into_iter().map(|x| x.unwrap()).collect();
4354 /// Parse the argument list and result type of a function declaration
4355 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> P<FnDecl> {
4357 let (args, variadic) = self.parse_fn_args(true, allow_variadic);
4358 let ret_ty = self.parse_ret_ty();
4367 fn is_self_ident(&mut self) -> bool {
4369 token::Ident(id, token::Plain) => id.name == special_idents::self_.name,
4374 fn expect_self_ident(&mut self) -> ast::Ident {
4376 token::Ident(id, token::Plain) if id.name == special_idents::self_.name => {
4381 let token_str = self.this_token_to_string();
4382 self.fatal(&format!("expected `self`, found `{}`",
4388 fn is_self_type_ident(&mut self) -> bool {
4390 token::Ident(id, token::Plain) => id.name == special_idents::type_self.name,
4395 fn expect_self_type_ident(&mut self) -> ast::Ident {
4397 token::Ident(id, token::Plain) if id.name == special_idents::type_self.name => {
4402 let token_str = self.this_token_to_string();
4403 self.fatal(&format!("expected `Self`, found `{}`",
4409 /// Parse the argument list and result type of a function
4410 /// that may have a self type.
4411 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> (ExplicitSelf, P<FnDecl>) where
4412 F: FnMut(&mut Parser) -> Arg,
4414 fn maybe_parse_borrowed_explicit_self(this: &mut Parser)
4415 -> ast::ExplicitSelf_ {
4416 // The following things are possible to see here:
4421 // fn(&'lt mut self)
4423 // We already know that the current token is `&`.
4425 if this.look_ahead(1, |t| t.is_keyword(keywords::SelfValue)) {
4427 SelfRegion(None, MutImmutable, this.expect_self_ident())
4428 } else if this.look_ahead(1, |t| t.is_mutability()) &&
4429 this.look_ahead(2, |t| t.is_keyword(keywords::SelfValue)) {
4431 let mutability = this.parse_mutability();
4432 SelfRegion(None, mutability, this.expect_self_ident())
4433 } else if this.look_ahead(1, |t| t.is_lifetime()) &&
4434 this.look_ahead(2, |t| t.is_keyword(keywords::SelfValue)) {
4436 let lifetime = this.parse_lifetime();
4437 SelfRegion(Some(lifetime), MutImmutable, this.expect_self_ident())
4438 } else if this.look_ahead(1, |t| t.is_lifetime()) &&
4439 this.look_ahead(2, |t| t.is_mutability()) &&
4440 this.look_ahead(3, |t| t.is_keyword(keywords::SelfValue)) {
4442 let lifetime = this.parse_lifetime();
4443 let mutability = this.parse_mutability();
4444 SelfRegion(Some(lifetime), mutability, this.expect_self_ident())
4450 self.expect(&token::OpenDelim(token::Paren));
4452 // A bit of complexity and lookahead is needed here in order to be
4453 // backwards compatible.
4454 let lo = self.span.lo;
4455 let mut self_ident_lo = self.span.lo;
4456 let mut self_ident_hi = self.span.hi;
4458 let mut mutbl_self = MutImmutable;
4459 let explicit_self = match self.token {
4460 token::BinOp(token::And) => {
4461 let eself = maybe_parse_borrowed_explicit_self(self);
4462 self_ident_lo = self.last_span.lo;
4463 self_ident_hi = self.last_span.hi;
4466 token::BinOp(token::Star) => {
4467 // Possibly "*self" or "*mut self" -- not supported. Try to avoid
4468 // emitting cryptic "unexpected token" errors.
4470 let _mutability = if self.token.is_mutability() {
4471 self.parse_mutability()
4475 if self.is_self_ident() {
4476 let span = self.span;
4477 self.span_err(span, "cannot pass self by unsafe pointer");
4480 // error case, making bogus self ident:
4481 SelfValue(special_idents::self_)
4483 token::Ident(..) => {
4484 if self.is_self_ident() {
4485 let self_ident = self.expect_self_ident();
4487 // Determine whether this is the fully explicit form, `self:
4489 if self.eat(&token::Colon) {
4490 SelfExplicit(self.parse_ty_sum(), self_ident)
4492 SelfValue(self_ident)
4494 } else if self.token.is_mutability() &&
4495 self.look_ahead(1, |t| t.is_keyword(keywords::SelfValue)) {
4496 mutbl_self = self.parse_mutability();
4497 let self_ident = self.expect_self_ident();
4499 // Determine whether this is the fully explicit form,
4501 if self.eat(&token::Colon) {
4502 SelfExplicit(self.parse_ty_sum(), self_ident)
4504 SelfValue(self_ident)
4513 let explicit_self_sp = mk_sp(self_ident_lo, self_ident_hi);
4515 // shared fall-through for the three cases below. borrowing prevents simply
4516 // writing this as a closure
4517 macro_rules! parse_remaining_arguments {
4520 // If we parsed a self type, expect a comma before the argument list.
4524 let sep = seq_sep_trailing_allowed(token::Comma);
4525 let mut fn_inputs = self.parse_seq_to_before_end(
4526 &token::CloseDelim(token::Paren),
4530 fn_inputs.insert(0, Arg::new_self(explicit_self_sp, mutbl_self, $self_id));
4533 token::CloseDelim(token::Paren) => {
4534 vec!(Arg::new_self(explicit_self_sp, mutbl_self, $self_id))
4537 let token_str = self.this_token_to_string();
4538 self.fatal(&format!("expected `,` or `)`, found `{}`",
4545 let fn_inputs = match explicit_self {
4547 let sep = seq_sep_trailing_allowed(token::Comma);
4548 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)
4550 SelfValue(id) => parse_remaining_arguments!(id),
4551 SelfRegion(_,_,id) => parse_remaining_arguments!(id),
4552 SelfExplicit(_,id) => parse_remaining_arguments!(id),
4556 self.expect(&token::CloseDelim(token::Paren));
4558 let hi = self.span.hi;
4560 let ret_ty = self.parse_ret_ty();
4562 let fn_decl = P(FnDecl {
4568 (spanned(lo, hi, explicit_self), fn_decl)
4571 // parse the |arg, arg| header on a lambda
4572 fn parse_fn_block_decl(&mut self) -> P<FnDecl> {
4573 let inputs_captures = {
4574 if self.eat(&token::OrOr) {
4577 self.expect(&token::BinOp(token::Or));
4578 self.parse_obsolete_closure_kind();
4579 let args = self.parse_seq_to_before_end(
4580 &token::BinOp(token::Or),
4581 seq_sep_trailing_allowed(token::Comma),
4582 |p| p.parse_fn_block_arg()
4588 let output = self.parse_ret_ty();
4591 inputs: inputs_captures,
4597 /// Parses the `(arg, arg) -> return_type` header on a procedure.
4598 fn parse_proc_decl(&mut self) -> P<FnDecl> {
4600 self.parse_unspanned_seq(&token::OpenDelim(token::Paren),
4601 &token::CloseDelim(token::Paren),
4602 seq_sep_trailing_allowed(token::Comma),
4603 |p| p.parse_fn_block_arg());
4605 let output = self.parse_ret_ty();
4614 /// Parse the name and optional generic types of a function header.
4615 fn parse_fn_header(&mut self) -> (Ident, ast::Generics) {
4616 let id = self.parse_ident();
4617 let generics = self.parse_generics();
4621 fn mk_item(&mut self, lo: BytePos, hi: BytePos, ident: Ident,
4622 node: Item_, vis: Visibility,
4623 attrs: Vec<Attribute>) -> P<Item> {
4627 id: ast::DUMMY_NODE_ID,
4634 /// Parse an item-position function declaration.
4635 fn parse_item_fn(&mut self, unsafety: Unsafety, abi: abi::Abi) -> ItemInfo {
4636 let (ident, mut generics) = self.parse_fn_header();
4637 let decl = self.parse_fn_decl(false);
4638 self.parse_where_clause(&mut generics);
4639 let (inner_attrs, body) = self.parse_inner_attrs_and_block();
4640 (ident, ItemFn(decl, unsafety, abi, generics, body), Some(inner_attrs))
4643 /// Parse a method in a trait impl
4644 pub fn parse_method_with_outer_attributes(&mut self) -> P<Method> {
4645 let attrs = self.parse_outer_attributes();
4646 let visa = self.parse_visibility();
4647 self.parse_method(attrs, visa)
4650 fn complain_if_pub_macro(&mut self, visa: Visibility, span: Span) {
4653 self.span_err(span, "can't qualify macro invocation with `pub`");
4654 self.span_help(span, "try adjusting the macro to put `pub` inside \
4661 /// Parse a method in a trait impl, starting with `attrs` attributes.
4662 pub fn parse_method(&mut self,
4663 attrs: Vec<Attribute>,
4666 let lo = self.span.lo;
4668 // code copied from parse_macro_use_or_failure... abstraction!
4669 let (method_, hi, new_attrs) = {
4670 if !self.token.is_any_keyword()
4671 && self.look_ahead(1, |t| *t == token::Not)
4672 && (self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren))
4673 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) {
4676 let last_span = self.last_span;
4677 self.complain_if_pub_macro(visa, last_span);
4679 let pth = self.parse_path(NoTypesAllowed);
4680 self.expect(&token::Not);
4682 // eat a matched-delimiter token tree:
4683 let delim = self.expect_open_delim();
4684 let tts = self.parse_seq_to_end(&token::CloseDelim(delim),
4686 |p| p.parse_token_tree());
4687 let m_ = ast::MacInvocTT(pth, tts, EMPTY_CTXT);
4688 let m: ast::Mac = codemap::Spanned { node: m_,
4689 span: mk_sp(self.span.lo,
4691 if delim != token::Brace {
4692 self.expect(&token::Semi)
4694 (ast::MethMac(m), self.span.hi, attrs)
4696 let unsafety = self.parse_unsafety();
4697 let abi = if self.eat_keyword(keywords::Extern) {
4698 self.parse_opt_abi().unwrap_or(abi::C)
4702 self.expect_keyword(keywords::Fn);
4703 let ident = self.parse_ident();
4704 let mut generics = self.parse_generics();
4705 let (explicit_self, decl) = self.parse_fn_decl_with_self(|p| {
4708 self.parse_where_clause(&mut generics);
4709 let (inner_attrs, body) = self.parse_inner_attrs_and_block();
4710 let body_span = body.span;
4711 let mut new_attrs = attrs;
4712 new_attrs.push_all(&inner_attrs[..]);
4713 (ast::MethDecl(ident,
4721 body_span.hi, new_attrs)
4726 id: ast::DUMMY_NODE_ID,
4727 span: mk_sp(lo, hi),
4732 /// Parse trait Foo { ... }
4733 fn parse_item_trait(&mut self, unsafety: Unsafety) -> ItemInfo {
4735 let ident = self.parse_ident();
4736 let mut tps = self.parse_generics();
4737 // This is not very accurate, but since unbound only exists to catch
4738 // obsolete syntax, the span is unlikely to ever be used.
4739 let unbound_span = self.span;
4740 let unbound = self.parse_for_sized();
4742 // Parse supertrait bounds.
4743 let mut bounds = self.parse_colon_then_ty_param_bounds(BoundParsingMode::Bare);
4745 if let Some(unbound) = unbound {
4746 let mut bounds_as_vec = bounds.into_vec();
4747 bounds_as_vec.push(TraitTyParamBound(PolyTraitRef { bound_lifetimes: vec![],
4749 span: unbound_span },
4750 TraitBoundModifier::Maybe));
4751 bounds = OwnedSlice::from_vec(bounds_as_vec);
4754 self.parse_where_clause(&mut tps);
4756 let meths = self.parse_trait_items();
4757 (ident, ItemTrait(unsafety, tps, bounds, meths), None)
4760 fn parse_impl_items(&mut self) -> (Vec<ImplItem>, Vec<Attribute>) {
4761 let mut impl_items = Vec::new();
4762 self.expect(&token::OpenDelim(token::Brace));
4763 let (inner_attrs, mut method_attrs) =
4764 self.parse_inner_attrs_and_next();
4766 method_attrs.extend(self.parse_outer_attributes().into_iter());
4767 if method_attrs.is_empty() && self.eat(&token::CloseDelim(token::Brace)) {
4771 let vis = self.parse_visibility();
4772 if self.eat_keyword(keywords::Type) {
4773 impl_items.push(TypeImplItem(P(self.parse_typedef(
4777 impl_items.push(MethodImplItem(self.parse_method(
4781 method_attrs = vec![];
4783 (impl_items, inner_attrs)
4786 /// Parses two variants (with the region/type params always optional):
4787 /// impl<T> Foo { ... }
4788 /// impl<T> ToString for ~[T] { ... }
4789 fn parse_item_impl(&mut self, unsafety: ast::Unsafety) -> ItemInfo {
4790 // First, parse type parameters if necessary.
4791 let mut generics = self.parse_generics();
4793 // Special case: if the next identifier that follows is '(', don't
4794 // allow this to be parsed as a trait.
4795 let could_be_trait = self.token != token::OpenDelim(token::Paren);
4797 let neg_span = self.span;
4798 let polarity = if self.eat(&token::Not) {
4799 ast::ImplPolarity::Negative
4801 ast::ImplPolarity::Positive
4805 let mut ty = self.parse_ty_sum();
4807 // Parse traits, if necessary.
4808 let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) {
4809 // New-style trait. Reinterpret the type as a trait.
4810 let opt_trait_ref = match ty.node {
4811 TyPath(ref path, node_id) => {
4813 path: (*path).clone(),
4818 self.span_err(ty.span, "not a trait");
4823 ty = self.parse_ty_sum();
4827 ast::ImplPolarity::Negative => {
4828 // This is a negated type implementation
4829 // `impl !MyType {}`, which is not allowed.
4830 self.span_err(neg_span, "inherent implementation can't be negated");
4837 self.parse_where_clause(&mut generics);
4838 let (impl_items, attrs) = self.parse_impl_items();
4840 let ident = ast_util::impl_pretty_name(&opt_trait, &*ty);
4843 ItemImpl(unsafety, polarity, generics, opt_trait, ty, impl_items),
4847 /// Parse a::B<String,i32>
4848 fn parse_trait_ref(&mut self) -> TraitRef {
4850 path: self.parse_path(LifetimeAndTypesWithoutColons),
4851 ref_id: ast::DUMMY_NODE_ID,
4855 fn parse_late_bound_lifetime_defs(&mut self) -> Vec<ast::LifetimeDef> {
4856 if self.eat_keyword(keywords::For) {
4857 self.expect(&token::Lt);
4858 let lifetime_defs = self.parse_lifetime_defs();
4866 /// Parse for<'l> a::B<String,i32>
4867 fn parse_poly_trait_ref(&mut self) -> PolyTraitRef {
4868 let lo = self.span.lo;
4869 let lifetime_defs = self.parse_late_bound_lifetime_defs();
4872 bound_lifetimes: lifetime_defs,
4873 trait_ref: self.parse_trait_ref(),
4874 span: mk_sp(lo, self.last_span.hi),
4878 /// Parse struct Foo { ... }
4879 fn parse_item_struct(&mut self) -> ItemInfo {
4880 let class_name = self.parse_ident();
4881 let mut generics = self.parse_generics();
4883 if self.eat(&token::Colon) {
4884 let ty = self.parse_ty_sum();
4885 self.span_err(ty.span, "`virtual` structs have been removed from the language");
4888 // There is a special case worth noting here, as reported in issue #17904.
4889 // If we are parsing a tuple struct it is the case that the where clause
4890 // should follow the field list. Like so:
4892 // struct Foo<T>(T) where T: Copy;
4894 // If we are parsing a normal record-style struct it is the case
4895 // that the where clause comes before the body, and after the generics.
4896 // So if we look ahead and see a brace or a where-clause we begin
4897 // parsing a record style struct.
4899 // Otherwise if we look ahead and see a paren we parse a tuple-style
4902 let (fields, ctor_id) = if self.token.is_keyword(keywords::Where) {
4903 self.parse_where_clause(&mut generics);
4904 if self.eat(&token::Semi) {
4905 // If we see a: `struct Foo<T> where T: Copy;` style decl.
4906 (Vec::new(), Some(ast::DUMMY_NODE_ID))
4908 // If we see: `struct Foo<T> where T: Copy { ... }`
4909 (self.parse_record_struct_body(&class_name), None)
4911 // No `where` so: `struct Foo<T>;`
4912 } else if self.eat(&token::Semi) {
4913 (Vec::new(), Some(ast::DUMMY_NODE_ID))
4914 // Record-style struct definition
4915 } else if self.token == token::OpenDelim(token::Brace) {
4916 let fields = self.parse_record_struct_body(&class_name);
4918 // Tuple-style struct definition with optional where-clause.
4920 let fields = self.parse_tuple_struct_body(&class_name, &mut generics);
4921 (fields, Some(ast::DUMMY_NODE_ID))
4925 ItemStruct(P(ast::StructDef {
4932 pub fn parse_record_struct_body(&mut self, class_name: &ast::Ident) -> Vec<StructField> {
4933 let mut fields = Vec::new();
4934 if self.eat(&token::OpenDelim(token::Brace)) {
4935 while self.token != token::CloseDelim(token::Brace) {
4936 fields.push(self.parse_struct_decl_field(true));
4939 if fields.len() == 0 {
4940 self.fatal(&format!("unit-like struct definition should be \
4941 written as `struct {};`",
4942 token::get_ident(class_name.clone())));
4947 let token_str = self.this_token_to_string();
4948 self.fatal(&format!("expected `where`, or `{}` after struct \
4949 name, found `{}`", "{",
4956 pub fn parse_tuple_struct_body(&mut self,
4957 class_name: &ast::Ident,
4958 generics: &mut ast::Generics)
4959 -> Vec<StructField> {
4960 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
4961 if self.check(&token::OpenDelim(token::Paren)) {
4962 let fields = self.parse_unspanned_seq(
4963 &token::OpenDelim(token::Paren),
4964 &token::CloseDelim(token::Paren),
4965 seq_sep_trailing_allowed(token::Comma),
4967 let attrs = p.parse_outer_attributes();
4969 let struct_field_ = ast::StructField_ {
4970 kind: UnnamedField(p.parse_visibility()),
4971 id: ast::DUMMY_NODE_ID,
4972 ty: p.parse_ty_sum(),
4975 spanned(lo, p.span.hi, struct_field_)
4978 if fields.len() == 0 {
4979 self.fatal(&format!("unit-like struct definition should be \
4980 written as `struct {};`",
4981 token::get_ident(class_name.clone())));
4984 self.parse_where_clause(generics);
4985 self.expect(&token::Semi);
4987 // This is the case where we just see struct Foo<T> where T: Copy;
4988 } else if self.token.is_keyword(keywords::Where) {
4989 self.parse_where_clause(generics);
4990 self.expect(&token::Semi);
4992 // This case is where we see: `struct Foo<T>;`
4994 let token_str = self.this_token_to_string();
4995 self.fatal(&format!("expected `where`, `{}`, `(`, or `;` after struct \
4996 name, found `{}`", "{", token_str));
5000 /// Parse a structure field declaration
5001 pub fn parse_single_struct_field(&mut self,
5003 attrs: Vec<Attribute> )
5005 let a_var = self.parse_name_and_ty(vis, attrs);
5010 token::CloseDelim(token::Brace) => {}
5012 let span = self.span;
5013 let token_str = self.this_token_to_string();
5014 self.span_fatal_help(span,
5015 &format!("expected `,`, or `}}`, found `{}`",
5017 "struct fields should be separated by commas")
5023 /// Parse an element of a struct definition
5024 fn parse_struct_decl_field(&mut self, allow_pub: bool) -> StructField {
5026 let attrs = self.parse_outer_attributes();
5028 if self.eat_keyword(keywords::Pub) {
5030 let span = self.last_span;
5031 self.span_err(span, "`pub` is not allowed here");
5033 return self.parse_single_struct_field(Public, attrs);
5036 return self.parse_single_struct_field(Inherited, attrs);
5039 /// Parse visibility: PUB, PRIV, or nothing
5040 fn parse_visibility(&mut self) -> Visibility {
5041 if self.eat_keyword(keywords::Pub) { Public }
5045 fn parse_for_sized(&mut self) -> Option<ast::TraitRef> {
5046 // FIXME, this should really use TraitBoundModifier, but it will get
5047 // re-jigged shortly in any case, so leaving the hacky version for now.
5048 if self.eat_keyword(keywords::For) {
5049 let span = self.span;
5051 let mut ate_question = false;
5052 if self.eat(&token::Question) {
5053 ate_question = true;
5055 let ident = self.parse_ident();
5056 if self.eat(&token::Question) {
5061 ate_question = true;
5065 "expected `?Sized` after `for` in trait item");
5068 let _tref = Parser::trait_ref_from_ident(ident, span);
5070 self.obsolete(span, ObsoleteSyntax::ForSized);
5078 /// Given a termination token and a vector of already-parsed
5079 /// attributes (of length 0 or 1), parse all of the items in a module
5080 fn parse_mod_items(&mut self,
5082 first_item_attrs: Vec<Attribute>,
5085 // Parse all of the items up to closing or an attribute.
5087 let mut attrs = first_item_attrs;
5088 attrs.push_all(&self.parse_outer_attributes());
5089 let mut items = vec![];
5092 match self.parse_item_(attrs, true) {
5093 Err(returned_attrs) => {
5094 attrs = returned_attrs;
5098 attrs = self.parse_outer_attributes();
5104 // don't think this other loop is even necessary....
5106 while self.token != term {
5107 let mut attrs = mem::replace(&mut attrs, vec![]);
5108 attrs.push_all(&self.parse_outer_attributes());
5109 debug!("parse_mod_items: parse_item_(attrs={:?})", attrs);
5110 match self.parse_item_(attrs, true /* macros allowed */) {
5111 Ok(item) => items.push(item),
5113 let token_str = self.this_token_to_string();
5114 self.fatal(&format!("expected item, found `{}`",
5120 if !attrs.is_empty() {
5121 // We parsed attributes for the first item but didn't find it
5122 let last_span = self.last_span;
5123 self.span_err(last_span,
5124 Parser::expected_item_err(&attrs[..]));
5128 inner: mk_sp(inner_lo, self.span.lo),
5133 fn parse_item_const(&mut self, m: Option<Mutability>) -> ItemInfo {
5134 let id = self.parse_ident();
5135 self.expect(&token::Colon);
5136 let ty = self.parse_ty_sum();
5137 self.expect(&token::Eq);
5138 let e = self.parse_expr();
5139 self.commit_expr_expecting(&*e, token::Semi);
5140 let item = match m {
5141 Some(m) => ItemStatic(ty, m, e),
5142 None => ItemConst(ty, e),
5147 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
5148 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> ItemInfo {
5149 let id_span = self.span;
5150 let id = self.parse_ident();
5151 if self.check(&token::Semi) {
5153 // This mod is in an external file. Let's go get it!
5154 let (m, attrs) = self.eval_src_mod(id, outer_attrs, id_span);
5155 (id, m, Some(attrs))
5157 self.push_mod_path(id, outer_attrs);
5158 self.expect(&token::OpenDelim(token::Brace));
5159 let mod_inner_lo = self.span.lo;
5160 let old_owns_directory = self.owns_directory;
5161 self.owns_directory = true;
5162 let (inner, next) = self.parse_inner_attrs_and_next();
5163 let m = self.parse_mod_items(token::CloseDelim(token::Brace), next, mod_inner_lo);
5164 self.expect(&token::CloseDelim(token::Brace));
5165 self.owns_directory = old_owns_directory;
5166 self.pop_mod_path();
5167 (id, ItemMod(m), Some(inner))
5171 fn push_mod_path(&mut self, id: Ident, attrs: &[Attribute]) {
5172 let default_path = self.id_to_interned_str(id);
5173 let file_path = match ::attr::first_attr_value_str_by_name(attrs,
5176 None => default_path,
5178 self.mod_path_stack.push(file_path)
5181 fn pop_mod_path(&mut self) {
5182 self.mod_path_stack.pop().unwrap();
5185 /// Read a module from a source file.
5186 fn eval_src_mod(&mut self,
5188 outer_attrs: &[ast::Attribute],
5190 -> (ast::Item_, Vec<ast::Attribute> ) {
5191 let mut prefix = Path::new(self.sess.span_diagnostic.cm.span_to_filename(self.span));
5193 let mod_path = Path::new(".").join_many(&self.mod_path_stack[]);
5194 let dir_path = prefix.join(&mod_path);
5195 let mod_string = token::get_ident(id);
5196 let (file_path, owns_directory) = match ::attr::first_attr_value_str_by_name(
5197 outer_attrs, "path") {
5198 Some(d) => (dir_path.join(d), true),
5200 let mod_name = mod_string.to_string();
5201 let default_path_str = format!("{}.rs", mod_name);
5202 let secondary_path_str = format!("{}/mod.rs", mod_name);
5203 let default_path = dir_path.join(&default_path_str[..]);
5204 let secondary_path = dir_path.join(&secondary_path_str[..]);
5205 let default_exists = default_path.exists();
5206 let secondary_exists = secondary_path.exists();
5208 if !self.owns_directory {
5209 self.span_err(id_sp,
5210 "cannot declare a new module at this location");
5211 let this_module = match self.mod_path_stack.last() {
5212 Some(name) => name.to_string(),
5213 None => self.root_module_name.as_ref().unwrap().clone(),
5215 self.span_note(id_sp,
5216 &format!("maybe move this module `{0}` \
5217 to its own directory via \
5220 if default_exists || secondary_exists {
5221 self.span_note(id_sp,
5222 &format!("... or maybe `use` the module \
5223 `{}` instead of possibly \
5227 self.abort_if_errors();
5230 match (default_exists, secondary_exists) {
5231 (true, false) => (default_path, false),
5232 (false, true) => (secondary_path, true),
5234 self.span_fatal_help(id_sp,
5235 &format!("file not found for module `{}`",
5237 &format!("name the file either {} or {} inside \
5238 the directory {:?}",
5241 dir_path.display()));
5244 self.span_fatal_help(
5246 &format!("file for module `{}` found at both {} \
5250 secondary_path_str),
5251 "delete or rename one of them to remove the ambiguity");
5257 self.eval_src_mod_from_path(file_path, owns_directory,
5258 mod_string.to_string(), id_sp)
5261 fn eval_src_mod_from_path(&mut self,
5263 owns_directory: bool,
5265 id_sp: Span) -> (ast::Item_, Vec<ast::Attribute> ) {
5266 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
5267 match included_mod_stack.iter().position(|p| *p == path) {
5269 let mut err = String::from_str("circular modules: ");
5270 let len = included_mod_stack.len();
5271 for p in &included_mod_stack[i.. len] {
5272 err.push_str(&p.display().as_cow());
5273 err.push_str(" -> ");
5275 err.push_str(&path.display().as_cow());
5276 self.span_fatal(id_sp, &err[..]);
5280 included_mod_stack.push(path.clone());
5281 drop(included_mod_stack);
5284 new_sub_parser_from_file(self.sess,
5290 let mod_inner_lo = p0.span.lo;
5291 let (mod_attrs, next) = p0.parse_inner_attrs_and_next();
5292 let first_item_outer_attrs = next;
5293 let m0 = p0.parse_mod_items(token::Eof, first_item_outer_attrs, mod_inner_lo);
5294 self.sess.included_mod_stack.borrow_mut().pop();
5295 return (ast::ItemMod(m0), mod_attrs);
5298 /// Parse a function declaration from a foreign module
5299 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility,
5300 attrs: Vec<Attribute>) -> P<ForeignItem> {
5301 let lo = self.span.lo;
5302 self.expect_keyword(keywords::Fn);
5304 let (ident, mut generics) = self.parse_fn_header();
5305 let decl = self.parse_fn_decl(true);
5306 self.parse_where_clause(&mut generics);
5307 let hi = self.span.hi;
5308 self.expect(&token::Semi);
5309 P(ast::ForeignItem {
5312 node: ForeignItemFn(decl, generics),
5313 id: ast::DUMMY_NODE_ID,
5314 span: mk_sp(lo, hi),
5319 /// Parse a static item from a foreign module
5320 fn parse_item_foreign_static(&mut self, vis: ast::Visibility,
5321 attrs: Vec<Attribute>) -> P<ForeignItem> {
5322 let lo = self.span.lo;
5324 self.expect_keyword(keywords::Static);
5325 let mutbl = self.eat_keyword(keywords::Mut);
5327 let ident = self.parse_ident();
5328 self.expect(&token::Colon);
5329 let ty = self.parse_ty_sum();
5330 let hi = self.span.hi;
5331 self.expect(&token::Semi);
5335 node: ForeignItemStatic(ty, mutbl),
5336 id: ast::DUMMY_NODE_ID,
5337 span: mk_sp(lo, hi),
5342 /// At this point, this is essentially a wrapper for
5343 /// parse_foreign_items.
5344 fn parse_foreign_mod_items(&mut self,
5346 first_item_attrs: Vec<Attribute>)
5348 let foreign_items = self.parse_foreign_items(first_item_attrs);
5349 assert!(self.token == token::CloseDelim(token::Brace));
5352 items: foreign_items
5356 /// Parse extern crate links
5360 /// extern crate url;
5361 /// extern crate foo = "bar"; //deprecated
5362 /// extern crate "bar" as foo;
5363 fn parse_item_extern_crate(&mut self,
5365 visibility: Visibility,
5366 attrs: Vec<Attribute>)
5369 let span = self.span;
5370 let (maybe_path, ident) = match self.token {
5371 token::Ident(..) => {
5372 let the_ident = self.parse_ident();
5373 let path = if self.eat_keyword_noexpect(keywords::As) {
5374 // skip the ident if there is one
5375 if self.token.is_ident() { self.bump(); }
5377 self.span_err(span, "expected `;`, found `as`");
5378 self.span_help(span,
5379 &format!("perhaps you meant to enclose the crate name `{}` in \
5381 the_ident.as_str()));
5386 self.expect(&token::Semi);
5389 token::Literal(token::Str_(..), suf) | token::Literal(token::StrRaw(..), suf) => {
5391 self.expect_no_suffix(sp, "extern crate name", suf);
5392 // forgo the internal suffix check of `parse_str` to
5393 // avoid repeats (this unwrap will always succeed due
5394 // to the restriction of the `match`)
5395 let (s, style, _) = self.parse_optional_str().unwrap();
5396 self.expect_keyword(keywords::As);
5397 let the_ident = self.parse_ident();
5398 self.expect(&token::Semi);
5399 (Some((s, style)), the_ident)
5402 let span = self.span;
5403 let token_str = self.this_token_to_string();
5404 self.span_fatal(span,
5405 &format!("expected extern crate name but \
5411 let last_span = self.last_span;
5415 ItemExternCrate(maybe_path),
5420 /// Parse `extern` for foreign ABIs
5423 /// `extern` is expected to have been
5424 /// consumed before calling this method
5430 fn parse_item_foreign_mod(&mut self,
5432 opt_abi: Option<abi::Abi>,
5433 visibility: Visibility,
5434 attrs: Vec<Attribute>)
5437 self.expect(&token::OpenDelim(token::Brace));
5439 let abi = opt_abi.unwrap_or(abi::C);
5441 let (inner, next) = self.parse_inner_attrs_and_next();
5442 let m = self.parse_foreign_mod_items(abi, next);
5443 self.expect(&token::CloseDelim(token::Brace));
5445 let last_span = self.last_span;
5448 special_idents::invalid,
5451 maybe_append(attrs, Some(inner)))
5454 /// Parse type Foo = Bar;
5455 fn parse_item_type(&mut self) -> ItemInfo {
5456 let ident = self.parse_ident();
5457 let mut tps = self.parse_generics();
5458 self.parse_where_clause(&mut tps);
5459 self.expect(&token::Eq);
5460 let ty = self.parse_ty_sum();
5461 self.expect(&token::Semi);
5462 (ident, ItemTy(ty, tps), None)
5465 /// Parse a structure-like enum variant definition
5466 /// this should probably be renamed or refactored...
5467 fn parse_struct_def(&mut self) -> P<StructDef> {
5468 let mut fields: Vec<StructField> = Vec::new();
5469 while self.token != token::CloseDelim(token::Brace) {
5470 fields.push(self.parse_struct_decl_field(false));
5480 /// Parse the part of an "enum" decl following the '{'
5481 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> EnumDef {
5482 let mut variants = Vec::new();
5483 let mut all_nullary = true;
5484 let mut any_disr = None;
5485 while self.token != token::CloseDelim(token::Brace) {
5486 let variant_attrs = self.parse_outer_attributes();
5487 let vlo = self.span.lo;
5489 let vis = self.parse_visibility();
5493 let mut args = Vec::new();
5494 let mut disr_expr = None;
5495 ident = self.parse_ident();
5496 if self.eat(&token::OpenDelim(token::Brace)) {
5497 // Parse a struct variant.
5498 all_nullary = false;
5499 let start_span = self.span;
5500 let struct_def = self.parse_struct_def();
5501 if struct_def.fields.len() == 0 {
5502 self.span_err(start_span,
5503 &format!("unit-like struct variant should be written \
5504 without braces, as `{},`",
5505 token::get_ident(ident)));
5507 kind = StructVariantKind(struct_def);
5508 } else if self.check(&token::OpenDelim(token::Paren)) {
5509 all_nullary = false;
5510 let arg_tys = self.parse_enum_variant_seq(
5511 &token::OpenDelim(token::Paren),
5512 &token::CloseDelim(token::Paren),
5513 seq_sep_trailing_allowed(token::Comma),
5514 |p| p.parse_ty_sum()
5517 args.push(ast::VariantArg {
5519 id: ast::DUMMY_NODE_ID,
5522 kind = TupleVariantKind(args);
5523 } else if self.eat(&token::Eq) {
5524 disr_expr = Some(self.parse_expr());
5525 any_disr = disr_expr.as_ref().map(|expr| expr.span);
5526 kind = TupleVariantKind(args);
5528 kind = TupleVariantKind(Vec::new());
5531 let vr = ast::Variant_ {
5533 attrs: variant_attrs,
5535 id: ast::DUMMY_NODE_ID,
5536 disr_expr: disr_expr,
5539 variants.push(P(spanned(vlo, self.last_span.hi, vr)));
5541 if !self.eat(&token::Comma) { break; }
5543 self.expect(&token::CloseDelim(token::Brace));
5545 Some(disr_span) if !all_nullary =>
5546 self.span_err(disr_span,
5547 "discriminator values can only be used with a c-like enum"),
5551 ast::EnumDef { variants: variants }
5554 /// Parse an "enum" declaration
5555 fn parse_item_enum(&mut self) -> ItemInfo {
5556 let id = self.parse_ident();
5557 let mut generics = self.parse_generics();
5558 self.parse_where_clause(&mut generics);
5559 self.expect(&token::OpenDelim(token::Brace));
5561 let enum_definition = self.parse_enum_def(&generics);
5562 (id, ItemEnum(enum_definition, generics), None)
5565 /// Parses a string as an ABI spec on an extern type or module. Consumes
5566 /// the `extern` keyword, if one is found.
5567 fn parse_opt_abi(&mut self) -> Option<abi::Abi> {
5569 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
5571 self.expect_no_suffix(sp, "ABI spec", suf);
5573 let the_string = s.as_str();
5574 match abi::lookup(the_string) {
5575 Some(abi) => Some(abi),
5577 let last_span = self.last_span;
5580 &format!("illegal ABI: expected one of [{}], \
5582 abi::all_names().connect(", "),
5593 /// Parse one of the items allowed by the flags; on failure,
5594 /// return `Err(remaining_attrs)`.
5595 /// NB: this function no longer parses the items inside an
5597 fn parse_item_(&mut self, attrs: Vec<Attribute>,
5598 macros_allowed: bool) -> MaybeItem {
5599 let nt_item = match self.token {
5600 token::Interpolated(token::NtItem(ref item)) => {
5601 Some((**item).clone())
5608 let mut attrs = attrs;
5609 mem::swap(&mut item.attrs, &mut attrs);
5610 item.attrs.extend(attrs.into_iter());
5616 let lo = self.span.lo;
5618 let visibility = self.parse_visibility();
5620 if self.eat_keyword(keywords::Use) {
5622 let item_ = ItemUse(self.parse_view_path());
5623 self.expect(&token::Semi);
5625 let last_span = self.last_span;
5626 let item = self.mk_item(lo,
5628 token::special_idents::invalid,
5635 if self.eat_keyword(keywords::Extern) {
5636 if self.eat_keyword(keywords::Crate) {
5637 return Ok(self.parse_item_extern_crate(lo, visibility, attrs));
5640 let opt_abi = self.parse_opt_abi();
5642 if self.eat_keyword(keywords::Fn) {
5643 // EXTERN FUNCTION ITEM
5644 let abi = opt_abi.unwrap_or(abi::C);
5645 let (ident, item_, extra_attrs) =
5646 self.parse_item_fn(Unsafety::Normal, abi);
5647 let last_span = self.last_span;
5648 let item = self.mk_item(lo,
5653 maybe_append(attrs, extra_attrs));
5655 } else if self.check(&token::OpenDelim(token::Brace)) {
5656 return Ok(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs));
5659 let span = self.span;
5660 let token_str = self.this_token_to_string();
5661 self.span_fatal(span,
5662 &format!("expected `{}` or `fn`, found `{}`", "{",
5666 if self.eat_keyword_noexpect(keywords::Virtual) {
5667 let span = self.span;
5668 self.span_err(span, "`virtual` structs have been removed from the language");
5671 if self.eat_keyword(keywords::Static) {
5673 let m = if self.eat_keyword(keywords::Mut) {MutMutable} else {MutImmutable};
5674 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m));
5675 let last_span = self.last_span;
5676 let item = self.mk_item(lo,
5681 maybe_append(attrs, extra_attrs));
5684 if self.eat_keyword(keywords::Const) {
5686 if self.eat_keyword(keywords::Mut) {
5687 let last_span = self.last_span;
5688 self.span_err(last_span, "const globals cannot be mutable");
5689 self.span_help(last_span, "did you mean to declare a static?");
5691 let (ident, item_, extra_attrs) = self.parse_item_const(None);
5692 let last_span = self.last_span;
5693 let item = self.mk_item(lo,
5698 maybe_append(attrs, extra_attrs));
5701 if self.check_keyword(keywords::Unsafe) &&
5702 self.look_ahead(1, |t| t.is_keyword(keywords::Trait))
5704 // UNSAFE TRAIT ITEM
5705 self.expect_keyword(keywords::Unsafe);
5706 self.expect_keyword(keywords::Trait);
5707 let (ident, item_, extra_attrs) =
5708 self.parse_item_trait(ast::Unsafety::Unsafe);
5709 let last_span = self.last_span;
5710 let item = self.mk_item(lo,
5715 maybe_append(attrs, extra_attrs));
5718 if self.check_keyword(keywords::Unsafe) &&
5719 self.look_ahead(1, |t| t.is_keyword(keywords::Impl))
5722 self.expect_keyword(keywords::Unsafe);
5723 self.expect_keyword(keywords::Impl);
5724 let (ident, item_, extra_attrs) = self.parse_item_impl(ast::Unsafety::Unsafe);
5725 let last_span = self.last_span;
5726 let item = self.mk_item(lo,
5731 maybe_append(attrs, extra_attrs));
5734 if self.check_keyword(keywords::Fn) {
5737 let (ident, item_, extra_attrs) =
5738 self.parse_item_fn(Unsafety::Normal, abi::Rust);
5739 let last_span = self.last_span;
5740 let item = self.mk_item(lo,
5745 maybe_append(attrs, extra_attrs));
5748 if self.check_keyword(keywords::Unsafe)
5749 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
5750 // UNSAFE FUNCTION ITEM
5752 let abi = if self.eat_keyword(keywords::Extern) {
5753 self.parse_opt_abi().unwrap_or(abi::C)
5757 self.expect_keyword(keywords::Fn);
5758 let (ident, item_, extra_attrs) =
5759 self.parse_item_fn(Unsafety::Unsafe, abi);
5760 let last_span = self.last_span;
5761 let item = self.mk_item(lo,
5766 maybe_append(attrs, extra_attrs));
5769 if self.eat_keyword(keywords::Mod) {
5771 let (ident, item_, extra_attrs) =
5772 self.parse_item_mod(&attrs[..]);
5773 let last_span = self.last_span;
5774 let item = self.mk_item(lo,
5779 maybe_append(attrs, extra_attrs));
5782 if self.eat_keyword(keywords::Type) {
5784 let (ident, item_, extra_attrs) = self.parse_item_type();
5785 let last_span = self.last_span;
5786 let item = self.mk_item(lo,
5791 maybe_append(attrs, extra_attrs));
5794 if self.eat_keyword(keywords::Enum) {
5796 let (ident, item_, extra_attrs) = self.parse_item_enum();
5797 let last_span = self.last_span;
5798 let item = self.mk_item(lo,
5803 maybe_append(attrs, extra_attrs));
5806 if self.eat_keyword(keywords::Trait) {
5808 let (ident, item_, extra_attrs) =
5809 self.parse_item_trait(ast::Unsafety::Normal);
5810 let last_span = self.last_span;
5811 let item = self.mk_item(lo,
5816 maybe_append(attrs, extra_attrs));
5819 if self.eat_keyword(keywords::Impl) {
5821 let (ident, item_, extra_attrs) = self.parse_item_impl(ast::Unsafety::Normal);
5822 let last_span = self.last_span;
5823 let item = self.mk_item(lo,
5828 maybe_append(attrs, extra_attrs));
5831 if self.eat_keyword(keywords::Struct) {
5833 let (ident, item_, extra_attrs) = self.parse_item_struct();
5834 let last_span = self.last_span;
5835 let item = self.mk_item(lo,
5840 maybe_append(attrs, extra_attrs));
5843 self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility)
5846 /// Parse a foreign item; on failure, return `Err(remaining_attrs)`.
5847 fn parse_foreign_item(&mut self, attrs: Vec<Attribute>)
5848 -> Result<P<ForeignItem>, Vec<Attribute>> {
5849 let lo = self.span.lo;
5851 let visibility = self.parse_visibility();
5853 if self.check_keyword(keywords::Static) {
5854 // FOREIGN STATIC ITEM
5855 return Ok(self.parse_item_foreign_static(visibility, attrs));
5857 if self.check_keyword(keywords::Fn) || self.check_keyword(keywords::Unsafe) {
5858 // FOREIGN FUNCTION ITEM
5859 return Ok(self.parse_item_foreign_fn(visibility, attrs));
5862 // FIXME #5668: this will occur for a macro invocation:
5863 let item = try!(self.parse_macro_use_or_failure(attrs, true, lo, visibility));
5864 self.span_fatal(item.span, "macros cannot expand to foreign items");
5867 /// This is the fall-through for parsing items.
5868 fn parse_macro_use_or_failure(
5870 attrs: Vec<Attribute> ,
5871 macros_allowed: bool,
5873 visibility: Visibility
5875 if macros_allowed && !self.token.is_any_keyword()
5876 && self.look_ahead(1, |t| *t == token::Not)
5877 && (self.look_ahead(2, |t| t.is_plain_ident())
5878 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren))
5879 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) {
5880 // MACRO INVOCATION ITEM
5882 let last_span = self.last_span;
5883 self.complain_if_pub_macro(visibility, last_span);
5886 let pth = self.parse_path(NoTypesAllowed);
5887 self.expect(&token::Not);
5889 // a 'special' identifier (like what `macro_rules!` uses)
5890 // is optional. We should eventually unify invoc syntax
5892 let id = if self.token.is_plain_ident() {
5895 token::special_idents::invalid // no special identifier
5897 // eat a matched-delimiter token tree:
5898 let delim = self.expect_open_delim();
5899 let tts = self.parse_seq_to_end(&token::CloseDelim(delim),
5901 |p| p.parse_token_tree());
5902 // single-variant-enum... :
5903 let m = ast::MacInvocTT(pth, tts, EMPTY_CTXT);
5904 let m: ast::Mac = codemap::Spanned { node: m,
5905 span: mk_sp(self.span.lo,
5908 if delim != token::Brace {
5909 if !self.eat(&token::Semi) {
5910 let last_span = self.last_span;
5911 self.span_err(last_span,
5912 "macros that expand to items must either \
5913 be surrounded with braces or followed by \
5918 let item_ = ItemMac(m);
5919 let last_span = self.last_span;
5920 let item = self.mk_item(lo,
5929 // FAILURE TO PARSE ITEM
5933 let last_span = self.last_span;
5934 self.span_fatal(last_span, "unmatched visibility `pub`");
5940 pub fn parse_item_with_outer_attributes(&mut self) -> Option<P<Item>> {
5941 let attrs = self.parse_outer_attributes();
5942 self.parse_item(attrs)
5945 pub fn parse_item(&mut self, attrs: Vec<Attribute>) -> Option<P<Item>> {
5946 self.parse_item_(attrs, true).ok()
5949 /// Matches view_path : MOD? non_global_path as IDENT
5950 /// | MOD? non_global_path MOD_SEP LBRACE RBRACE
5951 /// | MOD? non_global_path MOD_SEP LBRACE ident_seq RBRACE
5952 /// | MOD? non_global_path MOD_SEP STAR
5953 /// | MOD? non_global_path
5954 fn parse_view_path(&mut self) -> P<ViewPath> {
5955 let lo = self.span.lo;
5957 // Allow a leading :: because the paths are absolute either way.
5958 // This occurs with "use $crate::..." in macros.
5959 self.eat(&token::ModSep);
5961 if self.check(&token::OpenDelim(token::Brace)) {
5963 let idents = self.parse_unspanned_seq(
5964 &token::OpenDelim(token::Brace),
5965 &token::CloseDelim(token::Brace),
5966 seq_sep_trailing_allowed(token::Comma),
5967 |p| p.parse_path_list_item());
5968 let path = ast::Path {
5969 span: mk_sp(lo, self.span.hi),
5971 segments: Vec::new()
5973 return P(spanned(lo, self.span.hi, ViewPathList(path, idents)));
5976 let first_ident = self.parse_ident();
5977 let mut path = vec!(first_ident);
5978 if let token::ModSep = self.token {
5979 // foo::bar or foo::{a,b,c} or foo::*
5980 while self.check(&token::ModSep) {
5984 token::Ident(..) => {
5985 let ident = self.parse_ident();
5989 // foo::bar::{a,b,c}
5990 token::OpenDelim(token::Brace) => {
5991 let idents = self.parse_unspanned_seq(
5992 &token::OpenDelim(token::Brace),
5993 &token::CloseDelim(token::Brace),
5994 seq_sep_trailing_allowed(token::Comma),
5995 |p| p.parse_path_list_item()
5997 let path = ast::Path {
5998 span: mk_sp(lo, self.span.hi),
6000 segments: path.into_iter().map(|identifier| {
6002 identifier: identifier,
6003 parameters: ast::PathParameters::none(),
6007 return P(spanned(lo, self.span.hi, ViewPathList(path, idents)));
6011 token::BinOp(token::Star) => {
6013 let path = ast::Path {
6014 span: mk_sp(lo, self.span.hi),
6016 segments: path.into_iter().map(|identifier| {
6018 identifier: identifier,
6019 parameters: ast::PathParameters::none(),
6023 return P(spanned(lo, self.span.hi, ViewPathGlob(path)));
6026 // fall-through for case foo::bar::;
6028 self.span_err(self.span, "expected identifier or `{` or `*`, found `;`");
6035 let mut rename_to = path[path.len() - 1];
6036 let path = ast::Path {
6037 span: mk_sp(lo, self.last_span.hi),
6039 segments: path.into_iter().map(|identifier| {
6041 identifier: identifier,
6042 parameters: ast::PathParameters::none(),
6046 if self.eat_keyword(keywords::As) {
6047 rename_to = self.parse_ident()
6049 P(spanned(lo, self.last_span.hi, ViewPathSimple(rename_to, path)))
6052 /// Parses a sequence of foreign items. Stops when it finds program
6053 /// text that can't be parsed as an item
6054 fn parse_foreign_items(&mut self, first_item_attrs: Vec<Attribute>)
6055 -> Vec<P<ForeignItem>> {
6056 let mut attrs = first_item_attrs;
6057 attrs.push_all(&self.parse_outer_attributes());
6058 let mut foreign_items = Vec::new();
6060 match self.parse_foreign_item(attrs) {
6061 Ok(foreign_item) => {
6062 foreign_items.push(foreign_item);
6064 Err(returned_attrs) => {
6065 if self.check(&token::CloseDelim(token::Brace)) {
6066 attrs = returned_attrs;
6072 attrs = self.parse_outer_attributes();
6075 if !attrs.is_empty() {
6076 let last_span = self.last_span;
6077 self.span_err(last_span,
6078 Parser::expected_item_err(&attrs[..]));
6084 /// Parses a source module as a crate. This is the main
6085 /// entry point for the parser.
6086 pub fn parse_crate_mod(&mut self) -> Crate {
6087 let lo = self.span.lo;
6088 // parse the crate's inner attrs, maybe (oops) one
6089 // of the attrs of an item:
6090 let (inner, next) = self.parse_inner_attrs_and_next();
6091 let first_item_outer_attrs = next;
6092 // parse the items inside the crate:
6093 let m = self.parse_mod_items(token::Eof, first_item_outer_attrs, lo);
6098 config: self.cfg.clone(),
6099 span: mk_sp(lo, self.span.lo),
6100 exported_macros: Vec::new(),
6104 pub fn parse_optional_str(&mut self)
6105 -> Option<(InternedString, ast::StrStyle, Option<ast::Name>)> {
6106 let ret = match self.token {
6107 token::Literal(token::Str_(s), suf) => {
6108 (self.id_to_interned_str(s.ident()), ast::CookedStr, suf)
6110 token::Literal(token::StrRaw(s, n), suf) => {
6111 (self.id_to_interned_str(s.ident()), ast::RawStr(n), suf)
6119 pub fn parse_str(&mut self) -> (InternedString, StrStyle) {
6120 match self.parse_optional_str() {
6121 Some((s, style, suf)) => {
6122 let sp = self.last_span;
6123 self.expect_no_suffix(sp, "str literal", suf);
6126 _ => self.fatal("expected string literal")