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.
13 pub use self::PathParsingMode::*;
14 use self::ItemOrViewItem::*;
17 use ast::{AssociatedType, BareFnTy, ClosureTy};
18 use ast::{RegionTyParamBound, TraitTyParamBound, TraitBoundModifier};
19 use ast::{ProvidedMethod, Public, Unsafety};
20 use ast::{Mod, BiAdd, Arg, Arm, Attribute, BindByRef, BindByValue};
21 use ast::{BiBitAnd, BiBitOr, BiBitXor, BiRem, Block};
22 use ast::{BlockCheckMode, CaptureByRef, CaptureByValue, CaptureClause};
23 use ast::{Crate, CrateConfig, Decl, DeclItem};
24 use ast::{DeclLocal, DefaultBlock, UnDeref, BiDiv, EMPTY_CTXT, EnumDef, ExplicitSelf};
25 use ast::{Expr, Expr_, ExprAddrOf, ExprMatch, ExprAgain};
26 use ast::{ExprAssign, ExprAssignOp, ExprBinary, ExprBlock, ExprBox};
27 use ast::{ExprBreak, ExprCall, ExprCast};
28 use ast::{ExprField, ExprTupField, ExprClosure, ExprIf, ExprIfLet, ExprIndex};
29 use ast::{ExprLit, ExprLoop, ExprMac, ExprRange};
30 use ast::{ExprMethodCall, ExprParen, ExprPath};
31 use ast::{ExprRepeat, ExprRet, ExprStruct, ExprTup, ExprUnary};
32 use ast::{ExprVec, ExprWhile, ExprWhileLet, ExprForLoop, Field, FnDecl};
34 use ast::{FnUnboxedClosureKind, FnMutUnboxedClosureKind};
35 use ast::{FnOnceUnboxedClosureKind};
36 use ast::{ForeignItem, ForeignItemStatic, ForeignItemFn, ForeignMod, FunctionRetTy};
37 use ast::{Ident, Inherited, ImplItem, Item, Item_, ItemStatic};
38 use ast::{ItemEnum, ItemFn, ItemForeignMod, ItemImpl, ItemConst};
39 use ast::{ItemMac, ItemMod, ItemStruct, ItemTrait, ItemTy};
40 use ast::{LifetimeDef, Lit, Lit_};
41 use ast::{LitBool, LitChar, LitByte, LitBinary};
42 use ast::{LitStr, LitInt, Local, LocalLet};
43 use ast::{MacStmtWithBraces, MacStmtWithSemicolon, MacStmtWithoutBraces};
44 use ast::{MutImmutable, MutMutable, Mac_, MacInvocTT, MatchSource};
45 use ast::{Method, MutTy, BiMul, Mutability};
46 use ast::{MethodImplItem, NamedField, UnNeg, NoReturn, NodeId, UnNot};
47 use ast::{Pat, PatEnum, PatIdent, PatLit, PatRange, PatRegion, PatStruct};
48 use ast::{PatTup, PatBox, PatWild, PatWildMulti, PatWildSingle};
49 use ast::{PolyTraitRef};
50 use ast::{QPath, RequiredMethod};
51 use ast::{Return, BiShl, BiShr, Stmt, StmtDecl};
52 use ast::{StmtExpr, StmtSemi, StmtMac, StructDef, StructField};
53 use ast::{StructVariantKind, BiSub, StrStyle};
54 use ast::{SelfExplicit, SelfRegion, SelfStatic, SelfValue};
55 use ast::{Delimited, SequenceRepetition, TokenTree, TraitItem, TraitRef};
56 use ast::{TtDelimited, TtSequence, TtToken};
57 use ast::{TupleVariantKind, Ty, Ty_, TypeBinding};
58 use ast::{TypeField, TyFixedLengthVec, TyClosure, TyBareFn};
59 use ast::{TyTypeof, TyInfer, TypeMethod};
60 use ast::{TyParam, TyParamBound, TyParen, TyPath, TyPolyTraitRef, TyPtr, TyQPath};
61 use ast::{TyRptr, TyTup, TyU32, TyVec, UnUniq};
62 use ast::{TypeImplItem, TypeTraitItem, Typedef, UnboxedClosureKind};
63 use ast::{UnnamedField, UnsafeBlock};
64 use ast::{ViewItem, ViewItem_, ViewItemExternCrate, ViewItemUse};
65 use ast::{ViewPath, ViewPathGlob, ViewPathList, ViewPathSimple};
66 use ast::{Visibility, WhereClause};
68 use ast_util::{self, as_prec, ident_to_path, operator_prec};
69 use codemap::{self, Span, BytePos, Spanned, spanned, mk_sp, DUMMY_SP};
71 use ext::tt::macro_parser;
73 use parse::attr::ParserAttr;
75 use parse::common::{SeqSep, seq_sep_none, seq_sep_trailing_allowed};
76 use parse::lexer::{Reader, TokenAndSpan};
77 use parse::obsolete::*;
78 use parse::token::{self, MatchNt, SubstNt, InternedString};
79 use parse::token::{keywords, special_idents};
80 use parse::{new_sub_parser_from_file, ParseSess};
83 use owned_slice::OwnedSlice;
85 use std::collections::HashSet;
86 use std::io::fs::PathExtensions;
94 flags Restrictions: u8 {
95 const UNRESTRICTED = 0b0000,
96 const RESTRICTION_STMT_EXPR = 0b0001,
97 const RESTRICTION_NO_BAR_OP = 0b0010,
98 const RESTRICTION_NO_STRUCT_LITERAL = 0b0100,
99 const RESTRICTION_NO_DOTS = 0b1000,
104 type ItemInfo = (Ident, Item_, Option<Vec<Attribute> >);
106 /// How to parse a path. There are four different kinds of paths, all of which
107 /// are parsed somewhat differently.
108 #[derive(Copy, PartialEq)]
109 pub enum PathParsingMode {
110 /// A path with no type parameters; e.g. `foo::bar::Baz`
112 /// A path with a lifetime and type parameters, with no double colons
113 /// before the type parameters; e.g. `foo::bar<'a>::Baz<T>`
114 LifetimeAndTypesWithoutColons,
115 /// A path with a lifetime and type parameters with double colons before
116 /// the type parameters; e.g. `foo::bar::<'a>::Baz::<T>`
117 LifetimeAndTypesWithColons,
120 /// How to parse a bound, whether to allow bound modifiers such as `?`.
121 #[derive(Copy, PartialEq)]
122 pub enum BoundParsingMode {
127 enum ItemOrViewItem {
128 /// Indicates a failure to parse any kind of item. The attributes are
130 IoviNone(Vec<Attribute>),
132 IoviForeignItem(P<ForeignItem>),
133 IoviViewItem(ViewItem)
137 /// Possibly accept an `token::Interpolated` expression (a pre-parsed expression
138 /// dropped into the token stream, which happens while parsing the result of
139 /// macro expansion). Placement of these is not as complex as I feared it would
140 /// be. The important thing is to make sure that lookahead doesn't balk at
141 /// `token::Interpolated` tokens.
142 macro_rules! maybe_whole_expr {
145 let found = match $p.token {
146 token::Interpolated(token::NtExpr(ref e)) => {
149 token::Interpolated(token::NtPath(_)) => {
150 // FIXME: The following avoids an issue with lexical borrowck scopes,
151 // but the clone is unfortunate.
152 let pt = match $p.token {
153 token::Interpolated(token::NtPath(ref pt)) => (**pt).clone(),
157 Some($p.mk_expr(span.lo, span.hi, ExprPath(pt)))
159 token::Interpolated(token::NtBlock(_)) => {
160 // FIXME: The following avoids an issue with lexical borrowck scopes,
161 // but the clone is unfortunate.
162 let b = match $p.token {
163 token::Interpolated(token::NtBlock(ref b)) => (*b).clone(),
167 Some($p.mk_expr(span.lo, span.hi, ExprBlock(b)))
182 /// As maybe_whole_expr, but for things other than expressions
183 macro_rules! maybe_whole {
184 ($p:expr, $constructor:ident) => (
186 let found = match ($p).token {
187 token::Interpolated(token::$constructor(_)) => {
188 Some(($p).bump_and_get())
192 if let Some(token::Interpolated(token::$constructor(x))) = found {
197 (no_clone $p:expr, $constructor:ident) => (
199 let found = match ($p).token {
200 token::Interpolated(token::$constructor(_)) => {
201 Some(($p).bump_and_get())
205 if let Some(token::Interpolated(token::$constructor(x))) = found {
210 (deref $p:expr, $constructor:ident) => (
212 let found = match ($p).token {
213 token::Interpolated(token::$constructor(_)) => {
214 Some(($p).bump_and_get())
218 if let Some(token::Interpolated(token::$constructor(x))) = found {
223 (Some $p:expr, $constructor:ident) => (
225 let found = match ($p).token {
226 token::Interpolated(token::$constructor(_)) => {
227 Some(($p).bump_and_get())
231 if let Some(token::Interpolated(token::$constructor(x))) = found {
232 return Some(x.clone());
236 (iovi $p:expr, $constructor:ident) => (
238 let found = match ($p).token {
239 token::Interpolated(token::$constructor(_)) => {
240 Some(($p).bump_and_get())
244 if let Some(token::Interpolated(token::$constructor(x))) = found {
245 return IoviItem(x.clone());
249 (pair_empty $p:expr, $constructor:ident) => (
251 let found = match ($p).token {
252 token::Interpolated(token::$constructor(_)) => {
253 Some(($p).bump_and_get())
257 if let Some(token::Interpolated(token::$constructor(x))) = found {
258 return (Vec::new(), x);
265 fn maybe_append(mut lhs: Vec<Attribute>, rhs: Option<Vec<Attribute>>)
268 Some(ref attrs) => lhs.extend(attrs.iter().map(|a| a.clone())),
275 struct ParsedItemsAndViewItems {
276 attrs_remaining: Vec<Attribute>,
277 view_items: Vec<ViewItem>,
278 items: Vec<P<Item>> ,
279 foreign_items: Vec<P<ForeignItem>>
282 /* ident is handled by common.rs */
284 pub struct Parser<'a> {
285 pub sess: &'a ParseSess,
286 /// the current token:
287 pub token: token::Token,
288 /// the span of the current token:
290 /// the span of the prior token:
292 pub cfg: CrateConfig,
293 /// the previous token or None (only stashed sometimes).
294 pub last_token: Option<Box<token::Token>>,
295 pub buffer: [TokenAndSpan; 4],
296 pub buffer_start: int,
298 pub tokens_consumed: uint,
299 pub restrictions: Restrictions,
300 pub quote_depth: uint, // not (yet) related to the quasiquoter
301 pub reader: Box<Reader+'a>,
302 pub interner: Rc<token::IdentInterner>,
303 /// The set of seen errors about obsolete syntax. Used to suppress
304 /// extra detail when the same error is seen twice
305 pub obsolete_set: HashSet<ObsoleteSyntax>,
306 /// Used to determine the path to externally loaded source files
307 pub mod_path_stack: Vec<InternedString>,
308 /// Stack of spans of open delimiters. Used for error message.
309 pub open_braces: Vec<Span>,
310 /// Flag if this parser "owns" the directory that it is currently parsing
311 /// in. This will affect how nested files are looked up.
312 pub owns_directory: bool,
313 /// Name of the root module this parser originated from. If `None`, then the
314 /// name is not known. This does not change while the parser is descending
315 /// into modules, and sub-parsers have new values for this name.
316 pub root_module_name: Option<String>,
317 pub expected_tokens: Vec<TokenType>,
320 #[derive(PartialEq, Eq, Clone)]
327 fn to_string(&self) -> String {
329 TokenType::Token(ref t) => format!("`{}`", Parser::token_to_string(t)),
330 TokenType::Operator => "an operator".to_string(),
335 fn is_plain_ident_or_underscore(t: &token::Token) -> bool {
336 t.is_plain_ident() || *t == token::Underscore
339 impl<'a> Parser<'a> {
340 pub fn new(sess: &'a ParseSess,
341 cfg: ast::CrateConfig,
342 mut rdr: Box<Reader+'a>)
345 let tok0 = rdr.real_token();
347 let placeholder = TokenAndSpan {
348 tok: token::Underscore,
354 interner: token::get_ident_interner(),
370 restrictions: UNRESTRICTED,
372 obsolete_set: HashSet::new(),
373 mod_path_stack: Vec::new(),
374 open_braces: Vec::new(),
375 owns_directory: true,
376 root_module_name: None,
377 expected_tokens: Vec::new(),
381 /// Convert a token to a string using self's reader
382 pub fn token_to_string(token: &token::Token) -> String {
383 pprust::token_to_string(token)
386 /// Convert the current token to a string using self's reader
387 pub fn this_token_to_string(&mut self) -> String {
388 Parser::token_to_string(&self.token)
391 pub fn unexpected_last(&mut self, t: &token::Token) -> ! {
392 let token_str = Parser::token_to_string(t);
393 let last_span = self.last_span;
394 self.span_fatal(last_span, format!("unexpected token: `{}`",
398 pub fn unexpected(&mut self) -> ! {
399 let this_token = self.this_token_to_string();
400 self.fatal(format!("unexpected token: `{}`", this_token)[]);
403 /// Expect and consume the token t. Signal an error if
404 /// the next token is not t.
405 pub fn expect(&mut self, t: &token::Token) {
406 if self.expected_tokens.is_empty() {
407 if self.token == *t {
410 let token_str = Parser::token_to_string(t);
411 let this_token_str = self.this_token_to_string();
412 self.fatal(format!("expected `{}`, found `{}`",
417 self.expect_one_of(slice::ref_slice(t), &[]);
421 /// Expect next token to be edible or inedible token. If edible,
422 /// then consume it; if inedible, then return without consuming
423 /// anything. Signal a fatal error if next token is unexpected.
424 pub fn expect_one_of(&mut self,
425 edible: &[token::Token],
426 inedible: &[token::Token]) {
427 fn tokens_to_string(tokens: &[TokenType]) -> String {
428 let mut i = tokens.iter();
429 // This might be a sign we need a connect method on Iterator.
431 .map_or("".to_string(), |t| t.to_string());
432 i.enumerate().fold(b, |mut b, (i, ref a)| {
433 if tokens.len() > 2 && i == tokens.len() - 2 {
435 } else if tokens.len() == 2 && i == tokens.len() - 2 {
440 b.push_str(&*a.to_string());
444 if edible.contains(&self.token) {
446 } else if inedible.contains(&self.token) {
447 // leave it in the input
449 let mut expected = edible.iter().map(|x| TokenType::Token(x.clone()))
450 .collect::<Vec<_>>();
451 expected.extend(inedible.iter().map(|x| TokenType::Token(x.clone())));
452 expected.push_all(&*self.expected_tokens);
453 expected.sort_by(|a, b| a.to_string().cmp(&b.to_string()));
455 let expect = tokens_to_string(expected[]);
456 let actual = self.this_token_to_string();
458 (if expected.len() != 1 {
459 (format!("expected one of {}, found `{}`",
463 (format!("expected {}, found `{}`",
471 /// Check for erroneous `ident { }`; if matches, signal error and
472 /// recover (without consuming any expected input token). Returns
473 /// true if and only if input was consumed for recovery.
474 pub fn check_for_erroneous_unit_struct_expecting(&mut self, expected: &[token::Token]) -> bool {
475 if self.token == token::OpenDelim(token::Brace)
476 && expected.iter().all(|t| *t != token::OpenDelim(token::Brace))
477 && self.look_ahead(1, |t| *t == token::CloseDelim(token::Brace)) {
478 // matched; signal non-fatal error and recover.
479 let span = self.span;
481 "unit-like struct construction is written with no trailing `{ }`");
482 self.eat(&token::OpenDelim(token::Brace));
483 self.eat(&token::CloseDelim(token::Brace));
490 /// Commit to parsing a complete expression `e` expected to be
491 /// followed by some token from the set edible + inedible. Recover
492 /// from anticipated input errors, discarding erroneous characters.
493 pub fn commit_expr(&mut self, e: &Expr, edible: &[token::Token], inedible: &[token::Token]) {
494 debug!("commit_expr {}", e);
495 if let ExprPath(..) = e.node {
496 // might be unit-struct construction; check for recoverableinput error.
497 let mut expected = edible.iter().map(|x| x.clone()).collect::<Vec<_>>();
498 expected.push_all(inedible);
499 self.check_for_erroneous_unit_struct_expecting(expected[]);
501 self.expect_one_of(edible, inedible)
504 pub fn commit_expr_expecting(&mut self, e: &Expr, edible: token::Token) {
505 self.commit_expr(e, &[edible], &[])
508 /// Commit to parsing a complete statement `s`, which expects to be
509 /// followed by some token from the set edible + inedible. Check
510 /// for recoverable input errors, discarding erroneous characters.
511 pub fn commit_stmt(&mut self, edible: &[token::Token], inedible: &[token::Token]) {
514 .map_or(false, |t| t.is_ident() || t.is_path()) {
515 let mut expected = edible.iter().map(|x| x.clone()).collect::<Vec<_>>();
516 expected.push_all(inedible[]);
517 self.check_for_erroneous_unit_struct_expecting(
520 self.expect_one_of(edible, inedible)
523 pub fn commit_stmt_expecting(&mut self, edible: token::Token) {
524 self.commit_stmt(&[edible], &[])
527 pub fn parse_ident(&mut self) -> ast::Ident {
528 self.check_strict_keywords();
529 self.check_reserved_keywords();
531 token::Ident(i, _) => {
535 token::Interpolated(token::NtIdent(..)) => {
536 self.bug("ident interpolation not converted to real token");
539 let token_str = self.this_token_to_string();
540 self.fatal((format!("expected ident, found `{}`",
546 pub fn parse_path_list_item(&mut self) -> ast::PathListItem {
547 let lo = self.span.lo;
548 let node = if self.eat_keyword(keywords::Mod) {
549 let span = self.last_span;
550 self.span_warn(span, "deprecated syntax; use the `self` keyword now");
551 ast::PathListMod { id: ast::DUMMY_NODE_ID }
552 } else if self.eat_keyword(keywords::Self) {
553 ast::PathListMod { id: ast::DUMMY_NODE_ID }
555 let ident = self.parse_ident();
556 ast::PathListIdent { name: ident, id: ast::DUMMY_NODE_ID }
558 let hi = self.last_span.hi;
559 spanned(lo, hi, node)
562 /// Check if the next token is `tok`, and return `true` if so.
564 /// This method is will automatically add `tok` to `expected_tokens` if `tok` is not
566 pub fn check(&mut self, tok: &token::Token) -> bool {
567 let is_present = self.token == *tok;
568 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
572 /// Consume token 'tok' if it exists. Returns true if the given
573 /// token was present, false otherwise.
574 pub fn eat(&mut self, tok: &token::Token) -> bool {
575 let is_present = self.check(tok);
576 if is_present { self.bump() }
580 /// If the next token is the given keyword, eat it and return
581 /// true. Otherwise, return false.
582 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
583 if self.token.is_keyword(kw) {
591 /// If the given word is not a keyword, signal an error.
592 /// If the next token is not the given word, signal an error.
593 /// Otherwise, eat it.
594 pub fn expect_keyword(&mut self, kw: keywords::Keyword) {
595 if !self.eat_keyword(kw) {
596 let id_interned_str = token::get_name(kw.to_name());
597 let token_str = self.this_token_to_string();
598 self.fatal(format!("expected `{}`, found `{}`",
599 id_interned_str, token_str)[])
603 /// Signal an error if the given string is a strict keyword
604 pub fn check_strict_keywords(&mut self) {
605 if self.token.is_strict_keyword() {
606 let token_str = self.this_token_to_string();
607 let span = self.span;
609 format!("expected identifier, found keyword `{}`",
614 /// Signal an error if the current token is a reserved keyword
615 pub fn check_reserved_keywords(&mut self) {
616 if self.token.is_reserved_keyword() {
617 let token_str = self.this_token_to_string();
618 self.fatal(format!("`{}` is a reserved keyword",
623 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
624 /// `&` and continue. If an `&` is not seen, signal an error.
625 fn expect_and(&mut self) {
627 token::BinOp(token::And) => self.bump(),
629 let span = self.span;
630 let lo = span.lo + BytePos(1);
631 self.replace_token(token::BinOp(token::And), lo, span.hi)
634 let token_str = self.this_token_to_string();
636 Parser::token_to_string(&token::BinOp(token::And));
637 self.fatal(format!("expected `{}`, found `{}`",
644 /// Expect and consume a `|`. If `||` is seen, replace it with a single
645 /// `|` and continue. If a `|` is not seen, signal an error.
646 fn expect_or(&mut self) {
648 token::BinOp(token::Or) => self.bump(),
650 let span = self.span;
651 let lo = span.lo + BytePos(1);
652 self.replace_token(token::BinOp(token::Or), lo, span.hi)
655 let found_token = self.this_token_to_string();
657 Parser::token_to_string(&token::BinOp(token::Or));
658 self.fatal(format!("expected `{}`, found `{}`",
665 pub fn expect_no_suffix(&mut self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
667 None => {/* everything ok */}
669 let text = suf.as_str();
671 self.span_bug(sp, "found empty literal suffix in Some")
673 self.span_err(sp, &*format!("{} with a suffix is illegal", kind));
679 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
680 /// `<` and continue. If a `<` is not seen, return false.
682 /// This is meant to be used when parsing generics on a path to get the
684 fn eat_lt(&mut self) -> bool {
686 token::Lt => { self.bump(); true }
687 token::BinOp(token::Shl) => {
688 let span = self.span;
689 let lo = span.lo + BytePos(1);
690 self.replace_token(token::Lt, lo, span.hi);
697 fn expect_lt(&mut self) {
699 let found_token = self.this_token_to_string();
700 let token_str = Parser::token_to_string(&token::Lt);
701 self.fatal(format!("expected `{}`, found `{}`",
707 /// Parse a sequence bracketed by `|` and `|`, stopping before the `|`.
708 fn parse_seq_to_before_or<T, F>(&mut self,
712 F: FnMut(&mut Parser) -> T,
714 let mut first = true;
715 let mut vector = Vec::new();
716 while self.token != token::BinOp(token::Or) &&
717 self.token != token::OrOr {
729 /// Expect and consume a GT. if a >> is seen, replace it
730 /// with a single > and continue. If a GT is not seen,
732 pub fn expect_gt(&mut self) {
734 token::Gt => self.bump(),
735 token::BinOp(token::Shr) => {
736 let span = self.span;
737 let lo = span.lo + BytePos(1);
738 self.replace_token(token::Gt, lo, span.hi)
740 token::BinOpEq(token::Shr) => {
741 let span = self.span;
742 let lo = span.lo + BytePos(1);
743 self.replace_token(token::Ge, lo, span.hi)
746 let span = self.span;
747 let lo = span.lo + BytePos(1);
748 self.replace_token(token::Eq, lo, span.hi)
751 let gt_str = Parser::token_to_string(&token::Gt);
752 let this_token_str = self.this_token_to_string();
753 self.fatal(format!("expected `{}`, found `{}`",
760 pub fn parse_seq_to_before_gt_or_return<T, F>(&mut self,
761 sep: Option<token::Token>,
763 -> (OwnedSlice<T>, bool) where
764 F: FnMut(&mut Parser) -> Option<T>,
766 let mut v = Vec::new();
767 // This loop works by alternating back and forth between parsing types
768 // and commas. For example, given a string `A, B,>`, the parser would
769 // first parse `A`, then a comma, then `B`, then a comma. After that it
770 // would encounter a `>` and stop. This lets the parser handle trailing
771 // commas in generic parameters, because it can stop either after
772 // parsing a type or after parsing a comma.
773 for i in iter::count(0u, 1) {
774 if self.check(&token::Gt)
775 || self.token == token::BinOp(token::Shr)
776 || self.token == token::Ge
777 || self.token == token::BinOpEq(token::Shr) {
783 Some(result) => v.push(result),
784 None => return (OwnedSlice::from_vec(v), true)
787 sep.as_ref().map(|t| self.expect(t));
790 return (OwnedSlice::from_vec(v), false);
793 /// Parse a sequence bracketed by '<' and '>', stopping
795 pub fn parse_seq_to_before_gt<T, F>(&mut self,
796 sep: Option<token::Token>,
798 -> OwnedSlice<T> where
799 F: FnMut(&mut Parser) -> T,
801 let (result, returned) = self.parse_seq_to_before_gt_or_return(sep, |p| Some(f(p)));
806 pub fn parse_seq_to_gt<T, F>(&mut self,
807 sep: Option<token::Token>,
809 -> OwnedSlice<T> where
810 F: FnMut(&mut Parser) -> T,
812 let v = self.parse_seq_to_before_gt(sep, f);
817 pub fn parse_seq_to_gt_or_return<T, F>(&mut self,
818 sep: Option<token::Token>,
820 -> (OwnedSlice<T>, bool) where
821 F: FnMut(&mut Parser) -> Option<T>,
823 let (v, returned) = self.parse_seq_to_before_gt_or_return(sep, f);
827 return (v, returned);
830 /// Parse a sequence, including the closing delimiter. The function
831 /// f must consume tokens until reaching the next separator or
833 pub fn parse_seq_to_end<T, F>(&mut self,
838 F: FnMut(&mut Parser) -> T,
840 let val = self.parse_seq_to_before_end(ket, sep, f);
845 /// Parse a sequence, not including the closing delimiter. The function
846 /// f must consume tokens until reaching the next separator or
848 pub fn parse_seq_to_before_end<T, F>(&mut self,
853 F: FnMut(&mut Parser) -> T,
855 let mut first: bool = true;
857 while self.token != *ket {
860 if first { first = false; }
861 else { self.expect(t); }
865 if sep.trailing_sep_allowed && self.check(ket) { break; }
871 /// Parse a sequence, including the closing delimiter. The function
872 /// f must consume tokens until reaching the next separator or
874 pub fn parse_unspanned_seq<T, F>(&mut self,
880 F: FnMut(&mut Parser) -> T,
883 let result = self.parse_seq_to_before_end(ket, sep, f);
888 /// Parse a sequence parameter of enum variant. For consistency purposes,
889 /// these should not be empty.
890 pub fn parse_enum_variant_seq<T, F>(&mut self,
896 F: FnMut(&mut Parser) -> T,
898 let result = self.parse_unspanned_seq(bra, ket, sep, f);
899 if result.is_empty() {
900 let last_span = self.last_span;
901 self.span_err(last_span,
902 "nullary enum variants are written with no trailing `( )`");
907 // NB: Do not use this function unless you actually plan to place the
908 // spanned list in the AST.
909 pub fn parse_seq<T, F>(&mut self,
914 -> Spanned<Vec<T>> where
915 F: FnMut(&mut Parser) -> T,
917 let lo = self.span.lo;
919 let result = self.parse_seq_to_before_end(ket, sep, f);
920 let hi = self.span.hi;
922 spanned(lo, hi, result)
925 /// Advance the parser by one token
926 pub fn bump(&mut self) {
927 self.last_span = self.span;
928 // Stash token for error recovery (sometimes; clone is not necessarily cheap).
929 self.last_token = if self.token.is_ident() || self.token.is_path() {
930 Some(box self.token.clone())
934 let next = if self.buffer_start == self.buffer_end {
935 self.reader.real_token()
937 // Avoid token copies with `replace`.
938 let buffer_start = self.buffer_start as uint;
939 let next_index = (buffer_start + 1) & 3 as uint;
940 self.buffer_start = next_index as int;
942 let placeholder = TokenAndSpan {
943 tok: token::Underscore,
946 mem::replace(&mut self.buffer[buffer_start], placeholder)
949 self.token = next.tok;
950 self.tokens_consumed += 1u;
951 self.expected_tokens.clear();
954 /// Advance the parser by one token and return the bumped token.
955 pub fn bump_and_get(&mut self) -> token::Token {
956 let old_token = mem::replace(&mut self.token, token::Underscore);
961 /// EFFECT: replace the current token and span with the given one
962 pub fn replace_token(&mut self,
966 self.last_span = mk_sp(self.span.lo, lo);
968 self.span = mk_sp(lo, hi);
970 pub fn buffer_length(&mut self) -> int {
971 if self.buffer_start <= self.buffer_end {
972 return self.buffer_end - self.buffer_start;
974 return (4 - self.buffer_start) + self.buffer_end;
976 pub fn look_ahead<R, F>(&mut self, distance: uint, f: F) -> R where
977 F: FnOnce(&token::Token) -> R,
979 let dist = distance as int;
980 while self.buffer_length() < dist {
981 self.buffer[self.buffer_end as uint] = self.reader.real_token();
982 self.buffer_end = (self.buffer_end + 1) & 3;
984 f(&self.buffer[((self.buffer_start + dist - 1) & 3) as uint].tok)
986 pub fn fatal(&mut self, m: &str) -> ! {
987 self.sess.span_diagnostic.span_fatal(self.span, m)
989 pub fn span_fatal(&mut self, sp: Span, m: &str) -> ! {
990 self.sess.span_diagnostic.span_fatal(sp, m)
992 pub fn span_fatal_help(&mut self, sp: Span, m: &str, help: &str) -> ! {
993 self.span_err(sp, m);
994 self.span_help(sp, help);
995 panic!(diagnostic::FatalError);
997 pub fn span_note(&mut self, sp: Span, m: &str) {
998 self.sess.span_diagnostic.span_note(sp, m)
1000 pub fn span_help(&mut self, sp: Span, m: &str) {
1001 self.sess.span_diagnostic.span_help(sp, m)
1003 pub fn bug(&mut self, m: &str) -> ! {
1004 self.sess.span_diagnostic.span_bug(self.span, m)
1006 pub fn warn(&mut self, m: &str) {
1007 self.sess.span_diagnostic.span_warn(self.span, m)
1009 pub fn span_warn(&mut self, sp: Span, m: &str) {
1010 self.sess.span_diagnostic.span_warn(sp, m)
1012 pub fn span_err(&mut self, sp: Span, m: &str) {
1013 self.sess.span_diagnostic.span_err(sp, m)
1015 pub fn span_bug(&mut self, sp: Span, m: &str) -> ! {
1016 self.sess.span_diagnostic.span_bug(sp, m)
1018 pub fn abort_if_errors(&mut self) {
1019 self.sess.span_diagnostic.handler().abort_if_errors();
1022 pub fn id_to_interned_str(&mut self, id: Ident) -> InternedString {
1023 token::get_ident(id)
1026 /// Is the current token one of the keywords that signals a bare function
1028 pub fn token_is_bare_fn_keyword(&mut self) -> bool {
1029 self.token.is_keyword(keywords::Fn) ||
1030 self.token.is_keyword(keywords::Unsafe) ||
1031 self.token.is_keyword(keywords::Extern)
1034 /// Is the current token one of the keywords that signals a closure type?
1035 pub fn token_is_closure_keyword(&mut self) -> bool {
1036 self.token.is_keyword(keywords::Unsafe)
1039 pub fn get_lifetime(&mut self) -> ast::Ident {
1041 token::Lifetime(ref ident) => *ident,
1042 _ => self.bug("not a lifetime"),
1046 pub fn parse_for_in_type(&mut self) -> Ty_ {
1048 Parses whatever can come after a `for` keyword in a type.
1049 The `for` has already been consumed.
1053 - for <'lt> |S| -> T
1057 - for <'lt> [unsafe] [extern "ABI"] fn (S) -> T
1058 - for <'lt> path::foo(a, b)
1063 let lifetime_defs = self.parse_late_bound_lifetime_defs();
1065 // examine next token to decide to do
1066 if self.eat_keyword(keywords::Proc) {
1067 self.parse_proc_type(lifetime_defs)
1068 } else if self.token_is_bare_fn_keyword() || self.token_is_closure_keyword() {
1069 self.parse_ty_bare_fn_or_ty_closure(lifetime_defs)
1070 } else if self.check(&token::ModSep) ||
1071 self.token.is_ident() ||
1072 self.token.is_path()
1074 let trait_ref = self.parse_trait_ref();
1075 let poly_trait_ref = ast::PolyTraitRef { bound_lifetimes: lifetime_defs,
1076 trait_ref: trait_ref };
1077 let other_bounds = if self.eat(&token::BinOp(token::Plus)) {
1078 self.parse_ty_param_bounds(BoundParsingMode::Bare)
1083 Some(TraitTyParamBound(poly_trait_ref, TraitBoundModifier::None)).into_iter()
1084 .chain(other_bounds.into_vec().into_iter())
1086 ast::TyPolyTraitRef(all_bounds)
1088 self.parse_ty_closure(lifetime_defs)
1092 pub fn parse_ty_path(&mut self) -> Ty_ {
1093 let path = self.parse_path(LifetimeAndTypesWithoutColons);
1094 TyPath(path, ast::DUMMY_NODE_ID)
1097 /// parse a TyBareFn type:
1098 pub fn parse_ty_bare_fn(&mut self, lifetime_defs: Vec<ast::LifetimeDef>) -> Ty_ {
1101 [unsafe] [extern "ABI"] fn <'lt> (S) -> T
1102 ^~~~^ ^~~~^ ^~~~^ ^~^ ^
1105 | | | Argument types
1111 let unsafety = self.parse_unsafety();
1112 let abi = if self.eat_keyword(keywords::Extern) {
1113 self.parse_opt_abi().unwrap_or(abi::C)
1118 self.expect_keyword(keywords::Fn);
1119 let lifetime_defs = self.parse_legacy_lifetime_defs(lifetime_defs);
1120 let (inputs, variadic) = self.parse_fn_args(false, true);
1121 let ret_ty = self.parse_ret_ty();
1122 let decl = P(FnDecl {
1127 TyBareFn(P(BareFnTy {
1130 lifetimes: lifetime_defs,
1135 /// Parses a procedure type (`proc`). The initial `proc` keyword must
1136 /// already have been parsed.
1137 pub fn parse_proc_type(&mut self, lifetime_defs: Vec<ast::LifetimeDef>) -> Ty_ {
1140 proc <'lt> (S) [:Bounds] -> T
1141 ^~~^ ^~~~^ ^ ^~~~~~~~^ ^
1147 the `proc` keyword (already consumed)
1151 let proc_span = self.last_span;
1153 // To be helpful, parse the proc as ever
1154 let _ = self.parse_legacy_lifetime_defs(lifetime_defs);
1155 let _ = self.parse_fn_args(false, false);
1156 let _ = self.parse_colon_then_ty_param_bounds(BoundParsingMode::Bare);
1157 let _ = self.parse_ret_ty();
1159 self.obsolete(proc_span, ObsoleteProcType);
1164 /// Parses an optional unboxed closure kind (`&:`, `&mut:`, or `:`).
1165 pub fn parse_optional_unboxed_closure_kind(&mut self)
1166 -> Option<UnboxedClosureKind> {
1167 if self.check(&token::BinOp(token::And)) &&
1168 self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
1169 self.look_ahead(2, |t| *t == token::Colon) {
1173 return Some(FnMutUnboxedClosureKind)
1176 if self.token == token::BinOp(token::And) &&
1177 self.look_ahead(1, |t| *t == token::Colon) {
1180 return Some(FnUnboxedClosureKind)
1183 if self.eat(&token::Colon) {
1184 return Some(FnOnceUnboxedClosureKind)
1190 pub fn parse_ty_bare_fn_or_ty_closure(&mut self, lifetime_defs: Vec<LifetimeDef>) -> Ty_ {
1191 // Both bare fns and closures can begin with stuff like unsafe
1192 // and extern. So we just scan ahead a few tokens to see if we see
1195 // Closure: [unsafe] <'lt> |S| [:Bounds] -> T
1196 // Fn: [unsafe] [extern "ABI"] fn <'lt> (S) -> T
1198 if self.token.is_keyword(keywords::Fn) {
1199 self.parse_ty_bare_fn(lifetime_defs)
1200 } else if self.token.is_keyword(keywords::Extern) {
1201 self.parse_ty_bare_fn(lifetime_defs)
1202 } else if self.token.is_keyword(keywords::Unsafe) {
1203 if self.look_ahead(1, |t| t.is_keyword(keywords::Fn) ||
1204 t.is_keyword(keywords::Extern)) {
1205 self.parse_ty_bare_fn(lifetime_defs)
1207 self.parse_ty_closure(lifetime_defs)
1210 self.parse_ty_closure(lifetime_defs)
1214 /// Parse a TyClosure type
1215 pub fn parse_ty_closure(&mut self, lifetime_defs: Vec<ast::LifetimeDef>) -> Ty_ {
1218 [unsafe] <'lt> |S| [:Bounds] -> T
1219 ^~~~~~~^ ^~~~^ ^ ^~~~~~~~^ ^
1222 | | | Closure bounds
1224 | Deprecated lifetime defs
1230 let unsafety = self.parse_unsafety();
1232 let lifetime_defs = self.parse_legacy_lifetime_defs(lifetime_defs);
1234 let inputs = if self.eat(&token::OrOr) {
1239 let inputs = self.parse_seq_to_before_or(
1241 |p| p.parse_arg_general(false));
1246 let bounds = self.parse_colon_then_ty_param_bounds(BoundParsingMode::Bare);
1248 let output = self.parse_ret_ty();
1249 let decl = P(FnDecl {
1255 TyClosure(P(ClosureTy {
1260 lifetimes: lifetime_defs,
1264 pub fn parse_unsafety(&mut self) -> Unsafety {
1265 if self.eat_keyword(keywords::Unsafe) {
1266 return Unsafety::Unsafe;
1268 return Unsafety::Normal;
1272 /// Parses `[ 'for' '<' lifetime_defs '>' ]'
1273 fn parse_legacy_lifetime_defs(&mut self,
1274 lifetime_defs: Vec<ast::LifetimeDef>)
1275 -> Vec<ast::LifetimeDef>
1277 if self.token == token::Lt {
1279 if lifetime_defs.is_empty() {
1280 self.warn("deprecated syntax; use the `for` keyword now \
1281 (e.g. change `fn<'a>` to `for<'a> fn`)");
1282 let lifetime_defs = self.parse_lifetime_defs();
1286 self.fatal("cannot use new `for` keyword and older syntax together");
1293 /// Parses `type Foo;` in a trait declaration only. The `type` keyword has
1294 /// already been parsed.
1295 fn parse_associated_type(&mut self, attrs: Vec<Attribute>)
1298 let ty_param = self.parse_ty_param();
1299 self.expect(&token::Semi);
1306 /// Parses `type Foo = TYPE;` in an implementation declaration only. The
1307 /// `type` keyword has already been parsed.
1308 fn parse_typedef(&mut self, attrs: Vec<Attribute>, vis: Visibility)
1310 let lo = self.span.lo;
1311 let ident = self.parse_ident();
1312 self.expect(&token::Eq);
1313 let typ = self.parse_ty_sum();
1314 let hi = self.span.hi;
1315 self.expect(&token::Semi);
1317 id: ast::DUMMY_NODE_ID,
1318 span: mk_sp(lo, hi),
1326 /// Parse the items in a trait declaration
1327 pub fn parse_trait_items(&mut self) -> Vec<TraitItem> {
1328 self.parse_unspanned_seq(
1329 &token::OpenDelim(token::Brace),
1330 &token::CloseDelim(token::Brace),
1333 let attrs = p.parse_outer_attributes();
1335 if p.eat_keyword(keywords::Type) {
1336 TypeTraitItem(P(p.parse_associated_type(attrs)))
1340 let vis = p.parse_visibility();
1341 let style = p.parse_unsafety();
1342 let abi = if p.eat_keyword(keywords::Extern) {
1343 p.parse_opt_abi().unwrap_or(abi::C)
1347 p.expect_keyword(keywords::Fn);
1349 let ident = p.parse_ident();
1350 let mut generics = p.parse_generics();
1352 let (explicit_self, d) = p.parse_fn_decl_with_self(|p| {
1353 // This is somewhat dubious; We don't want to allow
1354 // argument names to be left off if there is a
1356 p.parse_arg_general(false)
1359 p.parse_where_clause(&mut generics);
1361 let hi = p.last_span.hi;
1365 debug!("parse_trait_methods(): parsing required method");
1366 RequiredMethod(TypeMethod {
1373 explicit_self: explicit_self,
1374 id: ast::DUMMY_NODE_ID,
1375 span: mk_sp(lo, hi),
1379 token::OpenDelim(token::Brace) => {
1380 debug!("parse_trait_methods(): parsing provided method");
1381 let (inner_attrs, body) =
1382 p.parse_inner_attrs_and_block();
1383 let mut attrs = attrs;
1384 attrs.push_all(inner_attrs[]);
1385 ProvidedMethod(P(ast::Method {
1387 id: ast::DUMMY_NODE_ID,
1388 span: mk_sp(lo, hi),
1389 node: ast::MethDecl(ident,
1401 let token_str = p.this_token_to_string();
1402 p.fatal((format!("expected `;` or `{{`, found `{}`",
1410 /// Parse a possibly mutable type
1411 pub fn parse_mt(&mut self) -> MutTy {
1412 let mutbl = self.parse_mutability();
1413 let t = self.parse_ty();
1414 MutTy { ty: t, mutbl: mutbl }
1417 /// Parse [mut/const/imm] ID : TY
1418 /// now used only by obsolete record syntax parser...
1419 pub fn parse_ty_field(&mut self) -> TypeField {
1420 let lo = self.span.lo;
1421 let mutbl = self.parse_mutability();
1422 let id = self.parse_ident();
1423 self.expect(&token::Colon);
1424 let ty = self.parse_ty_sum();
1425 let hi = ty.span.hi;
1428 mt: MutTy { ty: ty, mutbl: mutbl },
1429 span: mk_sp(lo, hi),
1433 /// Parse optional return type [ -> TY ] in function decl
1434 pub fn parse_ret_ty(&mut self) -> FunctionRetTy {
1435 if self.eat(&token::RArrow) {
1436 if self.eat(&token::Not) {
1439 let t = self.parse_ty();
1441 // We used to allow `fn foo() -> &T + U`, but don't
1442 // anymore. If we see it, report a useful error. This
1443 // only makes sense because `parse_ret_ty` is only
1444 // used in fn *declarations*, not fn types or where
1445 // clauses (i.e., not when parsing something like
1446 // `FnMut() -> T + Send`, where the `+` is legal).
1447 if self.token == token::BinOp(token::Plus) {
1448 self.warn("deprecated syntax: `()` are required, see RFC 438 for details");
1454 let pos = self.span.lo;
1456 id: ast::DUMMY_NODE_ID,
1457 node: TyTup(vec![]),
1458 span: mk_sp(pos, pos),
1463 /// Parse a type in a context where `T1+T2` is allowed.
1464 pub fn parse_ty_sum(&mut self) -> P<Ty> {
1465 let lo = self.span.lo;
1466 let lhs = self.parse_ty();
1468 if !self.eat(&token::BinOp(token::Plus)) {
1472 let bounds = self.parse_ty_param_bounds(BoundParsingMode::Bare);
1474 // In type grammar, `+` is treated like a binary operator,
1475 // and hence both L and R side are required.
1476 if bounds.len() == 0 {
1477 let last_span = self.last_span;
1478 self.span_err(last_span,
1479 "at least one type parameter bound \
1480 must be specified");
1483 let sp = mk_sp(lo, self.last_span.hi);
1484 let sum = ast::TyObjectSum(lhs, bounds);
1485 P(Ty {id: ast::DUMMY_NODE_ID, node: sum, span: sp})
1489 pub fn parse_ty(&mut self) -> P<Ty> {
1490 maybe_whole!(no_clone self, NtTy);
1492 let lo = self.span.lo;
1494 let t = if self.check(&token::OpenDelim(token::Paren)) {
1497 // (t) is a parenthesized ty
1498 // (t,) is the type of a tuple with only one field,
1500 let mut ts = vec![];
1501 let mut last_comma = false;
1502 while self.token != token::CloseDelim(token::Paren) {
1503 ts.push(self.parse_ty_sum());
1504 if self.check(&token::Comma) {
1513 self.expect(&token::CloseDelim(token::Paren));
1514 if ts.len() == 1 && !last_comma {
1515 TyParen(ts.into_iter().nth(0).unwrap())
1519 } else if self.token == token::Tilde {
1522 let last_span = self.last_span;
1524 token::OpenDelim(token::Bracket) => self.obsolete(last_span, ObsoleteOwnedVector),
1525 _ => self.obsolete(last_span, ObsoleteOwnedType)
1527 TyTup(vec![self.parse_ty()])
1528 } else if self.check(&token::BinOp(token::Star)) {
1529 // STAR POINTER (bare pointer?)
1531 TyPtr(self.parse_ptr())
1532 } else if self.check(&token::OpenDelim(token::Bracket)) {
1534 self.expect(&token::OpenDelim(token::Bracket));
1535 let t = self.parse_ty_sum();
1537 // Parse the `; e` in `[ int; e ]`
1538 // where `e` is a const expression
1539 let t = match self.maybe_parse_fixed_length_of_vec() {
1541 Some(suffix) => TyFixedLengthVec(t, suffix)
1543 self.expect(&token::CloseDelim(token::Bracket));
1545 } else if self.check(&token::BinOp(token::And)) ||
1546 self.token == token::AndAnd {
1549 self.parse_borrowed_pointee()
1550 } else if self.token.is_keyword(keywords::For) {
1551 self.parse_for_in_type()
1552 } else if self.token_is_bare_fn_keyword() ||
1553 self.token_is_closure_keyword() {
1554 // BARE FUNCTION OR CLOSURE
1555 self.parse_ty_bare_fn_or_ty_closure(Vec::new())
1556 } else if self.check(&token::BinOp(token::Or)) ||
1557 self.token == token::OrOr ||
1558 (self.token == token::Lt &&
1559 self.look_ahead(1, |t| {
1560 *t == token::Gt || t.is_lifetime()
1563 self.parse_ty_closure(Vec::new())
1564 } else if self.eat_keyword(keywords::Typeof) {
1566 // In order to not be ambiguous, the type must be surrounded by parens.
1567 self.expect(&token::OpenDelim(token::Paren));
1568 let e = self.parse_expr();
1569 self.expect(&token::CloseDelim(token::Paren));
1571 } else if self.eat_keyword(keywords::Proc) {
1572 self.parse_proc_type(Vec::new())
1573 } else if self.eat_lt() {
1574 // QUALIFIED PATH `<TYPE as TRAIT_REF>::item`
1575 let self_type = self.parse_ty_sum();
1576 self.expect_keyword(keywords::As);
1577 let trait_ref = self.parse_trait_ref();
1578 self.expect(&token::Gt);
1579 self.expect(&token::ModSep);
1580 let item_name = self.parse_ident();
1582 self_type: self_type,
1583 trait_ref: P(trait_ref),
1584 item_name: item_name,
1586 } else if self.check(&token::ModSep) ||
1587 self.token.is_ident() ||
1588 self.token.is_path() {
1590 self.parse_ty_path()
1591 } else if self.eat(&token::Underscore) {
1592 // TYPE TO BE INFERRED
1595 let this_token_str = self.this_token_to_string();
1596 let msg = format!("expected type, found `{}`", this_token_str);
1600 let sp = mk_sp(lo, self.last_span.hi);
1601 P(Ty {id: ast::DUMMY_NODE_ID, node: t, span: sp})
1604 pub fn parse_borrowed_pointee(&mut self) -> Ty_ {
1605 // look for `&'lt` or `&'foo ` and interpret `foo` as the region name:
1606 let opt_lifetime = self.parse_opt_lifetime();
1608 let mt = self.parse_mt();
1609 return TyRptr(opt_lifetime, mt);
1612 pub fn parse_ptr(&mut self) -> MutTy {
1613 let mutbl = if self.eat_keyword(keywords::Mut) {
1615 } else if self.eat_keyword(keywords::Const) {
1618 let span = self.last_span;
1620 "bare raw pointers are no longer allowed, you should \
1621 likely use `*mut T`, but otherwise `*T` is now \
1622 known as `*const T`");
1625 let t = self.parse_ty();
1626 MutTy { ty: t, mutbl: mutbl }
1629 pub fn is_named_argument(&mut self) -> bool {
1630 let offset = match self.token {
1631 token::BinOp(token::And) => 1,
1633 _ if self.token.is_keyword(keywords::Mut) => 1,
1637 debug!("parser is_named_argument offset:{}", offset);
1640 is_plain_ident_or_underscore(&self.token)
1641 && self.look_ahead(1, |t| *t == token::Colon)
1643 self.look_ahead(offset, |t| is_plain_ident_or_underscore(t))
1644 && self.look_ahead(offset + 1, |t| *t == token::Colon)
1648 /// This version of parse arg doesn't necessarily require
1649 /// identifier names.
1650 pub fn parse_arg_general(&mut self, require_name: bool) -> Arg {
1651 let pat = if require_name || self.is_named_argument() {
1652 debug!("parse_arg_general parse_pat (require_name:{})",
1654 let pat = self.parse_pat();
1656 self.expect(&token::Colon);
1659 debug!("parse_arg_general ident_to_pat");
1660 ast_util::ident_to_pat(ast::DUMMY_NODE_ID,
1662 special_idents::invalid)
1665 let t = self.parse_ty_sum();
1670 id: ast::DUMMY_NODE_ID,
1674 /// Parse a single function argument
1675 pub fn parse_arg(&mut self) -> Arg {
1676 self.parse_arg_general(true)
1679 /// Parse an argument in a lambda header e.g. |arg, arg|
1680 pub fn parse_fn_block_arg(&mut self) -> Arg {
1681 let pat = self.parse_pat();
1682 let t = if self.eat(&token::Colon) {
1686 id: ast::DUMMY_NODE_ID,
1688 span: mk_sp(self.span.lo, self.span.hi),
1694 id: ast::DUMMY_NODE_ID
1698 pub fn maybe_parse_fixed_length_of_vec(&mut self) -> Option<P<ast::Expr>> {
1699 if self.check(&token::Semi) {
1701 Some(self.parse_expr())
1707 /// Matches token_lit = LIT_INTEGER | ...
1708 pub fn lit_from_token(&mut self, tok: &token::Token) -> Lit_ {
1710 token::Interpolated(token::NtExpr(ref v)) => {
1712 ExprLit(ref lit) => { lit.node.clone() }
1713 _ => { self.unexpected_last(tok); }
1716 token::Literal(lit, suf) => {
1717 let (suffix_illegal, out) = match lit {
1718 token::Byte(i) => (true, LitByte(parse::byte_lit(i.as_str()).0)),
1719 token::Char(i) => (true, LitChar(parse::char_lit(i.as_str()).0)),
1721 // there are some valid suffixes for integer and
1722 // float literals, so all the handling is done
1724 token::Integer(s) => {
1725 (false, parse::integer_lit(s.as_str(),
1726 suf.as_ref().map(|s| s.as_str()),
1727 &self.sess.span_diagnostic,
1730 token::Float(s) => {
1731 (false, parse::float_lit(s.as_str(),
1732 suf.as_ref().map(|s| s.as_str()),
1733 &self.sess.span_diagnostic,
1739 LitStr(token::intern_and_get_ident(parse::str_lit(s.as_str())[]),
1742 token::StrRaw(s, n) => {
1745 token::intern_and_get_ident(
1746 parse::raw_str_lit(s.as_str())[]),
1750 (true, LitBinary(parse::binary_lit(i.as_str()))),
1751 token::BinaryRaw(i, _) =>
1753 LitBinary(Rc::new(i.as_str().as_bytes().iter().map(|&x| x).collect()))),
1757 let sp = self.last_span;
1758 self.expect_no_suffix(sp, &*format!("{} literal", lit.short_name()), suf)
1763 _ => { self.unexpected_last(tok); }
1767 /// Matches lit = true | false | token_lit
1768 pub fn parse_lit(&mut self) -> Lit {
1769 let lo = self.span.lo;
1770 let lit = if self.eat_keyword(keywords::True) {
1772 } else if self.eat_keyword(keywords::False) {
1775 let token = self.bump_and_get();
1776 let lit = self.lit_from_token(&token);
1779 codemap::Spanned { node: lit, span: mk_sp(lo, self.last_span.hi) }
1782 /// matches '-' lit | lit
1783 pub fn parse_literal_maybe_minus(&mut self) -> P<Expr> {
1784 let minus_lo = self.span.lo;
1785 let minus_present = self.eat(&token::BinOp(token::Minus));
1787 let lo = self.span.lo;
1788 let literal = P(self.parse_lit());
1789 let hi = self.span.hi;
1790 let expr = self.mk_expr(lo, hi, ExprLit(literal));
1793 let minus_hi = self.span.hi;
1794 let unary = self.mk_unary(UnNeg, expr);
1795 self.mk_expr(minus_lo, minus_hi, unary)
1801 /// Parses a path and optional type parameter bounds, depending on the
1802 /// mode. The `mode` parameter determines whether lifetimes, types, and/or
1803 /// bounds are permitted and whether `::` must precede type parameter
1805 pub fn parse_path(&mut self, mode: PathParsingMode) -> ast::Path {
1806 // Check for a whole path...
1807 let found = match self.token {
1808 token::Interpolated(token::NtPath(_)) => Some(self.bump_and_get()),
1811 if let Some(token::Interpolated(token::NtPath(box path))) = found {
1815 let lo = self.span.lo;
1816 let is_global = self.eat(&token::ModSep);
1818 // Parse any number of segments and bound sets. A segment is an
1819 // identifier followed by an optional lifetime and a set of types.
1820 // A bound set is a set of type parameter bounds.
1821 let segments = match mode {
1822 LifetimeAndTypesWithoutColons => {
1823 self.parse_path_segments_without_colons()
1825 LifetimeAndTypesWithColons => {
1826 self.parse_path_segments_with_colons()
1829 self.parse_path_segments_without_types()
1833 // Assemble the span.
1834 let span = mk_sp(lo, self.last_span.hi);
1836 // Assemble the result.
1845 /// - `a::b<T,U>::c<V,W>`
1846 /// - `a::b<T,U>::c(V) -> W`
1847 /// - `a::b<T,U>::c(V)`
1848 pub fn parse_path_segments_without_colons(&mut self) -> Vec<ast::PathSegment> {
1849 let mut segments = Vec::new();
1851 // First, parse an identifier.
1852 let identifier = self.parse_ident();
1854 // Parse types, optionally.
1855 let parameters = if self.eat_lt() {
1856 let (lifetimes, types, bindings) = self.parse_generic_values_after_lt();
1858 ast::AngleBracketedParameters(ast::AngleBracketedParameterData {
1859 lifetimes: lifetimes,
1860 types: OwnedSlice::from_vec(types),
1861 bindings: OwnedSlice::from_vec(bindings),
1863 } else if self.eat(&token::OpenDelim(token::Paren)) {
1864 let inputs = self.parse_seq_to_end(
1865 &token::CloseDelim(token::Paren),
1866 seq_sep_trailing_allowed(token::Comma),
1867 |p| p.parse_ty_sum());
1869 let output_ty = if self.eat(&token::RArrow) {
1870 Some(self.parse_ty())
1875 ast::ParenthesizedParameters(ast::ParenthesizedParameterData {
1880 ast::PathParameters::none()
1883 // Assemble and push the result.
1884 segments.push(ast::PathSegment { identifier: identifier,
1885 parameters: parameters });
1887 // Continue only if we see a `::`
1888 if !self.eat(&token::ModSep) {
1895 /// - `a::b::<T,U>::c`
1896 pub fn parse_path_segments_with_colons(&mut self) -> Vec<ast::PathSegment> {
1897 let mut segments = Vec::new();
1899 // First, parse an identifier.
1900 let identifier = self.parse_ident();
1902 // If we do not see a `::`, stop.
1903 if !self.eat(&token::ModSep) {
1904 segments.push(ast::PathSegment {
1905 identifier: identifier,
1906 parameters: ast::AngleBracketedParameters(ast::AngleBracketedParameterData {
1907 lifetimes: Vec::new(),
1908 types: OwnedSlice::empty(),
1909 bindings: OwnedSlice::empty(),
1915 // Check for a type segment.
1917 // Consumed `a::b::<`, go look for types
1918 let (lifetimes, types, bindings) = self.parse_generic_values_after_lt();
1919 segments.push(ast::PathSegment {
1920 identifier: identifier,
1921 parameters: ast::AngleBracketedParameters(ast::AngleBracketedParameterData {
1922 lifetimes: lifetimes,
1923 types: OwnedSlice::from_vec(types),
1924 bindings: OwnedSlice::from_vec(bindings),
1928 // Consumed `a::b::<T,U>`, check for `::` before proceeding
1929 if !self.eat(&token::ModSep) {
1933 // Consumed `a::`, go look for `b`
1934 segments.push(ast::PathSegment {
1935 identifier: identifier,
1936 parameters: ast::PathParameters::none(),
1945 pub fn parse_path_segments_without_types(&mut self) -> Vec<ast::PathSegment> {
1946 let mut segments = Vec::new();
1948 // First, parse an identifier.
1949 let identifier = self.parse_ident();
1951 // Assemble and push the result.
1952 segments.push(ast::PathSegment {
1953 identifier: identifier,
1954 parameters: ast::PathParameters::none()
1957 // If we do not see a `::`, stop.
1958 if !self.eat(&token::ModSep) {
1964 /// parses 0 or 1 lifetime
1965 pub fn parse_opt_lifetime(&mut self) -> Option<ast::Lifetime> {
1967 token::Lifetime(..) => {
1968 Some(self.parse_lifetime())
1976 /// Parses a single lifetime
1977 /// Matches lifetime = LIFETIME
1978 pub fn parse_lifetime(&mut self) -> ast::Lifetime {
1980 token::Lifetime(i) => {
1981 let span = self.span;
1983 return ast::Lifetime {
1984 id: ast::DUMMY_NODE_ID,
1990 self.fatal(format!("expected a lifetime name")[]);
1995 /// Parses `lifetime_defs = [ lifetime_defs { ',' lifetime_defs } ]` where `lifetime_def =
1996 /// lifetime [':' lifetimes]`
1997 pub fn parse_lifetime_defs(&mut self) -> Vec<ast::LifetimeDef> {
1999 let mut res = Vec::new();
2002 token::Lifetime(_) => {
2003 let lifetime = self.parse_lifetime();
2005 if self.eat(&token::Colon) {
2006 self.parse_lifetimes(token::BinOp(token::Plus))
2010 res.push(ast::LifetimeDef { lifetime: lifetime,
2020 token::Comma => { self.bump(); }
2021 token::Gt => { return res; }
2022 token::BinOp(token::Shr) => { return res; }
2024 let this_token_str = self.this_token_to_string();
2025 let msg = format!("expected `,` or `>` after lifetime \
2034 /// matches lifetimes = ( lifetime ) | ( lifetime , lifetimes ) actually, it matches the empty
2035 /// one too, but putting that in there messes up the grammar....
2037 /// Parses zero or more comma separated lifetimes. Expects each lifetime to be followed by
2038 /// either a comma or `>`. Used when parsing type parameter lists, where we expect something
2039 /// like `<'a, 'b, T>`.
2040 pub fn parse_lifetimes(&mut self, sep: token::Token) -> Vec<ast::Lifetime> {
2042 let mut res = Vec::new();
2045 token::Lifetime(_) => {
2046 res.push(self.parse_lifetime());
2053 if self.token != sep {
2061 /// Parse mutability declaration (mut/const/imm)
2062 pub fn parse_mutability(&mut self) -> Mutability {
2063 if self.eat_keyword(keywords::Mut) {
2070 /// Parse ident COLON expr
2071 pub fn parse_field(&mut self) -> Field {
2072 let lo = self.span.lo;
2073 let i = self.parse_ident();
2074 let hi = self.last_span.hi;
2075 self.expect(&token::Colon);
2076 let e = self.parse_expr();
2078 ident: spanned(lo, hi, i),
2079 span: mk_sp(lo, e.span.hi),
2084 pub fn mk_expr(&mut self, lo: BytePos, hi: BytePos, node: Expr_) -> P<Expr> {
2086 id: ast::DUMMY_NODE_ID,
2088 span: mk_sp(lo, hi),
2092 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::Expr_ {
2093 ExprUnary(unop, expr)
2096 pub fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::Expr_ {
2097 ExprBinary(binop, lhs, rhs)
2100 pub fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::Expr_ {
2104 fn mk_method_call(&mut self,
2105 ident: ast::SpannedIdent,
2109 ExprMethodCall(ident, tps, args)
2112 pub fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::Expr_ {
2113 ExprIndex(expr, idx)
2116 pub fn mk_slice(&mut self,
2118 start: Option<P<Expr>>,
2119 end: Option<P<Expr>>,
2122 // FIXME: we could give more accurate span info here.
2123 let (lo, hi) = match (&start, &end) {
2124 (&Some(ref s), &Some(ref e)) => (s.span.lo, e.span.hi),
2125 (&Some(ref s), &None) => (s.span.lo, s.span.hi),
2126 (&None, &Some(ref e)) => (e.span.lo, e.span.hi),
2127 (&None, &None) => (DUMMY_SP.lo, DUMMY_SP.hi),
2129 ExprIndex(expr, self.mk_expr(lo, hi, ExprRange(start, end)))
2132 pub fn mk_range(&mut self,
2133 start: Option<P<Expr>>,
2134 end: Option<P<Expr>>)
2136 ExprRange(start, end)
2139 pub fn mk_field(&mut self, expr: P<Expr>, ident: ast::SpannedIdent) -> ast::Expr_ {
2140 ExprField(expr, ident)
2143 pub fn mk_tup_field(&mut self, expr: P<Expr>, idx: codemap::Spanned<uint>) -> ast::Expr_ {
2144 ExprTupField(expr, idx)
2147 pub fn mk_assign_op(&mut self, binop: ast::BinOp,
2148 lhs: P<Expr>, rhs: P<Expr>) -> ast::Expr_ {
2149 ExprAssignOp(binop, lhs, rhs)
2152 pub fn mk_mac_expr(&mut self, lo: BytePos, hi: BytePos, m: Mac_) -> P<Expr> {
2154 id: ast::DUMMY_NODE_ID,
2155 node: ExprMac(codemap::Spanned {node: m, span: mk_sp(lo, hi)}),
2156 span: mk_sp(lo, hi),
2160 pub fn mk_lit_u32(&mut self, i: u32) -> P<Expr> {
2161 let span = &self.span;
2162 let lv_lit = P(codemap::Spanned {
2163 node: LitInt(i as u64, ast::UnsignedIntLit(TyU32)),
2168 id: ast::DUMMY_NODE_ID,
2169 node: ExprLit(lv_lit),
2174 fn expect_open_delim(&mut self) -> token::DelimToken {
2176 token::OpenDelim(delim) => {
2180 _ => self.fatal("expected open delimiter"),
2184 /// At the bottom (top?) of the precedence hierarchy,
2185 /// parse things like parenthesized exprs,
2186 /// macros, return, etc.
2187 pub fn parse_bottom_expr(&mut self) -> P<Expr> {
2188 maybe_whole_expr!(self);
2190 let lo = self.span.lo;
2191 let mut hi = self.span.hi;
2196 token::OpenDelim(token::Paren) => {
2199 // (e) is parenthesized e
2200 // (e,) is a tuple with only one field, e
2201 let mut es = vec![];
2202 let mut trailing_comma = false;
2203 while self.token != token::CloseDelim(token::Paren) {
2204 es.push(self.parse_expr());
2205 self.commit_expr(&**es.last().unwrap(), &[],
2206 &[token::Comma, token::CloseDelim(token::Paren)]);
2207 if self.check(&token::Comma) {
2208 trailing_comma = true;
2212 trailing_comma = false;
2219 return if es.len() == 1 && !trailing_comma {
2220 self.mk_expr(lo, hi, ExprParen(es.into_iter().nth(0).unwrap()))
2222 self.mk_expr(lo, hi, ExprTup(es))
2225 token::OpenDelim(token::Brace) => {
2227 let blk = self.parse_block_tail(lo, DefaultBlock);
2228 return self.mk_expr(blk.span.lo, blk.span.hi,
2231 token::BinOp(token::Or) | token::OrOr => {
2232 return self.parse_lambda_expr(CaptureByRef);
2234 // FIXME #13626: Should be able to stick in
2235 // token::SELF_KEYWORD_NAME
2236 token::Ident(id @ ast::Ident {
2237 name: ast::Name(token::SELF_KEYWORD_NAME_NUM),
2239 }, token::Plain) => {
2241 let path = ast_util::ident_to_path(mk_sp(lo, hi), id);
2242 ex = ExprPath(path);
2243 hi = self.last_span.hi;
2245 token::OpenDelim(token::Bracket) => {
2248 if self.check(&token::CloseDelim(token::Bracket)) {
2251 ex = ExprVec(Vec::new());
2254 let first_expr = self.parse_expr();
2255 if self.check(&token::Semi) {
2256 // Repeating vector syntax: [ 0; 512 ]
2258 let count = self.parse_expr();
2259 self.expect(&token::CloseDelim(token::Bracket));
2260 ex = ExprRepeat(first_expr, count);
2261 } else if self.check(&token::Comma) {
2262 // Vector with two or more elements.
2264 let remaining_exprs = self.parse_seq_to_end(
2265 &token::CloseDelim(token::Bracket),
2266 seq_sep_trailing_allowed(token::Comma),
2269 let mut exprs = vec!(first_expr);
2270 exprs.extend(remaining_exprs.into_iter());
2271 ex = ExprVec(exprs);
2273 // Vector with one element.
2274 self.expect(&token::CloseDelim(token::Bracket));
2275 ex = ExprVec(vec!(first_expr));
2278 hi = self.last_span.hi;
2281 if self.eat_keyword(keywords::Move) {
2282 return self.parse_lambda_expr(CaptureByValue);
2284 if self.eat_keyword(keywords::Proc) {
2285 let span = self.last_span;
2286 let _ = self.parse_proc_decl();
2287 let _ = self.parse_expr();
2288 return self.obsolete_expr(span, ObsoleteProcExpr);
2290 if self.eat_keyword(keywords::If) {
2291 return self.parse_if_expr();
2293 if self.eat_keyword(keywords::For) {
2294 return self.parse_for_expr(None);
2296 if self.eat_keyword(keywords::While) {
2297 return self.parse_while_expr(None);
2299 if self.token.is_lifetime() {
2300 let lifetime = self.get_lifetime();
2302 self.expect(&token::Colon);
2303 if self.eat_keyword(keywords::While) {
2304 return self.parse_while_expr(Some(lifetime))
2306 if self.eat_keyword(keywords::For) {
2307 return self.parse_for_expr(Some(lifetime))
2309 if self.eat_keyword(keywords::Loop) {
2310 return self.parse_loop_expr(Some(lifetime))
2312 self.fatal("expected `while`, `for`, or `loop` after a label")
2314 if self.eat_keyword(keywords::Loop) {
2315 return self.parse_loop_expr(None);
2317 if self.eat_keyword(keywords::Continue) {
2318 let lo = self.span.lo;
2319 let ex = if self.token.is_lifetime() {
2320 let lifetime = self.get_lifetime();
2322 ExprAgain(Some(lifetime))
2326 let hi = self.span.hi;
2327 return self.mk_expr(lo, hi, ex);
2329 if self.eat_keyword(keywords::Match) {
2330 return self.parse_match_expr();
2332 if self.eat_keyword(keywords::Unsafe) {
2333 return self.parse_block_expr(
2335 UnsafeBlock(ast::UserProvided));
2337 if self.eat_keyword(keywords::Return) {
2338 // RETURN expression
2339 if self.token.can_begin_expr() {
2340 let e = self.parse_expr();
2342 ex = ExprRet(Some(e));
2346 } else if self.eat_keyword(keywords::Break) {
2348 if self.token.is_lifetime() {
2349 let lifetime = self.get_lifetime();
2351 ex = ExprBreak(Some(lifetime));
2353 ex = ExprBreak(None);
2356 } else if self.check(&token::ModSep) ||
2357 self.token.is_ident() &&
2358 !self.token.is_keyword(keywords::True) &&
2359 !self.token.is_keyword(keywords::False) {
2361 self.parse_path(LifetimeAndTypesWithColons);
2363 // `!`, as an operator, is prefix, so we know this isn't that
2364 if self.check(&token::Not) {
2365 // MACRO INVOCATION expression
2368 let delim = self.expect_open_delim();
2369 let tts = self.parse_seq_to_end(
2370 &token::CloseDelim(delim),
2372 |p| p.parse_token_tree());
2373 let hi = self.span.hi;
2375 return self.mk_mac_expr(lo,
2381 if self.check(&token::OpenDelim(token::Brace)) {
2382 // This is a struct literal, unless we're prohibited
2383 // from parsing struct literals here.
2384 if !self.restrictions.contains(RESTRICTION_NO_STRUCT_LITERAL) {
2385 // It's a struct literal.
2387 let mut fields = Vec::new();
2388 let mut base = None;
2390 while self.token != token::CloseDelim(token::Brace) {
2391 if self.eat(&token::DotDot) {
2392 base = Some(self.parse_expr());
2396 fields.push(self.parse_field());
2397 self.commit_expr(&*fields.last().unwrap().expr,
2399 &[token::CloseDelim(token::Brace)]);
2402 if fields.len() == 0 && base.is_none() {
2403 let last_span = self.last_span;
2404 self.span_err(last_span,
2405 "structure literal must either \
2406 have at least one field or use \
2407 functional structure update \
2412 self.expect(&token::CloseDelim(token::Brace));
2413 ex = ExprStruct(pth, fields, base);
2414 return self.mk_expr(lo, hi, ex);
2421 // other literal expression
2422 let lit = self.parse_lit();
2424 ex = ExprLit(P(lit));
2429 return self.mk_expr(lo, hi, ex);
2432 /// Parse a block or unsafe block
2433 pub fn parse_block_expr(&mut self, lo: BytePos, blk_mode: BlockCheckMode)
2435 self.expect(&token::OpenDelim(token::Brace));
2436 let blk = self.parse_block_tail(lo, blk_mode);
2437 return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk));
2440 /// parse a.b or a(13) or a[4] or just a
2441 pub fn parse_dot_or_call_expr(&mut self) -> P<Expr> {
2442 let b = self.parse_bottom_expr();
2443 self.parse_dot_or_call_expr_with(b)
2446 pub fn parse_dot_or_call_expr_with(&mut self, e0: P<Expr>) -> P<Expr> {
2452 if self.eat(&token::Dot) {
2454 token::Ident(i, _) => {
2455 let dot = self.last_span.hi;
2458 let (_, tys, bindings) = if self.eat(&token::ModSep) {
2460 self.parse_generic_values_after_lt()
2462 (Vec::new(), Vec::new(), Vec::new())
2465 if bindings.len() > 0 {
2466 let last_span = self.last_span;
2467 self.span_err(last_span, "type bindings are only permitted on trait paths");
2470 // expr.f() method call
2472 token::OpenDelim(token::Paren) => {
2473 let mut es = self.parse_unspanned_seq(
2474 &token::OpenDelim(token::Paren),
2475 &token::CloseDelim(token::Paren),
2476 seq_sep_trailing_allowed(token::Comma),
2479 hi = self.last_span.hi;
2482 let id = spanned(dot, hi, i);
2483 let nd = self.mk_method_call(id, tys, es);
2484 e = self.mk_expr(lo, hi, nd);
2487 if !tys.is_empty() {
2488 let last_span = self.last_span;
2489 self.span_err(last_span,
2490 "field expressions may not \
2491 have type parameters");
2494 let id = spanned(dot, hi, i);
2495 let field = self.mk_field(e, id);
2496 e = self.mk_expr(lo, hi, field);
2500 token::Literal(token::Integer(n), suf) => {
2503 // A tuple index may not have a suffix
2504 self.expect_no_suffix(sp, "tuple index", suf);
2506 let dot = self.last_span.hi;
2510 let index = n.as_str().parse::<uint>();
2513 let id = spanned(dot, hi, n);
2514 let field = self.mk_tup_field(e, id);
2515 e = self.mk_expr(lo, hi, field);
2518 let last_span = self.last_span;
2519 self.span_err(last_span, "invalid tuple or tuple struct index");
2523 token::Literal(token::Float(n), _suf) => {
2525 let last_span = self.last_span;
2526 let fstr = n.as_str();
2527 self.span_err(last_span,
2528 format!("unexpected token: `{}`", n.as_str())[]);
2529 if fstr.chars().all(|x| "0123456789.".contains_char(x)) {
2530 let float = match fstr.parse::<f64>() {
2534 self.span_help(last_span,
2535 format!("try parenthesizing the first index; e.g., `(foo.{}){}`",
2536 float.trunc() as uint,
2537 float.fract().to_string()[1..])[]);
2539 self.abort_if_errors();
2542 _ => self.unexpected()
2546 if self.expr_is_complete(&*e) { break; }
2549 token::OpenDelim(token::Paren) => {
2550 let es = self.parse_unspanned_seq(
2551 &token::OpenDelim(token::Paren),
2552 &token::CloseDelim(token::Paren),
2553 seq_sep_trailing_allowed(token::Comma),
2556 hi = self.last_span.hi;
2558 let nd = self.mk_call(e, es);
2559 e = self.mk_expr(lo, hi, nd);
2563 // Could be either an index expression or a slicing expression.
2564 // Any slicing non-terminal can have a mutable version with `mut`
2565 // after the opening square bracket.
2566 token::OpenDelim(token::Bracket) => {
2568 let mutbl = if self.eat_keyword(keywords::Mut) {
2575 token::CloseDelim(token::Bracket) => {
2578 let slice = self.mk_slice(e, None, None, mutbl);
2579 e = self.mk_expr(lo, hi, slice)
2586 token::CloseDelim(token::Bracket) => {
2589 let slice = self.mk_slice(e, None, None, mutbl);
2590 e = self.mk_expr(lo, hi, slice);
2592 self.span_err(e.span, "incorrect slicing expression: `[..]`");
2593 self.span_note(e.span,
2594 "use `expr[]` to construct a slice of the whole of expr");
2599 let e2 = self.parse_expr();
2600 self.commit_expr_expecting(&*e2, token::CloseDelim(token::Bracket));
2601 let slice = self.mk_slice(e, None, Some(e2), mutbl);
2602 e = self.mk_expr(lo, hi, slice)
2606 // e[e] | e[e..] | e[e..e]
2608 let ix = self.parse_expr_res(RESTRICTION_NO_DOTS);
2613 let e2 = match self.token {
2615 token::CloseDelim(token::Bracket) => {
2621 let e2 = self.parse_expr_res(RESTRICTION_NO_DOTS);
2622 self.commit_expr_expecting(&*e2,
2623 token::CloseDelim(token::Bracket));
2628 let slice = self.mk_slice(e, Some(ix), e2, mutbl);
2629 e = self.mk_expr(lo, hi, slice)
2633 if mutbl == ast::MutMutable {
2634 self.span_err(e.span,
2635 "`mut` keyword is invalid in index expressions");
2638 self.commit_expr_expecting(&*ix, token::CloseDelim(token::Bracket));
2639 let index = self.mk_index(e, ix);
2640 e = self.mk_expr(lo, hi, index)
2647 // A range expression, either `expr..expr` or `expr..`.
2648 token::DotDot if !self.restrictions.contains(RESTRICTION_NO_DOTS) => {
2651 let opt_end = if self.token.can_begin_expr() {
2652 let end = self.parse_expr_res(RESTRICTION_NO_DOTS);
2658 let hi = self.span.hi;
2659 let range = self.mk_range(Some(e), opt_end);
2660 return self.mk_expr(lo, hi, range);
2668 /// Parse an optional separator followed by a Kleene-style
2669 /// repetition token (+ or *).
2670 pub fn parse_sep_and_kleene_op(&mut self) -> (Option<token::Token>, ast::KleeneOp) {
2671 fn parse_kleene_op(parser: &mut Parser) -> Option<ast::KleeneOp> {
2672 match parser.token {
2673 token::BinOp(token::Star) => {
2675 Some(ast::ZeroOrMore)
2677 token::BinOp(token::Plus) => {
2679 Some(ast::OneOrMore)
2685 match parse_kleene_op(self) {
2686 Some(kleene_op) => return (None, kleene_op),
2690 let separator = self.bump_and_get();
2691 match parse_kleene_op(self) {
2692 Some(zerok) => (Some(separator), zerok),
2693 None => self.fatal("expected `*` or `+`")
2697 /// parse a single token tree from the input.
2698 pub fn parse_token_tree(&mut self) -> TokenTree {
2699 // FIXME #6994: currently, this is too eager. It
2700 // parses token trees but also identifies TtSequence's
2701 // and token::SubstNt's; it's too early to know yet
2702 // whether something will be a nonterminal or a seq
2704 maybe_whole!(deref self, NtTT);
2706 // this is the fall-through for the 'match' below.
2707 // invariants: the current token is not a left-delimiter,
2708 // not an EOF, and not the desired right-delimiter (if
2709 // it were, parse_seq_to_before_end would have prevented
2710 // reaching this point.
2711 fn parse_non_delim_tt_tok(p: &mut Parser) -> TokenTree {
2712 maybe_whole!(deref p, NtTT);
2714 token::CloseDelim(_) => {
2715 // This is a conservative error: only report the last unclosed delimiter. The
2716 // previous unclosed delimiters could actually be closed! The parser just hasn't
2717 // gotten to them yet.
2718 match p.open_braces.last() {
2720 Some(&sp) => p.span_note(sp, "unclosed delimiter"),
2722 let token_str = p.this_token_to_string();
2723 p.fatal(format!("incorrect close delimiter: `{}`",
2726 /* we ought to allow different depths of unquotation */
2727 token::Dollar if p.quote_depth > 0u => {
2731 if p.token == token::OpenDelim(token::Paren) {
2732 let seq = p.parse_seq(
2733 &token::OpenDelim(token::Paren),
2734 &token::CloseDelim(token::Paren),
2736 |p| p.parse_token_tree()
2738 let (sep, repeat) = p.parse_sep_and_kleene_op();
2739 let seq = match seq {
2740 Spanned { node, .. } => node,
2742 let name_num = macro_parser::count_names(seq[]);
2743 TtSequence(mk_sp(sp.lo, p.span.hi),
2744 Rc::new(SequenceRepetition {
2748 num_captures: name_num
2751 // A nonterminal that matches or not
2752 let namep = match p.token { token::Ident(_, p) => p, _ => token::Plain };
2753 let name = p.parse_ident();
2754 if p.token == token::Colon && p.look_ahead(1, |t| t.is_ident()) {
2756 let kindp = match p.token { token::Ident(_, p) => p, _ => token::Plain };
2757 let nt_kind = p.parse_ident();
2758 let m = TtToken(sp, MatchNt(name, nt_kind, namep, kindp));
2761 TtToken(sp, SubstNt(name, namep))
2766 TtToken(p.span, p.bump_and_get())
2773 let open_braces = self.open_braces.clone();
2774 for sp in open_braces.iter() {
2775 self.span_help(*sp, "did you mean to close this delimiter?");
2777 // There shouldn't really be a span, but it's easier for the test runner
2778 // if we give it one
2779 self.fatal("this file contains an un-closed delimiter ");
2781 token::OpenDelim(delim) => {
2782 // The span for beginning of the delimited section
2783 let pre_span = self.span;
2785 // Parse the open delimiter.
2786 self.open_braces.push(self.span);
2787 let open_span = self.span;
2790 // Parse the token trees within the delimeters
2791 let tts = self.parse_seq_to_before_end(
2792 &token::CloseDelim(delim),
2794 |p| p.parse_token_tree()
2797 // Parse the close delimiter.
2798 let close_span = self.span;
2800 self.open_braces.pop().unwrap();
2802 // Expand to cover the entire delimited token tree
2803 let span = Span { hi: self.span.hi, ..pre_span };
2805 TtDelimited(span, Rc::new(Delimited {
2807 open_span: open_span,
2809 close_span: close_span,
2812 _ => parse_non_delim_tt_tok(self),
2816 // parse a stream of tokens into a list of TokenTree's,
2818 pub fn parse_all_token_trees(&mut self) -> Vec<TokenTree> {
2819 let mut tts = Vec::new();
2820 while self.token != token::Eof {
2821 tts.push(self.parse_token_tree());
2826 /// Parse a prefix-operator expr
2827 pub fn parse_prefix_expr(&mut self) -> P<Expr> {
2828 let lo = self.span.lo;
2835 let e = self.parse_prefix_expr();
2837 ex = self.mk_unary(UnNot, e);
2839 token::BinOp(token::Minus) => {
2841 let e = self.parse_prefix_expr();
2843 ex = self.mk_unary(UnNeg, e);
2845 token::BinOp(token::Star) => {
2847 let e = self.parse_prefix_expr();
2849 ex = self.mk_unary(UnDeref, e);
2851 token::BinOp(token::And) | token::AndAnd => {
2853 let m = self.parse_mutability();
2854 let e = self.parse_prefix_expr();
2856 ex = ExprAddrOf(m, e);
2860 let last_span = self.last_span;
2862 token::OpenDelim(token::Bracket) => {
2863 self.obsolete(last_span, ObsoleteOwnedVector)
2865 _ => self.obsolete(last_span, ObsoleteOwnedExpr)
2868 let e = self.parse_prefix_expr();
2870 ex = self.mk_unary(UnUniq, e);
2872 token::DotDot if !self.restrictions.contains(RESTRICTION_NO_DOTS) => {
2873 // A range, closed above: `..expr`.
2875 let e = self.parse_prefix_expr();
2877 ex = self.mk_range(None, Some(e));
2879 token::Ident(_, _) => {
2880 if !self.token.is_keyword(keywords::Box) {
2881 return self.parse_dot_or_call_expr();
2884 let lo = self.span.lo;
2888 // Check for a place: `box(PLACE) EXPR`.
2889 if self.eat(&token::OpenDelim(token::Paren)) {
2890 // Support `box() EXPR` as the default.
2891 if !self.eat(&token::CloseDelim(token::Paren)) {
2892 let place = self.parse_expr();
2893 self.expect(&token::CloseDelim(token::Paren));
2894 // Give a suggestion to use `box()` when a parenthesised expression is used
2895 if !self.token.can_begin_expr() {
2896 let span = self.span;
2897 let this_token_to_string = self.this_token_to_string();
2899 format!("expected expression, found `{}`",
2900 this_token_to_string)[]);
2901 let box_span = mk_sp(lo, self.last_span.hi);
2902 self.span_help(box_span,
2903 "perhaps you meant `box() (foo)` instead?");
2904 self.abort_if_errors();
2906 let subexpression = self.parse_prefix_expr();
2907 hi = subexpression.span.hi;
2908 ex = ExprBox(Some(place), subexpression);
2909 return self.mk_expr(lo, hi, ex);
2913 // Otherwise, we use the unique pointer default.
2914 let subexpression = self.parse_prefix_expr();
2915 hi = subexpression.span.hi;
2916 // FIXME (pnkfelix): After working out kinks with box
2917 // desugaring, should be `ExprBox(None, subexpression)`
2919 ex = self.mk_unary(UnUniq, subexpression);
2921 _ => return self.parse_dot_or_call_expr()
2923 return self.mk_expr(lo, hi, ex);
2926 /// Parse an expression of binops
2927 pub fn parse_binops(&mut self) -> P<Expr> {
2928 let prefix_expr = self.parse_prefix_expr();
2929 self.parse_more_binops(prefix_expr, 0)
2932 /// Parse an expression of binops of at least min_prec precedence
2933 pub fn parse_more_binops(&mut self, lhs: P<Expr>, min_prec: uint) -> P<Expr> {
2934 if self.expr_is_complete(&*lhs) { return lhs; }
2936 // Prevent dynamic borrow errors later on by limiting the
2937 // scope of the borrows.
2938 if self.token == token::BinOp(token::Or) &&
2939 self.restrictions.contains(RESTRICTION_NO_BAR_OP) {
2942 self.expected_tokens.push(TokenType::Operator);
2944 let cur_opt = self.token.to_binop();
2947 let cur_prec = operator_prec(cur_op);
2948 if cur_prec > min_prec {
2950 let expr = self.parse_prefix_expr();
2951 let rhs = self.parse_more_binops(expr, cur_prec);
2952 let lhs_span = lhs.span;
2953 let rhs_span = rhs.span;
2954 let binary = self.mk_binary(cur_op, lhs, rhs);
2955 let bin = self.mk_expr(lhs_span.lo, rhs_span.hi, binary);
2956 self.parse_more_binops(bin, min_prec)
2962 if as_prec > min_prec && self.eat_keyword(keywords::As) {
2963 let rhs = self.parse_ty();
2964 let _as = self.mk_expr(lhs.span.lo,
2966 ExprCast(lhs, rhs));
2967 self.parse_more_binops(_as, min_prec)
2975 /// Parse an assignment expression....
2976 /// actually, this seems to be the main entry point for
2977 /// parsing an arbitrary expression.
2978 pub fn parse_assign_expr(&mut self) -> P<Expr> {
2979 let lo = self.span.lo;
2980 let lhs = self.parse_binops();
2981 let restrictions = self.restrictions & RESTRICTION_NO_STRUCT_LITERAL;
2985 let rhs = self.parse_expr_res(restrictions);
2986 self.mk_expr(lo, rhs.span.hi, ExprAssign(lhs, rhs))
2988 token::BinOpEq(op) => {
2990 let rhs = self.parse_expr_res(restrictions);
2991 let aop = match op {
2992 token::Plus => BiAdd,
2993 token::Minus => BiSub,
2994 token::Star => BiMul,
2995 token::Slash => BiDiv,
2996 token::Percent => BiRem,
2997 token::Caret => BiBitXor,
2998 token::And => BiBitAnd,
2999 token::Or => BiBitOr,
3000 token::Shl => BiShl,
3003 let rhs_span = rhs.span;
3004 let assign_op = self.mk_assign_op(aop, lhs, rhs);
3005 self.mk_expr(lo, rhs_span.hi, assign_op)
3013 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
3014 pub fn parse_if_expr(&mut self) -> P<Expr> {
3015 if self.token.is_keyword(keywords::Let) {
3016 return self.parse_if_let_expr();
3018 let lo = self.last_span.lo;
3019 let cond = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
3020 let thn = self.parse_block();
3021 let mut els: Option<P<Expr>> = None;
3022 let mut hi = thn.span.hi;
3023 if self.eat_keyword(keywords::Else) {
3024 let elexpr = self.parse_else_expr();
3025 hi = elexpr.span.hi;
3028 self.mk_expr(lo, hi, ExprIf(cond, thn, els))
3031 /// Parse an 'if let' expression ('if' token already eaten)
3032 pub fn parse_if_let_expr(&mut self) -> P<Expr> {
3033 let lo = self.last_span.lo;
3034 self.expect_keyword(keywords::Let);
3035 let pat = self.parse_pat();
3036 self.expect(&token::Eq);
3037 let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
3038 let thn = self.parse_block();
3039 let (hi, els) = if self.eat_keyword(keywords::Else) {
3040 let expr = self.parse_else_expr();
3041 (expr.span.hi, Some(expr))
3045 self.mk_expr(lo, hi, ExprIfLet(pat, expr, thn, els))
3049 pub fn parse_lambda_expr(&mut self, capture_clause: CaptureClause)
3052 let lo = self.span.lo;
3053 let (decl, optional_unboxed_closure_kind) =
3054 self.parse_fn_block_decl();
3055 let body = self.parse_expr();
3056 let fakeblock = P(ast::Block {
3057 id: ast::DUMMY_NODE_ID,
3058 view_items: Vec::new(),
3062 rules: DefaultBlock,
3068 ExprClosure(capture_clause, optional_unboxed_closure_kind, decl, fakeblock))
3071 pub fn parse_else_expr(&mut self) -> P<Expr> {
3072 if self.eat_keyword(keywords::If) {
3073 return self.parse_if_expr();
3075 let blk = self.parse_block();
3076 return self.mk_expr(blk.span.lo, blk.span.hi, ExprBlock(blk));
3080 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3081 pub fn parse_for_expr(&mut self, opt_ident: Option<ast::Ident>) -> P<Expr> {
3082 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3084 let lo = self.last_span.lo;
3085 let pat = self.parse_pat();
3086 self.expect_keyword(keywords::In);
3087 let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
3088 let loop_block = self.parse_block();
3089 let hi = self.span.hi;
3091 self.mk_expr(lo, hi, ExprForLoop(pat, expr, loop_block, opt_ident))
3094 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3095 pub fn parse_while_expr(&mut self, opt_ident: Option<ast::Ident>) -> P<Expr> {
3096 if self.token.is_keyword(keywords::Let) {
3097 return self.parse_while_let_expr(opt_ident);
3099 let lo = self.last_span.lo;
3100 let cond = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
3101 let body = self.parse_block();
3102 let hi = body.span.hi;
3103 return self.mk_expr(lo, hi, ExprWhile(cond, body, opt_ident));
3106 /// Parse a 'while let' expression ('while' token already eaten)
3107 pub fn parse_while_let_expr(&mut self, opt_ident: Option<ast::Ident>) -> P<Expr> {
3108 let lo = self.last_span.lo;
3109 self.expect_keyword(keywords::Let);
3110 let pat = self.parse_pat();
3111 self.expect(&token::Eq);
3112 let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
3113 let body = self.parse_block();
3114 let hi = body.span.hi;
3115 return self.mk_expr(lo, hi, ExprWhileLet(pat, expr, body, opt_ident));
3118 pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::Ident>) -> P<Expr> {
3119 let lo = self.last_span.lo;
3120 let body = self.parse_block();
3121 let hi = body.span.hi;
3122 self.mk_expr(lo, hi, ExprLoop(body, opt_ident))
3125 fn parse_match_expr(&mut self) -> P<Expr> {
3126 let lo = self.last_span.lo;
3127 let discriminant = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL);
3128 self.commit_expr_expecting(&*discriminant, token::OpenDelim(token::Brace));
3129 let mut arms: Vec<Arm> = Vec::new();
3130 while self.token != token::CloseDelim(token::Brace) {
3131 arms.push(self.parse_arm());
3133 let hi = self.span.hi;
3135 return self.mk_expr(lo, hi, ExprMatch(discriminant, arms, MatchSource::Normal));
3138 pub fn parse_arm(&mut self) -> Arm {
3139 let attrs = self.parse_outer_attributes();
3140 let pats = self.parse_pats();
3141 let mut guard = None;
3142 if self.eat_keyword(keywords::If) {
3143 guard = Some(self.parse_expr());
3145 self.expect(&token::FatArrow);
3146 let expr = self.parse_expr_res(RESTRICTION_STMT_EXPR);
3149 !classify::expr_is_simple_block(&*expr)
3150 && self.token != token::CloseDelim(token::Brace);
3153 self.commit_expr(&*expr, &[token::Comma], &[token::CloseDelim(token::Brace)]);
3155 self.eat(&token::Comma);
3166 /// Parse an expression
3167 pub fn parse_expr(&mut self) -> P<Expr> {
3168 return self.parse_expr_res(UNRESTRICTED);
3171 /// Parse an expression, subject to the given restrictions
3172 pub fn parse_expr_res(&mut self, r: Restrictions) -> P<Expr> {
3173 let old = self.restrictions;
3174 self.restrictions = r;
3175 let e = self.parse_assign_expr();
3176 self.restrictions = old;
3180 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3181 fn parse_initializer(&mut self) -> Option<P<Expr>> {
3182 if self.check(&token::Eq) {
3184 Some(self.parse_expr())
3190 /// Parse patterns, separated by '|' s
3191 fn parse_pats(&mut self) -> Vec<P<Pat>> {
3192 let mut pats = Vec::new();
3194 pats.push(self.parse_pat());
3195 if self.check(&token::BinOp(token::Or)) { self.bump(); }
3196 else { return pats; }
3200 fn parse_pat_vec_elements(
3202 ) -> (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>) {
3203 let mut before = Vec::new();
3204 let mut slice = None;
3205 let mut after = Vec::new();
3206 let mut first = true;
3207 let mut before_slice = true;
3209 while self.token != token::CloseDelim(token::Bracket) {
3213 self.expect(&token::Comma);
3215 if self.token == token::CloseDelim(token::Bracket)
3216 && (before_slice || after.len() != 0) {
3222 if self.check(&token::DotDot) {
3225 if self.check(&token::Comma) ||
3226 self.check(&token::CloseDelim(token::Bracket)) {
3227 slice = Some(P(ast::Pat {
3228 id: ast::DUMMY_NODE_ID,
3229 node: PatWild(PatWildMulti),
3232 before_slice = false;
3234 let _ = self.parse_pat();
3235 let span = self.span;
3236 self.obsolete(span, ObsoleteSubsliceMatch);
3242 let subpat = self.parse_pat();
3243 if before_slice && self.check(&token::DotDot) {
3245 slice = Some(subpat);
3246 before_slice = false;
3247 } else if before_slice {
3248 before.push(subpat);
3254 (before, slice, after)
3257 /// Parse the fields of a struct-like pattern
3258 fn parse_pat_fields(&mut self) -> (Vec<codemap::Spanned<ast::FieldPat>> , bool) {
3259 let mut fields = Vec::new();
3260 let mut etc = false;
3261 let mut first = true;
3262 while self.token != token::CloseDelim(token::Brace) {
3266 self.expect(&token::Comma);
3267 // accept trailing commas
3268 if self.check(&token::CloseDelim(token::Brace)) { break }
3271 let lo = self.span.lo;
3274 if self.check(&token::DotDot) {
3276 if self.token != token::CloseDelim(token::Brace) {
3277 let token_str = self.this_token_to_string();
3278 self.fatal(format!("expected `{}`, found `{}`", "}",
3285 let bind_type = if self.eat_keyword(keywords::Mut) {
3286 BindByValue(MutMutable)
3287 } else if self.eat_keyword(keywords::Ref) {
3288 BindByRef(self.parse_mutability())
3290 BindByValue(MutImmutable)
3293 let fieldname = self.parse_ident();
3295 let (subpat, is_shorthand) = if self.check(&token::Colon) {
3297 BindByRef(..) | BindByValue(MutMutable) => {
3298 let token_str = self.this_token_to_string();
3299 self.fatal(format!("unexpected `{}`",
3306 let pat = self.parse_pat();
3310 hi = self.last_span.hi;
3311 let fieldpath = codemap::Spanned{span:self.last_span, node: fieldname};
3313 id: ast::DUMMY_NODE_ID,
3314 node: PatIdent(bind_type, fieldpath, None),
3315 span: self.last_span
3318 fields.push(codemap::Spanned { span: mk_sp(lo, hi),
3319 node: ast::FieldPat { ident: fieldname,
3321 is_shorthand: is_shorthand }});
3323 return (fields, etc);
3326 /// Parse a pattern.
3327 pub fn parse_pat(&mut self) -> P<Pat> {
3328 maybe_whole!(self, NtPat);
3330 let lo = self.span.lo;
3335 token::Underscore => {
3337 pat = PatWild(PatWildSingle);
3338 hi = self.last_span.hi;
3340 id: ast::DUMMY_NODE_ID,
3348 let sub = self.parse_pat();
3350 let last_span = self.last_span;
3352 self.obsolete(last_span, ObsoleteOwnedPattern);
3354 id: ast::DUMMY_NODE_ID,
3359 token::BinOp(token::And) | token::AndAnd => {
3361 let lo = self.span.lo;
3363 let sub = self.parse_pat();
3364 pat = PatRegion(sub);
3365 hi = self.last_span.hi;
3367 id: ast::DUMMY_NODE_ID,
3372 token::OpenDelim(token::Paren) => {
3373 // parse (pat,pat,pat,...) as tuple
3375 if self.check(&token::CloseDelim(token::Paren)) {
3377 pat = PatTup(vec![]);
3379 let mut fields = vec!(self.parse_pat());
3380 if self.look_ahead(1, |t| *t != token::CloseDelim(token::Paren)) {
3381 while self.check(&token::Comma) {
3383 if self.check(&token::CloseDelim(token::Paren)) { break; }
3384 fields.push(self.parse_pat());
3387 if fields.len() == 1 { self.expect(&token::Comma); }
3388 self.expect(&token::CloseDelim(token::Paren));
3389 pat = PatTup(fields);
3391 hi = self.last_span.hi;
3393 id: ast::DUMMY_NODE_ID,
3398 token::OpenDelim(token::Bracket) => {
3399 // parse [pat,pat,...] as vector pattern
3401 let (before, slice, after) =
3402 self.parse_pat_vec_elements();
3404 self.expect(&token::CloseDelim(token::Bracket));
3405 pat = ast::PatVec(before, slice, after);
3406 hi = self.last_span.hi;
3408 id: ast::DUMMY_NODE_ID,
3415 // at this point, token != _, ~, &, &&, (, [
3417 if (!(self.token.is_ident() || self.token.is_path())
3418 && self.token != token::ModSep)
3419 || self.token.is_keyword(keywords::True)
3420 || self.token.is_keyword(keywords::False) {
3421 // Parse an expression pattern or exp .. exp.
3423 // These expressions are limited to literals (possibly
3424 // preceded by unary-minus) or identifiers.
3425 let val = self.parse_literal_maybe_minus();
3426 if (self.check(&token::DotDotDot)) &&
3427 self.look_ahead(1, |t| {
3428 *t != token::Comma && *t != token::CloseDelim(token::Bracket)
3431 let end = if self.token.is_ident() || self.token.is_path() {
3432 let path = self.parse_path(LifetimeAndTypesWithColons);
3433 let hi = self.span.hi;
3434 self.mk_expr(lo, hi, ExprPath(path))
3436 self.parse_literal_maybe_minus()
3438 pat = PatRange(val, end);
3442 } else if self.eat_keyword(keywords::Mut) {
3443 pat = self.parse_pat_ident(BindByValue(MutMutable));
3444 } else if self.eat_keyword(keywords::Ref) {
3446 let mutbl = self.parse_mutability();
3447 pat = self.parse_pat_ident(BindByRef(mutbl));
3448 } else if self.eat_keyword(keywords::Box) {
3451 // FIXME(#13910): Rename to `PatBox` and extend to full DST
3453 let sub = self.parse_pat();
3455 hi = self.last_span.hi;
3457 id: ast::DUMMY_NODE_ID,
3462 let can_be_enum_or_struct = self.look_ahead(1, |t| {
3464 token::OpenDelim(_) | token::Lt | token::ModSep => true,
3469 if self.look_ahead(1, |t| *t == token::DotDotDot) &&
3470 self.look_ahead(2, |t| {
3471 *t != token::Comma && *t != token::CloseDelim(token::Bracket)
3473 let start = self.parse_expr_res(RESTRICTION_NO_BAR_OP);
3474 self.eat(&token::DotDotDot);
3475 let end = self.parse_expr_res(RESTRICTION_NO_BAR_OP);
3476 pat = PatRange(start, end);
3477 } else if self.token.is_plain_ident() && !can_be_enum_or_struct {
3478 let id = self.parse_ident();
3479 let id_span = self.last_span;
3480 let pth1 = codemap::Spanned{span:id_span, node: id};
3481 if self.eat(&token::Not) {
3483 let delim = self.expect_open_delim();
3484 let tts = self.parse_seq_to_end(&token::CloseDelim(delim),
3486 |p| p.parse_token_tree());
3488 let mac = MacInvocTT(ident_to_path(id_span,id), tts, EMPTY_CTXT);
3489 pat = ast::PatMac(codemap::Spanned {node: mac, span: self.span});
3491 let sub = if self.eat(&token::At) {
3493 Some(self.parse_pat())
3498 pat = PatIdent(BindByValue(MutImmutable), pth1, sub);
3501 // parse an enum pat
3502 let enum_path = self.parse_path(LifetimeAndTypesWithColons);
3504 token::OpenDelim(token::Brace) => {
3507 self.parse_pat_fields();
3509 pat = PatStruct(enum_path, fields, etc);
3512 let mut args: Vec<P<Pat>> = Vec::new();
3514 token::OpenDelim(token::Paren) => {
3515 let is_dotdot = self.look_ahead(1, |t| {
3517 token::DotDot => true,
3522 // This is a "top constructor only" pat
3525 self.expect(&token::CloseDelim(token::Paren));
3526 pat = PatEnum(enum_path, None);
3528 args = self.parse_enum_variant_seq(
3529 &token::OpenDelim(token::Paren),
3530 &token::CloseDelim(token::Paren),
3531 seq_sep_trailing_allowed(token::Comma),
3534 pat = PatEnum(enum_path, Some(args));
3538 if !enum_path.global &&
3539 enum_path.segments.len() == 1 &&
3540 enum_path.segments[0].parameters.is_empty()
3542 // it could still be either an enum
3543 // or an identifier pattern, resolve
3544 // will sort it out:
3545 pat = PatIdent(BindByValue(MutImmutable),
3547 span: enum_path.span,
3548 node: enum_path.segments[0]
3552 pat = PatEnum(enum_path, Some(args));
3560 hi = self.last_span.hi;
3562 id: ast::DUMMY_NODE_ID,
3564 span: mk_sp(lo, hi),
3568 /// Parse ident or ident @ pat
3569 /// used by the copy foo and ref foo patterns to give a good
3570 /// error message when parsing mistakes like ref foo(a,b)
3571 fn parse_pat_ident(&mut self,
3572 binding_mode: ast::BindingMode)
3574 if !self.token.is_plain_ident() {
3575 let span = self.span;
3576 let tok_str = self.this_token_to_string();
3577 self.span_fatal(span,
3578 format!("expected identifier, found `{}`", tok_str)[]);
3580 let ident = self.parse_ident();
3581 let last_span = self.last_span;
3582 let name = codemap::Spanned{span: last_span, node: ident};
3583 let sub = if self.eat(&token::At) {
3584 Some(self.parse_pat())
3589 // just to be friendly, if they write something like
3591 // we end up here with ( as the current token. This shortly
3592 // leads to a parse error. Note that if there is no explicit
3593 // binding mode then we do not end up here, because the lookahead
3594 // will direct us over to parse_enum_variant()
3595 if self.token == token::OpenDelim(token::Paren) {
3596 let last_span = self.last_span;
3599 "expected identifier, found enum pattern");
3602 PatIdent(binding_mode, name, sub)
3605 /// Parse a local variable declaration
3606 fn parse_local(&mut self) -> P<Local> {
3607 let lo = self.span.lo;
3608 let pat = self.parse_pat();
3611 if self.eat(&token::Colon) {
3612 ty = Some(self.parse_ty_sum());
3614 let init = self.parse_initializer();
3619 id: ast::DUMMY_NODE_ID,
3620 span: mk_sp(lo, self.last_span.hi),
3625 /// Parse a "let" stmt
3626 fn parse_let(&mut self) -> P<Decl> {
3627 let lo = self.span.lo;
3628 let local = self.parse_local();
3629 P(spanned(lo, self.last_span.hi, DeclLocal(local)))
3632 /// Parse a structure field
3633 fn parse_name_and_ty(&mut self, pr: Visibility,
3634 attrs: Vec<Attribute> ) -> StructField {
3635 let lo = self.span.lo;
3636 if !self.token.is_plain_ident() {
3637 self.fatal("expected ident");
3639 let name = self.parse_ident();
3640 self.expect(&token::Colon);
3641 let ty = self.parse_ty_sum();
3642 spanned(lo, self.last_span.hi, ast::StructField_ {
3643 kind: NamedField(name, pr),
3644 id: ast::DUMMY_NODE_ID,
3650 /// Get an expected item after attributes error message.
3651 fn expected_item_err(attrs: &[Attribute]) -> &'static str {
3652 match attrs.last() {
3653 Some(&Attribute { node: ast::Attribute_ { is_sugared_doc: true, .. }, .. }) => {
3654 "expected item after doc comment"
3656 _ => "expected item after attributes",
3660 /// Parse a statement. may include decl.
3661 /// Precondition: any attributes are parsed already
3662 pub fn parse_stmt(&mut self, item_attrs: Vec<Attribute>) -> P<Stmt> {
3663 maybe_whole!(self, NtStmt);
3665 fn check_expected_item(p: &mut Parser, attrs: &[Attribute]) {
3666 // If we have attributes then we should have an item
3667 if !attrs.is_empty() {
3668 let last_span = p.last_span;
3669 p.span_err(last_span, Parser::expected_item_err(attrs));
3673 let lo = self.span.lo;
3674 if self.token.is_keyword(keywords::Let) {
3675 check_expected_item(self, item_attrs[]);
3676 self.expect_keyword(keywords::Let);
3677 let decl = self.parse_let();
3678 P(spanned(lo, decl.span.hi, StmtDecl(decl, ast::DUMMY_NODE_ID)))
3679 } else if self.token.is_ident()
3680 && !self.token.is_any_keyword()
3681 && self.look_ahead(1, |t| *t == token::Not) {
3682 // it's a macro invocation:
3684 check_expected_item(self, item_attrs[]);
3686 // Potential trouble: if we allow macros with paths instead of
3687 // idents, we'd need to look ahead past the whole path here...
3688 let pth = self.parse_path(NoTypesAllowed);
3691 let id = match self.token {
3692 token::OpenDelim(_) => token::special_idents::invalid, // no special identifier
3693 _ => self.parse_ident(),
3696 // check that we're pointing at delimiters (need to check
3697 // again after the `if`, because of `parse_ident`
3698 // consuming more tokens).
3699 let delim = match self.token {
3700 token::OpenDelim(delim) => delim,
3702 // we only expect an ident if we didn't parse one
3704 let ident_str = if id.name == token::special_idents::invalid.name {
3709 let tok_str = self.this_token_to_string();
3710 self.fatal(format!("expected {}`(` or `{{`, found `{}`",
3716 let tts = self.parse_unspanned_seq(
3717 &token::OpenDelim(delim),
3718 &token::CloseDelim(delim),
3720 |p| p.parse_token_tree()
3722 let hi = self.span.hi;
3724 let style = if delim == token::Brace {
3727 MacStmtWithoutBraces
3730 if id.name == token::special_idents::invalid.name {
3733 StmtMac(P(spanned(lo,
3735 MacInvocTT(pth, tts, EMPTY_CTXT))),
3738 // if it has a special ident, it's definitely an item
3740 // Require a semicolon or braces.
3741 if style != MacStmtWithBraces {
3742 if !self.eat(&token::Semi) {
3743 let last_span = self.last_span;
3744 self.span_err(last_span,
3745 "macros that expand to items must \
3746 either be surrounded with braces or \
3747 followed by a semicolon");
3750 P(spanned(lo, hi, StmtDecl(
3751 P(spanned(lo, hi, DeclItem(
3753 lo, hi, id /*id is good here*/,
3754 ItemMac(spanned(lo, hi, MacInvocTT(pth, tts, EMPTY_CTXT))),
3755 Inherited, Vec::new(/*no attrs*/))))),
3756 ast::DUMMY_NODE_ID)))
3759 let found_attrs = !item_attrs.is_empty();
3760 let item_err = Parser::expected_item_err(item_attrs[]);
3761 match self.parse_item_or_view_item(item_attrs, false) {
3764 let decl = P(spanned(lo, hi, DeclItem(i)));
3765 P(spanned(lo, hi, StmtDecl(decl, ast::DUMMY_NODE_ID)))
3767 IoviViewItem(vi) => {
3768 self.span_fatal(vi.span,
3769 "view items must be declared at the top of the block");
3771 IoviForeignItem(_) => {
3772 self.fatal("foreign items are not allowed here");
3776 let last_span = self.last_span;
3777 self.span_err(last_span, item_err);
3780 // Remainder are line-expr stmts.
3781 let e = self.parse_expr_res(RESTRICTION_STMT_EXPR);
3782 P(spanned(lo, e.span.hi, StmtExpr(e, ast::DUMMY_NODE_ID)))
3788 /// Is this expression a successfully-parsed statement?
3789 fn expr_is_complete(&mut self, e: &Expr) -> bool {
3790 self.restrictions.contains(RESTRICTION_STMT_EXPR) &&
3791 !classify::expr_requires_semi_to_be_stmt(e)
3794 /// Parse a block. No inner attrs are allowed.
3795 pub fn parse_block(&mut self) -> P<Block> {
3796 maybe_whole!(no_clone self, NtBlock);
3798 let lo = self.span.lo;
3800 if !self.eat(&token::OpenDelim(token::Brace)) {
3802 let tok = self.this_token_to_string();
3803 self.span_fatal_help(sp,
3804 format!("expected `{{`, found `{}`", tok)[],
3805 "place this code inside a block");
3808 return self.parse_block_tail_(lo, DefaultBlock, Vec::new());
3811 /// Parse a block. Inner attrs are allowed.
3812 fn parse_inner_attrs_and_block(&mut self)
3813 -> (Vec<Attribute> , P<Block>) {
3815 maybe_whole!(pair_empty self, NtBlock);
3817 let lo = self.span.lo;
3818 self.expect(&token::OpenDelim(token::Brace));
3819 let (inner, next) = self.parse_inner_attrs_and_next();
3821 (inner, self.parse_block_tail_(lo, DefaultBlock, next))
3824 /// Precondition: already parsed the '{' or '#{'
3825 /// I guess that also means "already parsed the 'impure'" if
3826 /// necessary, and this should take a qualifier.
3827 /// Some blocks start with "#{"...
3828 fn parse_block_tail(&mut self, lo: BytePos, s: BlockCheckMode) -> P<Block> {
3829 self.parse_block_tail_(lo, s, Vec::new())
3832 /// Parse the rest of a block expression or function body
3833 fn parse_block_tail_(&mut self, lo: BytePos, s: BlockCheckMode,
3834 first_item_attrs: Vec<Attribute> ) -> P<Block> {
3835 let mut stmts = Vec::new();
3836 let mut expr = None;
3838 // wouldn't it be more uniform to parse view items only, here?
3839 let ParsedItemsAndViewItems {
3844 } = self.parse_items_and_view_items(first_item_attrs,
3847 for item in items.into_iter() {
3848 let span = item.span;
3849 let decl = P(spanned(span.lo, span.hi, DeclItem(item)));
3850 stmts.push(P(spanned(span.lo, span.hi, StmtDecl(decl, ast::DUMMY_NODE_ID))));
3853 let mut attributes_box = attrs_remaining;
3855 while self.token != token::CloseDelim(token::Brace) {
3856 // parsing items even when they're not allowed lets us give
3857 // better error messages and recover more gracefully.
3858 attributes_box.push_all(self.parse_outer_attributes()[]);
3861 if !attributes_box.is_empty() {
3862 let last_span = self.last_span;
3863 self.span_err(last_span,
3864 Parser::expected_item_err(attributes_box[]));
3865 attributes_box = Vec::new();
3867 self.bump(); // empty
3869 token::CloseDelim(token::Brace) => {
3870 // fall through and out.
3873 let stmt = self.parse_stmt(attributes_box);
3874 attributes_box = Vec::new();
3875 stmt.and_then(|Spanned {node, span}| match node {
3876 StmtExpr(e, stmt_id) => {
3877 self.handle_expression_like_statement(e,
3883 StmtMac(macro, MacStmtWithoutBraces) => {
3884 // statement macro without braces; might be an
3885 // expr depending on whether a semicolon follows
3888 stmts.push(P(Spanned {
3889 node: StmtMac(macro,
3890 MacStmtWithSemicolon),
3896 let e = self.mk_mac_expr(span.lo,
3898 macro.and_then(|m| m.node));
3900 self.parse_dot_or_call_expr_with(e);
3901 self.handle_expression_like_statement(
3910 StmtMac(m, style) => {
3911 // statement macro; might be an expr
3914 stmts.push(P(Spanned {
3916 MacStmtWithSemicolon),
3921 token::CloseDelim(token::Brace) => {
3922 // if a block ends in `m!(arg)` without
3923 // a `;`, it must be an expr
3925 self.mk_mac_expr(span.lo,
3927 m.and_then(|x| x.node)));
3930 stmts.push(P(Spanned {
3931 node: StmtMac(m, style),
3937 _ => { // all other kinds of statements:
3938 if classify::stmt_ends_with_semi(&node) {
3939 self.commit_stmt_expecting(token::Semi);
3942 stmts.push(P(Spanned {
3952 if !attributes_box.is_empty() {
3953 let last_span = self.last_span;
3954 self.span_err(last_span,
3955 Parser::expected_item_err(attributes_box[]));
3958 let hi = self.span.hi;
3961 view_items: view_items,
3964 id: ast::DUMMY_NODE_ID,
3966 span: mk_sp(lo, hi),
3970 fn handle_expression_like_statement(
3975 stmts: &mut Vec<P<Stmt>>,
3976 last_block_expr: &mut Option<P<Expr>>) {
3977 // expression without semicolon
3978 if classify::expr_requires_semi_to_be_stmt(&*e) {
3979 // Just check for errors and recover; do not eat semicolon yet.
3980 self.commit_stmt(&[],
3981 &[token::Semi, token::CloseDelim(token::Brace)]);
3987 let span_with_semi = Span {
3989 hi: self.last_span.hi,
3990 expn_id: span.expn_id,
3992 stmts.push(P(Spanned {
3993 node: StmtSemi(e, stmt_id),
3994 span: span_with_semi,
3997 token::CloseDelim(token::Brace) => *last_block_expr = Some(e),
3999 stmts.push(P(Spanned {
4000 node: StmtExpr(e, stmt_id),
4007 // Parses a sequence of bounds if a `:` is found,
4008 // otherwise returns empty list.
4009 fn parse_colon_then_ty_param_bounds(&mut self,
4010 mode: BoundParsingMode)
4011 -> OwnedSlice<TyParamBound>
4013 if !self.eat(&token::Colon) {
4016 self.parse_ty_param_bounds(mode)
4020 // matches bounds = ( boundseq )?
4021 // where boundseq = ( polybound + boundseq ) | polybound
4022 // and polybound = ( 'for' '<' 'region '>' )? bound
4023 // and bound = 'region | trait_ref
4024 fn parse_ty_param_bounds(&mut self,
4025 mode: BoundParsingMode)
4026 -> OwnedSlice<TyParamBound>
4028 let mut result = vec!();
4030 let question_span = self.span;
4031 let ate_question = self.eat(&token::Question);
4033 token::Lifetime(lifetime) => {
4035 self.span_err(question_span,
4036 "`?` may only modify trait bounds, not lifetime bounds");
4038 result.push(RegionTyParamBound(ast::Lifetime {
4039 id: ast::DUMMY_NODE_ID,
4045 token::ModSep | token::Ident(..) => {
4046 let poly_trait_ref = self.parse_poly_trait_ref();
4047 let modifier = if ate_question {
4048 if mode == BoundParsingMode::Modified {
4049 TraitBoundModifier::Maybe
4051 self.span_err(question_span,
4053 TraitBoundModifier::None
4056 TraitBoundModifier::None
4058 result.push(TraitTyParamBound(poly_trait_ref, modifier))
4063 if !self.eat(&token::BinOp(token::Plus)) {
4068 return OwnedSlice::from_vec(result);
4071 fn trait_ref_from_ident(ident: Ident, span: Span) -> TraitRef {
4072 let segment = ast::PathSegment {
4074 parameters: ast::PathParameters::none()
4076 let path = ast::Path {
4079 segments: vec![segment],
4083 ref_id: ast::DUMMY_NODE_ID,
4087 /// Matches typaram = (unbound `?`)? IDENT (`?` unbound)? optbounds ( EQ ty )?
4088 fn parse_ty_param(&mut self) -> TyParam {
4089 // This is a bit hacky. Currently we are only interested in a single
4090 // unbound, and it may only be `Sized`. To avoid backtracking and other
4091 // complications, we parse an ident, then check for `?`. If we find it,
4092 // we use the ident as the unbound, otherwise, we use it as the name of
4093 // type param. Even worse, for now, we need to check for `?` before or
4095 let mut span = self.span;
4096 let mut ident = self.parse_ident();
4097 let mut unbound = None;
4098 if self.eat(&token::Question) {
4099 let tref = Parser::trait_ref_from_ident(ident, span);
4100 unbound = Some(tref);
4102 ident = self.parse_ident();
4105 let mut bounds = self.parse_colon_then_ty_param_bounds(BoundParsingMode::Modified);
4106 if let Some(unbound) = unbound {
4107 let mut bounds_as_vec = bounds.into_vec();
4108 bounds_as_vec.push(TraitTyParamBound(PolyTraitRef { bound_lifetimes: vec![],
4109 trait_ref: unbound },
4110 TraitBoundModifier::Maybe));
4111 bounds = OwnedSlice::from_vec(bounds_as_vec);
4114 let default = if self.check(&token::Eq) {
4116 Some(self.parse_ty_sum())
4122 id: ast::DUMMY_NODE_ID,
4129 /// Parse a set of optional generic type parameter declarations. Where
4130 /// clauses are not parsed here, and must be added later via
4131 /// `parse_where_clause()`.
4133 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
4134 /// | ( < lifetimes , typaramseq ( , )? > )
4135 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
4136 pub fn parse_generics(&mut self) -> ast::Generics {
4137 if self.eat(&token::Lt) {
4138 let lifetime_defs = self.parse_lifetime_defs();
4139 let mut seen_default = false;
4140 let ty_params = self.parse_seq_to_gt(Some(token::Comma), |p| {
4141 p.forbid_lifetime();
4142 let ty_param = p.parse_ty_param();
4143 if ty_param.default.is_some() {
4144 seen_default = true;
4145 } else if seen_default {
4146 let last_span = p.last_span;
4147 p.span_err(last_span,
4148 "type parameters with a default must be trailing");
4153 lifetimes: lifetime_defs,
4154 ty_params: ty_params,
4155 where_clause: WhereClause {
4156 id: ast::DUMMY_NODE_ID,
4157 predicates: Vec::new(),
4161 ast_util::empty_generics()
4165 fn parse_generic_values_after_lt(&mut self)
4166 -> (Vec<ast::Lifetime>, Vec<P<Ty>>, Vec<P<TypeBinding>>) {
4167 let lifetimes = self.parse_lifetimes(token::Comma);
4169 // First parse types.
4170 let (types, returned) = self.parse_seq_to_gt_or_return(
4173 p.forbid_lifetime();
4174 if p.look_ahead(1, |t| t == &token::Eq) {
4177 Some(p.parse_ty_sum())
4182 // If we found the `>`, don't continue.
4184 return (lifetimes, types.into_vec(), Vec::new());
4187 // Then parse type bindings.
4188 let bindings = self.parse_seq_to_gt(
4191 p.forbid_lifetime();
4193 let ident = p.parse_ident();
4194 let found_eq = p.eat(&token::Eq);
4197 p.span_warn(span, "whoops, no =?");
4199 let ty = p.parse_ty();
4201 let span = mk_sp(lo, hi);
4202 return P(TypeBinding{id: ast::DUMMY_NODE_ID,
4209 (lifetimes, types.into_vec(), bindings.into_vec())
4212 fn forbid_lifetime(&mut self) {
4213 if self.token.is_lifetime() {
4214 let span = self.span;
4215 self.span_fatal(span, "lifetime parameters must be declared \
4216 prior to type parameters");
4220 /// Parses an optional `where` clause and places it in `generics`.
4223 /// where T : Trait<U, V> + 'b, 'a : 'b
4225 fn parse_where_clause(&mut self, generics: &mut ast::Generics) {
4226 if !self.eat_keyword(keywords::Where) {
4230 let mut parsed_something = false;
4232 let lo = self.span.lo;
4234 token::OpenDelim(token::Brace) => {
4238 token::Lifetime(..) => {
4239 let bounded_lifetime =
4240 self.parse_lifetime();
4242 self.eat(&token::Colon);
4245 self.parse_lifetimes(token::BinOp(token::Plus));
4247 let hi = self.span.hi;
4248 let span = mk_sp(lo, hi);
4250 generics.where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
4251 ast::WhereRegionPredicate {
4253 lifetime: bounded_lifetime,
4258 parsed_something = true;
4262 let bounded_ty = self.parse_ty();
4264 if self.eat(&token::Colon) {
4265 let bounds = self.parse_ty_param_bounds(BoundParsingMode::Bare);
4266 let hi = self.span.hi;
4267 let span = mk_sp(lo, hi);
4269 if bounds.len() == 0 {
4271 "each predicate in a `where` clause must have \
4272 at least one bound in it");
4275 generics.where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
4276 ast::WhereBoundPredicate {
4278 bounded_ty: bounded_ty,
4282 parsed_something = true;
4283 } else if self.eat(&token::Eq) {
4284 // let ty = self.parse_ty();
4285 let hi = self.span.hi;
4286 let span = mk_sp(lo, hi);
4287 // generics.where_clause.predicates.push(
4288 // ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
4289 // id: ast::DUMMY_NODE_ID,
4291 // path: panic!("NYI"), //bounded_ty,
4294 // parsed_something = true;
4297 "equality constraints are not yet supported \
4298 in where clauses (#20041)");
4300 let last_span = self.last_span;
4301 self.span_err(last_span,
4302 "unexpected token in `where` clause");
4307 if !self.eat(&token::Comma) {
4312 if !parsed_something {
4313 let last_span = self.last_span;
4314 self.span_err(last_span,
4315 "a `where` clause must have at least one predicate \
4320 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
4321 -> (Vec<Arg> , bool) {
4323 let mut args: Vec<Option<Arg>> =
4324 self.parse_unspanned_seq(
4325 &token::OpenDelim(token::Paren),
4326 &token::CloseDelim(token::Paren),
4327 seq_sep_trailing_allowed(token::Comma),
4329 if p.token == token::DotDotDot {
4332 if p.token != token::CloseDelim(token::Paren) {
4335 "`...` must be last in argument list for variadic function");
4340 "only foreign functions are allowed to be variadic");
4344 Some(p.parse_arg_general(named_args))
4349 let variadic = match args.pop() {
4352 // Need to put back that last arg
4359 if variadic && args.is_empty() {
4361 "variadic function must be declared with at least one named argument");
4364 let args = args.into_iter().map(|x| x.unwrap()).collect();
4369 /// Parse the argument list and result type of a function declaration
4370 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> P<FnDecl> {
4372 let (args, variadic) = self.parse_fn_args(true, allow_variadic);
4373 let ret_ty = self.parse_ret_ty();
4382 fn is_self_ident(&mut self) -> bool {
4384 token::Ident(id, token::Plain) => id.name == special_idents::self_.name,
4389 fn expect_self_ident(&mut self) -> ast::Ident {
4391 token::Ident(id, token::Plain) if id.name == special_idents::self_.name => {
4396 let token_str = self.this_token_to_string();
4397 self.fatal(format!("expected `self`, found `{}`",
4403 /// Parse the argument list and result type of a function
4404 /// that may have a self type.
4405 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> (ExplicitSelf, P<FnDecl>) where
4406 F: FnMut(&mut Parser) -> Arg,
4408 fn maybe_parse_borrowed_explicit_self(this: &mut Parser)
4409 -> ast::ExplicitSelf_ {
4410 // The following things are possible to see here:
4415 // fn(&'lt mut self)
4417 // We already know that the current token is `&`.
4419 if this.look_ahead(1, |t| t.is_keyword(keywords::Self)) {
4421 SelfRegion(None, MutImmutable, this.expect_self_ident())
4422 } else if this.look_ahead(1, |t| t.is_mutability()) &&
4423 this.look_ahead(2, |t| t.is_keyword(keywords::Self)) {
4425 let mutability = this.parse_mutability();
4426 SelfRegion(None, mutability, this.expect_self_ident())
4427 } else if this.look_ahead(1, |t| t.is_lifetime()) &&
4428 this.look_ahead(2, |t| t.is_keyword(keywords::Self)) {
4430 let lifetime = this.parse_lifetime();
4431 SelfRegion(Some(lifetime), MutImmutable, this.expect_self_ident())
4432 } else if this.look_ahead(1, |t| t.is_lifetime()) &&
4433 this.look_ahead(2, |t| t.is_mutability()) &&
4434 this.look_ahead(3, |t| t.is_keyword(keywords::Self)) {
4436 let lifetime = this.parse_lifetime();
4437 let mutability = this.parse_mutability();
4438 SelfRegion(Some(lifetime), mutability, this.expect_self_ident())
4444 self.expect(&token::OpenDelim(token::Paren));
4446 // A bit of complexity and lookahead is needed here in order to be
4447 // backwards compatible.
4448 let lo = self.span.lo;
4449 let mut self_ident_lo = self.span.lo;
4450 let mut self_ident_hi = self.span.hi;
4452 let mut mutbl_self = MutImmutable;
4453 let explicit_self = match self.token {
4454 token::BinOp(token::And) => {
4455 let eself = maybe_parse_borrowed_explicit_self(self);
4456 self_ident_lo = self.last_span.lo;
4457 self_ident_hi = self.last_span.hi;
4461 // We need to make sure it isn't a type
4462 if self.look_ahead(1, |t| t.is_keyword(keywords::Self)) {
4464 drop(self.expect_self_ident());
4465 let last_span = self.last_span;
4466 self.obsolete(last_span, ObsoleteOwnedSelf)
4470 token::BinOp(token::Star) => {
4471 // Possibly "*self" or "*mut self" -- not supported. Try to avoid
4472 // emitting cryptic "unexpected token" errors.
4474 let _mutability = if self.token.is_mutability() {
4475 self.parse_mutability()
4479 if self.is_self_ident() {
4480 let span = self.span;
4481 self.span_err(span, "cannot pass self by unsafe pointer");
4484 // error case, making bogus self ident:
4485 SelfValue(special_idents::self_)
4487 token::Ident(..) => {
4488 if self.is_self_ident() {
4489 let self_ident = self.expect_self_ident();
4491 // Determine whether this is the fully explicit form, `self:
4493 if self.eat(&token::Colon) {
4494 SelfExplicit(self.parse_ty_sum(), self_ident)
4496 SelfValue(self_ident)
4498 } else if self.token.is_mutability() &&
4499 self.look_ahead(1, |t| t.is_keyword(keywords::Self)) {
4500 mutbl_self = self.parse_mutability();
4501 let self_ident = self.expect_self_ident();
4503 // Determine whether this is the fully explicit form,
4505 if self.eat(&token::Colon) {
4506 SelfExplicit(self.parse_ty_sum(), self_ident)
4508 SelfValue(self_ident)
4510 } else if self.token.is_mutability() &&
4511 self.look_ahead(1, |t| *t == token::Tilde) &&
4512 self.look_ahead(2, |t| t.is_keyword(keywords::Self)) {
4513 mutbl_self = self.parse_mutability();
4515 drop(self.expect_self_ident());
4516 let last_span = self.last_span;
4517 self.obsolete(last_span, ObsoleteOwnedSelf);
4526 let explicit_self_sp = mk_sp(self_ident_lo, self_ident_hi);
4528 // shared fall-through for the three cases below. borrowing prevents simply
4529 // writing this as a closure
4530 macro_rules! parse_remaining_arguments {
4533 // If we parsed a self type, expect a comma before the argument list.
4537 let sep = seq_sep_trailing_allowed(token::Comma);
4538 let mut fn_inputs = self.parse_seq_to_before_end(
4539 &token::CloseDelim(token::Paren),
4543 fn_inputs.insert(0, Arg::new_self(explicit_self_sp, mutbl_self, $self_id));
4546 token::CloseDelim(token::Paren) => {
4547 vec!(Arg::new_self(explicit_self_sp, mutbl_self, $self_id))
4550 let token_str = self.this_token_to_string();
4551 self.fatal(format!("expected `,` or `)`, found `{}`",
4558 let fn_inputs = match explicit_self {
4560 let sep = seq_sep_trailing_allowed(token::Comma);
4561 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)
4563 SelfValue(id) => parse_remaining_arguments!(id),
4564 SelfRegion(_,_,id) => parse_remaining_arguments!(id),
4565 SelfExplicit(_,id) => parse_remaining_arguments!(id),
4569 self.expect(&token::CloseDelim(token::Paren));
4571 let hi = self.span.hi;
4573 let ret_ty = self.parse_ret_ty();
4575 let fn_decl = P(FnDecl {
4581 (spanned(lo, hi, explicit_self), fn_decl)
4584 // parse the |arg, arg| header on a lambda
4585 fn parse_fn_block_decl(&mut self)
4586 -> (P<FnDecl>, Option<UnboxedClosureKind>) {
4587 let (optional_unboxed_closure_kind, inputs_captures) = {
4588 if self.eat(&token::OrOr) {
4591 self.expect(&token::BinOp(token::Or));
4592 let optional_unboxed_closure_kind =
4593 self.parse_optional_unboxed_closure_kind();
4594 let args = self.parse_seq_to_before_end(
4595 &token::BinOp(token::Or),
4596 seq_sep_trailing_allowed(token::Comma),
4597 |p| p.parse_fn_block_arg()
4600 (optional_unboxed_closure_kind, args)
4603 let output = if self.check(&token::RArrow) {
4607 id: ast::DUMMY_NODE_ID,
4614 inputs: inputs_captures,
4617 }), optional_unboxed_closure_kind)
4620 /// Parses the `(arg, arg) -> return_type` header on a procedure.
4621 fn parse_proc_decl(&mut self) -> P<FnDecl> {
4623 self.parse_unspanned_seq(&token::OpenDelim(token::Paren),
4624 &token::CloseDelim(token::Paren),
4625 seq_sep_trailing_allowed(token::Comma),
4626 |p| p.parse_fn_block_arg());
4628 let output = if self.check(&token::RArrow) {
4632 id: ast::DUMMY_NODE_ID,
4645 /// Parse the name and optional generic types of a function header.
4646 fn parse_fn_header(&mut self) -> (Ident, ast::Generics) {
4647 let id = self.parse_ident();
4648 let generics = self.parse_generics();
4652 fn mk_item(&mut self, lo: BytePos, hi: BytePos, ident: Ident,
4653 node: Item_, vis: Visibility,
4654 attrs: Vec<Attribute>) -> P<Item> {
4658 id: ast::DUMMY_NODE_ID,
4665 /// Parse an item-position function declaration.
4666 fn parse_item_fn(&mut self, unsafety: Unsafety, abi: abi::Abi) -> ItemInfo {
4667 let (ident, mut generics) = self.parse_fn_header();
4668 let decl = self.parse_fn_decl(false);
4669 self.parse_where_clause(&mut generics);
4670 let (inner_attrs, body) = self.parse_inner_attrs_and_block();
4671 (ident, ItemFn(decl, unsafety, abi, generics, body), Some(inner_attrs))
4674 /// Parse a method in a trait impl
4675 pub fn parse_method_with_outer_attributes(&mut self) -> P<Method> {
4676 let attrs = self.parse_outer_attributes();
4677 let visa = self.parse_visibility();
4678 self.parse_method(attrs, visa)
4681 /// Parse a method in a trait impl, starting with `attrs` attributes.
4682 pub fn parse_method(&mut self,
4683 attrs: Vec<Attribute>,
4686 let lo = self.span.lo;
4688 // code copied from parse_macro_use_or_failure... abstraction!
4689 let (method_, hi, new_attrs) = {
4690 if !self.token.is_any_keyword()
4691 && self.look_ahead(1, |t| *t == token::Not)
4692 && (self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren))
4693 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) {
4695 let pth = self.parse_path(NoTypesAllowed);
4696 self.expect(&token::Not);
4698 // eat a matched-delimiter token tree:
4699 let delim = self.expect_open_delim();
4700 let tts = self.parse_seq_to_end(&token::CloseDelim(delim),
4702 |p| p.parse_token_tree());
4703 let m_ = ast::MacInvocTT(pth, tts, EMPTY_CTXT);
4704 let m: ast::Mac = codemap::Spanned { node: m_,
4705 span: mk_sp(self.span.lo,
4707 if delim != token::Brace {
4708 self.expect(&token::Semi)
4710 (ast::MethMac(m), self.span.hi, attrs)
4712 let unsafety = self.parse_unsafety();
4713 let abi = if self.eat_keyword(keywords::Extern) {
4714 self.parse_opt_abi().unwrap_or(abi::C)
4718 self.expect_keyword(keywords::Fn);
4719 let ident = self.parse_ident();
4720 let mut generics = self.parse_generics();
4721 let (explicit_self, decl) = self.parse_fn_decl_with_self(|p| {
4724 self.parse_where_clause(&mut generics);
4725 let (inner_attrs, body) = self.parse_inner_attrs_and_block();
4726 let body_span = body.span;
4727 let mut new_attrs = attrs;
4728 new_attrs.push_all(inner_attrs[]);
4729 (ast::MethDecl(ident,
4737 body_span.hi, new_attrs)
4742 id: ast::DUMMY_NODE_ID,
4743 span: mk_sp(lo, hi),
4748 /// Parse trait Foo { ... }
4749 fn parse_item_trait(&mut self, unsafety: Unsafety) -> ItemInfo {
4750 let ident = self.parse_ident();
4751 let mut tps = self.parse_generics();
4752 let unbound = self.parse_for_sized();
4754 // Parse supertrait bounds.
4755 let mut bounds = self.parse_colon_then_ty_param_bounds(BoundParsingMode::Bare);
4757 if let Some(unbound) = unbound {
4758 let mut bounds_as_vec = bounds.into_vec();
4759 bounds_as_vec.push(TraitTyParamBound(PolyTraitRef { bound_lifetimes: vec![],
4760 trait_ref: unbound },
4761 TraitBoundModifier::Maybe));
4762 bounds = OwnedSlice::from_vec(bounds_as_vec);
4765 self.parse_where_clause(&mut tps);
4767 let meths = self.parse_trait_items();
4768 (ident, ItemTrait(unsafety, tps, bounds, meths), None)
4771 fn parse_impl_items(&mut self) -> (Vec<ImplItem>, Vec<Attribute>) {
4772 let mut impl_items = Vec::new();
4773 self.expect(&token::OpenDelim(token::Brace));
4774 let (inner_attrs, mut method_attrs) =
4775 self.parse_inner_attrs_and_next();
4776 while !self.eat(&token::CloseDelim(token::Brace)) {
4777 method_attrs.extend(self.parse_outer_attributes().into_iter());
4778 let vis = self.parse_visibility();
4779 if self.eat_keyword(keywords::Type) {
4780 impl_items.push(TypeImplItem(P(self.parse_typedef(
4784 impl_items.push(MethodImplItem(self.parse_method(
4788 method_attrs = self.parse_outer_attributes();
4790 (impl_items, inner_attrs)
4793 /// Parses two variants (with the region/type params always optional):
4794 /// impl<T> Foo { ... }
4795 /// impl<T> ToString for ~[T] { ... }
4796 fn parse_item_impl(&mut self, unsafety: ast::Unsafety) -> ItemInfo {
4797 // First, parse type parameters if necessary.
4798 let mut generics = self.parse_generics();
4800 // Special case: if the next identifier that follows is '(', don't
4801 // allow this to be parsed as a trait.
4802 let could_be_trait = self.token != token::OpenDelim(token::Paren);
4805 let mut ty = self.parse_ty_sum();
4807 // Parse traits, if necessary.
4808 let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) {
4809 // New-style trait. Reinterpret the type as a trait.
4810 let opt_trait_ref = match ty.node {
4811 TyPath(ref path, node_id) => {
4813 path: (*path).clone(),
4818 self.span_err(ty.span, "not a trait");
4823 ty = self.parse_ty_sum();
4829 self.parse_where_clause(&mut generics);
4830 let (impl_items, attrs) = self.parse_impl_items();
4832 let ident = ast_util::impl_pretty_name(&opt_trait, &*ty);
4835 ItemImpl(unsafety, generics, opt_trait, ty, impl_items),
4839 /// Parse a::B<String,int>
4840 fn parse_trait_ref(&mut self) -> TraitRef {
4842 path: self.parse_path(LifetimeAndTypesWithoutColons),
4843 ref_id: ast::DUMMY_NODE_ID,
4847 fn parse_late_bound_lifetime_defs(&mut self) -> Vec<ast::LifetimeDef> {
4848 if self.eat_keyword(keywords::For) {
4849 self.expect(&token::Lt);
4850 let lifetime_defs = self.parse_lifetime_defs();
4858 /// Parse for<'l> a::B<String,int>
4859 fn parse_poly_trait_ref(&mut self) -> PolyTraitRef {
4860 let lifetime_defs = self.parse_late_bound_lifetime_defs();
4863 bound_lifetimes: lifetime_defs,
4864 trait_ref: self.parse_trait_ref()
4868 /// Parse struct Foo { ... }
4869 fn parse_item_struct(&mut self) -> ItemInfo {
4870 let class_name = self.parse_ident();
4871 let mut generics = self.parse_generics();
4873 if self.eat(&token::Colon) {
4874 let ty = self.parse_ty_sum();
4875 self.span_err(ty.span, "`virtual` structs have been removed from the language");
4878 self.parse_where_clause(&mut generics);
4880 let mut fields: Vec<StructField>;
4883 if self.eat(&token::OpenDelim(token::Brace)) {
4884 // It's a record-like struct.
4885 is_tuple_like = false;
4886 fields = Vec::new();
4887 while self.token != token::CloseDelim(token::Brace) {
4888 fields.push(self.parse_struct_decl_field(true));
4890 if fields.len() == 0 {
4891 self.fatal(format!("unit-like struct definition should be \
4892 written as `struct {};`",
4893 token::get_ident(class_name))[]);
4896 } else if self.check(&token::OpenDelim(token::Paren)) {
4897 // It's a tuple-like struct.
4898 is_tuple_like = true;
4899 fields = self.parse_unspanned_seq(
4900 &token::OpenDelim(token::Paren),
4901 &token::CloseDelim(token::Paren),
4902 seq_sep_trailing_allowed(token::Comma),
4904 let attrs = p.parse_outer_attributes();
4906 let struct_field_ = ast::StructField_ {
4907 kind: UnnamedField(p.parse_visibility()),
4908 id: ast::DUMMY_NODE_ID,
4909 ty: p.parse_ty_sum(),
4912 spanned(lo, p.span.hi, struct_field_)
4914 if fields.len() == 0 {
4915 self.fatal(format!("unit-like struct definition should be \
4916 written as `struct {};`",
4917 token::get_ident(class_name))[]);
4919 self.expect(&token::Semi);
4920 } else if self.eat(&token::Semi) {
4921 // It's a unit-like struct.
4922 is_tuple_like = true;
4923 fields = Vec::new();
4925 let token_str = self.this_token_to_string();
4926 self.fatal(format!("expected `{}`, `(`, or `;` after struct \
4927 name, found `{}`", "{",
4931 let _ = ast::DUMMY_NODE_ID; // FIXME: Workaround for crazy bug.
4932 let new_id = ast::DUMMY_NODE_ID;
4934 ItemStruct(P(ast::StructDef {
4936 ctor_id: if is_tuple_like { Some(new_id) } else { None },
4941 /// Parse a structure field declaration
4942 pub fn parse_single_struct_field(&mut self,
4944 attrs: Vec<Attribute> )
4946 let a_var = self.parse_name_and_ty(vis, attrs);
4951 token::CloseDelim(token::Brace) => {}
4953 let span = self.span;
4954 let token_str = self.this_token_to_string();
4955 self.span_fatal_help(span,
4956 format!("expected `,`, or `}}`, found `{}`",
4958 "struct fields should be separated by commas")
4964 /// Parse an element of a struct definition
4965 fn parse_struct_decl_field(&mut self, allow_pub: bool) -> StructField {
4967 let attrs = self.parse_outer_attributes();
4969 if self.eat_keyword(keywords::Pub) {
4971 let span = self.last_span;
4972 self.span_err(span, "`pub` is not allowed here");
4974 return self.parse_single_struct_field(Public, attrs);
4977 return self.parse_single_struct_field(Inherited, attrs);
4980 /// Parse visibility: PUB, PRIV, or nothing
4981 fn parse_visibility(&mut self) -> Visibility {
4982 if self.eat_keyword(keywords::Pub) { Public }
4986 fn parse_for_sized(&mut self) -> Option<ast::TraitRef> {
4987 // FIXME, this should really use TraitBoundModifier, but it will get
4988 // re-jigged shortly in any case, so leaving the hacky version for now.
4989 if self.eat_keyword(keywords::For) {
4990 let span = self.span;
4991 let mut ate_question = false;
4992 if self.eat(&token::Question) {
4993 ate_question = true;
4995 let ident = self.parse_ident();
4996 if self.eat(&token::Question) {
5001 ate_question = true;
5005 "expected `?Sized` after `for` in trait item");
5008 let tref = Parser::trait_ref_from_ident(ident, span);
5015 /// Given a termination token and a vector of already-parsed
5016 /// attributes (of length 0 or 1), parse all of the items in a module
5017 fn parse_mod_items(&mut self,
5019 first_item_attrs: Vec<Attribute>,
5022 // parse all of the items up to closing or an attribute.
5023 // view items are legal here.
5024 let ParsedItemsAndViewItems {
5027 items: starting_items,
5029 } = self.parse_items_and_view_items(first_item_attrs, true, true);
5030 let mut items: Vec<P<Item>> = starting_items;
5031 let attrs_remaining_len = attrs_remaining.len();
5033 // don't think this other loop is even necessary....
5035 let mut first = true;
5036 while self.token != term {
5037 let mut attrs = self.parse_outer_attributes();
5039 let mut tmp = attrs_remaining.clone();
5040 tmp.push_all(attrs[]);
5044 debug!("parse_mod_items: parse_item_or_view_item(attrs={})",
5046 match self.parse_item_or_view_item(attrs,
5047 true /* macros allowed */) {
5048 IoviItem(item) => items.push(item),
5049 IoviViewItem(view_item) => {
5050 self.span_fatal(view_item.span,
5051 "view items must be declared at the top of \
5055 let token_str = self.this_token_to_string();
5056 self.fatal(format!("expected item, found `{}`",
5062 if first && attrs_remaining_len > 0u {
5063 // We parsed attributes for the first item but didn't find it
5064 let last_span = self.last_span;
5065 self.span_err(last_span,
5066 Parser::expected_item_err(attrs_remaining[]));
5070 inner: mk_sp(inner_lo, self.span.lo),
5071 view_items: view_items,
5076 fn parse_item_const(&mut self, m: Option<Mutability>) -> ItemInfo {
5077 let id = self.parse_ident();
5078 self.expect(&token::Colon);
5079 let ty = self.parse_ty_sum();
5080 self.expect(&token::Eq);
5081 let e = self.parse_expr();
5082 self.commit_expr_expecting(&*e, token::Semi);
5083 let item = match m {
5084 Some(m) => ItemStatic(ty, m, e),
5085 None => ItemConst(ty, e),
5090 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
5091 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> ItemInfo {
5092 let id_span = self.span;
5093 let id = self.parse_ident();
5094 if self.check(&token::Semi) {
5096 // This mod is in an external file. Let's go get it!
5097 let (m, attrs) = self.eval_src_mod(id, outer_attrs, id_span);
5098 (id, m, Some(attrs))
5100 self.push_mod_path(id, outer_attrs);
5101 self.expect(&token::OpenDelim(token::Brace));
5102 let mod_inner_lo = self.span.lo;
5103 let old_owns_directory = self.owns_directory;
5104 self.owns_directory = true;
5105 let (inner, next) = self.parse_inner_attrs_and_next();
5106 let m = self.parse_mod_items(token::CloseDelim(token::Brace), next, mod_inner_lo);
5107 self.expect(&token::CloseDelim(token::Brace));
5108 self.owns_directory = old_owns_directory;
5109 self.pop_mod_path();
5110 (id, ItemMod(m), Some(inner))
5114 fn push_mod_path(&mut self, id: Ident, attrs: &[Attribute]) {
5115 let default_path = self.id_to_interned_str(id);
5116 let file_path = match ::attr::first_attr_value_str_by_name(attrs,
5119 None => default_path,
5121 self.mod_path_stack.push(file_path)
5124 fn pop_mod_path(&mut self) {
5125 self.mod_path_stack.pop().unwrap();
5128 /// Read a module from a source file.
5129 fn eval_src_mod(&mut self,
5131 outer_attrs: &[ast::Attribute],
5133 -> (ast::Item_, Vec<ast::Attribute> ) {
5134 let mut prefix = Path::new(self.sess.span_diagnostic.cm.span_to_filename(self.span));
5136 let mod_path = Path::new(".").join_many(self.mod_path_stack[]);
5137 let dir_path = prefix.join(&mod_path);
5138 let mod_string = token::get_ident(id);
5139 let (file_path, owns_directory) = match ::attr::first_attr_value_str_by_name(
5140 outer_attrs, "path") {
5141 Some(d) => (dir_path.join(d), true),
5143 let mod_name = mod_string.get().to_string();
5144 let default_path_str = format!("{}.rs", mod_name);
5145 let secondary_path_str = format!("{}/mod.rs", mod_name);
5146 let default_path = dir_path.join(default_path_str[]);
5147 let secondary_path = dir_path.join(secondary_path_str[]);
5148 let default_exists = default_path.exists();
5149 let secondary_exists = secondary_path.exists();
5151 if !self.owns_directory {
5152 self.span_err(id_sp,
5153 "cannot declare a new module at this location");
5154 let this_module = match self.mod_path_stack.last() {
5155 Some(name) => name.get().to_string(),
5156 None => self.root_module_name.as_ref().unwrap().clone(),
5158 self.span_note(id_sp,
5159 format!("maybe move this module `{0}` \
5160 to its own directory via \
5163 if default_exists || secondary_exists {
5164 self.span_note(id_sp,
5165 format!("... or maybe `use` the module \
5166 `{}` instead of possibly \
5170 self.abort_if_errors();
5173 match (default_exists, secondary_exists) {
5174 (true, false) => (default_path, false),
5175 (false, true) => (secondary_path, true),
5177 self.span_fatal_help(id_sp,
5178 format!("file not found for module `{}`",
5180 format!("name the file either {} or {} inside \
5184 dir_path.display())[]);
5187 self.span_fatal_help(
5189 format!("file for module `{}` found at both {} \
5193 secondary_path_str)[],
5194 "delete or rename one of them to remove the ambiguity");
5200 self.eval_src_mod_from_path(file_path, owns_directory,
5201 mod_string.get().to_string(), id_sp)
5204 fn eval_src_mod_from_path(&mut self,
5206 owns_directory: bool,
5208 id_sp: Span) -> (ast::Item_, Vec<ast::Attribute> ) {
5209 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
5210 match included_mod_stack.iter().position(|p| *p == path) {
5212 let mut err = String::from_str("circular modules: ");
5213 let len = included_mod_stack.len();
5214 for p in included_mod_stack.slice(i, len).iter() {
5215 err.push_str(p.display().as_cow()[]);
5216 err.push_str(" -> ");
5218 err.push_str(path.display().as_cow()[]);
5219 self.span_fatal(id_sp, err[]);
5223 included_mod_stack.push(path.clone());
5224 drop(included_mod_stack);
5227 new_sub_parser_from_file(self.sess,
5233 let mod_inner_lo = p0.span.lo;
5234 let (mod_attrs, next) = p0.parse_inner_attrs_and_next();
5235 let first_item_outer_attrs = next;
5236 let m0 = p0.parse_mod_items(token::Eof, first_item_outer_attrs, mod_inner_lo);
5237 self.sess.included_mod_stack.borrow_mut().pop();
5238 return (ast::ItemMod(m0), mod_attrs);
5241 /// Parse a function declaration from a foreign module
5242 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility,
5243 attrs: Vec<Attribute>) -> P<ForeignItem> {
5244 let lo = self.span.lo;
5245 self.expect_keyword(keywords::Fn);
5247 let (ident, mut generics) = self.parse_fn_header();
5248 let decl = self.parse_fn_decl(true);
5249 self.parse_where_clause(&mut generics);
5250 let hi = self.span.hi;
5251 self.expect(&token::Semi);
5252 P(ast::ForeignItem {
5255 node: ForeignItemFn(decl, generics),
5256 id: ast::DUMMY_NODE_ID,
5257 span: mk_sp(lo, hi),
5262 /// Parse a static item from a foreign module
5263 fn parse_item_foreign_static(&mut self, vis: ast::Visibility,
5264 attrs: Vec<Attribute>) -> P<ForeignItem> {
5265 let lo = self.span.lo;
5267 self.expect_keyword(keywords::Static);
5268 let mutbl = self.eat_keyword(keywords::Mut);
5270 let ident = self.parse_ident();
5271 self.expect(&token::Colon);
5272 let ty = self.parse_ty_sum();
5273 let hi = self.span.hi;
5274 self.expect(&token::Semi);
5278 node: ForeignItemStatic(ty, mutbl),
5279 id: ast::DUMMY_NODE_ID,
5280 span: mk_sp(lo, hi),
5285 /// At this point, this is essentially a wrapper for
5286 /// parse_foreign_items.
5287 fn parse_foreign_mod_items(&mut self,
5289 first_item_attrs: Vec<Attribute> )
5291 let ParsedItemsAndViewItems {
5296 } = self.parse_foreign_items(first_item_attrs, true);
5297 if !attrs_remaining.is_empty() {
5298 let last_span = self.last_span;
5299 self.span_err(last_span,
5300 Parser::expected_item_err(attrs_remaining[]));
5302 assert!(self.token == token::CloseDelim(token::Brace));
5305 view_items: view_items,
5306 items: foreign_items
5310 /// Parse extern crate links
5314 /// extern crate url;
5315 /// extern crate foo = "bar"; //deprecated
5316 /// extern crate "bar" as foo;
5317 fn parse_item_extern_crate(&mut self,
5319 visibility: Visibility,
5320 attrs: Vec<Attribute> )
5323 let span = self.span;
5324 let (maybe_path, ident) = match self.token {
5325 token::Ident(..) => {
5326 let the_ident = self.parse_ident();
5327 let path = if self.token == token::Eq {
5329 let path = self.parse_str();
5330 let span = self.span;
5331 self.obsolete(span, ObsoleteExternCrateRenaming);
5333 } else if self.eat_keyword(keywords::As) {
5334 // skip the ident if there is one
5335 if self.token.is_ident() { self.bump(); }
5337 self.span_err(span, "expected `;`, found `as`");
5338 self.span_help(span,
5339 format!("perhaps you meant to enclose the crate name `{}` in \
5341 the_ident.as_str())[]);
5346 self.expect(&token::Semi);
5349 token::Literal(token::Str_(..), suf) | token::Literal(token::StrRaw(..), suf) => {
5351 self.expect_no_suffix(sp, "extern crate name", suf);
5352 // forgo the internal suffix check of `parse_str` to
5353 // avoid repeats (this unwrap will always succeed due
5354 // to the restriction of the `match`)
5355 let (s, style, _) = self.parse_optional_str().unwrap();
5356 self.expect_keyword(keywords::As);
5357 let the_ident = self.parse_ident();
5358 self.expect(&token::Semi);
5359 (Some((s, style)), the_ident)
5362 let span = self.span;
5363 let token_str = self.this_token_to_string();
5364 self.span_fatal(span,
5365 format!("expected extern crate name but \
5371 IoviViewItem(ast::ViewItem {
5372 node: ViewItemExternCrate(ident, maybe_path, ast::DUMMY_NODE_ID),
5375 span: mk_sp(lo, self.last_span.hi)
5379 /// Parse `extern` for foreign ABIs
5382 /// `extern` is expected to have been
5383 /// consumed before calling this method
5389 fn parse_item_foreign_mod(&mut self,
5391 opt_abi: Option<abi::Abi>,
5392 visibility: Visibility,
5393 attrs: Vec<Attribute> )
5396 self.expect(&token::OpenDelim(token::Brace));
5398 let abi = opt_abi.unwrap_or(abi::C);
5400 let (inner, next) = self.parse_inner_attrs_and_next();
5401 let m = self.parse_foreign_mod_items(abi, next);
5402 self.expect(&token::CloseDelim(token::Brace));
5404 let last_span = self.last_span;
5405 let item = self.mk_item(lo,
5407 special_idents::invalid,
5410 maybe_append(attrs, Some(inner)));
5411 return IoviItem(item);
5414 /// Parse type Foo = Bar;
5415 fn parse_item_type(&mut self) -> ItemInfo {
5416 let ident = self.parse_ident();
5417 let mut tps = self.parse_generics();
5418 self.parse_where_clause(&mut tps);
5419 self.expect(&token::Eq);
5420 let ty = self.parse_ty_sum();
5421 self.expect(&token::Semi);
5422 (ident, ItemTy(ty, tps), None)
5425 /// Parse a structure-like enum variant definition
5426 /// this should probably be renamed or refactored...
5427 fn parse_struct_def(&mut self) -> P<StructDef> {
5428 let mut fields: Vec<StructField> = Vec::new();
5429 while self.token != token::CloseDelim(token::Brace) {
5430 fields.push(self.parse_struct_decl_field(false));
5440 /// Parse the part of an "enum" decl following the '{'
5441 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> EnumDef {
5442 let mut variants = Vec::new();
5443 let mut all_nullary = true;
5444 let mut any_disr = None;
5445 while self.token != token::CloseDelim(token::Brace) {
5446 let variant_attrs = self.parse_outer_attributes();
5447 let vlo = self.span.lo;
5449 let vis = self.parse_visibility();
5453 let mut args = Vec::new();
5454 let mut disr_expr = None;
5455 ident = self.parse_ident();
5456 if self.eat(&token::OpenDelim(token::Brace)) {
5457 // Parse a struct variant.
5458 all_nullary = false;
5459 let start_span = self.span;
5460 let struct_def = self.parse_struct_def();
5461 if struct_def.fields.len() == 0 {
5462 self.span_err(start_span,
5463 format!("unit-like struct variant should be written \
5464 without braces, as `{},`",
5465 token::get_ident(ident))[]);
5467 kind = StructVariantKind(struct_def);
5468 } else if self.check(&token::OpenDelim(token::Paren)) {
5469 all_nullary = false;
5470 let arg_tys = self.parse_enum_variant_seq(
5471 &token::OpenDelim(token::Paren),
5472 &token::CloseDelim(token::Paren),
5473 seq_sep_trailing_allowed(token::Comma),
5474 |p| p.parse_ty_sum()
5476 for ty in arg_tys.into_iter() {
5477 args.push(ast::VariantArg {
5479 id: ast::DUMMY_NODE_ID,
5482 kind = TupleVariantKind(args);
5483 } else if self.eat(&token::Eq) {
5484 disr_expr = Some(self.parse_expr());
5485 any_disr = disr_expr.as_ref().map(|expr| expr.span);
5486 kind = TupleVariantKind(args);
5488 kind = TupleVariantKind(Vec::new());
5491 let vr = ast::Variant_ {
5493 attrs: variant_attrs,
5495 id: ast::DUMMY_NODE_ID,
5496 disr_expr: disr_expr,
5499 variants.push(P(spanned(vlo, self.last_span.hi, vr)));
5501 if !self.eat(&token::Comma) { break; }
5503 self.expect(&token::CloseDelim(token::Brace));
5505 Some(disr_span) if !all_nullary =>
5506 self.span_err(disr_span,
5507 "discriminator values can only be used with a c-like enum"),
5511 ast::EnumDef { variants: variants }
5514 /// Parse an "enum" declaration
5515 fn parse_item_enum(&mut self) -> ItemInfo {
5516 let id = self.parse_ident();
5517 let mut generics = self.parse_generics();
5518 self.parse_where_clause(&mut generics);
5519 self.expect(&token::OpenDelim(token::Brace));
5521 let enum_definition = self.parse_enum_def(&generics);
5522 (id, ItemEnum(enum_definition, generics), None)
5525 fn fn_expr_lookahead(tok: &token::Token) -> bool {
5527 token::OpenDelim(token::Paren) | token::At | token::Tilde | token::BinOp(_) => true,
5532 /// Parses a string as an ABI spec on an extern type or module. Consumes
5533 /// the `extern` keyword, if one is found.
5534 fn parse_opt_abi(&mut self) -> Option<abi::Abi> {
5536 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
5538 self.expect_no_suffix(sp, "ABI spec", suf);
5540 let the_string = s.as_str();
5541 match abi::lookup(the_string) {
5542 Some(abi) => Some(abi),
5544 let last_span = self.last_span;
5547 format!("illegal ABI: expected one of [{}], \
5549 abi::all_names().connect(", "),
5560 /// Parse one of the items or view items allowed by the
5561 /// flags; on failure, return IoviNone.
5562 /// NB: this function no longer parses the items inside an
5564 fn parse_item_or_view_item(&mut self,
5565 attrs: Vec<Attribute> ,
5566 macros_allowed: bool)
5568 let nt_item = match self.token {
5569 token::Interpolated(token::NtItem(ref item)) => {
5570 Some((**item).clone())
5577 let mut attrs = attrs;
5578 mem::swap(&mut item.attrs, &mut attrs);
5579 item.attrs.extend(attrs.into_iter());
5580 return IoviItem(P(item));
5585 let lo = self.span.lo;
5587 let visibility = self.parse_visibility();
5589 // must be a view item:
5590 if self.eat_keyword(keywords::Use) {
5591 // USE ITEM (IoviViewItem)
5592 let view_item = self.parse_use();
5593 self.expect(&token::Semi);
5594 return IoviViewItem(ast::ViewItem {
5598 span: mk_sp(lo, self.last_span.hi)
5601 // either a view item or an item:
5602 if self.eat_keyword(keywords::Extern) {
5603 let next_is_mod = self.eat_keyword(keywords::Mod);
5605 if next_is_mod || self.eat_keyword(keywords::Crate) {
5607 let last_span = self.last_span;
5608 self.span_err(mk_sp(lo, last_span.hi),
5609 format!("`extern mod` is obsolete, use \
5610 `extern crate` instead \
5611 to refer to external \
5614 return self.parse_item_extern_crate(lo, visibility, attrs);
5617 let opt_abi = self.parse_opt_abi();
5619 if self.eat_keyword(keywords::Fn) {
5620 // EXTERN FUNCTION ITEM
5621 let abi = opt_abi.unwrap_or(abi::C);
5622 let (ident, item_, extra_attrs) =
5623 self.parse_item_fn(Unsafety::Normal, abi);
5624 let last_span = self.last_span;
5625 let item = self.mk_item(lo,
5630 maybe_append(attrs, extra_attrs));
5631 return IoviItem(item);
5632 } else if self.check(&token::OpenDelim(token::Brace)) {
5633 return self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs);
5636 let span = self.span;
5637 let token_str = self.this_token_to_string();
5638 self.span_fatal(span,
5639 format!("expected `{}` or `fn`, found `{}`", "{",
5643 if self.eat_keyword(keywords::Virtual) {
5644 let span = self.span;
5645 self.span_err(span, "`virtual` structs have been removed from the language");
5648 // the rest are all guaranteed to be items:
5649 if self.token.is_keyword(keywords::Static) {
5652 let m = if self.eat_keyword(keywords::Mut) {MutMutable} else {MutImmutable};
5653 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m));
5654 let last_span = self.last_span;
5655 let item = self.mk_item(lo,
5660 maybe_append(attrs, extra_attrs));
5661 return IoviItem(item);
5663 if self.token.is_keyword(keywords::Const) {
5666 if self.eat_keyword(keywords::Mut) {
5667 let last_span = self.last_span;
5668 self.span_err(last_span, "const globals cannot be mutable");
5669 self.span_help(last_span, "did you mean to declare a static?");
5671 let (ident, item_, extra_attrs) = self.parse_item_const(None);
5672 let last_span = self.last_span;
5673 let item = self.mk_item(lo,
5678 maybe_append(attrs, extra_attrs));
5679 return IoviItem(item);
5681 if self.token.is_keyword(keywords::Unsafe) &&
5682 self.look_ahead(1u, |t| t.is_keyword(keywords::Trait))
5684 // UNSAFE TRAIT ITEM
5685 self.expect_keyword(keywords::Unsafe);
5686 self.expect_keyword(keywords::Trait);
5687 let (ident, item_, extra_attrs) =
5688 self.parse_item_trait(ast::Unsafety::Unsafe);
5689 let last_span = self.last_span;
5690 let item = self.mk_item(lo,
5695 maybe_append(attrs, extra_attrs));
5696 return IoviItem(item);
5698 if self.token.is_keyword(keywords::Unsafe) &&
5699 self.look_ahead(1u, |t| t.is_keyword(keywords::Impl))
5702 self.expect_keyword(keywords::Unsafe);
5703 self.expect_keyword(keywords::Impl);
5704 let (ident, item_, extra_attrs) = self.parse_item_impl(ast::Unsafety::Unsafe);
5705 let last_span = self.last_span;
5706 let item = self.mk_item(lo,
5711 maybe_append(attrs, extra_attrs));
5712 return IoviItem(item);
5714 if self.token.is_keyword(keywords::Fn) &&
5715 self.look_ahead(1, |f| !Parser::fn_expr_lookahead(f)) {
5718 let (ident, item_, extra_attrs) =
5719 self.parse_item_fn(Unsafety::Normal, abi::Rust);
5720 let last_span = self.last_span;
5721 let item = self.mk_item(lo,
5726 maybe_append(attrs, extra_attrs));
5727 return IoviItem(item);
5729 if self.token.is_keyword(keywords::Unsafe)
5730 && self.look_ahead(1u, |t| *t != token::OpenDelim(token::Brace)) {
5731 // UNSAFE FUNCTION ITEM
5733 let abi = if self.eat_keyword(keywords::Extern) {
5734 self.parse_opt_abi().unwrap_or(abi::C)
5738 self.expect_keyword(keywords::Fn);
5739 let (ident, item_, extra_attrs) =
5740 self.parse_item_fn(Unsafety::Unsafe, abi);
5741 let last_span = self.last_span;
5742 let item = self.mk_item(lo,
5747 maybe_append(attrs, extra_attrs));
5748 return IoviItem(item);
5750 if self.eat_keyword(keywords::Mod) {
5752 let (ident, item_, extra_attrs) =
5753 self.parse_item_mod(attrs[]);
5754 let last_span = self.last_span;
5755 let item = self.mk_item(lo,
5760 maybe_append(attrs, extra_attrs));
5761 return IoviItem(item);
5763 if self.eat_keyword(keywords::Type) {
5765 let (ident, item_, extra_attrs) = self.parse_item_type();
5766 let last_span = self.last_span;
5767 let item = self.mk_item(lo,
5772 maybe_append(attrs, extra_attrs));
5773 return IoviItem(item);
5775 if self.eat_keyword(keywords::Enum) {
5777 let (ident, item_, extra_attrs) = self.parse_item_enum();
5778 let last_span = self.last_span;
5779 let item = self.mk_item(lo,
5784 maybe_append(attrs, extra_attrs));
5785 return IoviItem(item);
5787 if self.eat_keyword(keywords::Trait) {
5789 let (ident, item_, extra_attrs) =
5790 self.parse_item_trait(ast::Unsafety::Normal);
5791 let last_span = self.last_span;
5792 let item = self.mk_item(lo,
5797 maybe_append(attrs, extra_attrs));
5798 return IoviItem(item);
5800 if self.eat_keyword(keywords::Impl) {
5802 let (ident, item_, extra_attrs) = self.parse_item_impl(ast::Unsafety::Normal);
5803 let last_span = self.last_span;
5804 let item = self.mk_item(lo,
5809 maybe_append(attrs, extra_attrs));
5810 return IoviItem(item);
5812 if self.eat_keyword(keywords::Struct) {
5814 let (ident, item_, extra_attrs) = self.parse_item_struct();
5815 let last_span = self.last_span;
5816 let item = self.mk_item(lo,
5821 maybe_append(attrs, extra_attrs));
5822 return IoviItem(item);
5824 self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility)
5827 /// Parse a foreign item; on failure, return IoviNone.
5828 fn parse_foreign_item(&mut self,
5829 attrs: Vec<Attribute> ,
5830 macros_allowed: bool)
5832 maybe_whole!(iovi self, NtItem);
5833 let lo = self.span.lo;
5835 let visibility = self.parse_visibility();
5837 if self.token.is_keyword(keywords::Static) {
5838 // FOREIGN STATIC ITEM
5839 let item = self.parse_item_foreign_static(visibility, attrs);
5840 return IoviForeignItem(item);
5842 if self.token.is_keyword(keywords::Fn) || self.token.is_keyword(keywords::Unsafe) {
5843 // FOREIGN FUNCTION ITEM
5844 let item = self.parse_item_foreign_fn(visibility, attrs);
5845 return IoviForeignItem(item);
5847 self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility)
5850 /// This is the fall-through for parsing items.
5851 fn parse_macro_use_or_failure(
5853 attrs: Vec<Attribute> ,
5854 macros_allowed: bool,
5856 visibility: Visibility
5857 ) -> ItemOrViewItem {
5858 if macros_allowed && !self.token.is_any_keyword()
5859 && self.look_ahead(1, |t| *t == token::Not)
5860 && (self.look_ahead(2, |t| t.is_plain_ident())
5861 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren))
5862 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) {
5863 // MACRO INVOCATION ITEM
5866 let pth = self.parse_path(NoTypesAllowed);
5867 self.expect(&token::Not);
5869 // a 'special' identifier (like what `macro_rules!` uses)
5870 // is optional. We should eventually unify invoc syntax
5872 let id = if self.token.is_plain_ident() {
5875 token::special_idents::invalid // no special identifier
5877 // eat a matched-delimiter token tree:
5878 let delim = self.expect_open_delim();
5879 let tts = self.parse_seq_to_end(&token::CloseDelim(delim),
5881 |p| p.parse_token_tree());
5882 // single-variant-enum... :
5883 let m = ast::MacInvocTT(pth, tts, EMPTY_CTXT);
5884 let m: ast::Mac = codemap::Spanned { node: m,
5885 span: mk_sp(self.span.lo,
5888 if delim != token::Brace {
5889 if !self.eat(&token::Semi) {
5890 let last_span = self.last_span;
5891 self.span_err(last_span,
5892 "macros that expand to items must either \
5893 be surrounded with braces or followed by \
5898 let item_ = ItemMac(m);
5899 let last_span = self.last_span;
5900 let item = self.mk_item(lo,
5906 return IoviItem(item);
5909 // FAILURE TO PARSE ITEM
5913 let last_span = self.last_span;
5914 self.span_fatal(last_span, "unmatched visibility `pub`");
5917 return IoviNone(attrs);
5920 pub fn parse_item_with_outer_attributes(&mut self) -> Option<P<Item>> {
5921 let attrs = self.parse_outer_attributes();
5922 self.parse_item(attrs)
5925 pub fn parse_item(&mut self, attrs: Vec<Attribute>) -> Option<P<Item>> {
5926 match self.parse_item_or_view_item(attrs, true) {
5927 IoviNone(_) => None,
5929 self.fatal("view items are not allowed here"),
5930 IoviForeignItem(_) =>
5931 self.fatal("foreign items are not allowed here"),
5932 IoviItem(item) => Some(item)
5936 /// Parse a ViewItem, e.g. `use foo::bar` or `extern crate foo`
5937 pub fn parse_view_item(&mut self, attrs: Vec<Attribute>) -> ViewItem {
5938 match self.parse_item_or_view_item(attrs, false) {
5939 IoviViewItem(vi) => vi,
5940 _ => self.fatal("expected `use` or `extern crate`"),
5944 /// Parse, e.g., "use a::b::{z,y}"
5945 fn parse_use(&mut self) -> ViewItem_ {
5946 return ViewItemUse(self.parse_view_path());
5950 /// Matches view_path : MOD? non_global_path as IDENT
5951 /// | MOD? non_global_path MOD_SEP LBRACE RBRACE
5952 /// | MOD? non_global_path MOD_SEP LBRACE ident_seq RBRACE
5953 /// | MOD? non_global_path MOD_SEP STAR
5954 /// | MOD? non_global_path
5955 fn parse_view_path(&mut self) -> P<ViewPath> {
5956 let lo = self.span.lo;
5958 if self.check(&token::OpenDelim(token::Brace)) {
5960 let idents = self.parse_unspanned_seq(
5961 &token::OpenDelim(token::Brace),
5962 &token::CloseDelim(token::Brace),
5963 seq_sep_trailing_allowed(token::Comma),
5964 |p| p.parse_path_list_item());
5965 let path = ast::Path {
5966 span: mk_sp(lo, self.span.hi),
5968 segments: Vec::new()
5970 return P(spanned(lo, self.span.hi,
5971 ViewPathList(path, idents, ast::DUMMY_NODE_ID)));
5974 let first_ident = self.parse_ident();
5975 let mut path = vec!(first_ident);
5980 let path_lo = self.span.lo;
5981 path = vec!(self.parse_ident());
5982 while self.check(&token::ModSep) {
5984 let id = self.parse_ident();
5987 let span = mk_sp(path_lo, self.span.hi);
5988 self.obsolete(span, ObsoleteImportRenaming);
5989 let path = ast::Path {
5992 segments: path.into_iter().map(|identifier| {
5994 identifier: identifier,
5995 parameters: ast::PathParameters::none(),
5999 return P(spanned(lo, self.span.hi,
6000 ViewPathSimple(first_ident, path,
6001 ast::DUMMY_NODE_ID)));
6005 // foo::bar or foo::{a,b,c} or foo::*
6006 while self.check(&token::ModSep) {
6010 token::Ident(i, _) => {
6015 // foo::bar::{a,b,c}
6016 token::OpenDelim(token::Brace) => {
6017 let idents = self.parse_unspanned_seq(
6018 &token::OpenDelim(token::Brace),
6019 &token::CloseDelim(token::Brace),
6020 seq_sep_trailing_allowed(token::Comma),
6021 |p| p.parse_path_list_item()
6023 let path = ast::Path {
6024 span: mk_sp(lo, self.span.hi),
6026 segments: path.into_iter().map(|identifier| {
6028 identifier: identifier,
6029 parameters: ast::PathParameters::none(),
6033 return P(spanned(lo, self.span.hi,
6034 ViewPathList(path, idents, ast::DUMMY_NODE_ID)));
6038 token::BinOp(token::Star) => {
6040 let path = ast::Path {
6041 span: mk_sp(lo, self.span.hi),
6043 segments: path.into_iter().map(|identifier| {
6045 identifier: identifier,
6046 parameters: ast::PathParameters::none(),
6050 return P(spanned(lo, self.span.hi,
6051 ViewPathGlob(path, ast::DUMMY_NODE_ID)));
6060 let mut rename_to = path[path.len() - 1u];
6061 let path = ast::Path {
6062 span: mk_sp(lo, self.last_span.hi),
6064 segments: path.into_iter().map(|identifier| {
6066 identifier: identifier,
6067 parameters: ast::PathParameters::none(),
6071 if self.eat_keyword(keywords::As) {
6072 rename_to = self.parse_ident()
6076 ViewPathSimple(rename_to, path, ast::DUMMY_NODE_ID)))
6079 /// Parses a sequence of items. Stops when it finds program
6080 /// text that can't be parsed as an item
6081 /// - mod_items uses extern_mod_allowed = true
6082 /// - block_tail_ uses extern_mod_allowed = false
6083 fn parse_items_and_view_items(&mut self,
6084 first_item_attrs: Vec<Attribute> ,
6085 mut extern_mod_allowed: bool,
6086 macros_allowed: bool)
6087 -> ParsedItemsAndViewItems {
6088 let mut attrs = first_item_attrs;
6089 attrs.push_all(self.parse_outer_attributes()[]);
6090 // First, parse view items.
6091 let mut view_items : Vec<ast::ViewItem> = Vec::new();
6092 let mut items = Vec::new();
6094 // I think this code would probably read better as a single
6095 // loop with a mutable three-state-variable (for extern crates,
6096 // view items, and regular items) ... except that because
6097 // of macros, I'd like to delay that entire check until later.
6099 match self.parse_item_or_view_item(attrs, macros_allowed) {
6100 IoviNone(attrs) => {
6101 return ParsedItemsAndViewItems {
6102 attrs_remaining: attrs,
6103 view_items: view_items,
6105 foreign_items: Vec::new()
6108 IoviViewItem(view_item) => {
6109 match view_item.node {
6110 ViewItemUse(..) => {
6111 // `extern crate` must precede `use`.
6112 extern_mod_allowed = false;
6114 ViewItemExternCrate(..) if !extern_mod_allowed => {
6115 self.span_err(view_item.span,
6116 "\"extern crate\" declarations are \
6119 ViewItemExternCrate(..) => {}
6121 view_items.push(view_item);
6125 attrs = self.parse_outer_attributes();
6128 IoviForeignItem(_) => {
6132 attrs = self.parse_outer_attributes();
6135 // Next, parse items.
6137 match self.parse_item_or_view_item(attrs, macros_allowed) {
6138 IoviNone(returned_attrs) => {
6139 attrs = returned_attrs;
6142 IoviViewItem(view_item) => {
6143 attrs = self.parse_outer_attributes();
6144 self.span_err(view_item.span,
6145 "`use` and `extern crate` declarations must precede items");
6148 attrs = self.parse_outer_attributes();
6151 IoviForeignItem(_) => {
6157 ParsedItemsAndViewItems {
6158 attrs_remaining: attrs,
6159 view_items: view_items,
6161 foreign_items: Vec::new()
6165 /// Parses a sequence of foreign items. Stops when it finds program
6166 /// text that can't be parsed as an item
6167 fn parse_foreign_items(&mut self, first_item_attrs: Vec<Attribute> ,
6168 macros_allowed: bool)
6169 -> ParsedItemsAndViewItems {
6170 let mut attrs = first_item_attrs;
6171 attrs.push_all(self.parse_outer_attributes()[]);
6172 let mut foreign_items = Vec::new();
6174 match self.parse_foreign_item(attrs, macros_allowed) {
6175 IoviNone(returned_attrs) => {
6176 if self.check(&token::CloseDelim(token::Brace)) {
6177 attrs = returned_attrs;
6182 IoviViewItem(view_item) => {
6183 // I think this can't occur:
6184 self.span_err(view_item.span,
6185 "`use` and `extern crate` declarations must precede items");
6188 // FIXME #5668: this will occur for a macro invocation:
6189 self.span_fatal(item.span, "macros cannot expand to foreign items");
6191 IoviForeignItem(foreign_item) => {
6192 foreign_items.push(foreign_item);
6195 attrs = self.parse_outer_attributes();
6198 ParsedItemsAndViewItems {
6199 attrs_remaining: attrs,
6200 view_items: Vec::new(),
6202 foreign_items: foreign_items
6206 /// Parses a source module as a crate. This is the main
6207 /// entry point for the parser.
6208 pub fn parse_crate_mod(&mut self) -> Crate {
6209 let lo = self.span.lo;
6210 // parse the crate's inner attrs, maybe (oops) one
6211 // of the attrs of an item:
6212 let (inner, next) = self.parse_inner_attrs_and_next();
6213 let first_item_outer_attrs = next;
6214 // parse the items inside the crate:
6215 let m = self.parse_mod_items(token::Eof, first_item_outer_attrs, lo);
6220 config: self.cfg.clone(),
6221 span: mk_sp(lo, self.span.lo),
6222 exported_macros: Vec::new(),
6226 pub fn parse_optional_str(&mut self)
6227 -> Option<(InternedString, ast::StrStyle, Option<ast::Name>)> {
6228 let ret = match self.token {
6229 token::Literal(token::Str_(s), suf) => {
6230 (self.id_to_interned_str(s.ident()), ast::CookedStr, suf)
6232 token::Literal(token::StrRaw(s, n), suf) => {
6233 (self.id_to_interned_str(s.ident()), ast::RawStr(n), suf)
6241 pub fn parse_str(&mut self) -> (InternedString, StrStyle) {
6242 match self.parse_optional_str() {
6243 Some((s, style, suf)) => {
6244 let sp = self.last_span;
6245 self.expect_no_suffix(sp, "str literal", suf);
6248 _ => self.fatal("expected string literal")