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::*;
12 use self::ItemOrViewItem::*;
15 use ast::{AssociatedType, BareFnTy};
16 use ast::{RegionTyParamBound, TraitTyParamBound, TraitBoundModifier};
17 use ast::{ProvidedMethod, Public, Unsafety};
18 use ast::{Mod, BiAdd, Arg, Arm, Attribute, BindByRef, BindByValue};
19 use ast::{BiBitAnd, BiBitOr, BiBitXor, BiRem, BiLt, BiGt, Block};
20 use ast::{BlockCheckMode, CaptureByRef, CaptureByValue, CaptureClause};
21 use ast::{Crate, CrateConfig, Decl, DeclItem};
22 use ast::{DeclLocal, DefaultBlock, UnDeref, BiDiv, EMPTY_CTXT, EnumDef, ExplicitSelf};
23 use ast::{Expr, Expr_, ExprAddrOf, ExprMatch, ExprAgain};
24 use ast::{ExprAssign, ExprAssignOp, ExprBinary, ExprBlock, ExprBox};
25 use ast::{ExprBreak, ExprCall, ExprCast};
26 use ast::{ExprField, ExprTupField, ExprClosure, ExprIf, ExprIfLet, ExprIndex};
27 use ast::{ExprLit, ExprLoop, ExprMac, ExprRange};
28 use ast::{ExprMethodCall, ExprParen, ExprPath, ExprQPath};
29 use ast::{ExprRepeat, ExprRet, ExprStruct, ExprTup, ExprUnary};
30 use ast::{ExprVec, ExprWhile, ExprWhileLet, ExprForLoop, Field, FnDecl};
31 use ast::{FnUnboxedClosureKind, FnMutUnboxedClosureKind};
32 use ast::{FnOnceUnboxedClosureKind};
33 use ast::{ForeignItem, ForeignItemStatic, ForeignItemFn, ForeignMod, FunctionRetTy};
34 use ast::{Ident, Inherited, ImplItem, Item, Item_, ItemStatic};
35 use ast::{ItemEnum, ItemFn, ItemForeignMod, ItemImpl, ItemConst};
36 use ast::{ItemMac, ItemMod, ItemStruct, ItemTrait, ItemTy};
37 use ast::{LifetimeDef, Lit, Lit_};
38 use ast::{LitBool, LitChar, LitByte, LitBinary};
39 use ast::{LitStr, LitInt, Local, LocalLet};
40 use ast::{MacStmtWithBraces, MacStmtWithSemicolon, MacStmtWithoutBraces};
41 use ast::{MutImmutable, MutMutable, Mac_, MacInvocTT, MatchSource};
42 use ast::{Method, MutTy, BiMul, Mutability};
43 use ast::{MethodImplItem, NamedField, UnNeg, NoReturn, NodeId, UnNot};
44 use ast::{Pat, PatEnum, PatIdent, PatLit, PatRange, PatRegion, PatStruct};
45 use ast::{PatTup, PatBox, PatWild, PatWildMulti, PatWildSingle};
46 use ast::{PolyTraitRef};
47 use ast::{QPath, RequiredMethod};
48 use ast::{Return, BiShl, BiShr, Stmt, StmtDecl};
49 use ast::{StmtExpr, StmtSemi, StmtMac, StructDef, StructField};
50 use ast::{StructVariantKind, BiSub, StrStyle};
51 use ast::{SelfExplicit, SelfRegion, SelfStatic, SelfValue};
52 use ast::{Delimited, SequenceRepetition, TokenTree, TraitItem, TraitRef};
53 use ast::{TtDelimited, TtSequence, TtToken};
54 use ast::{TupleVariantKind, Ty, Ty_, TypeBinding};
55 use ast::{TyFixedLengthVec, TyBareFn};
56 use ast::{TyTypeof, TyInfer, TypeMethod};
57 use ast::{TyParam, TyParamBound, TyParen, TyPath, TyPolyTraitRef, TyPtr, TyQPath};
58 use ast::{TyRptr, TyTup, TyU32, TyVec, UnUniq};
59 use ast::{TypeImplItem, TypeTraitItem, Typedef, UnboxedClosureKind};
60 use ast::{UnnamedField, UnsafeBlock};
61 use ast::{ViewItem, ViewItem_, ViewItemExternCrate, ViewItemUse};
62 use ast::{ViewPath, ViewPathGlob, ViewPathList, ViewPathSimple};
63 use ast::{Visibility, WhereClause};
65 use ast_util::{self, as_prec, ident_to_path, operator_prec};
66 use codemap::{self, Span, BytePos, Spanned, spanned, mk_sp};
68 use ext::tt::macro_parser;
70 use parse::attr::ParserAttr;
72 use parse::common::{SeqSep, seq_sep_none, seq_sep_trailing_allowed};
73 use parse::lexer::{Reader, TokenAndSpan};
74 use parse::obsolete::{ParserObsoleteMethods, ObsoleteSyntax};
75 use parse::token::{self, MatchNt, SubstNt, SpecialVarNt, InternedString};
76 use parse::token::{keywords, special_idents, SpecialMacroVar};
77 use parse::{new_sub_parser_from_file, ParseSess};
80 use owned_slice::OwnedSlice;
82 use std::collections::HashSet;
83 use std::io::fs::PathExtensions;
91 flags Restrictions: u8 {
92 const UNRESTRICTED = 0b0000,
93 const RESTRICTION_STMT_EXPR = 0b0001,
94 const RESTRICTION_NO_BAR_OP = 0b0010,
95 const RESTRICTION_NO_STRUCT_LITERAL = 0b0100,
96 const RESTRICTION_NO_DOTS = 0b1000,
101 type ItemInfo = (Ident, Item_, Option<Vec<Attribute> >);
103 /// How to parse a path. There are four different kinds of paths, all of which
104 /// are parsed somewhat differently.
105 #[derive(Copy, PartialEq)]
106 pub enum PathParsingMode {
107 /// A path with no type parameters; e.g. `foo::bar::Baz`
109 /// A path with a lifetime and type parameters, with no double colons
110 /// before the type parameters; e.g. `foo::bar<'a>::Baz<T>`
111 LifetimeAndTypesWithoutColons,
112 /// A path with a lifetime and type parameters with double colons before
113 /// the type parameters; e.g. `foo::bar::<'a>::Baz::<T>`
114 LifetimeAndTypesWithColons,
117 /// How to parse a bound, whether to allow bound modifiers such as `?`.
118 #[derive(Copy, PartialEq)]
119 pub enum BoundParsingMode {
124 enum ItemOrViewItem {
125 /// Indicates a failure to parse any kind of item. The attributes are
127 IoviNone(Vec<Attribute>),
129 IoviForeignItem(P<ForeignItem>),
130 IoviViewItem(ViewItem)
134 /// Possibly accept an `token::Interpolated` expression (a pre-parsed expression
135 /// dropped into the token stream, which happens while parsing the result of
136 /// macro expansion). Placement of these is not as complex as I feared it would
137 /// be. The important thing is to make sure that lookahead doesn't balk at
138 /// `token::Interpolated` tokens.
139 macro_rules! maybe_whole_expr {
142 let found = match $p.token {
143 token::Interpolated(token::NtExpr(ref e)) => {
146 token::Interpolated(token::NtPath(_)) => {
147 // FIXME: The following avoids an issue with lexical borrowck scopes,
148 // but the clone is unfortunate.
149 let pt = match $p.token {
150 token::Interpolated(token::NtPath(ref pt)) => (**pt).clone(),
154 Some($p.mk_expr(span.lo, span.hi, ExprPath(pt)))
156 token::Interpolated(token::NtBlock(_)) => {
157 // FIXME: The following avoids an issue with lexical borrowck scopes,
158 // but the clone is unfortunate.
159 let b = match $p.token {
160 token::Interpolated(token::NtBlock(ref b)) => (*b).clone(),
164 Some($p.mk_expr(span.lo, span.hi, ExprBlock(b)))
179 /// As maybe_whole_expr, but for things other than expressions
180 macro_rules! maybe_whole {
181 ($p:expr, $constructor:ident) => (
183 let found = match ($p).token {
184 token::Interpolated(token::$constructor(_)) => {
185 Some(($p).bump_and_get())
189 if let Some(token::Interpolated(token::$constructor(x))) = found {
194 (no_clone $p:expr, $constructor:ident) => (
196 let found = match ($p).token {
197 token::Interpolated(token::$constructor(_)) => {
198 Some(($p).bump_and_get())
202 if let Some(token::Interpolated(token::$constructor(x))) = found {
207 (deref $p:expr, $constructor:ident) => (
209 let found = match ($p).token {
210 token::Interpolated(token::$constructor(_)) => {
211 Some(($p).bump_and_get())
215 if let Some(token::Interpolated(token::$constructor(x))) = found {
220 (Some $p:expr, $constructor:ident) => (
222 let found = match ($p).token {
223 token::Interpolated(token::$constructor(_)) => {
224 Some(($p).bump_and_get())
228 if let Some(token::Interpolated(token::$constructor(x))) = found {
229 return Some(x.clone());
233 (iovi $p:expr, $constructor:ident) => (
235 let found = match ($p).token {
236 token::Interpolated(token::$constructor(_)) => {
237 Some(($p).bump_and_get())
241 if let Some(token::Interpolated(token::$constructor(x))) = found {
242 return IoviItem(x.clone());
246 (pair_empty $p:expr, $constructor:ident) => (
248 let found = match ($p).token {
249 token::Interpolated(token::$constructor(_)) => {
250 Some(($p).bump_and_get())
254 if let Some(token::Interpolated(token::$constructor(x))) = found {
255 return (Vec::new(), x);
262 fn maybe_append(mut lhs: Vec<Attribute>, rhs: Option<Vec<Attribute>>)
265 Some(ref attrs) => lhs.extend(attrs.iter().map(|a| a.clone())),
272 struct ParsedItemsAndViewItems {
273 attrs_remaining: Vec<Attribute>,
274 view_items: Vec<ViewItem>,
275 items: Vec<P<Item>> ,
276 foreign_items: Vec<P<ForeignItem>>
279 /* ident is handled by common.rs */
281 pub struct Parser<'a> {
282 pub sess: &'a ParseSess,
283 /// the current token:
284 pub token: token::Token,
285 /// the span of the current token:
287 /// the span of the prior token:
289 pub cfg: CrateConfig,
290 /// the previous token or None (only stashed sometimes).
291 pub last_token: Option<Box<token::Token>>,
292 pub buffer: [TokenAndSpan; 4],
293 pub buffer_start: int,
295 pub tokens_consumed: uint,
296 pub restrictions: Restrictions,
297 pub quote_depth: uint, // not (yet) related to the quasiquoter
298 pub reader: Box<Reader+'a>,
299 pub interner: Rc<token::IdentInterner>,
300 /// The set of seen errors about obsolete syntax. Used to suppress
301 /// extra detail when the same error is seen twice
302 pub obsolete_set: HashSet<ObsoleteSyntax>,
303 /// Used to determine the path to externally loaded source files
304 pub mod_path_stack: Vec<InternedString>,
305 /// Stack of spans of open delimiters. Used for error message.
306 pub open_braces: Vec<Span>,
307 /// Flag if this parser "owns" the directory that it is currently parsing
308 /// in. This will affect how nested files are looked up.
309 pub owns_directory: bool,
310 /// Name of the root module this parser originated from. If `None`, then the
311 /// name is not known. This does not change while the parser is descending
312 /// into modules, and sub-parsers have new values for this name.
313 pub root_module_name: Option<String>,
314 pub expected_tokens: Vec<TokenType>,
317 #[derive(PartialEq, Eq, Clone)]
324 fn to_string(&self) -> String {
326 TokenType::Token(ref t) => format!("`{}`", Parser::token_to_string(t)),
327 TokenType::Operator => "an operator".to_string(),
332 fn is_plain_ident_or_underscore(t: &token::Token) -> bool {
333 t.is_plain_ident() || *t == token::Underscore
336 impl<'a> Parser<'a> {
337 pub fn new(sess: &'a ParseSess,
338 cfg: ast::CrateConfig,
339 mut rdr: Box<Reader+'a>)
342 let tok0 = rdr.real_token();
344 let placeholder = TokenAndSpan {
345 tok: token::Underscore,
351 interner: token::get_ident_interner(),
367 restrictions: UNRESTRICTED,
369 obsolete_set: HashSet::new(),
370 mod_path_stack: Vec::new(),
371 open_braces: Vec::new(),
372 owns_directory: true,
373 root_module_name: None,
374 expected_tokens: Vec::new(),
378 /// Convert a token to a string using self's reader
379 pub fn token_to_string(token: &token::Token) -> String {
380 pprust::token_to_string(token)
383 /// Convert the current token to a string using self's reader
384 pub fn this_token_to_string(&mut self) -> String {
385 Parser::token_to_string(&self.token)
388 pub fn unexpected_last(&mut self, t: &token::Token) -> ! {
389 let token_str = Parser::token_to_string(t);
390 let last_span = self.last_span;
391 self.span_fatal(last_span, &format!("unexpected token: `{}`",
395 pub fn unexpected(&mut self) -> ! {
396 let this_token = self.this_token_to_string();
397 self.fatal(&format!("unexpected token: `{}`", this_token)[]);
400 /// Expect and consume the token t. Signal an error if
401 /// the next token is not t.
402 pub fn expect(&mut self, t: &token::Token) {
403 if self.expected_tokens.is_empty() {
404 if self.token == *t {
407 let token_str = Parser::token_to_string(t);
408 let this_token_str = self.this_token_to_string();
409 self.fatal(&format!("expected `{}`, found `{}`",
414 self.expect_one_of(slice::ref_slice(t), &[]);
418 /// Expect next token to be edible or inedible token. If edible,
419 /// then consume it; if inedible, then return without consuming
420 /// anything. Signal a fatal error if next token is unexpected.
421 pub fn expect_one_of(&mut self,
422 edible: &[token::Token],
423 inedible: &[token::Token]) {
424 fn tokens_to_string(tokens: &[TokenType]) -> String {
425 let mut i = tokens.iter();
426 // This might be a sign we need a connect method on Iterator.
428 .map_or("".to_string(), |t| t.to_string());
429 i.enumerate().fold(b, |mut b, (i, ref a)| {
430 if tokens.len() > 2 && i == tokens.len() - 2 {
432 } else if tokens.len() == 2 && i == tokens.len() - 2 {
437 b.push_str(&*a.to_string());
441 if edible.contains(&self.token) {
443 } else if inedible.contains(&self.token) {
444 // leave it in the input
446 let mut expected = edible.iter().map(|x| TokenType::Token(x.clone()))
447 .collect::<Vec<_>>();
448 expected.extend(inedible.iter().map(|x| TokenType::Token(x.clone())));
449 expected.push_all(&*self.expected_tokens);
450 expected.sort_by(|a, b| a.to_string().cmp(&b.to_string()));
452 let expect = tokens_to_string(&expected[]);
453 let actual = self.this_token_to_string();
455 &(if expected.len() != 1 {
456 (format!("expected one of {}, found `{}`",
460 (format!("expected {}, found `{}`",
468 /// Check for erroneous `ident { }`; if matches, signal error and
469 /// recover (without consuming any expected input token). Returns
470 /// true if and only if input was consumed for recovery.
471 pub fn check_for_erroneous_unit_struct_expecting(&mut self, expected: &[token::Token]) -> bool {
472 if self.token == token::OpenDelim(token::Brace)
473 && expected.iter().all(|t| *t != token::OpenDelim(token::Brace))
474 && self.look_ahead(1, |t| *t == token::CloseDelim(token::Brace)) {
475 // matched; signal non-fatal error and recover.
476 let span = self.span;
478 "unit-like struct construction is written with no trailing `{ }`");
479 self.eat(&token::OpenDelim(token::Brace));
480 self.eat(&token::CloseDelim(token::Brace));
487 /// Commit to parsing a complete expression `e` expected to be
488 /// followed by some token from the set edible + inedible. Recover
489 /// from anticipated input errors, discarding erroneous characters.
490 pub fn commit_expr(&mut self, e: &Expr, edible: &[token::Token], inedible: &[token::Token]) {
491 debug!("commit_expr {:?}", e);
492 if let ExprPath(..) = e.node {
493 // might be unit-struct construction; check for recoverableinput error.
494 let mut expected = edible.iter().map(|x| x.clone()).collect::<Vec<_>>();
495 expected.push_all(inedible);
496 self.check_for_erroneous_unit_struct_expecting(&expected[]);
498 self.expect_one_of(edible, inedible)
501 pub fn commit_expr_expecting(&mut self, e: &Expr, edible: token::Token) {
502 self.commit_expr(e, &[edible], &[])
505 /// Commit to parsing a complete statement `s`, which expects to be
506 /// followed by some token from the set edible + inedible. Check
507 /// for recoverable input errors, discarding erroneous characters.
508 pub fn commit_stmt(&mut self, edible: &[token::Token], inedible: &[token::Token]) {
511 .map_or(false, |t| t.is_ident() || t.is_path()) {
512 let mut expected = edible.iter().map(|x| x.clone()).collect::<Vec<_>>();
513 expected.push_all(&inedible[]);
514 self.check_for_erroneous_unit_struct_expecting(
517 self.expect_one_of(edible, inedible)
520 pub fn commit_stmt_expecting(&mut self, edible: token::Token) {
521 self.commit_stmt(&[edible], &[])
524 pub fn parse_ident(&mut self) -> ast::Ident {
525 self.check_strict_keywords();
526 self.check_reserved_keywords();
528 token::Ident(i, _) => {
532 token::Interpolated(token::NtIdent(..)) => {
533 self.bug("ident interpolation not converted to real token");
536 let token_str = self.this_token_to_string();
537 self.fatal(&format!("expected ident, found `{}`",
543 pub fn parse_path_list_item(&mut self) -> ast::PathListItem {
544 let lo = self.span.lo;
545 let node = if self.eat_keyword(keywords::Mod) {
546 let span = self.last_span;
547 self.span_warn(span, "deprecated syntax; use the `self` keyword now");
548 ast::PathListMod { id: ast::DUMMY_NODE_ID }
549 } else if self.eat_keyword(keywords::Self) {
550 ast::PathListMod { id: ast::DUMMY_NODE_ID }
552 let ident = self.parse_ident();
553 ast::PathListIdent { name: ident, id: ast::DUMMY_NODE_ID }
555 let hi = self.last_span.hi;
556 spanned(lo, hi, node)
559 /// Check if the next token is `tok`, and return `true` if so.
561 /// This method is will automatically add `tok` to `expected_tokens` if `tok` is not
563 pub fn check(&mut self, tok: &token::Token) -> bool {
564 let is_present = self.token == *tok;
565 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
569 /// Consume token 'tok' if it exists. Returns true if the given
570 /// token was present, false otherwise.
571 pub fn eat(&mut self, tok: &token::Token) -> bool {
572 let is_present = self.check(tok);
573 if is_present { self.bump() }
577 /// If the next token is the given keyword, eat it and return
578 /// true. Otherwise, return false.
579 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
580 if self.token.is_keyword(kw) {
588 /// If the given word is not a keyword, signal an error.
589 /// If the next token is not the given word, signal an error.
590 /// Otherwise, eat it.
591 pub fn expect_keyword(&mut self, kw: keywords::Keyword) {
592 if !self.eat_keyword(kw) {
593 let id_interned_str = token::get_name(kw.to_name());
594 let token_str = self.this_token_to_string();
595 self.fatal(&format!("expected `{}`, found `{}`",
596 id_interned_str, token_str)[])
600 /// Signal an error if the given string is a strict keyword
601 pub fn check_strict_keywords(&mut self) {
602 if self.token.is_strict_keyword() {
603 let token_str = self.this_token_to_string();
604 let span = self.span;
606 &format!("expected identifier, found keyword `{}`",
611 /// Signal an error if the current token is a reserved keyword
612 pub fn check_reserved_keywords(&mut self) {
613 if self.token.is_reserved_keyword() {
614 let token_str = self.this_token_to_string();
615 self.fatal(&format!("`{}` is a reserved keyword",
620 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
621 /// `&` and continue. If an `&` is not seen, signal an error.
622 fn expect_and(&mut self) {
624 token::BinOp(token::And) => self.bump(),
626 let span = self.span;
627 let lo = span.lo + BytePos(1);
628 self.replace_token(token::BinOp(token::And), lo, span.hi)
631 let token_str = self.this_token_to_string();
633 Parser::token_to_string(&token::BinOp(token::And));
634 self.fatal(&format!("expected `{}`, found `{}`",
641 /// Expect and consume a `|`. If `||` is seen, replace it with a single
642 /// `|` and continue. If a `|` is not seen, signal an error.
643 fn expect_or(&mut self) {
645 token::BinOp(token::Or) => self.bump(),
647 let span = self.span;
648 let lo = span.lo + BytePos(1);
649 self.replace_token(token::BinOp(token::Or), lo, span.hi)
652 let found_token = self.this_token_to_string();
654 Parser::token_to_string(&token::BinOp(token::Or));
655 self.fatal(&format!("expected `{}`, found `{}`",
662 pub fn expect_no_suffix(&mut self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
664 None => {/* everything ok */}
666 let text = suf.as_str();
668 self.span_bug(sp, "found empty literal suffix in Some")
670 self.span_err(sp, &*format!("{} with a suffix is illegal", kind));
676 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
677 /// `<` and continue. If a `<` is not seen, return false.
679 /// This is meant to be used when parsing generics on a path to get the
681 fn eat_lt(&mut self) -> bool {
683 token::Lt => { self.bump(); true }
684 token::BinOp(token::Shl) => {
685 let span = self.span;
686 let lo = span.lo + BytePos(1);
687 self.replace_token(token::Lt, lo, span.hi);
694 fn expect_lt(&mut self) {
696 let found_token = self.this_token_to_string();
697 let token_str = Parser::token_to_string(&token::Lt);
698 self.fatal(&format!("expected `{}`, found `{}`",
704 /// Parse a sequence bracketed by `|` and `|`, stopping before the `|`.
705 fn parse_seq_to_before_or<T, F>(&mut self,
709 F: FnMut(&mut Parser) -> T,
711 let mut first = true;
712 let mut vector = Vec::new();
713 while self.token != token::BinOp(token::Or) &&
714 self.token != token::OrOr {
726 /// Expect and consume a GT. if a >> is seen, replace it
727 /// with a single > and continue. If a GT is not seen,
729 pub fn expect_gt(&mut self) {
731 token::Gt => self.bump(),
732 token::BinOp(token::Shr) => {
733 let span = self.span;
734 let lo = span.lo + BytePos(1);
735 self.replace_token(token::Gt, lo, span.hi)
737 token::BinOpEq(token::Shr) => {
738 let span = self.span;
739 let lo = span.lo + BytePos(1);
740 self.replace_token(token::Ge, lo, span.hi)
743 let span = self.span;
744 let lo = span.lo + BytePos(1);
745 self.replace_token(token::Eq, lo, span.hi)
748 let gt_str = Parser::token_to_string(&token::Gt);
749 let this_token_str = self.this_token_to_string();
750 self.fatal(&format!("expected `{}`, found `{}`",
757 pub fn parse_seq_to_before_gt_or_return<T, F>(&mut self,
758 sep: Option<token::Token>,
760 -> (OwnedSlice<T>, bool) where
761 F: FnMut(&mut Parser) -> Option<T>,
763 let mut v = Vec::new();
764 // This loop works by alternating back and forth between parsing types
765 // and commas. For example, given a string `A, B,>`, the parser would
766 // first parse `A`, then a comma, then `B`, then a comma. After that it
767 // would encounter a `>` and stop. This lets the parser handle trailing
768 // commas in generic parameters, because it can stop either after
769 // parsing a type or after parsing a comma.
770 for i in iter::count(0u, 1) {
771 if self.check(&token::Gt)
772 || self.token == token::BinOp(token::Shr)
773 || self.token == token::Ge
774 || self.token == token::BinOpEq(token::Shr) {
780 Some(result) => v.push(result),
781 None => return (OwnedSlice::from_vec(v), true)
784 sep.as_ref().map(|t| self.expect(t));
787 return (OwnedSlice::from_vec(v), false);
790 /// Parse a sequence bracketed by '<' and '>', stopping
792 pub fn parse_seq_to_before_gt<T, F>(&mut self,
793 sep: Option<token::Token>,
795 -> OwnedSlice<T> where
796 F: FnMut(&mut Parser) -> T,
798 let (result, returned) = self.parse_seq_to_before_gt_or_return(sep, |p| Some(f(p)));
803 pub fn parse_seq_to_gt<T, F>(&mut self,
804 sep: Option<token::Token>,
806 -> OwnedSlice<T> where
807 F: FnMut(&mut Parser) -> T,
809 let v = self.parse_seq_to_before_gt(sep, f);
814 pub fn parse_seq_to_gt_or_return<T, F>(&mut self,
815 sep: Option<token::Token>,
817 -> (OwnedSlice<T>, bool) where
818 F: FnMut(&mut Parser) -> Option<T>,
820 let (v, returned) = self.parse_seq_to_before_gt_or_return(sep, f);
824 return (v, returned);
827 /// Parse a sequence, including the closing delimiter. The function
828 /// f must consume tokens until reaching the next separator or
830 pub fn parse_seq_to_end<T, F>(&mut self,
835 F: FnMut(&mut Parser) -> T,
837 let val = self.parse_seq_to_before_end(ket, sep, f);
842 /// Parse a sequence, not including the closing delimiter. The function
843 /// f must consume tokens until reaching the next separator or
845 pub fn parse_seq_to_before_end<T, F>(&mut self,
850 F: FnMut(&mut Parser) -> T,
852 let mut first: bool = true;
854 while self.token != *ket {
857 if first { first = false; }
858 else { self.expect(t); }
862 if sep.trailing_sep_allowed && self.check(ket) { break; }
868 /// Parse a sequence, including the closing delimiter. The function
869 /// f must consume tokens until reaching the next separator or
871 pub fn parse_unspanned_seq<T, F>(&mut self,
877 F: FnMut(&mut Parser) -> T,
880 let result = self.parse_seq_to_before_end(ket, sep, f);
885 /// Parse a sequence parameter of enum variant. For consistency purposes,
886 /// these should not be empty.
887 pub fn parse_enum_variant_seq<T, F>(&mut self,
893 F: FnMut(&mut Parser) -> T,
895 let result = self.parse_unspanned_seq(bra, ket, sep, f);
896 if result.is_empty() {
897 let last_span = self.last_span;
898 self.span_err(last_span,
899 "nullary enum variants are written with no trailing `( )`");
904 // NB: Do not use this function unless you actually plan to place the
905 // spanned list in the AST.
906 pub fn parse_seq<T, F>(&mut self,
911 -> Spanned<Vec<T>> where
912 F: FnMut(&mut Parser) -> T,
914 let lo = self.span.lo;
916 let result = self.parse_seq_to_before_end(ket, sep, f);
917 let hi = self.span.hi;
919 spanned(lo, hi, result)
922 /// Advance the parser by one token
923 pub fn bump(&mut self) {
924 self.last_span = self.span;
925 // Stash token for error recovery (sometimes; clone is not necessarily cheap).
926 self.last_token = if self.token.is_ident() || self.token.is_path() {
927 Some(box self.token.clone())
931 let next = if self.buffer_start == self.buffer_end {
932 self.reader.real_token()
934 // Avoid token copies with `replace`.
935 let buffer_start = self.buffer_start as uint;
936 let next_index = (buffer_start + 1) & 3 as uint;
937 self.buffer_start = next_index as int;
939 let placeholder = TokenAndSpan {
940 tok: token::Underscore,
943 mem::replace(&mut self.buffer[buffer_start], placeholder)
946 self.token = next.tok;
947 self.tokens_consumed += 1u;
948 self.expected_tokens.clear();
949 // check after each token
950 self.check_unknown_macro_variable();
953 /// Advance the parser by one token and return the bumped token.
954 pub fn bump_and_get(&mut self) -> token::Token {
955 let old_token = mem::replace(&mut self.token, token::Underscore);
960 /// EFFECT: replace the current token and span with the given one
961 pub fn replace_token(&mut self,
965 self.last_span = mk_sp(self.span.lo, lo);
967 self.span = mk_sp(lo, hi);
969 pub fn buffer_length(&mut self) -> int {
970 if self.buffer_start <= self.buffer_end {
971 return self.buffer_end - self.buffer_start;
973 return (4 - self.buffer_start) + self.buffer_end;
975 pub fn look_ahead<R, F>(&mut self, distance: uint, f: F) -> R where
976 F: FnOnce(&token::Token) -> R,
978 let dist = distance as int;
979 while self.buffer_length() < dist {
980 self.buffer[self.buffer_end as uint] = self.reader.real_token();
981 self.buffer_end = (self.buffer_end + 1) & 3;
983 f(&self.buffer[((self.buffer_start + dist - 1) & 3) as uint].tok)
985 pub fn fatal(&mut self, m: &str) -> ! {
986 self.sess.span_diagnostic.span_fatal(self.span, m)
988 pub fn span_fatal(&mut self, sp: Span, m: &str) -> ! {
989 self.sess.span_diagnostic.span_fatal(sp, m)
991 pub fn span_fatal_help(&mut self, sp: Span, m: &str, help: &str) -> ! {
992 self.span_err(sp, m);
993 self.span_help(sp, help);
994 panic!(diagnostic::FatalError);
996 pub fn span_note(&mut self, sp: Span, m: &str) {
997 self.sess.span_diagnostic.span_note(sp, m)
999 pub fn span_help(&mut self, sp: Span, m: &str) {
1000 self.sess.span_diagnostic.span_help(sp, m)
1002 pub fn bug(&mut self, m: &str) -> ! {
1003 self.sess.span_diagnostic.span_bug(self.span, m)
1005 pub fn warn(&mut self, m: &str) {
1006 self.sess.span_diagnostic.span_warn(self.span, m)
1008 pub fn span_warn(&mut self, sp: Span, m: &str) {
1009 self.sess.span_diagnostic.span_warn(sp, m)
1011 pub fn span_err(&mut self, sp: Span, m: &str) {
1012 self.sess.span_diagnostic.span_err(sp, m)
1014 pub fn span_bug(&mut self, sp: Span, m: &str) -> ! {
1015 self.sess.span_diagnostic.span_bug(sp, m)
1017 pub fn abort_if_errors(&mut self) {
1018 self.sess.span_diagnostic.handler().abort_if_errors();
1021 pub fn id_to_interned_str(&mut self, id: Ident) -> InternedString {
1022 token::get_ident(id)
1025 /// Is the current token one of the keywords that signals a bare function
1027 pub fn token_is_bare_fn_keyword(&mut self) -> bool {
1028 self.token.is_keyword(keywords::Fn) ||
1029 self.token.is_keyword(keywords::Unsafe) ||
1030 self.token.is_keyword(keywords::Extern)
1033 /// Is the current token one of the keywords that signals a closure type?
1034 pub fn token_is_closure_keyword(&mut self) -> bool {
1035 self.token.is_keyword(keywords::Unsafe)
1038 pub fn get_lifetime(&mut self) -> ast::Ident {
1040 token::Lifetime(ref ident) => *ident,
1041 _ => self.bug("not a lifetime"),
1045 pub fn parse_for_in_type(&mut self) -> Ty_ {
1047 Parses whatever can come after a `for` keyword in a type.
1048 The `for` has already been consumed.
1052 - for <'lt> |S| -> T
1056 - for <'lt> [unsafe] [extern "ABI"] fn (S) -> T
1057 - for <'lt> path::foo(a, b)
1062 let lifetime_defs = self.parse_late_bound_lifetime_defs();
1064 // examine next token to decide to do
1065 if self.eat_keyword(keywords::Proc) {
1066 self.parse_proc_type(lifetime_defs)
1067 } else if self.token_is_bare_fn_keyword() || self.token_is_closure_keyword() {
1068 self.parse_ty_bare_fn_or_ty_closure(lifetime_defs)
1069 } else if self.check(&token::ModSep) ||
1070 self.token.is_ident() ||
1071 self.token.is_path()
1073 let trait_ref = self.parse_trait_ref();
1074 let poly_trait_ref = ast::PolyTraitRef { bound_lifetimes: lifetime_defs,
1075 trait_ref: trait_ref };
1076 let other_bounds = if self.eat(&token::BinOp(token::Plus)) {
1077 self.parse_ty_param_bounds(BoundParsingMode::Bare)
1082 Some(TraitTyParamBound(poly_trait_ref, TraitBoundModifier::None)).into_iter()
1083 .chain(other_bounds.into_vec().into_iter())
1085 ast::TyPolyTraitRef(all_bounds)
1087 self.parse_ty_closure(lifetime_defs)
1091 pub fn parse_ty_path(&mut self) -> Ty_ {
1092 let path = self.parse_path(LifetimeAndTypesWithoutColons);
1093 TyPath(path, ast::DUMMY_NODE_ID)
1096 /// parse a TyBareFn type:
1097 pub fn parse_ty_bare_fn(&mut self, lifetime_defs: Vec<ast::LifetimeDef>) -> Ty_ {
1100 [unsafe] [extern "ABI"] fn <'lt> (S) -> T
1101 ^~~~^ ^~~~^ ^~~~^ ^~^ ^
1104 | | | Argument types
1110 let unsafety = self.parse_unsafety();
1111 let abi = if self.eat_keyword(keywords::Extern) {
1112 self.parse_opt_abi().unwrap_or(abi::C)
1117 self.expect_keyword(keywords::Fn);
1118 let lifetime_defs = self.parse_legacy_lifetime_defs(lifetime_defs);
1119 let (inputs, variadic) = self.parse_fn_args(false, true);
1120 let ret_ty = self.parse_ret_ty();
1121 let decl = P(FnDecl {
1126 TyBareFn(P(BareFnTy {
1129 lifetimes: lifetime_defs,
1134 /// Parses a procedure type (`proc`). The initial `proc` keyword must
1135 /// already have been parsed.
1136 pub fn parse_proc_type(&mut self, lifetime_defs: Vec<ast::LifetimeDef>) -> Ty_ {
1139 proc <'lt> (S) [:Bounds] -> T
1140 ^~~^ ^~~~^ ^ ^~~~~~~~^ ^
1146 the `proc` keyword (already consumed)
1150 let proc_span = self.last_span;
1152 // To be helpful, parse the proc as ever
1153 let _ = self.parse_legacy_lifetime_defs(lifetime_defs);
1154 let _ = self.parse_fn_args(false, false);
1155 let _ = self.parse_colon_then_ty_param_bounds(BoundParsingMode::Bare);
1156 let _ = self.parse_ret_ty();
1158 self.obsolete(proc_span, ObsoleteSyntax::ProcType);
1163 /// Parses an optional unboxed closure kind (`&:`, `&mut:`, or `:`).
1164 pub fn parse_optional_unboxed_closure_kind(&mut self)
1165 -> Option<UnboxedClosureKind> {
1166 if self.check(&token::BinOp(token::And)) &&
1167 self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
1168 self.look_ahead(2, |t| *t == token::Colon) {
1172 return Some(FnMutUnboxedClosureKind)
1175 if self.token == token::BinOp(token::And) &&
1176 self.look_ahead(1, |t| *t == token::Colon) {
1179 return Some(FnUnboxedClosureKind)
1182 if self.eat(&token::Colon) {
1183 return Some(FnOnceUnboxedClosureKind)
1189 pub fn parse_ty_bare_fn_or_ty_closure(&mut self, lifetime_defs: Vec<LifetimeDef>) -> Ty_ {
1190 // Both bare fns and closures can begin with stuff like unsafe
1191 // and extern. So we just scan ahead a few tokens to see if we see
1194 // Closure: [unsafe] <'lt> |S| [:Bounds] -> T
1195 // Fn: [unsafe] [extern "ABI"] fn <'lt> (S) -> T
1197 if self.token.is_keyword(keywords::Fn) {
1198 self.parse_ty_bare_fn(lifetime_defs)
1199 } else if self.token.is_keyword(keywords::Extern) {
1200 self.parse_ty_bare_fn(lifetime_defs)
1201 } else if self.token.is_keyword(keywords::Unsafe) {
1202 if self.look_ahead(1, |t| t.is_keyword(keywords::Fn) ||
1203 t.is_keyword(keywords::Extern)) {
1204 self.parse_ty_bare_fn(lifetime_defs)
1206 self.parse_ty_closure(lifetime_defs)
1209 self.parse_ty_closure(lifetime_defs)
1213 /// Parse a TyClosure type
1214 pub fn parse_ty_closure(&mut self, lifetime_defs: Vec<ast::LifetimeDef>) -> Ty_ {
1217 [unsafe] <'lt> |S| [:Bounds] -> T
1218 ^~~~~~~^ ^~~~^ ^ ^~~~~~~~^ ^
1221 | | | Closure bounds
1223 | Deprecated lifetime defs
1229 let ty_closure_span = self.last_span;
1231 // To be helpful, parse the closure type as ever
1232 let _ = self.parse_unsafety();
1234 let _ = self.parse_legacy_lifetime_defs(lifetime_defs);
1236 if !self.eat(&token::OrOr) {
1239 let _ = self.parse_seq_to_before_or(
1241 |p| p.parse_arg_general(false));
1245 let _ = self.parse_colon_then_ty_param_bounds(BoundParsingMode::Bare);
1247 let _ = self.parse_ret_ty();
1249 self.obsolete(ty_closure_span, ObsoleteSyntax::ClosureType);
1254 pub fn parse_unsafety(&mut self) -> Unsafety {
1255 if self.eat_keyword(keywords::Unsafe) {
1256 return Unsafety::Unsafe;
1258 return Unsafety::Normal;
1262 /// Parses `[ 'for' '<' lifetime_defs '>' ]'
1263 fn parse_legacy_lifetime_defs(&mut self,
1264 lifetime_defs: Vec<ast::LifetimeDef>)
1265 -> Vec<ast::LifetimeDef>
1267 if self.token == token::Lt {
1269 if lifetime_defs.is_empty() {
1270 self.warn("deprecated syntax; use the `for` keyword now \
1271 (e.g. change `fn<'a>` to `for<'a> fn`)");
1272 let lifetime_defs = self.parse_lifetime_defs();
1276 self.fatal("cannot use new `for` keyword and older syntax together");
1283 /// Parses `type Foo;` in a trait declaration only. The `type` keyword has
1284 /// already been parsed.
1285 fn parse_associated_type(&mut self, attrs: Vec<Attribute>)
1288 let ty_param = self.parse_ty_param();
1289 self.expect(&token::Semi);
1296 /// Parses `type Foo = TYPE;` in an implementation declaration only. The
1297 /// `type` keyword has already been parsed.
1298 fn parse_typedef(&mut self, attrs: Vec<Attribute>, vis: Visibility)
1300 let lo = self.span.lo;
1301 let ident = self.parse_ident();
1302 self.expect(&token::Eq);
1303 let typ = self.parse_ty_sum();
1304 let hi = self.span.hi;
1305 self.expect(&token::Semi);
1307 id: ast::DUMMY_NODE_ID,
1308 span: mk_sp(lo, hi),
1316 /// Parse the items in a trait declaration
1317 pub fn parse_trait_items(&mut self) -> Vec<TraitItem> {
1318 self.parse_unspanned_seq(
1319 &token::OpenDelim(token::Brace),
1320 &token::CloseDelim(token::Brace),
1323 let attrs = p.parse_outer_attributes();
1325 if p.eat_keyword(keywords::Type) {
1326 TypeTraitItem(P(p.parse_associated_type(attrs)))
1330 let vis = p.parse_visibility();
1331 let style = p.parse_unsafety();
1332 let abi = if p.eat_keyword(keywords::Extern) {
1333 p.parse_opt_abi().unwrap_or(abi::C)
1337 p.expect_keyword(keywords::Fn);
1339 let ident = p.parse_ident();
1340 let mut generics = p.parse_generics();
1342 let (explicit_self, d) = p.parse_fn_decl_with_self(|p| {
1343 // This is somewhat dubious; We don't want to allow
1344 // argument names to be left off if there is a
1346 p.parse_arg_general(false)
1349 p.parse_where_clause(&mut generics);
1351 let hi = p.last_span.hi;
1355 debug!("parse_trait_methods(): parsing required method");
1356 RequiredMethod(TypeMethod {
1363 explicit_self: explicit_self,
1364 id: ast::DUMMY_NODE_ID,
1365 span: mk_sp(lo, hi),
1369 token::OpenDelim(token::Brace) => {
1370 debug!("parse_trait_methods(): parsing provided method");
1371 let (inner_attrs, body) =
1372 p.parse_inner_attrs_and_block();
1373 let mut attrs = attrs;
1374 attrs.push_all(&inner_attrs[]);
1375 ProvidedMethod(P(ast::Method {
1377 id: ast::DUMMY_NODE_ID,
1378 span: mk_sp(lo, hi),
1379 node: ast::MethDecl(ident,
1391 let token_str = p.this_token_to_string();
1392 p.fatal(&format!("expected `;` or `{{`, found `{}`",
1400 /// Parse a possibly mutable type
1401 pub fn parse_mt(&mut self) -> MutTy {
1402 let mutbl = self.parse_mutability();
1403 let t = self.parse_ty();
1404 MutTy { ty: t, mutbl: mutbl }
1407 /// Parse optional return type [ -> TY ] in function decl
1408 pub fn parse_ret_ty(&mut self) -> FunctionRetTy {
1409 if self.eat(&token::RArrow) {
1410 if self.eat(&token::Not) {
1413 let t = self.parse_ty();
1415 // We used to allow `fn foo() -> &T + U`, but don't
1416 // anymore. If we see it, report a useful error. This
1417 // only makes sense because `parse_ret_ty` is only
1418 // used in fn *declarations*, not fn types or where
1419 // clauses (i.e., not when parsing something like
1420 // `FnMut() -> T + Send`, where the `+` is legal).
1421 if self.token == token::BinOp(token::Plus) {
1422 self.warn("deprecated syntax: `()` are required, see RFC 438 for details");
1428 let pos = self.span.lo;
1430 id: ast::DUMMY_NODE_ID,
1431 node: TyTup(vec![]),
1432 span: mk_sp(pos, pos),
1437 /// Parse a type in a context where `T1+T2` is allowed.
1438 pub fn parse_ty_sum(&mut self) -> P<Ty> {
1439 let lo = self.span.lo;
1440 let lhs = self.parse_ty();
1442 if !self.eat(&token::BinOp(token::Plus)) {
1446 let bounds = self.parse_ty_param_bounds(BoundParsingMode::Bare);
1448 // In type grammar, `+` is treated like a binary operator,
1449 // and hence both L and R side are required.
1450 if bounds.len() == 0 {
1451 let last_span = self.last_span;
1452 self.span_err(last_span,
1453 "at least one type parameter bound \
1454 must be specified");
1457 let sp = mk_sp(lo, self.last_span.hi);
1458 let sum = ast::TyObjectSum(lhs, bounds);
1459 P(Ty {id: ast::DUMMY_NODE_ID, node: sum, span: sp})
1463 pub fn parse_ty(&mut self) -> P<Ty> {
1464 maybe_whole!(no_clone self, NtTy);
1466 let lo = self.span.lo;
1468 let t = if self.check(&token::OpenDelim(token::Paren)) {
1471 // (t) is a parenthesized ty
1472 // (t,) is the type of a tuple with only one field,
1474 let mut ts = vec![];
1475 let mut last_comma = false;
1476 while self.token != token::CloseDelim(token::Paren) {
1477 ts.push(self.parse_ty_sum());
1478 if self.check(&token::Comma) {
1487 self.expect(&token::CloseDelim(token::Paren));
1488 if ts.len() == 1 && !last_comma {
1489 TyParen(ts.into_iter().nth(0).unwrap())
1493 } else if self.check(&token::BinOp(token::Star)) {
1494 // STAR POINTER (bare pointer?)
1496 TyPtr(self.parse_ptr())
1497 } else if self.check(&token::OpenDelim(token::Bracket)) {
1499 self.expect(&token::OpenDelim(token::Bracket));
1500 let t = self.parse_ty_sum();
1502 // Parse the `; e` in `[ int; e ]`
1503 // where `e` is a const expression
1504 let t = match self.maybe_parse_fixed_length_of_vec() {
1506 Some(suffix) => TyFixedLengthVec(t, suffix)
1508 self.expect(&token::CloseDelim(token::Bracket));
1510 } else if self.check(&token::BinOp(token::And)) ||
1511 self.token == token::AndAnd {
1514 self.parse_borrowed_pointee()
1515 } else if self.token.is_keyword(keywords::For) {
1516 self.parse_for_in_type()
1517 } else if self.token_is_bare_fn_keyword() ||
1518 self.token_is_closure_keyword() {
1519 // BARE FUNCTION OR CLOSURE
1520 self.parse_ty_bare_fn_or_ty_closure(Vec::new())
1521 } else if self.check(&token::BinOp(token::Or)) ||
1522 self.token == token::OrOr ||
1523 (self.token == token::Lt &&
1524 self.look_ahead(1, |t| {
1525 *t == token::Gt || t.is_lifetime()
1528 self.parse_ty_closure(Vec::new())
1529 } else if self.eat_keyword(keywords::Typeof) {
1531 // In order to not be ambiguous, the type must be surrounded by parens.
1532 self.expect(&token::OpenDelim(token::Paren));
1533 let e = self.parse_expr();
1534 self.expect(&token::CloseDelim(token::Paren));
1536 } else if self.eat_keyword(keywords::Proc) {
1537 self.parse_proc_type(Vec::new())
1538 } else if self.eat_lt() {
1539 // QUALIFIED PATH `<TYPE as TRAIT_REF>::item`
1540 let self_type = self.parse_ty_sum();
1541 self.expect_keyword(keywords::As);
1542 let trait_ref = self.parse_trait_ref();
1543 self.expect(&token::Gt);
1544 self.expect(&token::ModSep);
1545 let item_name = self.parse_ident();
1547 self_type: self_type,
1548 trait_ref: P(trait_ref),
1549 item_path: ast::PathSegment {
1550 identifier: item_name,
1551 parameters: ast::PathParameters::none()
1554 } else if self.check(&token::ModSep) ||
1555 self.token.is_ident() ||
1556 self.token.is_path() {
1558 self.parse_ty_path()
1559 } else if self.eat(&token::Underscore) {
1560 // TYPE TO BE INFERRED
1563 let this_token_str = self.this_token_to_string();
1564 let msg = format!("expected type, found `{}`", this_token_str);
1568 let sp = mk_sp(lo, self.last_span.hi);
1569 P(Ty {id: ast::DUMMY_NODE_ID, node: t, span: sp})
1572 pub fn parse_borrowed_pointee(&mut self) -> Ty_ {
1573 // look for `&'lt` or `&'foo ` and interpret `foo` as the region name:
1574 let opt_lifetime = self.parse_opt_lifetime();
1576 let mt = self.parse_mt();
1577 return TyRptr(opt_lifetime, mt);
1580 pub fn parse_ptr(&mut self) -> MutTy {
1581 let mutbl = if self.eat_keyword(keywords::Mut) {
1583 } else if self.eat_keyword(keywords::Const) {
1586 let span = self.last_span;
1588 "bare raw pointers are no longer allowed, you should \
1589 likely use `*mut T`, but otherwise `*T` is now \
1590 known as `*const T`");
1593 let t = self.parse_ty();
1594 MutTy { ty: t, mutbl: mutbl }
1597 pub fn is_named_argument(&mut self) -> bool {
1598 let offset = match self.token {
1599 token::BinOp(token::And) => 1,
1601 _ if self.token.is_keyword(keywords::Mut) => 1,
1605 debug!("parser is_named_argument offset:{}", offset);
1608 is_plain_ident_or_underscore(&self.token)
1609 && self.look_ahead(1, |t| *t == token::Colon)
1611 self.look_ahead(offset, |t| is_plain_ident_or_underscore(t))
1612 && self.look_ahead(offset + 1, |t| *t == token::Colon)
1616 /// This version of parse arg doesn't necessarily require
1617 /// identifier names.
1618 pub fn parse_arg_general(&mut self, require_name: bool) -> Arg {
1619 let pat = if require_name || self.is_named_argument() {
1620 debug!("parse_arg_general parse_pat (require_name:{})",
1622 let pat = self.parse_pat();
1624 self.expect(&token::Colon);
1627 debug!("parse_arg_general ident_to_pat");
1628 ast_util::ident_to_pat(ast::DUMMY_NODE_ID,
1630 special_idents::invalid)
1633 let t = self.parse_ty_sum();
1638 id: ast::DUMMY_NODE_ID,
1642 /// Parse a single function argument
1643 pub fn parse_arg(&mut self) -> Arg {
1644 self.parse_arg_general(true)
1647 /// Parse an argument in a lambda header e.g. |arg, arg|
1648 pub fn parse_fn_block_arg(&mut self) -> Arg {
1649 let pat = self.parse_pat();
1650 let t = if self.eat(&token::Colon) {
1654 id: ast::DUMMY_NODE_ID,
1656 span: mk_sp(self.span.lo, self.span.hi),
1662 id: ast::DUMMY_NODE_ID
1666 pub fn maybe_parse_fixed_length_of_vec(&mut self) -> Option<P<ast::Expr>> {
1667 if self.check(&token::Semi) {
1669 Some(self.parse_expr())
1675 /// Matches token_lit = LIT_INTEGER | ...
1676 pub fn lit_from_token(&mut self, tok: &token::Token) -> Lit_ {
1678 token::Interpolated(token::NtExpr(ref v)) => {
1680 ExprLit(ref lit) => { lit.node.clone() }
1681 _ => { self.unexpected_last(tok); }
1684 token::Literal(lit, suf) => {
1685 let (suffix_illegal, out) = match lit {
1686 token::Byte(i) => (true, LitByte(parse::byte_lit(i.as_str()).0)),
1687 token::Char(i) => (true, LitChar(parse::char_lit(i.as_str()).0)),
1689 // there are some valid suffixes for integer and
1690 // float literals, so all the handling is done
1692 token::Integer(s) => {
1693 (false, parse::integer_lit(s.as_str(),
1694 suf.as_ref().map(|s| s.as_str()),
1695 &self.sess.span_diagnostic,
1698 token::Float(s) => {
1699 (false, parse::float_lit(s.as_str(),
1700 suf.as_ref().map(|s| s.as_str()),
1701 &self.sess.span_diagnostic,
1707 LitStr(token::intern_and_get_ident(parse::str_lit(s.as_str()).as_slice()),
1710 token::StrRaw(s, n) => {
1713 token::intern_and_get_ident(&parse::raw_str_lit(s.as_str())[]),
1717 (true, LitBinary(parse::binary_lit(i.as_str()))),
1718 token::BinaryRaw(i, _) =>
1720 LitBinary(Rc::new(i.as_str().as_bytes().iter().map(|&x| x).collect()))),
1724 let sp = self.last_span;
1725 self.expect_no_suffix(sp, &*format!("{} literal", lit.short_name()), suf)
1730 _ => { self.unexpected_last(tok); }
1734 /// Matches lit = true | false | token_lit
1735 pub fn parse_lit(&mut self) -> Lit {
1736 let lo = self.span.lo;
1737 let lit = if self.eat_keyword(keywords::True) {
1739 } else if self.eat_keyword(keywords::False) {
1742 let token = self.bump_and_get();
1743 let lit = self.lit_from_token(&token);
1746 codemap::Spanned { node: lit, span: mk_sp(lo, self.last_span.hi) }
1749 /// matches '-' lit | lit
1750 pub fn parse_literal_maybe_minus(&mut self) -> P<Expr> {
1751 let minus_lo = self.span.lo;
1752 let minus_present = self.eat(&token::BinOp(token::Minus));
1754 let lo = self.span.lo;
1755 let literal = P(self.parse_lit());
1756 let hi = self.span.hi;
1757 let expr = self.mk_expr(lo, hi, ExprLit(literal));
1760 let minus_hi = self.span.hi;
1761 let unary = self.mk_unary(UnNeg, expr);
1762 self.mk_expr(minus_lo, minus_hi, unary)
1768 /// Parses a path and optional type parameter bounds, depending on the
1769 /// mode. The `mode` parameter determines whether lifetimes, types, and/or
1770 /// bounds are permitted and whether `::` must precede type parameter
1772 pub fn parse_path(&mut self, mode: PathParsingMode) -> ast::Path {
1773 // Check for a whole path...
1774 let found = match self.token {
1775 token::Interpolated(token::NtPath(_)) => Some(self.bump_and_get()),
1778 if let Some(token::Interpolated(token::NtPath(box path))) = found {
1782 let lo = self.span.lo;
1783 let is_global = self.eat(&token::ModSep);
1785 // Parse any number of segments and bound sets. A segment is an
1786 // identifier followed by an optional lifetime and a set of types.
1787 // A bound set is a set of type parameter bounds.
1788 let segments = match mode {
1789 LifetimeAndTypesWithoutColons => {
1790 self.parse_path_segments_without_colons()
1792 LifetimeAndTypesWithColons => {
1793 self.parse_path_segments_with_colons()
1796 self.parse_path_segments_without_types()
1800 // Assemble the span.
1801 let span = mk_sp(lo, self.last_span.hi);
1803 // Assemble the result.
1812 /// - `a::b<T,U>::c<V,W>`
1813 /// - `a::b<T,U>::c(V) -> W`
1814 /// - `a::b<T,U>::c(V)`
1815 pub fn parse_path_segments_without_colons(&mut self) -> Vec<ast::PathSegment> {
1816 let mut segments = Vec::new();
1818 // First, parse an identifier.
1819 let identifier = self.parse_ident();
1821 // Parse types, optionally.
1822 let parameters = if self.eat_lt() {
1823 let (lifetimes, types, bindings) = self.parse_generic_values_after_lt();
1825 ast::AngleBracketedParameters(ast::AngleBracketedParameterData {
1826 lifetimes: lifetimes,
1827 types: OwnedSlice::from_vec(types),
1828 bindings: OwnedSlice::from_vec(bindings),
1830 } else if self.eat(&token::OpenDelim(token::Paren)) {
1831 let inputs = self.parse_seq_to_end(
1832 &token::CloseDelim(token::Paren),
1833 seq_sep_trailing_allowed(token::Comma),
1834 |p| p.parse_ty_sum());
1836 let output_ty = if self.eat(&token::RArrow) {
1837 Some(self.parse_ty())
1842 ast::ParenthesizedParameters(ast::ParenthesizedParameterData {
1847 ast::PathParameters::none()
1850 // Assemble and push the result.
1851 segments.push(ast::PathSegment { identifier: identifier,
1852 parameters: parameters });
1854 // Continue only if we see a `::`
1855 if !self.eat(&token::ModSep) {
1862 /// - `a::b::<T,U>::c`
1863 pub fn parse_path_segments_with_colons(&mut self) -> Vec<ast::PathSegment> {
1864 let mut segments = Vec::new();
1866 // First, parse an identifier.
1867 let identifier = self.parse_ident();
1869 // If we do not see a `::`, stop.
1870 if !self.eat(&token::ModSep) {
1871 segments.push(ast::PathSegment {
1872 identifier: identifier,
1873 parameters: ast::PathParameters::none()
1878 // Check for a type segment.
1880 // Consumed `a::b::<`, go look for types
1881 let (lifetimes, types, bindings) = self.parse_generic_values_after_lt();
1882 segments.push(ast::PathSegment {
1883 identifier: identifier,
1884 parameters: ast::AngleBracketedParameters(ast::AngleBracketedParameterData {
1885 lifetimes: lifetimes,
1886 types: OwnedSlice::from_vec(types),
1887 bindings: OwnedSlice::from_vec(bindings),
1891 // Consumed `a::b::<T,U>`, check for `::` before proceeding
1892 if !self.eat(&token::ModSep) {
1896 // Consumed `a::`, go look for `b`
1897 segments.push(ast::PathSegment {
1898 identifier: identifier,
1899 parameters: ast::PathParameters::none(),
1908 pub fn parse_path_segments_without_types(&mut self) -> Vec<ast::PathSegment> {
1909 let mut segments = Vec::new();
1911 // First, parse an identifier.
1912 let identifier = self.parse_ident();
1914 // Assemble and push the result.
1915 segments.push(ast::PathSegment {
1916 identifier: identifier,
1917 parameters: ast::PathParameters::none()
1920 // If we do not see a `::`, stop.
1921 if !self.eat(&token::ModSep) {
1927 /// parses 0 or 1 lifetime
1928 pub fn parse_opt_lifetime(&mut self) -> Option<ast::Lifetime> {
1930 token::Lifetime(..) => {
1931 Some(self.parse_lifetime())
1939 /// Parses a single lifetime
1940 /// Matches lifetime = LIFETIME
1941 pub fn parse_lifetime(&mut self) -> ast::Lifetime {
1943 token::Lifetime(i) => {
1944 let span = self.span;
1946 return ast::Lifetime {
1947 id: ast::DUMMY_NODE_ID,
1953 self.fatal(&format!("expected a lifetime name")[]);
1958 /// Parses `lifetime_defs = [ lifetime_defs { ',' lifetime_defs } ]` where `lifetime_def =
1959 /// lifetime [':' lifetimes]`
1960 pub fn parse_lifetime_defs(&mut self) -> Vec<ast::LifetimeDef> {
1962 let mut res = Vec::new();
1965 token::Lifetime(_) => {
1966 let lifetime = self.parse_lifetime();
1968 if self.eat(&token::Colon) {
1969 self.parse_lifetimes(token::BinOp(token::Plus))
1973 res.push(ast::LifetimeDef { lifetime: lifetime,
1983 token::Comma => { self.bump(); }
1984 token::Gt => { return res; }
1985 token::BinOp(token::Shr) => { return res; }
1987 let this_token_str = self.this_token_to_string();
1988 let msg = format!("expected `,` or `>` after lifetime \
1997 /// matches lifetimes = ( lifetime ) | ( lifetime , lifetimes ) actually, it matches the empty
1998 /// one too, but putting that in there messes up the grammar....
2000 /// Parses zero or more comma separated lifetimes. Expects each lifetime to be followed by
2001 /// either a comma or `>`. Used when parsing type parameter lists, where we expect something
2002 /// like `<'a, 'b, T>`.
2003 pub fn parse_lifetimes(&mut self, sep: token::Token) -> Vec<ast::Lifetime> {
2005 let mut res = Vec::new();
2008 token::Lifetime(_) => {
2009 res.push(self.parse_lifetime());
2016 if self.token != sep {
2024 /// Parse mutability declaration (mut/const/imm)
2025 pub fn parse_mutability(&mut self) -> Mutability {
2026 if self.eat_keyword(keywords::Mut) {
2033 /// Parse ident COLON expr
2034 pub fn parse_field(&mut self) -> Field {
2035 let lo = self.span.lo;
2036 let i = self.parse_ident();
2037 let hi = self.last_span.hi;
2038 self.expect(&token::Colon);
2039 let e = self.parse_expr();
2041 ident: spanned(lo, hi, i),
2042 span: mk_sp(lo, e.span.hi),
2047 pub fn mk_expr(&mut self, lo: BytePos, hi: BytePos, node: Expr_) -> P<Expr> {
2049 id: ast::DUMMY_NODE_ID,
2051 span: mk_sp(lo, hi),
2055 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::Expr_ {
2056 ExprUnary(unop, expr)
2059 pub fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::Expr_ {
2060 ExprBinary(binop, lhs, rhs)
2063 pub fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::Expr_ {
2067 fn mk_method_call(&mut self,
2068 ident: ast::SpannedIdent,
2072 ExprMethodCall(ident, tps, args)
2075 pub fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::Expr_ {
2076 ExprIndex(expr, idx)
2079 pub fn mk_range(&mut self,
2080 start: Option<P<Expr>>,
2081 end: Option<P<Expr>>)
2083 ExprRange(start, end)
2086 pub fn mk_field(&mut self, expr: P<Expr>, ident: ast::SpannedIdent) -> ast::Expr_ {
2087 ExprField(expr, ident)
2090 pub fn mk_tup_field(&mut self, expr: P<Expr>, idx: codemap::Spanned<uint>) -> ast::Expr_ {
2091 ExprTupField(expr, idx)
2094 pub fn mk_assign_op(&mut self, binop: ast::BinOp,
2095 lhs: P<Expr>, rhs: P<Expr>) -> ast::Expr_ {
2096 ExprAssignOp(binop, lhs, rhs)
2099 pub fn mk_mac_expr(&mut self, lo: BytePos, hi: BytePos, m: Mac_) -> P<Expr> {
2101 id: ast::DUMMY_NODE_ID,
2102 node: ExprMac(codemap::Spanned {node: m, span: mk_sp(lo, hi)}),
2103 span: mk_sp(lo, hi),
2107 pub fn mk_lit_u32(&mut self, i: u32) -> P<Expr> {
2108 let span = &self.span;
2109 let lv_lit = P(codemap::Spanned {
2110 node: LitInt(i as u64, ast::UnsignedIntLit(TyU32)),
2115 id: ast::DUMMY_NODE_ID,
2116 node: ExprLit(lv_lit),
2121 fn expect_open_delim(&mut self) -> token::DelimToken {
2123 token::OpenDelim(delim) => {
2127 _ => self.fatal("expected open delimiter"),
2131 /// At the bottom (top?) of the precedence hierarchy,
2132 /// parse things like parenthesized exprs,
2133 /// macros, return, etc.
2134 pub fn parse_bottom_expr(&mut self) -> P<Expr> {
2135 maybe_whole_expr!(self);
2137 let lo = self.span.lo;
2138 let mut hi = self.span.hi;
2142 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2144 token::OpenDelim(token::Paren) => {
2147 // (e) is parenthesized e
2148 // (e,) is a tuple with only one field, e
2149 let mut es = vec![];
2150 let mut trailing_comma = false;
2151 while self.token != token::CloseDelim(token::Paren) {
2152 es.push(self.parse_expr());
2153 self.commit_expr(&**es.last().unwrap(), &[],
2154 &[token::Comma, token::CloseDelim(token::Paren)]);
2155 if self.check(&token::Comma) {
2156 trailing_comma = true;
2160 trailing_comma = false;
2167 return if es.len() == 1 && !trailing_comma {
2168 self.mk_expr(lo, hi, ExprParen(es.into_iter().nth(0).unwrap()))
2170 self.mk_expr(lo, hi, ExprTup(es))
2173 token::OpenDelim(token::Brace) => {
2175 let blk = self.parse_block_tail(lo, DefaultBlock);
2176 return self.mk_expr(blk.span.lo, blk.span.hi,
2179 token::BinOp(token::Or) | token::OrOr => {
2180 return self.parse_lambda_expr(CaptureByRef);
2182 // FIXME #13626: Should be able to stick in
2183 // token::SELF_KEYWORD_NAME
2184 token::Ident(id @ ast::Ident {
2185 name: ast::Name(token::SELF_KEYWORD_NAME_NUM),
2187 }, token::Plain) => {
2189 let path = ast_util::ident_to_path(mk_sp(lo, hi), id);
2190 ex = ExprPath(path);
2191 hi = self.last_span.hi;
2193 token::OpenDelim(token::Bracket) => {
2196 if self.check(&token::CloseDelim(token::Bracket)) {
2199 ex = ExprVec(Vec::new());
2202 let first_expr = self.parse_expr();
2203 if self.check(&token::Semi) {
2204 // Repeating vector syntax: [ 0; 512 ]
2206 let count = self.parse_expr();
2207 self.expect(&token::CloseDelim(token::Bracket));
2208 ex = ExprRepeat(first_expr, count);
2209 } else if self.check(&token::Comma) {
2210 // Vector with two or more elements.
2212 let remaining_exprs = self.parse_seq_to_end(
2213 &token::CloseDelim(token::Bracket),
2214 seq_sep_trailing_allowed(token::Comma),
2217 let mut exprs = vec!(first_expr);
2218 exprs.extend(remaining_exprs.into_iter());
2219 ex = ExprVec(exprs);
2221 // Vector with one element.
2222 self.expect(&token::CloseDelim(token::Bracket));
2223 ex = ExprVec(vec!(first_expr));
2226 hi = self.last_span.hi;
2230 // QUALIFIED PATH `<TYPE as TRAIT_REF>::item::<'a, T>`
2231 let self_type = self.parse_ty_sum();
2232 self.expect_keyword(keywords::As);
2233 let trait_ref = self.parse_trait_ref();
2234 self.expect(&token::Gt);
2235 self.expect(&token::ModSep);
2236 let item_name = self.parse_ident();
2237 let parameters = if self.eat(&token::ModSep) {
2239 // Consumed `item::<`, go look for types
2240 let (lifetimes, types, bindings) =
2241 self.parse_generic_values_after_lt();
2242 ast::AngleBracketedParameters(ast::AngleBracketedParameterData {
2243 lifetimes: lifetimes,
2244 types: OwnedSlice::from_vec(types),
2245 bindings: OwnedSlice::from_vec(bindings),
2248 ast::PathParameters::none()
2250 let hi = self.span.hi;
2251 return self.mk_expr(lo, hi, ExprQPath(P(QPath {
2252 self_type: self_type,
2253 trait_ref: P(trait_ref),
2254 item_path: ast::PathSegment {
2255 identifier: item_name,
2256 parameters: parameters
2260 if self.eat_keyword(keywords::Move) {
2261 return self.parse_lambda_expr(CaptureByValue);
2263 if self.eat_keyword(keywords::Proc) {
2264 let span = self.last_span;
2265 let _ = self.parse_proc_decl();
2266 let _ = self.parse_expr();
2267 return self.obsolete_expr(span, ObsoleteSyntax::ProcExpr);
2269 if self.eat_keyword(keywords::If) {
2270 return self.parse_if_expr();
2272 if self.eat_keyword(keywords::For) {
2273 return self.parse_for_expr(None);
2275 if self.eat_keyword(keywords::While) {
2276 return self.parse_while_expr(None);
2278 if self.token.is_lifetime() {
2279 let lifetime = self.get_lifetime();
2281 self.expect(&token::Colon);
2282 if self.eat_keyword(keywords::While) {
2283 return self.parse_while_expr(Some(lifetime))
2285 if self.eat_keyword(keywords::For) {
2286 return self.parse_for_expr(Some(lifetime))
2288 if self.eat_keyword(keywords::Loop) {
2289 return self.parse_loop_expr(Some(lifetime))
2291 self.fatal("expected `while`, `for`, or `loop` after a label")
2293 if self.eat_keyword(keywords::Loop) {
2294 return self.parse_loop_expr(None);
2296 if self.eat_keyword(keywords::Continue) {
2297 let lo = self.span.lo;
2298 let ex = if self.token.is_lifetime() {
2299 let lifetime = self.get_lifetime();
2301 ExprAgain(Some(lifetime))
2305 let hi = self.span.hi;
2306 return self.mk_expr(lo, hi, ex);
2308 if self.eat_keyword(keywords::Match) {
2309 return self.parse_match_expr();
2311 if self.eat_keyword(keywords::Unsafe) {
2312 return self.parse_block_expr(
2314 UnsafeBlock(ast::UserProvided));
2316 if self.eat_keyword(keywords::Return) {
2317 // RETURN expression
2318 if self.token.can_begin_expr() {
2319 let e = self.parse_expr();
2321 ex = ExprRet(Some(e));
2325 } else if self.eat_keyword(keywords::Break) {
2327 if self.token.is_lifetime() {
2328 let lifetime = self.get_lifetime();
2330 ex = ExprBreak(Some(lifetime));
2332 ex = ExprBreak(None);
2335 } else if self.check(&token::ModSep) ||
2336 self.token.is_ident() &&
2337 !self.token.is_keyword(keywords::True) &&
2338 !self.token.is_keyword(keywords::False) {
2340 self.parse_path(LifetimeAndTypesWithColons);
2342 // `!`, as an operator, is prefix, so we know this isn't that
2343 if self.check(&token::Not) {
2344 // MACRO INVOCATION expression
2347 let delim = self.expect_open_delim();
2348 let tts = self.parse_seq_to_end(
2349 &token::CloseDelim(delim),
2351 |p| p.parse_token_tree());
2352 let hi = self.span.hi;
2354 return self.mk_mac_expr(lo,
2360 if self.check(&token::OpenDelim(token::Brace)) {
2361 // This is a struct literal, unless we're prohibited
2362 // from parsing struct literals here.
2363 if !self.restrictions.contains(RESTRICTION_NO_STRUCT_LITERAL) {
2364 // It's a struct literal.
2366 let mut fields = Vec::new();
2367 let mut base = None;
2369 while self.token != token::CloseDelim(token::Brace) {
2370 if self.eat(&token::DotDot) {
2371 base = Some(self.parse_expr());
2375 fields.push(self.parse_field());
2376 self.commit_expr(&*fields.last().unwrap().expr,
2378 &[token::CloseDelim(token::Brace)]);
2381 if fields.len() == 0 && base.is_none() {
2382 let last_span = self.last_span;
2383 self.span_err(last_span,
2384 "structure literal must either \
2385 have at least one field or use \
2386 functional structure update \
2391 self.expect(&token::CloseDelim(token::Brace));
2392 ex = ExprStruct(pth, fields, base);
2393 return self.mk_expr(lo, hi, ex);
2400 // other literal expression
2401 let lit = self.parse_lit();
2403 ex = ExprLit(P(lit));
2408 return self.mk_expr(lo, hi, ex);
2411 /// Parse a block or unsafe block
2412 pub fn parse_block_expr(&mut self, lo: BytePos, blk_mode: BlockCheckMode)
2414 self.expect(&token::OpenDelim(token::Brace));
2415 let blk = self.parse_block_tail(lo, blk_mode);
2416 return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk));
2419 /// parse a.b or a(13) or a[4] or just a
2420 pub fn parse_dot_or_call_expr(&mut self) -> P<Expr> {
2421 let b = self.parse_bottom_expr();
2422 self.parse_dot_or_call_expr_with(b)
2425 pub fn parse_dot_or_call_expr_with(&mut self, e0: P<Expr>) -> P<Expr> {
2431 if self.eat(&token::Dot) {
2433 token::Ident(i, _) => {
2434 let dot = self.last_span.hi;
2437 let (_, tys, bindings) = if self.eat(&token::ModSep) {
2439 self.parse_generic_values_after_lt()
2441 (Vec::new(), Vec::new(), Vec::new())
2444 if bindings.len() > 0 {
2445 let last_span = self.last_span;
2446 self.span_err(last_span, "type bindings are only permitted on trait paths");
2449 // expr.f() method call
2451 token::OpenDelim(token::Paren) => {
2452 let mut es = self.parse_unspanned_seq(
2453 &token::OpenDelim(token::Paren),
2454 &token::CloseDelim(token::Paren),
2455 seq_sep_trailing_allowed(token::Comma),
2458 hi = self.last_span.hi;
2461 let id = spanned(dot, hi, i);
2462 let nd = self.mk_method_call(id, tys, es);
2463 e = self.mk_expr(lo, hi, nd);
2466 if !tys.is_empty() {
2467 let last_span = self.last_span;
2468 self.span_err(last_span,
2469 "field expressions may not \
2470 have type parameters");
2473 let id = spanned(dot, hi, i);
2474 let field = self.mk_field(e, id);
2475 e = self.mk_expr(lo, hi, field);
2479 token::Literal(token::Integer(n), suf) => {
2482 // A tuple index may not have a suffix
2483 self.expect_no_suffix(sp, "tuple index", suf);
2485 let dot = self.last_span.hi;
2489 let index = n.as_str().parse::<uint>();
2492 let id = spanned(dot, hi, n);
2493 let field = self.mk_tup_field(e, id);
2494 e = self.mk_expr(lo, hi, field);
2497 let last_span = self.last_span;
2498 self.span_err(last_span, "invalid tuple or tuple struct index");
2502 token::Literal(token::Float(n), _suf) => {
2504 let last_span = self.last_span;
2505 let fstr = n.as_str();
2506 self.span_err(last_span,
2507 &format!("unexpected token: `{}`", n.as_str())[]);
2508 if fstr.chars().all(|x| "0123456789.".contains_char(x)) {
2509 let float = match fstr.parse::<f64>() {
2513 self.span_help(last_span,
2514 &format!("try parenthesizing the first index; e.g., `(foo.{}){}`",
2515 float.trunc() as uint,
2516 &float.fract().to_string()[1..])[]);
2518 self.abort_if_errors();
2521 _ => self.unexpected()
2525 if self.expr_is_complete(&*e) { break; }
2528 token::OpenDelim(token::Paren) => {
2529 let es = self.parse_unspanned_seq(
2530 &token::OpenDelim(token::Paren),
2531 &token::CloseDelim(token::Paren),
2532 seq_sep_trailing_allowed(token::Comma),
2535 hi = self.last_span.hi;
2537 let nd = self.mk_call(e, es);
2538 e = self.mk_expr(lo, hi, nd);
2542 // Could be either an index expression or a slicing expression.
2543 token::OpenDelim(token::Bracket) => {
2544 let bracket_pos = self.span.lo;
2547 let mut found_dotdot = false;
2548 if self.token == token::DotDot &&
2549 self.look_ahead(1, |t| t == &token::CloseDelim(token::Bracket)) {
2550 // Using expr[..], which is a mistake, should be expr[]
2553 found_dotdot = true;
2556 if found_dotdot || self.eat(&token::CloseDelim(token::Bracket)) {
2557 // No expression, expand to a FullRange
2558 // FIXME(#20516) It would be better to use a lang item or
2559 // something for FullRange.
2560 hi = self.last_span.hi;
2561 let range = ExprStruct(ident_to_path(mk_sp(lo, hi),
2562 token::special_idents::FullRange),
2565 let ix = self.mk_expr(bracket_pos, hi, range);
2566 let index = self.mk_index(e, ix);
2567 e = self.mk_expr(lo, hi, index)
2569 let ix = self.parse_expr();
2571 self.commit_expr_expecting(&*ix, token::CloseDelim(token::Bracket));
2572 let index = self.mk_index(e, ix);
2573 e = self.mk_expr(lo, hi, index)
2577 self.span_err(e.span, "incorrect slicing expression: `[..]`");
2578 self.span_note(e.span,
2579 "use `&expr[]` to construct a slice of the whole of expr");
2588 // Parse unquoted tokens after a `$` in a token tree
2589 fn parse_unquoted(&mut self) -> TokenTree {
2590 let mut sp = self.span;
2591 let (name, namep) = match self.token {
2595 if self.token == token::OpenDelim(token::Paren) {
2596 let Spanned { node: seq, span: seq_span } = self.parse_seq(
2597 &token::OpenDelim(token::Paren),
2598 &token::CloseDelim(token::Paren),
2600 |p| p.parse_token_tree()
2602 let (sep, repeat) = self.parse_sep_and_kleene_op();
2603 let name_num = macro_parser::count_names(seq.as_slice());
2604 return TtSequence(mk_sp(sp.lo, seq_span.hi),
2605 Rc::new(SequenceRepetition {
2609 num_captures: name_num
2611 } else if self.token.is_keyword_allow_following_colon(keywords::Crate) {
2613 return TtToken(sp, SpecialVarNt(SpecialMacroVar::CrateMacroVar));
2615 sp = mk_sp(sp.lo, self.span.hi);
2616 let namep = match self.token { token::Ident(_, p) => p, _ => token::Plain };
2617 let name = self.parse_ident();
2621 token::SubstNt(name, namep) => {
2627 // continue by trying to parse the `:ident` after `$name`
2628 if self.token == token::Colon && self.look_ahead(1, |t| t.is_ident() &&
2629 !t.is_strict_keyword() &&
2630 !t.is_reserved_keyword()) {
2632 sp = mk_sp(sp.lo, self.span.hi);
2633 let kindp = match self.token { token::Ident(_, p) => p, _ => token::Plain };
2634 let nt_kind = self.parse_ident();
2635 TtToken(sp, MatchNt(name, nt_kind, namep, kindp))
2637 TtToken(sp, SubstNt(name, namep))
2641 pub fn check_unknown_macro_variable(&mut self) {
2642 if self.quote_depth == 0u {
2644 token::SubstNt(name, _) =>
2645 self.fatal(&format!("unknown macro variable `{}`",
2646 token::get_ident(name))[]),
2652 /// Parse an optional separator followed by a Kleene-style
2653 /// repetition token (+ or *).
2654 pub fn parse_sep_and_kleene_op(&mut self) -> (Option<token::Token>, ast::KleeneOp) {
2655 fn parse_kleene_op(parser: &mut Parser) -> Option<ast::KleeneOp> {
2656 match parser.token {
2657 token::BinOp(token::Star) => {
2659 Some(ast::ZeroOrMore)
2661 token::BinOp(token::Plus) => {
2663 Some(ast::OneOrMore)
2669 match parse_kleene_op(self) {
2670 Some(kleene_op) => return (None, kleene_op),
2674 let separator = self.bump_and_get();
2675 match parse_kleene_op(self) {
2676 Some(zerok) => (Some(separator), zerok),
2677 None => self.fatal("expected `*` or `+`")
2681 /// parse a single token tree from the input.
2682 pub fn parse_token_tree(&mut self) -> TokenTree {
2683 // FIXME #6994: currently, this is too eager. It
2684 // parses token trees but also identifies TtSequence's
2685 // and token::SubstNt's; it's too early to know yet
2686 // whether something will be a nonterminal or a seq
2688 maybe_whole!(deref self, NtTT);
2690 // this is the fall-through for the 'match' below.
2691 // invariants: the current token is not a left-delimiter,
2692 // not an EOF, and not the desired right-delimiter (if
2693 // it were, parse_seq_to_before_end would have prevented
2694 // reaching this point.
2695 fn parse_non_delim_tt_tok(p: &mut Parser) -> TokenTree {
2696 maybe_whole!(deref p, NtTT);
2698 token::CloseDelim(_) => {
2699 // This is a conservative error: only report the last unclosed delimiter. The
2700 // previous unclosed delimiters could actually be closed! The parser just hasn't
2701 // gotten to them yet.
2702 match p.open_braces.last() {
2704 Some(&sp) => p.span_note(sp, "unclosed delimiter"),
2706 let token_str = p.this_token_to_string();
2707 p.fatal(&format!("incorrect close delimiter: `{}`",
2710 /* we ought to allow different depths of unquotation */
2711 token::Dollar | token::SubstNt(..) if p.quote_depth > 0u => {
2715 TtToken(p.span, p.bump_and_get())
2722 let open_braces = self.open_braces.clone();
2723 for sp in open_braces.iter() {
2724 self.span_help(*sp, "did you mean to close this delimiter?");
2726 // There shouldn't really be a span, but it's easier for the test runner
2727 // if we give it one
2728 self.fatal("this file contains an un-closed delimiter ");
2730 token::OpenDelim(delim) => {
2731 // The span for beginning of the delimited section
2732 let pre_span = self.span;
2734 // Parse the open delimiter.
2735 self.open_braces.push(self.span);
2736 let open_span = self.span;
2739 // Parse the token trees within the delimiters
2740 let tts = self.parse_seq_to_before_end(
2741 &token::CloseDelim(delim),
2743 |p| p.parse_token_tree()
2746 // Parse the close delimiter.
2747 let close_span = self.span;
2749 self.open_braces.pop().unwrap();
2751 // Expand to cover the entire delimited token tree
2752 let span = Span { hi: self.span.hi, ..pre_span };
2754 TtDelimited(span, Rc::new(Delimited {
2756 open_span: open_span,
2758 close_span: close_span,
2761 _ => parse_non_delim_tt_tok(self),
2765 // parse a stream of tokens into a list of TokenTree's,
2767 pub fn parse_all_token_trees(&mut self) -> Vec<TokenTree> {
2768 let mut tts = Vec::new();
2769 while self.token != token::Eof {
2770 tts.push(self.parse_token_tree());
2775 /// Parse a prefix-operator expr
2776 pub fn parse_prefix_expr(&mut self) -> P<Expr> {
2777 let lo = self.span.lo;
2780 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2785 let e = self.parse_prefix_expr();
2787 ex = self.mk_unary(UnNot, e);
2789 token::BinOp(token::Minus) => {
2791 let e = self.parse_prefix_expr();
2793 ex = self.mk_unary(UnNeg, e);
2795 token::BinOp(token::Star) => {
2797 let e = self.parse_prefix_expr();
2799 ex = self.mk_unary(UnDeref, e);
2801 token::BinOp(token::And) | token::AndAnd => {
2803 let m = self.parse_mutability();
2804 let e = self.parse_prefix_expr();
2806 ex = ExprAddrOf(m, e);
2808 token::DotDot if !self.restrictions.contains(RESTRICTION_NO_DOTS) => {
2809 // A range, closed above: `..expr`.
2811 let e = self.parse_expr();
2813 ex = self.mk_range(None, Some(e));
2815 token::Ident(_, _) => {
2816 if !self.token.is_keyword(keywords::Box) {
2817 return self.parse_dot_or_call_expr();
2820 let lo = self.span.lo;
2824 // Check for a place: `box(PLACE) EXPR`.
2825 if self.eat(&token::OpenDelim(token::Paren)) {
2826 // Support `box() EXPR` as the default.
2827 if !self.eat(&token::CloseDelim(token::Paren)) {
2828 let place = self.parse_expr();
2829 self.expect(&token::CloseDelim(token::Paren));
2830 // Give a suggestion to use `box()` when a parenthesised expression is used
2831 if !self.token.can_begin_expr() {
2832 let span = self.span;
2833 let this_token_to_string = self.this_token_to_string();
2835 &format!("expected expression, found `{}`",
2836 this_token_to_string)[]);
2837 let box_span = mk_sp(lo, self.last_span.hi);
2838 self.span_help(box_span,
2839 "perhaps you meant `box() (foo)` instead?");
2840 self.abort_if_errors();
2842 let subexpression = self.parse_prefix_expr();
2843 hi = subexpression.span.hi;
2844 ex = ExprBox(Some(place), subexpression);
2845 return self.mk_expr(lo, hi, ex);
2849 // Otherwise, we use the unique pointer default.
2850 let subexpression = self.parse_prefix_expr();
2851 hi = subexpression.span.hi;
2852 // FIXME (pnkfelix): After working out kinks with box
2853 // desugaring, should be `ExprBox(None, subexpression)`
2855 ex = self.mk_unary(UnUniq, subexpression);
2857 _ => return self.parse_dot_or_call_expr()
2859 return self.mk_expr(lo, hi, ex);
2862 /// Parse an expression of binops
2863 pub fn parse_binops(&mut self) -> P<Expr> {
2864 let prefix_expr = self.parse_prefix_expr();
2865 self.parse_more_binops(prefix_expr, 0)
2868 /// Parse an expression of binops of at least min_prec precedence
2869 pub fn parse_more_binops(&mut self, lhs: P<Expr>, min_prec: uint) -> P<Expr> {
2870 if self.expr_is_complete(&*lhs) { return lhs; }
2872 // Prevent dynamic borrow errors later on by limiting the
2873 // scope of the borrows.
2874 if self.token == token::BinOp(token::Or) &&
2875 self.restrictions.contains(RESTRICTION_NO_BAR_OP) {
2879 self.expected_tokens.push(TokenType::Operator);
2881 let cur_opt = self.token.to_binop();
2884 if ast_util::is_comparison_binop(cur_op) {
2885 self.check_no_chained_comparison(&*lhs, cur_op)
2887 let cur_prec = operator_prec(cur_op);
2888 if cur_prec > min_prec {
2890 let expr = self.parse_prefix_expr();
2891 let rhs = self.parse_more_binops(expr, cur_prec);
2892 let lhs_span = lhs.span;
2893 let rhs_span = rhs.span;
2894 let binary = self.mk_binary(cur_op, lhs, rhs);
2895 let bin = self.mk_expr(lhs_span.lo, rhs_span.hi, binary);
2896 self.parse_more_binops(bin, min_prec)
2902 if as_prec > min_prec && self.eat_keyword(keywords::As) {
2903 let rhs = self.parse_ty();
2904 let _as = self.mk_expr(lhs.span.lo,
2906 ExprCast(lhs, rhs));
2907 self.parse_more_binops(_as, min_prec)
2915 /// Produce an error if comparison operators are chained (RFC #558).
2916 /// We only need to check lhs, not rhs, because all comparison ops
2917 /// have same precedence and are left-associative
2918 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: ast::BinOp) {
2919 debug_assert!(ast_util::is_comparison_binop(outer_op));
2921 ExprBinary(op, _, _) if ast_util::is_comparison_binop(op) => {
2922 let op_span = self.span;
2923 self.span_err(op_span,
2924 "Chained comparison operators require parentheses");
2925 if op == BiLt && outer_op == BiGt {
2926 self.span_help(op_span,
2927 "Use ::< instead of < if you meant to specify type arguments.");
2934 /// Parse an assignment expression....
2935 /// actually, this seems to be the main entry point for
2936 /// parsing an arbitrary expression.
2937 pub fn parse_assign_expr(&mut self) -> P<Expr> {
2938 let lhs = self.parse_binops();
2939 self.parse_assign_expr_with(lhs)
2942 pub fn parse_assign_expr_with(&mut self, lhs: P<Expr>) -> P<Expr> {
2943 let restrictions = self.restrictions & RESTRICTION_NO_STRUCT_LITERAL;
2947 let rhs = self.parse_expr_res(restrictions);
2948 self.mk_expr(lhs.span.lo, rhs.span.hi, ExprAssign(lhs, rhs))
2950 token::BinOpEq(op) => {
2952 let rhs = self.parse_expr_res(restrictions);
2953 let aop = match op {
2954 token::Plus => BiAdd,
2955 token::Minus => BiSub,
2956 token::Star => BiMul,
2957 token::Slash => BiDiv,
2958 token::Percent => BiRem,
2959 token::Caret => BiBitXor,
2960 token::And => BiBitAnd,
2961 token::Or => BiBitOr,
2962 token::Shl => BiShl,
2965 let rhs_span = rhs.span;
2966 let span = lhs.span;
2967 let assign_op = self.mk_assign_op(aop, lhs, rhs);
2968 self.mk_expr(span.lo, rhs_span.hi, assign_op)
2970 // A range expression, either `expr..expr` or `expr..`.
2971 token::DotDot if !self.restrictions.contains(RESTRICTION_NO_DOTS) => {
2974 let opt_end = if self.token.can_begin_expr() {
2975 let end = self.parse_expr_res(RESTRICTION_NO_DOTS);
2981 let lo = lhs.span.lo;
2982 let hi = self.span.hi;
2983 let range = self.mk_range(Some(lhs), opt_end);
2984 return self.mk_expr(lo, hi, range);
2993 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
2994 pub fn parse_if_expr(&mut self) -> P<Expr> {
2995 if self.token.is_keyword(keywords::Let) {
2996 return self.parse_if_let_expr();
2998 let lo = self.last_span.lo;
2999 let cond = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
3000 let thn = self.parse_block();
3001 let mut els: Option<P<Expr>> = None;
3002 let mut hi = thn.span.hi;
3003 if self.eat_keyword(keywords::Else) {
3004 let elexpr = self.parse_else_expr();
3005 hi = elexpr.span.hi;
3008 self.mk_expr(lo, hi, ExprIf(cond, thn, els))
3011 /// Parse an 'if let' expression ('if' token already eaten)
3012 pub fn parse_if_let_expr(&mut self) -> P<Expr> {
3013 let lo = self.last_span.lo;
3014 self.expect_keyword(keywords::Let);
3015 let pat = self.parse_pat();
3016 self.expect(&token::Eq);
3017 let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
3018 let thn = self.parse_block();
3019 let (hi, els) = if self.eat_keyword(keywords::Else) {
3020 let expr = self.parse_else_expr();
3021 (expr.span.hi, Some(expr))
3025 self.mk_expr(lo, hi, ExprIfLet(pat, expr, thn, els))
3029 pub fn parse_lambda_expr(&mut self, capture_clause: CaptureClause)
3032 let lo = self.span.lo;
3033 let (decl, optional_unboxed_closure_kind) =
3034 self.parse_fn_block_decl();
3035 let body = self.parse_expr();
3036 let fakeblock = P(ast::Block {
3037 id: ast::DUMMY_NODE_ID,
3038 view_items: Vec::new(),
3042 rules: DefaultBlock,
3048 ExprClosure(capture_clause, optional_unboxed_closure_kind, decl, fakeblock))
3051 pub fn parse_else_expr(&mut self) -> P<Expr> {
3052 if self.eat_keyword(keywords::If) {
3053 return self.parse_if_expr();
3055 let blk = self.parse_block();
3056 return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk));
3060 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3061 pub fn parse_for_expr(&mut self, opt_ident: Option<ast::Ident>) -> P<Expr> {
3062 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3064 let lo = self.last_span.lo;
3065 let pat = self.parse_pat();
3066 self.expect_keyword(keywords::In);
3067 let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
3068 let loop_block = self.parse_block();
3069 let hi = self.span.hi;
3071 self.mk_expr(lo, hi, ExprForLoop(pat, expr, loop_block, opt_ident))
3074 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3075 pub fn parse_while_expr(&mut self, opt_ident: Option<ast::Ident>) -> P<Expr> {
3076 if self.token.is_keyword(keywords::Let) {
3077 return self.parse_while_let_expr(opt_ident);
3079 let lo = self.last_span.lo;
3080 let cond = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
3081 let body = self.parse_block();
3082 let hi = body.span.hi;
3083 return self.mk_expr(lo, hi, ExprWhile(cond, body, opt_ident));
3086 /// Parse a 'while let' expression ('while' token already eaten)
3087 pub fn parse_while_let_expr(&mut self, opt_ident: Option<ast::Ident>) -> P<Expr> {
3088 let lo = self.last_span.lo;
3089 self.expect_keyword(keywords::Let);
3090 let pat = self.parse_pat();
3091 self.expect(&token::Eq);
3092 let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
3093 let body = self.parse_block();
3094 let hi = body.span.hi;
3095 return self.mk_expr(lo, hi, ExprWhileLet(pat, expr, body, opt_ident));
3098 pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::Ident>) -> P<Expr> {
3099 let lo = self.last_span.lo;
3100 let body = self.parse_block();
3101 let hi = body.span.hi;
3102 self.mk_expr(lo, hi, ExprLoop(body, opt_ident))
3105 fn parse_match_expr(&mut self) -> P<Expr> {
3106 let lo = self.last_span.lo;
3107 let discriminant = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
3108 self.commit_expr_expecting(&*discriminant, token::OpenDelim(token::Brace));
3109 let mut arms: Vec<Arm> = Vec::new();
3110 while self.token != token::CloseDelim(token::Brace) {
3111 arms.push(self.parse_arm());
3113 let hi = self.span.hi;
3115 return self.mk_expr(lo, hi, ExprMatch(discriminant, arms, MatchSource::Normal));
3118 pub fn parse_arm(&mut self) -> Arm {
3119 let attrs = self.parse_outer_attributes();
3120 let pats = self.parse_pats();
3121 let mut guard = None;
3122 if self.eat_keyword(keywords::If) {
3123 guard = Some(self.parse_expr());
3125 self.expect(&token::FatArrow);
3126 let expr = self.parse_expr_res(RESTRICTION_STMT_EXPR);
3129 !classify::expr_is_simple_block(&*expr)
3130 && self.token != token::CloseDelim(token::Brace);
3133 self.commit_expr(&*expr, &[token::Comma], &[token::CloseDelim(token::Brace)]);
3135 self.eat(&token::Comma);
3146 /// Parse an expression
3147 pub fn parse_expr(&mut self) -> P<Expr> {
3148 return self.parse_expr_res(UNRESTRICTED);
3151 /// Parse an expression, subject to the given restrictions
3152 pub fn parse_expr_res(&mut self, r: Restrictions) -> P<Expr> {
3153 let old = self.restrictions;
3154 self.restrictions = r;
3155 let e = self.parse_assign_expr();
3156 self.restrictions = old;
3160 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3161 fn parse_initializer(&mut self) -> Option<P<Expr>> {
3162 if self.check(&token::Eq) {
3164 Some(self.parse_expr())
3170 /// Parse patterns, separated by '|' s
3171 fn parse_pats(&mut self) -> Vec<P<Pat>> {
3172 let mut pats = Vec::new();
3174 pats.push(self.parse_pat());
3175 if self.check(&token::BinOp(token::Or)) { self.bump(); }
3176 else { return pats; }
3180 fn parse_pat_vec_elements(
3182 ) -> (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>) {
3183 let mut before = Vec::new();
3184 let mut slice = None;
3185 let mut after = Vec::new();
3186 let mut first = true;
3187 let mut before_slice = true;
3189 while self.token != token::CloseDelim(token::Bracket) {
3193 self.expect(&token::Comma);
3195 if self.token == token::CloseDelim(token::Bracket)
3196 && (before_slice || after.len() != 0) {
3202 if self.check(&token::DotDot) {
3205 if self.check(&token::Comma) ||
3206 self.check(&token::CloseDelim(token::Bracket)) {
3207 slice = Some(P(ast::Pat {
3208 id: ast::DUMMY_NODE_ID,
3209 node: PatWild(PatWildMulti),
3212 before_slice = false;
3218 let subpat = self.parse_pat();
3219 if before_slice && self.check(&token::DotDot) {
3221 slice = Some(subpat);
3222 before_slice = false;
3223 } else if before_slice {
3224 before.push(subpat);
3230 (before, slice, after)
3233 /// Parse the fields of a struct-like pattern
3234 fn parse_pat_fields(&mut self) -> (Vec<codemap::Spanned<ast::FieldPat>> , bool) {
3235 let mut fields = Vec::new();
3236 let mut etc = false;
3237 let mut first = true;
3238 while self.token != token::CloseDelim(token::Brace) {
3242 self.expect(&token::Comma);
3243 // accept trailing commas
3244 if self.check(&token::CloseDelim(token::Brace)) { break }
3247 let lo = self.span.lo;
3250 if self.check(&token::DotDot) {
3252 if self.token != token::CloseDelim(token::Brace) {
3253 let token_str = self.this_token_to_string();
3254 self.fatal(&format!("expected `{}`, found `{}`", "}",
3261 let bind_type = if self.eat_keyword(keywords::Mut) {
3262 BindByValue(MutMutable)
3263 } else if self.eat_keyword(keywords::Ref) {
3264 BindByRef(self.parse_mutability())
3266 BindByValue(MutImmutable)
3269 let fieldname = self.parse_ident();
3271 let (subpat, is_shorthand) = if self.check(&token::Colon) {
3273 BindByRef(..) | BindByValue(MutMutable) => {
3274 let token_str = self.this_token_to_string();
3275 self.fatal(&format!("unexpected `{}`",
3282 let pat = self.parse_pat();
3286 hi = self.last_span.hi;
3287 let fieldpath = codemap::Spanned{span:self.last_span, node: fieldname};
3289 id: ast::DUMMY_NODE_ID,
3290 node: PatIdent(bind_type, fieldpath, None),
3291 span: self.last_span
3294 fields.push(codemap::Spanned { span: mk_sp(lo, hi),
3295 node: ast::FieldPat { ident: fieldname,
3297 is_shorthand: is_shorthand }});
3299 return (fields, etc);
3302 /// Parse a pattern.
3303 pub fn parse_pat(&mut self) -> P<Pat> {
3304 maybe_whole!(self, NtPat);
3306 let lo = self.span.lo;
3311 token::Underscore => {
3313 pat = PatWild(PatWildSingle);
3314 hi = self.last_span.hi;
3316 id: ast::DUMMY_NODE_ID,
3321 token::BinOp(token::And) | token::AndAnd => {
3322 // parse &pat and &mut pat
3323 let lo = self.span.lo;
3325 let mutability = if self.eat_keyword(keywords::Mut) {
3330 let sub = self.parse_pat();
3331 pat = PatRegion(sub, mutability);
3332 hi = self.last_span.hi;
3334 id: ast::DUMMY_NODE_ID,
3339 token::OpenDelim(token::Paren) => {
3340 // parse (pat,pat,pat,...) as tuple
3342 if self.check(&token::CloseDelim(token::Paren)) {
3344 pat = PatTup(vec![]);
3346 let mut fields = vec!(self.parse_pat());
3347 if self.look_ahead(1, |t| *t != token::CloseDelim(token::Paren)) {
3348 while self.check(&token::Comma) {
3350 if self.check(&token::CloseDelim(token::Paren)) { break; }
3351 fields.push(self.parse_pat());
3354 if fields.len() == 1 { self.expect(&token::Comma); }
3355 self.expect(&token::CloseDelim(token::Paren));
3356 pat = PatTup(fields);
3358 hi = self.last_span.hi;
3360 id: ast::DUMMY_NODE_ID,
3365 token::OpenDelim(token::Bracket) => {
3366 // parse [pat,pat,...] as vector pattern
3368 let (before, slice, after) =
3369 self.parse_pat_vec_elements();
3371 self.expect(&token::CloseDelim(token::Bracket));
3372 pat = ast::PatVec(before, slice, after);
3373 hi = self.last_span.hi;
3375 id: ast::DUMMY_NODE_ID,
3382 // at this point, token != _, ~, &, &&, (, [
3384 if (!(self.token.is_ident() || self.token.is_path())
3385 && self.token != token::ModSep)
3386 || self.token.is_keyword(keywords::True)
3387 || self.token.is_keyword(keywords::False) {
3388 // Parse an expression pattern or exp .. exp.
3390 // These expressions are limited to literals (possibly
3391 // preceded by unary-minus) or identifiers.
3392 let val = self.parse_literal_maybe_minus();
3393 if (self.check(&token::DotDotDot)) &&
3394 self.look_ahead(1, |t| {
3395 *t != token::Comma && *t != token::CloseDelim(token::Bracket)
3398 let end = if self.token.is_ident() || self.token.is_path() {
3399 let path = self.parse_path(LifetimeAndTypesWithColons);
3400 let hi = self.span.hi;
3401 self.mk_expr(lo, hi, ExprPath(path))
3403 self.parse_literal_maybe_minus()
3405 pat = PatRange(val, end);
3409 } else if self.eat_keyword(keywords::Mut) {
3410 pat = self.parse_pat_ident(BindByValue(MutMutable));
3411 } else if self.eat_keyword(keywords::Ref) {
3413 let mutbl = self.parse_mutability();
3414 pat = self.parse_pat_ident(BindByRef(mutbl));
3415 } else if self.eat_keyword(keywords::Box) {
3418 // FIXME(#13910): Rename to `PatBox` and extend to full DST
3420 let sub = self.parse_pat();
3422 hi = self.last_span.hi;
3424 id: ast::DUMMY_NODE_ID,
3429 let can_be_enum_or_struct = self.look_ahead(1, |t| {
3431 token::OpenDelim(_) | token::Lt | token::ModSep => true,
3436 if self.look_ahead(1, |t| *t == token::DotDotDot) &&
3437 self.look_ahead(2, |t| {
3438 *t != token::Comma && *t != token::CloseDelim(token::Bracket)
3440 let start = self.parse_expr_res(RESTRICTION_NO_BAR_OP);
3441 self.eat(&token::DotDotDot);
3442 let end = self.parse_expr_res(RESTRICTION_NO_BAR_OP);
3443 pat = PatRange(start, end);
3444 } else if self.token.is_plain_ident() && !can_be_enum_or_struct {
3445 let id = self.parse_ident();
3446 let id_span = self.last_span;
3447 let pth1 = codemap::Spanned{span:id_span, node: id};
3448 if self.eat(&token::Not) {
3450 let delim = self.expect_open_delim();
3451 let tts = self.parse_seq_to_end(&token::CloseDelim(delim),
3453 |p| p.parse_token_tree());
3455 let mac = MacInvocTT(ident_to_path(id_span,id), tts, EMPTY_CTXT);
3456 pat = ast::PatMac(codemap::Spanned {node: mac, span: self.span});
3458 let sub = if self.eat(&token::At) {
3460 Some(self.parse_pat())
3465 pat = PatIdent(BindByValue(MutImmutable), pth1, sub);
3468 // parse an enum pat
3469 let enum_path = self.parse_path(LifetimeAndTypesWithColons);
3471 token::OpenDelim(token::Brace) => {
3474 self.parse_pat_fields();
3476 pat = PatStruct(enum_path, fields, etc);
3479 let mut args: Vec<P<Pat>> = Vec::new();
3481 token::OpenDelim(token::Paren) => {
3482 let is_dotdot = self.look_ahead(1, |t| {
3484 token::DotDot => true,
3489 // This is a "top constructor only" pat
3492 self.expect(&token::CloseDelim(token::Paren));
3493 pat = PatEnum(enum_path, None);
3495 args = self.parse_enum_variant_seq(
3496 &token::OpenDelim(token::Paren),
3497 &token::CloseDelim(token::Paren),
3498 seq_sep_trailing_allowed(token::Comma),
3501 pat = PatEnum(enum_path, Some(args));
3505 if !enum_path.global &&
3506 enum_path.segments.len() == 1 &&
3507 enum_path.segments[0].parameters.is_empty()
3509 // it could still be either an enum
3510 // or an identifier pattern, resolve
3511 // will sort it out:
3512 pat = PatIdent(BindByValue(MutImmutable),
3514 span: enum_path.span,
3515 node: enum_path.segments[0]
3519 pat = PatEnum(enum_path, Some(args));
3527 hi = self.last_span.hi;
3529 id: ast::DUMMY_NODE_ID,
3531 span: mk_sp(lo, hi),
3535 /// Parse ident or ident @ pat
3536 /// used by the copy foo and ref foo patterns to give a good
3537 /// error message when parsing mistakes like ref foo(a,b)
3538 fn parse_pat_ident(&mut self,
3539 binding_mode: ast::BindingMode)
3541 if !self.token.is_plain_ident() {
3542 let span = self.span;
3543 let tok_str = self.this_token_to_string();
3544 self.span_fatal(span,
3545 &format!("expected identifier, found `{}`", tok_str)[]);
3547 let ident = self.parse_ident();
3548 let last_span = self.last_span;
3549 let name = codemap::Spanned{span: last_span, node: ident};
3550 let sub = if self.eat(&token::At) {
3551 Some(self.parse_pat())
3556 // just to be friendly, if they write something like
3558 // we end up here with ( as the current token. This shortly
3559 // leads to a parse error. Note that if there is no explicit
3560 // binding mode then we do not end up here, because the lookahead
3561 // will direct us over to parse_enum_variant()
3562 if self.token == token::OpenDelim(token::Paren) {
3563 let last_span = self.last_span;
3566 "expected identifier, found enum pattern");
3569 PatIdent(binding_mode, name, sub)
3572 /// Parse a local variable declaration
3573 fn parse_local(&mut self) -> P<Local> {
3574 let lo = self.span.lo;
3575 let pat = self.parse_pat();
3578 if self.eat(&token::Colon) {
3579 ty = Some(self.parse_ty_sum());
3581 let init = self.parse_initializer();
3586 id: ast::DUMMY_NODE_ID,
3587 span: mk_sp(lo, self.last_span.hi),
3592 /// Parse a "let" stmt
3593 fn parse_let(&mut self) -> P<Decl> {
3594 let lo = self.span.lo;
3595 let local = self.parse_local();
3596 P(spanned(lo, self.last_span.hi, DeclLocal(local)))
3599 /// Parse a structure field
3600 fn parse_name_and_ty(&mut self, pr: Visibility,
3601 attrs: Vec<Attribute> ) -> StructField {
3602 let lo = self.span.lo;
3603 if !self.token.is_plain_ident() {
3604 self.fatal("expected ident");
3606 let name = self.parse_ident();
3607 self.expect(&token::Colon);
3608 let ty = self.parse_ty_sum();
3609 spanned(lo, self.last_span.hi, ast::StructField_ {
3610 kind: NamedField(name, pr),
3611 id: ast::DUMMY_NODE_ID,
3617 /// Get an expected item after attributes error message.
3618 fn expected_item_err(attrs: &[Attribute]) -> &'static str {
3619 match attrs.last() {
3620 Some(&Attribute { node: ast::Attribute_ { is_sugared_doc: true, .. }, .. }) => {
3621 "expected item after doc comment"
3623 _ => "expected item after attributes",
3627 /// Parse a statement. may include decl.
3628 /// Precondition: any attributes are parsed already
3629 pub fn parse_stmt(&mut self, item_attrs: Vec<Attribute>) -> P<Stmt> {
3630 maybe_whole!(self, NtStmt);
3632 fn check_expected_item(p: &mut Parser, attrs: &[Attribute]) {
3633 // If we have attributes then we should have an item
3634 if !attrs.is_empty() {
3635 let last_span = p.last_span;
3636 p.span_err(last_span, Parser::expected_item_err(attrs));
3640 let lo = self.span.lo;
3641 if self.token.is_keyword(keywords::Let) {
3642 check_expected_item(self, &item_attrs[]);
3643 self.expect_keyword(keywords::Let);
3644 let decl = self.parse_let();
3645 P(spanned(lo, decl.span.hi, StmtDecl(decl, ast::DUMMY_NODE_ID)))
3646 } else if self.token.is_ident()
3647 && !self.token.is_any_keyword()
3648 && self.look_ahead(1, |t| *t == token::Not) {
3649 // it's a macro invocation:
3651 check_expected_item(self, &item_attrs[]);
3653 // Potential trouble: if we allow macros with paths instead of
3654 // idents, we'd need to look ahead past the whole path here...
3655 let pth = self.parse_path(NoTypesAllowed);
3658 let id = match self.token {
3659 token::OpenDelim(_) => token::special_idents::invalid, // no special identifier
3660 _ => self.parse_ident(),
3663 // check that we're pointing at delimiters (need to check
3664 // again after the `if`, because of `parse_ident`
3665 // consuming more tokens).
3666 let delim = match self.token {
3667 token::OpenDelim(delim) => delim,
3669 // we only expect an ident if we didn't parse one
3671 let ident_str = if id.name == token::special_idents::invalid.name {
3676 let tok_str = self.this_token_to_string();
3677 self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
3683 let tts = self.parse_unspanned_seq(
3684 &token::OpenDelim(delim),
3685 &token::CloseDelim(delim),
3687 |p| p.parse_token_tree()
3689 let hi = self.span.hi;
3691 let style = if delim == token::Brace {
3694 MacStmtWithoutBraces
3697 if id.name == token::special_idents::invalid.name {
3700 StmtMac(P(spanned(lo,
3702 MacInvocTT(pth, tts, EMPTY_CTXT))),
3705 // if it has a special ident, it's definitely an item
3707 // Require a semicolon or braces.
3708 if style != MacStmtWithBraces {
3709 if !self.eat(&token::Semi) {
3710 let last_span = self.last_span;
3711 self.span_err(last_span,
3712 "macros that expand to items must \
3713 either be surrounded with braces or \
3714 followed by a semicolon");
3717 P(spanned(lo, hi, StmtDecl(
3718 P(spanned(lo, hi, DeclItem(
3720 lo, hi, id /*id is good here*/,
3721 ItemMac(spanned(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT))),
3722 Inherited, Vec::new(/*no attrs*/))))),
3723 ast::DUMMY_NODE_ID)))
3726 let found_attrs = !item_attrs.is_empty();
3727 let item_err = Parser::expected_item_err(&item_attrs[]);
3728 match self.parse_item_or_view_item(item_attrs, false) {
3731 let decl = P(spanned(lo, hi, DeclItem(i)));
3732 P(spanned(lo, hi, StmtDecl(decl, ast::DUMMY_NODE_ID)))
3734 IoviViewItem(vi) => {
3735 self.span_fatal(vi.span,
3736 "view items must be declared at the top of the block");
3738 IoviForeignItem(_) => {
3739 self.fatal("foreign items are not allowed here");
3743 let last_span = self.last_span;
3744 self.span_err(last_span, item_err);
3747 // Remainder are line-expr stmts.
3748 let e = self.parse_expr_res(RESTRICTION_STMT_EXPR);
3749 P(spanned(lo, e.span.hi, StmtExpr(e, ast::DUMMY_NODE_ID)))
3755 /// Is this expression a successfully-parsed statement?
3756 fn expr_is_complete(&mut self, e: &Expr) -> bool {
3757 self.restrictions.contains(RESTRICTION_STMT_EXPR) &&
3758 !classify::expr_requires_semi_to_be_stmt(e)
3761 /// Parse a block. No inner attrs are allowed.
3762 pub fn parse_block(&mut self) -> P<Block> {
3763 maybe_whole!(no_clone self, NtBlock);
3765 let lo = self.span.lo;
3767 if !self.eat(&token::OpenDelim(token::Brace)) {
3769 let tok = self.this_token_to_string();
3770 self.span_fatal_help(sp,
3771 &format!("expected `{{`, found `{}`", tok)[],
3772 "place this code inside a block");
3775 return self.parse_block_tail_(lo, DefaultBlock, Vec::new());
3778 /// Parse a block. Inner attrs are allowed.
3779 fn parse_inner_attrs_and_block(&mut self)
3780 -> (Vec<Attribute> , P<Block>) {
3782 maybe_whole!(pair_empty self, NtBlock);
3784 let lo = self.span.lo;
3785 self.expect(&token::OpenDelim(token::Brace));
3786 let (inner, next) = self.parse_inner_attrs_and_next();
3788 (inner, self.parse_block_tail_(lo, DefaultBlock, next))
3791 /// Precondition: already parsed the '{' or '#{'
3792 /// I guess that also means "already parsed the 'impure'" if
3793 /// necessary, and this should take a qualifier.
3794 /// Some blocks start with "#{"...
3795 fn parse_block_tail(&mut self, lo: BytePos, s: BlockCheckMode) -> P<Block> {
3796 self.parse_block_tail_(lo, s, Vec::new())
3799 /// Parse the rest of a block expression or function body
3800 fn parse_block_tail_(&mut self, lo: BytePos, s: BlockCheckMode,
3801 first_item_attrs: Vec<Attribute> ) -> P<Block> {
3802 let mut stmts = Vec::new();
3803 let mut expr = None;
3805 // wouldn't it be more uniform to parse view items only, here?
3806 let ParsedItemsAndViewItems {
3811 } = self.parse_items_and_view_items(first_item_attrs,
3814 for item in items.into_iter() {
3815 let span = item.span;
3816 let decl = P(spanned(span.lo, span.hi, DeclItem(item)));
3817 stmts.push(P(spanned(span.lo, span.hi, StmtDecl(decl, ast::DUMMY_NODE_ID))));
3820 let mut attributes_box = attrs_remaining;
3822 while self.token != token::CloseDelim(token::Brace) {
3823 // parsing items even when they're not allowed lets us give
3824 // better error messages and recover more gracefully.
3825 attributes_box.push_all(&self.parse_outer_attributes()[]);
3828 if !attributes_box.is_empty() {
3829 let last_span = self.last_span;
3830 self.span_err(last_span,
3831 Parser::expected_item_err(&attributes_box[]));
3832 attributes_box = Vec::new();
3834 self.bump(); // empty
3836 token::CloseDelim(token::Brace) => {
3837 // fall through and out.
3840 let stmt = self.parse_stmt(attributes_box);
3841 attributes_box = Vec::new();
3842 stmt.and_then(|Spanned {node, span}| match node {
3843 StmtExpr(e, stmt_id) => {
3844 self.handle_expression_like_statement(e,
3850 StmtMac(mac, MacStmtWithoutBraces) => {
3851 // statement macro without braces; might be an
3852 // expr depending on whether a semicolon follows
3855 stmts.push(P(Spanned {
3857 MacStmtWithSemicolon),
3863 let e = self.mk_mac_expr(span.lo,
3865 mac.and_then(|m| m.node));
3866 let e = self.parse_dot_or_call_expr_with(e);
3867 let e = self.parse_more_binops(e, 0);
3868 let e = self.parse_assign_expr_with(e);
3869 self.handle_expression_like_statement(
3878 StmtMac(m, style) => {
3879 // statement macro; might be an expr
3882 stmts.push(P(Spanned {
3884 MacStmtWithSemicolon),
3889 token::CloseDelim(token::Brace) => {
3890 // if a block ends in `m!(arg)` without
3891 // a `;`, it must be an expr
3893 self.mk_mac_expr(span.lo,
3895 m.and_then(|x| x.node)));
3898 stmts.push(P(Spanned {
3899 node: StmtMac(m, style),
3905 _ => { // all other kinds of statements:
3906 if classify::stmt_ends_with_semi(&node) {
3907 self.commit_stmt_expecting(token::Semi);
3910 stmts.push(P(Spanned {
3920 if !attributes_box.is_empty() {
3921 let last_span = self.last_span;
3922 self.span_err(last_span,
3923 Parser::expected_item_err(&attributes_box[]));
3926 let hi = self.span.hi;
3929 view_items: view_items,
3932 id: ast::DUMMY_NODE_ID,
3934 span: mk_sp(lo, hi),
3938 fn handle_expression_like_statement(
3943 stmts: &mut Vec<P<Stmt>>,
3944 last_block_expr: &mut Option<P<Expr>>) {
3945 // expression without semicolon
3946 if classify::expr_requires_semi_to_be_stmt(&*e) {
3947 // Just check for errors and recover; do not eat semicolon yet.
3948 self.commit_stmt(&[],
3949 &[token::Semi, token::CloseDelim(token::Brace)]);
3955 let span_with_semi = Span {
3957 hi: self.last_span.hi,
3958 expn_id: span.expn_id,
3960 stmts.push(P(Spanned {
3961 node: StmtSemi(e, stmt_id),
3962 span: span_with_semi,
3965 token::CloseDelim(token::Brace) => *last_block_expr = Some(e),
3967 stmts.push(P(Spanned {
3968 node: StmtExpr(e, stmt_id),
3975 // Parses a sequence of bounds if a `:` is found,
3976 // otherwise returns empty list.
3977 fn parse_colon_then_ty_param_bounds(&mut self,
3978 mode: BoundParsingMode)
3979 -> OwnedSlice<TyParamBound>
3981 if !self.eat(&token::Colon) {
3984 self.parse_ty_param_bounds(mode)
3988 // matches bounds = ( boundseq )?
3989 // where boundseq = ( polybound + boundseq ) | polybound
3990 // and polybound = ( 'for' '<' 'region '>' )? bound
3991 // and bound = 'region | trait_ref
3992 fn parse_ty_param_bounds(&mut self,
3993 mode: BoundParsingMode)
3994 -> OwnedSlice<TyParamBound>
3996 let mut result = vec!();
3998 let question_span = self.span;
3999 let ate_question = self.eat(&token::Question);
4001 token::Lifetime(lifetime) => {
4003 self.span_err(question_span,
4004 "`?` may only modify trait bounds, not lifetime bounds");
4006 result.push(RegionTyParamBound(ast::Lifetime {
4007 id: ast::DUMMY_NODE_ID,
4013 token::ModSep | token::Ident(..) => {
4014 let poly_trait_ref = self.parse_poly_trait_ref();
4015 let modifier = if ate_question {
4016 if mode == BoundParsingMode::Modified {
4017 TraitBoundModifier::Maybe
4019 self.span_err(question_span,
4021 TraitBoundModifier::None
4024 TraitBoundModifier::None
4026 result.push(TraitTyParamBound(poly_trait_ref, modifier))
4031 if !self.eat(&token::BinOp(token::Plus)) {
4036 return OwnedSlice::from_vec(result);
4039 fn trait_ref_from_ident(ident: Ident, span: Span) -> TraitRef {
4040 let segment = ast::PathSegment {
4042 parameters: ast::PathParameters::none()
4044 let path = ast::Path {
4047 segments: vec![segment],
4051 ref_id: ast::DUMMY_NODE_ID,
4055 /// Matches typaram = (unbound `?`)? IDENT (`?` unbound)? optbounds ( EQ ty )?
4056 fn parse_ty_param(&mut self) -> TyParam {
4057 // This is a bit hacky. Currently we are only interested in a single
4058 // unbound, and it may only be `Sized`. To avoid backtracking and other
4059 // complications, we parse an ident, then check for `?`. If we find it,
4060 // we use the ident as the unbound, otherwise, we use it as the name of
4061 // type param. Even worse, we need to check for `?` before or after the
4063 let mut span = self.span;
4064 let mut ident = self.parse_ident();
4065 let mut unbound = None;
4066 if self.eat(&token::Question) {
4067 let tref = Parser::trait_ref_from_ident(ident, span);
4068 unbound = Some(tref);
4070 ident = self.parse_ident();
4071 self.obsolete(span, ObsoleteSyntax::Sized);
4074 let mut bounds = self.parse_colon_then_ty_param_bounds(BoundParsingMode::Modified);
4075 if let Some(unbound) = unbound {
4076 let mut bounds_as_vec = bounds.into_vec();
4077 bounds_as_vec.push(TraitTyParamBound(PolyTraitRef { bound_lifetimes: vec![],
4078 trait_ref: unbound },
4079 TraitBoundModifier::Maybe));
4080 bounds = OwnedSlice::from_vec(bounds_as_vec);
4083 let default = if self.check(&token::Eq) {
4085 Some(self.parse_ty_sum())
4091 id: ast::DUMMY_NODE_ID,
4098 /// Parse a set of optional generic type parameter declarations. Where
4099 /// clauses are not parsed here, and must be added later via
4100 /// `parse_where_clause()`.
4102 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
4103 /// | ( < lifetimes , typaramseq ( , )? > )
4104 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
4105 pub fn parse_generics(&mut self) -> ast::Generics {
4106 if self.eat(&token::Lt) {
4107 let lifetime_defs = self.parse_lifetime_defs();
4108 let mut seen_default = false;
4109 let ty_params = self.parse_seq_to_gt(Some(token::Comma), |p| {
4110 p.forbid_lifetime();
4111 let ty_param = p.parse_ty_param();
4112 if ty_param.default.is_some() {
4113 seen_default = true;
4114 } else if seen_default {
4115 let last_span = p.last_span;
4116 p.span_err(last_span,
4117 "type parameters with a default must be trailing");
4122 lifetimes: lifetime_defs,
4123 ty_params: ty_params,
4124 where_clause: WhereClause {
4125 id: ast::DUMMY_NODE_ID,
4126 predicates: Vec::new(),
4130 ast_util::empty_generics()
4134 fn parse_generic_values_after_lt(&mut self)
4135 -> (Vec<ast::Lifetime>, Vec<P<Ty>>, Vec<P<TypeBinding>>) {
4136 let lifetimes = self.parse_lifetimes(token::Comma);
4138 // First parse types.
4139 let (types, returned) = self.parse_seq_to_gt_or_return(
4142 p.forbid_lifetime();
4143 if p.look_ahead(1, |t| t == &token::Eq) {
4146 Some(p.parse_ty_sum())
4151 // If we found the `>`, don't continue.
4153 return (lifetimes, types.into_vec(), Vec::new());
4156 // Then parse type bindings.
4157 let bindings = self.parse_seq_to_gt(
4160 p.forbid_lifetime();
4162 let ident = p.parse_ident();
4163 let found_eq = p.eat(&token::Eq);
4166 p.span_warn(span, "whoops, no =?");
4168 let ty = p.parse_ty();
4170 let span = mk_sp(lo, hi);
4171 return P(TypeBinding{id: ast::DUMMY_NODE_ID,
4178 (lifetimes, types.into_vec(), bindings.into_vec())
4181 fn forbid_lifetime(&mut self) {
4182 if self.token.is_lifetime() {
4183 let span = self.span;
4184 self.span_fatal(span, "lifetime parameters must be declared \
4185 prior to type parameters");
4189 /// Parses an optional `where` clause and places it in `generics`.
4192 /// where T : Trait<U, V> + 'b, 'a : 'b
4194 fn parse_where_clause(&mut self, generics: &mut ast::Generics) {
4195 if !self.eat_keyword(keywords::Where) {
4199 let mut parsed_something = false;
4201 let lo = self.span.lo;
4203 token::OpenDelim(token::Brace) => {
4207 token::Lifetime(..) => {
4208 let bounded_lifetime =
4209 self.parse_lifetime();
4211 self.eat(&token::Colon);
4214 self.parse_lifetimes(token::BinOp(token::Plus));
4216 let hi = self.span.hi;
4217 let span = mk_sp(lo, hi);
4219 generics.where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
4220 ast::WhereRegionPredicate {
4222 lifetime: bounded_lifetime,
4227 parsed_something = true;
4231 let bounded_ty = self.parse_ty();
4233 if self.eat(&token::Colon) {
4234 let bounds = self.parse_ty_param_bounds(BoundParsingMode::Bare);
4235 let hi = self.span.hi;
4236 let span = mk_sp(lo, hi);
4238 if bounds.len() == 0 {
4240 "each predicate in a `where` clause must have \
4241 at least one bound in it");
4244 generics.where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
4245 ast::WhereBoundPredicate {
4247 bounded_ty: bounded_ty,
4251 parsed_something = true;
4252 } else if self.eat(&token::Eq) {
4253 // let ty = self.parse_ty();
4254 let hi = self.span.hi;
4255 let span = mk_sp(lo, hi);
4256 // generics.where_clause.predicates.push(
4257 // ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
4258 // id: ast::DUMMY_NODE_ID,
4260 // path: panic!("NYI"), //bounded_ty,
4263 // parsed_something = true;
4266 "equality constraints are not yet supported \
4267 in where clauses (#20041)");
4269 let last_span = self.last_span;
4270 self.span_err(last_span,
4271 "unexpected token in `where` clause");
4276 if !self.eat(&token::Comma) {
4281 if !parsed_something {
4282 let last_span = self.last_span;
4283 self.span_err(last_span,
4284 "a `where` clause must have at least one predicate \
4289 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
4290 -> (Vec<Arg> , bool) {
4292 let mut args: Vec<Option<Arg>> =
4293 self.parse_unspanned_seq(
4294 &token::OpenDelim(token::Paren),
4295 &token::CloseDelim(token::Paren),
4296 seq_sep_trailing_allowed(token::Comma),
4298 if p.token == token::DotDotDot {
4301 if p.token != token::CloseDelim(token::Paren) {
4304 "`...` must be last in argument list for variadic function");
4309 "only foreign functions are allowed to be variadic");
4313 Some(p.parse_arg_general(named_args))
4318 let variadic = match args.pop() {
4321 // Need to put back that last arg
4328 if variadic && args.is_empty() {
4330 "variadic function must be declared with at least one named argument");
4333 let args = args.into_iter().map(|x| x.unwrap()).collect();
4338 /// Parse the argument list and result type of a function declaration
4339 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> P<FnDecl> {
4341 let (args, variadic) = self.parse_fn_args(true, allow_variadic);
4342 let ret_ty = self.parse_ret_ty();
4351 fn is_self_ident(&mut self) -> bool {
4353 token::Ident(id, token::Plain) => id.name == special_idents::self_.name,
4358 fn expect_self_ident(&mut self) -> ast::Ident {
4360 token::Ident(id, token::Plain) if id.name == special_idents::self_.name => {
4365 let token_str = self.this_token_to_string();
4366 self.fatal(&format!("expected `self`, found `{}`",
4372 /// Parse the argument list and result type of a function
4373 /// that may have a self type.
4374 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> (ExplicitSelf, P<FnDecl>) where
4375 F: FnMut(&mut Parser) -> Arg,
4377 fn maybe_parse_borrowed_explicit_self(this: &mut Parser)
4378 -> ast::ExplicitSelf_ {
4379 // The following things are possible to see here:
4384 // fn(&'lt mut self)
4386 // We already know that the current token is `&`.
4388 if this.look_ahead(1, |t| t.is_keyword(keywords::Self)) {
4390 SelfRegion(None, MutImmutable, this.expect_self_ident())
4391 } else if this.look_ahead(1, |t| t.is_mutability()) &&
4392 this.look_ahead(2, |t| t.is_keyword(keywords::Self)) {
4394 let mutability = this.parse_mutability();
4395 SelfRegion(None, mutability, this.expect_self_ident())
4396 } else if this.look_ahead(1, |t| t.is_lifetime()) &&
4397 this.look_ahead(2, |t| t.is_keyword(keywords::Self)) {
4399 let lifetime = this.parse_lifetime();
4400 SelfRegion(Some(lifetime), MutImmutable, this.expect_self_ident())
4401 } else if this.look_ahead(1, |t| t.is_lifetime()) &&
4402 this.look_ahead(2, |t| t.is_mutability()) &&
4403 this.look_ahead(3, |t| t.is_keyword(keywords::Self)) {
4405 let lifetime = this.parse_lifetime();
4406 let mutability = this.parse_mutability();
4407 SelfRegion(Some(lifetime), mutability, this.expect_self_ident())
4413 self.expect(&token::OpenDelim(token::Paren));
4415 // A bit of complexity and lookahead is needed here in order to be
4416 // backwards compatible.
4417 let lo = self.span.lo;
4418 let mut self_ident_lo = self.span.lo;
4419 let mut self_ident_hi = self.span.hi;
4421 let mut mutbl_self = MutImmutable;
4422 let explicit_self = match self.token {
4423 token::BinOp(token::And) => {
4424 let eself = maybe_parse_borrowed_explicit_self(self);
4425 self_ident_lo = self.last_span.lo;
4426 self_ident_hi = self.last_span.hi;
4429 token::BinOp(token::Star) => {
4430 // Possibly "*self" or "*mut self" -- not supported. Try to avoid
4431 // emitting cryptic "unexpected token" errors.
4433 let _mutability = if self.token.is_mutability() {
4434 self.parse_mutability()
4438 if self.is_self_ident() {
4439 let span = self.span;
4440 self.span_err(span, "cannot pass self by unsafe pointer");
4443 // error case, making bogus self ident:
4444 SelfValue(special_idents::self_)
4446 token::Ident(..) => {
4447 if self.is_self_ident() {
4448 let self_ident = self.expect_self_ident();
4450 // Determine whether this is the fully explicit form, `self:
4452 if self.eat(&token::Colon) {
4453 SelfExplicit(self.parse_ty_sum(), self_ident)
4455 SelfValue(self_ident)
4457 } else if self.token.is_mutability() &&
4458 self.look_ahead(1, |t| t.is_keyword(keywords::Self)) {
4459 mutbl_self = self.parse_mutability();
4460 let self_ident = self.expect_self_ident();
4462 // Determine whether this is the fully explicit form,
4464 if self.eat(&token::Colon) {
4465 SelfExplicit(self.parse_ty_sum(), self_ident)
4467 SelfValue(self_ident)
4476 let explicit_self_sp = mk_sp(self_ident_lo, self_ident_hi);
4478 // shared fall-through for the three cases below. borrowing prevents simply
4479 // writing this as a closure
4480 macro_rules! parse_remaining_arguments {
4483 // If we parsed a self type, expect a comma before the argument list.
4487 let sep = seq_sep_trailing_allowed(token::Comma);
4488 let mut fn_inputs = self.parse_seq_to_before_end(
4489 &token::CloseDelim(token::Paren),
4493 fn_inputs.insert(0, Arg::new_self(explicit_self_sp, mutbl_self, $self_id));
4496 token::CloseDelim(token::Paren) => {
4497 vec!(Arg::new_self(explicit_self_sp, mutbl_self, $self_id))
4500 let token_str = self.this_token_to_string();
4501 self.fatal(&format!("expected `,` or `)`, found `{}`",
4508 let fn_inputs = match explicit_self {
4510 let sep = seq_sep_trailing_allowed(token::Comma);
4511 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)
4513 SelfValue(id) => parse_remaining_arguments!(id),
4514 SelfRegion(_,_,id) => parse_remaining_arguments!(id),
4515 SelfExplicit(_,id) => parse_remaining_arguments!(id),
4519 self.expect(&token::CloseDelim(token::Paren));
4521 let hi = self.span.hi;
4523 let ret_ty = self.parse_ret_ty();
4525 let fn_decl = P(FnDecl {
4531 (spanned(lo, hi, explicit_self), fn_decl)
4534 // parse the |arg, arg| header on a lambda
4535 fn parse_fn_block_decl(&mut self)
4536 -> (P<FnDecl>, Option<UnboxedClosureKind>) {
4537 let (optional_unboxed_closure_kind, inputs_captures) = {
4538 if self.eat(&token::OrOr) {
4541 self.expect(&token::BinOp(token::Or));
4542 let optional_unboxed_closure_kind =
4543 self.parse_optional_unboxed_closure_kind();
4544 let args = self.parse_seq_to_before_end(
4545 &token::BinOp(token::Or),
4546 seq_sep_trailing_allowed(token::Comma),
4547 |p| p.parse_fn_block_arg()
4550 (optional_unboxed_closure_kind, args)
4553 let output = if self.check(&token::RArrow) {
4557 id: ast::DUMMY_NODE_ID,
4564 inputs: inputs_captures,
4567 }), optional_unboxed_closure_kind)
4570 /// Parses the `(arg, arg) -> return_type` header on a procedure.
4571 fn parse_proc_decl(&mut self) -> P<FnDecl> {
4573 self.parse_unspanned_seq(&token::OpenDelim(token::Paren),
4574 &token::CloseDelim(token::Paren),
4575 seq_sep_trailing_allowed(token::Comma),
4576 |p| p.parse_fn_block_arg());
4578 let output = if self.check(&token::RArrow) {
4582 id: ast::DUMMY_NODE_ID,
4595 /// Parse the name and optional generic types of a function header.
4596 fn parse_fn_header(&mut self) -> (Ident, ast::Generics) {
4597 let id = self.parse_ident();
4598 let generics = self.parse_generics();
4602 fn mk_item(&mut self, lo: BytePos, hi: BytePos, ident: Ident,
4603 node: Item_, vis: Visibility,
4604 attrs: Vec<Attribute>) -> P<Item> {
4608 id: ast::DUMMY_NODE_ID,
4615 /// Parse an item-position function declaration.
4616 fn parse_item_fn(&mut self, unsafety: Unsafety, abi: abi::Abi) -> ItemInfo {
4617 let (ident, mut generics) = self.parse_fn_header();
4618 let decl = self.parse_fn_decl(false);
4619 self.parse_where_clause(&mut generics);
4620 let (inner_attrs, body) = self.parse_inner_attrs_and_block();
4621 (ident, ItemFn(decl, unsafety, abi, generics, body), Some(inner_attrs))
4624 /// Parse a method in a trait impl
4625 pub fn parse_method_with_outer_attributes(&mut self) -> P<Method> {
4626 let attrs = self.parse_outer_attributes();
4627 let visa = self.parse_visibility();
4628 self.parse_method(attrs, visa)
4631 /// Parse a method in a trait impl, starting with `attrs` attributes.
4632 pub fn parse_method(&mut self,
4633 attrs: Vec<Attribute>,
4636 let lo = self.span.lo;
4638 // code copied from parse_macro_use_or_failure... abstraction!
4639 let (method_, hi, new_attrs) = {
4640 if !self.token.is_any_keyword()
4641 && self.look_ahead(1, |t| *t == token::Not)
4642 && (self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren))
4643 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) {
4645 let pth = self.parse_path(NoTypesAllowed);
4646 self.expect(&token::Not);
4648 // eat a matched-delimiter token tree:
4649 let delim = self.expect_open_delim();
4650 let tts = self.parse_seq_to_end(&token::CloseDelim(delim),
4652 |p| p.parse_token_tree());
4653 let m_ = ast::MacInvocTT(pth, tts, EMPTY_CTXT);
4654 let m: ast::Mac = codemap::Spanned { node: m_,
4655 span: mk_sp(self.span.lo,
4657 if delim != token::Brace {
4658 self.expect(&token::Semi)
4660 (ast::MethMac(m), self.span.hi, attrs)
4662 let unsafety = self.parse_unsafety();
4663 let abi = if self.eat_keyword(keywords::Extern) {
4664 self.parse_opt_abi().unwrap_or(abi::C)
4668 self.expect_keyword(keywords::Fn);
4669 let ident = self.parse_ident();
4670 let mut generics = self.parse_generics();
4671 let (explicit_self, decl) = self.parse_fn_decl_with_self(|p| {
4674 self.parse_where_clause(&mut generics);
4675 let (inner_attrs, body) = self.parse_inner_attrs_and_block();
4676 let body_span = body.span;
4677 let mut new_attrs = attrs;
4678 new_attrs.push_all(&inner_attrs[]);
4679 (ast::MethDecl(ident,
4687 body_span.hi, new_attrs)
4692 id: ast::DUMMY_NODE_ID,
4693 span: mk_sp(lo, hi),
4698 /// Parse trait Foo { ... }
4699 fn parse_item_trait(&mut self, unsafety: Unsafety) -> ItemInfo {
4700 let ident = self.parse_ident();
4701 let mut tps = self.parse_generics();
4702 let unbound = self.parse_for_sized();
4704 // Parse supertrait bounds.
4705 let mut bounds = self.parse_colon_then_ty_param_bounds(BoundParsingMode::Bare);
4707 if let Some(unbound) = unbound {
4708 let mut bounds_as_vec = bounds.into_vec();
4709 bounds_as_vec.push(TraitTyParamBound(PolyTraitRef { bound_lifetimes: vec![],
4710 trait_ref: unbound },
4711 TraitBoundModifier::Maybe));
4712 bounds = OwnedSlice::from_vec(bounds_as_vec);
4715 self.parse_where_clause(&mut tps);
4717 let meths = self.parse_trait_items();
4718 (ident, ItemTrait(unsafety, tps, bounds, meths), None)
4721 fn parse_impl_items(&mut self) -> (Vec<ImplItem>, Vec<Attribute>) {
4722 let mut impl_items = Vec::new();
4723 self.expect(&token::OpenDelim(token::Brace));
4724 let (inner_attrs, mut method_attrs) =
4725 self.parse_inner_attrs_and_next();
4727 method_attrs.extend(self.parse_outer_attributes().into_iter());
4728 if method_attrs.is_empty() && self.eat(&token::CloseDelim(token::Brace)) {
4732 let vis = self.parse_visibility();
4733 if self.eat_keyword(keywords::Type) {
4734 impl_items.push(TypeImplItem(P(self.parse_typedef(
4738 impl_items.push(MethodImplItem(self.parse_method(
4742 method_attrs = vec![];
4744 (impl_items, inner_attrs)
4747 /// Parses two variants (with the region/type params always optional):
4748 /// impl<T> Foo { ... }
4749 /// impl<T> ToString for ~[T] { ... }
4750 fn parse_item_impl(&mut self, unsafety: ast::Unsafety) -> ItemInfo {
4751 // First, parse type parameters if necessary.
4752 let mut generics = self.parse_generics();
4754 // Special case: if the next identifier that follows is '(', don't
4755 // allow this to be parsed as a trait.
4756 let could_be_trait = self.token != token::OpenDelim(token::Paren);
4758 let neg_span = self.span;
4759 let polarity = if self.eat(&token::Not) {
4760 ast::ImplPolarity::Negative
4762 ast::ImplPolarity::Positive
4766 let mut ty = self.parse_ty_sum();
4768 // Parse traits, if necessary.
4769 let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) {
4770 // New-style trait. Reinterpret the type as a trait.
4771 let opt_trait_ref = match ty.node {
4772 TyPath(ref path, node_id) => {
4774 path: (*path).clone(),
4779 self.span_err(ty.span, "not a trait");
4784 ty = self.parse_ty_sum();
4788 ast::ImplPolarity::Negative => {
4789 // This is a negated type implementation
4790 // `impl !MyType {}`, which is not allowed.
4791 self.span_err(neg_span, "inherent implementation can't be negated");
4798 self.parse_where_clause(&mut generics);
4799 let (impl_items, attrs) = self.parse_impl_items();
4801 let ident = ast_util::impl_pretty_name(&opt_trait, &*ty);
4804 ItemImpl(unsafety, polarity, generics, opt_trait, ty, impl_items),
4808 /// Parse a::B<String,int>
4809 fn parse_trait_ref(&mut self) -> TraitRef {
4811 path: self.parse_path(LifetimeAndTypesWithoutColons),
4812 ref_id: ast::DUMMY_NODE_ID,
4816 fn parse_late_bound_lifetime_defs(&mut self) -> Vec<ast::LifetimeDef> {
4817 if self.eat_keyword(keywords::For) {
4818 self.expect(&token::Lt);
4819 let lifetime_defs = self.parse_lifetime_defs();
4827 /// Parse for<'l> a::B<String,int>
4828 fn parse_poly_trait_ref(&mut self) -> PolyTraitRef {
4829 let lifetime_defs = self.parse_late_bound_lifetime_defs();
4832 bound_lifetimes: lifetime_defs,
4833 trait_ref: self.parse_trait_ref()
4837 /// Parse struct Foo { ... }
4838 fn parse_item_struct(&mut self) -> ItemInfo {
4839 let class_name = self.parse_ident();
4840 let mut generics = self.parse_generics();
4842 if self.eat(&token::Colon) {
4843 let ty = self.parse_ty_sum();
4844 self.span_err(ty.span, "`virtual` structs have been removed from the language");
4847 // There is a special case worth noting here, as reported in issue #17904.
4848 // If we are parsing a tuple struct it is the case that the where clause
4849 // should follow the field list. Like so:
4851 // struct Foo<T>(T) where T: Copy;
4853 // If we are parsing a normal record-style struct it is the case
4854 // that the where clause comes before the body, and after the generics.
4855 // So if we look ahead and see a brace or a where-clause we begin
4856 // parsing a record style struct.
4858 // Otherwise if we look ahead and see a paren we parse a tuple-style
4861 let (fields, ctor_id) = if self.token.is_keyword(keywords::Where) {
4862 self.parse_where_clause(&mut generics);
4863 if self.eat(&token::Semi) {
4864 // If we see a: `struct Foo<T> where T: Copy;` style decl.
4865 (Vec::new(), Some(ast::DUMMY_NODE_ID))
4867 // If we see: `struct Foo<T> where T: Copy { ... }`
4868 (self.parse_record_struct_body(&class_name), None)
4870 // No `where` so: `struct Foo<T>;`
4871 } else if self.eat(&token::Semi) {
4872 (Vec::new(), Some(ast::DUMMY_NODE_ID))
4873 // Record-style struct definition
4874 } else if self.token == token::OpenDelim(token::Brace) {
4875 let fields = self.parse_record_struct_body(&class_name);
4877 // Tuple-style struct definition with optional where-clause.
4879 let fields = self.parse_tuple_struct_body(&class_name, &mut generics);
4880 (fields, Some(ast::DUMMY_NODE_ID))
4884 ItemStruct(P(ast::StructDef {
4891 pub fn parse_record_struct_body(&mut self, class_name: &ast::Ident) -> Vec<StructField> {
4892 let mut fields = Vec::new();
4893 if self.eat(&token::OpenDelim(token::Brace)) {
4894 while self.token != token::CloseDelim(token::Brace) {
4895 fields.push(self.parse_struct_decl_field(true));
4898 if fields.len() == 0 {
4899 self.fatal(&format!("unit-like struct definition should be \
4900 written as `struct {};`",
4901 token::get_ident(class_name.clone()))[]);
4906 let token_str = self.this_token_to_string();
4907 self.fatal(&format!("expected `where`, or `{}` after struct \
4908 name, found `{}`", "{",
4915 pub fn parse_tuple_struct_body(&mut self,
4916 class_name: &ast::Ident,
4917 generics: &mut ast::Generics)
4918 -> Vec<StructField> {
4919 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
4920 if self.check(&token::OpenDelim(token::Paren)) {
4921 let fields = self.parse_unspanned_seq(
4922 &token::OpenDelim(token::Paren),
4923 &token::CloseDelim(token::Paren),
4924 seq_sep_trailing_allowed(token::Comma),
4926 let attrs = p.parse_outer_attributes();
4928 let struct_field_ = ast::StructField_ {
4929 kind: UnnamedField(p.parse_visibility()),
4930 id: ast::DUMMY_NODE_ID,
4931 ty: p.parse_ty_sum(),
4934 spanned(lo, p.span.hi, struct_field_)
4937 if fields.len() == 0 {
4938 self.fatal(&format!("unit-like struct definition should be \
4939 written as `struct {};`",
4940 token::get_ident(class_name.clone()))[]);
4943 self.parse_where_clause(generics);
4944 self.expect(&token::Semi);
4946 // This is the case where we just see struct Foo<T> where T: Copy;
4947 } else if self.token.is_keyword(keywords::Where) {
4948 self.parse_where_clause(generics);
4949 self.expect(&token::Semi);
4951 // This case is where we see: `struct Foo<T>;`
4953 let token_str = self.this_token_to_string();
4954 self.fatal(&format!("expected `where`, `{}`, `(`, or `;` after struct \
4955 name, found `{}`", "{", token_str)[]);
4959 /// Parse a structure field declaration
4960 pub fn parse_single_struct_field(&mut self,
4962 attrs: Vec<Attribute> )
4964 let a_var = self.parse_name_and_ty(vis, attrs);
4969 token::CloseDelim(token::Brace) => {}
4971 let span = self.span;
4972 let token_str = self.this_token_to_string();
4973 self.span_fatal_help(span,
4974 &format!("expected `,`, or `}}`, found `{}`",
4976 "struct fields should be separated by commas")
4982 /// Parse an element of a struct definition
4983 fn parse_struct_decl_field(&mut self, allow_pub: bool) -> StructField {
4985 let attrs = self.parse_outer_attributes();
4987 if self.eat_keyword(keywords::Pub) {
4989 let span = self.last_span;
4990 self.span_err(span, "`pub` is not allowed here");
4992 return self.parse_single_struct_field(Public, attrs);
4995 return self.parse_single_struct_field(Inherited, attrs);
4998 /// Parse visibility: PUB, PRIV, or nothing
4999 fn parse_visibility(&mut self) -> Visibility {
5000 if self.eat_keyword(keywords::Pub) { Public }
5004 fn parse_for_sized(&mut self) -> Option<ast::TraitRef> {
5005 // FIXME, this should really use TraitBoundModifier, but it will get
5006 // re-jigged shortly in any case, so leaving the hacky version for now.
5007 if self.eat_keyword(keywords::For) {
5008 let span = self.span;
5010 let mut ate_question = false;
5011 if self.eat(&token::Question) {
5012 ate_question = true;
5014 let ident = self.parse_ident();
5015 if self.eat(&token::Question) {
5020 ate_question = true;
5024 "expected `?Sized` after `for` in trait item");
5027 let _tref = Parser::trait_ref_from_ident(ident, span);
5029 self.obsolete(span, ObsoleteSyntax::ForSized);
5037 /// Given a termination token and a vector of already-parsed
5038 /// attributes (of length 0 or 1), parse all of the items in a module
5039 fn parse_mod_items(&mut self,
5041 first_item_attrs: Vec<Attribute>,
5044 // parse all of the items up to closing or an attribute.
5045 // view items are legal here.
5046 let ParsedItemsAndViewItems {
5049 items: starting_items,
5051 } = self.parse_items_and_view_items(first_item_attrs, true, true);
5052 let mut items: Vec<P<Item>> = starting_items;
5053 let attrs_remaining_len = attrs_remaining.len();
5055 // don't think this other loop is even necessary....
5057 let mut first = true;
5058 while self.token != term {
5059 let mut attrs = self.parse_outer_attributes();
5061 let mut tmp = attrs_remaining.clone();
5062 tmp.push_all(&attrs[]);
5066 debug!("parse_mod_items: parse_item_or_view_item(attrs={:?})",
5068 match self.parse_item_or_view_item(attrs,
5069 true /* macros allowed */) {
5070 IoviItem(item) => items.push(item),
5071 IoviViewItem(view_item) => {
5072 self.span_fatal(view_item.span,
5073 "view items must be declared at the top of \
5077 let token_str = self.this_token_to_string();
5078 self.fatal(&format!("expected item, found `{}`",
5084 if first && attrs_remaining_len > 0u {
5085 // We parsed attributes for the first item but didn't find it
5086 let last_span = self.last_span;
5087 self.span_err(last_span,
5088 Parser::expected_item_err(&attrs_remaining[]));
5092 inner: mk_sp(inner_lo, self.span.lo),
5093 view_items: view_items,
5098 fn parse_item_const(&mut self, m: Option<Mutability>) -> ItemInfo {
5099 let id = self.parse_ident();
5100 self.expect(&token::Colon);
5101 let ty = self.parse_ty_sum();
5102 self.expect(&token::Eq);
5103 let e = self.parse_expr();
5104 self.commit_expr_expecting(&*e, token::Semi);
5105 let item = match m {
5106 Some(m) => ItemStatic(ty, m, e),
5107 None => ItemConst(ty, e),
5112 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
5113 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> ItemInfo {
5114 let id_span = self.span;
5115 let id = self.parse_ident();
5116 if self.check(&token::Semi) {
5118 // This mod is in an external file. Let's go get it!
5119 let (m, attrs) = self.eval_src_mod(id, outer_attrs, id_span);
5120 (id, m, Some(attrs))
5122 self.push_mod_path(id, outer_attrs);
5123 self.expect(&token::OpenDelim(token::Brace));
5124 let mod_inner_lo = self.span.lo;
5125 let old_owns_directory = self.owns_directory;
5126 self.owns_directory = true;
5127 let (inner, next) = self.parse_inner_attrs_and_next();
5128 let m = self.parse_mod_items(token::CloseDelim(token::Brace), next, mod_inner_lo);
5129 self.expect(&token::CloseDelim(token::Brace));
5130 self.owns_directory = old_owns_directory;
5131 self.pop_mod_path();
5132 (id, ItemMod(m), Some(inner))
5136 fn push_mod_path(&mut self, id: Ident, attrs: &[Attribute]) {
5137 let default_path = self.id_to_interned_str(id);
5138 let file_path = match ::attr::first_attr_value_str_by_name(attrs,
5141 None => default_path,
5143 self.mod_path_stack.push(file_path)
5146 fn pop_mod_path(&mut self) {
5147 self.mod_path_stack.pop().unwrap();
5150 /// Read a module from a source file.
5151 fn eval_src_mod(&mut self,
5153 outer_attrs: &[ast::Attribute],
5155 -> (ast::Item_, Vec<ast::Attribute> ) {
5156 let mut prefix = Path::new(self.sess.span_diagnostic.cm.span_to_filename(self.span));
5158 let mod_path = Path::new(".").join_many(&self.mod_path_stack[]);
5159 let dir_path = prefix.join(&mod_path);
5160 let mod_string = token::get_ident(id);
5161 let (file_path, owns_directory) = match ::attr::first_attr_value_str_by_name(
5162 outer_attrs, "path") {
5163 Some(d) => (dir_path.join(d), true),
5165 let mod_name = mod_string.get().to_string();
5166 let default_path_str = format!("{}.rs", mod_name);
5167 let secondary_path_str = format!("{}/mod.rs", mod_name);
5168 let default_path = dir_path.join(&default_path_str[]);
5169 let secondary_path = dir_path.join(&secondary_path_str[]);
5170 let default_exists = default_path.exists();
5171 let secondary_exists = secondary_path.exists();
5173 if !self.owns_directory {
5174 self.span_err(id_sp,
5175 "cannot declare a new module at this location");
5176 let this_module = match self.mod_path_stack.last() {
5177 Some(name) => name.get().to_string(),
5178 None => self.root_module_name.as_ref().unwrap().clone(),
5180 self.span_note(id_sp,
5181 &format!("maybe move this module `{0}` \
5182 to its own directory via \
5185 if default_exists || secondary_exists {
5186 self.span_note(id_sp,
5187 &format!("... or maybe `use` the module \
5188 `{}` instead of possibly \
5192 self.abort_if_errors();
5195 match (default_exists, secondary_exists) {
5196 (true, false) => (default_path, false),
5197 (false, true) => (secondary_path, true),
5199 self.span_fatal_help(id_sp,
5200 &format!("file not found for module `{}`",
5202 &format!("name the file either {} or {} inside \
5203 the directory {:?}",
5206 dir_path.display())[]);
5209 self.span_fatal_help(
5211 &format!("file for module `{}` found at both {} \
5215 secondary_path_str)[],
5216 "delete or rename one of them to remove the ambiguity");
5222 self.eval_src_mod_from_path(file_path, owns_directory,
5223 mod_string.get().to_string(), id_sp)
5226 fn eval_src_mod_from_path(&mut self,
5228 owns_directory: bool,
5230 id_sp: Span) -> (ast::Item_, Vec<ast::Attribute> ) {
5231 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
5232 match included_mod_stack.iter().position(|p| *p == path) {
5234 let mut err = String::from_str("circular modules: ");
5235 let len = included_mod_stack.len();
5236 for p in included_mod_stack.slice(i, len).iter() {
5237 err.push_str(&p.display().as_cow()[]);
5238 err.push_str(" -> ");
5240 err.push_str(&path.display().as_cow()[]);
5241 self.span_fatal(id_sp, &err[]);
5245 included_mod_stack.push(path.clone());
5246 drop(included_mod_stack);
5249 new_sub_parser_from_file(self.sess,
5255 let mod_inner_lo = p0.span.lo;
5256 let (mod_attrs, next) = p0.parse_inner_attrs_and_next();
5257 let first_item_outer_attrs = next;
5258 let m0 = p0.parse_mod_items(token::Eof, first_item_outer_attrs, mod_inner_lo);
5259 self.sess.included_mod_stack.borrow_mut().pop();
5260 return (ast::ItemMod(m0), mod_attrs);
5263 /// Parse a function declaration from a foreign module
5264 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility,
5265 attrs: Vec<Attribute>) -> P<ForeignItem> {
5266 let lo = self.span.lo;
5267 self.expect_keyword(keywords::Fn);
5269 let (ident, mut generics) = self.parse_fn_header();
5270 let decl = self.parse_fn_decl(true);
5271 self.parse_where_clause(&mut generics);
5272 let hi = self.span.hi;
5273 self.expect(&token::Semi);
5274 P(ast::ForeignItem {
5277 node: ForeignItemFn(decl, generics),
5278 id: ast::DUMMY_NODE_ID,
5279 span: mk_sp(lo, hi),
5284 /// Parse a static item from a foreign module
5285 fn parse_item_foreign_static(&mut self, vis: ast::Visibility,
5286 attrs: Vec<Attribute>) -> P<ForeignItem> {
5287 let lo = self.span.lo;
5289 self.expect_keyword(keywords::Static);
5290 let mutbl = self.eat_keyword(keywords::Mut);
5292 let ident = self.parse_ident();
5293 self.expect(&token::Colon);
5294 let ty = self.parse_ty_sum();
5295 let hi = self.span.hi;
5296 self.expect(&token::Semi);
5300 node: ForeignItemStatic(ty, mutbl),
5301 id: ast::DUMMY_NODE_ID,
5302 span: mk_sp(lo, hi),
5307 /// At this point, this is essentially a wrapper for
5308 /// parse_foreign_items.
5309 fn parse_foreign_mod_items(&mut self,
5311 first_item_attrs: Vec<Attribute> )
5313 let ParsedItemsAndViewItems {
5318 } = self.parse_foreign_items(first_item_attrs, true);
5319 if !attrs_remaining.is_empty() {
5320 let last_span = self.last_span;
5321 self.span_err(last_span,
5322 Parser::expected_item_err(&attrs_remaining[]));
5324 assert!(self.token == token::CloseDelim(token::Brace));
5327 view_items: view_items,
5328 items: foreign_items
5332 /// Parse extern crate links
5336 /// extern crate url;
5337 /// extern crate foo = "bar"; //deprecated
5338 /// extern crate "bar" as foo;
5339 fn parse_item_extern_crate(&mut self,
5341 visibility: Visibility,
5342 attrs: Vec<Attribute> )
5345 let span = self.span;
5346 let (maybe_path, ident) = match self.token {
5347 token::Ident(..) => {
5348 let the_ident = self.parse_ident();
5349 let path = if self.eat_keyword(keywords::As) {
5350 // skip the ident if there is one
5351 if self.token.is_ident() { self.bump(); }
5353 self.span_err(span, "expected `;`, found `as`");
5354 self.span_help(span,
5355 &format!("perhaps you meant to enclose the crate name `{}` in \
5357 the_ident.as_str())[]);
5362 self.expect(&token::Semi);
5365 token::Literal(token::Str_(..), suf) | token::Literal(token::StrRaw(..), suf) => {
5367 self.expect_no_suffix(sp, "extern crate name", suf);
5368 // forgo the internal suffix check of `parse_str` to
5369 // avoid repeats (this unwrap will always succeed due
5370 // to the restriction of the `match`)
5371 let (s, style, _) = self.parse_optional_str().unwrap();
5372 self.expect_keyword(keywords::As);
5373 let the_ident = self.parse_ident();
5374 self.expect(&token::Semi);
5375 (Some((s, style)), the_ident)
5378 let span = self.span;
5379 let token_str = self.this_token_to_string();
5380 self.span_fatal(span,
5381 &format!("expected extern crate name but \
5387 IoviViewItem(ast::ViewItem {
5388 node: ViewItemExternCrate(ident, maybe_path, ast::DUMMY_NODE_ID),
5391 span: mk_sp(lo, self.last_span.hi)
5395 /// Parse `extern` for foreign ABIs
5398 /// `extern` is expected to have been
5399 /// consumed before calling this method
5405 fn parse_item_foreign_mod(&mut self,
5407 opt_abi: Option<abi::Abi>,
5408 visibility: Visibility,
5409 attrs: Vec<Attribute> )
5412 self.expect(&token::OpenDelim(token::Brace));
5414 let abi = opt_abi.unwrap_or(abi::C);
5416 let (inner, next) = self.parse_inner_attrs_and_next();
5417 let m = self.parse_foreign_mod_items(abi, next);
5418 self.expect(&token::CloseDelim(token::Brace));
5420 let last_span = self.last_span;
5421 let item = self.mk_item(lo,
5423 special_idents::invalid,
5426 maybe_append(attrs, Some(inner)));
5427 return IoviItem(item);
5430 /// Parse type Foo = Bar;
5431 fn parse_item_type(&mut self) -> ItemInfo {
5432 let ident = self.parse_ident();
5433 let mut tps = self.parse_generics();
5434 self.parse_where_clause(&mut tps);
5435 self.expect(&token::Eq);
5436 let ty = self.parse_ty_sum();
5437 self.expect(&token::Semi);
5438 (ident, ItemTy(ty, tps), None)
5441 /// Parse a structure-like enum variant definition
5442 /// this should probably be renamed or refactored...
5443 fn parse_struct_def(&mut self) -> P<StructDef> {
5444 let mut fields: Vec<StructField> = Vec::new();
5445 while self.token != token::CloseDelim(token::Brace) {
5446 fields.push(self.parse_struct_decl_field(false));
5456 /// Parse the part of an "enum" decl following the '{'
5457 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> EnumDef {
5458 let mut variants = Vec::new();
5459 let mut all_nullary = true;
5460 let mut any_disr = None;
5461 while self.token != token::CloseDelim(token::Brace) {
5462 let variant_attrs = self.parse_outer_attributes();
5463 let vlo = self.span.lo;
5465 let vis = self.parse_visibility();
5469 let mut args = Vec::new();
5470 let mut disr_expr = None;
5471 ident = self.parse_ident();
5472 if self.eat(&token::OpenDelim(token::Brace)) {
5473 // Parse a struct variant.
5474 all_nullary = false;
5475 let start_span = self.span;
5476 let struct_def = self.parse_struct_def();
5477 if struct_def.fields.len() == 0 {
5478 self.span_err(start_span,
5479 &format!("unit-like struct variant should be written \
5480 without braces, as `{},`",
5481 token::get_ident(ident))[]);
5483 kind = StructVariantKind(struct_def);
5484 } else if self.check(&token::OpenDelim(token::Paren)) {
5485 all_nullary = false;
5486 let arg_tys = self.parse_enum_variant_seq(
5487 &token::OpenDelim(token::Paren),
5488 &token::CloseDelim(token::Paren),
5489 seq_sep_trailing_allowed(token::Comma),
5490 |p| p.parse_ty_sum()
5492 for ty in arg_tys.into_iter() {
5493 args.push(ast::VariantArg {
5495 id: ast::DUMMY_NODE_ID,
5498 kind = TupleVariantKind(args);
5499 } else if self.eat(&token::Eq) {
5500 disr_expr = Some(self.parse_expr());
5501 any_disr = disr_expr.as_ref().map(|expr| expr.span);
5502 kind = TupleVariantKind(args);
5504 kind = TupleVariantKind(Vec::new());
5507 let vr = ast::Variant_ {
5509 attrs: variant_attrs,
5511 id: ast::DUMMY_NODE_ID,
5512 disr_expr: disr_expr,
5515 variants.push(P(spanned(vlo, self.last_span.hi, vr)));
5517 if !self.eat(&token::Comma) { break; }
5519 self.expect(&token::CloseDelim(token::Brace));
5521 Some(disr_span) if !all_nullary =>
5522 self.span_err(disr_span,
5523 "discriminator values can only be used with a c-like enum"),
5527 ast::EnumDef { variants: variants }
5530 /// Parse an "enum" declaration
5531 fn parse_item_enum(&mut self) -> ItemInfo {
5532 let id = self.parse_ident();
5533 let mut generics = self.parse_generics();
5534 self.parse_where_clause(&mut generics);
5535 self.expect(&token::OpenDelim(token::Brace));
5537 let enum_definition = self.parse_enum_def(&generics);
5538 (id, ItemEnum(enum_definition, generics), None)
5541 /// Parses a string as an ABI spec on an extern type or module. Consumes
5542 /// the `extern` keyword, if one is found.
5543 fn parse_opt_abi(&mut self) -> Option<abi::Abi> {
5545 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
5547 self.expect_no_suffix(sp, "ABI spec", suf);
5549 let the_string = s.as_str();
5550 match abi::lookup(the_string) {
5551 Some(abi) => Some(abi),
5553 let last_span = self.last_span;
5556 &format!("illegal ABI: expected one of [{}], \
5558 abi::all_names().connect(", "),
5569 /// Parse one of the items or view items allowed by the
5570 /// flags; on failure, return IoviNone.
5571 /// NB: this function no longer parses the items inside an
5573 fn parse_item_or_view_item(&mut self,
5574 attrs: Vec<Attribute> ,
5575 macros_allowed: bool)
5577 let nt_item = match self.token {
5578 token::Interpolated(token::NtItem(ref item)) => {
5579 Some((**item).clone())
5586 let mut attrs = attrs;
5587 mem::swap(&mut item.attrs, &mut attrs);
5588 item.attrs.extend(attrs.into_iter());
5589 return IoviItem(P(item));
5594 let lo = self.span.lo;
5596 let visibility = self.parse_visibility();
5598 // must be a view item:
5599 if self.eat_keyword(keywords::Use) {
5600 // USE ITEM (IoviViewItem)
5601 let view_item = self.parse_use();
5602 self.expect(&token::Semi);
5603 return IoviViewItem(ast::ViewItem {
5607 span: mk_sp(lo, self.last_span.hi)
5610 // either a view item or an item:
5611 if self.eat_keyword(keywords::Extern) {
5612 if self.eat_keyword(keywords::Crate) {
5613 return self.parse_item_extern_crate(lo, visibility, attrs);
5616 let opt_abi = self.parse_opt_abi();
5618 if self.eat_keyword(keywords::Fn) {
5619 // EXTERN FUNCTION ITEM
5620 let abi = opt_abi.unwrap_or(abi::C);
5621 let (ident, item_, extra_attrs) =
5622 self.parse_item_fn(Unsafety::Normal, abi);
5623 let last_span = self.last_span;
5624 let item = self.mk_item(lo,
5629 maybe_append(attrs, extra_attrs));
5630 return IoviItem(item);
5631 } else if self.check(&token::OpenDelim(token::Brace)) {
5632 return self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs);
5635 let span = self.span;
5636 let token_str = self.this_token_to_string();
5637 self.span_fatal(span,
5638 &format!("expected `{}` or `fn`, found `{}`", "{",
5642 if self.eat_keyword(keywords::Virtual) {
5643 let span = self.span;
5644 self.span_err(span, "`virtual` structs have been removed from the language");
5647 // the rest are all guaranteed to be items:
5648 if self.token.is_keyword(keywords::Static) {
5651 let m = if self.eat_keyword(keywords::Mut) {MutMutable} else {MutImmutable};
5652 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m));
5653 let last_span = self.last_span;
5654 let item = self.mk_item(lo,
5659 maybe_append(attrs, extra_attrs));
5660 return IoviItem(item);
5662 if self.token.is_keyword(keywords::Const) {
5665 if self.eat_keyword(keywords::Mut) {
5666 let last_span = self.last_span;
5667 self.span_err(last_span, "const globals cannot be mutable");
5668 self.span_help(last_span, "did you mean to declare a static?");
5670 let (ident, item_, extra_attrs) = self.parse_item_const(None);
5671 let last_span = self.last_span;
5672 let item = self.mk_item(lo,
5677 maybe_append(attrs, extra_attrs));
5678 return IoviItem(item);
5680 if self.token.is_keyword(keywords::Unsafe) &&
5681 self.look_ahead(1u, |t| t.is_keyword(keywords::Trait))
5683 // UNSAFE TRAIT ITEM
5684 self.expect_keyword(keywords::Unsafe);
5685 self.expect_keyword(keywords::Trait);
5686 let (ident, item_, extra_attrs) =
5687 self.parse_item_trait(ast::Unsafety::Unsafe);
5688 let last_span = self.last_span;
5689 let item = self.mk_item(lo,
5694 maybe_append(attrs, extra_attrs));
5695 return IoviItem(item);
5697 if self.token.is_keyword(keywords::Unsafe) &&
5698 self.look_ahead(1u, |t| t.is_keyword(keywords::Impl))
5701 self.expect_keyword(keywords::Unsafe);
5702 self.expect_keyword(keywords::Impl);
5703 let (ident, item_, extra_attrs) = self.parse_item_impl(ast::Unsafety::Unsafe);
5704 let last_span = self.last_span;
5705 let item = self.mk_item(lo,
5710 maybe_append(attrs, extra_attrs));
5711 return IoviItem(item);
5713 if self.token.is_keyword(keywords::Fn) {
5716 let (ident, item_, extra_attrs) =
5717 self.parse_item_fn(Unsafety::Normal, abi::Rust);
5718 let last_span = self.last_span;
5719 let item = self.mk_item(lo,
5724 maybe_append(attrs, extra_attrs));
5725 return IoviItem(item);
5727 if self.token.is_keyword(keywords::Unsafe)
5728 && self.look_ahead(1u, |t| *t != token::OpenDelim(token::Brace)) {
5729 // UNSAFE FUNCTION ITEM
5731 let abi = if self.eat_keyword(keywords::Extern) {
5732 self.parse_opt_abi().unwrap_or(abi::C)
5736 self.expect_keyword(keywords::Fn);
5737 let (ident, item_, extra_attrs) =
5738 self.parse_item_fn(Unsafety::Unsafe, abi);
5739 let last_span = self.last_span;
5740 let item = self.mk_item(lo,
5745 maybe_append(attrs, extra_attrs));
5746 return IoviItem(item);
5748 if self.eat_keyword(keywords::Mod) {
5750 let (ident, item_, extra_attrs) =
5751 self.parse_item_mod(&attrs[]);
5752 let last_span = self.last_span;
5753 let item = self.mk_item(lo,
5758 maybe_append(attrs, extra_attrs));
5759 return IoviItem(item);
5761 if self.eat_keyword(keywords::Type) {
5763 let (ident, item_, extra_attrs) = self.parse_item_type();
5764 let last_span = self.last_span;
5765 let item = self.mk_item(lo,
5770 maybe_append(attrs, extra_attrs));
5771 return IoviItem(item);
5773 if self.eat_keyword(keywords::Enum) {
5775 let (ident, item_, extra_attrs) = self.parse_item_enum();
5776 let last_span = self.last_span;
5777 let item = self.mk_item(lo,
5782 maybe_append(attrs, extra_attrs));
5783 return IoviItem(item);
5785 if self.eat_keyword(keywords::Trait) {
5787 let (ident, item_, extra_attrs) =
5788 self.parse_item_trait(ast::Unsafety::Normal);
5789 let last_span = self.last_span;
5790 let item = self.mk_item(lo,
5795 maybe_append(attrs, extra_attrs));
5796 return IoviItem(item);
5798 if self.eat_keyword(keywords::Impl) {
5800 let (ident, item_, extra_attrs) = self.parse_item_impl(ast::Unsafety::Normal);
5801 let last_span = self.last_span;
5802 let item = self.mk_item(lo,
5807 maybe_append(attrs, extra_attrs));
5808 return IoviItem(item);
5810 if self.eat_keyword(keywords::Struct) {
5812 let (ident, item_, extra_attrs) = self.parse_item_struct();
5813 let last_span = self.last_span;
5814 let item = self.mk_item(lo,
5819 maybe_append(attrs, extra_attrs));
5820 return IoviItem(item);
5822 self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility)
5825 /// Parse a foreign item; on failure, return IoviNone.
5826 fn parse_foreign_item(&mut self,
5827 attrs: Vec<Attribute> ,
5828 macros_allowed: bool)
5830 maybe_whole!(iovi self, NtItem);
5831 let lo = self.span.lo;
5833 let visibility = self.parse_visibility();
5835 if self.token.is_keyword(keywords::Static) {
5836 // FOREIGN STATIC ITEM
5837 let item = self.parse_item_foreign_static(visibility, attrs);
5838 return IoviForeignItem(item);
5840 if self.token.is_keyword(keywords::Fn) || self.token.is_keyword(keywords::Unsafe) {
5841 // FOREIGN FUNCTION ITEM
5842 let item = self.parse_item_foreign_fn(visibility, attrs);
5843 return IoviForeignItem(item);
5845 self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility)
5848 /// This is the fall-through for parsing items.
5849 fn parse_macro_use_or_failure(
5851 attrs: Vec<Attribute> ,
5852 macros_allowed: bool,
5854 visibility: Visibility
5855 ) -> ItemOrViewItem {
5856 if macros_allowed && !self.token.is_any_keyword()
5857 && self.look_ahead(1, |t| *t == token::Not)
5858 && (self.look_ahead(2, |t| t.is_plain_ident())
5859 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren))
5860 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) {
5861 // MACRO INVOCATION ITEM
5864 let pth = self.parse_path(NoTypesAllowed);
5865 self.expect(&token::Not);
5867 // a 'special' identifier (like what `macro_rules!` uses)
5868 // is optional. We should eventually unify invoc syntax
5870 let id = if self.token.is_plain_ident() {
5873 token::special_idents::invalid // no special identifier
5875 // eat a matched-delimiter token tree:
5876 let delim = self.expect_open_delim();
5877 let tts = self.parse_seq_to_end(&token::CloseDelim(delim),
5879 |p| p.parse_token_tree());
5880 // single-variant-enum... :
5881 let m = ast::MacInvocTT(pth, tts, EMPTY_CTXT);
5882 let m: ast::Mac = codemap::Spanned { node: m,
5883 span: mk_sp(self.span.lo,
5886 if delim != token::Brace {
5887 if !self.eat(&token::Semi) {
5888 let last_span = self.last_span;
5889 self.span_err(last_span,
5890 "macros that expand to items must either \
5891 be surrounded with braces or followed by \
5896 let item_ = ItemMac(m);
5897 let last_span = self.last_span;
5898 let item = self.mk_item(lo,
5904 return IoviItem(item);
5907 // FAILURE TO PARSE ITEM
5911 let last_span = self.last_span;
5912 self.span_fatal(last_span, "unmatched visibility `pub`");
5915 return IoviNone(attrs);
5918 pub fn parse_item_with_outer_attributes(&mut self) -> Option<P<Item>> {
5919 let attrs = self.parse_outer_attributes();
5920 self.parse_item(attrs)
5923 pub fn parse_item(&mut self, attrs: Vec<Attribute>) -> Option<P<Item>> {
5924 match self.parse_item_or_view_item(attrs, true) {
5925 IoviNone(_) => None,
5927 self.fatal("view items are not allowed here"),
5928 IoviForeignItem(_) =>
5929 self.fatal("foreign items are not allowed here"),
5930 IoviItem(item) => Some(item)
5934 /// Parse a ViewItem, e.g. `use foo::bar` or `extern crate foo`
5935 pub fn parse_view_item(&mut self, attrs: Vec<Attribute>) -> ViewItem {
5936 match self.parse_item_or_view_item(attrs, false) {
5937 IoviViewItem(vi) => vi,
5938 _ => self.fatal("expected `use` or `extern crate`"),
5942 /// Parse, e.g., "use a::b::{z,y}"
5943 fn parse_use(&mut self) -> ViewItem_ {
5944 return ViewItemUse(self.parse_view_path());
5948 /// Matches view_path : MOD? non_global_path as IDENT
5949 /// | MOD? non_global_path MOD_SEP LBRACE RBRACE
5950 /// | MOD? non_global_path MOD_SEP LBRACE ident_seq RBRACE
5951 /// | MOD? non_global_path MOD_SEP STAR
5952 /// | MOD? non_global_path
5953 fn parse_view_path(&mut self) -> P<ViewPath> {
5954 let lo = self.span.lo;
5956 // Allow a leading :: because the paths are absolute either way.
5957 // This occurs with "use $crate::..." in macros.
5958 self.eat(&token::ModSep);
5960 if self.check(&token::OpenDelim(token::Brace)) {
5962 let idents = self.parse_unspanned_seq(
5963 &token::OpenDelim(token::Brace),
5964 &token::CloseDelim(token::Brace),
5965 seq_sep_trailing_allowed(token::Comma),
5966 |p| p.parse_path_list_item());
5967 let path = ast::Path {
5968 span: mk_sp(lo, self.span.hi),
5970 segments: Vec::new()
5972 return P(spanned(lo, self.span.hi,
5973 ViewPathList(path, idents, ast::DUMMY_NODE_ID)));
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(i, _) => {
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,
6008 ViewPathList(path, idents, ast::DUMMY_NODE_ID)));
6012 token::BinOp(token::Star) => {
6014 let path = ast::Path {
6015 span: mk_sp(lo, self.span.hi),
6017 segments: path.into_iter().map(|identifier| {
6019 identifier: identifier,
6020 parameters: ast::PathParameters::none(),
6024 return P(spanned(lo, self.span.hi,
6025 ViewPathGlob(path, ast::DUMMY_NODE_ID)));
6032 let mut rename_to = path[path.len() - 1u];
6033 let path = ast::Path {
6034 span: mk_sp(lo, self.last_span.hi),
6036 segments: path.into_iter().map(|identifier| {
6038 identifier: identifier,
6039 parameters: ast::PathParameters::none(),
6043 if self.eat_keyword(keywords::As) {
6044 rename_to = self.parse_ident()
6048 ViewPathSimple(rename_to, path, ast::DUMMY_NODE_ID)))
6051 /// Parses a sequence of items. Stops when it finds program
6052 /// text that can't be parsed as an item
6053 /// - mod_items uses extern_mod_allowed = true
6054 /// - block_tail_ uses extern_mod_allowed = false
6055 fn parse_items_and_view_items(&mut self,
6056 first_item_attrs: Vec<Attribute> ,
6057 mut extern_mod_allowed: bool,
6058 macros_allowed: bool)
6059 -> ParsedItemsAndViewItems {
6060 let mut attrs = first_item_attrs;
6061 attrs.push_all(&self.parse_outer_attributes()[]);
6062 // First, parse view items.
6063 let mut view_items : Vec<ast::ViewItem> = Vec::new();
6064 let mut items = Vec::new();
6066 // I think this code would probably read better as a single
6067 // loop with a mutable three-state-variable (for extern crates,
6068 // view items, and regular items) ... except that because
6069 // of macros, I'd like to delay that entire check until later.
6071 match self.parse_item_or_view_item(attrs, macros_allowed) {
6072 IoviNone(attrs) => {
6073 return ParsedItemsAndViewItems {
6074 attrs_remaining: attrs,
6075 view_items: view_items,
6077 foreign_items: Vec::new()
6080 IoviViewItem(view_item) => {
6081 match view_item.node {
6082 ViewItemUse(..) => {
6083 // `extern crate` must precede `use`.
6084 extern_mod_allowed = false;
6086 ViewItemExternCrate(..) if !extern_mod_allowed => {
6087 self.span_err(view_item.span,
6088 "\"extern crate\" declarations are \
6091 ViewItemExternCrate(..) => {}
6093 view_items.push(view_item);
6097 attrs = self.parse_outer_attributes();
6100 IoviForeignItem(_) => {
6104 attrs = self.parse_outer_attributes();
6107 // Next, parse items.
6109 match self.parse_item_or_view_item(attrs, macros_allowed) {
6110 IoviNone(returned_attrs) => {
6111 attrs = returned_attrs;
6114 IoviViewItem(view_item) => {
6115 attrs = self.parse_outer_attributes();
6116 self.span_err(view_item.span,
6117 "`use` and `extern crate` declarations must precede items");
6120 attrs = self.parse_outer_attributes();
6123 IoviForeignItem(_) => {
6129 ParsedItemsAndViewItems {
6130 attrs_remaining: attrs,
6131 view_items: view_items,
6133 foreign_items: Vec::new()
6137 /// Parses a sequence of foreign items. Stops when it finds program
6138 /// text that can't be parsed as an item
6139 fn parse_foreign_items(&mut self, first_item_attrs: Vec<Attribute> ,
6140 macros_allowed: bool)
6141 -> ParsedItemsAndViewItems {
6142 let mut attrs = first_item_attrs;
6143 attrs.push_all(&self.parse_outer_attributes()[]);
6144 let mut foreign_items = Vec::new();
6146 match self.parse_foreign_item(attrs, macros_allowed) {
6147 IoviNone(returned_attrs) => {
6148 if self.check(&token::CloseDelim(token::Brace)) {
6149 attrs = returned_attrs;
6154 IoviViewItem(view_item) => {
6155 // I think this can't occur:
6156 self.span_err(view_item.span,
6157 "`use` and `extern crate` declarations must precede items");
6160 // FIXME #5668: this will occur for a macro invocation:
6161 self.span_fatal(item.span, "macros cannot expand to foreign items");
6163 IoviForeignItem(foreign_item) => {
6164 foreign_items.push(foreign_item);
6167 attrs = self.parse_outer_attributes();
6170 ParsedItemsAndViewItems {
6171 attrs_remaining: attrs,
6172 view_items: Vec::new(),
6174 foreign_items: foreign_items
6178 /// Parses a source module as a crate. This is the main
6179 /// entry point for the parser.
6180 pub fn parse_crate_mod(&mut self) -> Crate {
6181 let lo = self.span.lo;
6182 // parse the crate's inner attrs, maybe (oops) one
6183 // of the attrs of an item:
6184 let (inner, next) = self.parse_inner_attrs_and_next();
6185 let first_item_outer_attrs = next;
6186 // parse the items inside the crate:
6187 let m = self.parse_mod_items(token::Eof, first_item_outer_attrs, lo);
6192 config: self.cfg.clone(),
6193 span: mk_sp(lo, self.span.lo),
6194 exported_macros: Vec::new(),
6198 pub fn parse_optional_str(&mut self)
6199 -> Option<(InternedString, ast::StrStyle, Option<ast::Name>)> {
6200 let ret = match self.token {
6201 token::Literal(token::Str_(s), suf) => {
6202 (self.id_to_interned_str(s.ident()), ast::CookedStr, suf)
6204 token::Literal(token::StrRaw(s, n), suf) => {
6205 (self.id_to_interned_str(s.ident()), ast::RawStr(n), suf)
6213 pub fn parse_str(&mut self) -> (InternedString, StrStyle) {
6214 match self.parse_optional_str() {
6215 Some((s, style, suf)) => {
6216 let sp = self.last_span;
6217 self.expect_no_suffix(sp, "str literal", suf);
6220 _ => self.fatal("expected string literal")